source
stringlengths
3
92
c
stringlengths
26
2.25M
vpmg.c
/** * @file vpmg.c * @author Nathan Baker * @brief Class Vpmg methods * @ingroup Vpmg * @version $Id$ * @attention * @verbatim * * APBS -- Adaptive Poisson-Boltzmann Solver * * Nathan A. Baker (nathan.baker@pnnl.gov) * Pacific Northwest National Laboratory * * Additional contributing authors listed in the code documentation. * * Copyright (c) 2010-2020 Battelle Memorial Institute. Developed at the * Pacific Northwest National Laboratory, operated by Battelle Memorial * Institute, Pacific Northwest Division for the U.S. Department of Energy. * * Portions Copyright (c) 2002-2010, Washington University in St. Louis. * Portions Copyright (c) 2002-2020, Nathan A. Baker. * Portions Copyright (c) 1999-2002, The Regents of the University of * California. * Portions Copyright (c) 1995, Michael Holst. * 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 Washington University in St. Louis 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. * * Neither the name of the developer 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. * * @endverbatim */ #include "vpmg.h" VEMBED(rcsid="$Id$") #if !defined(VINLINE_VPMG) VPUBLIC unsigned long int Vpmg_memChk(Vpmg *thee) { if (thee == VNULL) return 0; return Vmem_bytes(thee->vmem); } #endif /* if !defined(VINLINE_VPMG) */ VPUBLIC void Vpmg_printColComp(Vpmg *thee, char path[72], char title[72], char mxtype[3], int flag) { int nn, nxm2, nym2, nzm2, ncol, nrow, nonz; double *nzval; int *colptr, *rowind; /* Calculate the total number of unknowns */ nxm2 = thee->pmgp->nx - 2; nym2 = thee->pmgp->ny - 2; nzm2 = thee->pmgp->nz - 2; nn = nxm2*nym2*nzm2; ncol = nn; nrow = nn; /* Calculate the number of non-zero matrix entries: * nn nonzeros on diagonal * nn-1 nonzeros on first off-diagonal * nn-nx nonzeros on second off-diagonal * nn-nx*ny nonzeros on third off-diagonal * * 7*nn-2*nx*ny-2*nx-2 TOTAL non-zeros */ nonz = 7*nn - 2*nxm2*nym2 - 2*nxm2 - 2; nzval = (double*)Vmem_malloc(thee->vmem, nonz, sizeof(double)); rowind = (int*)Vmem_malloc(thee->vmem, nonz, sizeof(int)); colptr = (int*)Vmem_malloc(thee->vmem, (ncol+1), sizeof(int)); #ifndef VAPBSQUIET Vnm_print(1, "Vpmg_printColComp: Allocated space for %d nonzeros\n", nonz); #endif bcolcomp(thee->iparm, thee->rparm, thee->iwork, thee->rwork, nzval, rowind, colptr, &flag); #if 0 for (i=0; i<nn; i++) { Vnm_print(1, "nnz(%d) = %g\n", i, nzval[i]); } #endif /* I do not understand why I need to pass nzval in this way, but it * works... */ pcolcomp(&nrow, &ncol, &nonz, &(nzval[0]), rowind, colptr, path, title, mxtype); Vmem_free(thee->vmem, (ncol+1), sizeof(int), (void **)&colptr); Vmem_free(thee->vmem, nonz, sizeof(int), (void **)&rowind); Vmem_free(thee->vmem, nonz, sizeof(double), (void **)&nzval); } VPUBLIC Vpmg* Vpmg_ctor(Vpmgp *pmgp, Vpbe *pbe, int focusFlag, Vpmg *pmgOLD, MGparm *mgparm, PBEparm_calcEnergy energyFlag) { Vpmg *thee = VNULL; thee = (Vpmg*)Vmem_malloc(VNULL, 1, sizeof(Vpmg) ); VASSERT(thee != VNULL); VASSERT( Vpmg_ctor2(thee, pmgp, pbe, focusFlag, pmgOLD, mgparm, energyFlag) ); return thee; } VPUBLIC int Vpmg_ctor2(Vpmg *thee, Vpmgp *pmgp, Vpbe *pbe, int focusFlag, Vpmg *pmgOLD, MGparm *mgparm, PBEparm_calcEnergy energyFlag) { int i, j, nion; double ionConc[MAXION], ionQ[MAXION], ionRadii[MAXION], zkappa2, zks2; double ionstr, partMin[3], partMax[3]; size_t size; /* Get the parameters */ VASSERT(pmgp != VNULL); VASSERT(pbe != VNULL); thee->pmgp = pmgp; thee->pbe = pbe; /* Set up the memory */ thee->vmem = Vmem_ctor("APBS:VPMG"); /// @note this is common to both replace/noreplace options /* Initialize ion concentrations and valencies in PMG routines */ zkappa2 = Vpbe_getZkappa2(thee->pbe); ionstr = Vpbe_getBulkIonicStrength(thee->pbe); if (ionstr > 0.0) zks2 = 0.5/ionstr; else zks2 = 0.0; Vpbe_getIons(thee->pbe, &nion, ionConc, ionRadii, ionQ); /* TEMPORARY USEAQUA */ /* Calculate storage requirements */ if(mgparm->useAqua == 0){ Vpmgp_size(thee->pmgp); }else{ VABORT_MSG0("Aqua is currently disabled"); } /* We need some additional storage if: nonlinear & newton OR cgmg */ /* SMPBE Added - nonlin = 2 added since it mimics NPBE */ if ( ( ((thee->pmgp->nonlin == NONLIN_NPBE) || (thee->pmgp->nonlin == NONLIN_SMPBE)) && (thee->pmgp->meth == VSOL_Newton) ) || (thee->pmgp->meth == VSOL_CGMG) ) { thee->pmgp->nrwk += (2*(thee->pmgp->nf)); } if (thee->pmgp->iinfo > 1) { Vnm_print(2, "Vpmg_ctor2: PMG chose nx = %d, ny = %d, nz = %d\n", thee->pmgp->nx, thee->pmgp->ny, thee->pmgp->nz); Vnm_print(2, "Vpmg_ctor2: PMG chose nlev = %d\n", thee->pmgp->nlev); Vnm_print(2, "Vpmg_ctor2: PMG chose nxc = %d, nyc = %d, nzc = %d\n", thee->pmgp->nxc, thee->pmgp->nyc, thee->pmgp->nzc); Vnm_print(2, "Vpmg_ctor2: PMG chose nf = %d, nc = %d\n", thee->pmgp->nf, thee->pmgp->nc); Vnm_print(2, "Vpmg_ctor2: PMG chose narr = %d, narrc = %d\n", thee->pmgp->narr, thee->pmgp->narrc); Vnm_print(2, "Vpmg_ctor2: PMG chose n_rpc = %d, n_iz = %d, n_ipc = %d\n", thee->pmgp->n_rpc, thee->pmgp->n_iz, thee->pmgp->n_ipc); Vnm_print(2, "Vpmg_ctor2: PMG chose nrwk = %d, niwk = %d\n", thee->pmgp->nrwk, thee->pmgp->niwk); } /* Allocate boundary storage */ thee->gxcf = (double *)Vmem_malloc( thee->vmem, 10*(thee->pmgp->ny)*(thee->pmgp->nz), sizeof(double) ); thee->gycf = (double *)Vmem_malloc( thee->vmem, 10*(thee->pmgp->nx)*(thee->pmgp->nz), sizeof(double) ); thee->gzcf = (double *)Vmem_malloc( thee->vmem, 10*(thee->pmgp->nx)*(thee->pmgp->ny), sizeof(double) ); /* Warn users if they are using BCFL_MAP that we do not include external energies */ if (thee->pmgp->bcfl == BCFL_MAP) Vnm_print(2,"Vpmg_ctor2: \nWarning: External energies are not used in BCFL_MAP calculations!\n"); if (focusFlag) { /* Overwrite any default or user-specified boundary condition * arguments; we are now committed to a calculation via focusing */ if (thee->pmgp->bcfl != BCFL_FOCUS) { Vnm_print(2, "Vpmg_ctor2: reset boundary condition flag to BCFL_FOCUS!\n"); thee->pmgp->bcfl = BCFL_FOCUS; } /* Fill boundaries */ Vnm_print(0, "Vpmg_ctor2: Filling boundary with old solution!\n"); focusFillBound(thee, pmgOLD); /* Calculate energetic contributions from region outside focusing * domain */ if (energyFlag != PCE_NO) { if (mgparm->type == MCT_PARALLEL) { for (j=0; j<3; j++) { partMin[j] = mgparm->partDisjCenter[j] - 0.5*mgparm->partDisjLength[j]; partMax[j] = mgparm->partDisjCenter[j] + 0.5*mgparm->partDisjLength[j]; } } else { for (j=0; j<3; j++) { partMin[j] = mgparm->center[j] - 0.5*mgparm->glen[j]; partMax[j] = mgparm->center[j] + 0.5*mgparm->glen[j]; } } extEnergy(thee, pmgOLD, energyFlag, partMin, partMax, mgparm->partDisjOwnSide); } } else { /* Ignore external energy contributions */ thee->extQmEnergy = 0; thee->extDiEnergy = 0; thee->extQfEnergy = 0; } /* Allocate partition vector storage */ size = (thee->pmgp->nx)*(thee->pmgp->ny)*(thee->pmgp->nz); thee->pvec = (double *)Vmem_malloc( thee->vmem, size, sizeof(double) ); /* Allocate remaining storage */ thee->iparm = ( int *)Vmem_malloc(thee->vmem, 100, sizeof( int)); thee->rparm = (double *)Vmem_malloc(thee->vmem, 100, sizeof(double)); thee->iwork = ( int *)Vmem_malloc(thee->vmem, thee->pmgp->niwk, sizeof( int)); thee->rwork = (double *)Vmem_malloc(thee->vmem, thee->pmgp->nrwk, sizeof(double)); thee->charge = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->kappa = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->pot = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->epsx = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->epsy = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->epsz = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->a1cf = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->a2cf = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->a3cf = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->ccf = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->fcf = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->tcf = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->u = (double *)Vmem_malloc(thee->vmem, thee->pmgp->narr, sizeof(double)); thee->xf = (double *)Vmem_malloc(thee->vmem, 5*(thee->pmgp->nx), sizeof(double)); thee->yf = (double *)Vmem_malloc(thee->vmem, 5*(thee->pmgp->ny), sizeof(double)); thee->zf = (double *)Vmem_malloc(thee->vmem, 5*(thee->pmgp->nz), sizeof(double)); /* Packs parameters into the iparm and rparm arrays */ Vpackmg(thee->iparm, thee->rparm, &(thee->pmgp->nrwk), &(thee->pmgp->niwk), &(thee->pmgp->nx), &(thee->pmgp->ny), &(thee->pmgp->nz), &(thee->pmgp->nlev), &(thee->pmgp->nu1), &(thee->pmgp->nu2), &(thee->pmgp->mgkey), &(thee->pmgp->itmax), &(thee->pmgp->istop), &(thee->pmgp->ipcon), &(thee->pmgp->nonlin), &(thee->pmgp->mgsmoo), &(thee->pmgp->mgprol), &(thee->pmgp->mgcoar), &(thee->pmgp->mgsolv), &(thee->pmgp->mgdisc), &(thee->pmgp->iinfo), &(thee->pmgp->errtol), &(thee->pmgp->ipkey), &(thee->pmgp->omegal), &(thee->pmgp->omegan), &(thee->pmgp->irite), &(thee->pmgp->iperf)); /* Currently for SMPBE type calculations we do not want to apply a scale factor to the ionConc */ /** @note The fortran replacement functions are run along side the old * fortran functions. This is due to the use of common variables * in the fortran sub-routines. Once the fortran code has been * successfully excised, these functions will no longer need to be * called in tandem, and the fortran version may be dropped */ switch(pmgp->ipkey){ case IPKEY_SMPBE: Vmypdefinitsmpbe(&nion, ionQ, ionConc, &pbe->smvolume, &pbe->smsize); break; case IPKEY_NPBE: /* Else adjust the inoConc by scaling factor zks2 */ for (i=0; i<nion; i++) ionConc[i] = zks2 * ionConc[i]; Vmypdefinitnpbe(&nion, ionQ, ionConc); break; case IPKEY_LPBE: /* Else adjust the inoConc by scaling factor zks2 */ for (i=0; i<nion; i++) ionConc[i] = zks2 * ionConc[i]; Vmypdefinitlpbe(&nion, ionQ, ionConc); break; default: Vnm_print(2, "PMG: Warning: PBE structure not initialized!\n"); /* Else adjust the inoConc by scaling factor zks2 */ for (i=0; i<nion; i++) ionConc[i] = zks2 * ionConc[i]; break; } /* Set the default chargeSrc for 5th order splines */ thee->chargeSrc = mgparm->chgs; /* Turn off restriction of observable calculations to a specific * partition */ Vpmg_unsetPart(thee); /* The coefficient arrays have not been filled */ thee->filled = 0; /* * TODO: Move the dtor out of here. The current ctor is done in routines.c, * This was originally moved out to kill a memory leak. The dtor has * has been removed from initMG and placed back here to keep memory * usage low. killMG has been modified accordingly. */ Vpmg_dtor(&pmgOLD); return 1; } VPUBLIC int Vpmg_solve(Vpmg *thee) { int i, nx, ny, nz, n; double zkappa2; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; n = nx*ny*nz; if (!(thee->filled)) { Vnm_print(2, "Vpmg_solve: Need to call Vpmg_fillco()!\n"); return 0; } /* Fill the "true solution" array */ for (i=0; i<n; i++) { thee->tcf[i] = 0.0; } /* Fill the RHS array */ for (i=0; i<n; i++) { thee->fcf[i] = thee->charge[i]; } /* Fill the operator coefficient array. */ for (i=0; i<n; i++) { thee->a1cf[i] = thee->epsx[i]; thee->a2cf[i] = thee->epsy[i]; thee->a3cf[i] = thee->epsz[i]; } /* Fill the nonlinear coefficient array by multiplying the kappa * accessibility array (containing values between 0 and 1) by zkappa2. */ zkappa2 = Vpbe_getZkappa2(thee->pbe); if (zkappa2 > VPMGSMALL) { for (i=0; i<n; i++) { thee->ccf[i] = zkappa2*thee->kappa[i]; } } else { for (i=0; i<n; i++) { thee->ccf[i] = 0.0; } } switch(thee->pmgp->meth) { /* CGMG (linear) */ case VSOL_CGMG: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with CGMGDRIV\n"); VABORT_MSG0("CGMGDRIV is not currently supported"); break; /* Newton (nonlinear) */ case VSOL_Newton: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NEWDRIV\n"); Vnewdriv (thee->iparm, thee->rparm, thee->iwork, thee->rwork, thee->u, thee->xf, thee->yf, thee->zf, thee->gxcf, thee->gycf, thee->gzcf, thee->a1cf, thee->a2cf, thee->a3cf, thee->ccf, thee->fcf, thee->tcf); break; /* MG (linear/nonlinear) */ case VSOL_MG: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with MGDRIV\n"); Vmgdriv(thee->iparm, thee->rparm, thee->iwork, thee->rwork, thee->u, thee->xf, thee->yf, thee->zf, thee->gxcf, thee->gycf, thee->gzcf, thee->a1cf, thee->a2cf, thee->a3cf, thee->ccf, thee->fcf, thee->tcf); break; /* CGHS (linear/nonlinear) */ case VSOL_CG: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NCGHSDRIV\n"); VABORT_MSG0("NCGHSDRIV is not currently supported"); break; /* SOR (linear/nonlinear) */ case VSOL_SOR: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NSORDRIV\n"); VABORT_MSG0("NSORDRIV is not currently supported"); break; /* GSRB (linear/nonlinear) */ case VSOL_RBGS: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NGSRBDRIV\n"); VABORT_MSG0("NGSRBDRIV is not currently supported"); break; /* WJAC (linear/nonlinear) */ case VSOL_WJ: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NWJACDRIV\n"); VABORT_MSG0("NWJACDRIV is not currently supported"); break; /* RICH (linear/nonlinear) */ case VSOL_Richardson: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NRICHDRIV\n"); VABORT_MSG0("NRICHDRIV is not currently supported"); break; /* CGMG (linear) TEMPORARY USEAQUA */ case VSOL_CGMGAqua: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with CGMGDRIVAQUA\n"); VABORT_MSG0("CGMGDRIVAQUA is not currently supported"); break; /* Newton (nonlinear) TEMPORARY USEAQUA */ case VSOL_NewtonAqua: if (thee->pmgp->iinfo > 1) Vnm_print(2, "Driving with NEWDRIVAQUA\n"); VABORT_MSG0("NEWDRIVAQUA is not currently supported"); break; /* Error handling */ default: Vnm_print(2, "Vpmg_solve: invalid solver method key (%d)\n", thee->pmgp->key); return 0; break; } return 1; } VPUBLIC void Vpmg_dtor(Vpmg **thee) { if ((*thee) != VNULL) { Vpmg_dtor2(*thee); Vmem_free(VNULL, 1, sizeof(Vpmg), (void **)thee); (*thee) = VNULL; } } VPUBLIC void Vpmg_dtor2(Vpmg *thee) { /* Clean up the storage */ Vmem_free(thee->vmem, 100, sizeof(int), (void **)&(thee->iparm)); Vmem_free(thee->vmem, 100, sizeof(double), (void **)&(thee->rparm)); Vmem_free(thee->vmem, thee->pmgp->niwk, sizeof(int), (void **)&(thee->iwork)); Vmem_free(thee->vmem, thee->pmgp->nrwk, sizeof(double), (void **)&(thee->rwork)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->charge)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->kappa)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->pot)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->epsx)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->epsy)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->epsz)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->a1cf)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->a2cf)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->a3cf)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->ccf)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->fcf)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->tcf)); Vmem_free(thee->vmem, thee->pmgp->narr, sizeof(double), (void **)&(thee->u)); Vmem_free(thee->vmem, 5*(thee->pmgp->nx), sizeof(double), (void **)&(thee->xf)); Vmem_free(thee->vmem, 5*(thee->pmgp->ny), sizeof(double), (void **)&(thee->yf)); Vmem_free(thee->vmem, 5*(thee->pmgp->nz), sizeof(double), (void **)&(thee->zf)); Vmem_free(thee->vmem, 10*(thee->pmgp->ny)*(thee->pmgp->nz), sizeof(double), (void **)&(thee->gxcf)); Vmem_free(thee->vmem, 10*(thee->pmgp->nx)*(thee->pmgp->nz), sizeof(double), (void **)&(thee->gycf)); Vmem_free(thee->vmem, 10*(thee->pmgp->nx)*(thee->pmgp->ny), sizeof(double), (void **)&(thee->gzcf)); Vmem_free(thee->vmem, (thee->pmgp->nx)*(thee->pmgp->ny)*(thee->pmgp->nz), sizeof(double), (void **)&(thee->pvec)); Vmem_dtor(&(thee->vmem)); } VPUBLIC void Vpmg_setPart(Vpmg *thee, double lowerCorner[3], double upperCorner[3], int bflags[6]) { Valist *alist; Vatom *atom; int i, j, k, nx, ny, nz; double xmin, ymin, zmin, x, y, z, hx, hy, hzed, xok, yok, zok; double x0,x1,y0,y1,z0,z1; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmin = thee->pmgp->xcent - 0.5*hx*(nx-1); ymin = thee->pmgp->ycent - 0.5*hy*(ny-1); zmin = thee->pmgp->zcent - 0.5*hzed*(nz-1); xok = 0; yok = 0; zok = 0; /* We need have called Vpmg_fillco first */ alist = thee->pbe->alist; Vnm_print(0, "Vpmg_setPart: lower corner = (%g, %g, %g)\n", lowerCorner[0], lowerCorner[1], lowerCorner[2]); Vnm_print(0, "Vpmg_setPart: upper corner = (%g, %g, %g)\n", upperCorner[0], upperCorner[1], upperCorner[2]); Vnm_print(0, "Vpmg_setPart: actual minima = (%g, %g, %g)\n", xmin, ymin, zmin); Vnm_print(0, "Vpmg_setPart: actual maxima = (%g, %g, %g)\n", xmin+hx*(nx-1), ymin+hy*(ny-1), zmin+hzed*(nz-1)); Vnm_print(0, "Vpmg_setPart: bflag[FRONT] = %d\n", bflags[VAPBS_FRONT]); Vnm_print(0, "Vpmg_setPart: bflag[BACK] = %d\n", bflags[VAPBS_BACK]); Vnm_print(0, "Vpmg_setPart: bflag[LEFT] = %d\n", bflags[VAPBS_LEFT]); Vnm_print(0, "Vpmg_setPart: bflag[RIGHT] = %d\n", bflags[VAPBS_RIGHT]); Vnm_print(0, "Vpmg_setPart: bflag[UP] = %d\n", bflags[VAPBS_UP]); Vnm_print(0, "Vpmg_setPart: bflag[DOWN] = %d\n", bflags[VAPBS_DOWN]); /* Identify atoms as inside, outside, or on the border If on the border, use the bflags to determine if there is an adjacent processor - if so, this atom should be equally shared. */ for (i=0; i<Valist_getNumberAtoms(alist); i++) { atom = Valist_getAtom(alist, i); if ((atom->position[0] < upperCorner[0]) && (atom->position[0] > lowerCorner[0])) xok = 1; else { if ((VABS(atom->position[0] - lowerCorner[0]) < VPMGSMALL) && (bflags[VAPBS_LEFT] == 0)) xok = 1; else if ((VABS(atom->position[0] - lowerCorner[0]) < VPMGSMALL) && (bflags[VAPBS_LEFT] == 1)) xok = 0.5; else if ((VABS(atom->position[0] - upperCorner[0]) < VPMGSMALL) && (bflags[VAPBS_RIGHT] == 0)) xok = 1; else if ((VABS(atom->position[0] - upperCorner[0]) < VPMGSMALL) && (bflags[VAPBS_RIGHT] == 1)) xok = 0.5; else xok = 0; } if ((atom->position[1] < upperCorner[1]) && (atom->position[1] > lowerCorner[1])) yok = 1; else { if ((VABS(atom->position[1] - lowerCorner[1]) < VPMGSMALL) && (bflags[VAPBS_BACK] == 0)) yok = 1; else if ((VABS(atom->position[1] - lowerCorner[1]) < VPMGSMALL) && (bflags[VAPBS_BACK] == 1)) yok = 0.5; else if ((VABS(atom->position[1] - upperCorner[1]) < VPMGSMALL) && (bflags[VAPBS_FRONT] == 0)) yok = 1; else if ((VABS(atom->position[1] - upperCorner[1]) < VPMGSMALL) && (bflags[VAPBS_FRONT] == 1)) yok = 0.5; else yok = 0; } if ((atom->position[2] < upperCorner[2]) && (atom->position[2] > lowerCorner[2])) zok = 1; else { if ((VABS(atom->position[2] - lowerCorner[2]) < VPMGSMALL) && (bflags[VAPBS_DOWN] == 0)) zok = 1; else if ((VABS(atom->position[2] - lowerCorner[2]) < VPMGSMALL) && (bflags[VAPBS_DOWN] == 1)) zok = 0.5; else if ((VABS(atom->position[2] - upperCorner[2]) < VPMGSMALL) && (bflags[VAPBS_UP] == 0)) zok = 1; else if ((VABS(atom->position[2] - upperCorner[2]) < VPMGSMALL) && (bflags[VAPBS_UP] == 1)) zok = 0.5; else zok = 0; } atom->partID = xok*yok*zok; /* Vnm_print(1, "DEBUG (%s, %d): atom->position[0] - upperCorner[0] = %g\n", __FILE__, __LINE__, atom->position[0] - upperCorner[0]); Vnm_print(1, "DEBUG (%s, %d): atom->position[0] - lowerCorner[0] = %g\n", __FILE__, __LINE__, atom->position[0] - lowerCorner[0]); Vnm_print(1, "DEBUG (%s, %d): atom->position[1] - upperCorner[1] = %g\n", __FILE__, __LINE__, atom->position[1] - upperCorner[1]); Vnm_print(1, "DEBUG (%s, %d): atom->position[1] - lowerCorner[1] = %g\n", __FILE__, __LINE__, atom->position[1] - lowerCorner[1]); Vnm_print(1, "DEBUG (%s, %d): atom->position[2] - upperCorner[2] = %g\n", __FILE__, __LINE__, atom->position[2] - upperCorner[2]); Vnm_print(1, "DEBUG (%s, %d): atom->position[2] - lowerCorner[0] = %g\n", __FILE__, __LINE__, atom->position[2] - lowerCorner[2]); Vnm_print(1, "DEBUG (%s, %d): xok = %g, yok = %g, zok = %g\n", __FILE__, __LINE__, xok, yok, zok); */ } /* Load up pvec - For all points within h{axis}/2 of a border - use a gradient to determine the pvec weight. Points on the boundary depend on the presence of an adjacent processor. */ for (i=0; i<(nx*ny*nz); i++) thee->pvec[i] = 0.0; for (i=0; i<nx; i++) { xok = 0.0; x = i*hx + xmin; if ( (x < (upperCorner[0]-hx/2)) && (x > (lowerCorner[0]+hx/2)) ) xok = 1.0; else if ( (VABS(x - lowerCorner[0]) < VPMGSMALL) && (bflags[VAPBS_LEFT] == 0)) xok = 1.0; else if ((VABS(x - lowerCorner[0]) < VPMGSMALL) && (bflags[VAPBS_LEFT] == 1)) xok = 0.5; else if ((VABS(x - upperCorner[0]) < VPMGSMALL) && (bflags[VAPBS_RIGHT] == 0)) xok = 1.0; else if ((VABS(x - upperCorner[0]) < VPMGSMALL) && (bflags[VAPBS_RIGHT] == 1)) xok = 0.5; else if ((x > (upperCorner[0] + hx/2)) || (x < (lowerCorner[0] - hx/2))) xok = 0.0; else if ((x < (upperCorner[0] + hx/2)) || (x > (lowerCorner[0] - hx/2))) { x0 = VMAX2(x - hx/2, lowerCorner[0]); x1 = VMIN2(x + hx/2, upperCorner[0]); xok = VABS(x1-x0)/hx; if (xok < 0.0) { if (VABS(xok) < VPMGSMALL) xok = 0.0; else { Vnm_print(2, "Vpmg_setPart: fell off x-interval (%1.12E)!\n", xok); VASSERT(0); } } if (xok > 1.0) { if (VABS(xok - 1.0) < VPMGSMALL) xok = 1.0; else { Vnm_print(2, "Vpmg_setPart: fell off x-interval (%1.12E)!\n", xok); VASSERT(0); } } } else xok = 0.0; for (j=0; j<ny; j++) { yok = 0.0; y = j*hy + ymin; if ((y < (upperCorner[1]-hy/2)) && (y > (lowerCorner[1]+hy/2))) yok = 1.0; else if ((VABS(y - lowerCorner[1]) < VPMGSMALL) && (bflags[VAPBS_BACK] == 0)) yok = 1.0; else if ((VABS(y - lowerCorner[1]) < VPMGSMALL) && (bflags[VAPBS_BACK] == 1)) yok = 0.5; else if ((VABS(y - upperCorner[1]) < VPMGSMALL) && (bflags[VAPBS_FRONT] == 0)) yok = 1.0; else if ((VABS(y - upperCorner[1]) < VPMGSMALL) && (bflags[VAPBS_FRONT] == 1)) yok = 0.5; else if ((y > (upperCorner[1] + hy/2)) || (y < (lowerCorner[1] - hy/2))) yok=0.0; else if ((y < (upperCorner[1] + hy/2)) || (y > (lowerCorner[1] - hy/2))){ y0 = VMAX2(y - hy/2, lowerCorner[1]); y1 = VMIN2(y + hy/2, upperCorner[1]); yok = VABS(y1-y0)/hy; if (yok < 0.0) { if (VABS(yok) < VPMGSMALL) yok = 0.0; else { Vnm_print(2, "Vpmg_setPart: fell off y-interval (%1.12E)!\n", yok); VASSERT(0); } } if (yok > 1.0) { if (VABS(yok - 1.0) < VPMGSMALL) yok = 1.0; else { Vnm_print(2, "Vpmg_setPart: fell off y-interval (%1.12E)!\n", yok); VASSERT(0); } } } else yok=0.0; for (k=0; k<nz; k++) { zok = 0.0; z = k*hzed + zmin; if ((z < (upperCorner[2]-hzed/2)) && (z > (lowerCorner[2]+hzed/2))) zok = 1.0; else if ((VABS(z - lowerCorner[2]) < VPMGSMALL) && (bflags[VAPBS_DOWN] == 0)) zok = 1.0; else if ((VABS(z - lowerCorner[2]) < VPMGSMALL) && (bflags[VAPBS_DOWN] == 1)) zok = 0.5; else if ((VABS(z - upperCorner[2]) < VPMGSMALL) && (bflags[VAPBS_UP] == 0)) zok = 1.0; else if ((VABS(z - upperCorner[2]) < VPMGSMALL) && (bflags[VAPBS_UP] == 1)) zok = 0.5; else if ((z > (upperCorner[2] + hzed/2)) || (z < (lowerCorner[2] - hzed/2))) zok=0.0; else if ((z < (upperCorner[2] + hzed/2)) || (z > (lowerCorner[2] - hzed/2))){ z0 = VMAX2(z - hzed/2, lowerCorner[2]); z1 = VMIN2(z + hzed/2, upperCorner[2]); zok = VABS(z1-z0)/hzed; if (zok < 0.0) { if (VABS(zok) < VPMGSMALL) zok = 0.0; else { Vnm_print(2, "Vpmg_setPart: fell off z-interval (%1.12E)!\n", zok); VASSERT(0); } } if (zok > 1.0) { if (VABS(zok - 1.0) < VPMGSMALL) zok = 1.0; else { Vnm_print(2, "Vpmg_setPart: fell off z-interval (%1.12E)!\n", zok); VASSERT(0); } } } else zok = 0.0; if (VABS(xok*yok*zok) < VPMGSMALL) thee->pvec[IJK(i,j,k)] = 0.0; else thee->pvec[IJK(i,j,k)] = xok*yok*zok; } } } } VPUBLIC void Vpmg_unsetPart(Vpmg *thee) { int i, nx, ny, nz; Vatom *atom; Valist *alist; VASSERT(thee != VNULL); nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; alist = thee->pbe->alist; for (i=0; i<(nx*ny*nz); i++) thee->pvec[i] = 1; for (i=0; i<Valist_getNumberAtoms(alist); i++) { atom = Valist_getAtom(alist, i); atom->partID = 1; } } VPUBLIC int Vpmg_fillArray(Vpmg *thee, double *vec, Vdata_Type type, double parm, Vhal_PBEType pbetype, PBEparm *pbeparm) { Vacc *acc = VNULL; Vpbe *pbe = VNULL; Vgrid *grid = VNULL; Vatom *atoms = VNULL; Valist *alist = VNULL; double position[3], hx, hy, hzed, xmin, ymin, zmin; double grad[3], eps, epsp, epss, zmagic, u; int i, j, k, l, nx, ny, nz, ichop; pbe = thee->pbe; acc = Vpbe_getVacc(pbe); nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; epsp = Vpbe_getSoluteDiel(pbe); epss = Vpbe_getSolventDiel(pbe); zmagic = Vpbe_getZmagic(pbe); if (!(thee->filled)) { Vnm_print(2, "Vpmg_fillArray: need to call Vpmg_fillco first!\n"); return 0; } switch (type) { case VDT_CHARGE: for (i=0; i<nx*ny*nz; i++) vec[i] = thee->charge[i]/zmagic; break; case VDT_DIELX: for (i=0; i<nx*ny*nz; i++) vec[i] = thee->epsx[i]; break; case VDT_DIELY: for (i=0; i<nx*ny*nz; i++) vec[i] = thee->epsy[i]; break; case VDT_DIELZ: for (i=0; i<nx*ny*nz; i++) vec[i] = thee->epsz[i]; break; case VDT_KAPPA: for (i=0; i<nx*ny*nz; i++) vec[i] = thee->kappa[i]; break; case VDT_POT: for (i=0; i<nx*ny*nz; i++) vec[i] = thee->u[i]; break; case VDT_ATOMPOT: alist = thee->pbe->alist; atoms = alist[pbeparm->molid-1].atoms; grid = Vgrid_ctor(nx, ny, nz, hx, hy, hzed, xmin, ymin, zmin,thee->u); for (i=0; i<alist[pbeparm->molid-1].number;i++) { position[0] = atoms[i].position[0]; position[1] = atoms[i].position[1]; position[2] = atoms[i].position[2]; Vgrid_value(grid, position, &vec[i]); } Vgrid_dtor(&grid); break; case VDT_SMOL: for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; vec[IJK(i,j,k)] = (Vacc_molAcc(acc,position,parm)); } } } break; case VDT_SSPL: for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; vec[IJK(i,j,k)] = Vacc_splineAcc(acc,position,parm,0); } } } break; case VDT_VDW: for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; vec[IJK(i,j,k)] = Vacc_vdwAcc(acc,position); } } } break; case VDT_IVDW: for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; vec[IJK(i,j,k)] = Vacc_ivdwAcc(acc,position,parm); } } } break; case VDT_LAP: grid = Vgrid_ctor(nx, ny, nz, hx, hy, hzed, xmin, ymin, zmin, thee->u); for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { if ((k==0) || (k==(nz-1)) || (j==0) || (j==(ny-1)) || (i==0) || (i==(nx-1))) { vec[IJK(i,j,k)] = 0; } else { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; VASSERT(Vgrid_curvature(grid,position, 1, &(vec[IJK(i,j,k)]))); } } } } Vgrid_dtor(&grid); break; case VDT_EDENS: grid = Vgrid_ctor(nx, ny, nz, hx, hy, hzed, xmin, ymin, zmin, thee->u); for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; VASSERT(Vgrid_gradient(grid, position, grad)); eps = epsp + (epss-epsp)*Vacc_molAcc(acc, position, pbe->solventRadius); vec[IJK(i,j,k)] = 0.0; for (l=0; l<3; l++) vec[IJK(i,j,k)] += eps*VSQR(grad[l]); } } } Vgrid_dtor(&grid); break; case VDT_NDENS: for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; vec[IJK(i,j,k)] = 0.0; u = thee->u[IJK(i,j,k)]; if ( VABS(Vacc_ivdwAcc(acc, position, pbe->maxIonRadius) - 1.0) < VSMALL) { for (l=0; l<pbe->numIon; l++) { double q = pbe->ionQ[l]; if (pbetype == PBE_NPBE || pbetype == PBE_SMPBE /* SMPBE Added */) { vec[IJK(i,j,k)] += pbe->ionConc[l]*Vcap_exp(-q*u, &ichop); } else if (pbetype == PBE_LPBE){ vec[IJK(i,j,k)] += pbe->ionConc[l]*(1 - q*u + 0.5*q*q*u*u); } } } } } } break; case VDT_QDENS: for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = i*hx + xmin; position[1] = j*hy + ymin; position[2] = k*hzed + zmin; vec[IJK(i,j,k)] = 0.0; u = thee->u[IJK(i,j,k)]; if ( VABS(Vacc_ivdwAcc(acc, position, pbe->maxIonRadius) - 1.0) < VSMALL) { for (l=0; l<pbe->numIon; l++) { double q = pbe->ionQ[l]; if (pbetype == PBE_NPBE || pbetype == PBE_SMPBE /* SMPBE Added */) { vec[IJK(i,j,k)] += pbe->ionConc[l]*q*Vcap_exp(-q*u, &ichop); } else if (pbetype == PBE_LPBE) { vec[IJK(i,j,k)] += pbe->ionConc[l]*q*(1 - q*u + 0.5*q*q*u*u); } } } }}} break; default: Vnm_print(2, "main: Bogus data type (%d)!\n", type); return 0; break; } return 1; } VPRIVATE double Vpmg_polarizEnergy(Vpmg *thee, int extFlag ) { int i, j, k, ijk, nx, ny, nz, iatom; double xmin, ymin, zmin, //x, // gcc: not used //y, //z, hx, hy, hzed, epsp, lap, pt[3], T, pre, polq, dist2, dist, energy, q, *charge, *pos, eps_w; Vgrid *potgrid; Vpbe *pbe; Valist *alist; Vatom *atom; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->ymin; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; pbe = thee->pbe; epsp = Vpbe_getSoluteDiel(pbe); eps_w = Vpbe_getSolventDiel(pbe); alist = pbe->alist; charge = thee->charge; /* Calculate the prefactor for Coulombic calculations */ T = Vpbe_getTemperature(pbe); pre = (Vunit_ec*Vunit_ec)/(4*VPI*Vunit_eps0*eps_w*Vunit_kb*T); pre = pre*(1.0e10); /* Set up Vgrid object with solution */ potgrid = Vgrid_ctor(nx, ny, nz, hx, hy, hzed, xmin, ymin, zmin, thee->u); /* Calculate polarization charge */ energy = 0.0; for (i=1; i<(nx-1); i++) { pt[0] = xmin + hx*i; for (j=1; j<(ny-1); j++) { pt[1] = ymin + hy*j; for (k=1; k<(nz-1); k++) { pt[2] = zmin + hzed*k; /* Calculate polarization charge */ VASSERT(Vgrid_curvature(potgrid, pt, 1, &lap)); ijk = IJK(i,j,k); polq = charge[ijk] + epsp*lap*3.0; /* Calculate interaction energy with atoms */ if (VABS(polq) > VSMALL) { for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); q = Vatom_getCharge(atom); pos = Vatom_getPosition(atom); dist2 = VSQR(pos[0]-pt[0]) + VSQR(pos[1]-pt[1]) \ + VSQR(pos[2]-pt[2]); dist = VSQRT(dist2); if (dist < VSMALL) { Vnm_print(2, "Vpmg_polarizEnergy: atom on grid point; ignoring!\n"); } else { energy = energy + polq*q/dist; } } } } } } return pre*energy; } VPUBLIC double Vpmg_energy(Vpmg *thee, int extFlag ) { double totEnergy = 0.0, dielEnergy = 0.0, qmEnergy = 0.0, qfEnergy = 0.0; VASSERT(thee != VNULL); if ((thee->pmgp->nonlin) && (Vpbe_getBulkIonicStrength(thee->pbe) > 0.)) { Vnm_print(0, "Vpmg_energy: calculating full PBE energy\n"); qmEnergy = Vpmg_qmEnergy(thee, extFlag); Vnm_print(0, "Vpmg_energy: qmEnergy = %1.12E kT\n", qmEnergy); qfEnergy = Vpmg_qfEnergy(thee, extFlag); Vnm_print(0, "Vpmg_energy: qfEnergy = %1.12E kT\n", qfEnergy); dielEnergy = Vpmg_dielEnergy(thee, extFlag); Vnm_print(0, "Vpmg_energy: dielEnergy = %1.12E kT\n", dielEnergy); totEnergy = qfEnergy - dielEnergy - qmEnergy; } else { Vnm_print(0, "Vpmg_energy: calculating only q-phi energy\n"); qfEnergy = Vpmg_qfEnergy(thee, extFlag); Vnm_print(0, "Vpmg_energy: qfEnergy = %1.12E kT\n", qfEnergy); totEnergy = 0.5*qfEnergy; } return totEnergy; } VPUBLIC double Vpmg_dielEnergy(Vpmg *thee, int extFlag ) { double hx, hy, hzed, energy, nrgx, nrgy, nrgz, pvecx, pvecy, pvecz; int i, j, k, nx, ny, nz; VASSERT(thee != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; energy = 0.0; if (!thee->filled) { Vnm_print(2, "Vpmg_dielEnergy: Need to call Vpmg_fillco!\n"); VASSERT(0); } for (k=0; k<(nz-1); k++) { for (j=0; j<(ny-1); j++) { for (i=0; i<(nx-1); i++) { pvecx = 0.5*(thee->pvec[IJK(i,j,k)]+thee->pvec[IJK(i+1,j,k)]); pvecy = 0.5*(thee->pvec[IJK(i,j,k)]+thee->pvec[IJK(i,j+1,k)]); pvecz = 0.5*(thee->pvec[IJK(i,j,k)]+thee->pvec[IJK(i,j,k+1)]); nrgx = thee->epsx[IJK(i,j,k)]*pvecx * VSQR((thee->u[IJK(i,j,k)]-thee->u[IJK(i+1,j,k)])/hx); nrgy = thee->epsy[IJK(i,j,k)]*pvecy * VSQR((thee->u[IJK(i,j,k)]-thee->u[IJK(i,j+1,k)])/hy); nrgz = thee->epsz[IJK(i,j,k)]*pvecz * VSQR((thee->u[IJK(i,j,k)]-thee->u[IJK(i,j,k+1)])/hzed); energy += (nrgx + nrgy + nrgz); } } } energy = 0.5*energy*hx*hy*hzed; energy = energy/Vpbe_getZmagic(thee->pbe); if (extFlag == 1) energy += (thee->extDiEnergy); return energy; } VPUBLIC double Vpmg_dielGradNorm(Vpmg *thee) { double hx, hy, hzed, energy, nrgx, nrgy, nrgz, pvecx, pvecy, pvecz; int i, j, k, nx, ny, nz; VASSERT(thee != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; energy = 0.0; if (!thee->filled) { Vnm_print(2, "Vpmg_dielGradNorm: Need to call Vpmg_fillco!\n"); VASSERT(0); } for (k=1; k<nz; k++) { for (j=1; j<ny; j++) { for (i=1; i<nx; i++) { pvecx = 0.5*(thee->pvec[IJK(i,j,k)]+thee->pvec[IJK(i-1,j,k)]); pvecy = 0.5*(thee->pvec[IJK(i,j,k)]+thee->pvec[IJK(i,j-1,k)]); pvecz = 0.5*(thee->pvec[IJK(i,j,k)]+thee->pvec[IJK(i,j,k-1)]); nrgx = pvecx * VSQR((thee->epsx[IJK(i,j,k)]-thee->epsx[IJK(i-1,j,k)])/hx); nrgy = pvecy * VSQR((thee->epsy[IJK(i,j,k)]-thee->epsy[IJK(i,j-1,k)])/hy); nrgz = pvecz * VSQR((thee->epsz[IJK(i,j,k)]-thee->epsz[IJK(i,j,k-1)])/hzed); energy += VSQRT(nrgx + nrgy + nrgz); } } } energy = energy*hx*hy*hzed; return energy; } VPUBLIC double Vpmg_qmEnergy(Vpmg *thee, int extFlag ) { double energy; if(thee->pbe->ipkey == IPKEY_SMPBE){ energy = Vpmg_qmEnergySMPBE(thee,extFlag); }else{ energy = Vpmg_qmEnergyNONLIN(thee,extFlag); } return energy; } VPRIVATE double Vpmg_qmEnergyNONLIN(Vpmg *thee, int extFlag ) { double hx, hy, hzed, energy, ionConc[MAXION], ionRadii[MAXION], ionQ[MAXION], zkappa2, ionstr, zks2; int i, /* Loop variable */ j, nx, ny, nz, nion, ichop, nchop, len; /* Stores number of iterations for loops to avoid multiple recalculations */ VASSERT(thee != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; zkappa2 = Vpbe_getZkappa2(thee->pbe); ionstr = Vpbe_getBulkIonicStrength(thee->pbe); /* Bail if we're at zero ionic strength */ if (zkappa2 < VSMALL) { #ifndef VAPBSQUIET Vnm_print(0, "Vpmg_qmEnergy: Zero energy for zero ionic strength!\n"); #endif return 0.0; } zks2 = 0.5*zkappa2/ionstr; if (!thee->filled) { Vnm_print(2, "Vpmg_qmEnergy: Need to call Vpmg_fillco()!\n"); VASSERT(0); } energy = 0.0; nchop = 0; Vpbe_getIons(thee->pbe, &nion, ionConc, ionRadii, ionQ); if (thee->pmgp->nonlin) { Vnm_print(0, "Vpmg_qmEnergy: Calculating nonlinear energy\n"); for (i=0, len=nx*ny*nz; i<len; i++) { if (thee->pvec[i]*thee->kappa[i] > VSMALL) { for (j=0; j<nion; j++) { energy += (thee->pvec[i]*thee->kappa[i]*zks2 * ionConc[j] * (Vcap_exp(-ionQ[j]*thee->u[i], &ichop)-1.0)); nchop += ichop; } } } if (nchop > 0){ Vnm_print(2, "Vpmg_qmEnergy: Chopped EXP %d times!\n",nchop); Vnm_print(2, "\nERROR! Detected large potential values in energy evaluation! \nERROR! This calculation failed -- please report to the APBS developers!\n\n"); VASSERT(0); } } else { /* Zkappa2 OK here b/c LPBE approx */ Vnm_print(0, "Vpmg_qmEnergy: Calculating linear energy\n"); for (i=0, len=nx*ny*nz; i<len; i++) { if (thee->pvec[i]*thee->kappa[i] > VSMALL) energy += (thee->pvec[i]*zkappa2*thee->kappa[i]*VSQR(thee->u[i])); } energy = 0.5*energy; } energy = energy*hx*hy*hzed; energy = energy/Vpbe_getZmagic(thee->pbe); if (extFlag == 1) energy += thee->extQmEnergy; return energy; } VPUBLIC double Vpmg_qmEnergySMPBE(Vpmg *thee, int extFlag ) { double hx, hy, hzed, energy, ionConc[MAXION], ionRadii[MAXION], ionQ[MAXION], zkappa2, ionstr, zks2; int i, //j, // gcc: not used nx, ny, nz, nion, //ichop, // gcc: not used nchop, len; /* Loop variable */ /* SMPB Modification (vchu, 09/21/06)*/ /* variable declarations for SMPB energy terms */ double a, k, z1, z2, z3, cb1, cb2, cb3, a1, a2, a3, c1, c2, c3, currEnergy, fracOccA, fracOccB, fracOccC, phi, gpark, denom; // Na; /**< @todo remove if no conflicts are caused - This constant is already defined in vpde.h. no need to redefine. */ int ichop1, ichop2, ichop3; VASSERT(thee != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; zkappa2 = Vpbe_getZkappa2(thee->pbe); ionstr = Vpbe_getBulkIonicStrength(thee->pbe); /* Bail if we're at zero ionic strength */ if (zkappa2 < VSMALL) { #ifndef VAPBSQUIET Vnm_print(0, "Vpmg_qmEnergySMPBE: Zero energy for zero ionic strength!\n"); #endif return 0.0; } zks2 = 0.5*zkappa2/ionstr; if (!thee->filled) { Vnm_print(2, "Vpmg_qmEnergySMPBE: Need to call Vpmg_fillco()!\n"); VASSERT(0); } energy = 0.0; nchop = 0; Vpbe_getIons(thee->pbe, &nion, ionConc, ionRadii, ionQ); /* SMPB Modification (vchu, 09/21/06) */ /* Extensive modification to the first part of the if statement where that handles the thee->pmgp->nonlin part. Basically, I've deleted all of the original code and written my own code that computes the electrostatic free energy in the SMPB framework. Definitely really hacky at this stage of the game, but gets the job done. The second part of the if statement (the part that handles linear poisson-boltzmann) has been deleted because there will be no linearized SMPB energy.. */ z1 = ionQ[0]; z2 = ionQ[1]; z3 = ionQ[2]; cb1 = ionConc[0]; cb2 = ionConc[1]; cb3 = ionConc[2]; a = thee->pbe->smvolume; k = thee->pbe->smsize; /// @todo remove if no conflicts are caused // This constant is defined in vpde.h Do not need to redefine //Na = 6.022045000e-04; /* Converts from Molar to N/A^3 */ fracOccA = Na*cb1*VCUB(a); fracOccB = Na*cb2*VCUB(a); fracOccC = Na*cb3*VCUB(a); phi = (fracOccA/k) + fracOccB + fracOccC; if (thee->pmgp->nonlin) { Vnm_print(0, "Vpmg_qmEnergySMPBE: Calculating nonlinear energy using SMPB functional!\n"); for (i=0, len=nx*ny*nz; i<len; i++) { if (((k-1) > VSMALL) && (thee->pvec[i]*thee->kappa[i] > VSMALL)) { a1 = Vcap_exp(-1.0*z1*thee->u[i], &ichop1); a2 = Vcap_exp(-1.0*z2*thee->u[i], &ichop2); a3 = Vcap_exp(-1.0*z3*thee->u[i], &ichop3); nchop += ichop1 + ichop2 + ichop3; gpark = (1 - phi + (fracOccA/k)*a1); denom = VPOW(gpark, k) + VPOW(1-fracOccB-fracOccC, k-1)*(fracOccB*a2+fracOccC*a3); if (cb1 > VSMALL) { c1 = Na*cb1*VPOW(gpark, k-1)*a1/denom; if(c1 != c1) c1 = 0.; } else c1 = 0.; if (cb2 > VSMALL) { c2 = Na*cb2*VPOW(1-fracOccB-fracOccC,k-1)*a2/denom; if(c2 != c2) c2 = 0.; } else c2 = 0.; if (cb3 > VSMALL) { c3 = Na*cb3*VPOW(1-fracOccB-fracOccC,k-1)*a3/denom; if(c3 != c3) c3 = 0.; } else c3 = 0.; currEnergy = k*VLOG((1-(c1*VCUB(a)/k)-c2*VCUB(a)-c3*VCUB(a))/(1-phi)) -(k-1)*VLOG((1-c2*VCUB(a)-c3*VCUB(a))/(1-phi+(fracOccA/k))); energy += thee->pvec[i]*thee->kappa[i]*currEnergy; } else if (thee->pvec[i]*thee->kappa[i] > VSMALL){ a1 = Vcap_exp(-1.0*z1*thee->u[i], &ichop1); a2 = Vcap_exp(-1.0*z2*thee->u[i], &ichop2); a3 = Vcap_exp(-1.0*z3*thee->u[i], &ichop3); nchop += ichop1 + ichop2 + ichop3; gpark = (1 - phi + (fracOccA)*a1); denom = gpark + (fracOccB*a2+fracOccC*a3); if (cb1 > VSMALL) { c1 = Na*cb1*a1/denom; if(c1 != c1) c1 = 0.; } else c1 = 0.; if (cb2 > VSMALL) { c2 = Na*cb2*a2/denom; if(c2 != c2) c2 = 0.; } else c2 = 0.; if (cb3 > VSMALL) { c3 = Na*cb3*a3/denom; if(c3 != c3) c3 = 0.; } else c3 = 0.; currEnergy = VLOG((1-c1*VCUB(a)-c2*VCUB(a)-c3*VCUB(a))/(1-fracOccA-fracOccB-fracOccC)); energy += thee->pvec[i]*thee->kappa[i]*currEnergy; } } energy = -energy/VCUB(a); if (nchop > 0) Vnm_print(2, "Vpmg_qmEnergySMPBE: Chopped EXP %d times!\n", nchop); } else { /* Zkappa2 OK here b/c LPBE approx */ Vnm_print(0, "Vpmg_qmEnergySMPBE: ERROR: NO LINEAR ENERGY!! Returning 0!\n"); energy = 0.0; } energy = energy*hx*hy*hzed; if (extFlag == 1) energy += thee->extQmEnergy; return energy; } VPUBLIC double Vpmg_qfEnergy(Vpmg *thee, int extFlag ) { double energy = 0.0; VASSERT(thee != VNULL); if ((thee->useChargeMap) || (thee->chargeMeth == VCM_BSPL2)) { energy = Vpmg_qfEnergyVolume(thee, extFlag); } else { energy = Vpmg_qfEnergyPoint(thee, extFlag); } return energy; } VPRIVATE double Vpmg_qfEnergyPoint(Vpmg *thee, int extFlag ) { int iatom, nx, ny, nz, ihi, ilo, jhi, jlo, khi, klo; double xmax, ymax, zmax, xmin, ymin, zmin, hx, hy, hzed, ifloat, jfloat; double charge, kfloat, dx, dy, dz, energy, uval, *position; double *u; double *pvec; Valist *alist; Vatom *atom; Vpbe *pbe; pbe = thee->pbe; alist = pbe->alist; VASSERT(alist != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; u = thee->u; pvec = thee->pvec; energy = 0.0; for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { /* Get atomic information */ atom = Valist_getAtom(alist, iatom); position = Vatom_getPosition(atom); charge = Vatom_getCharge(atom); /* Figure out which vertices we're next to */ ifloat = (position[0] - xmin)/hx; jfloat = (position[1] - ymin)/hy; kfloat = (position[2] - zmin)/hzed; ihi = (int)ceil(ifloat); ilo = (int)floor(ifloat); jhi = (int)ceil(jfloat); jlo = (int)floor(jfloat); khi = (int)ceil(kfloat); klo = (int)floor(kfloat); if (atom->partID > 0) { if ((ihi<nx) && (jhi<ny) && (khi<nz) && (ilo>=0) && (jlo>=0) && (klo>=0)) { /* Now get trilinear interpolation constants */ dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); uval = dx*dy*dz*u[IJK(ihi,jhi,khi)] + dx*(1.0-dy)*dz*u[IJK(ihi,jlo,khi)] + dx*dy*(1.0-dz)*u[IJK(ihi,jhi,klo)] + dx*(1.0-dy)*(1.0-dz)*u[IJK(ihi,jlo,klo)] + (1.0-dx)*dy*dz*u[IJK(ilo,jhi,khi)] + (1.0-dx)*(1.0-dy)*dz*u[IJK(ilo,jlo,khi)] + (1.0-dx)*dy*(1.0-dz)*u[IJK(ilo,jhi,klo)] + (1.0-dx)*(1.0-dy)*(1.0-dz)*u[IJK(ilo,jlo,klo)]; energy += (uval*charge*atom->partID); } else if (thee->pmgp->bcfl != BCFL_FOCUS) { Vnm_print(2, "Vpmg_qfEnergy: Atom #%d at (%4.3f, %4.3f, \ %4.3f) is off the mesh (ignoring)!\n", iatom, position[0], position[1], position[2]); } } } if (extFlag) energy += thee->extQfEnergy; return energy; } VPUBLIC double Vpmg_qfAtomEnergy(Vpmg *thee, Vatom *atom) { int nx, ny, nz, ihi, ilo, jhi, jlo, khi, klo; double xmax, xmin, ymax, ymin, zmax, zmin, hx, hy, hzed, ifloat, jfloat; double charge, kfloat, dx, dy, dz, energy, uval, *position; double *u; /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmax = thee->xf[nx-1]; ymax = thee->yf[ny-1]; zmax = thee->zf[nz-1]; xmin = thee->xf[0]; ymin = thee->yf[0]; zmin = thee->zf[0]; u = thee->u; energy = 0.0; position = Vatom_getPosition(atom); charge = Vatom_getCharge(atom); /* Figure out which vertices we're next to */ ifloat = (position[0] - xmin)/hx; jfloat = (position[1] - ymin)/hy; kfloat = (position[2] - zmin)/hzed; ihi = (int)ceil(ifloat); ilo = (int)floor(ifloat); jhi = (int)ceil(jfloat); jlo = (int)floor(jfloat); khi = (int)ceil(kfloat); klo = (int)floor(kfloat); if (atom->partID > 0) { if ((ihi<nx) && (jhi<ny) && (khi<nz) && (ilo>=0) && (jlo>=0) && (klo>=0)) { /* Now get trilinear interpolation constants */ dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); uval = dx*dy*dz*u[IJK(ihi,jhi,khi)] + dx*(1.0-dy)*dz*u[IJK(ihi,jlo,khi)] + dx*dy*(1.0-dz)*u[IJK(ihi,jhi,klo)] + dx*(1.0-dy)*(1.0-dz)*u[IJK(ihi,jlo,klo)] + (1.0-dx)*dy*dz*u[IJK(ilo,jhi,khi)] + (1.0-dx)*(1.0-dy)*dz*u[IJK(ilo,jlo,khi)] + (1.0-dx)*dy*(1.0-dz)*u[IJK(ilo,jhi,klo)] + (1.0-dx)*(1.0-dy)*(1.0-dz)*u[IJK(ilo,jlo,klo)]; energy += (uval*charge*atom->partID); } else if (thee->pmgp->bcfl != BCFL_FOCUS) { Vnm_print(2, "Vpmg_qfAtomEnergy: Atom at (%4.3f, %4.3f, \ %4.3f) is off the mesh (ignoring)!\n", position[0], position[1], position[2]); } } return energy; } VPRIVATE double Vpmg_qfEnergyVolume(Vpmg *thee, int extFlag) { double hx, hy, hzed, energy; int i, nx, ny, nz; VASSERT(thee != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; if (!thee->filled) { Vnm_print(2, "Vpmg_qfEnergyVolume: need to call Vpmg_fillco!\n"); VASSERT(0); } energy = 0.0; Vnm_print(0, "Vpmg_qfEnergyVolume: Calculating energy\n"); for (i=0; i<(nx*ny*nz); i++) { energy += (thee->pvec[i]*thee->u[i]*thee->charge[i]); } energy = energy*hx*hy*hzed/Vpbe_getZmagic(thee->pbe); if (extFlag == 1) energy += thee->extQfEnergy; return energy; } VPRIVATE void Vpmg_splineSelect(int srfm,Vacc *acc,double *gpos,double win, double infrad,Vatom *atom,double *force){ switch (srfm) { case VSM_SPLINE : Vacc_splineAccGradAtomNorm(acc, gpos, win, infrad, atom, force); break; case VSM_SPLINE3: Vacc_splineAccGradAtomNorm3(acc, gpos, win, infrad, atom, force); break; case VSM_SPLINE4 : Vacc_splineAccGradAtomNorm4(acc, gpos, win, infrad, atom, force); break; default: Vnm_print(2, "Vpmg_dbnbForce: Unknown surface method.\n"); return; } return; } VPRIVATE void focusFillBound(Vpmg *thee, Vpmg *pmgOLD ) { Vpbe *pbe; double hxOLD, hyOLD, hzOLD, xminOLD, yminOLD, zminOLD, xmaxOLD, ymaxOLD, zmaxOLD, hxNEW, hyNEW, hzNEW, xminNEW, yminNEW, zminNEW, xmaxNEW, ymaxNEW, zmaxNEW, x, y, z, dx, dy, dz, ifloat, jfloat, kfloat, uval, eps_w, T, pre1, xkappa, size, *apos, charge, //pos[3], // gcc: not used uvalMin, uvalMax, *data; int nxOLD, nyOLD, nzOLD, nxNEW, nyNEW, nzNEW, i, j, k, ihi, ilo, jhi, jlo, khi, klo, nx, ny, nz; /* Calculate new problem dimensions */ hxNEW = thee->pmgp->hx; hyNEW = thee->pmgp->hy; hzNEW = thee->pmgp->hzed; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; nxNEW = thee->pmgp->nx; nyNEW = thee->pmgp->ny; nzNEW = thee->pmgp->nz; xminNEW = thee->pmgp->xcent - ((double)(nxNEW-1)*hxNEW)/2.0; xmaxNEW = thee->pmgp->xcent + ((double)(nxNEW-1)*hxNEW)/2.0; yminNEW = thee->pmgp->ycent - ((double)(nyNEW-1)*hyNEW)/2.0; ymaxNEW = thee->pmgp->ycent + ((double)(nyNEW-1)*hyNEW)/2.0; zminNEW = thee->pmgp->zcent - ((double)(nzNEW-1)*hzNEW)/2.0; zmaxNEW = thee->pmgp->zcent + ((double)(nzNEW-1)*hzNEW)/2.0; if(pmgOLD != VNULL){ /* Relevant old problem parameters */ hxOLD = pmgOLD->pmgp->hx; hyOLD = pmgOLD->pmgp->hy; hzOLD = pmgOLD->pmgp->hzed; nxOLD = pmgOLD->pmgp->nx; nyOLD = pmgOLD->pmgp->ny; nzOLD = pmgOLD->pmgp->nz; xminOLD = pmgOLD->pmgp->xcent - ((double)(nxOLD-1)*hxOLD)/2.0; xmaxOLD = pmgOLD->pmgp->xcent + ((double)(nxOLD-1)*hxOLD)/2.0; yminOLD = pmgOLD->pmgp->ycent - ((double)(nyOLD-1)*hyOLD)/2.0; ymaxOLD = pmgOLD->pmgp->ycent + ((double)(nyOLD-1)*hyOLD)/2.0; zminOLD = pmgOLD->pmgp->zcent - ((double)(nzOLD-1)*hzOLD)/2.0; zmaxOLD = pmgOLD->pmgp->zcent + ((double)(nzOLD-1)*hzOLD)/2.0; data = pmgOLD->u; }else{ /* Relevant old problem parameters */ hxOLD = thee->potMap->hx; hyOLD = thee->potMap->hy; hzOLD = thee->potMap->hzed; nxOLD = thee->potMap->nx; nyOLD = thee->potMap->ny; nzOLD = thee->potMap->nz; xminOLD = thee->potMap->xmin; xmaxOLD = thee->potMap->xmax; yminOLD = thee->potMap->ymin; ymaxOLD = thee->potMap->ymax; zminOLD = thee->potMap->zmin; zmaxOLD = thee->potMap->zmax; data = thee->potMap->data; } /* BOUNDARY CONDITION SETUP FOR POINTS OFF OLD MESH: * For each "atom" (only one for bcfl=1), we use the following formula to * calculate the boundary conditions: * g(x) = \frac{q e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} * * 1/d * where d = ||x - x_0|| (in m) and a is the size of the atom (in m). * We only need to evaluate some of these prefactors once: * pre1 = \frac{e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * which gives the potential as * g(x) = pre1 * q/d * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} */ pbe = thee->pbe; eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre1 = (Vunit_ec)/(4*VPI*Vunit_eps0*eps_w*Vunit_kb*T); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ pre1 = pre1*(1.0e10); size = Vpbe_getSoluteRadius(pbe); apos = Vpbe_getSoluteCenter(pbe); charge = Vunit_ec*Vpbe_getSoluteCharge(pbe); /* Check for rounding error */ if (VABS(xminOLD-xminNEW) < VSMALL) xminNEW = xminOLD; if (VABS(xmaxOLD-xmaxNEW) < VSMALL) xmaxNEW = xmaxOLD; if (VABS(yminOLD-yminNEW) < VSMALL) yminNEW = yminOLD; if (VABS(ymaxOLD-ymaxNEW) < VSMALL) ymaxNEW = ymaxOLD; if (VABS(zminOLD-zminNEW) < VSMALL) zminNEW = zminOLD; if (VABS(zmaxOLD-zmaxNEW) < VSMALL) zmaxNEW = zmaxOLD; /* Sanity check: make sure we're within the old mesh */ Vnm_print(0, "VPMG::focusFillBound -- New mesh mins = %g, %g, %g\n", xminNEW, yminNEW, zminNEW); Vnm_print(0, "VPMG::focusFillBound -- New mesh maxs = %g, %g, %g\n", xmaxNEW, ymaxNEW, zmaxNEW); Vnm_print(0, "VPMG::focusFillBound -- Old mesh mins = %g, %g, %g\n", xminOLD, yminOLD, zminOLD); Vnm_print(0, "VPMG::focusFillBound -- Old mesh maxs = %g, %g, %g\n", xmaxOLD, ymaxOLD, zmaxOLD); /* The following is obsolete; we'll substitute analytical boundary * condition values when the new mesh falls outside the old */ if ((xmaxNEW>xmaxOLD) || (ymaxNEW>ymaxOLD) || (zmaxNEW>zmaxOLD) || (xminOLD>xminNEW) || (yminOLD>yminNEW) || (zminOLD>zminNEW)) { Vnm_print(2, "Vpmg::focusFillBound -- new mesh not contained in old!\n"); Vnm_print(2, "Vpmg::focusFillBound -- old mesh min = (%g, %g, %g)\n", xminOLD, yminOLD, zminOLD); Vnm_print(2, "Vpmg::focusFillBound -- old mesh max = (%g, %g, %g)\n", xmaxOLD, ymaxOLD, zmaxOLD); Vnm_print(2, "Vpmg::focusFillBound -- new mesh min = (%g, %g, %g)\n", xminNEW, yminNEW, zminNEW); Vnm_print(2, "Vpmg::focusFillBound -- new mesh max = (%g, %g, %g)\n", xmaxNEW, ymaxNEW, zmaxNEW); fflush(stderr); VASSERT(0); } uvalMin = VPMGSMALL; uvalMax = -VPMGSMALL; /* Fill the "i" boundaries (dirichlet) */ for (k=0; k<nzNEW; k++) { for (j=0; j<nyNEW; j++) { /* Low X face */ x = xminNEW; y = yminNEW + j*hyNEW; z = zminNEW + k*hzNEW; if ((x >= (xminOLD-VSMALL)) && (y >= (yminOLD-VSMALL)) && (z >= (zminOLD-VSMALL)) && (x <= (xmaxOLD+VSMALL)) && (y <= (ymaxOLD+VSMALL)) && (z <= (zmaxOLD+VSMALL))) { ifloat = (x - xminOLD)/hxOLD; jfloat = (y - yminOLD)/hyOLD; kfloat = (z - zminOLD)/hzOLD; ihi = (int)ceil(ifloat); if (ihi > (nxOLD-1)) ihi = nxOLD-1; ilo = (int)floor(ifloat); if (ilo < 0) ilo = 0; jhi = (int)ceil(jfloat); if (jhi > (nyOLD-1)) jhi = nyOLD-1; jlo = (int)floor(jfloat); if (jlo < 0) jlo = 0; khi = (int)ceil(kfloat); if (khi > (nzOLD-1)) khi = nzOLD-1; klo = (int)floor(kfloat); if (klo < 0) klo = 0; dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); nx = nxOLD; ny = nyOLD; nz = nzOLD; uval = dx*dy*dz*(data[IJK(ihi,jhi,khi)]) + dx*(1.0-dy)*dz*(data[IJK(ihi,jlo,khi)]) + dx*dy*(1.0-dz)*(data[IJK(ihi,jhi,klo)]) + dx*(1.0-dy)*(1.0-dz)*(data[IJK(ihi,jlo,klo)]) + (1.0-dx)*dy*dz*(data[IJK(ilo,jhi,khi)]) + (1.0-dx)*(1.0-dy)*dz*(data[IJK(ilo,jlo,khi)]) + (1.0-dx)*dy*(1.0-dz)*(data[IJK(ilo,jhi,klo)]) + (1.0-dx)*(1.0-dy)*(1.0-dz)*(data[IJK(ilo,jlo,klo)]); nx = nxNEW; ny = nyNEW; nz = nzNEW; } else { Vnm_print(2, "focusFillBound (%s, %d): Off old mesh at %g, %g \ %g!\n", __FILE__, __LINE__, x, y, z); Vnm_print(2, "focusFillBound (%s, %d): old mesh lower corner at \ %g %g %g.\n", __FILE__, __LINE__, xminOLD, yminOLD, zminOLD); Vnm_print(2, "focusFillBound (%s, %d): old mesh upper corner at \ %g %g %g.\n", __FILE__, __LINE__, xmaxOLD, ymaxOLD, zmaxOLD); VASSERT(0); } nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gxcf[IJKx(j,k,0)] = uval; if(uval < uvalMin) uvalMin = uval; if(uval > uvalMax) uvalMax = uval; /* High X face */ x = xmaxNEW; if ((x >= (xminOLD-VSMALL)) && (y >= (yminOLD-VSMALL)) && (z >= (zminOLD-VSMALL)) && (x <= (xmaxOLD+VSMALL)) && (y <= (ymaxOLD+VSMALL)) && (z <= (zmaxOLD+VSMALL))) { ifloat = (x - xminOLD)/hxOLD; jfloat = (y - yminOLD)/hyOLD; kfloat = (z - zminOLD)/hzOLD; ihi = (int)ceil(ifloat); if (ihi > (nxOLD-1)) ihi = nxOLD-1; ilo = (int)floor(ifloat); if (ilo < 0) ilo = 0; jhi = (int)ceil(jfloat); if (jhi > (nyOLD-1)) jhi = nyOLD-1; jlo = (int)floor(jfloat); if (jlo < 0) jlo = 0; khi = (int)ceil(kfloat); if (khi > (nzOLD-1)) khi = nzOLD-1; klo = (int)floor(kfloat); if (klo < 0) klo = 0; dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); nx = nxOLD; ny = nyOLD; nz = nzOLD; uval = dx*dy*dz*(data[IJK(ihi,jhi,khi)]) + dx*(1.0-dy)*dz*(data[IJK(ihi,jlo,khi)]) + dx*dy*(1.0-dz)*(data[IJK(ihi,jhi,klo)]) + dx*(1.0-dy)*(1.0-dz)*(data[IJK(ihi,jlo,klo)]) + (1.0-dx)*dy*dz*(data[IJK(ilo,jhi,khi)]) + (1.0-dx)*(1.0-dy)*dz*(data[IJK(ilo,jlo,khi)]) + (1.0-dx)*dy*(1.0-dz)*(data[IJK(ilo,jhi,klo)]) + (1.0-dx)*(1.0-dy)*(1.0-dz)*(data[IJK(ilo,jlo,klo)]); nx = nxNEW; ny = nyNEW; nz = nzNEW; } else { Vnm_print(2, "focusFillBound (%s, %d): Off old mesh at %g, %g \ %g!\n", __FILE__, __LINE__, x, y, z); Vnm_print(2, "focusFillBound (%s, %d): old mesh lower corner at \ %g %g %g.\n", __FILE__, __LINE__, xminOLD, yminOLD, zminOLD); Vnm_print(2, "focusFillBound (%s, %d): old mesh upper corner at \ %g %g %g.\n", __FILE__, __LINE__, xmaxOLD, ymaxOLD, zmaxOLD); VASSERT(0); } nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gxcf[IJKx(j,k,1)] = uval; if(uval < uvalMin) uvalMin = uval; if(uval > uvalMax) uvalMax = uval; /* Zero Neumann conditions */ nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gxcf[IJKx(j,k,2)] = 0.0; nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gxcf[IJKx(j,k,3)] = 0.0; } } /* Fill the "j" boundaries (dirichlet) */ for (k=0; k<nzNEW; k++) { for (i=0; i<nxNEW; i++) { /* Low Y face */ x = xminNEW + i*hxNEW; y = yminNEW; z = zminNEW + k*hzNEW; if ((x >= (xminOLD-VSMALL)) && (y >= (yminOLD-VSMALL)) && (z >= (zminOLD-VSMALL)) && (x <= (xmaxOLD+VSMALL)) && (y <= (ymaxOLD+VSMALL)) && (z <= (zmaxOLD+VSMALL))) { ifloat = (x - xminOLD)/hxOLD; jfloat = (y - yminOLD)/hyOLD; kfloat = (z - zminOLD)/hzOLD; ihi = (int)ceil(ifloat); if (ihi > (nxOLD-1)) ihi = nxOLD-1; ilo = (int)floor(ifloat); if (ilo < 0) ilo = 0; jhi = (int)ceil(jfloat); if (jhi > (nyOLD-1)) jhi = nyOLD-1; jlo = (int)floor(jfloat); if (jlo < 0) jlo = 0; khi = (int)ceil(kfloat); if (khi > (nzOLD-1)) khi = nzOLD-1; klo = (int)floor(kfloat); if (klo < 0) klo = 0; dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); nx = nxOLD; ny = nyOLD; nz = nzOLD; uval = dx*dy*dz*(data[IJK(ihi,jhi,khi)]) + dx*(1.0-dy)*dz*(data[IJK(ihi,jlo,khi)]) + dx*dy*(1.0-dz)*(data[IJK(ihi,jhi,klo)]) + dx*(1.0-dy)*(1.0-dz)*(data[IJK(ihi,jlo,klo)]) + (1.0-dx)*dy*dz*(data[IJK(ilo,jhi,khi)]) + (1.0-dx)*(1.0-dy)*dz*(data[IJK(ilo,jlo,khi)]) + (1.0-dx)*dy*(1.0-dz)*(data[IJK(ilo,jhi,klo)]) + (1.0-dx)*(1.0-dy)*(1.0-dz)*(data[IJK(ilo,jlo,klo)]); nx = nxNEW; ny = nyNEW; nz = nzNEW; } else { Vnm_print(2, "focusFillBound (%s, %d): Off old mesh at %g, %g \ %g!\n", __FILE__, __LINE__, x, y, z); Vnm_print(2, "focusFillBound (%s, %d): old mesh lower corner at \ %g %g %g.\n", __FILE__, __LINE__, xminOLD, yminOLD, zminOLD); Vnm_print(2, "focusFillBound (%s, %d): old mesh upper corner at \ %g %g %g.\n", __FILE__, __LINE__, xmaxOLD, ymaxOLD, zmaxOLD); VASSERT(0); } nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gycf[IJKy(i,k,0)] = uval; if(uval < uvalMin) uvalMin = uval; if(uval > uvalMax) uvalMax = uval; /* High Y face */ y = ymaxNEW; if ((x >= (xminOLD-VSMALL)) && (y >= (yminOLD-VSMALL)) && (z >= (zminOLD-VSMALL)) && (x <= (xmaxOLD+VSMALL)) && (y <= (ymaxOLD+VSMALL)) && (z <= (zmaxOLD+VSMALL))) { ifloat = (x - xminOLD)/hxOLD; jfloat = (y - yminOLD)/hyOLD; kfloat = (z - zminOLD)/hzOLD; ihi = (int)ceil(ifloat); if (ihi > (nxOLD-1)) ihi = nxOLD-1; ilo = (int)floor(ifloat); if (ilo < 0) ilo = 0; jhi = (int)ceil(jfloat); if (jhi > (nyOLD-1)) jhi = nyOLD-1; jlo = (int)floor(jfloat); if (jlo < 0) jlo = 0; khi = (int)ceil(kfloat); if (khi > (nzOLD-1)) khi = nzOLD-1; klo = (int)floor(kfloat); if (klo < 0) klo = 0; dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); nx = nxOLD; ny = nyOLD; nz = nzOLD; uval = dx*dy*dz*(data[IJK(ihi,jhi,khi)]) + dx*(1.0-dy)*dz*(data[IJK(ihi,jlo,khi)]) + dx*dy*(1.0-dz)*(data[IJK(ihi,jhi,klo)]) + dx*(1.0-dy)*(1.0-dz)*(data[IJK(ihi,jlo,klo)]) + (1.0-dx)*dy*dz*(data[IJK(ilo,jhi,khi)]) + (1.0-dx)*(1.0-dy)*dz*(data[IJK(ilo,jlo,khi)]) + (1.0-dx)*dy*(1.0-dz)*(data[IJK(ilo,jhi,klo)]) + (1.0-dx)*(1.0-dy)*(1.0-dz)*(data[IJK(ilo,jlo,klo)]); nx = nxNEW; ny = nyNEW; nz = nzNEW; } else { Vnm_print(2, "focusFillBound (%s, %d): Off old mesh at %g, %g \ %g!\n", __FILE__, __LINE__, x, y, z); Vnm_print(2, "focusFillBound (%s, %d): old mesh lower corner at \ %g %g %g.\n", __FILE__, __LINE__, xminOLD, yminOLD, zminOLD); Vnm_print(2, "focusFillBound (%s, %d): old mesh upper corner at \ %g %g %g.\n", __FILE__, __LINE__, xmaxOLD, ymaxOLD, zmaxOLD); VASSERT(0); } nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gycf[IJKy(i,k,1)] = uval; if(uval < uvalMin) uvalMin = uval; if(uval > uvalMax) uvalMax = uval; /* Zero Neumann conditions */ nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gycf[IJKy(i,k,2)] = 0.0; nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gycf[IJKy(i,k,3)] = 0.0; } } /* Fill the "k" boundaries (dirichlet) */ for (j=0; j<nyNEW; j++) { for (i=0; i<nxNEW; i++) { /* Low Z face */ x = xminNEW + i*hxNEW; y = yminNEW + j*hyNEW; z = zminNEW; if ((x >= (xminOLD-VSMALL)) && (y >= (yminOLD-VSMALL)) && (z >= (zminOLD-VSMALL)) && (x <= (xmaxOLD+VSMALL)) && (y <= (ymaxOLD+VSMALL)) && (z <= (zmaxOLD+VSMALL))) { ifloat = (x - xminOLD)/hxOLD; jfloat = (y - yminOLD)/hyOLD; kfloat = (z - zminOLD)/hzOLD; ihi = (int)ceil(ifloat); if (ihi > (nxOLD-1)) ihi = nxOLD-1; ilo = (int)floor(ifloat); if (ilo < 0) ilo = 0; jhi = (int)ceil(jfloat); if (jhi > (nyOLD-1)) jhi = nyOLD-1; jlo = (int)floor(jfloat); if (jlo < 0) jlo = 0; khi = (int)ceil(kfloat); if (khi > (nzOLD-1)) khi = nzOLD-1; klo = (int)floor(kfloat); if (klo < 0) klo = 0; dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); nx = nxOLD; ny = nyOLD; nz = nzOLD; uval = dx*dy*dz*(data[IJK(ihi,jhi,khi)]) + dx*(1.0-dy)*dz*(data[IJK(ihi,jlo,khi)]) + dx*dy*(1.0-dz)*(data[IJK(ihi,jhi,klo)]) + dx*(1.0-dy)*(1.0-dz)*(data[IJK(ihi,jlo,klo)]) + (1.0-dx)*dy*dz*(data[IJK(ilo,jhi,khi)]) + (1.0-dx)*(1.0-dy)*dz*(data[IJK(ilo,jlo,khi)]) + (1.0-dx)*dy*(1.0-dz)*(data[IJK(ilo,jhi,klo)]) + (1.0-dx)*(1.0-dy)*(1.0-dz)*(data[IJK(ilo,jlo,klo)]); nx = nxNEW; ny = nyNEW; nz = nzNEW; } else { Vnm_print(2, "focusFillBound (%s, %d): Off old mesh at %g, %g \ %g!\n", __FILE__, __LINE__, x, y, z); Vnm_print(2, "focusFillBound (%s, %d): old mesh lower corner at \ %g %g %g.\n", __FILE__, __LINE__, xminOLD, yminOLD, zminOLD); Vnm_print(2, "focusFillBound (%s, %d): old mesh upper corner at \ %g %g %g.\n", __FILE__, __LINE__, xmaxOLD, ymaxOLD, zmaxOLD); VASSERT(0); } nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gzcf[IJKz(i,j,0)] = uval; if(uval < uvalMin) uvalMin = uval; if(uval > uvalMax) uvalMax = uval; /* High Z face */ z = zmaxNEW; if ((x >= (xminOLD-VSMALL)) && (y >= (yminOLD-VSMALL)) && (z >= (zminOLD-VSMALL)) && (x <= (xmaxOLD+VSMALL)) && (y <= (ymaxOLD+VSMALL)) && (z <= (zmaxOLD+VSMALL))) { ifloat = (x - xminOLD)/hxOLD; jfloat = (y - yminOLD)/hyOLD; kfloat = (z - zminOLD)/hzOLD; ihi = (int)ceil(ifloat); if (ihi > (nxOLD-1)) ihi = nxOLD-1; ilo = (int)floor(ifloat); if (ilo < 0) ilo = 0; jhi = (int)ceil(jfloat); if (jhi > (nyOLD-1)) jhi = nyOLD-1; jlo = (int)floor(jfloat); if (jlo < 0) jlo = 0; khi = (int)ceil(kfloat); if (khi > (nzOLD-1)) khi = nzOLD-1; klo = (int)floor(kfloat); if (klo < 0) klo = 0; dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); nx = nxOLD; ny = nyOLD; nz = nzOLD; uval = dx*dy*dz*(data[IJK(ihi,jhi,khi)]) + dx*(1.0-dy)*dz*(data[IJK(ihi,jlo,khi)]) + dx*dy*(1.0-dz)*(data[IJK(ihi,jhi,klo)]) + dx*(1.0-dy)*(1.0-dz)*(data[IJK(ihi,jlo,klo)]) + (1.0-dx)*dy*dz*(data[IJK(ilo,jhi,khi)]) + (1.0-dx)*(1.0-dy)*dz*(data[IJK(ilo,jlo,khi)]) + (1.0-dx)*dy*(1.0-dz)*(data[IJK(ilo,jhi,klo)]) + (1.0-dx)*(1.0-dy)*(1.0-dz)*(data[IJK(ilo,jlo,klo)]); nx = nxNEW; ny = nyNEW; nz = nzNEW; } else { Vnm_print(2, "focusFillBound (%s, %d): Off old mesh at %g, %g \ %g!\n", __FILE__, __LINE__, x, y, z); Vnm_print(2, "focusFillBound (%s, %d): old mesh lower corner at \ %g %g %g.\n", __FILE__, __LINE__, xminOLD, yminOLD, zminOLD); Vnm_print(2, "focusFillBound (%s, %d): old mesh upper corner at \ %g %g %g.\n", __FILE__, __LINE__, xmaxOLD, ymaxOLD, zmaxOLD); VASSERT(0); } nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gzcf[IJKz(i,j,1)] = uval; if(uval < uvalMin) uvalMin = uval; if(uval > uvalMax) uvalMax = uval; /* Zero Neumann conditions */ nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gzcf[IJKz(i,j,2)] = 0.0; nx = nxNEW; ny = nyNEW; nz = nzNEW; thee->gzcf[IJKz(i,j,3)] = 0.0; } } VWARN_MSG0( uvalMin >= SINH_MIN && uvalMax <= SINH_MAX, "Unusually large potential values\n" " detected on the focusing boundary!\n" " Convergence not guaranteed for NPBE/NRPBE calculations!" ); } VPRIVATE void extEnergy(Vpmg *thee, Vpmg *pmgOLD, PBEparm_calcEnergy extFlag, double partMin[3], double partMax[3], int bflags[6]) { Vatom *atom; double hxNEW, hyNEW, hzNEW; double lowerCorner[3], upperCorner[3]; int nxNEW, nyNEW, nzNEW; int nxOLD, nyOLD, nzOLD; int i,j,k; double xmin, xmax, ymin, ymax, zmin, zmax; double hxOLD, hyOLD, hzOLD; double xval, yval, zval; double x,y,z; int nx, ny, nz; /* Set the new external energy contribution to zero. Any external * contributions from higher levels will be included in the appropriate * energy function call. */ thee->extQmEnergy = 0; thee->extQfEnergy = 0; thee->extDiEnergy = 0; /* New problem dimensions */ hxNEW = thee->pmgp->hx; hyNEW = thee->pmgp->hy; hzNEW = thee->pmgp->hzed; nxNEW = thee->pmgp->nx; nyNEW = thee->pmgp->ny; nzNEW = thee->pmgp->nz; lowerCorner[0] = thee->pmgp->xcent - ((double)(nxNEW-1)*hxNEW)/2.0; upperCorner[0] = thee->pmgp->xcent + ((double)(nxNEW-1)*hxNEW)/2.0; lowerCorner[1] = thee->pmgp->ycent - ((double)(nyNEW-1)*hyNEW)/2.0; upperCorner[1] = thee->pmgp->ycent + ((double)(nyNEW-1)*hyNEW)/2.0; lowerCorner[2] = thee->pmgp->zcent - ((double)(nzNEW-1)*hzNEW)/2.0; upperCorner[2] = thee->pmgp->zcent + ((double)(nzNEW-1)*hzNEW)/2.0; Vnm_print(0, "VPMG::extEnergy: energy flag = %d\n", extFlag); /* Old problem dimensions */ nxOLD = pmgOLD->pmgp->nx; nyOLD = pmgOLD->pmgp->ny; nzOLD = pmgOLD->pmgp->nz; /* Create a partition based on the new problem dimensions */ /* Vnm_print(1, "DEBUG (%s, %d): extEnergy calling Vpmg_setPart for old PMG.\n", __FILE__, __LINE__); */ Vpmg_setPart(pmgOLD, lowerCorner, upperCorner, bflags); Vnm_print(0,"VPMG::extEnergy: Finding extEnergy dimensions...\n"); Vnm_print(0,"VPMG::extEnergy Disj part lower corner = (%g, %g, %g)\n", partMin[0], partMin[1], partMin[2]); Vnm_print(0,"VPMG::extEnergy Disj part upper corner = (%g, %g, %g)\n", partMax[0], partMax[1], partMax[2]); /* Find the old dimensions */ hxOLD = pmgOLD->pmgp->hx; hyOLD = pmgOLD->pmgp->hy; hzOLD = pmgOLD->pmgp->hzed; xmin = pmgOLD->pmgp->xcent - 0.5*hxOLD*(nxOLD-1); ymin = pmgOLD->pmgp->ycent - 0.5*hyOLD*(nyOLD-1); zmin = pmgOLD->pmgp->zcent - 0.5*hzOLD*(nzOLD-1); xmax = xmin+hxOLD*(nxOLD-1); ymax = ymin+hyOLD*(nyOLD-1); zmax = zmin+hzOLD*(nzOLD-1); Vnm_print(0,"VPMG::extEnergy Old lower corner = (%g, %g, %g)\n", xmin, ymin, zmin); Vnm_print(0,"VPMG::extEnergy Old upper corner = (%g, %g, %g)\n", xmax, ymax, zmax); /* Flip the partition, but do not include any points that will be included by another processor */ nx = nxOLD; ny = nyOLD; nz = nzOLD; for(i=0; i<nx; i++) { xval = 1; x = i*hxOLD + xmin; if (x < partMin[0] && bflags[VAPBS_LEFT] == 1) xval = 0; else if (x > partMax[0] && bflags[VAPBS_RIGHT] == 1) xval = 0; for(j=0; j<ny; j++) { yval = 1; y = j*hyOLD + ymin; if (y < partMin[1] && bflags[VAPBS_BACK] == 1) yval = 0; else if (y > partMax[1] && bflags[VAPBS_FRONT] == 1) yval = 0; for(k=0; k<nz; k++) { zval = 1; z = k*hzOLD + zmin; if (z < partMin[2] && bflags[VAPBS_DOWN] == 1) zval = 0; else if (z > partMax[2] && bflags[VAPBS_UP] == 1) zval = 0; if (pmgOLD->pvec[IJK(i,j,k)] > VSMALL) pmgOLD->pvec[IJK(i,j,k)] = 1.0; pmgOLD->pvec[IJK(i,j,k)] = (1 - (pmgOLD->pvec[IJK(i,j,k)])) * (xval*yval*zval); } } } for (i=0; i<Valist_getNumberAtoms(thee->pbe->alist); i++) { xval=1; yval=1; zval=1; atom = Valist_getAtom(thee->pbe->alist, i); x = atom->position[0]; y = atom->position[1]; z = atom->position[2]; if (x < partMin[0] && bflags[VAPBS_LEFT] == 1) xval = 0; else if (x > partMax[0] && bflags[VAPBS_RIGHT] == 1) xval = 0; if (y < partMin[1] && bflags[VAPBS_BACK] == 1) yval = 0; else if (y > partMax[1] && bflags[VAPBS_FRONT] == 1) yval = 0; if (z < partMin[2] && bflags[VAPBS_DOWN] == 1) zval = 0; else if (z > partMax[2] && bflags[VAPBS_UP] == 1) zval = 0; if (atom->partID > VSMALL) atom->partID = 1.0; atom->partID = (1 - atom->partID) * (xval*yval*zval); } /* Now calculate the energy on inverted subset of the domain */ thee->extQmEnergy = Vpmg_qmEnergy(pmgOLD, 1); Vnm_print(0, "VPMG::extEnergy: extQmEnergy = %g kT\n", thee->extQmEnergy); thee->extQfEnergy = Vpmg_qfEnergy(pmgOLD, 1); Vnm_print(0, "VPMG::extEnergy: extQfEnergy = %g kT\n", thee->extQfEnergy); thee->extDiEnergy = Vpmg_dielEnergy(pmgOLD, 1); Vnm_print(0, "VPMG::extEnergy: extDiEnergy = %g kT\n", thee->extDiEnergy); Vpmg_unsetPart(pmgOLD); } VPRIVATE double bcfl1sp(double size, double *apos, double charge, double xkappa, double pre1, double *pos) { double dist, val; dist = VSQRT(VSQR(pos[0]-apos[0]) + VSQR(pos[1]-apos[1]) + VSQR(pos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } return val; } VPRIVATE void bcfl1(double size, double *apos, double charge, double xkappa, double pre1, double *gxcf, double *gycf, double *gzcf, double *xf, double *yf, double *zf, int nx, int ny, int nz) { int i, j, k; double dist, val; double gpos[3]; /* the "i" boundaries (dirichlet) */ for (k=0; k<nz; k++) { gpos[2] = zf[k]; for (j=0; j<ny; j++) { gpos[1] = yf[j]; gpos[0] = xf[0]; dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } gxcf[IJKx(j,k,0)] += val; gpos[0] = xf[nx-1]; dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } gxcf[IJKx(j,k,1)] += val; } } /* the "j" boundaries (dirichlet) */ for (k=0; k<nz; k++) { gpos[2] = zf[k]; for (i=0; i<nx; i++) { gpos[0] = xf[i]; gpos[1] = yf[0]; dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } gycf[IJKy(i,k,0)] += val; gpos[1] = yf[ny-1]; dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } gycf[IJKy(i,k,1)] += val; } } /* the "k" boundaries (dirichlet) */ for (j=0; j<ny; j++) { gpos[1] = yf[j]; for (i=0; i<nx; i++) { gpos[0] = xf[i]; gpos[2] = zf[0]; dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } gzcf[IJKz(i,j,0)] += val; gpos[2] = zf[nz-1]; dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val = pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val = pre1*(charge/dist); } gzcf[IJKz(i,j,1)] += val; } } } VPRIVATE void bcfl2(double size, double *apos, double charge, double *dipole, double *quad, double xkappa, double eps_p, double eps_w, double T, double *gxcf, double *gycf, double *gzcf, double *xf, double *yf, double *zf, int nx, int ny, int nz) { int i, j, k; double val; double gpos[3],tensor[3]; double ux,uy,uz,xr,yr,zr; double qxx,qxy,qxz,qyx,qyy,qyz,qzx,qzy,qzz; double dist, pre; VASSERT(dipole != VNULL); ux = dipole[0]; uy = dipole[1]; uz = dipole[2]; if (quad != VNULL) { /* The factor of 1/3 results from using a traceless quadrupole definition. See, for example, "The Theory of Intermolecular Forces" by A.J. Stone, Chapter 3. */ qxx = quad[0] / 3.0; qxy = quad[1] / 3.0; qxz = quad[2] / 3.0; qyx = quad[3] / 3.0; qyy = quad[4] / 3.0; qyz = quad[5] / 3.0; qzx = quad[6] / 3.0; qzy = quad[7] / 3.0; qzz = quad[8] / 3.0; } else { qxx = 0.0; qxy = 0.0; qxz = 0.0; qyx = 0.0; qyy = 0.0; qyz = 0.0; qzx = 0.0; qzy = 0.0; qzz = 0.0; } pre = (Vunit_ec*Vunit_ec)/(4*VPI*Vunit_eps0*Vunit_kb*T); pre = pre*(1.0e10); /* the "i" boundaries (dirichlet) */ for (k=0; k<nz; k++) { gpos[2] = zf[k]; for (j=0; j<ny; j++) { gpos[1] = yf[j]; gpos[0] = xf[0]; xr = gpos[0] - apos[0]; yr = gpos[1] - apos[1]; zr = gpos[2] - apos[2]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*charge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; gxcf[IJKx(j,k,0)] += val; gpos[0] = xf[nx-1]; xr = gpos[0] - apos[0]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*charge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; gxcf[IJKx(j,k,1)] += val; } } /* the "j" boundaries (dirichlet) */ for (k=0; k<nz; k++) { gpos[2] = zf[k]; for (i=0; i<nx; i++) { gpos[0] = xf[i]; gpos[1] = yf[0]; xr = gpos[0] - apos[0]; yr = gpos[1] - apos[1]; zr = gpos[2] - apos[2]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*charge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; gycf[IJKy(i,k,0)] += val; gpos[1] = yf[ny-1]; yr = gpos[1] - apos[1]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*charge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; gycf[IJKy(i,k,1)] += val; } } /* the "k" boundaries (dirichlet) */ for (j=0; j<ny; j++) { gpos[1] = yf[j]; for (i=0; i<nx; i++) { gpos[0] = xf[i]; gpos[2] = zf[0]; xr = gpos[0] - apos[0]; yr = gpos[1] - apos[1]; zr = gpos[2] - apos[2]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*charge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; gzcf[IJKz(i,j,0)] += val; gpos[2] = zf[nz-1]; zr = gpos[2] - apos[2]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*charge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; gzcf[IJKz(i,j,1)] += val; } } } VPRIVATE void bcCalcOrig(Vpmg *thee) { int nx, ny, nz; double size, *position, charge, xkappa, eps_w, T, pre1; double *dipole, *quadrupole, debye, eps_p; double xr,yr,zr,qave,*apos; double sdhcharge, sdhdipole[3], traced[9], sdhquadrupole[9]; int i, j, k, iatom; Vpbe *pbe; Vatom *atom; Valist *alist; pbe = thee->pbe; alist = thee->pbe->alist; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; /* Zero out the boundaries */ /* the "i" boundaries (dirichlet) */ for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { thee->gxcf[IJKx(j,k,0)] = 0.0; thee->gxcf[IJKx(j,k,1)] = 0.0; thee->gxcf[IJKx(j,k,2)] = 0.0; thee->gxcf[IJKx(j,k,3)] = 0.0; } } /* the "j" boundaries (dirichlet) */ for (k=0; k<nz; k++) { for (i=0; i<nx; i++) { thee->gycf[IJKy(i,k,0)] = 0.0; thee->gycf[IJKy(i,k,1)] = 0.0; thee->gycf[IJKy(i,k,2)] = 0.0; thee->gycf[IJKy(i,k,3)] = 0.0; } } /* the "k" boundaries (dirichlet) */ for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { thee->gzcf[IJKz(i,j,0)] = 0.0; thee->gzcf[IJKz(i,j,1)] = 0.0; thee->gzcf[IJKz(i,j,2)] = 0.0; thee->gzcf[IJKz(i,j,3)] = 0.0; } } /* For each "atom" (only one for bcfl=1), we use the following formula to * calculate the boundary conditions: * g(x) = \frac{q e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} * * 1/d * where d = ||x - x_0|| (in m) and a is the size of the atom (in m). * We only need to evaluate some of these prefactors once: * pre1 = \frac{e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * which gives the potential as * g(x) = pre1 * q/d * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} */ eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ eps_p = Vpbe_getSoluteDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre1 = (Vunit_ec)/(4*VPI*Vunit_eps0*eps_w*Vunit_kb*T); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ pre1 = pre1*(1.0e10); switch (thee->pmgp->bcfl) { /* If we have zero boundary conditions, we're done */ case BCFL_ZERO: return; /* For single DH sphere BC's, we only have one "atom" to deal with; * get its information and */ case BCFL_SDH: size = Vpbe_getSoluteRadius(pbe); position = Vpbe_getSoluteCenter(pbe); /* For AMOEBA SDH boundary conditions, we need to find the total monopole, dipole and traceless quadrupole moments of either the permanent multipoles, induced dipoles or non-local induced dipoles. */ sdhcharge = 0.0; for (i=0; i<3; i++) sdhdipole[i] = 0.0; for (i=0; i<9; i++) sdhquadrupole[i] = 0.0; for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); xr = apos[0] - position[0]; yr = apos[1] - position[1]; zr = apos[2] - position[2]; switch (thee->chargeSrc) { case VCM_CHARGE: charge = Vatom_getCharge(atom); sdhcharge += charge; sdhdipole[0] += xr * charge; sdhdipole[1] += yr * charge; sdhdipole[2] += zr * charge; traced[0] = xr*xr*charge; traced[1] = xr*yr*charge; traced[2] = xr*zr*charge; traced[3] = yr*xr*charge; traced[4] = yr*yr*charge; traced[5] = yr*zr*charge; traced[6] = zr*xr*charge; traced[7] = zr*yr*charge; traced[8] = zr*zr*charge; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); #if defined(WITH_TINKER) case VCM_PERMANENT: charge = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); quadrupole = Vatom_getQuadrupole(atom); sdhcharge += charge; sdhdipole[0] += xr * charge; sdhdipole[1] += yr * charge; sdhdipole[2] += zr * charge; traced[0] = xr*xr*charge; traced[1] = xr*yr*charge; traced[2] = xr*zr*charge; traced[3] = yr*xr*charge; traced[4] = yr*yr*charge; traced[5] = yr*zr*charge; traced[6] = zr*xr*charge; traced[7] = zr*yr*charge; traced[8] = zr*zr*charge; sdhdipole[0] += dipole[0]; sdhdipole[1] += dipole[1]; sdhdipole[2] += dipole[2]; traced[0] += 2.0*xr*dipole[0]; traced[1] += xr*dipole[1] + yr*dipole[0]; traced[2] += xr*dipole[2] + zr*dipole[0]; traced[3] += yr*dipole[0] + xr*dipole[1]; traced[4] += 2.0*yr*dipole[1]; traced[5] += yr*dipole[2] + zr*dipole[1]; traced[6] += zr*dipole[0] + xr*dipole[2]; traced[7] += zr*dipole[1] + yr*dipole[2]; traced[8] += 2.0*zr*dipole[2]; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); sdhquadrupole[0] += quadrupole[0]; sdhquadrupole[1] += quadrupole[1]; sdhquadrupole[2] += quadrupole[2]; sdhquadrupole[3] += quadrupole[3]; sdhquadrupole[4] += quadrupole[4]; sdhquadrupole[5] += quadrupole[5]; sdhquadrupole[6] += quadrupole[6]; sdhquadrupole[7] += quadrupole[7]; sdhquadrupole[8] += quadrupole[8]; case VCM_INDUCED: dipole = Vatom_getInducedDipole(atom); sdhdipole[0] += dipole[0]; sdhdipole[1] += dipole[1]; sdhdipole[2] += dipole[2]; traced[0] = 2.0*xr*dipole[0]; traced[1] = xr*dipole[1] + yr*dipole[0]; traced[2] = xr*dipole[2] + zr*dipole[0]; traced[3] = yr*dipole[0] + xr*dipole[1]; traced[4] = 2.0*yr*dipole[1]; traced[5] = yr*dipole[2] + zr*dipole[1]; traced[6] = zr*dipole[0] + xr*dipole[2]; traced[7] = zr*dipole[1] + yr*dipole[2]; traced[8] = 2.0*zr*dipole[2]; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); case VCM_NLINDUCED: dipole = Vatom_getNLInducedDipole(atom); sdhdipole[0] += dipole[0]; sdhdipole[1] += dipole[1]; sdhdipole[2] += dipole[2]; traced[0] = 2.0*xr*dipole[0]; traced[1] = xr*dipole[1] + yr*dipole[0]; traced[2] = xr*dipole[2] + zr*dipole[0]; traced[3] = yr*dipole[0] + xr*dipole[1]; traced[4] = 2.0*yr*dipole[1]; traced[5] = yr*dipole[2] + zr*dipole[1]; traced[6] = zr*dipole[0] + xr*dipole[2]; traced[7] = zr*dipole[1] + yr*dipole[2]; traced[8] = 2.0*zr*dipole[2]; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); /*Added the else to kill a warning when building with clang*/ #else case VCM_PERMANENT:; case VCM_INDUCED:; case VCM_NLINDUCED:; #endif /* if defined(WITH_TINKER) */ } } /* SDH dipole and traceless quadrupole values were checked against similar routines in TINKER for large proteins. debye=4.8033324; printf("%6.3f, %6.3f, %6.3f\n", sdhdipole[0]*debye, sdhdipole[1]*debye, sdhdipole[2]*debye); printf("%6.3f\n", sdhquadrupole[0]*debye); printf("%6.3f %6.3f\n", sdhquadrupole[3]*debye, sdhquadrupole[4]*debye); printf("%6.3f %6.3f %6.3f\n", sdhquadrupole[6]*debye, sdhquadrupole[7]*debye, sdhquadrupole[8]*debye); */ bcfl2(size, position, sdhcharge, sdhdipole, sdhquadrupole, xkappa, eps_p, eps_w, T, thee->gxcf, thee->gycf, thee->gzcf, thee->xf, thee->yf, thee->zf, nx, ny, nz); break; case BCFL_MDH: for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); position = Vatom_getPosition(atom); charge = Vunit_ec*Vatom_getCharge(atom); dipole = VNULL; quadrupole = VNULL; size = Vatom_getRadius(atom); switch (thee->chargeSrc) { case VCM_CHARGE: ; #if defined(WITH_TINKER) case VCM_PERMANENT: dipole = Vatom_getDipole(atom); quadrupole = Vatom_getQuadrupole(atom); case VCM_INDUCED: dipole = Vatom_getInducedDipole(atom); case VCM_NLINDUCED: dipole = Vatom_getNLInducedDipole(atom); /*added this to kill a warning when building with clang (by Juan Brandi).*/ #else case VCM_PERMANENT:; case VCM_INDUCED:; case VCM_NLINDUCED:; #endif } bcfl1(size, position, charge, xkappa, pre1, thee->gxcf, thee->gycf, thee->gzcf, thee->xf, thee->yf, thee->zf, nx, ny, nz); } break; case BCFL_UNUSED: Vnm_print(2, "bcCalc: Invalid bcfl (%d)!\n", thee->pmgp->bcfl); VASSERT(0); case BCFL_FOCUS: Vnm_print(2, "VPMG::bcCalc -- not appropriate for focusing!\n"); VASSERT(0); default: Vnm_print(2, "VPMG::bcCalc -- invalid boundary condition \ flag (%d)!\n", thee->pmgp->bcfl); VASSERT(0); } } /* Used by bcflnew */ VPRIVATE int gridPointIsValid(int i, int j, int k, int nx, int ny, int nz){ int isValid = 0; if((k==0) || (k==nz-1)){ isValid = 1; }else if((j==0) || (j==ny-1)){ isValid = 1; }else if((i==0) || (i==nx-1)){ isValid = 1; } return isValid; } /* Used by bcflnew */ #ifdef DEBUG_MAC_OSX_OCL #include "mach_chud.h" VPRIVATE void packAtomsOpenCL(float *ax, float *ay, float *az, float *charge, float *size, Vpmg *thee){ int i; int natoms; Vatom *atom = VNULL; Valist *alist = VNULL; alist = thee->pbe->alist; natoms = Valist_getNumberAtoms(alist); for(i=0;i<natoms;i++){ atom = &(alist->atoms[i]); charge[i] = Vunit_ec*atom->charge; ax[i] = atom->position[0]; ay[i] = atom->position[1]; az[i] = atom->position[2]; size[i] = atom->radius; } } /* Used by bcflnew */ VPRIVATE void packUnpackOpenCL(int nx, int ny, int nz, int ngrid, float *gx, float *gy, float *gz, float *value, Vpmg *thee, int pack){ int i,j,k,igrid; int x0,x1,y0,y1,z0,z1; float gpos[3]; double *xf, *yf, *zf; double *gxcf, *gycf, *gzcf; xf = thee->xf; yf = thee->yf; zf = thee->zf; gxcf = thee->gxcf; gycf = thee->gycf; gzcf = thee->gzcf; igrid = 0; for(k=0;k<nz;k++){ gpos[2] = zf[k]; for(j=0;j<ny;j++){ gpos[1] = yf[j]; for(i=0;i<nx;i++){ gpos[0] = xf[i]; if(gridPointIsValid(i, j, k, nx, ny, nz)){ if(pack != 0){ gx[igrid] = gpos[0]; gy[igrid] = gpos[1]; gz[igrid] = gpos[2]; value[igrid] = 0.0; }else{ x0 = IJKx(j,k,0); x1 = IJKx(j,k,1); y0 = IJKy(i,k,0); y1 = IJKy(i,k,1); z0 = IJKz(i,j,0); z1 = IJKz(i,j,1); if(i==0){ gxcf[x0] += value[igrid]; } if(i==nx-1){ gxcf[x1] += value[igrid]; } if(j==0){ gycf[y0] += value[igrid]; } if(j==ny-1){ gycf[y1] += value[igrid]; } if(k==0){ gzcf[z0] += value[igrid]; } if(k==nz-1){ gzcf[z1] += value[igrid]; } } igrid++; } //end is valid point } //end i } //end j } //end k } /* bcflnew is an optimized replacement for bcfl1. bcfl1 is still used when TINKER support is compiled in. bcflnew uses: packUnpack, packAtoms, gridPointIsValid */ VPRIVATE void bcflnewOpenCL(Vpmg *thee){ int i,j,k, iatom, igrid; int x0, x1, y0, y1, z0, z1; int nx, ny, nz; int natoms, ngrid, ngadj; float dist, pre1, eps_w, eps_p, T, xkappa; float *ax, *ay, *az; float *charge, *size, *val; float *gx, *gy, *gz; Vpbe *pbe = thee->pbe; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ eps_p = Vpbe_getSoluteDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre1 = ((Vunit_ec)/(4*VPI*Vunit_eps0*eps_w*Vunit_kb*T))*(1.0e10); xkappa = Vpbe_getXkappa(pbe); natoms = Valist_getNumberAtoms(thee->pbe->alist); ngrid = 2*((nx*ny) + (ny*nz) + (nx*nz)); ngadj = ngrid + (512 - (ngrid & 511)); ax = (float*)malloc(natoms * sizeof(float)); ay = (float*)malloc(natoms * sizeof(float)); az = (float*)malloc(natoms * sizeof(float)); charge = (float*)malloc(natoms * sizeof(float)); size = (float*)malloc(natoms * sizeof(float)); gx = (float*)malloc(ngrid * sizeof(float)); gy = (float*)malloc(ngrid * sizeof(float)); gz = (float*)malloc(ngrid * sizeof(float)); val = (float*)malloc(ngrid * sizeof(float)); packAtomsOpenCL(ax,ay,az,charge,size,thee); packUnpackOpenCL(nx,ny,nz,ngrid,gx,gy,gz,val,thee,1); runMDHCL(ngrid,natoms,ngadj,ax,ay,az,gx,gy,gz,charge,size,xkappa,pre1,val); packUnpackOpenCL(nx,ny,nz,ngrid,gx,gy,gz,val,thee,0); free(ax); free(ay); free(az); free(charge); free(size); free(gx); free(gy); free(gz); free(val); } #endif VPRIVATE void packAtoms(double *ax, double *ay, double *az, double *charge, double *size, Vpmg *thee){ int i; int natoms; Vatom *atom = VNULL; Valist *alist = VNULL; alist = thee->pbe->alist; natoms = Valist_getNumberAtoms(alist); for(i=0;i<natoms;i++){ atom = &(alist->atoms[i]); charge[i] = Vunit_ec*atom->charge; ax[i] = atom->position[0]; ay[i] = atom->position[1]; az[i] = atom->position[2]; size[i] = atom->radius; } } /* Used by bcflnew */ VPRIVATE void packUnpack(int nx, int ny, int nz, int ngrid, double *gx, double *gy, double *gz, double *value, Vpmg *thee, int pack){ int i,j,k,igrid; int x0,x1,y0,y1,z0,z1; double gpos[3]; double *xf, *yf, *zf; double *gxcf, *gycf, *gzcf; xf = thee->xf; yf = thee->yf; zf = thee->zf; gxcf = thee->gxcf; gycf = thee->gycf; gzcf = thee->gzcf; igrid = 0; for(k=0;k<nz;k++){ gpos[2] = zf[k]; for(j=0;j<ny;j++){ gpos[1] = yf[j]; for(i=0;i<nx;i++){ gpos[0] = xf[i]; if(gridPointIsValid(i, j, k, nx, ny, nz)){ if(pack != 0){ gx[igrid] = gpos[0]; gy[igrid] = gpos[1]; gz[igrid] = gpos[2]; value[igrid] = 0.0; }else{ x0 = IJKx(j,k,0); x1 = IJKx(j,k,1); y0 = IJKy(i,k,0); y1 = IJKy(i,k,1); z0 = IJKz(i,j,0); z1 = IJKz(i,j,1); if(i==0){ gxcf[x0] += value[igrid]; } if(i==nx-1){ gxcf[x1] += value[igrid]; } if(j==0){ gycf[y0] += value[igrid]; } if(j==ny-1){ gycf[y1] += value[igrid]; } if(k==0){ gzcf[z0] += value[igrid]; } if(k==nz-1){ gzcf[z1] += value[igrid]; } } igrid++; } //end is valid point } //end i } //end j } //end k } VPRIVATE void bcflnew(Vpmg *thee){ int i,j,k, iatom, igrid; int x0, x1, y0, y1, z0, z1; int nx, ny, nz; int natoms, ngrid; double dist, pre1, eps_w, eps_p, T, xkappa; double *ax, *ay, *az; double *charge, *size, *val; double *gx, *gy, *gz; Vpbe *pbe = thee->pbe; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ eps_p = Vpbe_getSoluteDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre1 = ((Vunit_ec)/(4*VPI*Vunit_eps0*eps_w*Vunit_kb*T))*(1.0e10); xkappa = Vpbe_getXkappa(pbe); natoms = Valist_getNumberAtoms(thee->pbe->alist); ngrid = 2*((nx*ny) + (ny*nz) + (nx*nz)); ax = (double*)malloc(natoms * sizeof(double)); ay = (double*)malloc(natoms * sizeof(double)); az = (double*)malloc(natoms * sizeof(double)); charge = (double*)malloc(natoms * sizeof(double)); size = (double*)malloc(natoms * sizeof(double)); gx = (double*)malloc(ngrid * sizeof(double)); gy = (double*)malloc(ngrid * sizeof(double)); gz = (double*)malloc(ngrid * sizeof(double)); val = (double*)malloc(ngrid * sizeof(double)); packAtoms(ax,ay,az,charge,size,thee); packUnpack(nx,ny,nz,ngrid,gx,gy,gz,val,thee,1); if(xkappa > VSMALL){ #pragma omp parallel for default(shared) private(igrid,iatom,dist) for(igrid=0;igrid<ngrid;igrid++){ for(iatom=0; iatom<natoms; iatom++){ dist = VSQRT(VSQR(gx[igrid]-ax[iatom]) + VSQR(gy[igrid]-ay[iatom]) + VSQR(gz[igrid]-az[iatom])); val[igrid] += pre1*(charge[iatom]/dist)*VEXP(-xkappa*(dist-size[iatom])) / (1+xkappa*size[iatom]); } } }else{ #pragma omp parallel for default(shared) private(igrid,iatom,dist) for(igrid=0;igrid<ngrid;igrid++){ for(iatom=0; iatom<natoms; iatom++){ dist = VSQRT(VSQR(gx[igrid]-ax[iatom]) + VSQR(gy[igrid]-ay[iatom]) + VSQR(gz[igrid]-az[iatom])); val[igrid] += pre1*(charge[iatom]/dist); } } } packUnpack(nx,ny,nz,ngrid,gx,gy,gz,val,thee,0); free(ax); free(ay); free(az); free(charge); free(size); free(gx); free(gy); free(gz); free(val); } VPRIVATE void multipolebc(double r, double kappa, double eps_p, double eps_w, double rad, double tsr[3]) { double r2,r3,r5; double eps_r; double ka,ka2,ka3; double kr,kr2,kr3; /* Below an attempt is made to explain the potential outside of a multipole located at the center of spherical cavity of dieletric eps_p, with dielectric eps_w outside (and possibly kappa > 0). First, eps_p = 1.0 eps_w = 1.0 kappa = 0.0 The general form for the potential of a traceless multipole tensor of rank n in vacuum is: V(r) = (-1)^n * u . n . Del^n (1/r) where u is a multipole of order n (3^n components) u . n. Del^n (1/r) is the contraction of u with the nth derivative of 1/r for example, if n = 1, the dipole potential is V_vac(r) = (-1)*[ux*x + uy*y + uz*z]/r^3 This function returns the parts of V(r) for multipoles of order 0, 1 and 2 that are independent of the contraction. For the vacuum example, this would be 1/r, -1/r^3 and 3/r^5 respectively. *** Note that this requires that the quadrupole is traceless. If not, the diagonal quadrupole potential changes from qaa * 3*a^2/r^5 to qaa * (3*a^2/r^5 - 1/r^3a ) where we sum over the trace; a = x, y and z. (In other words, the -1/r^3 term cancels for a traceless quadrupole. qxx + qyy + qzz = 0 such that -(qxx + qyy + qzz)/r^3 = 0 For quadrupole with trace: qxx + qyy + qzz != 0 such that -(qxx + qyy + qzz)/r^3 != 0 ) ======================================================================== eps_p != 1 or eps_w != 1 kappa = 0.0 If the multipole is placed at the center of a sphere with dieletric eps_p in a solvent of dielectric eps_w, the potential outside the sphere is the solution to the Laplace equation: V(r) = 1/eps_w * (2*n+1)*eps_r/(n+(n+1)*eps_r) * (-1)^n * u . n . Del^n (1/r) where eps_r = eps_w / eps_p is the ratio of solvent to solute dielectric ======================================================================== kappa > 0 Finally, if the region outside the sphere is treated by the linearized PB equation with Debye-Huckel parameter kappa, the solution is: V(r) = kappa/eps_w * alpha_n(kappa*a) * K_n(kappa*r) * r^(n+1)/a^n * (-1)^n * u . n . Del^n (1/r) where alpha_n(x) is [(2n + 1) / x] / [(n*K_n(x)/eps_r) - x*K_n'(x)] K_n(x) are modified spherical Bessel functions of the third kind. K_n'(x) is the derivative of K_n(x) */ eps_r = eps_w/eps_p; r2 = r*r; r3 = r2*r; r5 = r3*r2; tsr[0] = (1.0/eps_w)/r; tsr[1] = (1.0/eps_w)*(-1.0)/r3; tsr[2] = (1.0/eps_w)*(3.0)/r5; if (kappa < VSMALL) { tsr[1] = (3.0*eps_r)/(1.0 + 2.0*eps_r)*tsr[1]; tsr[2] = (5.0*eps_r)/(2.0 + 3.0*eps_r)*tsr[2]; } else { ka = kappa*rad; ka2 = ka*ka; ka3 = ka2*ka; kr = kappa*r; kr2 = kr*kr; kr3 = kr2*kr; tsr[0] = exp(ka-kr) / (1.0 + ka) * tsr[0]; tsr[1] = 3.0*eps_r*exp(ka-kr)*(1.0 + kr) * tsr[1]; tsr[1] = tsr[1] / (1.0 + ka + eps_r*(2.0 + 2.0*ka + ka2)); tsr[2] = 5.0*eps_r*exp(ka-kr)*(3.0 + 3.0*kr + kr2) * tsr[2]; tsr[2] = tsr[2]/(6.0+6.0*ka+2.0*ka2+eps_r*(9.0+9.0*ka+4.0*ka2+ka3)); } } VPRIVATE void bcfl_sdh(Vpmg *thee){ int i,j,k,iatom; int nx, ny, nz; double size, *position, charge, xkappa, eps_w, eps_p, T, pre, dist; double sdhcharge, sdhdipole[3], traced[9], sdhquadrupole[9]; double *dipole, *quadrupole; double val, *apos, gpos[3], tensor[3], qave; double ux, uy, uz, xr, yr, zr; double qxx,qxy,qxz,qyx,qyy,qyz,qzx,qzy,qzz; double *xf, *yf, *zf; double *gxcf, *gycf, *gzcf; Vpbe *pbe; Vatom *atom; Valist *alist; pbe = thee->pbe; alist = thee->pbe->alist; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; xf = thee->xf; yf = thee->yf; zf = thee->zf; gxcf = thee->gxcf; gycf = thee->gycf; gzcf = thee->gzcf; /* For each "atom" (only one for bcfl=1), we use the following formula to * calculate the boundary conditions: * g(x) = \frac{q e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} * * 1/d * where d = ||x - x_0|| (in m) and a is the size of the atom (in m). * We only need to evaluate some of these prefactors once: * pre1 = \frac{e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * which gives the potential as * g(x) = pre1 * q/d * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} */ eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ eps_p = Vpbe_getSoluteDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre = (Vunit_ec*Vunit_ec)/(4*VPI*Vunit_eps0*Vunit_kb*T); pre = pre*(1.0e10); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ /* Solute size and position */ size = Vpbe_getSoluteRadius(pbe); position = Vpbe_getSoluteCenter(pbe); sdhcharge = 0.0; for (i=0; i<3; i++) sdhdipole[i] = 0.0; for (i=0; i<9; i++) sdhquadrupole[i] = 0.0; for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); xr = apos[0] - position[0]; yr = apos[1] - position[1]; zr = apos[2] - position[2]; switch (thee->chargeSrc) { case VCM_CHARGE: charge = Vatom_getCharge(atom); sdhcharge += charge; sdhdipole[0] += xr * charge; sdhdipole[1] += yr * charge; sdhdipole[2] += zr * charge; traced[0] = xr*xr*charge; traced[1] = xr*yr*charge; traced[2] = xr*zr*charge; traced[3] = yr*xr*charge; traced[4] = yr*yr*charge; traced[5] = yr*zr*charge; traced[6] = zr*xr*charge; traced[7] = zr*yr*charge; traced[8] = zr*zr*charge; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); #if defined(WITH_TINKER) case VCM_PERMANENT: charge = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); quadrupole = Vatom_getQuadrupole(atom); sdhcharge += charge; sdhdipole[0] += xr * charge; sdhdipole[1] += yr * charge; sdhdipole[2] += zr * charge; traced[0] = xr*xr*charge; traced[1] = xr*yr*charge; traced[2] = xr*zr*charge; traced[3] = yr*xr*charge; traced[4] = yr*yr*charge; traced[5] = yr*zr*charge; traced[6] = zr*xr*charge; traced[7] = zr*yr*charge; traced[8] = zr*zr*charge; sdhdipole[0] += dipole[0]; sdhdipole[1] += dipole[1]; sdhdipole[2] += dipole[2]; traced[0] += 2.0*xr*dipole[0]; traced[1] += xr*dipole[1] + yr*dipole[0]; traced[2] += xr*dipole[2] + zr*dipole[0]; traced[3] += yr*dipole[0] + xr*dipole[1]; traced[4] += 2.0*yr*dipole[1]; traced[5] += yr*dipole[2] + zr*dipole[1]; traced[6] += zr*dipole[0] + xr*dipole[2]; traced[7] += zr*dipole[1] + yr*dipole[2]; traced[8] += 2.0*zr*dipole[2]; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); sdhquadrupole[0] += quadrupole[0]; sdhquadrupole[1] += quadrupole[1]; sdhquadrupole[2] += quadrupole[2]; sdhquadrupole[3] += quadrupole[3]; sdhquadrupole[4] += quadrupole[4]; sdhquadrupole[5] += quadrupole[5]; sdhquadrupole[6] += quadrupole[6]; sdhquadrupole[7] += quadrupole[7]; sdhquadrupole[8] += quadrupole[8]; case VCM_INDUCED: dipole = Vatom_getInducedDipole(atom); sdhdipole[0] += dipole[0]; sdhdipole[1] += dipole[1]; sdhdipole[2] += dipole[2]; traced[0] = 2.0*xr*dipole[0]; traced[1] = xr*dipole[1] + yr*dipole[0]; traced[2] = xr*dipole[2] + zr*dipole[0]; traced[3] = yr*dipole[0] + xr*dipole[1]; traced[4] = 2.0*yr*dipole[1]; traced[5] = yr*dipole[2] + zr*dipole[1]; traced[6] = zr*dipole[0] + xr*dipole[2]; traced[7] = zr*dipole[1] + yr*dipole[2]; traced[8] = 2.0*zr*dipole[2]; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); case VCM_NLINDUCED: dipole = Vatom_getNLInducedDipole(atom); sdhdipole[0] += dipole[0]; sdhdipole[1] += dipole[1]; sdhdipole[2] += dipole[2]; traced[0] = 2.0*xr*dipole[0]; traced[1] = xr*dipole[1] + yr*dipole[0]; traced[2] = xr*dipole[2] + zr*dipole[0]; traced[3] = yr*dipole[0] + xr*dipole[1]; traced[4] = 2.0*yr*dipole[1]; traced[5] = yr*dipole[2] + zr*dipole[1]; traced[6] = zr*dipole[0] + xr*dipole[2]; traced[7] = zr*dipole[1] + yr*dipole[2]; traced[8] = 2.0*zr*dipole[2]; qave = (traced[0] + traced[4] + traced[8]) / 3.0; sdhquadrupole[0] += 1.5*(traced[0] - qave); sdhquadrupole[1] += 1.5*(traced[1]); sdhquadrupole[2] += 1.5*(traced[2]); sdhquadrupole[3] += 1.5*(traced[3]); sdhquadrupole[4] += 1.5*(traced[4] - qave); sdhquadrupole[5] += 1.5*(traced[5]); sdhquadrupole[6] += 1.5*(traced[6]); sdhquadrupole[7] += 1.5*(traced[7]); sdhquadrupole[8] += 1.5*(traced[8] - qave); /*added this to kill a warning when building with clang (by Juan Brandi)*/ #else case VCM_PERMANENT:; case VCM_INDUCED:; case VCM_NLINDUCED:; #endif /* if defined(WITH_TINKER) */ } } ux = sdhdipole[0]; uy = sdhdipole[1]; uz = sdhdipole[2]; /* The factor of 1/3 results from using a traceless quadrupole definition. See, for example, "The Theory of Intermolecular Forces" by A.J. Stone, Chapter 3. */ qxx = sdhquadrupole[0] / 3.0; qxy = sdhquadrupole[1] / 3.0; qxz = sdhquadrupole[2] / 3.0; qyx = sdhquadrupole[3] / 3.0; qyy = sdhquadrupole[4] / 3.0; qyz = sdhquadrupole[5] / 3.0; qzx = sdhquadrupole[6] / 3.0; qzy = sdhquadrupole[7] / 3.0; qzz = sdhquadrupole[8] / 3.0; for(k=0;k<nz;k++){ gpos[2] = zf[k]; for(j=0;j<ny;j++){ gpos[1] = yf[j]; for(i=0;i<nx;i++){ gpos[0] = xf[i]; if(gridPointIsValid(i, j, k, nx, ny, nz)){ xr = gpos[0] - position[0]; yr = gpos[1] - position[1]; zr = gpos[2] - position[2]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val = pre*sdhcharge*tensor[0]; val -= pre*ux*xr*tensor[1]; val -= pre*uy*yr*tensor[1]; val -= pre*uz*zr*tensor[1]; val += pre*qxx*xr*xr*tensor[2]; val += pre*qyy*yr*yr*tensor[2]; val += pre*qzz*zr*zr*tensor[2]; val += pre*2.0*qxy*xr*yr*tensor[2]; val += pre*2.0*qxz*xr*zr*tensor[2]; val += pre*2.0*qyz*yr*zr*tensor[2]; if(i==0){ gxcf[IJKx(j,k,0)] = val; } if(i==nx-1){ gxcf[IJKx(j,k,1)] = val; } if(j==0){ gycf[IJKy(i,k,0)] = val; } if(j==ny-1){ gycf[IJKy(i,k,1)] = val; } if(k==0){ gzcf[IJKz(i,j,0)] = val; } if(k==nz-1){ gzcf[IJKz(i,j,1)] = val; } } /* End grid point is valid */ } /* End i loop */ } /* End j loop */ } /* End k loop */ } VPRIVATE void bcfl_mdh(Vpmg *thee){ int i,j,k,iatom; int nx, ny, nz; double val, *apos, gpos[3]; double *dipole, *quadrupole; double size, charge, xkappa, eps_w, eps_p, T, pre1, dist; double *xf, *yf, *zf; double *gxcf, *gycf, *gzcf; Vpbe *pbe; Vatom *atom; Valist *alist; pbe = thee->pbe; alist = thee->pbe->alist; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; xf = thee->xf; yf = thee->yf; zf = thee->zf; gxcf = thee->gxcf; gycf = thee->gycf; gzcf = thee->gzcf; /* For each "atom" (only one for bcfl=1), we use the following formula to * calculate the boundary conditions: * g(x) = \frac{q e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} * * 1/d * where d = ||x - x_0|| (in m) and a is the size of the atom (in m). * We only need to evaluate some of these prefactors once: * pre1 = \frac{e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * which gives the potential as * g(x) = pre1 * q/d * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} */ eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ eps_p = Vpbe_getSoluteDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre1 = (Vunit_ec)/(4*VPI*Vunit_eps0*eps_w*Vunit_kb*T); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ pre1 = pre1*(1.0e10); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ for(k=0;k<nz;k++){ gpos[2] = zf[k]; for(j=0;j<ny;j++){ gpos[1] = yf[j]; for(i=0;i<nx;i++){ gpos[0] = xf[i]; if(gridPointIsValid(i, j, k, nx, ny, nz)){ val = 0.0; for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); charge = Vunit_ec*Vatom_getCharge(atom); size = Vatom_getRadius(atom); dist = VSQRT(VSQR(gpos[0]-apos[0]) + VSQR(gpos[1]-apos[1]) + VSQR(gpos[2]-apos[2])); if (xkappa > VSMALL) { val += pre1*(charge/dist)*VEXP(-xkappa*(dist-size)) / (1+xkappa*size); } else { val += pre1*(charge/dist); } } if(i==0){ gxcf[IJKx(j,k,0)] = val; } if(i==nx-1){ gxcf[IJKx(j,k,1)] = val; } if(j==0){ gycf[IJKy(i,k,0)] = val; } if(j==ny-1){ gycf[IJKy(i,k,1)] = val; } if(k==0){ gzcf[IJKz(i,j,0)] = val; } if(k==nz-1){ gzcf[IJKz(i,j,1)] = val; } } /* End grid point is valid */ } /* End i loop */ } /* End j loop */ } /* End k loop */ } /* /////////////////////////////////////////////////////////////////////////// // Routine: bcfl_mem // // Purpose: Increment all the boundary points by the // analytic expression for a membrane system in // the presence of a membrane potential. This // Boundary flag should only be used for systems // that explicitly have membranes in the dielectric // and solvent maps. // // There should be several input variables add to this // function such as membrane potential, membrane thickness // and height. // // Args: apos is a 3-vector // // Author: Michael Grabe /////////////////////////////////////////////////////////////////////////// */ VPRIVATE void bcfl_mem(double zmem, double L, double eps_m, double eps_w, double V, double xkappa, double *gxcf, double *gycf, double *gzcf, double *xf, double *yf, double *zf, int nx, int ny, int nz) { /////////////////////////////////////////////////// /* some definitions */ /* L = total length of the membrane */ /* xkappa = inverse Debeye length */ /* zmem = z value of membrane bottom (Cytoplasm) */ /* V = electrical potential inside the cell */ /////////////////////////////////////////////////// int i, j, k; double dist, val, z_low, z_high, z_shift; double A, B, C, D, edge_L, l; double G, z_0, z_rel; double gpos[3]; Vnm_print(0, "Here is the value of kappa: %f\n",xkappa); Vnm_print(0, "Here is the value of L: %f\n",L); Vnm_print(0, "Here is the value of zmem: %f\n",zmem); Vnm_print(0, "Here is the value of mdie: %f\n",eps_m); Vnm_print(0, "Here is the value of memv: %f\n",V); /* no salt symmetric BC's at +/- infinity */ // B=V/(edge_L - l*(1-eps_w/eps_m)); // A=V + B*edge_L; // D=eps_w/eps_m*B; z_low = zmem; /* this defines the bottom of the membrane */ z_high = zmem + L; /* this is the top of the membrane */ /******************************************************/ /* proper boundary conditions for V = 0 extracellular */ /* and psi=-V cytoplasm. */ /* Implicit in this formulation is that the membrane */ /* center be at z = 0 */ /******************************************************/ l=L/2; /* half of the membrane length */ z_0 = z_low + l; /* center of the membrane */ G=l*eps_w/eps_m*xkappa; A=-V/2*(1/(G+1))*exp(xkappa*l); B=V/2; C=-V/2*eps_w/eps_m*xkappa*(1/(G+1)); D=-A; /* The analytic expression for the boundary conditions */ /* had the cytoplasmic surface of the membrane set to zero. */ /* This requires an off-set of the BC equations. */ /* the "i" boundaries (dirichlet) */ for (k=0; k<nz; k++) { gpos[2] = zf[k]; z_rel = gpos[2] - z_0; /* relative position for BCs */ for (j=0; j<ny; j++) { if (gpos[2] <= z_low) { /* cytoplasmic */ val = A*exp(xkappa*z_rel) + V; gxcf[IJKx(j,k,0)] += val; /* assign low side BC */ gxcf[IJKx(j,k,1)] += val; /* assign high side BC */ } else if (gpos[2] > z_low && gpos[2] <= z_high) { /* in membrane */ val = B + C*z_rel; gxcf[IJKx(j,k,0)] += val; /* assign low side BC */ gxcf[IJKx(j,k,1)] += val; /* assign high side BC */ } else if (gpos[2] > z_high) { /* extracellular */ val = D*exp(-xkappa*z_rel); gxcf[IJKx(j,k,0)] += val; /* assign low side BC */ gxcf[IJKx(j,k,1)] += val; /* assign high side BC */ } } } /* the "j" boundaries (dirichlet) */ for (k=0; k<nz; k++) { gpos[2] = zf[k]; z_rel = gpos[2] - z_0; for (i=0; i<nx; i++) { if (gpos[2] <= z_low) { /* cytoplasmic */ val = A*exp(xkappa*z_rel) + V; gycf[IJKy(i,k,0)] += val; /* assign low side BC */ gycf[IJKy(i,k,1)] += val; /* assign high side BC */ //printf("%f \n",val); } else if (gpos[2] > z_low && gpos[2] <= z_high) { /* in membrane */ val = B + C*z_rel; gycf[IJKy(i,k,0)] += val; /* assign low side BC */ gycf[IJKy(i,k,1)] += val; /* assign high side BC */ //printf("%f \n",val); } else if (gpos[2] > z_high) { /* extracellular */ val = D*exp(-xkappa*z_rel); gycf[IJKy(i,k,0)] += val; /* assign low side BC */ gycf[IJKy(i,k,1)] += val; /* assign high side BC */ //printf("%f \n",val); } } } /* the "k" boundaries (dirichlet) */ for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { /* first assign the bottom boundary */ gpos[2] = zf[0]; z_rel = gpos[2] - z_0; if (gpos[2] <= z_low) { /* cytoplasmic */ val = A*exp(xkappa*z_rel) + V; gzcf[IJKz(i,j,0)] += val; /* assign low side BC */ //printf("%f \n",val); } else if (gpos[2] > z_low && gpos[2] <= z_high) { /* in membrane */ val = B + C*z_rel; gzcf[IJKz(i,j,0)] += val; /* assign low side BC */ } else if (gpos[2] > z_high) { /* extracellular */ val = D*exp(-xkappa*z_rel); gzcf[IJKz(i,j,0)] += val; /* assign low side BC */ } /* now assign the top boundary */ gpos[2] = zf[nz-1]; z_rel = gpos[2] - z_0; if (gpos[2] <= z_low) { /* cytoplasmic */ val = A*exp(xkappa*z_rel) + V; gzcf[IJKz(i,j,1)] += val; /* assign high side BC */ } else if (gpos[2] > z_low && gpos[2] <= z_high) { /* in membrane */ val = B + C*z_rel; gzcf[IJKz(i,j,1)] += val; /* assign high side BC */ } else if (gpos[2] > z_high) { /* extracellular */ val = D*exp(-xkappa*z_rel); gzcf[IJKz(i,j,1)] += val; /* assign high side BC */ //printf("%f \n",val); } } } } VPRIVATE void bcfl_map(Vpmg *thee){ Vpbe *pbe; double position[3], pot, hx, hy, hzed; int i, j, k, nx, ny, nz, rc; VASSERT(thee != VNULL); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Reset the potential array */ for (i=0; i<(nx*ny*nz); i++) thee->pot[i] = 0.0; /* Fill in the source term (atomic potentials) */ Vnm_print(0, "Vpmg_fillco: filling in source term.\n"); for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = thee->xf[i]; position[1] = thee->yf[j]; position[2] = thee->zf[k]; rc = Vgrid_value(thee->potMap, position, &pot); if (!rc) { Vnm_print(2, "fillcoChargeMap: Error -- fell off of potential map at (%g, %g, %g)!\n", position[0], position[1], position[2]); VASSERT(0); } thee->pot[IJK(i,j,k)] = pot; } } } } #if defined(WITH_TINKER) VPRIVATE void bcfl_mdh_tinker(Vpmg *thee){ int i,j,k,iatom; int nx, ny, nz; double val, *apos, gpos[3], tensor[9]; double *dipole, *quadrupole; double size, charge, xkappa, eps_w, eps_p, T, pre1, dist; double ux,uy,uz,xr,yr,zr; double qxx,qxy,qxz,qyx,qyy,qyz,qzx,qzy,qzz; double *xf, *yf, *zf; double *gxcf, *gycf, *gzcf; Vpbe *pbe; Vatom *atom; Valist *alist; pbe = thee->pbe; alist = thee->pbe->alist; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; xf = thee->xf; yf = thee->yf; zf = thee->zf; gxcf = thee->gxcf; gycf = thee->gycf; gzcf = thee->gzcf; /* For each "atom" (only one for bcfl=1), we use the following formula to * calculate the boundary conditions: * g(x) = \frac{q e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} * * 1/d * where d = ||x - x_0|| (in m) and a is the size of the atom (in m). * We only need to evaluate some of these prefactors once: * pre1 = \frac{e_c}{4*\pi*\eps_0*\eps_w*k_b*T} * which gives the potential as * g(x) = pre1 * q/d * \frac{exp(-xkappa*(d - a))}{1+xkappa*a} */ eps_w = Vpbe_getSolventDiel(pbe); /* Dimensionless */ eps_p = Vpbe_getSoluteDiel(pbe); /* Dimensionless */ T = Vpbe_getTemperature(pbe); /* K */ pre1 = (Vunit_ec*Vunit_ec)/(4*VPI*Vunit_eps0*Vunit_kb*T); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ pre1 = pre1*(1.0e10); /* Finally, if we convert keep xkappa in A^{-1} and scale pre1 by * m/A, then we will only need to deal with distances and sizes in * Angstroms rather than meters. */ xkappa = Vpbe_getXkappa(pbe); /* A^{-1} */ for(k=0;k<nz;k++){ gpos[2] = zf[k]; for(j=0;j<ny;j++){ gpos[1] = yf[j]; for(i=0;i<nx;i++){ gpos[0] = xf[i]; if(gridPointIsValid(i, j, k, nx, ny, nz)){ val = 0.0; for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); size = Vatom_getRadius(atom); charge = 0.0; dipole = VNULL; quadrupole = VNULL; if (thee->chargeSrc == VCM_PERMANENT) { charge = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); quadrupole = Vatom_getQuadrupole(atom); } else if (thee->chargeSrc == VCM_INDUCED) { dipole = Vatom_getInducedDipole(atom); } else { dipole = Vatom_getNLInducedDipole(atom); } ux = dipole[0]; uy = dipole[1]; uz = dipole[2]; if (quadrupole != VNULL) { /* The factor of 1/3 results from using a traceless quadrupole definition. See, for example, "The Theory of Intermolecular Forces" by A.J. Stone, Chapter 3. */ qxx = quadrupole[0] / 3.0; qxy = quadrupole[1] / 3.0; qxz = quadrupole[2] / 3.0; qyx = quadrupole[3] / 3.0; qyy = quadrupole[4] / 3.0; qyz = quadrupole[5] / 3.0; qzx = quadrupole[6] / 3.0; qzy = quadrupole[7] / 3.0; qzz = quadrupole[8] / 3.0; } else { qxx = 0.0; qxy = 0.0; qxz = 0.0; qyx = 0.0; qyy = 0.0; qyz = 0.0; qzx = 0.0; qzy = 0.0; qzz = 0.0; } xr = gpos[0] - apos[0]; yr = gpos[1] - apos[1]; zr = gpos[2] - apos[2]; dist = VSQRT(VSQR(xr) + VSQR(yr) + VSQR(zr)); multipolebc(dist, xkappa, eps_p, eps_w, size, tensor); val += pre1*charge*tensor[0]; val -= pre1*ux*xr*tensor[1]; val -= pre1*uy*yr*tensor[1]; val -= pre1*uz*zr*tensor[1]; val += pre1*qxx*xr*xr*tensor[2]; val += pre1*qyy*yr*yr*tensor[2]; val += pre1*qzz*zr*zr*tensor[2]; val += pre1*2.0*qxy*xr*yr*tensor[2]; val += pre1*2.0*qxz*xr*zr*tensor[2]; val += pre1*2.0*qyz*yr*zr*tensor[2]; } if(i==0){ gxcf[IJKx(j,k,0)] = val; } if(i==nx-1){ gxcf[IJKx(j,k,1)] = val; } if(j==0){ gycf[IJKy(i,k,0)] = val; } if(j==ny-1){ gycf[IJKy(i,k,1)] = val; } if(k==0){ gzcf[IJKz(i,j,0)] = val; } if(k==nz-1){ gzcf[IJKz(i,j,1)] = val; } } /* End grid point is valid */ } /* End i loop */ } /* End j loop */ } /* End k loop */ } #endif VPRIVATE void bcCalc(Vpmg *thee){ int i, j, k; int nx, ny, nz; double zmem, eps_m, Lmem, memv, eps_w, xkappa; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; /* Zero out the boundaries */ /* the "i" boundaries (dirichlet) */ for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { thee->gxcf[IJKx(j,k,0)] = 0.0; thee->gxcf[IJKx(j,k,1)] = 0.0; thee->gxcf[IJKx(j,k,2)] = 0.0; thee->gxcf[IJKx(j,k,3)] = 0.0; } } /* the "j" boundaries (dirichlet) */ for (k=0; k<nz; k++) { for (i=0; i<nx; i++) { thee->gycf[IJKy(i,k,0)] = 0.0; thee->gycf[IJKy(i,k,1)] = 0.0; thee->gycf[IJKy(i,k,2)] = 0.0; thee->gycf[IJKy(i,k,3)] = 0.0; } } /* the "k" boundaries (dirichlet) */ for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { thee->gzcf[IJKz(i,j,0)] = 0.0; thee->gzcf[IJKz(i,j,1)] = 0.0; thee->gzcf[IJKz(i,j,2)] = 0.0; thee->gzcf[IJKz(i,j,3)] = 0.0; } } switch (thee->pmgp->bcfl) { /* If we have zero boundary conditions, we're done */ case BCFL_ZERO: return; case BCFL_SDH: bcfl_sdh(thee); break; case BCFL_MDH: #if defined(WITH_TINKER) bcfl_mdh_tinker(thee); #else #ifdef DEBUG_MAC_OSX_OCL #include "mach_chud.h" uint64_t mbeg = mach_absolute_time(); /* * If OpenCL is available we use it, otherwise fall back to * normal route (CPU multithreaded w/ OpenMP) */ if (kOpenCLAvailable == 1) bcflnewOpenCL(thee); else bcflnew(thee); mets_(&mbeg, "MDH"); #else /* bcfl_mdh(thee); */ bcflnew(thee); #endif /* DEBUG_MAC_OSX_OCL */ #endif /* WITH_TINKER */ break; case BCFL_MEM: zmem = Vpbe_getzmem(thee->pbe); Lmem = Vpbe_getLmem(thee->pbe); eps_m = Vpbe_getmembraneDiel(thee->pbe); memv = Vpbe_getmemv(thee->pbe); eps_w = Vpbe_getSolventDiel(thee->pbe); xkappa = Vpbe_getXkappa(thee->pbe); bcfl_mem(zmem, Lmem, eps_m, eps_w, memv, xkappa, thee->gxcf, thee->gycf, thee->gzcf, thee->xf, thee->yf, thee->zf, nx, ny, nz); break; case BCFL_UNUSED: Vnm_print(2, "bcCalc: Invalid bcfl (%d)!\n", thee->pmgp->bcfl); VASSERT(0); break; case BCFL_FOCUS: Vnm_print(2, "VPMG::bcCalc -- not appropriate for focusing!\n"); VASSERT(0); break; case BCFL_MAP: bcfl_map(thee); focusFillBound(thee,VNULL); break; default: Vnm_print(2, "VPMG::bcCalc -- invalid boundary condition \ flag (%d)!\n", thee->pmgp->bcfl); VASSERT(0); break; } } VPRIVATE void fillcoCoefMap(Vpmg *thee) { Vpbe *pbe; double ionstr, position[3], tkappa, eps, pot, hx, hy, hzed; int i, j, k, nx, ny, nz; double kappamax; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; ionstr = Vpbe_getBulkIonicStrength(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; if ((!thee->useDielXMap) || (!thee->useDielYMap) || (!thee->useDielZMap) || ((!thee->useKappaMap) && (ionstr>VPMGSMALL))) { Vnm_print(2, "fillcoCoefMap: You need to use all coefficient maps!\n"); VASSERT(0); } /* Scale the kappa map to values between 0 and 1 Thus get the maximum value in the map - this is theoretically unnecessary, but a good check.*/ kappamax = -1.00; for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { if (ionstr > VPMGSMALL) { position[0] = thee->xf[i]; position[1] = thee->yf[j]; position[2] = thee->zf[k]; if (!Vgrid_value(thee->kappaMap, position, &tkappa)) { Vnm_print(2, "Vpmg_fillco: Off kappaMap at:\n"); Vnm_print(2, "Vpmg_fillco: (x,y,z) = (%g,%g %g)\n", position[0], position[1], position[2]); VASSERT(0); } if (tkappa > kappamax) { kappamax = tkappa; } if (tkappa < 0.0){ Vnm_print(2, "Vpmg_fillcoCoefMap: Kappa map less than 0\n"); Vnm_print(2, "Vpmg_fillcoCoefMap: at (x,y,z) = (%g,%g %g)\n", position[0], position[1], position[2]); VASSERT(0); } } } } } if (kappamax > 1.0){ Vnm_print(2, "Vpmg_fillcoCoefMap: Maximum Kappa value\n"); Vnm_print(2, "%g is greater than 1 - will scale appropriately!\n", kappamax); } else { kappamax = 1.0; } for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { if (ionstr > VPMGSMALL) { position[0] = thee->xf[i]; position[1] = thee->yf[j]; position[2] = thee->zf[k]; if (!Vgrid_value(thee->kappaMap, position, &tkappa)) { Vnm_print(2, "Vpmg_fillco: Off kappaMap at:\n"); Vnm_print(2, "Vpmg_fillco: (x,y,z) = (%g,%g %g)\n", position[0], position[1], position[2]); VASSERT(0); } if (tkappa < VPMGSMALL) tkappa = 0.0; thee->kappa[IJK(i,j,k)] = (tkappa / kappamax); } position[0] = thee->xf[i] + 0.5*hx; position[1] = thee->yf[j]; position[2] = thee->zf[k]; if (!Vgrid_value(thee->dielXMap, position, &eps)) { Vnm_print(2, "Vpmg_fillco: Off dielXMap at:\n"); Vnm_print(2, "Vpmg_fillco: (x,y,z) = (%g,%g %g)\n", position[0], position[1], position[2]); VASSERT(0); } thee->epsx[IJK(i,j,k)] = eps; position[0] = thee->xf[i]; position[1] = thee->yf[j] + 0.5*hy; position[2] = thee->zf[k]; if (!Vgrid_value(thee->dielYMap, position, &eps)) { Vnm_print(2, "Vpmg_fillco: Off dielYMap at:\n"); Vnm_print(2, "Vpmg_fillco: (x,y,z) = (%g,%g %g)\n", position[0], position[1], position[2]); VASSERT(0); } thee->epsy[IJK(i,j,k)] = eps; position[0] = thee->xf[i]; position[1] = thee->yf[j]; position[2] = thee->zf[k] + 0.5*hzed; if (!Vgrid_value(thee->dielZMap, position, &eps)) { Vnm_print(2, "Vpmg_fillco: Off dielZMap at:\n"); Vnm_print(2, "Vpmg_fillco: (x,y,z) = (%g,%g %g)\n", position[0], position[1], position[2]); VASSERT(0); } thee->epsz[IJK(i,j,k)] = eps; } } } } VPRIVATE void fillcoCoefMol(Vpmg *thee) { if (thee->useDielXMap || thee->useDielYMap || thee->useDielZMap || thee->useKappaMap) { fillcoCoefMap(thee); } else { fillcoCoefMolDiel(thee); fillcoCoefMolIon(thee); } } VPRIVATE void fillcoCoefMolIon(Vpmg *thee) { Vacc *acc; Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax, ionmask, ionstr; double xlen, ylen, zlen, irad; double hx, hy, hzed, *apos, arad; int i, nx, ny, nz, iatom; Vsurf_Meth surfMeth; VASSERT(thee != VNULL); surfMeth = thee->surfMeth; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); ionstr = Vpbe_getBulkIonicStrength(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* This is a floating point parameter related to the non-zero nature of the * bulk ionic strength. If the ionic strength is greater than zero; this * parameter is set to 1.0 and later scaled by the appropriate pre-factors. * Otherwise, this parameter is set to 0.0 */ if (ionstr > VPMGSMALL) ionmask = 1.0; else ionmask = 0.0; /* Reset the kappa array, marking everything accessible */ for (i=0; i<(nx*ny*nz); i++) thee->kappa[i] = ionmask; if (ionstr < VPMGSMALL) return; /* Loop through the atoms and set kappa = 0.0 (inaccessible) if a point * is inside the ion-inflated van der Waals radii */ for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); if (arad > VSMALL) { /* Make sure we're on the grid */ if ((apos[0]<(xmin-irad-arad)) || (apos[0]>(xmax+irad+arad)) || \ (apos[1]<(ymin-irad-arad)) || (apos[1]>(ymax+irad+arad)) || \ (apos[2]<(zmin-irad-arad)) || (apos[2]>(zmax+irad+arad))) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* if we're on the mesh */ /* Mark ions */ markSphere((irad+arad), apos, nx, ny, nz, hx, hy, hzed, xmin, ymin, zmin, thee->kappa, 0.0); } /* endif (on the mesh) */ } } /* endfor (over all atoms) */ } VPRIVATE void fillcoCoefMolDiel(Vpmg *thee) { /* Always call NoSmooth to fill the epsilon arrays */ fillcoCoefMolDielNoSmooth(thee); /* Call the smoothing algorithm as needed */ if (thee->surfMeth == VSM_MOLSMOOTH) { fillcoCoefMolDielSmooth(thee); } } VPRIVATE void fillcoCoefMolDielNoSmooth(Vpmg *thee) { Vacc *acc; VaccSurf *asurf; Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax; double xlen, ylen, zlen, position[3]; double srad, epsw, epsp, deps, area; double hx, hy, hzed, *apos, arad; int i, nx, ny, nz, ntot, iatom, ipt; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; alist = pbe->alist; srad = Vpbe_getSolventRadius(pbe); epsw = Vpbe_getSolventDiel(pbe); epsp = Vpbe_getSoluteDiel(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Reset the arrays */ ntot = nx*ny*nz; for (i=0; i<ntot; i++) { thee->epsx[i] = epsw; thee->epsy[i] = epsw; thee->epsz[i] = epsw; } /* Loop through the atoms and set a{123}cf = 0.0 (inaccessible) * if a point is inside the solvent-inflated van der Waals radii */ #pragma omp parallel for default(shared) private(iatom,atom,apos,arad) for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f,\ %4.3f) is off the mesh (ignoring):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* if we're on the mesh */ if (arad > VSMALL) { /* Mark x-shifted dielectric */ markSphere((arad+srad), apos, nx, ny, nz, hx, hy, hzed, (xmin+0.5*hx), ymin, zmin, thee->epsx, epsp); /* Mark y-shifted dielectric */ markSphere((arad+srad), apos, nx, ny, nz, hx, hy, hzed, xmin, (ymin+0.5*hy), zmin, thee->epsy, epsp); /* Mark z-shifted dielectric */ markSphere((arad+srad), apos, nx, ny, nz, hx, hy, hzed, xmin, ymin, (zmin+0.5*hzed), thee->epsz, epsp); } } /* endif (on the mesh) */ } /* endfor (over all atoms) */ area = Vacc_SASA(acc, srad); /* We only need to do the next step for non-zero solvent radii */ if (srad > VSMALL) { /* Now loop over the solvent accessible surface points */ #pragma omp parallel for default(shared) private(iatom,atom,area,asurf,ipt,position) for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); area = Vacc_atomSASA(acc, srad, atom); if (area > 0.0 ) { asurf = Vacc_atomSASPoints(acc, srad, atom); /* Use each point on the SAS to reset the solvent accessibility */ /* TODO: Make sure we're not still wasting time here. */ for (ipt=0; ipt<(asurf->npts); ipt++) { position[0] = asurf->xpts[ipt]; position[1] = asurf->ypts[ipt]; position[2] = asurf->zpts[ipt]; /* Mark x-shifted dielectric */ markSphere(srad, position, nx, ny, nz, hx, hy, hzed, (xmin+0.5*hx), ymin, zmin, thee->epsx, epsw); /* Mark y-shifted dielectric */ markSphere(srad, position, nx, ny, nz, hx, hy, hzed, xmin, (ymin+0.5*hy), zmin, thee->epsy, epsw); /* Mark z-shifted dielectric */ markSphere(srad, position, nx, ny, nz, hx, hy, hzed, xmin, ymin, (zmin+0.5*hzed), thee->epsz, epsw); } } } } } VPRIVATE void fillcoCoefMolDielSmooth(Vpmg *thee) { /* This function smoothes using a 9 point method based on Bruccoleri, et al. J Comput Chem 18 268-276 (1997). The nine points used are the shifted grid point and the 8 points that are 1/sqrt(2) grid spacings away. The harmonic mean of the 9 points is then used to find the overall dielectric value for the point in question. The use of this function assumes that the non-smoothed values were placed in the dielectric arrays by the fillcoCoefMolDielNoSmooth function.*/ Vpbe *pbe; double frac, epsw; int i, j, k, nx, ny, nz, numpts; /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; pbe = thee->pbe; epsw = Vpbe_getSolventDiel(pbe); /* Copy the existing diel arrays to work arrays */ for (i=0; i<(nx*ny*nz); i++) { thee->a1cf[i] = thee->epsx[i]; thee->a2cf[i] = thee->epsy[i]; thee->a3cf[i] = thee->epsz[i]; thee->epsx[i] = epsw; thee->epsy[i] = epsw; thee->epsz[i] = epsw; } /* Smooth the dielectric values */ for (i=0; i<nx; i++) { for (j=0; j<ny; j++) { for (k=0; k<nz; k++) { /* Get the 8 points that are 1/sqrt(2) grid spacings away */ /* Points for the X-shifted array */ frac = 1.0/thee->a1cf[IJK(i,j,k)]; frac += 1.0/thee->a2cf[IJK(i,j,k)]; frac += 1.0/thee->a3cf[IJK(i,j,k)]; numpts = 3; if (j > 0) { frac += 1.0/thee->a2cf[IJK(i,j-1,k)]; numpts += 1; } if (k > 0) { frac += 1.0/thee->a3cf[IJK(i,j,k-1)]; numpts += 1; } if (i < (nx-1)){ frac += 1.0/thee->a2cf[IJK(i+1,j,k)]; frac += 1.0/thee->a3cf[IJK(i+1,j,k)]; numpts += 2; if (j > 0) { frac += 1.0/thee->a2cf[IJK(i+1,j-1,k)]; numpts += 1; } if (k > 0) { frac += 1.0/thee->a3cf[IJK(i+1,j,k-1)]; numpts += 1; } } thee->epsx[IJK(i,j,k)] = numpts/frac; /* Points for the Y-shifted array */ frac = 1.0/thee->a2cf[IJK(i,j,k)]; frac += 1.0/thee->a1cf[IJK(i,j,k)]; frac += 1.0/thee->a3cf[IJK(i,j,k)]; numpts = 3; if (i > 0) { frac += 1.0/thee->a1cf[IJK(i-1,j,k)]; numpts += 1; } if (k > 0) { frac += 1.0/thee->a3cf[IJK(i,j,k-1)]; numpts += 1; } if (j < (ny-1)){ frac += 1.0/thee->a1cf[IJK(i,j+1,k)]; frac += 1.0/thee->a3cf[IJK(i,j+1,k)]; numpts += 2; if (i > 0) { frac += 1.0/thee->a1cf[IJK(i-1,j+1,k)]; numpts += 1; } if (k > 0) { frac += 1.0/thee->a3cf[IJK(i,j+1,k-1)]; numpts += 1; } } thee->epsy[IJK(i,j,k)] = numpts/frac; /* Points for the Z-shifted array */ frac = 1.0/thee->a3cf[IJK(i,j,k)]; frac += 1.0/thee->a1cf[IJK(i,j,k)]; frac += 1.0/thee->a2cf[IJK(i,j,k)]; numpts = 3; if (i > 0) { frac += 1.0/thee->a1cf[IJK(i-1,j,k)]; numpts += 1; } if (j > 0) { frac += 1.0/thee->a2cf[IJK(i,j-1,k)]; numpts += 1; } if (k < (nz-1)){ frac += 1.0/thee->a1cf[IJK(i,j,k+1)]; frac += 1.0/thee->a2cf[IJK(i,j,k+1)]; numpts += 2; if (i > 0) { frac += 1.0/thee->a1cf[IJK(i-1,j,k+1)]; numpts += 1; } if (j > 0) { frac += 1.0/thee->a2cf[IJK(i,j-1,k+1)]; numpts += 1; } } thee->epsz[IJK(i,j,k)] = numpts/frac; } } } } VPRIVATE void fillcoCoefSpline(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax, ionmask, ionstr, dist2; double xlen, ylen, zlen, position[3], itot, stot, ictot, ictot2, sctot; double irad, dx, dy, dz, epsw, epsp, w2i; double hx, hy, hzed, *apos, arad, sctot2; double dx2, dy2, dz2, stot2, itot2, rtot, rtot2, splineWin, w3i; double dist, value, sm, sm2; int i, j, k, nx, ny, nz, iatom; int imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); splineWin = thee->splineWin; w2i = 1.0/(splineWin*splineWin); w3i = 1.0/(splineWin*splineWin*splineWin); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); ionstr = Vpbe_getBulkIonicStrength(pbe); epsw = Vpbe_getSolventDiel(pbe); epsp = Vpbe_getSoluteDiel(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* This is a floating point parameter related to the non-zero nature of the * bulk ionic strength. If the ionic strength is greater than zero; this * parameter is set to 1.0 and later scaled by the appropriate pre-factors. * Otherwise, this parameter is set to 0.0 */ if (ionstr > VPMGSMALL) ionmask = 1.0; else ionmask = 0.0; /* Reset the kappa, epsx, epsy, and epsz arrays */ for (i=0; i<(nx*ny*nz); i++) { thee->kappa[i] = 1.0; thee->epsx[i] = 1.0; thee->epsy[i] = 1.0; thee->epsz[i] = 1.0; } /* Loop through the atoms and do assign the dielectric */ for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f,\ %4.3f) is off the mesh (ignoring):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else if (arad > VPMGSMALL ) { /* if we're on the mesh */ /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* MARK ION ACCESSIBILITY AND DIELECTRIC VALUES FOR LATER * ASSIGNMENT (Steps #1-3) */ itot = irad + arad + splineWin; itot2 = VSQR(itot); ictot = VMAX2(0, (irad + arad - splineWin)); ictot2 = VSQR(ictot); stot = arad + splineWin; stot2 = VSQR(stot); sctot = VMAX2(0, (arad - splineWin)); sctot2 = VSQR(sctot); /* We'll search over grid points which are in the greater of * these two radii */ rtot = VMAX2(itot, stot); rtot2 = VMAX2(itot2, stot2); dx = rtot + 0.5*hx; dy = rtot + 0.5*hy; dz = rtot + 0.5*hzed; imin = VMAX2(0,(int)floor((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)ceil((position[0] + dx)/hx)); jmin = VMAX2(0,(int)floor((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)ceil((position[1] + dy)/hy)); kmin = VMAX2(0,(int)floor((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)ceil((position[2] + dz)/hzed)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(position[2] - k*hzed); /* ASSIGN CCF */ if (thee->kappa[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2 + dy2 + dx2; if (dist2 >= itot2) { ; } if (dist2 <= ictot2) { thee->kappa[IJK(i,j,k)] = 0.0; } if ((dist2 < itot2) && (dist2 > ictot2)) { dist = VSQRT(dist2); sm = dist - (arad + irad) + splineWin; sm2 = VSQR(sm); value = 0.75*sm2*w2i - 0.25*sm*sm2*w3i; thee->kappa[IJK(i,j,k)] *= value; } } /* ASSIGN A1CF */ if (thee->epsx[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2+dy2+VSQR(position[0]-(i+0.5)*hx); if (dist2 >= stot2) { thee->epsx[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsx[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist - arad + splineWin; sm2 = VSQR(sm); value = 0.75*sm2*w2i - 0.25*sm*sm2*w3i; thee->epsx[IJK(i,j,k)] *= value; } } /* ASSIGN A2CF */ if (thee->epsy[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2+dx2+VSQR(position[1]-(j+0.5)*hy); if (dist2 >= stot2) { thee->epsy[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsy[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist - arad + splineWin; sm2 = VSQR(sm); value = 0.75*sm2*w2i - 0.25*sm*sm2*w3i; thee->epsy[IJK(i,j,k)] *= value; } } /* ASSIGN A3CF */ if (thee->epsz[IJK(i,j,k)] > VPMGSMALL) { dist2 = dy2+dx2+VSQR(position[2]-(k+0.5)*hzed); if (dist2 >= stot2) { thee->epsz[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsz[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist - arad + splineWin; sm2 = VSQR(sm); value = 0.75*sm2*w2i - 0.25*sm*sm2*w3i; thee->epsz[IJK(i,j,k)] *= value; } } } /* k loop */ } /* j loop */ } /* i loop */ } /* endif (on the mesh) */ } /* endfor (over all atoms) */ Vnm_print(0, "Vpmg_fillco: filling coefficient arrays\n"); /* Interpret markings and fill the coefficient arrays */ for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { thee->kappa[IJK(i,j,k)] = ionmask*thee->kappa[IJK(i,j,k)]; thee->epsx[IJK(i,j,k)] = (epsw-epsp)*thee->epsx[IJK(i,j,k)] + epsp; thee->epsy[IJK(i,j,k)] = (epsw-epsp)*thee->epsy[IJK(i,j,k)] + epsp; thee->epsz[IJK(i,j,k)] = (epsw-epsp)*thee->epsz[IJK(i,j,k)] + epsp; } /* i loop */ } /* j loop */ } /* k loop */ } VPRIVATE void fillcoCoef(Vpmg *thee) { VASSERT(thee != VNULL); if (thee->useDielXMap || thee->useDielYMap || thee->useDielZMap || thee->useKappaMap) { fillcoCoefMap(thee); return; } switch(thee->surfMeth) { case VSM_MOL: Vnm_print(0, "fillcoCoef: Calling fillcoCoefMol...\n"); fillcoCoefMol(thee); break; case VSM_MOLSMOOTH: Vnm_print(0, "fillcoCoef: Calling fillcoCoefMol...\n"); fillcoCoefMol(thee); break; case VSM_SPLINE: Vnm_print(0, "fillcoCoef: Calling fillcoCoefSpline...\n"); fillcoCoefSpline(thee); break; case VSM_SPLINE3: Vnm_print(0, "fillcoCoef: Calling fillcoCoefSpline3...\n"); fillcoCoefSpline3(thee); break; case VSM_SPLINE4: Vnm_print(0, "fillcoCoef: Calling fillcoCoefSpline4...\n"); fillcoCoefSpline4(thee); break; default: Vnm_print(2, "fillcoCoef: Invalid surfMeth (%d)!\n", thee->surfMeth); VASSERT(0); break; } } VPRIVATE Vrc_Codes fillcoCharge(Vpmg *thee) { Vrc_Codes rc; VASSERT(thee != VNULL); if (thee->useChargeMap) { return fillcoChargeMap(thee); } switch(thee->chargeMeth) { case VCM_TRIL: Vnm_print(0, "fillcoCharge: Calling fillcoChargeSpline1...\n"); fillcoChargeSpline1(thee); break; case VCM_BSPL2: Vnm_print(0, "fillcoCharge: Calling fillcoChargeSpline2...\n"); fillcoChargeSpline2(thee); break; case VCM_BSPL4: switch (thee->chargeSrc) { case VCM_CHARGE: Vnm_print(0, "fillcoCharge: Calling fillcoPermanentMultipole...\n"); fillcoPermanentMultipole(thee); break; #if defined(WITH_TINKER) case VCM_PERMANENT: Vnm_print(0, "fillcoCharge: Calling fillcoPermanentMultipole...\n"); fillcoPermanentMultipole(thee); break; case VCM_INDUCED: Vnm_print(0, "fillcoCharge: Calling fillcoInducedDipole...\n"); fillcoInducedDipole(thee); break; case VCM_NLINDUCED: Vnm_print(0, "fillcoCharge: Calling fillcoNLInducedDipole...\n"); fillcoNLInducedDipole(thee); break; #endif /* if defined(WITH_TINKER) */ default: Vnm_print(2, "fillcoCharge: Invalid chargeSource (%d)!\n", thee->chargeSrc); return VRC_FAILURE; break; } break; default: Vnm_print(2, "fillcoCharge: Invalid chargeMeth (%d)!\n", thee->chargeMeth); return VRC_FAILURE; break; } return VRC_SUCCESS; } VPRIVATE Vrc_Codes fillcoChargeMap(Vpmg *thee) { Vpbe *pbe; double position[3], charge, zmagic, hx, hy, hzed; int i, j, k, nx, ny, nz, rc; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Reset the charge array */ for (i=0; i<(nx*ny*nz); i++) thee->charge[i] = 0.0; /* Fill in the source term (atomic charges) */ Vnm_print(0, "Vpmg_fillco: filling in source term.\n"); for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { position[0] = thee->xf[i]; position[1] = thee->yf[j]; position[2] = thee->zf[k]; rc = Vgrid_value(thee->chargeMap, position, &charge); if (!rc) { Vnm_print(2, "fillcoChargeMap: Error -- fell off of charge map at (%g, %g, %g)!\n", position[0], position[1], position[2]); return VRC_FAILURE; } /* Scale the charge to internal units */ charge = charge*zmagic; thee->charge[IJK(i,j,k)] = charge; } } } return VRC_SUCCESS; } VPRIVATE void fillcoChargeSpline1(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax; double xlen, ylen, zlen, position[3], ifloat, jfloat, kfloat; double charge, dx, dy, dz, zmagic, hx, hy, hzed, *apos; int i, nx, ny, nz, iatom, ihi, ilo, jhi, jlo, khi, klo; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Reset the charge array */ for (i=0; i<(nx*ny*nz); i++) thee->charge[i] = 0.0; /* Fill in the source term (atomic charges) */ Vnm_print(0, "Vpmg_fillco: filling in source term.\n"); for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); charge = Vatom_getCharge(atom); /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f, \ %4.3f) is off the mesh (ignoring):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Scale the charge to be a delta function */ charge = charge*zmagic/(hx*hy*hzed); /* Figure out which vertices we're next to */ ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ihi = (int)ceil(ifloat); ilo = (int)floor(ifloat); jhi = (int)ceil(jfloat); jlo = (int)floor(jfloat); khi = (int)ceil(kfloat); klo = (int)floor(kfloat); /* Now assign fractions of the charge to the nearby verts */ dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); thee->charge[IJK(ihi,jhi,khi)] += (dx*dy*dz*charge); thee->charge[IJK(ihi,jlo,khi)] += (dx*(1.0-dy)*dz*charge); thee->charge[IJK(ihi,jhi,klo)] += (dx*dy*(1.0-dz)*charge); thee->charge[IJK(ihi,jlo,klo)] += (dx*(1.0-dy)*(1.0-dz)*charge); thee->charge[IJK(ilo,jhi,khi)] += ((1.0-dx)*dy*dz *charge); thee->charge[IJK(ilo,jlo,khi)] += ((1.0-dx)*(1.0-dy)*dz *charge); thee->charge[IJK(ilo,jhi,klo)] += ((1.0-dx)*dy*(1.0-dz)*charge); thee->charge[IJK(ilo,jlo,klo)] += ((1.0-dx)*(1.0-dy)*(1.0-dz)*charge); } /* endif (on the mesh) */ } /* endfor (each atom) */ } VPRIVATE double bspline2(double x) { double m2m, m2, m3; if ((x >= 0.0) && (x <= 2.0)) m2m = 1.0 - VABS(x - 1.0); else m2m = 0.0; if ((x >= 1.0) && (x <= 3.0)) m2 = 1.0 - VABS(x - 2.0); else m2 = 0.0; if ((x >= 0.0) && (x <= 3.0)) m3 = 0.5*x*m2m + 0.5*(3.0-x)*m2; else m3 = 0.0; return m3; } VPRIVATE double dbspline2(double x) { double m2m, m2, dm3; if ((x >= 0.0) && (x <= 2.0)) m2m = 1.0 - VABS(x - 1.0); else m2m = 0.0; if ((x >= 1.0) && (x <= 3.0)) m2 = 1.0 - VABS(x - 2.0); else m2 = 0.0; dm3 = m2m - m2; return dm3; } VPRIVATE void fillcoChargeSpline2(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax, zmagic; double xlen, ylen, zlen, position[3], ifloat, jfloat, kfloat; double charge, hx, hy, hzed, *apos, mx, my, mz; int i, ii, jj, kk, nx, ny, nz, iatom; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Reset the charge array */ for (i=0; i<(nx*ny*nz); i++) thee->charge[i] = 0.0; /* Fill in the source term (atomic charges) */ Vnm_print(0, "Vpmg_fillco: filling in source term.\n"); for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); charge = Vatom_getCharge(atom); /* Make sure we're on the grid */ if ((apos[0]<=(xmin-hx)) || (apos[0]>=(xmax+hx)) || \ (apos[1]<=(ymin-hy)) || (apos[1]>=(ymax+hy)) || \ (apos[2]<=(zmin-hzed)) || (apos[2]>=(zmax+hzed))) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f, \ %4.3f) is off the mesh (for cubic splines!!) (ignoring this atom):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Scale the charge to be a delta function */ charge = charge*zmagic/(hx*hy*hzed); /* Figure out which vertices we're next to */ ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 1; im1 = (int)floor(ifloat); im2 = im1 - 1; jp1 = (int)ceil(jfloat); jp2 = jp1 + 1; jm1 = (int)floor(jfloat); jm2 = jm1 - 1; kp1 = (int)ceil(kfloat); kp2 = kp1 + 1; km1 = (int)floor(kfloat); km2 = km1 - 1; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); /* Now assign fractions of the charge to the nearby verts */ for (ii=im2; ii<=ip2; ii++) { mx = bspline2(VFCHI(ii,ifloat)); for (jj=jm2; jj<=jp2; jj++) { my = bspline2(VFCHI(jj,jfloat)); for (kk=km2; kk<=kp2; kk++) { mz = bspline2(VFCHI(kk,kfloat)); thee->charge[IJK(ii,jj,kk)] += (charge*mx*my*mz); } } } } /* endif (on the mesh) */ } /* endfor (each atom) */ } VPUBLIC int Vpmg_fillco(Vpmg *thee, Vsurf_Meth surfMeth, double splineWin, Vchrg_Meth chargeMeth, int useDielXMap, Vgrid *dielXMap, int useDielYMap, Vgrid *dielYMap, int useDielZMap, Vgrid *dielZMap, int useKappaMap, Vgrid *kappaMap, int usePotMap, Vgrid *potMap, int useChargeMap, Vgrid *chargeMap ) { Vpbe *pbe; double xmin, xmax, ymin, ymax, zmin, zmax, xlen, ylen, zlen, hx, hy, hzed, epsw, epsp, ionstr; int i, nx, ny, nz, islap; Vrc_Codes rc; if (thee == VNULL) { Vnm_print(2, "Vpmg_fillco: got NULL thee!\n"); return 0; } thee->surfMeth = surfMeth; thee->splineWin = splineWin; thee->chargeMeth = chargeMeth; thee->useDielXMap = useDielXMap; if (thee->useDielXMap) thee->dielXMap = dielXMap; thee->useDielYMap = useDielYMap; if (thee->useDielYMap) thee->dielYMap = dielYMap; thee->useDielZMap = useDielZMap; if (thee->useDielZMap) thee->dielZMap = dielZMap; thee->useKappaMap = useKappaMap; if (thee->useKappaMap) thee->kappaMap = kappaMap; thee->usePotMap = usePotMap; if (thee->usePotMap) thee->potMap = potMap; thee->useChargeMap = useChargeMap; if (thee->useChargeMap) thee->chargeMap = chargeMap; /* Get PBE info */ pbe = thee->pbe; ionstr = Vpbe_getBulkIonicStrength(pbe); epsw = Vpbe_getSolventDiel(pbe); epsp = Vpbe_getSoluteDiel(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); thee->pmgp->xmin = xmin; ymin = thee->pmgp->ycent - (ylen/2.0); thee->pmgp->ymin = ymin; zmin = thee->pmgp->zcent - (zlen/2.0); thee->pmgp->zmin = zmin; xmax = thee->pmgp->xcent + (xlen/2.0); thee->pmgp->xmax = xmax; ymax = thee->pmgp->ycent + (ylen/2.0); thee->pmgp->ymax = ymax; zmax = thee->pmgp->zcent + (zlen/2.0); thee->pmgp->zmax = zmax; thee->rparm[2] = xmin; thee->rparm[3] = xmax; thee->rparm[4] = ymin; thee->rparm[5] = ymax; thee->rparm[6] = zmin; thee->rparm[7] = zmax; /* This is a flag that gets set if the operator is a simple Laplacian; * i.e., in the case of a homogenous dielectric and zero ionic strength * The operator cannot be a simple Laplacian if maps are read in. */ if(thee->useDielXMap || thee->useDielYMap || thee->useDielZMap || thee->useKappaMap || thee->usePotMap){ islap = 0; }else if ( (ionstr < VPMGSMALL) && (VABS(epsp-epsw) < VPMGSMALL) ){ islap = 1; }else{ islap = 0; } /* Fill the mesh point coordinate arrays */ for (i=0; i<nx; i++) thee->xf[i] = xmin + i*hx; for (i=0; i<ny; i++) thee->yf[i] = ymin + i*hy; for (i=0; i<nz; i++) thee->zf[i] = zmin + i*hzed; /* Reset the tcf array */ for (i=0; i<(nx*ny*nz); i++) thee->tcf[i] = 0.0; /* Fill in the source term (atomic charges) */ Vnm_print(0, "Vpmg_fillco: filling in source term.\n"); rc = fillcoCharge(thee); switch(rc) { case VRC_SUCCESS: break; case VRC_WARNING: Vnm_print(2, "Vpmg_fillco: non-fatal errors while filling charge map!\n"); break; case VRC_FAILURE: Vnm_print(2, "Vpmg_fillco: fatal errors while filling charge map!\n"); return 0; break; } /* THE FOLLOWING NEEDS TO BE DONE IF WE'RE NOT USING A SIMPLE LAPLACIAN * OPERATOR */ if (!islap) { Vnm_print(0, "Vpmg_fillco: marking ion and solvent accessibility.\n"); fillcoCoef(thee); Vnm_print(0, "Vpmg_fillco: done filling coefficient arrays\n"); } else { /* else (!islap) ==> It's a Laplacian operator! */ for (i=0; i<(nx*ny*nz); i++) { thee->kappa[i] = 0.0; thee->epsx[i] = epsp; thee->epsy[i] = epsp; thee->epsz[i] = epsp; } } /* endif (!islap) */ /* Fill the boundary arrays (except when focusing, bcfl = 4) */ if (thee->pmgp->bcfl != BCFL_FOCUS) { Vnm_print(0, "Vpmg_fillco: filling boundary arrays\n"); bcCalc(thee); Vnm_print(0, "Vpmg_fillco: done filling boundary arrays\n"); } thee->filled = 1; return 1; } VPUBLIC int Vpmg_force(Vpmg *thee, double *force, int atomID, Vsurf_Meth srfm, Vchrg_Meth chgm) { int rc = 1; double qfF[3]; /* Charge-field force */ double dbF[3]; /* Dielectric boundary force */ double ibF[3]; /* Ion boundary force */ double npF[3]; /* Non-polar boundary force */ VASSERT(thee != VNULL); rc = rc && Vpmg_dbForce(thee, qfF, atomID, srfm); rc = rc && Vpmg_ibForce(thee, dbF, atomID, srfm); rc = rc && Vpmg_qfForce(thee, ibF, atomID, chgm); force[0] = qfF[0] + dbF[0] + ibF[0]; force[1] = qfF[1] + dbF[1] + ibF[1]; force[2] = qfF[2] + dbF[2] + ibF[2]; return rc; } VPUBLIC int Vpmg_ibForce(Vpmg *thee, double *force, int atomID, Vsurf_Meth srfm) { Valist *alist; Vacc *acc; Vpbe *pbe; Vatom *atom; double *apos, position[3], arad, irad, zkappa2, hx, hy, hzed; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2; double rtot, dx, dx2, dy, dy2, dz, dz2, gpos[3], tgrad[3], fmag; double izmagic; int i, j, k, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; /* For nonlinear forces */ int ichop, nchop, nion, m; double ionConc[MAXION], ionRadii[MAXION], ionQ[MAXION], ionstr; VASSERT(thee != VNULL); acc = thee->pbe->acc; atom = Valist_getAtom(thee->pbe->alist, atomID); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Check surface definition */ if ((srfm != VSM_SPLINE) && (srfm!=VSM_SPLINE3) && (srfm!=VSM_SPLINE4)) { Vnm_print(2, "Vpmg_ibForce: Forces *must* be calculated with \ spline-based surfaces!\n"); Vnm_print(2, "Vpmg_ibForce: Skipping ionic boundary force \ calculation!\n"); return 0; } /* If we aren't in the current position, then we're done */ if (atom->partID == 0) return 1; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); zkappa2 = Vpbe_getZkappa2(pbe); izmagic = 1.0/Vpbe_getZmagic(pbe); ionstr = Vpbe_getBulkIonicStrength(pbe); Vpbe_getIons(pbe, &nion, ionConc, ionRadii, ionQ); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; /* Sanity check: there is no force if there is zero ionic strength */ if (zkappa2 < VPMGSMALL) { #ifndef VAPBSQUIET Vnm_print(2, "Vpmg_ibForce: No force for zero ionic strength!\n"); #endif return 1; } /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_ibForce: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", atom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_ibForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_ibForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_ibForce: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (irad + arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot + 0.5*hx; imin = VMAX2(0,(int)ceil((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)floor((position[0] + dx)/hx)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); if (rtot2 > dx2) dy = VSQRT(rtot2 - dx2) + 0.5*hy; else dy = 0.5*hy; jmin = VMAX2(0,(int)ceil((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)floor((position[1] + dy)/hy)); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); if (rtot2 > (dx2+dy2)) dz = VSQRT(rtot2-dx2-dy2)+0.5*hzed; else dz = 0.5*hzed; kmin = VMAX2(0,(int)ceil((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)floor((position[2] + dz)/hzed)); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(k*hzed - position[2]); /* See if grid point is inside ivdw radius and set kappa * accordingly (do spline assignment here) */ if ((dz2 + dy2 + dx2) <= rtot2) { gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos,thee->splineWin, irad, atom, tgrad); if (thee->pmgp->nonlin) { /* Nonlinear forces */ fmag = 0.0; nchop = 0; for (m=0; m<nion; m++) { fmag += (thee->kappa[IJK(i,j,k)])*ionConc[m]*(Vcap_exp(-ionQ[m]*thee->u[IJK(i,j,k)], &ichop)-1.0)/ionstr; nchop += ichop; } /* if (nchop > 0) Vnm_print(2, "Vpmg_ibForece: Chopped EXP %d times!\n", nchop);*/ force[0] += (zkappa2*fmag*tgrad[0]); force[1] += (zkappa2*fmag*tgrad[1]); force[2] += (zkappa2*fmag*tgrad[2]); } else { /* Use of bulk factor (zkappa2) OK here becuase * LPBE force approximation */ /* NAB -- did we forget a kappa factor here??? */ fmag = VSQR(thee->u[IJK(i,j,k)])*(thee->kappa[IJK(i,j,k)]); force[0] += (zkappa2*fmag*tgrad[0]); force[1] += (zkappa2*fmag*tgrad[1]); force[2] += (zkappa2*fmag*tgrad[2]); } } } /* k loop */ } /* j loop */ } /* i loop */ } force[0] = force[0] * 0.5 * hx * hy * hzed * izmagic; force[1] = force[1] * 0.5 * hx * hy * hzed * izmagic; force[2] = force[2] * 0.5 * hx * hy * hzed * izmagic; return 1; } VPUBLIC int Vpmg_dbForce(Vpmg *thee, double *dbForce, int atomID, Vsurf_Meth srfm) { Vacc *acc; Vpbe *pbe; Vatom *atom; double *apos, position[3], arad, srad, hx, hy, hzed, izmagic, deps, depsi; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2, epsp; double rtot, dx, gpos[3], tgrad[3], dbFmag, epsw, kT; double *u, Hxijk, Hyijk, Hzijk, Hxim1jk, Hyijm1k, Hzijkm1; double dHxijk[3], dHyijk[3], dHzijk[3], dHxim1jk[3], dHyijm1k[3]; double dHzijkm1[3]; int i, j, k, l, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); if (!thee->filled) { Vnm_print(2, "Vpmg_dbForce: Need to callVpmg_fillco!\n"); return 0; } acc = thee->pbe->acc; atom = Valist_getAtom(thee->pbe->alist, atomID); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); srad = Vpbe_getSolventRadius(thee->pbe); /* Reset force */ dbForce[0] = 0.0; dbForce[1] = 0.0; dbForce[2] = 0.0; /* Check surface definition */ if ((srfm != VSM_SPLINE) && (srfm!=VSM_SPLINE3) && (srfm!=VSM_SPLINE4)) { Vnm_print(2, "Vpmg_dbForce: Forces *must* be calculated with \ spline-based surfaces!\n"); Vnm_print(2, "Vpmg_dbForce: Skipping dielectric/apolar boundary \ force calculation!\n"); return 0; } /* If we aren't in the current position, then we're done */ if (atom->partID == 0) return 1; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; epsp = Vpbe_getSoluteDiel(pbe); epsw = Vpbe_getSolventDiel(pbe); kT = Vpbe_getTemperature(pbe)*(1e-3)*Vunit_Na*Vunit_kb; izmagic = 1.0/Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = thee->u; /* Sanity check: there is no force if there is zero ionic strength */ if (VABS(epsp-epsw) < VPMGSMALL) { Vnm_print(0, "Vpmg_dbForce: No force for uniform dielectric!\n"); return 1; } deps = (epsw - epsp); depsi = 1.0/deps; rtot = (arad + thee->splineWin + srad); /* Make sure we're on the grid */ /* Grid checking modified by Matteo Rotter */ if ((apos[0]<=xmin + rtot) || (apos[0]>=xmax - rtot) || \ (apos[1]<=ymin + rtot) || (apos[1]>=ymax - rtot) || \ (apos[2]<=zmin + rtot) || (apos[2]>=zmax - rtot)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_dbForce: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", atomID, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_dbForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_dbForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_dbForce: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot2 = VSQR(rtot); dx = rtot/hx; imin = (int)floor((position[0]-rtot)/hx); if (imin < 1) { Vnm_print(2, "Vpmg_dbForce: Atom %d off grid!\n", atomID); return 0; } imax = (int)ceil((position[0]+rtot)/hx); if (imax > (nx-2)) { Vnm_print(2, "Vpmg_dbForce: Atom %d off grid!\n", atomID); return 0; } jmin = (int)floor((position[1]-rtot)/hy); if (jmin < 1) { Vnm_print(2, "Vpmg_dbForce: Atom %d off grid!\n", atomID); return 0; } jmax = (int)ceil((position[1]+rtot)/hy); if (jmax > (ny-2)) { Vnm_print(2, "Vpmg_dbForce: Atom %d off grid!\n", atomID); return 0; } kmin = (int)floor((position[2]-rtot)/hzed); if (kmin < 1) { Vnm_print(2, "Vpmg_dbForce: Atom %d off grid!\n", atomID); return 0; } kmax = (int)ceil((position[2]+rtot)/hzed); if (kmax > (nz-2)) { Vnm_print(2, "Vpmg_dbForce: Atom %d off grid!\n", atomID); return 0; } for (i=imin; i<=imax; i++) { for (j=jmin; j<=jmax; j++) { for (k=kmin; k<=kmax; k++) { /* i,j,k */ gpos[0] = (i+0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxijk = (thee->epsx[IJK(i,j,k)] - epsp)*depsi; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos, thee->splineWin, 0.,atom, dHxijk); /* switch (srfm) { case VSM_SPLINE : Vacc_splineAccGradAtomNorm(acc, gpos, thee->splineWin, 0., atom, dHxijk); break; case VSM_SPLINE4 : Vacc_splineAccGradAtomNorm4(acc, gpos, thee->splineWin, 0., atom, dHxijk); break; default: Vnm_print(2, "Vpmg_dbnbForce: Unknown surface method.\n"); return; } */ for (l=0; l<3; l++) dHxijk[l] *= Hxijk; gpos[0] = i*hx + xmin; gpos[1] = (j+0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijk = (thee->epsy[IJK(i,j,k)] - epsp)*depsi; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos, thee->splineWin, 0.,atom, dHyijk); for (l=0; l<3; l++) dHyijk[l] *= Hyijk; gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k+0.5)*hzed + zmin; Hzijk = (thee->epsz[IJK(i,j,k)] - epsp)*depsi; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos, thee->splineWin, 0.,atom, dHzijk); for (l=0; l<3; l++) dHzijk[l] *= Hzijk; /* i-1,j,k */ gpos[0] = (i-0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxim1jk = (thee->epsx[IJK(i-1,j,k)] - epsp)*depsi; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos, thee->splineWin, 0.,atom, dHxim1jk); for (l=0; l<3; l++) dHxim1jk[l] *= Hxim1jk; /* i,j-1,k */ gpos[0] = i*hx + xmin; gpos[1] = (j-0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijm1k = (thee->epsy[IJK(i,j-1,k)] - epsp)*depsi; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos, thee->splineWin, 0.,atom, dHyijm1k); for (l=0; l<3; l++) dHyijm1k[l] *= Hyijm1k; /* i,j,k-1 */ gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k-0.5)*hzed + zmin; Hzijkm1 = (thee->epsz[IJK(i,j,k-1)] - epsp)*depsi; /* Select the correct function based on the surface definition * (now including the 7th order polynomial) */ Vpmg_splineSelect(srfm,acc, gpos, thee->splineWin, 0.,atom, dHzijkm1); for (l=0; l<3; l++) dHzijkm1[l] *= Hzijkm1; /* *** CALCULATE DIELECTRIC BOUNDARY FORCES *** */ dbFmag = u[IJK(i,j,k)]; tgrad[0] = (dHxijk[0] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[0]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[0] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[0]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[0] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[0]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[1] = (dHxijk[1] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[1]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[1] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[1]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[1] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[1]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[2] = (dHxijk[2] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[2]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[2] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[2]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[2] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[2]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); dbForce[0] += (dbFmag*tgrad[0]); dbForce[1] += (dbFmag*tgrad[1]); dbForce[2] += (dbFmag*tgrad[2]); } /* k loop */ } /* j loop */ } /* i loop */ dbForce[0] = -dbForce[0]*hx*hy*hzed*deps*0.5*izmagic; dbForce[1] = -dbForce[1]*hx*hy*hzed*deps*0.5*izmagic; dbForce[2] = -dbForce[2]*hx*hy*hzed*deps*0.5*izmagic; } return 1; } VPUBLIC int Vpmg_qfForce(Vpmg *thee, double *force, int atomID, Vchrg_Meth chgm) { double tforce[3]; /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Check surface definition */ if (chgm != VCM_BSPL2) { Vnm_print(2, "Vpmg_qfForce: It is recommended that forces be \ calculated with the\n"); Vnm_print(2, "Vpmg_qfForce: cubic spline charge discretization \ scheme\n"); } switch (chgm) { case VCM_TRIL: qfForceSpline1(thee, tforce, atomID); break; case VCM_BSPL2: qfForceSpline2(thee, tforce, atomID); break; case VCM_BSPL4: qfForceSpline4(thee, tforce, atomID); break; default: Vnm_print(2, "Vpmg_qfForce: Undefined charge discretization \ method (%d)!\n", chgm); Vnm_print(2, "Vpmg_qfForce: Forces not calculated!\n"); return 0; } /* Assign forces */ force[0] = tforce[0]; force[1] = tforce[1]; force[2] = tforce[2]; return 1; } VPRIVATE void qfForceSpline1(Vpmg *thee, double *force, int atomID) { Vatom *atom; double *apos, position[3], hx, hy, hzed; double xmin, ymin, zmin, xmax, ymax, zmax; double dx, dy, dz; double *u, charge, ifloat, jfloat, kfloat; int nx, ny, nz, ihi, ilo, jhi, jlo, khi, klo; VASSERT(thee != VNULL); atom = Valist_getAtom(thee->pbe->alist, atomID); apos = Vatom_getPosition(atom); charge = Vatom_getCharge(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* If we aren't in the current position, then we're done */ if (atom->partID == 0) return; /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = thee->u; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || (apos[1]<=ymin) || \ (apos[1]>=ymax) || (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_qfForce: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", atomID, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_qfForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_qfForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_qfForce: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ihi = (int)ceil(ifloat); ilo = (int)floor(ifloat); jhi = (int)ceil(jfloat); jlo = (int)floor(jfloat); khi = (int)ceil(kfloat); klo = (int)floor(kfloat); VASSERT((ihi < nx) && (ihi >=0)); VASSERT((ilo < nx) && (ilo >=0)); VASSERT((jhi < ny) && (jhi >=0)); VASSERT((jlo < ny) && (jlo >=0)); VASSERT((khi < nz) && (khi >=0)); VASSERT((klo < nz) && (klo >=0)); dx = ifloat - (double)(ilo); dy = jfloat - (double)(jlo); dz = kfloat - (double)(klo); #if 0 Vnm_print(1, "Vpmg_qfForce: (DEBUG) u ~ %g\n", dx *dy *dz *u[IJK(ihi,jhi,khi)] +dx *dy *(1-dz)*u[IJK(ihi,jhi,klo)] +dx *(1-dy)*dz *u[IJK(ihi,jlo,khi)] +dx *(1-dy)*(1-dz)*u[IJK(ihi,jlo,klo)] +(1-dx)*dy *dz *u[IJK(ilo,jhi,khi)] +(1-dx)*dy *(1-dz)*u[IJK(ilo,jhi,klo)] +(1-dx)*(1-dy)*dz *u[IJK(ilo,jlo,khi)] +(1-dx)*(1-dy)*(1-dz)*u[IJK(ilo,jlo,klo)]); #endif if ((dx > VPMGSMALL) && (VABS(1.0-dx) > VPMGSMALL)) { force[0] = -charge*(dy *dz *u[IJK(ihi,jhi,khi)] + dy *(1-dz)*u[IJK(ihi,jhi,klo)] + (1-dy)*dz *u[IJK(ihi,jlo,khi)] + (1-dy)*(1-dz)*u[IJK(ihi,jlo,klo)] - dy *dz *u[IJK(ilo,jhi,khi)] - dy *(1-dz)*u[IJK(ilo,jhi,klo)] - (1-dy)*dz *u[IJK(ilo,jlo,khi)] - (1-dy)*(1-dz)*u[IJK(ilo,jlo,klo)])/hx; } else { force[0] = 0; Vnm_print(0, "Vpmg_qfForce: Atom %d on x gridline; zero x-force\n", atomID); } if ((dy > VPMGSMALL) && (VABS(1.0-dy) > VPMGSMALL)) { force[1] = -charge*(dx *dz *u[IJK(ihi,jhi,khi)] + dx *(1-dz)*u[IJK(ihi,jhi,klo)] - dx *dz *u[IJK(ihi,jlo,khi)] - dx *(1-dz)*u[IJK(ihi,jlo,klo)] + (1-dx)*dz *u[IJK(ilo,jhi,khi)] + (1-dx)*(1-dz)*u[IJK(ilo,jhi,klo)] - (1-dx)*dz *u[IJK(ilo,jlo,khi)] - (1-dx)*(1-dz)*u[IJK(ilo,jlo,klo)])/hy; } else { force[1] = 0; Vnm_print(0, "Vpmg_qfForce: Atom %d on y gridline; zero y-force\n", atomID); } if ((dz > VPMGSMALL) && (VABS(1.0-dz) > VPMGSMALL)) { force[2] = -charge*(dy *dx *u[IJK(ihi,jhi,khi)] - dy *dx *u[IJK(ihi,jhi,klo)] + (1-dy)*dx *u[IJK(ihi,jlo,khi)] - (1-dy)*dx *u[IJK(ihi,jlo,klo)] + dy *(1-dx)*u[IJK(ilo,jhi,khi)] - dy *(1-dx)*u[IJK(ilo,jhi,klo)] + (1-dy)*(1-dx)*u[IJK(ilo,jlo,khi)] - (1-dy)*(1-dx)*u[IJK(ilo,jlo,klo)])/hzed; } else { force[2] = 0; Vnm_print(0, "Vpmg_qfForce: Atom %d on z gridline; zero z-force\n", atomID); } } } VPRIVATE void qfForceSpline2(Vpmg *thee, double *force, int atomID) { Vatom *atom; double *apos, position[3], hx, hy, hzed; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax; double mx, my, mz, dmx, dmy, dmz; double *u, charge, ifloat, jfloat, kfloat; int nx, ny, nz, im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1; int kp1, kp2, ii, jj, kk; VASSERT(thee != VNULL); atom = Valist_getAtom(thee->pbe->alist, atomID); apos = Vatom_getPosition(atom); charge = Vatom_getCharge(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* If we aren't in the current position, then we're done */ if (atom->partID == 0) return; /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = thee->u; /* Make sure we're on the grid */ if ((apos[0]<=(xmin+hx)) || (apos[0]>=(xmax-hx)) \ || (apos[1]<=(ymin+hy)) || (apos[1]>=(ymax-hy)) \ || (apos[2]<=(zmin+hzed)) || (apos[2]>=(zmax-hzed))) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "qfForceSpline2: Atom #%d off the mesh \ (ignoring)\n", atomID); } fflush(stderr); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 1; im1 = (int)floor(ifloat); im2 = im1 - 1; jp1 = (int)ceil(jfloat); jp2 = jp1 + 1; jm1 = (int)floor(jfloat); jm2 = jm1 - 1; kp1 = (int)ceil(kfloat); kp2 = kp1 + 1; km1 = (int)floor(kfloat); km2 = km1 - 1; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (ii=im2; ii<=ip2; ii++) { mx = bspline2(VFCHI(ii,ifloat)); dmx = dbspline2(VFCHI(ii,ifloat)); for (jj=jm2; jj<=jp2; jj++) { my = bspline2(VFCHI(jj,jfloat)); dmy = dbspline2(VFCHI(jj,jfloat)); for (kk=km2; kk<=kp2; kk++) { mz = bspline2(VFCHI(kk,kfloat)); dmz = dbspline2(VFCHI(kk,kfloat)); force[0] += (charge*dmx*my*mz*u[IJK(ii,jj,kk)])/hx; force[1] += (charge*mx*dmy*mz*u[IJK(ii,jj,kk)])/hy; force[2] += (charge*mx*my*dmz*u[IJK(ii,jj,kk)])/hzed; } } } } } VPRIVATE void qfForceSpline4(Vpmg *thee, double *force, int atomID) { Vatom *atom; double f, c, *u, *apos, position[3]; /* Grid variables */ int nx,ny,nz; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax; double hx, hy, hzed, ifloat, jfloat, kfloat; /* B-spline weights */ double mx, my, mz, dmx, dmy, dmz; double mi, mj, mk; /* Loop indeces */ int i, j, k, ii, jj, kk; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; /* field */ double e[3]; VASSERT(thee != VNULL); VASSERT(thee->filled); atom = Valist_getAtom(thee->pbe->alist, atomID); apos = Vatom_getPosition(atom); c = Vatom_getCharge(atom); for (i=0;i<3;i++){ e[i] = 0.0; } /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = thee->u; /* Make sure we're on the grid */ if ((apos[0]<=(xmin+2*hx)) || (apos[0]>=(xmax-2*hx)) \ || (apos[1]<=(ymin+2*hy)) || (apos[1]>=(ymax-2*hy)) \ || (apos[2]<=(zmin+2*hzed)) || (apos[2]>=(zmax-2*hzed))) { Vnm_print(2, "qfForceSpline4: Atom off the mesh \ (ignoring) %6.3f %6.3f %6.3f\n", apos[0], apos[1], apos[2]); fflush(stderr); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); f = u[IJK(ii,jj,kk)]; /* Field */ e[0] += f*dmx*my*mz/hx; e[1] += f*mx*dmy*mz/hy; e[2] += f*mx*my*dmz/hzed; } } } } /* Monopole Force */ force[0] = e[0]*c; force[1] = e[1]*c; force[2] = e[2]*c; } VPRIVATE void markFrac( double rtot, double *tpos, int nx, int ny, int nz, double hx, double hy, double hzed, double xmin, double ymin, double zmin, double *xarray, double *yarray, double *zarray) { int i, j, k, imin, imax, jmin, jmax, kmin, kmax; double dx, dx2, dy, dy2, dz, dz2, a000, a001, a010, a100, r2; double x, xp, xm, y, yp, ym, zp, z, zm, xspan, yspan, zspan; double rtot2, pos[3]; /* Convert to grid reference frame */ pos[0] = tpos[0] - xmin; pos[1] = tpos[1] - ymin; pos[2] = tpos[2] - zmin; rtot2 = VSQR(rtot); xspan = rtot + 2*hx; imin = VMAX2(0, (int)ceil((pos[0] - xspan)/hx)); imax = VMIN2(nx-1, (int)floor((pos[0] + xspan)/hx)); for (i=imin; i<=imax; i++) { x = hx*i; dx2 = VSQR(pos[0] - x); if (rtot2 > dx2) { yspan = VSQRT(rtot2 - dx2) + 2*hy; } else { yspan = 2*hy; } jmin = VMAX2(0,(int)ceil((pos[1] - yspan)/hy)); jmax = VMIN2(ny-1,(int)floor((pos[1] + yspan)/hy)); for (j=jmin; j<=jmax; j++) { y = hy*j; dy2 = VSQR(pos[1] - y); if (rtot2 > (dx2+dy2)) { zspan = VSQRT(rtot2-dx2-dy2) + 2*hzed; } else { zspan = 2*hzed; } kmin = VMAX2(0,(int)ceil((pos[2] - zspan)/hzed)); kmax = VMIN2(nz-1,(int)floor((pos[2] + zspan)/hzed)); for (k=kmin; k<=kmax; k++) { z = hzed*k; dz2 = VSQR(pos[2] - z); r2 = dx2 + dy2 + dz2; /* We need to determine the inclusion value a000 at (i,j,k) */ if (r2 < rtot2) a000 = 1.0; else a000 = 0.0; /* We need to evaluate the values of x which intersect the * sphere and determine if these are in the interval * [(i,j,k), (i+1,j,k)] */ if (r2 < (rtot2 - hx*hx)) a100 = 1.0; else if (r2 > (rtot2 + hx*hx)) a100 = 0.0; else if (rtot2 > (dy2 + dz2)) { dx = VSQRT(rtot2 - dy2 - dz2); xm = pos[0] - dx; xp = pos[0] + dx; if ((xm < x+hx) && (xm > x)) { a100 = (xm - x)/hx; } else if ((xp < x+hx) && (xp > x)) { a100 = (xp - x)/hx; } } else a100 = 0.0; /* We need to evaluate the values of y which intersect the * sphere and determine if these are in the interval * [(i,j,k), (i,j+1,k)] */ if (r2 < (rtot2 - hy*hy)) a010 = 1.0; else if (r2 > (rtot2 + hy*hy)) a010 = 0.0; else if (rtot2 > (dx2 + dz2)) { dy = VSQRT(rtot2 - dx2 - dz2); ym = pos[1] - dy; yp = pos[1] + dy; if ((ym < y+hy) && (ym > y)) { a010 = (ym - y)/hy; } else if ((yp < y+hy) && (yp > y)) { a010 = (yp - y)/hy; } } else a010 = 0.0; /* We need to evaluate the values of y which intersect the * sphere and determine if these are in the interval * [(i,j,k), (i,j,k+1)] */ if (r2 < (rtot2 - hzed*hzed)) a001 = 1.0; else if (r2 > (rtot2 + hzed*hzed)) a001 = 0.0; else if (rtot2 > (dx2 + dy2)) { dz = VSQRT(rtot2 - dx2 - dy2); zm = pos[2] - dz; zp = pos[2] + dz; if ((zm < z+hzed) && (zm > z)) { a001 = (zm - z)/hzed; } else if ((zp < z+hzed) && (zp > z)) { a001 = (zp - z)/hzed; } } else a001 = 0.0; if (a100 < xarray[IJK(i,j,k)]) xarray[IJK(i,j,k)] = a100; if (a010 < yarray[IJK(i,j,k)]) yarray[IJK(i,j,k)] = a010; if (a001 < zarray[IJK(i,j,k)]) zarray[IJK(i,j,k)] = a001; } /* k loop */ } /* j loop */ } /* i loop */ } /* NOTE: This is the original version of the markSphere function. It's in here for reference and in case a reversion to the original code is needed. D. Gohara (2/14/08) */ /* VPRIVATE void markSphere( double rtot, double *tpos, int nx, int ny, int nz, double hx, double hy, double hzed, double xmin, double ymin, double zmin, double *array, double markVal) { int i, j, k, imin, imax, jmin, jmax, kmin, kmax; double dx, dx2, dy, dy2, dz, dz2; double rtot2, pos[3]; // Convert to grid reference frame pos[0] = tpos[0] - xmin; pos[1] = tpos[1] - ymin; pos[2] = tpos[2] - zmin; rtot2 = VSQR(rtot); dx = rtot + 0.5*hx; imin = VMAX2(0,(int)ceil((pos[0] - dx)/hx)); imax = VMIN2(nx-1,(int)floor((pos[0] + dx)/hx)); for (i=imin; i<=imax; i++) { dx2 = VSQR(pos[0] - hx*i); if (rtot2 > dx2) { dy = VSQRT(rtot2 - dx2) + 0.5*hy; } else { dy = 0.5*hy; } jmin = VMAX2(0,(int)ceil((pos[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)floor((pos[1] + dy)/hy)); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(pos[1] - hy*j); if (rtot2 > (dx2+dy2)) { dz = VSQRT(rtot2-dx2-dy2)+0.5*hzed; } else { dz = 0.5*hzed; } kmin = VMAX2(0,(int)ceil((pos[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)floor((pos[2] + dz)/hzed)); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(k*hzed - pos[2]); if ((dz2 + dy2 + dx2) <= rtot2) { array[IJK(i,j,k)] = markVal; } } // k loop } // j loop } // i loop } */ VPRIVATE void markSphere(double rtot, double *tpos, int nx, int ny, int nz, double hx, double hy, double hz, double xmin, double ymin, double zmin, double *array, double markVal) { int i, j, k; double fi,fj,fk; int imin, imax; int jmin, jmax; int kmin, kmax; double dx2, dy2, dz2; double xrange, yrange, zrange; double rtot2, posx, posy, posz; /* Convert to grid reference frame */ posx = tpos[0] - xmin; posy = tpos[1] - ymin; posz = tpos[2] - zmin; rtot2 = VSQR(rtot); xrange = rtot + 0.5 * hx; yrange = rtot + 0.5 * hy; zrange = rtot + 0.5 * hz; imin = VMAX2(0, (int)ceil((posx - xrange)/hx)); jmin = VMAX2(0, (int)ceil((posy - yrange)/hy)); kmin = VMAX2(0, (int)ceil((posz - zrange)/hz)); imax = VMIN2(nx-1, (int)floor((posx + xrange)/hx)); jmax = VMIN2(ny-1, (int)floor((posy + yrange)/hy)); kmax = VMIN2(nz-1, (int)floor((posz + zrange)/hz)); for (i=imin,fi=imin; i<=imax; i++, fi+=1.) { dx2 = VSQR(posx - hx*fi); for (j=jmin,fj=jmin; j<=jmax; j++, fj+=1.) { dy2 = VSQR(posy - hy*fj); if((dx2 + dy2) > rtot2) continue; for (k=kmin, fk=kmin; k<=kmax; k++, fk+=1.) { dz2 = VSQR(posz - hz*fk); if ((dz2 + dy2 + dx2) <= rtot2) { array[IJK(i,j,k)] = markVal; } } } } } VPRIVATE void zlapSolve( Vpmg *thee, double **solution, double **source, double **work1 ) { /* NOTE: this is an incredibly inefficient algorithm. The next * improvement is to focus on only non-zero entries in the source term. * The best improvement is to use a fast sine transform */ int n, nx, ny, nz, i, j, k, kx, ky, kz; double hx, hy, hzed, wx, wy, wz, xlen, ylen, zlen; double phix, phixp1, phixm1, phiy, phiym1, phiyp1, phiz, phizm1, phizp1; double norm, coef, proj, eigx, eigy, eigz; double ihx2, ihy2, ihzed2; double *u, *f, *phi; /* Snarf grid parameters */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; n = nx*ny*nz; hx = thee->pmgp->hx; ihx2 = 1.0/hx/hx; hy = thee->pmgp->hy; ihy2 = 1.0/hy/hy; hzed = thee->pmgp->hzed; ihzed2 = 1.0/hzed/hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Set solution and source array pointers */ u = *solution; f = *source; phi = *work1; /* Zero out the solution vector */ for (i=0; i<n; i++) thee->u[i] = 0.0; /* Iterate through the wavenumbers */ for (kx=1; kx<(nx-1); kx++) { wx = (VPI*(double)kx)/((double)nx - 1.0); eigx = 2.0*ihx2*(1.0 - cos(wx)); for (ky=1; ky<(ny-1); ky++) { wy = (VPI*(double)ky)/((double)ny - 1.0); eigy = 2.0*ihy2*(1.0 - cos(wy)); for (kz=1; kz<(nz-1); kz++) { wz = (VPI*(double)kz)/((double)nz - 1.0); eigz = 2.0*ihzed2*(1.0 - cos(wz)); /* Calculate the basis function. * We could calculate each basis function as * phix(i) = sin(wx*i) * phiy(j) = sin(wy*j) * phiz(k) = sin(wz*k) * However, this is likely to be very expensive. * Therefore, we can use the fact that * phix(i+1) = (2-hx*hx*eigx)*phix(i) - phix(i-1) * */ for (i=1; i<(nx-1); i++) { if (i == 1) { phix = sin(wx*(double)i); phixm1 = 0.0; } else { phixp1 = (2.0-hx*hx*eigx)*phix - phixm1; phixm1 = phix; phix = phixp1; } /* phix = sin(wx*(double)i); */ for (j=1; j<(ny-1); j++) { if (j == 1) { phiy = sin(wy*(double)j); phiym1 = 0.0; } else { phiyp1 = (2.0-hy*hy*eigy)*phiy - phiym1; phiym1 = phiy; phiy = phiyp1; } /* phiy = sin(wy*(double)j); */ for (k=1; k<(nz-1); k++) { if (k == 1) { phiz = sin(wz*(double)k); phizm1 = 0.0; } else { phizp1 = (2.0-hzed*hzed*eigz)*phiz - phizm1; phizm1 = phiz; phiz = phizp1; } /* phiz = sin(wz*(double)k); */ phi[IJK(i,j,k)] = phix*phiy*phiz; } } } /* Calculate the projection of the source function on this * basis function */ proj = 0.0; for (i=1; i<(nx-1); i++) { for (j=1; j<(ny-1); j++) { for (k=1; k<(nz-1); k++) { proj += f[IJK(i,j,k)]*phi[IJK(i,j,k)]; } /* k loop */ } /* j loop */ } /* i loop */ /* Assemble the coefficient to weight the contribution of this * basis function to the solution */ /* The first contribution is the projection */ coef = proj; /* The second contribution is the eigenvalue */ coef = coef/(eigx + eigy + eigz); /* The third contribution is the normalization factor */ coef = (8.0/xlen/ylen/zlen)*coef; /* The fourth contribution is from scaling the diagonal */ /* coef = hx*hy*hzed*coef; */ /* Evaluate the basis function at each grid point */ for (i=1; i<(nx-1); i++) { for (j=1; j<(ny-1); j++) { for (k=1; k<(nz-1); k++) { u[IJK(i,j,k)] += coef*phi[IJK(i,j,k)]; } /* k loop */ } /* j loop */ } /* i loop */ } /* kz loop */ } /* ky loop */ } /* kx loop */ } VPUBLIC int Vpmg_solveLaplace(Vpmg *thee) { int i, j, k, ijk, nx, ny, nz, n, dilo, dihi, djlo, djhi, dklo, dkhi; double hx, hy, hzed, epsw, iepsw, scal, scalx, scaly, scalz; nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; n = nx*ny*nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; epsw = Vpbe_getSolventDiel(thee->pbe); iepsw = 1.0/epsw; scal = hx*hy*hzed; scalx = hx*hy/hzed; scaly = hx*hzed/hy; scalz = hx*hy/hzed; if (!(thee->filled)) { Vnm_print(2, "Vpmg_solve: Need to call Vpmg_fillco()!\n"); return 0; } /* Load boundary conditions into the RHS array */ for (i=1; i<(nx-1); i++) { if (i == 1) dilo = 1; else dilo = 0; if (i == nx-2) dihi = 1; else dihi = 0; for (j=1; j<(ny-1); j++) { if (j == 1) djlo = 1; else djlo = 0; if (j == ny-2) djhi = 1; else djhi = 0; for (k=1; k<(nz-1); k++) { if (k == 1) dklo = 1; else dklo = 0; if (k == nz-2) dkhi = 1; else dkhi = 0; /// @todo Fix this to use Vmatrices thee->fcf[IJK(i,j,k)] = \ iepsw*scal*thee->charge[IJK(i,j,k)] \ + dilo*scalx*thee->gxcf[IJKx(j,k,0)] \ + dihi*scalx*thee->gxcf[IJKx(j,k,1)] \ + djlo*scaly*thee->gycf[IJKy(i,k,0)] \ + djhi*scaly*thee->gycf[IJKy(i,k,1)] \ + dklo*scalz*thee->gzcf[IJKz(i,j,0)] \ + dkhi*scalz*thee->gzcf[IJKz(i,j,1)] ; } } } /* Solve */ zlapSolve( thee, &(thee->u), &(thee->fcf), &(thee->tcf) ); /* Add boundary conditions to solution */ /* i faces */ for (j=0; j<ny; j++) { for (k=0; k<nz; k++) { thee->u[IJK(0,j,k)] = thee->gxcf[IJKx(j,k,0)]; thee->u[IJK(nx-1,j,k)] = thee->gycf[IJKx(j,k,1)]; } } /* j faces */ for (i=0; i<nx; i++) { for (k=0; k<nz; k++) { thee->u[IJK(i,0,k)] = thee->gycf[IJKy(i,k,0)]; thee->u[IJK(i,ny-1,k)] = thee->gycf[IJKy(i,k,1)]; } } /* k faces */ for (i=0; i<nx; i++) { for (j=0; j<ny; j++) { thee->u[IJK(i,j,0)] = thee->gzcf[IJKz(i,j,0)]; thee->u[IJK(i,j,nz-1)] = thee->gzcf[IJKz(i,j,1)]; } } return 1; } VPRIVATE double VFCHI4(int i, double f) { return (2.5+((double)(i)-(f))); } VPRIVATE double bspline4(double x) { double m, m2; static double one6 = 1.0/6.0; static double one8 = 1.0/8.0; static double one24 = 1.0/24.0; static double thirteen24 = 13.0/24.0; static double fourtyseven24 = 47.0/24.0; static double seventeen24 = 17.0/24.0; if ((x > 0.0) && (x <= 1.0)){ m = x*x; return one24*m*m; } else if ((x > 1.0) && (x <= 2.0)){ m = x - 1.0; m2 = m*m; return -one8 + one6*x + m2*(0.25 + one6*m - one6*m2); } else if ((x > 2.0) && (x <= 3.0)){ m = x - 2.0; m2 = m*m; return -thirteen24 + 0.5*x + m2*(-0.25 - 0.5*m + 0.25*m2); } else if ((x > 3.0) && (x <= 4.0)){ m = x - 3.0; m2 = m*m; return fourtyseven24 - 0.5*x + m2*(-0.25 + 0.5*m - one6*m2); } else if ((x > 4.0) && (x <= 5.0)){ m = x - 4.0; m2 = m*m; return seventeen24 - one6*x + m2*(0.25 - one6*m + one24*m2); } else { return 0.0; } } VPUBLIC double dbspline4(double x) { double m, m2; static double one6 = 1.0/6.0; static double one3 = 1.0/3.0; static double two3 = 2.0/3.0; static double thirteen6 = 13.0/6.0; if ((x > 0.0) && (x <= 1.0)){ m2 = x*x; return one6*x*m2; } else if ((x > 1.0) && (x <= 2.0)){ m = x - 1.0; m2 = m*m; return -one3 + 0.5*x + m2*(0.5 - two3*m); } else if ((x > 2.0) && (x <= 3.0)){ m = x - 2.0; m2 = m*m; return 1.5 - 0.5*x + m2*(-1.5 + m); } else if ((x > 3.0) && (x <= 4.0)){ m = x - 3.0; m2 = m*m; return 1.0 - 0.5*x + m2*(1.5 - two3*m); } else if ((x > 4.0) && (x <= 5.0)){ m = x - 4.0; m2 = m*m; return -thirteen6 + 0.5*x + m2*(-0.5 + one6*m); } else { return 0.0; } } VPUBLIC double d2bspline4(double x) { double m, m2; if ((x > 0.0) && (x <= 1.0)){ return 0.5*x*x; } else if ((x > 1.0) && (x <= 2.0)){ m = x - 1.0; m2 = m*m; return -0.5 + x - 2.0*m2; } else if ((x > 2.0) && (x <= 3.0)){ m = x - 2.0; m2 = m*m; return 5.5 - 3.0*x + 3.0*m2; } else if ((x > 3.0) && (x <= 4.0)){ m = x - 3.0; m2 = m*m; return -9.5 + 3.0*x - 2.0*m2; } else if ((x > 4.0) && (x <= 5.0)){ m = x - 4.0; m2 = m*m; return 4.5 - x + 0.5*m2; } else { return 0.0; } } VPUBLIC double d3bspline4(double x) { if ((x > 0.0) && (x <= 1.0)) return x; else if ((x > 1.0) && (x <= 2.0)) return 5.0 - 4.0 * x; else if ((x > 2.0) && (x <= 3.0)) return -15.0 + 6.0 * x; else if ((x > 3.0) && (x <= 4.0)) return 15.0 - 4.0 * x; else if ((x > 4.0) && (x <= 5.0)) return x - 5.0; else return 0.0; } VPUBLIC void fillcoPermanentMultipole(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; /* Coversions */ double zmagic, f; /* Grid */ double xmin, xmax, ymin, ymax, zmin, zmax; double xlen, ylen, zlen, position[3], ifloat, jfloat, kfloat; double hx, hy, hzed, *apos; /* Multipole */ double charge, *dipole,*quad; double c,ux,uy,uz,qxx,qyx,qyy,qzx,qzy,qzz,qave; /* B-spline weights */ double mx,my,mz,dmx,dmy,dmz,d2mx,d2my,d2mz; double mi,mj,mk; /* Loop variables */ int i, ii, jj, kk, nx, ny, nz, iatom; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; /* sanity check */ double mir,mjr,mkr,mr2; double debye,mc,mux,muy,muz,mqxx,mqyx,mqyy,mqzx,mqzy,mqzz; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Conversion */ f = zmagic/(hx*hy*hzed); /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Fill in the source term (permanent atomic multipoles) */ Vnm_print(0, "fillcoPermanentMultipole: filling in source term.\n"); for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); c = Vatom_getCharge(atom)*f; #if defined(WITH_TINKER) dipole = Vatom_getDipole(atom); ux = dipole[0]/hx*f; uy = dipole[1]/hy*f; uz = dipole[2]/hzed*f; quad = Vatom_getQuadrupole(atom); qxx = (1.0/3.0)*quad[0]/(hx*hx)*f; qyx = (2.0/3.0)*quad[3]/(hx*hy)*f; qyy = (1.0/3.0)*quad[4]/(hy*hy)*f; qzx = (2.0/3.0)*quad[6]/(hzed*hx)*f; qzy = (2.0/3.0)*quad[7]/(hzed*hy)*f; qzz = (1.0/3.0)*quad[8]/(hzed*hzed)*f; #else ux = 0.0; uy = 0.0; uz = 0.0; qxx = 0.0; qyx = 0.0; qyy = 0.0; qzx = 0.0; qzy = 0.0; qzz = 0.0; #endif /* if defined(WITH_TINKER) */ /* check mc = 0.0; mux = 0.0; muy = 0.0; muz = 0.0; mqxx = 0.0; mqyx = 0.0; mqyy = 0.0; mqzx = 0.0; mqzy = 0.0; mqzz = 0.0; */ /* Make sure we're on the grid */ if ((apos[0]<=(xmin-2*hx)) || (apos[0]>=(xmax+2*hx)) || \ (apos[1]<=(ymin-2*hy)) || (apos[1]>=(ymax+2*hy)) || \ (apos[2]<=(zmin-2*hzed)) || (apos[2]>=(zmax+2*hzed))) { Vnm_print(2, "fillcoPermanentMultipole: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring this atom):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "fillcoPermanentMultipole: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "fillcoPermanentMultipole: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "fillcoPermanentMultipole: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Figure out which vertices we're next to */ ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); /* Now assign fractions of the charge to the nearby verts */ for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); charge = mx*my*mz*c - dmx*my*mz*ux - mx*dmy*mz*uy - mx*my*dmz*uz + d2mx*my*mz*qxx + dmx*dmy*mz*qyx + mx*d2my*mz*qyy + dmx*my*dmz*qzx + mx*dmy*dmz*qzy + mx*my*d2mz*qzz; thee->charge[IJK(ii,jj,kk)] += charge; /* sanity check - recalculate traceless multipoles from the grid charge distribution for this site. mir = (mi - 2.5) * hx; mjr = (mj - 2.5) * hy; mkr = (mk - 2.5) * hzed; mr2 = mir*mir+mjr*mjr+mkr*mkr; mc += charge; mux += mir * charge; muy += mjr * charge; muz += mkr * charge; mqxx += (1.5*mir*mir - 0.5*mr2) * charge; mqyx += 1.5*mjr*mir * charge; mqyy += (1.5*mjr*mjr - 0.5*mr2) * charge; mqzx += 1.5*mkr*mir * charge; mqzy += 1.5*mkr*mjr * charge; mqzz += (1.5*mkr*mkr - 0.5*mr2) * charge; */ } } } } /* endif (on the mesh) */ /* print out the Grid vs. Ideal Point Multipole. */ /* debye = 4.8033324; mc = mc/f; mux = mux/f*debye; muy = muy/f*debye; muz = muz/f*debye; mqxx = mqxx/f*debye; mqyy = mqyy/f*debye; mqzz = mqzz/f*debye; mqyx = mqyx/f*debye; mqzx = mqzx/f*debye; mqzy = mqzy/f*debye; printf(" Grid v. Actual Permanent Multipole for Site %i\n",iatom); printf(" G: %10.6f\n",mc); printf(" A: %10.6f\n\n",c/f); printf(" G: %10.6f %10.6f %10.6f\n",mux,muy,muz); printf(" A: %10.6f %10.6f %10.6f\n\n", (ux * hx / f) * debye, (uy * hy / f) * debye, (uz * hzed /f) * debye); printf(" G: %10.6f\n",mqxx); printf(" A: %10.6f\n",quad[0]*debye); printf(" G: %10.6f %10.6f\n",mqyx,mqyy); printf(" A: %10.6f %10.6f\n",quad[3]*debye,quad[4]*debye); printf(" G: %10.6f %10.6f %10.6f\n",mqzx,mqzy,mqzz); printf(" A: %10.6f %10.6f %10.6f\n\n", quad[6]*debye,quad[7]*debye,quad[8]*debye); */ } /* endfor (each atom) */ } #if defined(WITH_TINKER) VPUBLIC void fillcoInducedDipole(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; /* Conversions */ double zmagic, f; /* Grid */ double xmin, xmax, ymin, ymax, zmin, zmax; double xlen, ylen, zlen, ifloat, jfloat, kfloat; double hx, hy, hzed, *apos, position[3]; /* B-spline weights */ double mx, my, mz, dmx, dmy, dmz; /* Dipole */ double charge, *dipole, ux,uy,uz; double mi,mj,mk; /* Loop indeces */ int i, ii, jj, kk, nx, ny, nz, iatom; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; double debye; double mux,muy,muz; double mir,mjr,mkr; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Conversion */ f = zmagic/(hx*hy*hzed); /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Fill in the source term (induced dipoles) */ Vnm_print(0, "fillcoInducedDipole: filling in the source term.\n"); for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); dipole = Vatom_getInducedDipole(atom); ux = dipole[0]/hx*f; uy = dipole[1]/hy*f; uz = dipole[2]/hzed*f; mux = 0.0; muy = 0.0; muz = 0.0; /* Make sure we're on the grid */ if ((apos[0]<=(xmin-2*hx)) || (apos[0]>=(xmax+2*hx)) || \ (apos[1]<=(ymin-2*hy)) || (apos[1]>=(ymax+2*hy)) || \ (apos[2]<=(zmin-2*hzed)) || (apos[2]>=(zmax+2*hzed))) { Vnm_print(2, "fillcoInducedDipole: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring this atom):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "fillcoInducedDipole: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "fillcoInducedDipole: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "fillcoInducedDipole: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Figure out which vertices we're next to */ ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); /* Now assign fractions of the dipole to the nearby verts */ for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); charge = -dmx*my*mz*ux - mx*dmy*mz*uy - mx*my*dmz*uz; thee->charge[IJK(ii,jj,kk)] += charge; /* mir = (mi - 2.5) * hx; mjr = (mj - 2.5) * hy; mkr = (mk - 2.5) * hzed; mux += mir * charge; muy += mjr * charge; muz += mkr * charge; */ } } } } /* endif (on the mesh) */ /* check debye = 4.8033324; mux = mux/f*debye; muy = muy/f*debye; muz = muz/f*debye; printf(" Grid v. Actual Induced Dipole for Site %i\n",iatom); printf(" G: %10.6f %10.6f %10.6f\n",mux,muy,muz); printf(" A: %10.6f %10.6f %10.6f\n\n", (ux * hx / f) * debye, (uy * hy / f) * debye, (uz * hzed /f) * debye); */ } /* endfor (each atom) */ } VPUBLIC void fillcoNLInducedDipole(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; /* Conversions */ double zmagic, f; /* Grid */ double xmin, xmax, ymin, ymax, zmin, zmax; double xlen, ylen, zlen, ifloat, jfloat, kfloat; double hx, hy, hzed, *apos, position[3]; /* B-spline weights */ double mx, my, mz, dmx, dmy, dmz; /* Dipole */ double charge, *dipole, ux,uy,uz; double mi,mj,mk; /* Loop indeces */ int i, ii, jj, kk, nx, ny, nz, iatom; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; /* sanity check double debye; double mux,muy,muz; double mir,mjr,mkr; */ VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Conversion */ f = zmagic/(hx*hy*hzed); /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Fill in the source term (non-local induced dipoles) */ Vnm_print(0, "fillcoNLInducedDipole: filling in source term.\n"); for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); dipole = Vatom_getNLInducedDipole(atom); ux = dipole[0]/hx*f; uy = dipole[1]/hy*f; uz = dipole[2]/hzed*f; /* mux = 0.0; muy = 0.0; muz = 0.0; */ /* Make sure we're on the grid */ if ((apos[0]<=(xmin-2*hx)) || (apos[0]>=(xmax+2*hx)) || \ (apos[1]<=(ymin-2*hy)) || (apos[1]>=(ymax+2*hy)) || \ (apos[2]<=(zmin-2*hzed)) || (apos[2]>=(zmax+2*hzed))) { Vnm_print(2, "fillcoNLInducedDipole: Atom #%d at (%4.3f, %4.3f,%4.3f) is off the mesh (ignoring this atom):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "fillcoNLInducedDipole: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "fillcoNLInducedDipole: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "fillcoNLInducedDipole: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Figure out which vertices we're next to */ ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); /* Now assign fractions of the non local induced dipole to the nearby verts */ for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); charge = -dmx*my*mz*ux - mx*dmy*mz*uy - mx*my*dmz*uz; thee->charge[IJK(ii,jj,kk)] += charge; /* mir = (mi - 2.5) * hx; mjr = (mj - 2.5) * hy; mkr = (mk - 2.5) * hzed; mux += mir * charge; muy += mjr * charge; muz += mkr * charge; */ } } } } /* endif (on the mesh) */ /* debye = 4.8033324; mux = mux/f*debye; muy = muy/f*debye; muz = muz/f*debye; printf(" Grid v. Actual Non-Local Induced Dipole for Site %i\n",iatom); printf(" G: %10.6f %10.6f %10.6f\n",mux,muy,muz); printf(" A: %10.6f %10.6f %10.6f\n\n", (ux * hx / f) * debye, (uy * hy / f) * debye, (uz * hzed /f) * debye); */ } /* endfor (each atom) */ } VPUBLIC double Vpmg_qfPermanentMultipoleEnergy(Vpmg *thee, int atomID) { double *u; Vatom *atom; /* Grid variables */ int nx, ny, nz; double xmax, xmin, ymax, ymin, zmax, zmin; double hx, hy, hzed, ifloat, jfloat, kfloat; double mi, mj, mk; double *position; /* B-spline weights */ double mx, my, mz, dmx, dmy, dmz, d2mx, d2my, d2mz; /* Loop indeces */ int ip1,ip2,im1,im2,jp1,jp2,jm1,jm2,kp1,kp2,km1,km2; int i,j,ii,jj,kk; /* Potential, field, field gradient and multipole components */ double pot, rfe[3], rfde[3][3], energy; double f, charge, *dipole, *quad; double qxx, qyx, qyy, qzx, qzy, qzz; VASSERT(thee != VNULL); VASSERT(thee->filled); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmax = thee->xf[nx-1]; ymax = thee->yf[ny-1]; zmax = thee->zf[nz-1]; xmin = thee->xf[0]; ymin = thee->yf[0]; zmin = thee->zf[0]; u = thee->u; atom = Valist_getAtom(thee->pbe->alist, atomID); /* Currently all atoms must be in the same partition. */ VASSERT(atom->partID != 0); /* Convert the atom position to grid coordinates */ position = Vatom_getPosition(atom); ifloat = (position[0] - xmin)/hx; jfloat = (position[1] - ymin)/hy; kfloat = (position[2] - zmin)/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); /* Initialize observables to zero */ energy = 0.0; pot = 0.0; for (i=0;i<3;i++){ rfe[i] = 0.0; for (j=0;j<3;j++){ rfde[i][j] = 0.0; } } for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); f = u[IJK(ii,jj,kk)]; /* potential */ pot += f*mx*my*mz; /* field */ rfe[0] += f*dmx*my*mz/hx; rfe[1] += f*mx*dmy*mz/hy; rfe[2] += f*mx*my*dmz/hzed; /* field gradient */ rfde[0][0] += f*d2mx*my*mz/(hx*hx); rfde[1][0] += f*dmx*dmy*mz/(hy*hx); rfde[1][1] += f*mx*d2my*mz/(hy*hy); rfde[2][0] += f*dmx*my*dmz/(hx*hzed); rfde[2][1] += f*mx*dmy*dmz/(hy*hzed); rfde[2][2] += f*mx*my*d2mz/(hzed*hzed); } } } charge = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); quad = Vatom_getQuadrupole(atom); qxx = quad[0]/3.0; qyx = quad[3]/3.0; qyy = quad[4]/3.0; qzx = quad[6]/3.0; qzy = quad[7]/3.0; qzz = quad[8]/3.0; energy = pot * charge - rfe[0] * dipole[0] - rfe[1] * dipole[1] - rfe[2] * dipole[2] + rfde[0][0]*qxx + 2.0*rfde[1][0]*qyx + rfde[1][1]*qyy + 2.0*rfde[2][0]*qzx + 2.0*rfde[2][1]*qzy + rfde[2][2]*qzz; return energy; } VPUBLIC void Vpmg_fieldSpline4(Vpmg *thee, int atomID, double field[3]) { Vatom *atom; double *u, f; /* Grid variables */ int nx, ny, nz; double xmax, xmin, ymax, ymin, zmax, zmin; double hx, hy, hzed, ifloat, jfloat, kfloat; double *apos, position[3]; /* B-Spline weights */ double mx, my, mz, dmx, dmy, dmz; double mi, mj, mk; /* Loop indeces */ int ip1,ip2,im1,im2,jp1,jp2,jm1,jm2,kp1,kp2,km1,km2; int i,j,ii,jj,kk; VASSERT (thee != VNULL); /* Get the mesh information */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xmax = thee->xf[nx-1]; ymax = thee->yf[ny-1]; zmax = thee->zf[nz-1]; xmin = thee->xf[0]; ymin = thee->yf[0]; zmin = thee->zf[0]; u = thee->u; atom = Valist_getAtom(thee->pbe->alist, atomID); /* Currently all atoms must be in the same partition. */ VASSERT (atom->partID != 0); /* Convert the atom position to grid coordinates */ apos = Vatom_getPosition(atom); position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (i=0;i<3;i++){ field[i] = 0.0; } for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); f = u[IJK(ii,jj,kk)]; field[0] += f*dmx*my*mz/hx; field[1] += f*mx*dmy*mz/hy; field[2] += f*mx*my*dmz/hzed; } } } } VPUBLIC void Vpmg_qfPermanentMultipoleForce(Vpmg *thee, int atomID, double force[3], double torque[3]) { Vatom *atom; double f, *u, *apos, position[3]; /* Grid variables */ int nx,ny,nz; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax; double hx, hy, hzed, ifloat, jfloat, kfloat; /* B-spline weights */ double mx, my, mz, dmx, dmy, dmz, d2mx, d2my, d2mz, d3mx, d3my, d3mz; double mi, mj, mk; /* Loop indeces */ int i, j, k, ii, jj, kk; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; /* Potential, field, field gradient and 2nd field gradient */ double pot, e[3], de[3][3], d2e[3][3][3]; /* Permanent multipole components */ double *dipole, *quad; double c, ux, uy, uz, qxx, qxy, qxz, qyx, qyy, qyz, qzx, qzy, qzz; VASSERT(thee != VNULL); VASSERT(thee->filled); atom = Valist_getAtom(thee->pbe->alist, atomID); /* Currently all atoms must be in the same partition. */ VASSERT(atom->partID != 0); apos = Vatom_getPosition(atom); c = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); ux = dipole[0]; uy = dipole[1]; uz = dipole[2]; quad = Vatom_getQuadrupole(atom); qxx = quad[0]/3.0; qxy = quad[1]/3.0; qxz = quad[2]/3.0; qyx = quad[3]/3.0; qyy = quad[4]/3.0; qyz = quad[5]/3.0; qzx = quad[6]/3.0; qzy = quad[7]/3.0; qzz = quad[8]/3.0; /* Initialize observables */ pot = 0.0; for (i=0;i<3;i++){ e[i] = 0.0; for (j=0;j<3;j++){ de[i][j] = 0.0; for (k=0;k<3;k++){ d2e[i][j][k] = 0.0; } } } /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = thee->u; /* Make sure we're on the grid */ if ((apos[0]<=(xmin+2*hx)) || (apos[0]>=(xmax-2*hx)) \ || (apos[1]<=(ymin+2*hy)) || (apos[1]>=(ymax-2*hy)) \ || (apos[2]<=(zmin+2*hzed)) || (apos[2]>=(zmax-2*hzed))) { Vnm_print(2, "qfPermanentMultipoleForce: Atom off the mesh (ignoring) %6.3f %6.3f %6.3f\n", apos[0], apos[1], apos[2]); fflush(stderr); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); d3mx = d3bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); d3my = d3bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); d3mz = d3bspline4(mk); f = u[IJK(ii,jj,kk)]; /* Potential */ pot += f*mx*my*mz; /* Field */ e[0] += f*dmx*my*mz/hx; e[1] += f*mx*dmy*mz/hy; e[2] += f*mx*my*dmz/hzed; /* Field gradient */ de[0][0] += f*d2mx*my*mz/(hx*hx); de[1][0] += f*dmx*dmy*mz/(hy*hx); de[1][1] += f*mx*d2my*mz/(hy*hy); de[2][0] += f*dmx*my*dmz/(hx*hzed); de[2][1] += f*mx*dmy*dmz/(hy*hzed); de[2][2] += f*mx*my*d2mz/(hzed*hzed); /* 2nd Field Gradient VxVxVa */ d2e[0][0][0] += f*d3mx*my*mz /(hx*hx*hx); d2e[0][0][1] += f*d2mx*dmy*mz/(hx*hy*hx); d2e[0][0][2] += f*d2mx*my*dmz/(hx*hx*hzed); /* VyVxVa */ d2e[1][0][0] += f*d2mx*dmy*mz/(hx*hx*hy); d2e[1][0][1] += f*dmx*d2my*mz/(hx*hy*hy); d2e[1][0][2] += f*dmx*dmy*dmz/(hx*hy*hzed); /* VyVyVa */ d2e[1][1][0] += f*dmx*d2my*mz/(hx*hy*hy); d2e[1][1][1] += f*mx*d3my*mz /(hy*hy*hy); d2e[1][1][2] += f*mx*d2my*dmz/(hy*hy*hzed); /* VzVxVa */ d2e[2][0][0] += f*d2mx*my*dmz/(hx*hx*hzed); d2e[2][0][1] += f*dmx*dmy*dmz/(hx*hy*hzed); d2e[2][0][2] += f*dmx*my*d2mz/(hx*hzed*hzed); /* VzVyVa */ d2e[2][1][0] += f*dmx*dmy*dmz/(hx*hy*hzed); d2e[2][1][1] += f*mx*d2my*dmz/(hy*hy*hzed); d2e[2][1][2] += f*mx*dmy*d2mz/(hy*hzed*hzed); /* VzVzVa */ d2e[2][2][0] += f*dmx*my*d2mz/(hx*hzed*hzed); d2e[2][2][1] += f*mx*dmy*d2mz/(hy*hzed*hzed); d2e[2][2][2] += f*mx*my*d3mz /(hzed*hzed*hzed); } } } } /* Monopole Force */ force[0] = e[0]*c; force[1] = e[1]*c; force[2] = e[2]*c; /* Dipole Force */ force[0] -= de[0][0]*ux+de[1][0]*uy+de[2][0]*uz; force[1] -= de[1][0]*ux+de[1][1]*uy+de[2][1]*uz; force[2] -= de[2][0]*ux+de[2][1]*uy+de[2][2]*uz; /* Quadrupole Force */ force[0] += d2e[0][0][0]*qxx + d2e[1][0][0]*qyx*2.0+d2e[1][1][0]*qyy + d2e[2][0][0]*qzx*2.0+d2e[2][1][0]*qzy*2.0+d2e[2][2][0]*qzz; force[1] += d2e[0][0][1]*qxx + d2e[1][0][1]*qyx*2.0+d2e[1][1][1]*qyy + d2e[2][0][1]*qzx*2.0+d2e[2][1][1]*qzy*2.0+d2e[2][2][1]*qzz; force[2] += d2e[0][0][2]*qxx + d2e[1][0][2]*qyx*2.0+d2e[1][1][2]*qyy + d2e[2][0][2]*qzx*2.0+d2e[2][1][2]*qzy*2.0+d2e[2][2][2]*qzz; /* Dipole Torque */ torque[0] = uy * e[2] - uz * e[1]; torque[1] = uz * e[0] - ux * e[2]; torque[2] = ux * e[1] - uy * e[0]; /* Quadrupole Torque */ de[0][1] = de[1][0]; de[0][2] = de[2][0]; de[1][2] = de[2][1]; torque[0] -= 2.0*(qyx*de[0][2] + qyy*de[1][2] + qyz*de[2][2] - qzx*de[0][1] - qzy*de[1][1] - qzz*de[2][1]); torque[1] -= 2.0*(qzx*de[0][0] + qzy*de[1][0] + qzz*de[2][0] - qxx*de[0][2] - qxy*de[1][2] - qxz*de[2][2]); torque[2] -= 2.0*(qxx*de[0][1] + qxy*de[1][1] + qxz*de[2][1] - qyx*de[0][0] - qyy*de[1][0] - qyz*de[2][0]); /* printf(" qPhi Force %f %f %f\n", force[0], force[1], force[2]); printf(" qPhi Torque %f %f %f\n", torque[0], torque[1], torque[2]); */ } VPUBLIC void Vpmg_ibPermanentMultipoleForce(Vpmg *thee, int atomID, double force[3]) { Valist *alist; Vacc *acc; Vpbe *pbe; Vatom *atom; Vsurf_Meth srfm; /* Grid variables */ double *apos, position[3], arad, irad, zkappa2, hx, hy, hzed; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2; double rtot, dx, dx2, dy, dy2, dz, dz2, gpos[3], tgrad[3], fmag; double izmagic; int i, j, k, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); /* Nonlinear PBE is not implemented for AMOEBA */ VASSERT(!thee->pmgp->nonlin); acc = thee->pbe->acc; srfm = thee->surfMeth; atom = Valist_getAtom(thee->pbe->alist, atomID); /* Currently all atoms must be in the same partition. */ VASSERT(atom->partID != 0); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); zkappa2 = Vpbe_getZkappa2(pbe); izmagic = 1.0/Vpbe_getZmagic(pbe); /* Should be a check for this further up. */ VASSERT (zkappa2 > VPMGSMALL); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { Vnm_print(2, "ibPermanentMultipoleForce: Atom %d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", atomID, apos[0], apos[1], apos[2]); Vnm_print(2, "ibPermanentMultipoleForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "ibPermanentMultipoleForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "ibPermanentMultipoleForce: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (irad + arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot + 0.5*hx; imin = VMAX2(0,(int)ceil((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)floor((position[0] + dx)/hx)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); if (rtot2 > dx2) dy = VSQRT(rtot2 - dx2) + 0.5*hy; else dy = 0.5*hy; jmin = VMAX2(0,(int)ceil((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)floor((position[1] + dy)/hy)); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); if (rtot2 > (dx2+dy2)) dz = VSQRT(rtot2-dx2-dy2)+0.5*hzed; else dz = 0.5*hzed; kmin = VMAX2(0,(int)ceil((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)floor((position[2] + dz)/hzed)); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(k*hzed - position[2]); /* See if grid point is inside ivdw radius and set ccf * accordingly (do spline assignment here) */ if ((dz2 + dy2 + dx2) <= rtot2) { gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, irad, atom, tgrad); fmag = VSQR(thee->u[IJK(i,j,k)])*thee->kappa[IJK(i,j,k)]; force[0] += (zkappa2*fmag*tgrad[0]); force[1] += (zkappa2*fmag*tgrad[1]); force[2] += (zkappa2*fmag*tgrad[2]); } } /* k loop */ } /* j loop */ } /* i loop */ } force[0] = force[0] * 0.5 * hx * hy * hzed * izmagic; force[1] = force[1] * 0.5 * hx * hy * hzed * izmagic; force[2] = force[2] * 0.5 * hx * hy * hzed * izmagic; } VPUBLIC void Vpmg_dbPermanentMultipoleForce(Vpmg *thee, int atomID, double force[3]) { Vacc *acc; Vpbe *pbe; Vatom *atom; Vsurf_Meth srfm; double *apos, position[3], arad, hx, hy, hzed, izmagic, deps, depsi; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2, epsp; double rtot, dx, gpos[3], tgrad[3], dbFmag, epsw, kT; double *u, Hxijk, Hyijk, Hzijk, Hxim1jk, Hyijm1k, Hzijkm1; double dHxijk[3], dHyijk[3], dHzijk[3], dHxim1jk[3], dHyijm1k[3]; double dHzijkm1[3]; int i, j, k, l, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); acc = thee->pbe->acc; srfm = thee->surfMeth; atom = Valist_getAtom(thee->pbe->alist, atomID); /* Currently all atoms must be in the same partition. */ VASSERT(atom->partID != 0); arad = Vatom_getRadius(atom); apos = Vatom_getPosition(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; epsp = Vpbe_getSoluteDiel(pbe); epsw = Vpbe_getSolventDiel(pbe); kT = Vpbe_getTemperature(pbe)*(1e-3)*Vunit_Na*Vunit_kb; izmagic = 1.0/Vpbe_getZmagic(pbe); deps = (epsw - epsp); depsi = 1.0/deps; VASSERT(VABS(deps) > VPMGSMALL); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = thee->u; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { Vnm_print(2, "dbPermanentMultipoleForce: Atom at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", apos[0], apos[1], apos[2]); Vnm_print(2, "dbPermanentMultipoleForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "dbPermanentMultipoleForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "dbPermanentMultipoleForce: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot/hx; imin = (int)floor((position[0]-rtot)/hx); if (imin < 1) { Vnm_print(2, "dbPermanentMultipoleForce: Atom off grid!\n"); return; } imax = (int)ceil((position[0]+rtot)/hx); if (imax > (nx-2)) { Vnm_print(2, "dbPermanentMultipoleForce: Atom off grid!\n"); return; } jmin = (int)floor((position[1]-rtot)/hy); if (jmin < 1) { Vnm_print(2, "dbPermanentMultipoleForce: Atom off grid!\n"); return; } jmax = (int)ceil((position[1]+rtot)/hy); if (jmax > (ny-2)) { Vnm_print(2, "dbPermanentMultipoleForce: Atom off grid!\n"); return; } kmin = (int)floor((position[2]-rtot)/hzed); if (kmin < 1) { Vnm_print(2, "dbPermanentMultipoleForce: Atom off grid!\n"); return; } kmax = (int)ceil((position[2]+rtot)/hzed); if (kmax > (nz-2)) { Vnm_print(2, "dbPermanentMultipoleForce: Atom off grid!\n"); return; } for (i=imin; i<=imax; i++) { for (j=jmin; j<=jmax; j++) { for (k=kmin; k<=kmax; k++) { /* i,j,k */ gpos[0] = (i+0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxijk = (thee->epsx[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHxijk); for (l=0; l<3; l++) dHxijk[l] *= Hxijk; gpos[0] = i*hx + xmin; gpos[1] = (j+0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijk = (thee->epsy[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHyijk); for (l=0; l<3; l++) dHyijk[l] *= Hyijk; gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k+0.5)*hzed + zmin; Hzijk = (thee->epsz[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHzijk); for (l=0; l<3; l++) dHzijk[l] *= Hzijk; /* i-1,j,k */ gpos[0] = (i-0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxim1jk = (thee->epsx[IJK(i-1,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHxim1jk); for (l=0; l<3; l++) dHxim1jk[l] *= Hxim1jk; /* i,j-1,k */ gpos[0] = i*hx + xmin; gpos[1] = (j-0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijm1k = (thee->epsy[IJK(i,j-1,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHyijm1k); for (l=0; l<3; l++) dHyijm1k[l] *= Hyijm1k; /* i,j,k-1 */ gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k-0.5)*hzed + zmin; Hzijkm1 = (thee->epsz[IJK(i,j,k-1)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHzijkm1); for (l=0; l<3; l++) dHzijkm1[l] *= Hzijkm1; dbFmag = u[IJK(i,j,k)]; tgrad[0] = (dHxijk[0] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[0]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[0] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[0]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[0] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[0]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[1] = (dHxijk[1] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[1]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[1] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[1]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[1] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[1]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[2] = (dHxijk[2] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[2]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[2] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[2]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[2] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[2]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); force[0] += (dbFmag*tgrad[0]); force[1] += (dbFmag*tgrad[1]); force[2] += (dbFmag*tgrad[2]); } /* k loop */ } /* j loop */ } /* i loop */ force[0] = -force[0]*hx*hy*hzed*deps*0.5*izmagic; force[1] = -force[1]*hx*hy*hzed*deps*0.5*izmagic; force[2] = -force[2]*hx*hy*hzed*deps*0.5*izmagic; } } VPUBLIC void Vpmg_qfDirectPolForce(Vpmg *thee, Vgrid* perm, Vgrid *induced, int atomID, double force[3], double torque[3]) { Vatom *atom; Vpbe *pbe; double f, fp, *u, *up, *apos, position[3]; /* Grid variables */ int nx,ny,nz; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax; double hx, hy, hzed, ifloat, jfloat, kfloat; /* B-spline weights */ double mx, my, mz, dmx, dmy, dmz, d2mx, d2my, d2mz, d3mx, d3my, d3mz; double mi, mj, mk; /* Loop indeces */ int i, j, k, ii, jj, kk; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; /* Permanent potential, field, field gradient and 2nd field gradient */ double pot, e[3], de[3][3], d2e[3][3][3]; /* Induced dipole field */ double dep[3][3]; /* Permanent multipole components */ double *dipole, *quad; double c, ux, uy, uz, qxx, qxy, qxz, qyx, qyy, qyz, qzx, qzy, qzz; double uix, uiy, uiz; VASSERT(thee != VNULL); VASSERT(induced != VNULL); /* the potential due to permanent multipoles.*/ VASSERT(induced != VNULL); /* the potential due to local induced dipoles.*/ VASSERT(thee->pbe != VNULL); VASSERT(thee->pbe->alist != VNULL); atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT(atom->partID != 0); /* all atoms must be in the same partition.*/ apos = Vatom_getPosition(atom); c = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); ux = dipole[0]; uy = dipole[1]; uz = dipole[2]; quad = Vatom_getQuadrupole(atom); qxx = quad[0]/3.0; qxy = quad[1]/3.0; qxz = quad[2]/3.0; qyx = quad[3]/3.0; qyy = quad[4]/3.0; qyz = quad[5]/3.0; qzx = quad[6]/3.0; qzy = quad[7]/3.0; qzz = quad[8]/3.0; dipole = Vatom_getInducedDipole(atom); uix = dipole[0]; uiy = dipole[1]; uiz = dipole[2]; /* Reset Field Gradients */ pot = 0.0; for (i=0;i<3;i++){ e[i] = 0.0; for (j=0;j<3;j++){ de[i][j] = 0.0; dep[i][j] = 0.0; for (k=0;k<3;k++){ d2e[i][j][k] = 0.0; } } } /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = induced->data; up = perm->data; /* Make sure we're on the grid */ if ((apos[0]<=(xmin+2*hx)) || (apos[0]>=(xmax-2*hx)) \ || (apos[1]<=(ymin+2*hy)) || (apos[1]>=(ymax-2*hy)) \ || (apos[2]<=(zmin+2*hzed)) || (apos[2]>=(zmax-2*hzed))) { Vnm_print(2, "qfDirectPolForce: Atom off the mesh (ignoring) %6.3f %6.3f %6.3f\n", apos[0], apos[1], apos[2]); fflush(stderr); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); d3mx = d3bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); d3my = d3bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); d3mz = d3bspline4(mk); f = u[IJK(ii,jj,kk)]; fp = up[IJK(ii,jj,kk)]; /* The potential */ pot += f*mx*my*mz; /* The field */ e[0] += f*dmx*my*mz/hx; e[1] += f*mx*dmy*mz/hy; e[2] += f*mx*my*dmz/hzed; /* The gradient of the field */ de[0][0] += f*d2mx*my*mz/(hx*hx); de[1][0] += f*dmx*dmy*mz/(hy*hx); de[1][1] += f*mx*d2my*mz/(hy*hy); de[2][0] += f*dmx*my*dmz/(hx*hzed); de[2][1] += f*mx*dmy*dmz/(hy*hzed); de[2][2] += f*mx*my*d2mz/(hzed*hzed); /* The gradient of the (permanent) field */ dep[0][0] += fp*d2mx*my*mz/(hx*hx); dep[1][0] += fp*dmx*dmy*mz/(hy*hx); dep[1][1] += fp*mx*d2my*mz/(hy*hy); dep[2][0] += fp*dmx*my*dmz/(hx*hzed); dep[2][1] += fp*mx*dmy*dmz/(hy*hzed); dep[2][2] += fp*mx*my*d2mz/(hzed*hzed); /* The 2nd gradient of the field VxVxVa */ d2e[0][0][0] += f*d3mx*my*mz /(hx*hx*hx); d2e[0][0][1] += f*d2mx*dmy*mz/(hx*hy*hx); d2e[0][0][2] += f*d2mx*my*dmz/(hx*hx*hzed); /* VyVxVa */ d2e[1][0][0] += f*d2mx*dmy*mz/(hx*hx*hy); d2e[1][0][1] += f*dmx*d2my*mz/(hx*hy*hy); d2e[1][0][2] += f*dmx*dmy*dmz/(hx*hy*hzed); /* VyVyVa */ d2e[1][1][0] += f*dmx*d2my*mz/(hx*hy*hy); d2e[1][1][1] += f*mx*d3my*mz /(hy*hy*hy); d2e[1][1][2] += f*mx*d2my*dmz/(hy*hy*hzed); /* VzVxVa */ d2e[2][0][0] += f*d2mx*my*dmz/(hx*hx*hzed); d2e[2][0][1] += f*dmx*dmy*dmz/(hx*hy*hzed); d2e[2][0][2] += f*dmx*my*d2mz/(hx*hzed*hzed); /* VzVyVa */ d2e[2][1][0] += f*dmx*dmy*dmz/(hx*hy*hzed); d2e[2][1][1] += f*mx*d2my*dmz/(hy*hy*hzed); d2e[2][1][2] += f*mx*dmy*d2mz/(hy*hzed*hzed); /* VzVzVa */ d2e[2][2][0] += f*dmx*my*d2mz/(hx*hzed*hzed); d2e[2][2][1] += f*mx*dmy*d2mz/(hy*hzed*hzed); d2e[2][2][2] += f*mx*my*d3mz /(hzed*hzed*hzed); } } } } /* force on permanent multipole due to induced reaction field */ /* Monopole Force */ force[0] = e[0]*c; force[1] = e[1]*c; force[2] = e[2]*c; /* Dipole Force */ force[0] -= de[0][0]*ux+de[1][0]*uy+de[2][0]*uz; force[1] -= de[1][0]*ux+de[1][1]*uy+de[2][1]*uz; force[2] -= de[2][0]*ux+de[2][1]*uy+de[2][2]*uz; /* Quadrupole Force */ force[0] += d2e[0][0][0]*qxx + d2e[1][0][0]*qyx*2.0+d2e[1][1][0]*qyy + d2e[2][0][0]*qzx*2.0+d2e[2][1][0]*qzy*2.0+d2e[2][2][0]*qzz; force[1] += d2e[0][0][1]*qxx + d2e[1][0][1]*qyx*2.0+d2e[1][1][1]*qyy + d2e[2][0][1]*qzx*2.0+d2e[2][1][1]*qzy*2.0+d2e[2][2][1]*qzz; force[2] += d2e[0][0][2]*qxx + d2e[1][0][2]*qyx*2.0+d2e[1][1][2]*qyy + d2e[2][0][2]*qzx*2.0+d2e[2][1][2]*qzy*2.0+d2e[2][2][2]*qzz; /* torque on permanent mulitpole due to induced reaction field */ /* Dipole Torque */ torque[0] = uy * e[2] - uz * e[1]; torque[1] = uz * e[0] - ux * e[2]; torque[2] = ux * e[1] - uy * e[0]; /* Quadrupole Torque */ /* Tx = -2.0*(Sum_a (Qya*dEaz) + Sum_b (Qzb*dEby)) Ty = -2.0*(Sum_a (Qza*dEax) + Sum_b (Qxb*dEbz)) Tz = -2.0*(Sum_a (Qxa*dEay) + Sum_b (Qyb*dEbx)) */ de[0][1] = de[1][0]; de[0][2] = de[2][0]; de[1][2] = de[2][1]; torque[0] -= 2.0*(qyx*de[0][2] + qyy*de[1][2] + qyz*de[2][2] - qzx*de[0][1] - qzy*de[1][1] - qzz*de[2][1]); torque[1] -= 2.0*(qzx*de[0][0] + qzy*de[1][0] + qzz*de[2][0] - qxx*de[0][2] - qxy*de[1][2] - qxz*de[2][2]); torque[2] -= 2.0*(qxx*de[0][1] + qxy*de[1][1] + qxz*de[2][1] - qyx*de[0][0] - qyy*de[1][0] - qyz*de[2][0]); /* force on induced dipole due to permanent reaction field */ force[0] -= dep[0][0]*uix+dep[1][0]*uiy+dep[2][0]*uiz; force[1] -= dep[1][0]*uix+dep[1][1]*uiy+dep[2][1]*uiz; force[2] -= dep[2][0]*uix+dep[2][1]*uiy+dep[2][2]*uiz; force[0] = 0.5 * force[0]; force[1] = 0.5 * force[1]; force[2] = 0.5 * force[2]; torque[0] = 0.5 * torque[0]; torque[1] = 0.5 * torque[1]; torque[2] = 0.5 * torque[2]; /* printf(" qPhi Force %f %f %f\n", force[0], force[1], force[2]); printf(" qPhi Torque %f %f %f\n", torque[0], torque[1], torque[2]); */ } VPUBLIC void Vpmg_qfNLDirectPolForce(Vpmg *thee, Vgrid *perm, Vgrid *nlInduced, int atomID, double force[3], double torque[3]) { Vatom *atom; double *apos, *dipole, *quad, position[3], hx, hy, hzed; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax; double pot, e[3],de[3][3],dep[3][3],d2e[3][3][3]; double mx, my, mz, dmx, dmy, dmz, mi, mj, mk; double d2mx, d2my, d2mz, d3mx, d3my, d3mz; double *u, *up, charge, ifloat, jfloat, kfloat; double f, fp, c, ux, uy, uz, qxx, qxy, qxz, qyx, qyy, qyz, qzx, qzy, qzz; double uix, uiy, uiz; int i,j,k,nx, ny, nz, im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1; int kp1, kp2, ii, jj, kk; VASSERT(thee != VNULL); VASSERT(perm != VNULL); /* potential due to permanent multipoles. */ VASSERT(nlInduced != VNULL); /* potential due to non-local induced dipoles */ VASSERT(!thee->pmgp->nonlin); /* Nonlinear PBE is not implemented for AMOEBA */ atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT(atom->partID != 0); /* Currently all atoms must be in the same partition. */ apos = Vatom_getPosition(atom); c = Vatom_getCharge(atom); dipole = Vatom_getDipole(atom); ux = dipole[0]; uy = dipole[1]; uz = dipole[2]; quad = Vatom_getQuadrupole(atom); qxx = quad[0]/3.0; qxy = quad[1]/3.0; qxz = quad[2]/3.0; qyx = quad[3]/3.0; qyy = quad[4]/3.0; qyz = quad[5]/3.0; qzx = quad[6]/3.0; qzy = quad[7]/3.0; qzz = quad[8]/3.0; dipole = Vatom_getNLInducedDipole(atom); uix = dipole[0]; uiy = dipole[1]; uiz = dipole[2]; /* Reset Field Gradients */ pot = 0.0; for (i=0;i<3;i++){ e[i] = 0.0; for (j=0;j<3;j++){ de[i][j] = 0.0; dep[i][j] = 0.0; for (k=0;k<3;k++){ d2e[i][j][k] = 0.0; } } } /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = nlInduced->data; up = perm->data; /* Make sure we're on the grid */ if ((apos[0]<=(xmin+2*hx)) || (apos[0]>=(xmax-2*hx)) \ || (apos[1]<=(ymin+2*hy)) || (apos[1]>=(ymax-2*hy)) \ || (apos[2]<=(zmin+2*hzed)) || (apos[2]>=(zmax-2*hzed))) { Vnm_print(2, "qfNLDirectMultipoleForce: Atom off the mesh (ignoring) %6.3f %6.3f %6.3f\n", apos[0], apos[1], apos[2]); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); d3mx = d3bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); d3my = d3bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); d3mz = d3bspline4(mk); f = u[IJK(ii,jj,kk)]; fp = up[IJK(ii,jj,kk)]; /* The potential */ pot += f*mx*my*mz; /* The field */ e[0] += f*dmx*my*mz/hx; e[1] += f*mx*dmy*mz/hy; e[2] += f*mx*my*dmz/hzed; /* The gradient of the field */ de[0][0] += f*d2mx*my*mz/(hx*hx); de[1][0] += f*dmx*dmy*mz/(hy*hx); de[1][1] += f*mx*d2my*mz/(hy*hy); de[2][0] += f*dmx*my*dmz/(hx*hzed); de[2][1] += f*mx*dmy*dmz/(hy*hzed); de[2][2] += f*mx*my*d2mz/(hzed*hzed); /* The gradient of the (permanent) field */ dep[0][0] += fp*d2mx*my*mz/(hx*hx); dep[1][0] += fp*dmx*dmy*mz/(hy*hx); dep[1][1] += fp*mx*d2my*mz/(hy*hy); dep[2][0] += fp*dmx*my*dmz/(hx*hzed); dep[2][1] += fp*mx*dmy*dmz/(hy*hzed); dep[2][2] += fp*mx*my*d2mz/(hzed*hzed); /* The 2nd gradient of the field */ /* VxVxVa */ d2e[0][0][0] += f*d3mx*my*mz /(hx*hx*hx); d2e[0][0][1] += f*d2mx*dmy*mz/(hx*hy*hx); d2e[0][0][2] += f*d2mx*my*dmz/(hx*hx*hzed); /* VyVxVa */ d2e[1][0][0] += f*d2mx*dmy*mz/(hx*hx*hy); d2e[1][0][1] += f*dmx*d2my*mz/(hx*hy*hy); d2e[1][0][2] += f*dmx*dmy*dmz/(hx*hy*hzed); /* VyVyVa */ d2e[1][1][0] += f*dmx*d2my*mz/(hx*hy*hy); d2e[1][1][1] += f*mx*d3my*mz /(hy*hy*hy); d2e[1][1][2] += f*mx*d2my*dmz/(hy*hy*hzed); /* VzVxVa */ d2e[2][0][0] += f*d2mx*my*dmz/(hx*hx*hzed); d2e[2][0][1] += f*dmx*dmy*dmz/(hx*hy*hzed); d2e[2][0][2] += f*dmx*my*d2mz/(hx*hzed*hzed); /* VzVyVa */ d2e[2][1][0] += f*dmx*dmy*dmz/(hx*hy*hzed); d2e[2][1][1] += f*mx*d2my*dmz/(hy*hy*hzed); d2e[2][1][2] += f*mx*dmy*d2mz/(hy*hzed*hzed); /* VzVzVa */ d2e[2][2][0] += f*dmx*my*d2mz/(hx*hzed*hzed); d2e[2][2][1] += f*mx*dmy*d2mz/(hy*hzed*hzed); d2e[2][2][2] += f*mx*my*d3mz /(hzed*hzed*hzed); } } } } /* force on permanent multipole due to non-local induced reaction field */ /* Monopole Force */ force[0] = e[0]*c; force[1] = e[1]*c; force[2] = e[2]*c; /* Dipole Force */ force[0] -= de[0][0]*ux+de[1][0]*uy+de[2][0]*uz; force[1] -= de[1][0]*ux+de[1][1]*uy+de[2][1]*uz; force[2] -= de[2][0]*ux+de[2][1]*uy+de[2][2]*uz; /* Quadrupole Force */ force[0] += d2e[0][0][0]*qxx + d2e[1][0][0]*qyx*2.0+d2e[1][1][0]*qyy + d2e[2][0][0]*qzx*2.0+d2e[2][1][0]*qzy*2.0+d2e[2][2][0]*qzz; force[1] += d2e[0][0][1]*qxx + d2e[1][0][1]*qyx*2.0+d2e[1][1][1]*qyy + d2e[2][0][1]*qzx*2.0+d2e[2][1][1]*qzy*2.0+d2e[2][2][1]*qzz; force[2] += d2e[0][0][2]*qxx + d2e[1][0][2]*qyx*2.0+d2e[1][1][2]*qyy + d2e[2][0][2]*qzx*2.0+d2e[2][1][2]*qzy*2.0+d2e[2][2][2]*qzz; /* torque on permanent mulitpole due to non-local induced reaction field */ /* Dipole Torque */ torque[0] = uy * e[2] - uz * e[1]; torque[1] = uz * e[0] - ux * e[2]; torque[2] = ux * e[1] - uy * e[0]; /* Quadrupole Torque */ /* Tx = -2.0*(Sum_a (Qya*dEaz) + Sum_b (Qzb*dEby)) Ty = -2.0*(Sum_a (Qza*dEax) + Sum_b (Qxb*dEbz)) Tz = -2.0*(Sum_a (Qxa*dEay) + Sum_b (Qyb*dEbx)) */ de[0][1] = de[1][0]; de[0][2] = de[2][0]; de[1][2] = de[2][1]; torque[0] -= 2.0*(qyx*de[0][2] + qyy*de[1][2] + qyz*de[2][2] - qzx*de[0][1] - qzy*de[1][1] - qzz*de[2][1]); torque[1] -= 2.0*(qzx*de[0][0] + qzy*de[1][0] + qzz*de[2][0] - qxx*de[0][2] - qxy*de[1][2] - qxz*de[2][2]); torque[2] -= 2.0*(qxx*de[0][1] + qxy*de[1][1] + qxz*de[2][1] - qyx*de[0][0] - qyy*de[1][0] - qyz*de[2][0]); /* force on non-local induced dipole due to permanent reaction field */ force[0] -= dep[0][0]*uix+dep[1][0]*uiy+dep[2][0]*uiz; force[1] -= dep[1][0]*uix+dep[1][1]*uiy+dep[2][1]*uiz; force[2] -= dep[2][0]*uix+dep[2][1]*uiy+dep[2][2]*uiz; force[0] = 0.5 * force[0]; force[1] = 0.5 * force[1]; force[2] = 0.5 * force[2]; torque[0] = 0.5 * torque[0]; torque[1] = 0.5 * torque[1]; torque[2] = 0.5 * torque[2]; /* printf(" qPhi Force %f %f %f\n", force[0], force[1], force[2]); printf(" qPhi Torque %f %f %f\n", torque[0], torque[1], torque[2]); */ } VPUBLIC void Vpmg_ibDirectPolForce(Vpmg *thee, Vgrid *perm, Vgrid *induced, int atomID, double force[3]) { Vatom *atom; Valist *alist; Vacc *acc; Vpbe *pbe; Vsurf_Meth srfm; double *apos, position[3], arad, irad, zkappa2, hx, hy, hzed; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2; double rtot, dx, dx2, dy, dy2, dz, dz2, gpos[3], tgrad[3], fmag; double izmagic; int i, j, k, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); VASSERT(perm != VNULL); /* potential due to permanent multipoles.*/ VASSERT(induced != VNULL); /* potential due to induced dipoles. */ VASSERT (!thee->pmgp->nonlin); /* Nonlinear PBE is not implemented for AMOEBA */ acc = thee->pbe->acc; srfm = thee->surfMeth; atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT(atom->partID != 0); /* Currently all atoms must be in the same partition. */ apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); zkappa2 = Vpbe_getZkappa2(pbe); izmagic = 1.0/Vpbe_getZmagic(pbe); VASSERT (zkappa2 > VPMGSMALL); /* It is ok to run AMOEBA with no ions, but this is checked for higher up in the driver. */ /* Mesh info */ nx = induced->nx; ny = induced->ny; nz = induced->nz; hx = induced->hx; hy = induced->hy; hzed = induced->hzed; xmin = induced->xmin; ymin = induced->ymin; zmin = induced->zmin; xmax = induced->xmax; ymax = induced->ymax; zmax = induced->zmax; xlen = xmax-xmin; ylen = ymax-ymin; zlen = zmax-zmin; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { Vnm_print(2, "Vpmg_ibForce: Atom at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_ibForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_ibForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_ibForce: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (irad + arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot + 0.5*hx; imin = VMAX2(0,(int)ceil((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)floor((position[0] + dx)/hx)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); if (rtot2 > dx2) dy = VSQRT(rtot2 - dx2) + 0.5*hy; else dy = 0.5*hy; jmin = VMAX2(0,(int)ceil((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)floor((position[1] + dy)/hy)); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); if (rtot2 > (dx2+dy2)) dz = VSQRT(rtot2-dx2-dy2)+0.5*hzed; else dz = 0.5*hzed; kmin = VMAX2(0,(int)ceil((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)floor((position[2] + dz)/hzed)); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(k*hzed - position[2]); /* See if grid point is inside ivdw radius and set ccf * accordingly (do spline assignment here) */ if ((dz2 + dy2 + dx2) <= rtot2) { gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, irad, atom, tgrad); fmag = induced->data[IJK(i,j,k)]; fmag *= perm->data[IJK(i,j,k)]; fmag *= thee->kappa[IJK(i,j,k)]; force[0] += (zkappa2*fmag*tgrad[0]); force[1] += (zkappa2*fmag*tgrad[1]); force[2] += (zkappa2*fmag*tgrad[2]); } } /* k loop */ } /* j loop */ } /* i loop */ } force[0] = force[0] * 0.5 * hx * hy * hzed * izmagic; force[1] = force[1] * 0.5 * hx * hy * hzed * izmagic; force[2] = force[2] * 0.5 * hx * hy * hzed * izmagic; } VPUBLIC void Vpmg_ibNLDirectPolForce(Vpmg *thee, Vgrid *perm, Vgrid *nlInduced, int atomID, double force[3]) { Vpmg_ibDirectPolForce(thee, perm, nlInduced, atomID, force); } VPUBLIC void Vpmg_dbDirectPolForce(Vpmg *thee, Vgrid *perm, Vgrid *induced, int atomID, double force[3]) { Vatom *atom; Vacc *acc; Vpbe *pbe; Vsurf_Meth srfm; double *apos, position[3], arad, hx, hy, hzed, izmagic, deps, depsi; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2, epsp; double rtot, dx, gpos[3], tgrad[3], dbFmag, epsw, kT; double *u, *up, Hxijk, Hyijk, Hzijk, Hxim1jk, Hyijm1k, Hzijkm1; double dHxijk[3], dHyijk[3], dHzijk[3], dHxim1jk[3], dHyijm1k[3]; double dHzijkm1[3]; int i, j, k, l, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); VASSERT(perm != VNULL); /* permanent multipole PMG solution. */ VASSERT(induced != VNULL); /* potential due to induced dipoles. */ acc = thee->pbe->acc; atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT (atom->partID != 0); /* Currently all atoms must be in the same partition. */ apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; srfm = thee->surfMeth; epsp = Vpbe_getSoluteDiel(pbe); epsw = Vpbe_getSolventDiel(pbe); kT = Vpbe_getTemperature(pbe)*(1e-3)*Vunit_Na*Vunit_kb; izmagic = 1.0/Vpbe_getZmagic(pbe); deps = (epsw - epsp); depsi = 1.0/deps; VASSERT(VABS(deps) > VPMGSMALL); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; /* If the permanent and induced potentials are flipped the results are exactly the same. */ u = induced->data; up = perm->data; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_dbDirectPolForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_dbDirectPolForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_dbDirectPolForce: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot/hx; imin = (int)floor((position[0]-rtot)/hx); if (imin < 1) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom %d off grid!\n", atomID); return; } imax = (int)ceil((position[0]+rtot)/hx); if (imax > (nx-2)) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom %d off grid!\n", atomID); return; } jmin = (int)floor((position[1]-rtot)/hy); if (jmin < 1) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom %d off grid!\n", atomID); return; } jmax = (int)ceil((position[1]+rtot)/hy); if (jmax > (ny-2)) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom %d off grid!\n", atomID); return; } kmin = (int)floor((position[2]-rtot)/hzed); if (kmin < 1) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom %d off grid!\n", atomID); return; } kmax = (int)ceil((position[2]+rtot)/hzed); if (kmax > (nz-2)) { Vnm_print(2, "Vpmg_dbDirectPolForce: Atom %d off grid!\n", atomID); return; } for (i=imin; i<=imax; i++) { for (j=jmin; j<=jmax; j++) { for (k=kmin; k<=kmax; k++) { /* i,j,k */ gpos[0] = (i+0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxijk = (thee->epsx[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHxijk); for (l=0; l<3; l++) dHxijk[l] *= Hxijk; gpos[0] = i*hx + xmin; gpos[1] = (j+0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijk = (thee->epsy[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHyijk); for (l=0; l<3; l++) dHyijk[l] *= Hyijk; gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k+0.5)*hzed + zmin; Hzijk = (thee->epsz[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHzijk); for (l=0; l<3; l++) dHzijk[l] *= Hzijk; /* i-1,j,k */ gpos[0] = (i-0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxim1jk = (thee->epsx[IJK(i-1,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHxim1jk); for (l=0; l<3; l++) dHxim1jk[l] *= Hxim1jk; /* i,j-1,k */ gpos[0] = i*hx + xmin; gpos[1] = (j-0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijm1k = (thee->epsy[IJK(i,j-1,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHyijm1k); for (l=0; l<3; l++) dHyijm1k[l] *= Hyijm1k; /* i,j,k-1 */ gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k-0.5)*hzed + zmin; Hzijkm1 = (thee->epsz[IJK(i,j,k-1)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHzijkm1); for (l=0; l<3; l++) dHzijkm1[l] *= Hzijkm1; dbFmag = up[IJK(i,j,k)]; tgrad[0] = (dHxijk[0] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[0]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[0] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[0]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[0] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[0]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[1] = (dHxijk[1] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[1]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[1] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[1]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[1] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[1]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[2] = (dHxijk[2] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[2]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[2] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[2]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[2] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[2]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); force[0] += (dbFmag*tgrad[0]); force[1] += (dbFmag*tgrad[1]); force[2] += (dbFmag*tgrad[2]); } /* k loop */ } /* j loop */ } /* i loop */ force[0] = -force[0]*hx*hy*hzed*deps*0.5*izmagic; force[1] = -force[1]*hx*hy*hzed*deps*0.5*izmagic; force[2] = -force[2]*hx*hy*hzed*deps*0.5*izmagic; } } VPUBLIC void Vpmg_dbNLDirectPolForce(Vpmg *thee, Vgrid *perm, Vgrid *nlInduced, int atomID, double force[3]) { Vpmg_dbDirectPolForce(thee, perm, nlInduced, atomID, force); } VPUBLIC void Vpmg_qfMutualPolForce(Vpmg *thee, Vgrid *induced, Vgrid *nlinduced, int atomID, double force[3]) { Vatom *atom; double *apos, *dipole, position[3], hx, hy, hzed; double *u, *unl; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax; double de[3][3], denl[3][3]; double mx, my, mz, dmx, dmy, dmz, d2mx, d2my, d2mz, mi, mj, mk; double ifloat, jfloat, kfloat; double f, fnl, uix, uiy, uiz, uixnl, uiynl, uiznl; int i,j,k,nx, ny, nz, im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1; int kp1, kp2, ii, jj, kk; VASSERT(thee != VNULL); /* PMG object with PBE info. */ VASSERT(induced != VNULL); /* potential due to induced dipoles. */ VASSERT(nlinduced != VNULL); /* potential due to non-local induced dipoles. */ atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT(atom->partID != 0); /* all atoms must be in the same partition. */ apos = Vatom_getPosition(atom); dipole = Vatom_getInducedDipole(atom); uix = dipole[0]; uiy = dipole[1]; uiz = dipole[2]; dipole = Vatom_getNLInducedDipole(atom); uixnl = dipole[0]; uiynl = dipole[1]; uiznl = dipole[2]; u = induced->data; unl = nlinduced->data; for (i=0;i<3;i++){ for (j=0;j<3;j++){ de[i][j] = 0.0; denl[i][j] = 0.0; } } /* Mesh info */ nx = induced->nx; ny = induced->ny; nz = induced->nz; hx = induced->hx; hy = induced->hy; hzed = induced->hzed; xmin = induced->xmin; ymin = induced->ymin; zmin = induced->zmin; xmax = induced->xmax; ymax = induced->ymax; zmax = induced->zmax; xlen = xmax-xmin; ylen = ymax-ymin; zlen = zmax-zmin; /* If we aren't in the current position, then we're done */ if (atom->partID == 0) return; /* Make sure we're on the grid */ if ((apos[0]<=(xmin+2*hx)) || (apos[0]>=(xmax-2*hx)) \ || (apos[1]<=(ymin+2*hy)) || (apos[1]>=(ymax-2*hy)) \ || (apos[2]<=(zmin+2*hzed)) || (apos[2]>=(zmax-2*hzed))) { Vnm_print(2, "qfMutualPolForce: Atom off the mesh (ignoring) %6.3f %6.3f %6.3f\n", apos[0], apos[1], apos[2]); fflush(stderr); } else { /* Convert the atom position to grid coordinates */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); f = u[IJK(ii,jj,kk)]; fnl = unl[IJK(ii,jj,kk)]; /* The gradient of the reaction field due to induced dipoles */ de[0][0] += f*d2mx*my*mz/(hx*hx); de[1][0] += f*dmx*dmy*mz/(hy*hx); de[1][1] += f*mx*d2my*mz/(hy*hy); de[2][0] += f*dmx*my*dmz/(hx*hzed); de[2][1] += f*mx*dmy*dmz/(hy*hzed); de[2][2] += f*mx*my*d2mz/(hzed*hzed); /* The gradient of the reaction field due to non-local induced dipoles */ denl[0][0] += fnl*d2mx*my*mz/(hx*hx); denl[1][0] += fnl*dmx*dmy*mz/(hy*hx); denl[1][1] += fnl*mx*d2my*mz/(hy*hy); denl[2][0] += fnl*dmx*my*dmz/(hx*hzed); denl[2][1] += fnl*mx*dmy*dmz/(hy*hzed); denl[2][2] += fnl*mx*my*d2mz/(hzed*hzed); } } } } /* mutual polarization force */ force[0] = -(de[0][0]*uixnl + de[1][0]*uiynl + de[2][0]*uiznl); force[1] = -(de[1][0]*uixnl + de[1][1]*uiynl + de[2][1]*uiznl); force[2] = -(de[2][0]*uixnl + de[2][1]*uiynl + de[2][2]*uiznl); force[0] -= denl[0][0]*uix + denl[1][0]*uiy + denl[2][0]*uiz; force[1] -= denl[1][0]*uix + denl[1][1]*uiy + denl[2][1]*uiz; force[2] -= denl[2][0]*uix + denl[2][1]*uiy + denl[2][2]*uiz; force[0] = 0.5 * force[0]; force[1] = 0.5 * force[1]; force[2] = 0.5 * force[2]; } VPUBLIC void Vpmg_ibMutualPolForce(Vpmg *thee, Vgrid *induced, Vgrid *nlinduced, int atomID, double force[3]) { Vatom *atom; Valist *alist; Vacc *acc; Vpbe *pbe; Vsurf_Meth srfm; double *apos, position[3], arad, irad, zkappa2, hx, hy, hzed; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2; double rtot, dx, dx2, dy, dy2, dz, dz2, gpos[3], tgrad[3], fmag; double izmagic; int i, j, k, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); /* We need a PMG object with PBE info. */ VASSERT(induced != VNULL); /* We need the potential due to induced dipoles. */ VASSERT(nlinduced != VNULL); /* We need the potential due to non-local induced dipoles. */ VASSERT (!thee->pmgp->nonlin); /* Nonlinear PBE is not implemented for AMOEBA */ atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT (atom->partID != 0); /* Currently all atoms must be in the same partition. */ acc = thee->pbe->acc; srfm = thee->surfMeth; apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* If we aren't in the current position, then we're done */ if (atom->partID == 0) return; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); zkappa2 = Vpbe_getZkappa2(pbe); izmagic = 1.0/Vpbe_getZmagic(pbe); VASSERT (zkappa2 > VPMGSMALL); /* Should be a check for this further up.*/ /* Mesh info */ nx = induced->nx; ny = induced->ny; nz = induced->nz; hx = induced->hx; hy = induced->hy; hzed = induced->hzed; xmin = induced->xmin; ymin = induced->ymin; zmin = induced->zmin; xmax = induced->xmax; ymax = induced->ymax; zmax = induced->zmax; xlen = xmax-xmin; ylen = ymax-ymin; zlen = zmax-zmin; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { Vnm_print(2, "Vpmg_ibMutalPolForce: Atom at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_ibMutalPolForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_ibMutalPolForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_ibMutalPolForce: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (irad + arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot + 0.5*hx; imin = VMAX2(0,(int)ceil((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)floor((position[0] + dx)/hx)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); if (rtot2 > dx2) dy = VSQRT(rtot2 - dx2) + 0.5*hy; else dy = 0.5*hy; jmin = VMAX2(0,(int)ceil((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)floor((position[1] + dy)/hy)); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); if (rtot2 > (dx2+dy2)) dz = VSQRT(rtot2-dx2-dy2)+0.5*hzed; else dz = 0.5*hzed; kmin = VMAX2(0,(int)ceil((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)floor((position[2] + dz)/hzed)); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(k*hzed - position[2]); /* See if grid point is inside ivdw radius and set ccf * accordingly (do spline assignment here) */ if ((dz2 + dy2 + dx2) <= rtot2) { gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, irad, atom, tgrad); fmag = induced->data[IJK(i,j,k)]; fmag *= nlinduced->data[IJK(i,j,k)]; fmag *= thee->kappa[IJK(i,j,k)]; force[0] += (zkappa2*fmag*tgrad[0]); force[1] += (zkappa2*fmag*tgrad[1]); force[2] += (zkappa2*fmag*tgrad[2]); } } /* k loop */ } /* j loop */ } /* i loop */ } force[0] = force[0] * 0.5 * hx * hy * hzed * izmagic; force[1] = force[1] * 0.5 * hx * hy * hzed * izmagic; force[2] = force[2] * 0.5 * hx * hy * hzed * izmagic; } VPUBLIC void Vpmg_dbMutualPolForce(Vpmg *thee, Vgrid *induced, Vgrid *nlinduced, int atomID, double force[3]) { Vatom *atom; Vacc *acc; Vpbe *pbe; Vsurf_Meth srfm; double *apos, position[3], arad, hx, hy, hzed, izmagic, deps, depsi; double xlen, ylen, zlen, xmin, ymin, zmin, xmax, ymax, zmax, rtot2, epsp; double rtot, dx, gpos[3], tgrad[3], dbFmag, epsw, kT; double *u, *unl, Hxijk, Hyijk, Hzijk, Hxim1jk, Hyijm1k, Hzijkm1; double dHxijk[3], dHyijk[3], dHzijk[3], dHxim1jk[3], dHyijm1k[3]; double dHzijkm1[3]; int i, j, k, l, nx, ny, nz, imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); /* PMG object with PBE info. */ VASSERT(induced != VNULL); /* potential due to induced dipoles.*/ VASSERT(nlinduced != VNULL); /* potential due to non-local induced dipoles.*/ acc = thee->pbe->acc; srfm = thee->surfMeth; atom = Valist_getAtom(thee->pbe->alist, atomID); VASSERT (atom->partID != 0); /* all atoms must be in the same partition.*/ apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); /* Reset force */ force[0] = 0.0; force[1] = 0.0; force[2] = 0.0; /* Get PBE info */ pbe = thee->pbe; acc = pbe->acc; epsp = Vpbe_getSoluteDiel(pbe); epsw = Vpbe_getSolventDiel(pbe); kT = Vpbe_getTemperature(pbe)*(1e-3)*Vunit_Na*Vunit_kb; izmagic = 1.0/Vpbe_getZmagic(pbe); deps = (epsw - epsp); depsi = 1.0/deps; VASSERT(VABS(deps) > VPMGSMALL); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; xmin = thee->pmgp->xmin; ymin = thee->pmgp->ymin; zmin = thee->pmgp->zmin; xmax = thee->pmgp->xmax; ymax = thee->pmgp->ymax; zmax = thee->pmgp->zmax; u = induced->data; unl = nlinduced->data; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring):\n", apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_dbMutualPolForce: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_dbMutualPolForce: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_dbMutualPolForce: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Integrate over points within this atom's (inflated) radius */ rtot = (arad + thee->splineWin); rtot2 = VSQR(rtot); dx = rtot/hx; imin = (int)floor((position[0]-rtot)/hx); if (imin < 1) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom %d off grid!\n", atomID); return; } imax = (int)ceil((position[0]+rtot)/hx); if (imax > (nx-2)) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom %d off grid!\n", atomID); return; } jmin = (int)floor((position[1]-rtot)/hy); if (jmin < 1) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom %d off grid!\n", atomID); return; } jmax = (int)ceil((position[1]+rtot)/hy); if (jmax > (ny-2)) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom %d off grid!\n", atomID); return; } kmin = (int)floor((position[2]-rtot)/hzed); if (kmin < 1) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom %d off grid!\n", atomID); return; } kmax = (int)ceil((position[2]+rtot)/hzed); if (kmax > (nz-2)) { Vnm_print(2, "Vpmg_dbMutualPolForce: Atom %d off grid!\n", atomID); return; } for (i=imin; i<=imax; i++) { for (j=jmin; j<=jmax; j++) { for (k=kmin; k<=kmax; k++) { /* i,j,k */ gpos[0] = (i+0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxijk = (thee->epsx[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHxijk); for (l=0; l<3; l++) dHxijk[l] *= Hxijk; gpos[0] = i*hx + xmin; gpos[1] = (j+0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijk = (thee->epsy[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHyijk); for (l=0; l<3; l++) dHyijk[l] *= Hyijk; gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k+0.5)*hzed + zmin; Hzijk = (thee->epsz[IJK(i,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHzijk); for (l=0; l<3; l++) dHzijk[l] *= Hzijk; /* i-1,j,k */ gpos[0] = (i-0.5)*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = k*hzed + zmin; Hxim1jk = (thee->epsx[IJK(i-1,j,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHxim1jk); for (l=0; l<3; l++) dHxim1jk[l] *= Hxim1jk; /* i,j-1,k */ gpos[0] = i*hx + xmin; gpos[1] = (j-0.5)*hy + ymin; gpos[2] = k*hzed + zmin; Hyijm1k = (thee->epsy[IJK(i,j-1,k)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHyijm1k); for (l=0; l<3; l++) dHyijm1k[l] *= Hyijm1k; /* i,j,k-1 */ gpos[0] = i*hx + xmin; gpos[1] = j*hy + ymin; gpos[2] = (k-0.5)*hzed + zmin; Hzijkm1 = (thee->epsz[IJK(i,j,k-1)] - epsp)*depsi; Vpmg_splineSelect(srfm, acc, gpos, thee->splineWin, 0., atom, dHzijkm1); for (l=0; l<3; l++) dHzijkm1[l] *= Hzijkm1; dbFmag = unl[IJK(i,j,k)]; tgrad[0] = (dHxijk[0] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[0]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[0] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[0]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[0] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[0]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[1] = (dHxijk[1] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[1]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[1] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[1]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[1] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[1]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); tgrad[2] = (dHxijk[2] *(u[IJK(i+1,j,k)]-u[IJK(i,j,k)]) + dHxim1jk[2]*(u[IJK(i-1,j,k)]-u[IJK(i,j,k)]))/VSQR(hx) + (dHyijk[2] *(u[IJK(i,j+1,k)]-u[IJK(i,j,k)]) + dHyijm1k[2]*(u[IJK(i,j-1,k)]-u[IJK(i,j,k)]))/VSQR(hy) + (dHzijk[2] *(u[IJK(i,j,k+1)]-u[IJK(i,j,k)]) + dHzijkm1[2]*(u[IJK(i,j,k-1)]-u[IJK(i,j,k)]))/VSQR(hzed); force[0] += (dbFmag*tgrad[0]); force[1] += (dbFmag*tgrad[1]); force[2] += (dbFmag*tgrad[2]); } /* k loop */ } /* j loop */ } /* i loop */ force[0] = -force[0]*hx*hy*hzed*deps*0.5*izmagic; force[1] = -force[1]*hx*hy*hzed*deps*0.5*izmagic; force[2] = -force[2]*hx*hy*hzed*deps*0.5*izmagic; } } #endif /* if defined(WITH_TINKER) */ VPRIVATE void fillcoCoefSpline4(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax, ionmask, ionstr, dist2; double xlen, ylen, zlen, position[3], itot, stot, ictot, ictot2, sctot; double irad, dx, dy, dz, epsw, epsp, w2i; double hx, hy, hzed, *apos, arad, sctot2; double dx2, dy2, dz2, stot2, itot2, rtot, rtot2, splineWin; double dist, value, denom, sm, sm2, sm3, sm4, sm5, sm6, sm7; double e, e2, e3, e4, e5, e6, e7; double b, b2, b3, b4, b5, b6, b7; double c0, c1, c2, c3, c4, c5, c6, c7; double ic0, ic1, ic2, ic3, ic4, ic5, ic6, ic7; int i, j, k, nx, ny, nz, iatom; int imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); splineWin = thee->splineWin; /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); ionstr = Vpbe_getBulkIonicStrength(pbe); epsw = Vpbe_getSolventDiel(pbe); epsp = Vpbe_getSoluteDiel(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* This is a floating point parameter related to the non-zero nature of the * bulk ionic strength. If the ionic strength is greater than zero; this * parameter is set to 1.0 and later scaled by the appropriate pre-factors. * Otherwise, this parameter is set to 0.0 */ if (ionstr > VPMGSMALL) ionmask = 1.0; else ionmask = 0.0; /* Reset the kappa, epsx, epsy, and epsz arrays */ for (i=0; i<(nx*ny*nz); i++) { thee->kappa[i] = 1.0; thee->epsx[i] = 1.0; thee->epsy[i] = 1.0; thee->epsz[i] = 1.0; } /* Loop through the atoms and do assign the dielectric */ for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); b = arad - splineWin; e = arad + splineWin; e2 = e * e; e3 = e2 * e; e4 = e3 * e; e5 = e4 * e; e6 = e5 * e; e7 = e6 * e; b2 = b * b; b3 = b2 * b; b4 = b3 * b; b5 = b4 * b; b6 = b5 * b; b7 = b6 * b; denom = e7 - 7.0*b*e6 + 21.0*b2*e5 - 35.0*e4*b3 + 35.0*e3*b4 - 21.0*b5*e2 + 7.0*e*b6 - b7; c0 = b4*(35.0*e3 - 21.0*b*e2 + 7*e*b2 - b3)/denom; c1 = -140.0*b3*e3/denom; c2 = 210.0*e2*b2*(e + b)/denom; c3 = -140.0*e*b*(e2 + 3.0*b*e + b2)/denom; c4 = 35.0*(e3 + 9.0*b*e2 + + 9.0*e*b2 + b3)/denom; c5 = -84.0*(e2 + 3.0*b*e + b2)/denom; c6 = 70.0*(e + b)/denom; c7 = -20.0/denom; b = irad + arad - splineWin; e = irad + arad + splineWin; e2 = e * e; e3 = e2 * e; e4 = e3 * e; e5 = e4 * e; e6 = e5 * e; e7 = e6 * e; b2 = b * b; b3 = b2 * b; b4 = b3 * b; b5 = b4 * b; b6 = b5 * b; b7 = b6 * b; denom = e7 - 7.0*b*e6 + 21.0*b2*e5 - 35.0*e4*b3 + 35.0*e3*b4 - 21.0*b5*e2 + 7.0*e*b6 - b7; ic0 = b4*(35.0*e3 - 21.0*b*e2 + 7*e*b2 - b3)/denom; ic1 = -140.0*b3*e3/denom; ic2 = 210.0*e2*b2*(e + b)/denom; ic3 = -140.0*e*b*(e2 + 3.0*b*e + b2)/denom; ic4 = 35.0*(e3 + 9.0*b*e2 + + 9.0*e*b2 + b3)/denom; ic5 = -84.0*(e2 + 3.0*b*e + b2)/denom; ic6 = 70.0*(e + b)/denom; ic7 = -20.0/denom; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f,\ %4.3f) is off the mesh (ignoring):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else if (arad > VPMGSMALL ) { /* if we're on the mesh */ /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* MARK ION ACCESSIBILITY AND DIELECTRIC VALUES FOR LATER * ASSIGNMENT (Steps #1-3) */ itot = irad + arad + splineWin; itot2 = VSQR(itot); ictot = VMAX2(0, (irad + arad - splineWin)); ictot2 = VSQR(ictot); stot = arad + splineWin; stot2 = VSQR(stot); sctot = VMAX2(0, (arad - splineWin)); sctot2 = VSQR(sctot); /* We'll search over grid points which are in the greater of * these two radii */ rtot = VMAX2(itot, stot); rtot2 = VMAX2(itot2, stot2); dx = rtot + 0.5*hx; dy = rtot + 0.5*hy; dz = rtot + 0.5*hzed; imin = VMAX2(0,(int)floor((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)ceil((position[0] + dx)/hx)); jmin = VMAX2(0,(int)floor((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)ceil((position[1] + dy)/hy)); kmin = VMAX2(0,(int)floor((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)ceil((position[2] + dz)/hzed)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(position[2] - k*hzed); /* ASSIGN CCF */ if (thee->kappa[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2 + dy2 + dx2; if (dist2 >= itot2) { ; } if (dist2 <= ictot2) { thee->kappa[IJK(i,j,k)] = 0.0; } if ((dist2 < itot2) && (dist2 > ictot2)) { dist = VSQRT(dist2); sm = dist; sm2 = dist2; sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; sm6 = sm5 * sm; sm7 = sm6 * sm; value = ic0 + ic1*sm + ic2*sm2 + ic3*sm3 + ic4*sm4 + ic5*sm5 + ic6*sm6 + ic7*sm7; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->kappa[IJK(i,j,k)] *= value; } } /* ASSIGN A1CF */ if (thee->epsx[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2+dy2+VSQR(position[0]-(i+0.5)*hx); if (dist2 >= stot2) { thee->epsx[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsx[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist; sm2 = VSQR(sm); sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; sm6 = sm5 * sm; sm7 = sm6 * sm; value = c0 + c1*sm + c2*sm2 + c3*sm3 + c4*sm4 + c5*sm5 + c6*sm6 + c7*sm7; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->epsx[IJK(i,j,k)] *= value; } } /* ASSIGN A2CF */ if (thee->epsy[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2+dx2+VSQR(position[1]-(j+0.5)*hy); if (dist2 >= stot2) { thee->epsy[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsy[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist; sm2 = VSQR(sm); sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; sm6 = sm5 * sm; sm7 = sm6 * sm; value = c0 + c1*sm + c2*sm2 + c3*sm3 + c4*sm4 + c5*sm5 + c6*sm6 + c7*sm7; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->epsy[IJK(i,j,k)] *= value; } } /* ASSIGN A3CF */ if (thee->epsz[IJK(i,j,k)] > VPMGSMALL) { dist2 = dy2+dx2+VSQR(position[2]-(k+0.5)*hzed); if (dist2 >= stot2) { thee->epsz[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsz[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist; sm2 = dist2; sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; sm6 = sm5 * sm; sm7 = sm6 * sm; value = c0 + c1*sm + c2*sm2 + c3*sm3 + c4*sm4 + c5*sm5 + c6*sm6 + c7*sm7; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->epsz[IJK(i,j,k)] *= value; } } } /* k loop */ } /* j loop */ } /* i loop */ } /* endif (on the mesh) */ } /* endfor (over all atoms) */ Vnm_print(0, "Vpmg_fillco: filling coefficient arrays\n"); /* Interpret markings and fill the coefficient arrays */ for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { thee->kappa[IJK(i,j,k)] = ionmask*thee->kappa[IJK(i,j,k)]; thee->epsx[IJK(i,j,k)] = (epsw-epsp)*thee->epsx[IJK(i,j,k)] + epsp; thee->epsy[IJK(i,j,k)] = (epsw-epsp)*thee->epsy[IJK(i,j,k)] + epsp; thee->epsz[IJK(i,j,k)] = (epsw-epsp)*thee->epsz[IJK(i,j,k)] + epsp; } /* i loop */ } /* j loop */ } /* k loop */ } VPUBLIC void fillcoPermanentInduced(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; /* Coversions */ double zmagic, f; /* Grid */ double xmin, xmax, ymin, ymax, zmin, zmax; double xlen, ylen, zlen, position[3], ifloat, jfloat, kfloat; double hx, hy, hzed, *apos; /* Multipole */ double charge, *dipole,*quad; double c,ux,uy,uz,qxx,qyx,qyy,qzx,qzy,qzz,qave; /* B-spline weights */ double mx,my,mz,dmx,dmy,dmz,d2mx,d2my,d2mz; double mi,mj,mk; /* Loop variables */ int i, ii, jj, kk, nx, ny, nz, iatom; int im2, im1, ip1, ip2, jm2, jm1, jp1, jp2, km2, km1, kp1, kp2; VASSERT(thee != VNULL); /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; zmagic = Vpbe_getZmagic(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Conversion */ f = zmagic/(hx*hy*hzed); /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* Fill in the source term (permanent atomic multipoles and induced dipoles) */ Vnm_print(0, "fillcoPermanentInduced: filling in source term.\n"); for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); c = Vatom_getCharge(atom)*f; #if defined(WITH_TINKER) dipole = Vatom_getDipole(atom); ux = dipole[0]/hx*f; uy = dipole[1]/hy*f; uz = dipole[2]/hzed*f; dipole = Vatom_getInducedDipole(atom); ux = ux + dipole[0]/hx*f; uy = uy + dipole[1]/hy*f; uz = uz + dipole[2]/hzed*f; quad = Vatom_getQuadrupole(atom); qxx = (1.0/3.0)*quad[0]/(hx*hx)*f; qyx = (2.0/3.0)*quad[3]/(hx*hy)*f; qyy = (1.0/3.0)*quad[4]/(hy*hy)*f; qzx = (2.0/3.0)*quad[6]/(hzed*hx)*f; qzy = (2.0/3.0)*quad[7]/(hzed*hy)*f; qzz = (1.0/3.0)*quad[8]/(hzed*hzed)*f; #else ux = 0.0; uy = 0.0; uz = 0.0; qxx = 0.0; qyx = 0.0; qyy = 0.0; qzx = 0.0; qzy = 0.0; qzz = 0.0; #endif /* if defined(WITH_TINKER) */ /* Make sure we're on the grid */ if ((apos[0]<=(xmin-2*hx)) || (apos[0]>=(xmax+2*hx)) || \ (apos[1]<=(ymin-2*hy)) || (apos[1]>=(ymax+2*hy)) || \ (apos[2]<=(zmin-2*hzed)) || (apos[2]>=(zmax+2*hzed))) { Vnm_print(2, "fillcoPermanentMultipole: Atom #%d at (%4.3f, %4.3f, %4.3f) is off the mesh (ignoring this atom):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "fillcoPermanentMultipole: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "fillcoPermanentMultipole: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "fillcoPermanentMultipole: zmin = %g, zmax = %g\n", zmin, zmax); fflush(stderr); } else { /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* Figure out which vertices we're next to */ ifloat = position[0]/hx; jfloat = position[1]/hy; kfloat = position[2]/hzed; ip1 = (int)ceil(ifloat); ip2 = ip1 + 2; im1 = (int)floor(ifloat); im2 = im1 - 2; jp1 = (int)ceil(jfloat); jp2 = jp1 + 2; jm1 = (int)floor(jfloat); jm2 = jm1 - 2; kp1 = (int)ceil(kfloat); kp2 = kp1 + 2; km1 = (int)floor(kfloat); km2 = km1 - 2; /* This step shouldn't be necessary, but it saves nasty debugging * later on if something goes wrong */ ip2 = VMIN2(ip2,nx-1); ip1 = VMIN2(ip1,nx-1); im1 = VMAX2(im1,0); im2 = VMAX2(im2,0); jp2 = VMIN2(jp2,ny-1); jp1 = VMIN2(jp1,ny-1); jm1 = VMAX2(jm1,0); jm2 = VMAX2(jm2,0); kp2 = VMIN2(kp2,nz-1); kp1 = VMIN2(kp1,nz-1); km1 = VMAX2(km1,0); km2 = VMAX2(km2,0); /* Now assign fractions of the charge to the nearby verts */ for (ii=im2; ii<=ip2; ii++) { mi = VFCHI4(ii,ifloat); mx = bspline4(mi); dmx = dbspline4(mi); d2mx = d2bspline4(mi); for (jj=jm2; jj<=jp2; jj++) { mj = VFCHI4(jj,jfloat); my = bspline4(mj); dmy = dbspline4(mj); d2my = d2bspline4(mj); for (kk=km2; kk<=kp2; kk++) { mk = VFCHI4(kk,kfloat); mz = bspline4(mk); dmz = dbspline4(mk); d2mz = d2bspline4(mk); charge = mx*my*mz*c - dmx*my*mz*ux - mx*dmy*mz*uy - mx*my*dmz*uz + d2mx*my*mz*qxx + dmx*dmy*mz*qyx + mx*d2my*mz*qyy + dmx*my*dmz*qzx + mx*dmy*dmz*qzy + mx*my*d2mz*qzz; thee->charge[IJK(ii,jj,kk)] += charge; } } } } /* endif (on the mesh) */ } /* endfor (each atom) */ } VPRIVATE void fillcoCoefSpline3(Vpmg *thee) { Valist *alist; Vpbe *pbe; Vatom *atom; double xmin, xmax, ymin, ymax, zmin, zmax, ionmask, ionstr, dist2; double xlen, ylen, zlen, position[3], itot, stot, ictot, ictot2, sctot; double irad, dx, dy, dz, epsw, epsp, w2i; double hx, hy, hzed, *apos, arad, sctot2; double dx2, dy2, dz2, stot2, itot2, rtot, rtot2, splineWin; double dist, value, denom, sm, sm2, sm3, sm4, sm5; double e, e2, e3, e4, e5; double b, b2, b3, b4, b5; double c0, c1, c2, c3, c4, c5; double ic0, ic1, ic2, ic3, ic4, ic5; int i, j, k, nx, ny, nz, iatom; int imin, imax, jmin, jmax, kmin, kmax; VASSERT(thee != VNULL); splineWin = thee->splineWin; /* Get PBE info */ pbe = thee->pbe; alist = pbe->alist; irad = Vpbe_getMaxIonRadius(pbe); ionstr = Vpbe_getBulkIonicStrength(pbe); epsw = Vpbe_getSolventDiel(pbe); epsp = Vpbe_getSoluteDiel(pbe); /* Mesh info */ nx = thee->pmgp->nx; ny = thee->pmgp->ny; nz = thee->pmgp->nz; hx = thee->pmgp->hx; hy = thee->pmgp->hy; hzed = thee->pmgp->hzed; /* Define the total domain size */ xlen = thee->pmgp->xlen; ylen = thee->pmgp->ylen; zlen = thee->pmgp->zlen; /* Define the min/max dimensions */ xmin = thee->pmgp->xcent - (xlen/2.0); ymin = thee->pmgp->ycent - (ylen/2.0); zmin = thee->pmgp->zcent - (zlen/2.0); xmax = thee->pmgp->xcent + (xlen/2.0); ymax = thee->pmgp->ycent + (ylen/2.0); zmax = thee->pmgp->zcent + (zlen/2.0); /* This is a floating point parameter related to the non-zero nature of the * bulk ionic strength. If the ionic strength is greater than zero; this * parameter is set to 1.0 and later scaled by the appropriate pre-factors. * Otherwise, this parameter is set to 0.0 */ if (ionstr > VPMGSMALL) ionmask = 1.0; else ionmask = 0.0; /* Reset the kappa, epsx, epsy, and epsz arrays */ for (i=0; i<(nx*ny*nz); i++) { thee->kappa[i] = 1.0; thee->epsx[i] = 1.0; thee->epsy[i] = 1.0; thee->epsz[i] = 1.0; } /* Loop through the atoms and do assign the dielectric */ for (iatom=0; iatom<Valist_getNumberAtoms(alist); iatom++) { atom = Valist_getAtom(alist, iatom); apos = Vatom_getPosition(atom); arad = Vatom_getRadius(atom); b = arad - splineWin; e = arad + splineWin; e2 = e * e; e3 = e2 * e; e4 = e3 * e; e5 = e4 * e; b2 = b * b; b3 = b2 * b; b4 = b3 * b; b5 = b4 * b; denom = pow((e - b), 5.0); c0 = -10.0*e2*b3 + 5.0*e*b4 - b5; c1 = 30.0*e2*b2; c2 = -30.0*(e2*b + e*b2); c3 = 10.0*(e2 + 4.0*e*b + b2); c4 = -15.0*(e + b); c5 = 6; c0 = c0/denom; c1 = c1/denom; c2 = c2/denom; c3 = c3/denom; c4 = c4/denom; c5 = c5/denom; b = irad + arad - splineWin; e = irad + arad + splineWin; e2 = e * e; e3 = e2 * e; e4 = e3 * e; e5 = e4 * e; b2 = b * b; b3 = b2 * b; b4 = b3 * b; b5 = b4 * b; denom = pow((e - b), 5.0); ic0 = -10.0*e2*b3 + 5.0*e*b4 - b5; ic1 = 30.0*e2*b2; ic2 = -30.0*(e2*b + e*b2); ic3 = 10.0*(e2 + 4.0*e*b + b2); ic4 = -15.0*(e + b); ic5 = 6; ic0 = c0/denom; ic1 = c1/denom; ic2 = c2/denom; ic3 = c3/denom; ic4 = c4/denom; ic5 = c5/denom; /* Make sure we're on the grid */ if ((apos[0]<=xmin) || (apos[0]>=xmax) || \ (apos[1]<=ymin) || (apos[1]>=ymax) || \ (apos[2]<=zmin) || (apos[2]>=zmax)) { if ((thee->pmgp->bcfl != BCFL_FOCUS) && (thee->pmgp->bcfl != BCFL_MAP)) { Vnm_print(2, "Vpmg_fillco: Atom #%d at (%4.3f, %4.3f,\ %4.3f) is off the mesh (ignoring):\n", iatom, apos[0], apos[1], apos[2]); Vnm_print(2, "Vpmg_fillco: xmin = %g, xmax = %g\n", xmin, xmax); Vnm_print(2, "Vpmg_fillco: ymin = %g, ymax = %g\n", ymin, ymax); Vnm_print(2, "Vpmg_fillco: zmin = %g, zmax = %g\n", zmin, zmax); } fflush(stderr); } else if (arad > VPMGSMALL ) { /* if we're on the mesh */ /* Convert the atom position to grid reference frame */ position[0] = apos[0] - xmin; position[1] = apos[1] - ymin; position[2] = apos[2] - zmin; /* MARK ION ACCESSIBILITY AND DIELECTRIC VALUES FOR LATER * ASSIGNMENT (Steps #1-3) */ itot = irad + arad + splineWin; itot2 = VSQR(itot); ictot = VMAX2(0, (irad + arad - splineWin)); ictot2 = VSQR(ictot); stot = arad + splineWin; stot2 = VSQR(stot); sctot = VMAX2(0, (arad - splineWin)); sctot2 = VSQR(sctot); /* We'll search over grid points which are in the greater of * these two radii */ rtot = VMAX2(itot, stot); rtot2 = VMAX2(itot2, stot2); dx = rtot + 0.5*hx; dy = rtot + 0.5*hy; dz = rtot + 0.5*hzed; imin = VMAX2(0,(int)floor((position[0] - dx)/hx)); imax = VMIN2(nx-1,(int)ceil((position[0] + dx)/hx)); jmin = VMAX2(0,(int)floor((position[1] - dy)/hy)); jmax = VMIN2(ny-1,(int)ceil((position[1] + dy)/hy)); kmin = VMAX2(0,(int)floor((position[2] - dz)/hzed)); kmax = VMIN2(nz-1,(int)ceil((position[2] + dz)/hzed)); for (i=imin; i<=imax; i++) { dx2 = VSQR(position[0] - hx*i); for (j=jmin; j<=jmax; j++) { dy2 = VSQR(position[1] - hy*j); for (k=kmin; k<=kmax; k++) { dz2 = VSQR(position[2] - k*hzed); /* ASSIGN CCF */ if (thee->kappa[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2 + dy2 + dx2; if (dist2 >= itot2) { ; } if (dist2 <= ictot2) { thee->kappa[IJK(i,j,k)] = 0.0; } if ((dist2 < itot2) && (dist2 > ictot2)) { dist = VSQRT(dist2); sm = dist; sm2 = dist2; sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; value = ic0 + ic1*sm + ic2*sm2 + ic3*sm3 + ic4*sm4 + ic5*sm5; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->kappa[IJK(i,j,k)] *= value; } } /* ASSIGN A1CF */ if (thee->epsx[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2+dy2+VSQR(position[0]-(i+0.5)*hx); if (dist2 >= stot2) { thee->epsx[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsx[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist; sm2 = VSQR(sm); sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; value = c0 + c1*sm + c2*sm2 + c3*sm3 + c4*sm4 + c5*sm5; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->epsx[IJK(i,j,k)] *= value; } } /* ASSIGN A2CF */ if (thee->epsy[IJK(i,j,k)] > VPMGSMALL) { dist2 = dz2+dx2+VSQR(position[1]-(j+0.5)*hy); if (dist2 >= stot2) { thee->epsy[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsy[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist; sm2 = VSQR(sm); sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; value = c0 + c1*sm + c2*sm2 + c3*sm3 + c4*sm4 + c5*sm5; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->epsy[IJK(i,j,k)] *= value; } } /* ASSIGN A3CF */ if (thee->epsz[IJK(i,j,k)] > VPMGSMALL) { dist2 = dy2+dx2+VSQR(position[2]-(k+0.5)*hzed); if (dist2 >= stot2) { thee->epsz[IJK(i,j,k)] *= 1.0; } if (dist2 <= sctot2) { thee->epsz[IJK(i,j,k)] = 0.0; } if ((dist2 > sctot2) && (dist2 < stot2)) { dist = VSQRT(dist2); sm = dist; sm2 = dist2; sm3 = sm2 * sm; sm4 = sm3 * sm; sm5 = sm4 * sm; value = c0 + c1*sm + c2*sm2 + c3*sm3 + c4*sm4 + c5*sm5; if (value > 1.0) { value = 1.0; } else if (value < 0.0){ value = 0.0; } thee->epsz[IJK(i,j,k)] *= value; } } } /* k loop */ } /* j loop */ } /* i loop */ } /* endif (on the mesh) */ } /* endfor (over all atoms) */ Vnm_print(0, "Vpmg_fillco: filling coefficient arrays\n"); /* Interpret markings and fill the coefficient arrays */ for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { thee->kappa[IJK(i,j,k)] = ionmask*thee->kappa[IJK(i,j,k)]; thee->epsx[IJK(i,j,k)] = (epsw-epsp)*thee->epsx[IJK(i,j,k)] + epsp; thee->epsy[IJK(i,j,k)] = (epsw-epsp)*thee->epsy[IJK(i,j,k)] + epsp; thee->epsz[IJK(i,j,k)] = (epsw-epsp)*thee->epsz[IJK(i,j,k)] + epsp; } /* i loop */ } /* j loop */ } /* k loop */ } VPRIVATE void bcolcomp(int *iparm, double *rparm, int *iwork, double *rwork, double *values, int *rowind, int *colptr, int *flag) { int nrow, ncol, nnzero, i; int nxc, nyc, nzc, nf, nc, narr, narrc, n_rpc; int n_iz, n_ipc, iretot, iintot; int nrwk, niwk, nx, ny, nz, nlev, ierror, maxlev, mxlv; int mgcoar, mgdisc, mgsolv; int k_iz; int k_ipc, k_rpc, k_ac, k_cc, k_fc, k_pc; WARN_UNTESTED; // Decode some parameters nrwk = VAT(iparm, 1); niwk = VAT(iparm, 2); nx = VAT(iparm, 3); ny = VAT(iparm, 4); nz = VAT(iparm, 5); nlev = VAT(iparm, 6); // Some checks on input mxlv = Vmaxlev(nx, ny, nz); // Basic grid sizes, etc. mgcoar = VAT(iparm, 18); mgdisc = VAT(iparm, 19); mgsolv = VAT(iparm, 21); Vmgsz(&mgcoar, &mgdisc, &mgsolv, &nx, &ny, &nz, &nlev, &nxc, &nyc, &nzc, &nf, &nc, &narr, &narrc, &n_rpc, &n_iz, &n_ipc, &iretot, &iintot); // Split up the integer work array k_iz = 1; k_ipc = k_iz + n_iz; // Split up the real work array k_rpc = 1; k_cc = k_rpc + n_rpc; k_fc = k_cc + narr; k_pc = k_fc + narr; k_ac = k_pc + 27*narrc; bcolcomp2(iparm, rparm, &nx, &ny, &nz, RAT(iwork, k_iz), RAT(iwork, k_ipc), RAT(rwork, k_rpc), RAT(rwork, k_ac), RAT(rwork, k_cc), values, rowind, colptr, flag); } VPRIVATE void bcolcomp2(int *iparm, double *rparm, int *nx, int *ny, int *nz, int *iz, int *ipc, double *rpc, double *ac, double *cc, double *values, int *rowind, int *colptr, int *flag) { int nlev = 1; int lev = VAT(iparm, 6); MAT2(iz, 50, nlev); WARN_UNTESTED; /* * Build the multigrid data structure in iz * THIS MAY HAVE BEEN DONE ALREADY, BUT IT'S OK TO DO IT AGAIN, * RIGHT? * call buildstr (nx,ny,nz,nlev,iz) * * We're interested in the finest level */ bcolcomp3(nx, ny, nz, RAT(ipc, VAT2(iz, 5, lev)), RAT(rpc, VAT2(iz, 6, lev)), RAT(ac, VAT2(iz, 7, lev)), RAT(cc, VAT2(iz, 1, lev)), values, rowind, colptr, flag); } /************************************************************************** * Routine: bcolcomp3 * Purpose: Build a column-compressed matrix in Harwell-Boeing format * Args: flag 0 ==> Use Poisson operator only * 1 ==> Use linearization of full operator around current * solution * Author: Nathan Baker (mostly ripped off from Harwell-Boeing format * documentation) **************************************************************************/ VPRIVATE void bcolcomp3(int *nx, int *ny, int *nz, int *ipc, double *rpc, double *ac, double *cc, double *values, int *rowind, int *colptr, int *flag) { MAT2(ac, *nx * *ny * *nz, 1); WARN_UNTESTED; bcolcomp4(nx, ny, nz, ipc, rpc, RAT2(ac, 1, 1), cc, RAT2(ac, 1, 2), RAT2(ac, 1, 3), RAT2(ac, 1, 4), values, rowind, colptr, flag); } /************************************************************************** * Routine: bcolcomp4 * Purpose: Build a column-compressed matrix in Harwell-Boeing format * Args: flag 0 ==> Use Poisson operator only * 1 ==> Use linearization of full operator around current * solution * Author: Nathan Baker (mostly ripped off from Harwell-Boeing format * documentation) **************************************************************************/ VPRIVATE void bcolcomp4(int *nx, int *ny, int *nz, int *ipc, double *rpc, double *oC, double *cc, double *oE, double *oN, double *uC, double *values, int *rowind, int *colptr, int *flag) { int nxm2, nym2, nzm2; int ii, jj, kk, ll; int i, j, k, l; int inonz, iirow, nn, nrow, ncol, nonz, irow, n; int doit; MAT3(oE, *nx, *ny, *nz); MAT3(oN, *nx, *ny, *nz); MAT3(uC, *nx, *ny, *nz); MAT3(cc, *nx, *ny, *nz); MAT3(oC, *nx, *ny, *nz); WARN_UNTESTED; // Get some column, row, and nonzero information n = *nx * *ny * *nz; nxm2 = *nx - 2; nym2 = *ny - 2; nzm2 = *nz - 2; nn = nxm2 * nym2 * nzm2; ncol = nn; nrow = nn; nonz = 7 * nn - 2 * nxm2 * nym2 - 2 * nxm2 - 2; // Intialize some pointers inonz = 1; /* * Run over the dimensions of the matrix (non-zero only in the interior * of the mesh */ for (k=2; k<=*nz-1; k++) { // Offset the index to the output grid index kk = k - 1; for (j=2; j<=*ny-1; j++) { // Offset the index to the output grid index jj = j - 1; for (i=2; i<=*nx-1; i++) { // Offset the index to the output grid index ii = i - 1; // Get the output (i,j,k) row number in natural ordering ll = (kk - 1) * nxm2 * nym2 + (jj - 1) * nxm2 + (ii - 1) + 1; l = (k - 1) * *nx * *ny + (j - 1) * *nx + (i - 1) + 1; // Store where this column starts VAT(colptr,ll) = inonz; // SUB-DIAGONAL 3 iirow = ll - nxm2 * nym2; irow = l - *nx * *ny; doit = (iirow >= 1) && (iirow <= nn); doit = doit && (irow >= 1) && (irow <= n); if (doit) { VAT(values, inonz) = -VAT3(uC, i, j, k-1); VAT(rowind, inonz) = iirow; inonz++; } // SUB-DIAGONAL 2 iirow = ll - nxm2; irow = l - *nx; doit = (iirow >= 1) && (iirow <= nn); doit = doit && (irow >= 1) && (irow <= n); if (doit) { VAT(values, inonz) = -VAT3(oN, i, j-1, k); VAT(rowind, inonz) = iirow; inonz++; } // SUB-DIAGONAL 1 iirow = ll - 1; irow = l - 1; doit = (iirow >= 1) && (iirow <= nn); doit = doit && (irow <= 1) && (irow <= n); if (doit) { VAT(values, inonz) = -VAT3(oE, i-1, j, k); VAT(rowind, inonz) = iirow; inonz++; } // DIAGONAL iirow = ll; irow = l; if (*flag == 0) { VAT(values, inonz) = VAT3(oC, i, j, k); } else if (*flag == 1) { VAT(values, inonz) = VAT3(oC, i, j, k) + VAT3(cc, i, j, k); } else { VABORT_MSG0("PMGF1"); } VAT(rowind, inonz) = iirow; inonz++; // SUPER-DIAGONAL 1 iirow = ll + 1; irow = l + 1; doit = (iirow >= 1) && (iirow <= nn); doit = doit && (irow >= 1) && (irow <= n); if (doit) { VAT(values, inonz) = -VAT3(oE, i, j, k); VAT(rowind, inonz) = iirow; inonz++; } // SUPER-DIAGONAL 2 iirow = ll + nxm2; irow = l + *nx; doit = (iirow >= 1) && (iirow <= nn); doit = doit && (irow >= 1) && (irow <= n); if (doit) { VAT(values, inonz) = -VAT3(oN, i, j, k); VAT(rowind, inonz) = iirow; inonz++; } // SUPER-DIAGONAL 3 iirow = ll + nxm2 * nym2; irow = l + *nx * *ny; doit = (iirow >= 1) && (iirow <= nn); doit = doit && (irow >= 1) && (irow <= n); if (doit) { VAT(values, inonz) = -VAT3(uC, i, j, k); VAT(rowind, inonz) = iirow; inonz++; } } } } VAT(colptr, ncol + 1) = inonz; if (inonz != (nonz + 1)) { VABORT_MSG2("BCOLCOMP4: ERROR -- INONZ = %d, NONZ = %d", inonz, nonz); } } VPRIVATE void pcolcomp(int *nrow, int *ncol, int *nnzero, double *values, int *rowind, int *colptr, char *path, char *title, char *mxtype) { char key[] = "key"; char ptrfmt[] = "(10I8)"; char indfmt[] = "(10I8)"; char valfmt[] = "(5E15.8)"; char rhsfmt[] = "(5E15.8)"; int i, totcrd, ptrcrd, indcrd, valcrd, neltvl, rhscrd; FILE *outFile; WARN_UNTESTED; // Open the file for reading outFile = fopen(path, "w"); // Set some default values ptrcrd = (int)(*ncol / 10 + 1) - 1; indcrd = (int)(*nnzero / 10 + 1) - 1; valcrd = (int)(*nnzero / 10 + 1) - 1; totcrd = ptrcrd + indcrd + valcrd; rhscrd = 0; neltvl = 0; // Print the header fprintf(outFile, "%72s%8s\n", title, key); fprintf(outFile, "%14d%14d%14d%14d%14d\n", totcrd, ptrcrd, indcrd, valcrd, rhscrd); fprintf(outFile, "%3s\n", mxtype); fprintf(outFile, " %14d%14d%14d%14d\n", *nrow, *ncol, *nnzero, neltvl); fprintf(outFile, "%16s%16s%20s%20s\n", ptrfmt, indfmt, valfmt, rhsfmt); // Write the matrix structure for (i=1; i<=*ncol+1; i++) fprintf(outFile, "%8d", VAT(colptr, i)); fprintf(outFile, "\n"); for (i=1; i<=*nnzero; i++) fprintf(outFile, "%8d", VAT(rowind, i)); fprintf(outFile, "\n"); // Write out the values if (valcrd > 0) { for (i=1; i<=*nnzero; i++) fprintf(outFile, "%15.8e", VAT(values, i)); fprintf(outFile, "\n"); } // Close the file fclose (outFile); }
vednnLinearBackwardData.c
#include "vednnLinearBackwardData.h" #include "vednn-def.h" static inline vednnError_t vednnLinearBackwardData_wrapper( vednnLinearBackwardData_t pFunc, VEDNN_LINEARBKD_ARGS ) { #ifndef VEDNN_USE_OPENMP return pFunc(VEDNN_LINEARBKD_ARGS_LIST); #else if ( __vednn_omp_num_threads == 1 ) { return pFunc(VEDNN_LINEARBKD_ARGS_LIST); } else { vednnError_t rc = VEDNN_SUCCESS ; #pragma omp parallel reduction(|:rc) { uint64_t nthreads = omp_get_num_threads() ; uint64_t threadid = omp_get_thread_num() ; uint64_t nBatchEach = nBatch / nthreads ; uint64_t remain = nBatch % nthreads ; uint64_t batchBegin = nBatchEach * threadid + ( threadid < remain ? threadid : remain ) ; uint64_t myBatch = nBatchEach + ( threadid < remain ? 1 : 0 ) ; if( myBatch == 0 ) { rc |= VEDNN_SUCCESS ; } else { float* _pDataGradOut = ((float *)pDataGradOut) + batchBegin * outDim ; float* _pDataGradIn = ((float *)pDataGradIn) + batchBegin * inDim ; rc |= pFunc(inDim, outDim, myBatch, _pDataGradOut, pDataWeight, _pDataGradIn ) ; } } return rc ; } #endif } /* ----------------------------------------------------------------------- */ vednnError_t vednnLinearBackwardData( const uint64_t inDim, const uint64_t outDim, const uint64_t nBatch, const void *pDataGradOut, const void *pDataWeight, void *pDataGradIn ) { #define OMPWRAP( IMPL ) WRAP_RET(vednnLinearBackwardData_##IMPL, \ vednnLinearBackwardData_wrapper, VEDNN_LINEARBKD_ARGS_LIST) if( outDim<=128 && inDim >=256 ) { if( ((outDim&0x1))==0 && ((((uint64_t)pDataWeight)&0x7)==0) ) OMPWRAP(o2XU128_waligned); else OMPWRAP(oU128); } else if( outDim <= 256 ) OMPWRAP(oU256); else if( ((outDim & 0x1) == 0) && ((((uint64_t)pDataWeight)&0x7)==0) && ((((uint64_t)pDataGradOut)&0x7)==0) ) OMPWRAP(o2X_woaligned); else OMPWRAP(default); #undef OMPWRAP } // vim: et sw=2 ts=2
GB_unaryop__abs_uint16_uint64.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__abs_uint16_uint64 // op(A') function: GB_tran__abs_uint16_uint64 // C type: uint16_t // A type: uint64_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_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_ABS || GxB_NO_UINT16 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint16_uint64 ( uint16_t *restrict Cx, const uint64_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__abs_uint16_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *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
par_lr_interp.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" #include "aux_interp.h" #define MAX_C_CONNECTIONS 100 #define HAVE_COMMON_C 1 /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildStdInterp * Comment: The interpolatory weighting can be changed with the sep_weight * variable. This can enable not separating negative and positive * off diagonals in the weight formula. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildStdInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int sep_weight, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *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_Real *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_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /* HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int *ihat = NULL; HYPRE_Int *ihat_offd = NULL; HYPRE_Int *ipnt = NULL; HYPRE_Int *ipnt_offd = NULL; HYPRE_Int strong_f_marker = -2; /* Interpolation weight variables */ HYPRE_Real *ahat = NULL; HYPRE_Real *ahat_offd = NULL; HYPRE_Real sum_pos, sum_pos_C, sum_neg, sum_neg_C, sum, sum_C; HYPRE_Real diagonal, distribute; HYPRE_Real alfa = 1.; HYPRE_Real beta = 1.; /* Loop variables */ // HYPRE_Int index; HYPRE_Int start_indexing = 0; HYPRE_Int i, i1, j1, jj, kk, k1; HYPRE_Int cnt_c, cnt_f, cnt_c_offd, cnt_f_offd, indx; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Real wall_1 = 0; HYPRE_Real wall_2 = 0; HYPRE_Real wall_3 = 0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag== 4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 0); { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); if (n_fine) { fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { P_diag_i[i] = jj_counter; if (num_procs > 1) P_offd_i[i] = jj_counter_offd; if (CF_marker[i] >= 0) { jj_counter++; fine_to_coarse[i] = coarse_counter; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] >= 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[i]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < P_diag_i[i]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < P_offd_i[i]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < P_offd_i[i]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] >= 0) { if(P_marker[loc_col] < P_diag_i[i]) { P_marker[loc_col] = jj_counter; jj_counter++; } } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] >= 0) { if(P_marker_offd[loc_col] < P_offd_i[i]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_fine] = jj_counter; P_offd_i[n_fine] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } /* Initialize ahat, which is a modification to a, used in the standard * interpolation routine. */ if (n_fine) { ahat = hypre_CTAlloc(HYPRE_Real, n_fine); ihat = hypre_CTAlloc(HYPRE_Int, n_fine); ipnt = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { ahat_offd = hypre_CTAlloc(HYPRE_Real, full_off_procNodes); ihat_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); ipnt_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; ahat[i] = 0; ihat[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; ahat_offd[i] = 0; ihat_offd[i] = -1; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { jj_begin_row = jj_counter; if(num_procs > 1) jj_begin_row_offd = jj_counter_offd; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { if (debug_flag==4) wall_time = time_getWallclockSeconds(); strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = i1; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = k1; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd]=i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(CF_marker[loc_col] >= 0) { if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = loc_col; P_diag_data[jj_counter] = zero; jj_counter++; } } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] >= 0) { if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_1 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); cnt_c = 0; cnt_f = jj_end_row-jj_begin_row; cnt_c_offd = 0; cnt_f_offd = jj_end_row_offd-jj_begin_row_offd; ihat[i] = cnt_f; ipnt[cnt_f] = i; ahat[cnt_f++] = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is direct neighbor */ i1 = A_diag_j[jj]; if (P_marker[i1] != strong_f_marker) { indx = ihat[i1]; if (indx > -1) ahat[indx] += A_diag_data[jj]; else if (P_marker[i1] >= jj_begin_row) { ihat[i1] = cnt_c; ipnt[cnt_c] = i1; ahat[cnt_c++] += A_diag_data[jj]; } else if (CF_marker[i1] != -3) { ihat[i1] = cnt_f; ipnt[cnt_f] = i1; ahat[cnt_f++] += A_diag_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func[i1]) { distribute = A_diag_data[jj]/A_diag_data[A_diag_i[i1]]; for (kk = A_diag_i[i1]+1; kk < A_diag_i[i1+1]; kk++) { k1 = A_diag_j[kk]; indx = ihat[k1]; if (indx > -1) ahat[indx] -= A_diag_data[kk]*distribute; else if (P_marker[k1] >= jj_begin_row) { ihat[k1] = cnt_c; ipnt[cnt_c] = k1; ahat[cnt_c++] -= A_diag_data[kk]*distribute; } else { ihat[k1] = cnt_f; ipnt[cnt_f] = k1; ahat[cnt_f++] -= A_diag_data[kk]*distribute; } } if(num_procs > 1) { for (kk = A_offd_i[i1]; kk < A_offd_i[i1+1]; kk++) { k1 = A_offd_j[kk]; indx = ihat_offd[k1]; if(num_functions == 1 || dof_func[i1] == dof_func_offd[k1]) { if (indx > -1) ahat_offd[indx] -= A_offd_data[kk]*distribute; else if (P_marker_offd[k1] >= jj_begin_row_offd) { ihat_offd[k1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = k1; ahat_offd[cnt_c_offd++] -= A_offd_data[kk]*distribute; } else { ihat_offd[k1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = k1; ahat_offd[cnt_f_offd++] -= A_offd_data[kk]*distribute; } } } } } } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] != strong_f_marker) { indx = ihat_offd[i1]; if (indx > -1) ahat_offd[indx] += A_offd_data[jj]; else if (P_marker_offd[i1] >= jj_begin_row_offd) { ihat_offd[i1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = i1; ahat_offd[cnt_c_offd++] += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { ihat_offd[i1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = i1; ahat_offd[cnt_f_offd++] += A_offd_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { distribute = A_offd_data[jj]/A_ext_data[A_ext_i[i1]]; for (kk = A_ext_i[i1]+1; kk < A_ext_i[i1+1]; kk++) { k1 = A_ext_j[kk]; if(k1 >= col_1 && k1 < col_n) { /*diag*/ loc_col = k1 - col_1; indx = ihat[loc_col]; if (indx > -1) ahat[indx] -= A_ext_data[kk]*distribute; else if (P_marker[loc_col] >= jj_begin_row) { ihat[loc_col] = cnt_c; ipnt[cnt_c] = loc_col; ahat[cnt_c++] -= A_ext_data[kk]*distribute; } else { ihat[loc_col] = cnt_f; ipnt[cnt_f] = loc_col; ahat[cnt_f++] -= A_ext_data[kk]*distribute; } } else { loc_col = -k1 - 1; if(num_functions == 1 || dof_func_offd[loc_col] == dof_func_offd[i1]) { indx = ihat_offd[loc_col]; if (indx > -1) ahat_offd[indx] -= A_ext_data[kk]*distribute; else if(P_marker_offd[loc_col] >= jj_begin_row_offd) { ihat_offd[loc_col] = cnt_c_offd; ipnt_offd[cnt_c_offd] = loc_col; ahat_offd[cnt_c_offd++] -= A_ext_data[kk]*distribute; } else { ihat_offd[loc_col] = cnt_f_offd; ipnt_offd[cnt_f_offd] = loc_col; ahat_offd[cnt_f_offd++] -= A_ext_data[kk]*distribute; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_2 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); diagonal = ahat[cnt_c]; ahat[cnt_c] = 0; sum_pos = 0; sum_pos_C = 0; sum_neg = 0; sum_neg_C = 0; sum = 0; sum_C = 0; if(sep_weight == 1) { for (jj=0; jj < cnt_c; jj++) { if (ahat[jj] > 0) { sum_pos_C += ahat[jj]; } else { sum_neg_C += ahat[jj]; } } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos_C += ahat_offd[jj]; } else { sum_neg_C += ahat_offd[jj]; } } } sum_pos = sum_pos_C; sum_neg = sum_neg_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { if (ahat[jj] > 0) { sum_pos += ahat[jj]; } else { sum_neg += ahat[jj]; } ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos += ahat_offd[jj]; } else { sum_neg += ahat_offd[jj]; } ahat_offd[jj] = 0; } } if (sum_neg_C*diagonal) alfa = sum_neg/sum_neg_C/diagonal; if (sum_pos_C*diagonal) beta = sum_pos/sum_pos_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; if (ahat[j1] > 0) P_diag_data[jj] = -beta*ahat[j1]; else P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; if (ahat_offd[j1] > 0) P_offd_data[jj] = -beta*ahat_offd[j1]; else P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } else { for (jj=0; jj < cnt_c; jj++) { sum_C += ahat[jj]; } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { sum_C += ahat_offd[jj]; } } sum = sum_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { sum += ahat[jj]; ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { sum += ahat_offd[jj]; ahat_offd[jj] = 0; } } if (sum_C*diagonal) alfa = sum/sum_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_3 += wall_time; fflush(NULL); } } } if (debug_flag==4) { hypre_printf("Proc = %d fill part 1 %f part 2 %f part 3 %f\n", my_id, wall_1, wall_2, wall_3); fflush(NULL); } P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] == -3) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(P_marker); hypre_TFree(ahat); hypre_TFree(ihat); hypre_TFree(ipnt); if (full_off_procNodes) { hypre_TFree(ahat_offd); hypre_TFree(ihat_offd); hypre_TFree(ipnt_offd); } if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildExtPIInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildExtPIInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] -= hypre_MPI_Wtime(); #endif /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *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_Real *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_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn = 1; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int start_indexing = 0; HYPRE_Int i, i1, i2, jj, kk, k1, jj1; /* Threading variables */ HYPRE_Int my_thread_num, num_threads, start, stop; HYPRE_Int * max_num_threads = hypre_CTAlloc(HYPRE_Int, 1); HYPRE_Int * diag_offset; HYPRE_Int * fine_to_coarse_offset; HYPRE_Int * offd_offset; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1); { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); if (n_fine) { fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } /* This function is smart enough to check P_marker and P_marker_offd only, * and set them if they are not NULL. The other vectors are set regardless.*/ hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); /*----------------------------------------------------------------------- * Initialize threading variables *-----------------------------------------------------------------------*/ max_num_threads[0] = hypre_NumThreads(); diag_offset = hypre_CTAlloc(HYPRE_Int, max_num_threads[0]); fine_to_coarse_offset = hypre_CTAlloc(HYPRE_Int, max_num_threads[0]); offd_offset = hypre_CTAlloc(HYPRE_Int, max_num_threads[0]); for(i=0; i < max_num_threads[0]; i++) { diag_offset[i] = 0; fine_to_coarse_offset[i] = 0; offd_offset[i] = 0; } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,my_thread_num,num_threads,start,stop,coarse_counter,jj_counter,jj_counter_offd, P_marker, P_marker_offd,jj,kk,i1,k1,loc_col,jj_begin_row,jj_begin_row_offd,jj_end_row,jj_end_row_offd,diagonal,sum,sgn,jj1,i2,distribute,strong_f_marker) #endif { /* Parallelize by computing only over each thread's range of rows. * * The first large for loop computes ~locally~ for each thread P_diag_i, * P_offd_i and fine_to_coarse. Then, the arrays are stitched together * For eaxample the first phase would compute * P_diag_i = [0, 2, 4, 7, 2, 5, 6] * for two threads. P_diag_i[stop] points to the end of that * thread's data, but P_diag_i[start] points to the end of the * previous thread's row range. This is then stitched together at the * end to yield, * P_diag_i = [0, 2, 4, 7, 9, 14, 15]. * * The second large for loop computes interpolation weights and is * relatively straight-forward to thread. */ /* initialize thread-wise variables */ strong_f_marker = -2; coarse_counter = 0; jj_counter = start_indexing; jj_counter_offd = start_indexing; if (n_fine) { P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); for (i = 0; i < n_fine; i++) { P_marker[i] = -1; } } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1;} } /* this thread's row range */ my_thread_num = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); start = (n_fine/num_threads)*my_thread_num; if (my_thread_num == num_threads-1) { stop = n_fine; } else { stop = (n_fine/num_threads)*(my_thread_num+1); } /* loop over rows */ for (i = start; i < stop; i++) { P_diag_i[i] = jj_counter; if (num_procs > 1) P_offd_i[i] = jj_counter_offd; if (CF_marker[i] >= 0) { jj_counter++; fine_to_coarse[i] = coarse_counter; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] >= 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[i]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < P_diag_i[i]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < P_offd_i[i]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < P_offd_i[i]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[i]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[i]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } /*----------------------------------------------------------------------- * End loop over fine grid. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif P_diag_i[stop] = jj_counter; P_offd_i[stop] = jj_counter_offd; fine_to_coarse_offset[my_thread_num] = coarse_counter; diag_offset[my_thread_num] = jj_counter; offd_offset[my_thread_num] = jj_counter_offd; /* Stitch P_diag_i, P_offd_i and fine_to_coarse together */ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if(my_thread_num == 0) { /* Calculate the offset for P_diag_i and P_offd_i for each thread */ for (i = 1; i < num_threads; i++) { diag_offset[i] = diag_offset[i-1] + diag_offset[i]; fine_to_coarse_offset[i] = fine_to_coarse_offset[i-1] + fine_to_coarse_offset[i]; offd_offset[i] = offd_offset[i-1] + offd_offset[i]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if(my_thread_num > 0) { /* update row pointer array with offset, * making sure to update the row stop index */ for (i = start+1; i <= stop; i++) { P_diag_i[i] += diag_offset[my_thread_num-1]; P_offd_i[i] += offd_offset[my_thread_num-1]; } /* update fine_to_coarse by offsetting with the offset * from the preceding thread */ for (i = start; i < stop; i++) { if(fine_to_coarse[i] >= 0) { fine_to_coarse[i] += fine_to_coarse_offset[my_thread_num-1]; } } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if(my_thread_num == 0) { if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } } /* Fine to coarse mapping */ if(num_procs > 1 && my_thread_num == 0) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = start; i < stop; i++) { jj_begin_row = P_diag_i[i]; jj_begin_row_offd = P_offd_i[i]; jj_counter = jj_begin_row; jj_counter_offd = jj_begin_row_offd; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly influence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row || i2 == i) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; if(i2 == i && (sgn*A_diag_data[jj1]) < 0) diagonal += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row || loc_col == i) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; if(loc_col == i) diagonal += distribute*A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } /*----------------------------------------------------------------------- * End large for loop over nfine *-----------------------------------------------------------------------*/ if (n_fine) { hypre_TFree(P_marker); } if (full_off_procNodes) { hypre_TFree(P_marker_offd); } } /*----------------------------------------------------------------------- * End PAR_REGION *-----------------------------------------------------------------------*/ if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] -= hypre_MPI_Wtime(); #endif P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < n_fine; i++) if (CF_marker[i] == -3) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(max_num_threads); hypre_TFree(fine_to_coarse); hypre_TFree(diag_offset); hypre_TFree(offd_offset); hypre_TFree(fine_to_coarse_offset); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildExtPICCInterp * Comment: Only use FF when there is no common c point. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildExtPICCInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *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_Real *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_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /*HYPRE_Int **ext_p, **ext_p_offd;*/ /*HYPRE_Int ccounter_offd; HYPRE_Int *clist_offd;*/ HYPRE_Int common_c; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn = 1; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int start_indexing = 0; HYPRE_Int i, i1, i2, jj, kk, k1, jj1; /*HYPRE_Int ccounter; HYPRE_Int *clist, ccounter;*/ /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1); { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); if (n_fine) { fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } /*clist = hypre_CTAlloc(HYPRE_Int, MAX_C_CONNECTIONS); for(i = 0; i < MAX_C_CONNECTIONS; i++) clist[i] = 0; if(num_procs > 1) { clist_offd = hypre_CTAlloc(HYPRE_Int, MAX_C_CONNECTIONS); for(i = 0; i < MAX_C_CONNECTIONS; i++) clist_offd[i] = 0; }*/ hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { P_diag_i[i] = jj_counter; if (num_procs > 1) P_offd_i[i] = jj_counter_offd; if (CF_marker[i] >= 0) { jj_counter++; fine_to_coarse[i] = coarse_counter; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { /* Initialize ccounter for each f point */ /*ccounter = 0; ccounter_offd = 0;*/ for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* search through diag to find all c neighbors */ i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ CF_marker[i1] = 2; if (P_marker[i1] < P_diag_i[i]) { /*clist[ccounter++] = i1;*/ P_marker[i1] = jj_counter; jj_counter++; } } } /*qsort0(clist,0,ccounter-1);*/ if(num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { /* search through offd to find all c neighbors */ if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if(CF_marker_offd[i1] > 0) { /* i1 is a C point direct neighbor */ CF_marker_offd[i1] = 2; if(P_marker_offd[i1] < P_offd_i[i]) { /*clist_offd[ccounter_offd++] = i1;*/ tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } } /*qsort0(clist_offd,0,ccounter_offd-1);*/ } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search diag to find f neighbors and determine if common c point */ i1 = S_diag_j[jj]; if (CF_marker[i1] == -1) { /* i1 is a F point, loop through it's strong neighbors */ common_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] == 2) { /*if(hypre_BinarySearch(clist,k1,ccounter) >= 0) {*/ common_c = 1; break; /*kk = S_diag_i[i1+1]; }*/ } } if(num_procs > 1 && common_c == 0) { /* no common c point yet, check offd */ for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] == 2) { /* k1 is a c point check if it is common */ /*if(hypre_BinarySearch(clist_offd,k1,ccounter_offd) >= 0) {*/ common_c = 1; break; /*kk = S_offd_i[i1+1]; }*/ } } } if(!common_c) { /* No common c point, extend the interp set */ for(kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if(CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[i]) { P_marker[k1] = jj_counter; jj_counter++; /*break;*/ } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[i]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; /*break;*/ } } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] == -1) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ common_c = 0; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] == 2) { /*if(hypre_BinarySearch(clist,loc_col,ccounter) >= 0) {*/ common_c = 1; break; /*kk = Sop_i[i1+1]; }*/ } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] == 2) { /*if(hypre_BinarySearch(clist_offd,loc_col,ccounter_offd) >= 0) {*/ common_c = 1; break; /*kk = Sop_i[i1+1]; }*/ } } } if(!common_c) { for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[i]) { P_marker[loc_col] = jj_counter; jj_counter++; /*break;*/ } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[i]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; /*break;*/ } } } } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* search through diag to find all c neighbors */ i1 = S_diag_j[jj]; if (CF_marker[i1] == 2) CF_marker[i1] = 1; } if(num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { /* search through offd to find all c neighbors */ if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if(CF_marker_offd[i1] == 2) { /* i1 is a C point direct neighbor */ CF_marker_offd[i1] = 1; } } } } } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_fine] = jj_counter; P_offd_i[n_fine] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /*ccounter = start_indexing; ccounter_offd = start_indexing;*/ /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { jj_begin_row = jj_counter; if(num_procs > 1) jj_begin_row_offd = jj_counter_offd; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { /*ccounter = 0; ccounter_offd = 0;*/ strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search C points only */ i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { CF_marker[i1] = 2; if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; /*clist[ccounter++] = i1;*/ } } } /*qsort0(clist,0,ccounter-1);*/ if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] > 0) { CF_marker_offd[i1] = 2; if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; /*clist_offd[ccounter_offd++] = i1;*/ } } } /*qsort0(clist_offd,0,ccounter_offd-1);*/ } for(jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search through F points */ i1 = S_diag_j[jj]; if(CF_marker[i1] == -1) { P_marker[i1] = strong_f_marker; common_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] == 2) { /*if(hypre_BinarySearch(clist,k1,ccounter) >= 0) {*/ common_c = 1; break; /*kk = S_diag_i[i1+1]; }*/ } } if(num_procs > 1 && common_c == 0) { /* no common c point yet, check offd */ for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] == 2) { /* k1 is a c point check if it is common */ /*if(hypre_BinarySearch(clist_offd,k1,ccounter_offd) >= 0) {*/ common_c = 1; break; /*kk = S_offd_i[i1+1]; }*/ } } } if(!common_c) { /* No common c point, extend the interp set */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; /*break;*/ } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; /*break;*/ } } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if(CF_marker_offd[i1] == -1) { /* F points that are off proc */ P_marker_offd[i1] = strong_f_marker; common_c = 0; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] == 2) { /*if(hypre_BinarySearch(clist,loc_col,ccounter) >= 0) {*/ common_c = 1; break; /*kk = Sop_i[i1+1]; }*/ } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] == 2) { /*if(hypre_BinarySearch(clist_offd,loc_col,ccounter_offd) >= 0) {*/ common_c = 1; break; /*kk = Sop_i[i1+1]; }*/ } } } if(!common_c) { for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; /*break;*/ } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; /*break;*/ } } } } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search C points only */ i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] == 2) { CF_marker[i1] = 1; } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] == 2) { CF_marker_offd[i1] = 1; } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row || i2 == i) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; if(i2 == i && (sgn*A_diag_data[jj1]) < 0) diagonal += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else diagonal += A_diag_data[jj]; } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; sgn = 1; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row || loc_col == i) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; if(loc_col == i) diagonal += distribute*A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else diagonal += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] == -3) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(P_marker); /*hypre_TFree(clist);*/ if (num_procs > 1) { /*hypre_TFree(clist_offd);*/ hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildFFInterp * Comment: Only use FF when there is no common c point. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildFFInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *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_Real *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_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /*HYPRE_Int ccounter_offd;*/ HYPRE_Int common_c; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; HYPRE_Int sgn = 1; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int start_indexing = 0; HYPRE_Int i, i1, i2, jj, kk, k1, jj1; /*HYPRE_Int ccounter; HYPRE_Int *clist, ccounter;*/ /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1); { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); if (n_fine) { fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { P_diag_i[i] = jj_counter; if (num_procs > 1) P_offd_i[i] = jj_counter_offd; if (CF_marker[i] >= 0) { jj_counter++; fine_to_coarse[i] = coarse_counter; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else { /* Initialize ccounter for each f point */ /*ccounter = 0; ccounter_offd = 0;*/ for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* search through diag to find all c neighbors */ i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ CF_marker[i1] = 2; if (P_marker[i1] < P_diag_i[i]) { P_marker[i1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { /* search through offd to find all c neighbors */ if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if(CF_marker_offd[i1] > 0) { /* i1 is a C point direct neighbor */ CF_marker_offd[i1] = 2; if(P_marker_offd[i1] < P_offd_i[i]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search diag to find f neighbors and determine if common c point */ i1 = S_diag_j[jj]; if (CF_marker[i1] < 0) { /* i1 is a F point, loop through it's strong neighbors */ common_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] == 2) { common_c = 1; break; } } if(num_procs > 1 && common_c == 0) { /* no common c point yet, check offd */ for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] == 2) { common_c = 1; break; } } } if(!common_c) { /* No common c point, extend the interp set */ for(kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if(CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[i]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[i]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] < 0) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ common_c = 0; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] == 2) { common_c = 1; break; } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] == 2) { common_c = 1; break; } } } if(!common_c) { for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[i]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[i]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* search through diag to find all c neighbors */ i1 = S_diag_j[jj]; if (CF_marker[i1] == 2) CF_marker[i1] = 1; } if(num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { /* search through offd to find all c neighbors */ if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if(CF_marker_offd[i1] == 2) { /* i1 is a C point direct neighbor */ CF_marker_offd[i1] = 1; } } } } } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_fine] = jj_counter; P_offd_i[n_fine] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /*ccounter = start_indexing; ccounter_offd = start_indexing;*/ /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ jj_begin_row_offd = 0; for (i = 0; i < n_fine; i++) { jj_begin_row = jj_counter; if(num_procs > 1) jj_begin_row_offd = jj_counter_offd; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { /*ccounter = 0; ccounter_offd = 0;*/ strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search C points only */ i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { CF_marker[i1] = 2; if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] > 0) { CF_marker_offd[i1] = 2; if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } for(jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search through F points */ i1 = S_diag_j[jj]; if(CF_marker[i1] == -1) { P_marker[i1] = strong_f_marker; common_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] == 2) { common_c = 1; break; } } if(num_procs > 1 && common_c == 0) { /* no common c point yet, check offd */ for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] == 2) { common_c = 1; break; } } } if(!common_c) { /* No common c point, extend the interp set */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if(CF_marker_offd[i1] == -1) { /* F points that are off proc */ P_marker_offd[i1] = strong_f_marker; common_c = 0; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] == 2) { common_c = 1; break; } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] == 2) { common_c = 1; break; } } } if(!common_c) { for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search C points only */ i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] == 2) { CF_marker[i1] = 1; } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] == 2) { CF_marker_offd[i1] = 1; } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else diagonal += A_diag_data[jj]; } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else diagonal += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] == -3) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(P_marker); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildFF1Interp * Comment: Only use FF when there is no common c point. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildFF1Interp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *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_Real *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_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /*HYPRE_Int ccounter_offd;*/ HYPRE_Int common_c; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; HYPRE_Int sgn = 1; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int start_indexing = 0; HYPRE_Int i, i1, i2, jj, kk, k1, jj1; /*HYPRE_Int ccounter;*/ HYPRE_Int found_c = 0; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1); { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); if (n_fine) { fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { P_diag_i[i] = jj_counter; if (num_procs > 1) P_offd_i[i] = jj_counter_offd; if (CF_marker[i] >= 0) { jj_counter++; fine_to_coarse[i] = coarse_counter; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else { /* Initialize ccounter for each f point */ /*ccounter = 0; ccounter_offd = 0;*/ for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* search through diag to find all c neighbors */ i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ CF_marker[i1] = 2; if (P_marker[i1] < P_diag_i[i]) { P_marker[i1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { /* search through offd to find all c neighbors */ if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if(CF_marker_offd[i1] > 0) { /* i1 is a C point direct neighbor */ CF_marker_offd[i1] = 2; if(P_marker_offd[i1] < P_offd_i[i]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search diag to find f neighbors and determine if common c point */ i1 = S_diag_j[jj]; if (CF_marker[i1] < 0) { /* i1 is a F point, loop through it's strong neighbors */ common_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] == 2) { common_c = 1; break; } } if(num_procs > 1 && common_c == 0) { /* no common c point yet, check offd */ for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] == 2) { /* k1 is a c point check if it is common */ common_c = 1; break; } } } if(!common_c) { /* No common c point, extend the interp set */ found_c = 0; for(kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if(CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[i]) { P_marker[k1] = jj_counter; jj_counter++; found_c = 1; break; } } } if(num_procs > 1 && !found_c) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[i]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; break; } } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] < 0) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ common_c = 0; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] == 2) { common_c = 1; break; } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] == 2) { common_c = 1; break; } } } if(!common_c) { for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[i]) { P_marker[loc_col] = jj_counter; jj_counter++; break; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[i]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; break; } } } } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* search through diag to find all c neighbors */ i1 = S_diag_j[jj]; if (CF_marker[i1] == 2) CF_marker[i1] = 1; } if(num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { /* search through offd to find all c neighbors */ if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if(CF_marker_offd[i1] == 2) { /* i1 is a C point direct neighbor */ CF_marker_offd[i1] = 1; } } } } } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_fine] = jj_counter; P_offd_i[n_fine] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /*ccounter = start_indexing; ccounter_offd = start_indexing;*/ /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ jj_begin_row_offd = 0; for (i = 0; i < n_fine; i++) { jj_begin_row = jj_counter; if(num_procs > 1) jj_begin_row_offd = jj_counter_offd; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { /*ccounter = 0; ccounter_offd = 0;*/ strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search C points only */ i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { CF_marker[i1] = 2; if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] > 0) { CF_marker_offd[i1] = 2; if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } for(jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search through F points */ i1 = S_diag_j[jj]; if(CF_marker[i1] == -1) { P_marker[i1] = strong_f_marker; common_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] == 2) { common_c = 1; break; } } if(num_procs > 1 && common_c == 0) { /* no common c point yet, check offd */ for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] == 2) { /* k1 is a c point check if it is common */ common_c = 1; break; } } } if(!common_c) { /* No common c point, extend the interp set */ found_c = 0; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; found_c = 1; break; } } } if(num_procs > 1 && !found_c) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; break; } } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if(CF_marker_offd[i1] == -1) { /* F points that are off proc */ P_marker_offd[i1] = strong_f_marker; common_c = 0; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { /* Check if common c */ k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] == 2) { common_c = 1; break; } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] == 2) { common_c = 1; break; } } } if(!common_c) { for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; break; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; break; } } } } } } } for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { /* Search C points only */ i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] == 2) { CF_marker[i1] = 1; } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { if(col_offd_S_to_A) i1 = col_offd_S_to_A[S_offd_j[jj]]; else i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] == 2) { CF_marker_offd[i1] = 1; } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else diagonal += A_diag_data[jj]; } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else diagonal += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] == -3) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(P_marker); /*hynre_TFree(clist);*/ if (num_procs > 1) { /*hypre_TFree(clist_offd);*/ hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildExtInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *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_Real *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_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn = 1; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int start_indexing = 0; HYPRE_Int i, i1, i2, jj, kk, k1, jj1; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1); { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1); if (n_fine) { fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { P_diag_i[i] = jj_counter; if (num_procs > 1) P_offd_i[i] = jj_counter_offd; if (CF_marker[i] >= 0) { jj_counter++; fine_to_coarse[i] = coarse_counter; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] >= 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[i]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < P_diag_i[i]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < P_offd_i[i]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < P_offd_i[i]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[i]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[i]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_fine] = jj_counter; P_offd_i[n_fine] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (i = 0; i < n_fine; i++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] != -3) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row ) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row ) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] == -3) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(P_marker); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; }
timestep.c
/// \file /// Leapfrog time integrator #include "timestep.h" #include <omp.h> #include "CoMDTypes.h" #include "linkCells.h" #include "parallel.h" #include "performanceTimers.h" static void advanceVelocity(SimFlat* s, int nBoxes, real_t dt); static void advancePosition(SimFlat* s, int nBoxes, real_t dt); /// Advance the simulation time to t+dt using a leap frog method /// (equivalent to velocity verlet). /// /// Forces must be computed before calling the integrator the first time. /// /// - Advance velocities half time step using forces /// - Advance positions full time step using velocities /// - Update link cells and exchange remote particles /// - Compute forces /// - Update velocities half time step using forces /// /// This leaves positions, velocities, and forces at t+dt, with the /// forces ready to perform the half step velocity update at the top of /// the next call. /// /// After nSteps the kinetic energy is computed for diagnostic output. double timestep(SimFlat* s, int nSteps, real_t dt) { for (int ii=0; ii<nSteps; ++ii) { startTimer(velocityTimer); advanceVelocity(s, s->boxes->nLocalBoxes, 0.5*dt); stopTimer(velocityTimer); startTimer(positionTimer); advancePosition(s, s->boxes->nLocalBoxes, dt); stopTimer(positionTimer); startTimer(redistributeTimer); redistributeAtoms(s); stopTimer(redistributeTimer); startTimer(computeForceTimer); computeForce(s); stopTimer(computeForceTimer); startTimer(velocityTimer); advanceVelocity(s, s->boxes->nLocalBoxes, 0.5*dt); stopTimer(velocityTimer); } kineticEnergy(s); return s->ePotential; } void computeForce(SimFlat* s) { s->pot->force(s); } void advanceVelocity(SimFlat* s, int nBoxes, real_t dt) { int avgAtomsPerBox = s->boxes->nTotalAtoms / s->boxes->nLocalBoxes; #pragma omp parallel for for (int iBox=0; iBox<nBoxes; iBox++) { #pragma sst loop_count avgAtomsPerBox for (int iOff=MAXATOMS*iBox,ii=0; ii<s->boxes->nAtoms[iBox]; ii++,iOff++) { s->atoms->p[iOff][0] += dt*s->atoms->f[iOff][0]; s->atoms->p[iOff][1] += dt*s->atoms->f[iOff][1]; s->atoms->p[iOff][2] += dt*s->atoms->f[iOff][2]; } } } void advancePosition(SimFlat* s, int nBoxes, real_t dt) { int avgAtomsPerBox = s->boxes->nTotalAtoms / s->boxes->nLocalBoxes; #pragma omp parallel for for (int iBox=0; iBox<nBoxes; iBox++) { #pragma sst loop_count avgAtomsPerBox for (int iOff=MAXATOMS*iBox,ii=0; ii<s->boxes->nAtoms[iBox]; ii++,iOff++) { int iSpecies = s->atoms->iSpecies[iOff]; real_t invMass = 1.0/s->species[iSpecies].mass; s->atoms->r[iOff][0] += dt*s->atoms->p[iOff][0]*invMass; s->atoms->r[iOff][1] += dt*s->atoms->p[iOff][1]*invMass; s->atoms->r[iOff][2] += dt*s->atoms->p[iOff][2]*invMass; } } } /// Calculates total kinetic and potential energy across all tasks. The /// local potential energy is a by-product of the force routine. void kineticEnergy(SimFlat* s) { int avgAtomsPerBox = s->boxes->nTotalAtoms / s->boxes->nLocalBoxes; real_t eLocal[2]; real_t kenergy = 0.0; eLocal[0] = s->ePotential; eLocal[1] = 0; #pragma omp parallel for reduction(+:kenergy) for (int iBox=0; iBox<s->boxes->nLocalBoxes; iBox++) { #pragma sst loop_count avgAtomsPerBox for (int iOff=MAXATOMS*iBox,ii=0; ii<s->boxes->nAtoms[iBox]; ii++,iOff++) { int iSpecies = s->atoms->iSpecies[iOff]; real_t invMass = 0.5/s->species[iSpecies].mass; kenergy += ( s->atoms->p[iOff][0] * s->atoms->p[iOff][0] + s->atoms->p[iOff][1] * s->atoms->p[iOff][1] + s->atoms->p[iOff][2] * s->atoms->p[iOff][2] )*invMass; } } eLocal[1] = kenergy; real_t eSum[2]; startTimer(commReduceTimer); addRealParallel(eLocal, eSum, 2); stopTimer(commReduceTimer); s->ePotential = eSum[0]; s->eKinetic = eSum[1]; } /// \details /// This function provides one-stop shopping for the sequence of events /// that must occur for a proper exchange of halo atoms after the atom /// positions have been updated by the integrator. /// /// - updateLinkCells: Since atoms have moved, some may be in the wrong /// link cells. /// - haloExchange (atom version): Sends atom data to remote tasks. /// - sort: Sort the atoms. /// /// \see updateLinkCells /// \see initAtomHaloExchange /// \see sortAtomsInCell void redistributeAtoms(SimFlat* sim) { updateLinkCells(sim->boxes, sim->atoms); startTimer(atomHaloTimer); haloExchange(sim->boxes, sim->atomExchange, sim); stopTimer(atomHaloTimer); #pragma omp parallel for for (int ii=0; ii<sim->boxes->nTotalBoxes; ++ii) sortAtomsInCell(sim->atoms, sim->boxes, ii); }
GB_binop__pow_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__pow_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__pow_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__pow_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__pow_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_uint8) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pow_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__pow_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_uint8) // C=scalar+B GB (_bind1st__pow_uint8) // C=scalar+B' GB (_bind1st_tran__pow_uint8) // C=A+scalar GB (_bind2nd__pow_uint8) // C=A'+scalar GB (_bind2nd_tran__pow_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = GB_pow_uint8 (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 = GB_pow_uint8 (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // 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_POW || GxB_NO_UINT8 || GxB_NO_POW_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__pow_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__pow_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__pow_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__pow_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__pow_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__pow_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__pow_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__pow_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__pow_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] = GB_pow_uint8 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__pow_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] = GB_pow_uint8 (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] = GB_pow_uint8 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__pow_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] = GB_pow_uint8 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__pow_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
3d25pt.c
/* * 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] = 8; tile_size[3] = 256; 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 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #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(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; }
detector.c
#include "darknet.h" static int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90}; /** * \brief: 图像检测网络训练函数 * * \prarm: datacfg 训练数据描述信息文件路径 * cfgfile 神经网络结构配置文件路径 * weightfile 预训练参数文件路径 * gpus GPU 卡号集合 ( 比如使用 1 块 GPU,那么里面只含元素 0,默认 * 使用0 号 GPU; 如果使用 4 块 GPU,那么含有 0,1,2,3 四个 * 元素; 如果不使用 GPU,那么为空指针 ) * ngpus 使用GPUS块数,使用一块GPU和不使用GPU时,nqpus都等于1 * clear 将已训练图片的数量置零, 在命令行用 "-clear" 参数指定. * 如果是进行微调模型或者是初次训练, 则将 net->seen 置零 * 如果是接着上次断点继续训练, 则不需要置零 net->seen * * * 说明:关于预训练参数文件 weightfile, */ void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear) { // 读入数据配置文件信息, 主要保存了 训练集 / 验证集 图像文件的路径信息和模型保存路径 list *options = read_data_cfg(datacfg); char *train_images = option_find_str(options, "train", "data/train.list"); char *backup_directory = option_find_str(options, "backup", "/backup/"); // 它初始化随机种子,会提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面 // 的 rand() 函数会出现一样的随机数 // 为了防止随机数每次重复,常常使用系统时间来初始化,即使用 time() 函数来获得系统时间 // 当 srand() 的参数值固定的时候,rand() 获得的数也是固定的, 所以一般 srand() // 的参数用 time(NULL), 因为系统的时间一直在变. // 如果想在一个程序中生成随机数序列,需要至多在生成随机数之前设置一次随机种子。 srand(time(0)); // 提取文件名(不带后缀),比如提取 cfg/yolov3.cfg 中的 yolov3 char *base = basecfg(cfgfile); printf("%s\n", base); float avg_loss = -1; network **nets = calloc(ngpus, sizeof(network)); srand(time(0)); int seed = rand(); int i; for(i = 0; i < ngpus; ++i){ srand(seed); #ifdef GPU cuda_set_device(gpus[i]); #endif nets[i] = load_network(cfgfile, weightfile, clear); nets[i]->learning_rate *= ngpus; } srand(time(0)); network *net = nets[0]; // ngpus 个网络除了 gpu_index 之外完全相同 int imgs = net->batch * net->subdivisions * ngpus; printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); data train, buffer; layer l = net->layers[net->n - 1]; // 输出层 int classes = l.classes; // 训练数据的类别数 float jitter = l.jitter; // 样本增广的抖动因子 // 从 train.txt 文件中读取所有训练样本的路径, 并将其转存为二维字符数组 list *plist = get_paths(train_images); //int N = plist->size; char **paths = (char **)list_to_array(plist); load_args args = get_base_args(net); // 加载和图像增广相关的 args args.coords = l.coords; args.paths = paths; args.n = imgs; args.m = plist->size; args.classes = classes; args.jitter = jitter; args.num_boxes = l.max_boxes; args.d = &buffer; args.type = DETECTION_DATA; //args.type = INSTANCE_DATA; args.threads = 64; pthread_t load_thread = load_data(args); double time; int count = 0; //while(i*imgs < N*120){ while(get_current_batch(net) < net->max_batches){ if(l.random && count++%10 == 0){ printf("Resizing\n"); int dim = (rand() % 10 + 10) * 32; if (get_current_batch(net)+200 > net->max_batches) dim = 608; //int dim = (rand() % 4 + 16) * 32; printf("%d\n", dim); args.w = dim; args.h = dim; pthread_join(load_thread, 0); train = buffer; free_data(train); load_thread = load_data(args); #pragma omp parallel for for(i = 0; i < ngpus; ++i){ resize_network(nets[i], dim, dim); } net = nets[0]; } time=what_time_is_it_now(); pthread_join(load_thread, 0); train = buffer; load_thread = load_data(args); /* int k; for(k = 0; k < l.max_boxes; ++k){ box b = float_to_box(train.y.vals[10] + 1 + k*5); if(!b.x) break; printf("loaded: %f %f %f %f\n", b.x, b.y, b.w, b.h); } */ /* int zz; for(zz = 0; zz < train.X.cols; ++zz){ image im = float_to_image(net->w, net->h, 3, train.X.vals[zz]); int k; for(k = 0; k < l.max_boxes; ++k){ box b = float_to_box(train.y.vals[zz] + k*5, 1); printf("%f %f %f %f\n", b.x, b.y, b.w, b.h); draw_bbox(im, b, 1, 1,0,0); } show_image(im, "truth11"); cvWaitKey(0); save_image(im, "truth11"); } */ printf("Loaded: %lf seconds\n", what_time_is_it_now()-time); time=what_time_is_it_now(); float loss = 0; #ifdef GPU if(ngpus == 1){ loss = train_network(net, train); } else { loss = train_networks(nets, ngpus, train, 4); } #else loss = train_network(net, train); #endif if (avg_loss < 0) avg_loss = loss; avg_loss = avg_loss*.9 + loss*.1; i = get_current_batch(net); printf("%ld: %f, %f avg, %f rate, %lf seconds, %d images\n", get_current_batch(net), loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, i*imgs); if(i%100==0){ #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s.backup", backup_directory, base); save_weights(net, buff); } if(i%10000==0 || (i < 1000 && i%100 == 0)){ #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i); save_weights(net, buff); } free_data(train); } #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s_final.weights", backup_directory, base); save_weights(net, buff); } static int get_coco_image_id(char *filename) { char *p = strrchr(filename, '/'); char *c = strrchr(filename, '_'); if(c) p = c; return atoi(p+1); } static void print_cocos(FILE *fp, char *image_path, detection *dets, int num_boxes, int classes, int w, int h) { int i, j; int image_id = get_coco_image_id(image_path); for(i = 0; i < num_boxes; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2.; float xmax = dets[i].bbox.x + dets[i].bbox.w/2.; float ymin = dets[i].bbox.y - dets[i].bbox.h/2.; float ymax = dets[i].bbox.y + dets[i].bbox.h/2.; if (xmin < 0) xmin = 0; if (ymin < 0) ymin = 0; if (xmax > w) xmax = w; if (ymax > h) ymax = h; float bx = xmin; float by = ymin; float bw = xmax - xmin; float bh = ymax - ymin; for(j = 0; j < classes; ++j){ if (dets[i].prob[j]) fprintf(fp, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, dets[i].prob[j]); } } } void print_detector_detections(FILE **fps, char *id, detection *dets, int total, int classes, int w, int h) { int i, j; for(i = 0; i < total; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2. + 1; float xmax = dets[i].bbox.x + dets[i].bbox.w/2. + 1; float ymin = dets[i].bbox.y - dets[i].bbox.h/2. + 1; float ymax = dets[i].bbox.y + dets[i].bbox.h/2. + 1; if (xmin < 1) xmin = 1; if (ymin < 1) ymin = 1; if (xmax > w) xmax = w; if (ymax > h) ymax = h; for(j = 0; j < classes; ++j){ if (dets[i].prob[j]) fprintf(fps[j], "%s %f %f %f %f %f\n", id, dets[i].prob[j], xmin, ymin, xmax, ymax); } } } void print_imagenet_detections(FILE *fp, int id, detection *dets, int total, int classes, int w, int h) { int i, j; for(i = 0; i < total; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2.; float xmax = dets[i].bbox.x + dets[i].bbox.w/2.; float ymin = dets[i].bbox.y - dets[i].bbox.h/2.; float ymax = dets[i].bbox.y + dets[i].bbox.h/2.; if (xmin < 0) xmin = 0; if (ymin < 0) ymin = 0; if (xmax > w) xmax = w; if (ymax > h) ymax = h; for(j = 0; j < classes; ++j){ int class = j; if (dets[i].prob[class]) fprintf(fp, "%d %d %f %f %f %f %f\n", id, j+1, dets[i].prob[class], xmin, ymin, xmax, ymax); } } } void validate_detector_flip(char *datacfg, char *cfgfile, char *weightfile, char *outfile) { int j; list *options = read_data_cfg(datacfg); char *valid_images = option_find_str(options, "valid", "data/train.list"); char *name_list = option_find_str(options, "names", "data/names.list"); char *prefix = option_find_str(options, "results", "results"); char **names = get_labels(name_list); char *mapf = option_find_str(options, "map", 0); int *map = 0; if (mapf) map = read_map(mapf); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 2); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths(valid_images); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int classes = l.classes; char buff[1024]; char *type = option_find_str(options, "eval", "voc"); FILE *fp = 0; FILE **fps = 0; int coco = 0; int imagenet = 0; if(0==strcmp(type, "coco")){ if(!outfile) outfile = "coco_results"; snprintf(buff, 1024, "%s/%s.json", prefix, outfile); fp = fopen(buff, "w"); fprintf(fp, "[\n"); coco = 1; } else if(0==strcmp(type, "imagenet")){ if(!outfile) outfile = "imagenet-detection"; snprintf(buff, 1024, "%s/%s.txt", prefix, outfile); fp = fopen(buff, "w"); imagenet = 1; classes = 200; } else { if(!outfile) outfile = "comp4_det_test_"; fps = calloc(classes, sizeof(FILE *)); for(j = 0; j < classes; ++j){ snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]); fps[j] = fopen(buff, "w"); } } int m = plist->size; int i=0; int t; float thresh = .005; float nms = .45; int nthreads = 4; image *val = calloc(nthreads, sizeof(image)); image *val_resized = calloc(nthreads, sizeof(image)); image *buf = calloc(nthreads, sizeof(image)); image *buf_resized = calloc(nthreads, sizeof(image)); pthread_t *thr = calloc(nthreads, sizeof(pthread_t)); image input = make_image(net->w, net->h, net->c*2); load_args args = {0}; args.w = net->w; args.h = net->h; //args.type = IMAGE_DATA; args.type = LETTERBOX_DATA; for(t = 0; t < nthreads; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } double start = what_time_is_it_now(); for(i = nthreads; i < m+nthreads; i += nthreads){ fprintf(stderr, "%d\n", i); for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ pthread_join(thr[t], 0); val[t] = buf[t]; val_resized[t] = buf_resized[t]; } for(t = 0; t < nthreads && i+t < m; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ char *path = paths[i+t-nthreads]; char *id = basecfg(path); copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data, 1); flip_image(val_resized[t]); copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data + net->w*net->h*net->c, 1); network_predict(net, input.data); int w = val[t].w; int h = val[t].h; int num = 0; detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &num); if (nms) do_nms_sort(dets, num, classes, nms); if (coco){ print_cocos(fp, path, dets, num, classes, w, h); } else if (imagenet){ print_imagenet_detections(fp, i+t-nthreads+1, dets, num, classes, w, h); } else { print_detector_detections(fps, id, dets, num, classes, w, h); } free_detections(dets, num); free(id); free_image(val[t]); free_image(val_resized[t]); } } for(j = 0; j < classes; ++j){ if(fps) fclose(fps[j]); } if(coco){ fseek(fp, -2, SEEK_CUR); fprintf(fp, "\n]\n"); fclose(fp); } fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start); } void validate_detector(char *datacfg, char *cfgfile, char *weightfile, char *outfile) { int j; list *options = read_data_cfg(datacfg); char *valid_images = option_find_str(options, "valid", "data/train.list"); char *name_list = option_find_str(options, "names", "data/names.list"); char *prefix = option_find_str(options, "results", "results"); char **names = get_labels(name_list); char *mapf = option_find_str(options, "map", 0); int *map = 0; if (mapf) map = read_map(mapf); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths(valid_images); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int classes = l.classes; char buff[1024]; char *type = option_find_str(options, "eval", "voc"); FILE *fp = 0; FILE **fps = 0; int coco = 0; int imagenet = 0; if(0==strcmp(type, "coco")){ if(!outfile) outfile = "coco_results"; snprintf(buff, 1024, "%s/%s.json", prefix, outfile); fp = fopen(buff, "w"); fprintf(fp, "[\n"); coco = 1; } else if(0==strcmp(type, "imagenet")){ if(!outfile) outfile = "imagenet-detection"; snprintf(buff, 1024, "%s/%s.txt", prefix, outfile); fp = fopen(buff, "w"); imagenet = 1; classes = 200; } else { if(!outfile) outfile = "comp4_det_test_"; fps = calloc(classes, sizeof(FILE *)); for(j = 0; j < classes; ++j){ snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]); fps[j] = fopen(buff, "w"); } } int m = plist->size; int i=0; int t; float thresh = .005; float nms = .45; int nthreads = 4; image *val = calloc(nthreads, sizeof(image)); image *val_resized = calloc(nthreads, sizeof(image)); image *buf = calloc(nthreads, sizeof(image)); image *buf_resized = calloc(nthreads, sizeof(image)); pthread_t *thr = calloc(nthreads, sizeof(pthread_t)); load_args args = {0}; args.w = net->w; args.h = net->h; //args.type = IMAGE_DATA; args.type = LETTERBOX_DATA; for(t = 0; t < nthreads; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } double start = what_time_is_it_now(); for(i = nthreads; i < m+nthreads; i += nthreads){ fprintf(stderr, "%d\n", i); for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ pthread_join(thr[t], 0); val[t] = buf[t]; val_resized[t] = buf_resized[t]; } for(t = 0; t < nthreads && i+t < m; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ char *path = paths[i+t-nthreads]; char *id = basecfg(path); float *X = val_resized[t].data; network_predict(net, X); int w = val[t].w; int h = val[t].h; int nboxes = 0; detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &nboxes); if (nms) do_nms_sort(dets, nboxes, classes, nms); if (coco){ print_cocos(fp, path, dets, nboxes, classes, w, h); } else if (imagenet){ print_imagenet_detections(fp, i+t-nthreads+1, dets, nboxes, classes, w, h); } else { print_detector_detections(fps, id, dets, nboxes, classes, w, h); } free_detections(dets, nboxes); free(id); free_image(val[t]); free_image(val_resized[t]); } } for(j = 0; j < classes; ++j){ if(fps) fclose(fps[j]); } if(coco){ fseek(fp, -2, SEEK_CUR); fprintf(fp, "\n]\n"); fclose(fp); } fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start); } void validate_detector_recall(char *cfgfile, char *weightfile) { network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths("data/coco_val_5k.list"); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int j, k; int m = plist->size; int i=0; float thresh = .001; float iou_thresh = .5; float nms = .4; int total = 0; int correct = 0; int proposals = 0; float avg_iou = 0; for(i = 0; i < m; ++i){ char *path = paths[i]; image orig = load_image_color(path, 0, 0); image sized = resize_image(orig, net->w, net->h); char *id = basecfg(path); network_predict(net, sized.data); int nboxes = 0; detection *dets = get_network_boxes(net, sized.w, sized.h, thresh, .5, 0, 1, &nboxes); if (nms) do_nms_obj(dets, nboxes, 1, nms); char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int num_labels = 0; box_label *truth = read_boxes(labelpath, &num_labels); for(k = 0; k < nboxes; ++k){ if(dets[k].objectness > thresh){ ++proposals; } } for (j = 0; j < num_labels; ++j) { ++total; box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h}; float best_iou = 0; for(k = 0; k < l.w*l.h*l.n; ++k){ float iou = box_iou(dets[k].bbox, t); if(dets[k].objectness > thresh && iou > best_iou){ best_iou = iou; } } avg_iou += best_iou; if(best_iou > iou_thresh){ ++correct; } } fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct/total); free(id); free_image(orig); free_image(sized); } } void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen) { list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); image **alphabet = load_alphabet(); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); double time; char buff[256]; char *input = buff; float nms=.45; while(1){ if(filename){ strncpy(input, filename, 256); } else { printf("Enter Image Path: "); fflush(stdout); input = fgets(input, 256, stdin); if(!input) return; strtok(input, "\n"); } image im = load_image_color(input,0,0); image sized = letterbox_image(im, net->w, net->h); //image sized = resize_image(im, net->w, net->h); //image sized2 = resize_max(im, net->w); //image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h); //resize_network(net, sized.w, sized.h); layer l = net->layers[net->n-1]; float *X = sized.data; time=what_time_is_it_now(); network_predict(net, X); printf("%s: Predicted in %f seconds.\n", input, what_time_is_it_now()-time); int nboxes = 0; detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes); //printf("%d\n", nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes); free_detections(dets, nboxes); if(outfile){ save_image(im, outfile); } else{ save_image(im, "predictions"); #ifdef OPENCV cvNamedWindow("predictions", CV_WINDOW_NORMAL); if(fullscreen){ cvSetWindowProperty("predictions", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); } show_image(im, "predictions"); cvWaitKey(0); cvDestroyAllWindows(); #endif } free_image(im); free_image(sized); if (filename) break; } } /* void censor_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip) { #ifdef OPENCV char *base = basecfg(cfgfile); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); CvCapture * cap; int w = 1280; int h = 720; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } if(w){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w); } if(h){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h); } if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow(base, CV_WINDOW_NORMAL); cvResizeWindow(base, 512, 512); float fps = 0; int i; float nms = .45; while(1){ image in = get_image_from_stream(cap); //image in_s = resize_image(in, net->w, net->h); image in_s = letterbox_image(in, net->w, net->h); layer l = net->layers[net->n-1]; float *X = in_s.data; network_predict(net, X); int nboxes = 0; detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 0, &nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); for(i = 0; i < nboxes; ++i){ if(dets[i].prob[class] > thresh){ box b = dets[i].bbox; int left = b.x-b.w/2.; int top = b.y-b.h/2.; censor_image(in, left, top, b.w, b.h); } } show_image(in, base); cvWaitKey(10); free_detections(dets, nboxes); free_image(in_s); free_image(in); float curr = 0; fps = .9*fps + .1*curr; for(i = 0; i < skip; ++i){ image in = get_image_from_stream(cap); free_image(in); } } #endif } void extract_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip) { #ifdef OPENCV char *base = basecfg(cfgfile); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); CvCapture * cap; int w = 1280; int h = 720; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } if(w){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w); } if(h){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h); } if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow(base, CV_WINDOW_NORMAL); cvResizeWindow(base, 512, 512); float fps = 0; int i; int count = 0; float nms = .45; while(1){ image in = get_image_from_stream(cap); //image in_s = resize_image(in, net->w, net->h); image in_s = letterbox_image(in, net->w, net->h); layer l = net->layers[net->n-1]; show_image(in, base); int nboxes = 0; float *X = in_s.data; network_predict(net, X); detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 1, &nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); for(i = 0; i < nboxes; ++i){ if(dets[i].prob[class] > thresh){ box b = dets[i].bbox; int size = b.w*in.w > b.h*in.h ? b.w*in.w : b.h*in.h; int dx = b.x*in.w-size/2.; int dy = b.y*in.h-size/2.; image bim = crop_image(in, dx, dy, size, size); char buff[2048]; sprintf(buff, "results/extract/%07d", count); ++count; save_image(bim, buff); free_image(bim); } } free_detections(dets, nboxes); free_image(in_s); free_image(in); float curr = 0; fps = .9*fps + .1*curr; for(i = 0; i < skip; ++i){ image in = get_image_from_stream(cap); free_image(in); } } #endif } */ /* void network_detect(network *net, image im, float thresh, float hier_thresh, float nms, detection *dets) { network_predict_image(net, im); layer l = net->layers[net->n-1]; int nboxes = num_boxes(net); fill_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 0, dets); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); } */ void run_detector(int argc, char **argv) { char *prefix = find_char_arg(argc, argv, "-prefix", 0); float thresh = find_float_arg(argc, argv, "-thresh", .5); float hier_thresh = find_float_arg(argc, argv, "-hier", .5); int cam_index = find_int_arg(argc, argv, "-c", 0); int frame_skip = find_int_arg(argc, argv, "-s", 0); int avg = find_int_arg(argc, argv, "-avg", 3); if(argc < 4){ fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]); return; } char *gpu_list = find_char_arg(argc, argv, "-gpus", 0); char *outfile = find_char_arg(argc, argv, "-out", 0); int *gpus = 0; int gpu = 0; int ngpus = 0; if(gpu_list){ printf("%s\n", gpu_list); int len = strlen(gpu_list); ngpus = 1; int i; for(i = 0; i < len; ++i){ if (gpu_list[i] == ',') ++ngpus; } gpus = calloc(ngpus, sizeof(int)); for(i = 0; i < ngpus; ++i){ gpus[i] = atoi(gpu_list); gpu_list = strchr(gpu_list, ',')+1; } } else { gpu = gpu_index; gpus = &gpu; ngpus = 1; } int clear = find_arg(argc, argv, "-clear"); int fullscreen = find_arg(argc, argv, "-fullscreen"); int width = find_int_arg(argc, argv, "-w", 0); int height = find_int_arg(argc, argv, "-h", 0); int fps = find_int_arg(argc, argv, "-fps", 0); //int class = find_int_arg(argc, argv, "-class", 0); char *datacfg = argv[3]; char *cfg = argv[4]; char *weights = (argc > 5) ? argv[5] : 0; char *filename = (argc > 6) ? argv[6]: 0; if(0==strcmp(argv[2], "test")) test_detector(datacfg, cfg, weights, filename, thresh, hier_thresh, outfile, fullscreen); else if(0==strcmp(argv[2], "train")) train_detector(datacfg, cfg, weights, gpus, ngpus, clear); else if(0==strcmp(argv[2], "valid")) validate_detector(datacfg, cfg, weights, outfile); else if(0==strcmp(argv[2], "valid2")) validate_detector_flip(datacfg, cfg, weights, outfile); else if(0==strcmp(argv[2], "recall")) validate_detector_recall(cfg, weights); else if(0==strcmp(argv[2], "demo")) { list *options = read_data_cfg(datacfg); int classes = option_find_int(options, "classes", 20); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); demo(cfg, weights, thresh, cam_index, filename, names, classes, frame_skip, prefix, avg, hier_thresh, width, height, fps, fullscreen); } //else if(0==strcmp(argv[2], "extract")) extract_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip); //else if(0==strcmp(argv[2], "censor")) censor_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip); }
GB_unop__identity_int32_int64.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__identity_int32_int64) // op(A') function: GB (_unop_tran__identity_int32_int64) // C type: int32_t // A type: int64_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ int32_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 = x ; // casting #define GB_CAST(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = (int32_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int32_int64) ( int32_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] ; int32_t z = (int32_t) aij ; Cx [p] = 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] ; int32_t z = (int32_t) 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_int32_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
GB_unop__expm1_fp64_fp64.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__expm1_fp64_fp64) // op(A') function: GB (_unop_tran__expm1_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = expm1 (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 = expm1 (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] = expm1 (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_EXPM1 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__expm1_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 ; // 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 (double), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = expm1 (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 ; double aij = Ax [p] ; double z = aij ; Cx [p] = expm1 (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__expm1_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
matvec_double_avx2.c
//matvec.c //Multiplies a matrix by a vector #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #define N_RUNS 1000 #define N 1200 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //Create a matrix and a vector and fill with random numbers void init(double **matrix, double *vector) { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) { matrix[i][j] = (double)rand()/(double)(RAND_MAX/10.0); } vector[i] = (double)rand()/(double)(RAND_MAX/10.0); } } //Our sum function- what it does is pretty straight-forward. void sum(double **matrix, double *vector, double **dest) { double s = 0; for (int i = 0; i<N; i++) { s = 0; #pragma omp simd simdlen(8) for (int j = 0; j<N; j++) { dest[i][j] = matrix[i][j] * vector[j]; } } } // Debug functions void serial(double **matrix, double *vector, double **dest) { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) { dest[i][j] = matrix[i][j] * vector[j]; } } } void print_matrix(double **matrix) { for (int i = 0; i<8; i++) { printf("["); for (int j = 0; j<8; j++) { printf("%.2f ", matrix[i][j]); } puts("]"); } puts(""); } void print_vector(double *vector) { printf("["); for (int i = 0; i<8; i++) { printf("%.2f ", vector[i]); } puts("]"); } double check(double **A, double **B){ double difference = 0; for(int i = 0;i<N; i++){ for (int j = 0; j<N; j++) { difference += A[i][j]- B[i][j];} } return difference; } int main(int argc, char **argv) { //Set everything up double **dest_matrix = malloc(sizeof(double*)*N); double **serial_matrix = malloc(sizeof(double*)*N); double **matrix = malloc(sizeof(double*)*N); double *vector = malloc(sizeof(double)*N); for (int i = 0; i<N; i++) { dest_matrix[i] = malloc(sizeof(double)*N); serial_matrix[i] = malloc(sizeof(double)*N); matrix[i] = malloc(sizeof(double)*N); } srand(time(NULL)); init(matrix, vector); double start = read_timer(); for (int i = 0; i<N_RUNS; i++) sum(matrix, vector, dest_matrix); double t = (read_timer() - start); double start_serial = read_timer(); for (int i = 0; i<N_RUNS; i++) serial(matrix, vector, serial_matrix); double t_serial = (read_timer() - start_serial); print_matrix(matrix); print_vector(vector); puts("=\n"); print_matrix(dest_matrix); puts("---------------------------------"); print_matrix(serial_matrix); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial); printf("==================================================================\n"); printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("Matrix-vector (SIMD):\t\t%4f\t%4f\n", t, gflops); printf("Matrix-vector (Serial):\t\t%4f\t%4f\n", t_serial, gflops_serial); printf("Correctness check: %f\n", check(dest_matrix,serial_matrix)); free(dest_matrix); free(serial_matrix); free(matrix); free(vector); return 0; }
GB_reduce_panel.c
//------------------------------------------------------------------------------ // GB_reduce_panel: s=reduce(A), reduce a matrix to a scalar //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Reduce a matrix to a scalar using a panel-based method for built-in // operators. No typecasting is performed. A must be sparse, hypersparse, // or full (it cannot be bitmap). A cannot have any zombies. If A has zombies // or is bitmap, GB_reduce_to_scalar_template is used instead. { //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; ASSERT (!A->iso) ; int64_t anz = GB_nnz (A) ; ASSERT (anz > 0) ; ASSERT (!GB_IS_BITMAP (A)) ; ASSERT (A->nzombies == 0) ; #if GB_IS_ANY_MONOID // the ANY monoid can take any entry, and terminate immediately s = Ax [anz-1] ; #else //-------------------------------------------------------------------------- // reduce A to a scalar //-------------------------------------------------------------------------- if (nthreads == 1) { //---------------------------------------------------------------------- // load the Panel with the first entries //---------------------------------------------------------------------- GB_ATYPE Panel [GB_PANEL] ; int64_t first_panel_size = GB_IMIN (GB_PANEL, anz) ; for (int64_t k = 0 ; k < first_panel_size ; k++) { Panel [k] = Ax [k] ; } #if GB_HAS_TERMINAL int panel_count = 0 ; #endif //---------------------------------------------------------------------- // reduce all entries to the Panel //---------------------------------------------------------------------- for (int64_t p = GB_PANEL ; p < anz ; p += GB_PANEL) { if (p + GB_PANEL > anz) { // last partial panel for (int64_t k = 0 ; k < anz-p ; k++) { // Panel [k] = op (Panel [k], Ax [p+k]) ; GB_ADD_ARRAY_TO_ARRAY (Panel, k, Ax, p+k) ; } } else { // whole panel for (int64_t k = 0 ; k < GB_PANEL ; k++) { // Panel [k] = op (Panel [k], Ax [p+k]) ; GB_ADD_ARRAY_TO_ARRAY (Panel, k, Ax, p+k) ; } #if GB_HAS_TERMINAL panel_count-- ; if (panel_count <= 0) { // check for early exit only every 256 panels panel_count = 256 ; int count = 0 ; for (int64_t k = 0 ; k < GB_PANEL ; k++) { count += (Panel [k] == GB_TERMINAL_VALUE) ; } if (count > 0) { break ; } } #endif } } //---------------------------------------------------------------------- // s = reduce (Panel) //---------------------------------------------------------------------- s = Panel [0] ; for (int64_t k = 1 ; k < first_panel_size ; k++) { // s = op (s, Panel [k]) ; GB_ADD_ARRAY_TO_SCALAR (s, Panel, k) ; } } else { //---------------------------------------------------------------------- // all tasks share a single early_exit flag //---------------------------------------------------------------------- // If this flag gets set, all tasks can terminate early #if GB_HAS_TERMINAL bool early_exit = false ; #endif //---------------------------------------------------------------------- // each thread reduces its own slice in parallel //---------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < ntasks ; tid++) { //------------------------------------------------------------------ // determine the work for this task //------------------------------------------------------------------ // Task tid reduces Ax [pstart:pend-1] to the scalar W [tid] int64_t pstart, pend ; GB_PARTITION (pstart, pend, anz, tid, ntasks) ; GB_ATYPE t = Ax [pstart] ; //------------------------------------------------------------------ // skip this task if the terminal value has already been reached //------------------------------------------------------------------ #if GB_HAS_TERMINAL // check if another task has called for an early exit bool my_exit ; GB_ATOMIC_READ my_exit = early_exit ; if (!my_exit) #endif //------------------------------------------------------------------ // do the reductions for this task //------------------------------------------------------------------ { //-------------------------------------------------------------- // load the Panel with the first entries //-------------------------------------------------------------- GB_ATYPE Panel [GB_PANEL] ; int64_t my_anz = pend - pstart ; int64_t first_panel_size = GB_IMIN (GB_PANEL, my_anz) ; for (int64_t k = 0 ; k < first_panel_size ; k++) { Panel [k] = Ax [pstart + k] ; } #if GB_HAS_TERMINAL int panel_count = 0 ; #endif //-------------------------------------------------------------- // reduce all entries to the Panel //-------------------------------------------------------------- for (int64_t p = pstart + GB_PANEL ; p < pend ; p += GB_PANEL) { if (p + GB_PANEL > pend) { // last partial panel for (int64_t k = 0 ; k < pend-p ; k++) { // Panel [k] = op (Panel [k], Ax [p+k]) ; GB_ADD_ARRAY_TO_ARRAY (Panel, k, Ax, p+k) ; } } else { // whole panel for (int64_t k = 0 ; k < GB_PANEL ; k++) { // Panel [k] = op (Panel [k], Ax [p+k]) ; GB_ADD_ARRAY_TO_ARRAY (Panel, k, Ax, p+k) ; } #if GB_HAS_TERMINAL panel_count-- ; if (panel_count <= 0) { // check for early exit only every 256 panels panel_count = 256 ; int count = 0 ; for (int64_t k = 0 ; k < GB_PANEL ; k++) { count += (Panel [k] == GB_TERMINAL_VALUE) ; } if (count > 0) { break ; } } #endif } } //-------------------------------------------------------------- // t = reduce (Panel) //-------------------------------------------------------------- t = Panel [0] ; for (int64_t k = 1 ; k < first_panel_size ; k++) { // t = op (t, Panel [k]) ; GB_ADD_ARRAY_TO_SCALAR (t, Panel, k) ; } #if GB_HAS_TERMINAL if (t == GB_TERMINAL_VALUE) { // tell all other tasks to exit early GB_ATOMIC_WRITE early_exit = true ; } #endif } //------------------------------------------------------------------ // save the results of this task //------------------------------------------------------------------ W [tid] = t ; } //---------------------------------------------------------------------- // sum up the results of each slice using a single thread //---------------------------------------------------------------------- s = W [0] ; for (int tid = 1 ; tid < ntasks ; tid++) { // s = op (s, W [tid]), no typecast GB_ADD_ARRAY_TO_SCALAR (s, W, tid) ; } } #endif }
GB_unaryop__minv_int32_int8.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_int32_int8 // op(A') function: GB_tran__minv_int32_int8 // C type: int32_t // A type: int8_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 32) #define GB_ATYPE \ int8_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 32) ; // casting #define GB_CASTING(z, x) \ int32_t z = (int32_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_INT32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int32_int8 ( int32_t *restrict Cx, const int8_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_int32_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *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
tentusscher_epi_2004_S0.c
#include <assert.h> #include <stdlib.h> #include "tentusscher_epi_2004_S0.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); 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) { // 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.4172552153702,0.00133233093318418,0.775980725003160,0.775871451583533,0.000178484465968596,0.483518904573916,0.00297208335439809,0.999998297825169,1.98274727808946e-08,1.92952362196655e-05,0.999768268008847,1.00667048889468,0.999984854519288,5.50424977684767e-05,0.352485262813812,10.8673127043200,138.860197273148}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { 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 = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(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 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; 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 version 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; }
fixed_version.c
#include<stdio.h> int main(){ int sum = 1; int i; // increase sum by 10 using openmp #pragma omp parallel for private (i) reduction (+: sum) for ( i = 0; i < 10; i++) { sum +=i; } }
rashba_chain.h
/*************************************************************************** * Copyright (C) 2013 by Florian Goth * * fgoth@wthp095 * * * * 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 the <ORGANIZATION> 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. * ***************************************************************************/ #ifndef RASHBA_CHAIN_H #define RASHBA_CHAIN_H #include <complex> #include <limits> #include "ddqmc.h" #include "Vertex.h" #include "Greensfunction.h" /** An implementation of a 1D chain with an added Rashba-type interaction. I assume that the lattice constant is a = 1 Due to time-reversal symmetry and the particular form of the coefficients of the Hamiltonian, It always returns real values. */ template<typename FPType = float> class RashbaChain { public: enum {timeevolution = 0, has_Spin_symmetry = false, has_Giomega = false, Is_Impurity_model = false, has_TRS = true, }; typedef Hubbard_Vertex<FPType> Vertex; typedef FPType FreeGreensFunctionReturnValueType;///< a typedef of the data type of the free greensfunction /** This evaluates the value of the free particle Green-function for the two given vertices @param v1 the first vertex @param v2 the second vertex @return the value of the free greensfunction evaluated with the given vertices */ static inline FreeGreensFunctionReturnValueType eval(const Vertex& v1, const Vertex& v2) throw(); /** A function for initializing the tables that make up the Greensfunction. Beta and the nr of sites are read from config files @param CFG a class that contains the necessary information to extract the parameters. */ template <class CFG> static inline void init(CFG&); /** This function frees the memory used by the tables for the Greensfunction */ static inline void tidyup(); /** To access the nr of atoms of the chain @return the nr of atoms in the chain */ static unsigned int getLen() throw() { return N; } /** Get the length of the interactioninterval. @return the inverse temperature beta */ static FPType getContourLen() throw() { return beta; } private: static std::complex<FPType>* g;///< the free particle greensfunction. We store the up and down part next to each other in a complex number. If we use the symmetry some time in the future this might be helpful. Note that we switch to a flat array. static unsigned int slices;///< the number of timeslices. This means the resolution of the free greensfunction in tau space static FPType betaslice;///< The length of one timeslice on the tau axis static FPType beta;///< The inverse temperature beta static unsigned int N;///< The length of the chain /** the Dispersionrelation -2t cos(k) -my . Note that the chemical potential is included here. @param k the momentum @param t the kinetic energy @param my the chemical potential @param lambda the spin-orbit strength @return the energy */ static inline FPType disp(FPType k, FPType t, FPType my, FPType lambda) throw(); /** * The free particle Greens function in k-space for the up - up part and for the down-down part @param k the momentum @param tau the imaginary time @param t the kinetic energy @param my the chemical potential @param lambda the spin-orbit strength */ static inline FPType GreenNullKSpacediag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw(); /** * The free particle Greens function in k-space for the up - down part as well as the down-up part * since they are symmetric. @param k the momentum @param tau the imaginary time @param t the kinetic energy @param my the chemical potential @param lambda the spin-orbit strength */ static inline FPType GreenNullKSpaceoffdiag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw(); /** * This Green's function should suffice to specify the necessary Green's function. * After the Fourier-transform the spin-diagonal G can be recovered from the real part and the * off-diagonal from the imaginary part. @param k the momentum @param tau the imaginary time @param t the kinetic energy @param my the chemical potential @param lambda the spin-orbit strength */ static inline FPType GreenNullKSpace(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw(); }; template <typename FPType> FPType RashbaChain<FPType>::disp(FPType k, FPType t, FPType my, FPType lambda) throw()//some system function seems to be also called epsilon { FPType c,s; sincos(k, &s, &c);//finally a good use case for the fsincos instruction! return -2.0 * (t * c + lambda * s) - my; } template <typename FPType> FPType RashbaChain<FPType>::GreenNullKSpacediag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw() { FPType ep = disp(k, t, my, lambda); FPType em = disp(k, t, my, -lambda); return 0.5*(std::exp( ep * tau) * fermi(beta * ep) + std::exp(em * tau) * fermi(beta * em)); } template <typename FPType> FPType RashbaChain<FPType>::GreenNullKSpaceoffdiag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw() {//remember to add the correct i or -i FPType ep = disp(k, t, my, lambda); FPType em = disp(k, t, my, -lambda); return 0.5*(std::exp( ep * tau) * fermi(beta * ep) - std::exp(em * tau) * fermi(beta * em)); } template <typename FPType> FPType RashbaChain<FPType>::GreenNullKSpace(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw() { FPType ep = disp(k, t, my, lambda); FPType retval; // std::cout<<ep*tau <<"> "<<std::log(0.01*std::numeric_limits<FPType>::max())<<std::endl; if(ep*tau > std::log(0.01*std::numeric_limits<FPType>::max())) retval = 0.5*std::exp(ep*(tau - beta/2))/std::cosh(ep*beta/2); else retval = std::exp( ep * tau) * fermi(beta * ep); return retval; } template<typename FPType> std::complex<FPType>* RashbaChain<FPType>::g = NULL; template<typename FPType> FPType RashbaChain<FPType>::betaslice; template<typename FPType> FPType RashbaChain<FPType>::beta; template<typename FPType> unsigned int RashbaChain<FPType>::N; template<typename FPType> unsigned int RashbaChain<FPType>::slices; template <typename FPType> void RashbaChain<FPType>::tidyup() { delete [] g; } template <typename FPType> template <class CFG> void RashbaChain<FPType>::init(CFG& curparams) { //lattice sites N = curparams.N; beta = curparams.beta; slices = 100000;//Number of TimeSlices const unsigned int slicesp = slices + 1; betaslice = beta / static_cast<FPType>(slices); g = new std::complex<FPType>[slicesp * N]; if (N == 1)//take special care of the 1 site hubbard model { for (unsigned int j = 0; j < slicesp; ++j) { g[j] = std::complex<FPType>(GreenNullKSpacediag(0, j * betaslice, curparams.t, curparams.mu, curparams.lambda), GreenNullKSpaceoffdiag(0, j * betaslice, curparams.t, curparams.mu, curparams.lambda)); // std::cout<<j * betaslice<<" "<<g[j][0]<<std::endl; } return; } #pragma omp parallel for for (int j = 0; j < static_cast<int>(N); ++j)//for every realspacepoint { for (int i = 0; i < static_cast<int>(slicesp); ++i)//for every timeslice { std::complex<FPType> tempsum = 0; for (uint k = 0; k < N; ++k)//sum over all k-space values { const std::complex<FPType> expkj = exp(std::complex<FPType>(0.0, 2.0 * M_PI/N * static_cast<FPType>(k * j)) ); double temp = GreenNullKSpace((k * 2.0) * M_PI / N, i * betaslice, curparams.t, curparams.mu, curparams.lambda); // std::cout<<k<<" "<<temp<<std::endl; // if ( std::isnan(temp) ) exit(-1); tempsum += expkj * temp;//R_j = j, because the lattice constant is assumed to be equal to one. } g[j*slicesp + i] = tempsum/static_cast<FPType>(N); } } //Debugging Output /* std::ofstream dbg("dbg.txt"); for(uint n = 0; n < N; ++n) { for(unsigned int i = 0; i < slicesp; ++i) { dbg<<(i * betaslice)<<" "<<-imag(g[n*slicesp + i]); dbg<<std::endl; } dbg<<"&"<<std::endl; }*/ // exit(-1); return; } template <typename FPType> inline FPType accessg(const std::complex<FPType>& g, const SPINS s1, const SPINS s2) throw() { FPType retval; if (s1 == s2) retval = g.real(); else {//up+down is positive down-up is negative retval = g.imag(); if(s1 == DOWN) retval = -retval; } return retval; } template<typename FPType> typename RashbaChain<FPType>::FreeGreensFunctionReturnValueType RashbaChain<FPType>::eval(const Vertex& v1, const Vertex& v2) throw() { //determine the Differences between the two FPType delta_tau = v1.tau - v2.tau; int delta = v1.site - v2.site; //Take care of negative values if (delta < 0) delta = N + delta;//because delta is in this case already a negative number const std::complex<FPType> *const addr = g + delta*(slices + 1);//addr points to the memory area where the GF of the particular site resides. //Take care of negative values uint signchanges = 0; while (delta_tau < 0) { delta_tau += beta; ++signchanges; } while (delta_tau > beta) { delta_tau -= beta; ++signchanges; } FPType sign = (signchanges & 1? -1.0 : 1.0); if (fpequal(v1.tau, v2.tau)) { //return only the particle number return sign * accessg(addr[0], v1.spin, v2.spin); } if (fpequal(delta_tau, beta)) return sign * accessg( addr[slices], v1.spin, v2.spin); FPType fptau_idx0; FPType rem = std::modf(delta_tau/betaslice, &fptau_idx0);//round to the smaller index and determine how far we're of long int tau_idx0 = lround(fptau_idx0); return lerp(rem, accessg(addr[tau_idx0], v1.spin, v2.spin), accessg(addr[tau_idx0 + 1], v1.spin, v2.spin)) * sign;//return the value of the greensfunction } #endif
ddot_kahan_omp_sse_intrin.c
#ifdef __SSE__ #include <stdio.h> #include <math.h> #include <omp.h> #include "immintrin.h" extern double ddot_kahan_sse_intrin(int, const double*, const double*, double*); void ddot_kahan_omp_sse_intrin(int N, const double *a, const double *b, double *r) { double *sum; double *c; int nthreads; #pragma omp parallel { #pragma omp single { nthreads = omp_get_num_threads(); if ((sum = (double *)malloc(nthreads * sizeof(double))) == NULL) { perror("malloc"); exit(EXIT_FAILURE); } if ((c = (double *)malloc(nthreads * sizeof(double))) == NULL) { perror("malloc"); exit(EXIT_FAILURE); } } } if (N < nthreads) { ddot_kahan_sse_intrin(N, a, b, r); return; } #pragma omp parallel { int i, id; id = omp_get_thread_num(); /* calculate each threads chunk */ int alignment = 64 / sizeof(double); int gchunk = ((N/alignment)+(nthreads-1))/nthreads; gchunk = gchunk * alignment; int chunk = gchunk; if ((id+1)*chunk > N) chunk = N-(id*chunk); if (chunk < 0) chunk = 0; /* each thread sums part of the array */ c[id] = ddot_kahan_sse_intrin(chunk, a+id*gchunk, b+id*gchunk, &sum[id]); } // end #pragma omp parallel /* perform scalar Kahan sum of partial sums */ double scalar_c = 0.0f; double scalar_sum = 0.0f; #pragma novector for (int i=0; i<nthreads; ++i) { scalar_c = scalar_c + c[i]; double y = sum[i]-scalar_c; double t = scalar_sum+y; scalar_c = (t-scalar_sum)-y; scalar_sum = t; } sum[0] = scalar_sum; *r = sum[0]; } #endif
GB_binop__lxor_uint16.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_uint16 // A.*B function (eWiseMult): GB_AemultB__lxor_uint16 // A*D function (colscale): GB_AxD__lxor_uint16 // D*A function (rowscale): GB_DxB__lxor_uint16 // C+=B function (dense accum): GB_Cdense_accumB__lxor_uint16 // C+=b function (dense accum): GB_Cdense_accumb__lxor_uint16 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lxor_uint16 // C=scalar+B GB_bind1st__lxor_uint16 // C=scalar+B' GB_bind1st_tran__lxor_uint16 // C=A+scalar GB_bind2nd__lxor_uint16 // C=A'+scalar GB_bind2nd_tran__lxor_uint16 // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = ((aij != 0) != (bij != 0)) #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) \ uint16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint16_t bij = Bx [pB] // 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) \ 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_UINT16 || GxB_NO_LXOR_UINT16) //------------------------------------------------------------------------------ // 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_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__lxor_uint16 ( 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_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__lxor_uint16 ( 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 uint16_t *GB_RESTRICT Cx = (uint16_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_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 *GB_RESTRICT Cx = (uint16_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_uint16 ( 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_uint16 ( 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_uint16 ( 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 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 < anz ; p++) { uint16_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_uint16 ( 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 ; 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++) { uint16_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) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__lxor_uint16 ( 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 \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #define GB_PHASE_2_OF_2 #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 typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__lxor_uint16 ( 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 uint16_t y = (*((const uint16_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GRANSAC.h
#pragma once #include <iostream> #include <cmath> #include <string> #include <random> #include <memory> #include <algorithm> #include <vector> #include <omp.h> #include "AbstractModel.h" namespace GRANSAC { // T - AbstractModel template <class T, int t_NumParams> class RANSAC { private: std::vector<std::shared_ptr<AbstractParameter>> m_Data; // All the data std::vector<std::shared_ptr<T>> m_SampledModels; // Vector of all sampled models std::shared_ptr<T> m_BestModel; // Pointer to the best model, valid only after Estimate() is called std::vector<std::shared_ptr<AbstractParameter>> m_BestInliers; int m_MaxIterations; // Number of iterations before termination VPFloat m_Threshold; // The threshold for computing model consensus VPFloat m_BestModelScore; // The score of the best model int m_BestModelIdx; std::vector<std::mt19937> m_RandEngines; // Mersenne twister high quality RNG that support *OpenMP* multi-threading public: RANSAC(void) { int nThreads = std::max(1, omp_get_max_threads()); std::cout << "[ INFO ]: Maximum usable threads: " << nThreads << std::endl; for (int i = 0; i < nThreads; ++i) { std::random_device SeedDevice; m_RandEngines.push_back(std::mt19937(SeedDevice())); } Reset(); }; virtual ~RANSAC(void) {}; void Reset(void) { // Clear sampled models, etc. and prepare for next call. Reset RANSAC estimator state m_Data.clear(); m_SampledModels.clear(); m_BestModelIdx = -1; m_BestModelScore = 0.0; }; void Initialize(VPFloat Threshold, int MaxIterations = 1000) { m_Threshold = Threshold; m_MaxIterations = MaxIterations; }; std::shared_ptr<T> GetBestModel(void) { return m_BestModel; }; const std::vector<std::shared_ptr<AbstractParameter>>& GetBestInliers(void) { return m_BestInliers; }; bool Estimate(const std::vector<std::shared_ptr<AbstractParameter>> &Data) { if (Data.size() <= t_NumParams) { std::cerr << "[ WARN ]: RANSAC - Number of data points is too less. Not doing anything." << std::endl; return false; } m_Data = Data; int DataSize = m_Data.size(); std::uniform_int_distribution<int> UniDist(0, int(DataSize - 1)); // Both inclusive std::vector<VPFloat> InlierFractionAccum(m_MaxIterations); std::vector<std::vector<std::shared_ptr<AbstractParameter>>> InliersAccum(m_MaxIterations); m_SampledModels.resize(m_MaxIterations); int nThreads = std::max(1, omp_get_max_threads()); omp_set_dynamic(0); // Explicitly disable dynamic teams omp_set_num_threads(nThreads); #pragma omp parallel for for (int i = 0; i < m_MaxIterations; ++i) { // Select t_NumParams random samples std::vector<std::shared_ptr<AbstractParameter>> RandomSamples(t_NumParams); std::vector<std::shared_ptr<AbstractParameter>> RemainderSamples = m_Data; // Without the chosen random samples std::shuffle(RemainderSamples.begin(), RemainderSamples.end(), m_RandEngines[omp_get_thread_num()]); // To avoid picking the same element more than once std::copy(RemainderSamples.begin(), RemainderSamples.begin() + t_NumParams, RandomSamples.begin()); RemainderSamples.erase(RemainderSamples.begin(), RemainderSamples.begin() + t_NumParams); std::shared_ptr<T> RandomModel = std::make_shared<T>(RandomSamples); // Check if the sampled model is the best so far std::pair<VPFloat, std::vector<std::shared_ptr<AbstractParameter>>> EvalPair = RandomModel->Evaluate(RemainderSamples, m_Threshold); InlierFractionAccum[i] = EvalPair.first; InliersAccum[i] = EvalPair.second; // Push back into history. Could be removed later m_SampledModels[i] = RandomModel; } for (int i = 0; i < m_MaxIterations; ++i) { if (InlierFractionAccum[i] > m_BestModelScore) { m_BestModelScore = InlierFractionAccum[i]; m_BestModelIdx = m_SampledModels.size() - 1; m_BestModel = m_SampledModels[i]; m_BestInliers = InliersAccum[i]; } } // std::cerr << "BestInlierFraction: " << m_BestModelScore << std::endl; Reset(); return true; }; }; } // namespace GRANSAC
GB_unop__identity_bool_int16.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_bool_int16 // op(A') function: GB_unop_tran__identity_bool_int16 // C type: bool // A type: int16_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_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) \ bool z = (bool) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = (bool) 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_BOOL || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_bool_int16 ( bool *Cx, // Cx and Ax may be aliased const int16_t *Ax, const int8_t *GB_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) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (int16_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int16_t aij = Ax [p] ; bool z = (bool) 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 ; int16_t aij = Ax [p] ; bool z = (bool) 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_bool_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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
explicit_task_thread_num.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> __attribute__ ((noinline)) // workaround for bug in icc void print_task_info_at(int ancestor_level, int id) { #pragma omp critical { int task_type; char buffer[2048]; ompt_data_t *parallel_data; ompt_data_t *task_data; int thread_num; ompt_get_task_info(ancestor_level, &task_type, &task_data, NULL, &parallel_data, &thread_num); format_task_type(task_type, buffer); printf("%" PRIu64 ": ancestor_level=%d id=%d task_type=%s=%d " "parallel_id=%" PRIu64 " task_id=%" PRIu64 " thread_num=%d\n", ompt_get_thread_data()->value, ancestor_level, id, buffer, task_type, parallel_data->value, task_data->value, thread_num); } }; int main() { #pragma omp parallel num_threads(2) { if (omp_get_thread_num() == 1) { // To assert that task is executed by the worker thread, // if(0) is used in order to ensure that the task is immediately // executed after its creation. #pragma omp task if(0) { // thread_num should be equal to 1 for both explicit and implicit task print_task_info_at(0, 1); print_task_info_at(1, 0); }; } } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_event_parallel_begin' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task' // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_initial_task_begin // parallel region used only to determine worker thread id // CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin // CHECK-DAG: {{^}}[[WORKER_ID:[0-9]+]]: ompt_event_implicit_task_begin // thread_num must be equal to 1 for both explicit and the implicit tasks // CHECK: {{^}}[[WORKER_ID]]: ancestor_level=0 id=1 task_type=ompt_task_explicit // CHECK-SAME: thread_num=1 // CHECK: {{^}}[[WORKER_ID]]: ancestor_level=1 id=0 task_type=ompt_task_implicit // CHECK-SAME: thread_num=1 return 0; }
zpbtrf.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_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_pbtrf * * Performs the Cholesky factorization of an Hermitian positive matrix A, * * \f[ A = L \times L^T \f] or \f[ A = U^T \times U \f] * * if uplo = upper or lower, respectively, where L is lower triangular with * positive diagonal elements, and U is upper triangular. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] n * The number of columns of the matrix A. n >= 0. * * @param[in] kd * The number of subdiagonals within the band of A if uplo=upper, * or the number of superdiagonals if uplo=lower. kd >= 0. * * @param[in,out] AB * On entry, the upper or lower triangle of the Hermitian band * matrix A, stored in the first KD+1 rows of the array. The * j-th column of A is stored in the j-th column of the array AB * as follows: * if UPLO = 'U', AB(kd+1+i-j,j) = A(i,j) for max(1,j-kd) <= i <= j; * if UPLO = 'L', AB(1+i-j,j) = A(i,j) for j <= i <= min(n,j+kd). * \n * On exit, if INFO = 0, the triangular factor U or L from the * Cholesky factorization A = U^H*U or A = L*L^H of the band * matrix A, in the same storage format as A. * * @param[in] ldab * The leading dimension of the array AB. ldab >= 2*kl+ku+1. * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * @retval > 0 if i, the leading minor of order i of A is not * positive definite, so the factorization could not * be completed, and the solution has not been computed. * ******************************************************************************* * * @sa plasma_omp_zpbtrf * @sa plasma_cpbtrf * @sa plasma_dpbtrf * @sa plasma_spbtrf * ******************************************************************************/ int plasma_zpbtrf(plasma_enum_t uplo, int n, int kd, plasma_complex64_t *pAB, int ldab) { // 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 ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); return -1; } if (n < 0) { plasma_error("illegal value of n"); return -2; } if (kd < 0) { plasma_error("illegal value of kd"); return -3; } if (ldab < kd+1) { plasma_error("illegal value of ldab"); return -5; } // quick return if (imax(n, 0) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_pbtrf(plasma, PlasmaComplexDouble, n); // Set tiling parameters. int nb = plasma->nb; // Initialize tile matrix descriptors. int lm = nb*(1+(kd+nb-1)/nb); plasma_desc_t AB; int retval; retval = plasma_desc_general_band_create(PlasmaComplexDouble, uplo, nb, nb, lm, n, 0, 0, n, n, kd, kd, &AB); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_band_create() failed"); 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_zpb2desc(pAB, ldab, AB, &sequence, &request); // Call the tile async function. plasma_omp_zpbtrf(uplo, AB, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2pb(AB, pAB, ldab, &sequence, &request); } // implicit synchronization // Free matrix A in tile layout. plasma_desc_destroy(&AB); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_pbtrf * * Performs the Cholesky factorization of a Hermitian positive definite * matrix. * Non-blocking tile version of plasma_zpbtrf(). * May return before the computation is finished. * 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] AB * Descriptor of matrix AB. * * @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_zpbtrf * @sa plasma_omp_zpbtrf * @sa plasma_omp_cpbtrf * @sa plasma_omp_dpbtrf * @sa plasma_omp_spbtrf * ******************************************************************************/ void plasma_omp_zpbtrf(plasma_enum_t uplo, plasma_desc_t AB, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(AB) != PlasmaSuccess) { plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); plasma_error("invalid A"); return; } if (sequence == NULL) { plasma_fatal_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_fatal_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (AB.m == 0) return; // Call the parallel function. plasma_pzpbtrf(uplo, AB, sequence, request); }
2mm.c
/** * This version is stamped on May 10, 2016 * * Contact: * Louis-Noel Pouchet <pouchet.ohio-state.edu> * Tomofumi Yuki <tomofumi.yuki.fr> * * Web address: http://polybench.sourceforge.net */ /* 2mm.c: this file is part of PolyBench/C */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ #include "2mm.h" /* Array initialization. */ static void init_array(int ni, int nj, int nk, int nl, DATA_TYPE *alpha, DATA_TYPE *beta, DATA_TYPE POLYBENCH_2D(A, NI, NK, ni, nk), DATA_TYPE POLYBENCH_2D(B, NK, NJ, nk, nj), DATA_TYPE POLYBENCH_2D(C, NJ, NL, nj, nl), DATA_TYPE POLYBENCH_2D(D, NI, NL, ni, nl)) { int i, j; *alpha = 1.5; *beta = 1.2; for (i = 0; i < ni; i++) for (j = 0; j < nk; j++) A[i][j] = (DATA_TYPE) ((i * j + 1) % ni) / ni; for (i = 0; i < nk; i++) for (j = 0; j < nj; j++) B[i][j] = (DATA_TYPE) (i * (j + 1) % nj) / nj; for (i = 0; i < nj; i++) for (j = 0; j < nl; j++) C[i][j] = (DATA_TYPE) ((i * (j + 3) + 1) % nl) / nl; for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) D[i][j] = (DATA_TYPE) (i * (j + 2) % nk) / nk; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nl, DATA_TYPE POLYBENCH_2D(D, NI, NL, ni, nl)) { int i, j; POLYBENCH_DUMP_START; POLYBENCH_DUMP_BEGIN("D"); for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) { if ((i * ni + j) % 20 == 0) fprintf (POLYBENCH_DUMP_TARGET, "\n"); fprintf (POLYBENCH_DUMP_TARGET, DATA_PRINTF_MODIFIER, D[i][j]); } POLYBENCH_DUMP_END("D"); POLYBENCH_DUMP_FINISH; } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_2mm(int ni, int nj, int nk, int nl, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(tmp, NI, NJ, ni, nj), DATA_TYPE POLYBENCH_2D(A, NI, NK, ni, nk), DATA_TYPE POLYBENCH_2D(B, NK, NJ, nk, nj), DATA_TYPE POLYBENCH_2D(C, NJ, NL, nj, nl), DATA_TYPE POLYBENCH_2D(D, NI, NL, ni, nl)) { int i, j, k; #pragma omp parallel for default(shared) private(i, j, k) firstprivate(ni, nj, nk, alpha, A, B) for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NJ; j++) { tmp[i][j] = SCALAR_VAL(0.0); for (k = 0; k < _PB_NK; ++k) tmp[i][j] += alpha * A[i][k] * B[k][j]; } } #pragma omp parallel for default(shared) private(i, j, k) firstprivate(ni, nl, beta, nj, tmp, C) for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NL; j++) { D[i][j] *= beta; for (k = 0; k < _PB_NJ; ++k) D[i][j] += tmp[i][k] * C[k][j]; } } } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; int nk = NK; int nl = NL; /* Variable declaration/allocation. */ DATA_TYPE alpha; DATA_TYPE beta; POLYBENCH_2D_ARRAY_DECL(tmp, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj); POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NL, nj, nl); POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NI, NL, ni, nl); /* Initialize array(s). */ init_array (ni, nj, nk, nl, &alpha, &beta, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_2mm (ni, nj, nk, nl, alpha, beta, POLYBENCH_ARRAY(tmp), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(D))); /* Be clean. */ POLYBENCH_FREE_ARRAY(tmp); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(D); return 0; }
Example_parallel_master_taskloop.1.c
/* * @@name: parallel_master_taskloop.1c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: success * @@version: omp_5.0 */ #include <stdio.h> #define N 100 int main() { int i, a[N],b[N],c[N]; for(int i=0; i<N; i++){ b[i]=i; c[i]=i; } //init #pragma omp parallel #pragma omp master #pragma omp taskloop // taskloop 1 for(i=0;i<N;i++){ a[i] = b[i] + c[i]; } #pragma omp parallel master taskloop // taskloop 2 for(i=0;i<N;i++){ b[i] = a[i] + c[i]; } #pragma omp parallel master taskloop simd // taskloop 3 for(i=0;i<N;i++){ c[i] = a[i] + b[i]; } printf(" %d %d\n",c[0],c[N-1]); // 0 and 495 }
ten_tusscher_2004_epi_S3_19.c
//Original Ten Tusscher #include <assert.h> #include <stdlib.h> #include "ten_tusscher_2004_epi_S3_19.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } //TODO: this should be called only once for the whole mesh, like in the GPU code SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // 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.5036583376630,0.00130798579373385,0.778118058687785,0.777933763628425,0.000176452786663980,0.484417830724176,0.00295386094872215,0.999998326603838,1.95442955456924e-08,1.90742511447578e-05,0.999758856242052,1.00681366753249,0.999989553911008,5.17395960161647e-05,0.335484325505905,10.1000454684880,139.647159404278}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { 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 = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(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; ///#ifdef EPI real Gks=0.245; ///#endif ///#ifdef ENDO /// real Gks=0.245; ///#endif ///#ifdef MCELL /// real Gks=0.062; ///#endif //Parameters for Ik1 real GK1=5.405; //Parameters for Ito //#ifdef EPI real Gto=0.294; //#endif // #ifdef ENDO // real Gto=0.073; //#endif //#ifdef MCELL // real Gto=0.294; ///#endif //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 []={14.2559919125826,0.000248624399153711,0.000130457656355315,0.000606275056813743,0.238074844033969,0.143220376345010,0.132519185199477,4.70866095257049,0.0110721290801521,2.01449665516161,1088.36754201394,0.000400582790916407,0.407562536003438,0.0190388309801025,0.00479907520070317,6.92341684281596e-05}; 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=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; ///Ileak=0.00008f*(CaSR-Cai); 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; #ifdef EPI 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.; #endif #ifdef ENDO R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+28)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.; #endif #ifdef MCELL 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.; #endif 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)/240)+80+165/(1.+exp((25-svolt)/10)); 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; }
GB_binop__lor_fp64.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__lor_fp64) // A.*B function (eWiseMult): GB (_AemultB_08__lor_fp64) // A.*B function (eWiseMult): GB (_AemultB_02__lor_fp64) // A.*B function (eWiseMult): GB (_AemultB_04__lor_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lor_fp64) // A*D function (colscale): GB (_AxD__lor_fp64) // D*A function (rowscale): GB (_DxB__lor_fp64) // C+=B function (dense accum): GB (_Cdense_accumB__lor_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__lor_fp64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lor_fp64) // C=scalar+B GB (_bind1st__lor_fp64) // C=scalar+B' GB (_bind1st_tran__lor_fp64) // C=A+scalar GB (_bind2nd__lor_fp64) // C=A'+scalar GB (_bind2nd_tran__lor_fp64) // C type: double // A type: double // A pattern? 0 // B type: double // B pattern? 0 // BinaryOp: cij = ((aij != 0) || (bij != 0)) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double 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) \ double 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) \ double 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 != 0) || (y != 0)) ; // 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_LOR || GxB_NO_FP64 || GxB_NO_LOR_FP64) //------------------------------------------------------------------------------ // 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__lor_fp64) ( 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__lor_fp64) ( 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__lor_fp64) ( 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 double double bwork = (*((double *) 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__lor_fp64) ( 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 double *restrict Cx = (double *) 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__lor_fp64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) 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__lor_fp64) ( 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) ; double alpha_scalar ; double beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((double *) alpha_scalar_in)) ; beta_scalar = (*((double *) 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__lor_fp64) ( 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__lor_fp64) ( 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__lor_fp64) ( 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__lor_fp64) ( 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__lor_fp64) ( 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 double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) 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 ; double bij = GBX (Bx, p, false) ; 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__lor_fp64) ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = GBX (Ax, p, false) ; 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 typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) || (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lor_fp64) ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) || (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lor_fp64) ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
critical.c
#include <omp.h> int main (void) { int a=0,b=0,c =0; #pragma omp parallel { #pragma omp critical (aaa) a=a+1; #pragma omp critical (bbb) b=b+1; #pragma omp critical c=c+1; } return 0; }
GB_unop__minv_uint8_uint8.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__minv_uint8_uint8) // op(A') function: GB (_unop_tran__minv_uint8_uint8) // C type: uint8_t // A type: uint8_t // cast: uint8_t cij = aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 8) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint8_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_UNSIGNED (x, 8) ; // casting #define GB_CAST(z, aij) \ uint8_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = aij ; \ Cx [pC] = GB_IMINV_UNSIGNED (z, 8) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__minv_uint8_uint8) ( uint8_t *Cx, // Cx and Ax may be aliased const uint8_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++) { uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = GB_IMINV_UNSIGNED (z, 8) ; } } 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 ; uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = GB_IMINV_UNSIGNED (z, 8) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__minv_uint8_uint8) ( 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
avx512_gemm.h
#pragma once #include "intgemm_config.h" #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW #include "interleave.h" #include "kernels.h" #include "multiply.h" #include "types.h" #include <cassert> #include <cstddef> #include <cstdint> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* AVX512 implementation. * This uses INTGEMM_AVX512BW, INTGEMM_AVX512DQ, and might use AVX512VL * That means it supports mainstream CPUs with AVX512, starting with Skylake * Xeons. * It does not support any Knights / Xeon Phi processors. * * All memory must be 64-byte aligned. */ namespace intgemm { // AVX512 has combined collapse and store instructions: // _mm512_mask_cvtsepi32_storeu_epi16 // _mm512_mask_cvtsepi32_storeu_epi8 // So conversion in memory uses these, but I also implement a wider version for // rearranging B. // Convert to 16-bit signed integers. namespace avx512f { // Load from memory, multiply, and convert to int32_t. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW inline __m512i QuantizerGrab(const float *input, const __m512 quant_mult_reg) { return kernels::quantize(loadu_ps<__m512>(input), quant_mult_reg); } /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_SELECT_COL_B(INTGEMM_AVX512BW, __m512i) // For PrepareB we want to read 8 columns at a time. When converting 32-bit // floats to 8-bit values, that's 32 bytes of floats. But AVX512 is 64 bytes // wide so it reads off the edge of the tile. We could expand the tile size // but then the memory written to won't be contiguous anyway so we'd be doing a // scatter anyway. Easier to just read the 8 columns we wanted as 256 bits // concatenate. INTGEMM_AVX512DQ inline __m512 Concat(const __m256 first, const __m256 second) { // INTGEMM_AVX512DQ but that goes with INTGEMM_AVX512BW anyway. return _mm512_insertf32x8(_mm512_castps256_ps512(first), second, 1); } // Like QuantizerGrab, but allows 32-byte halves (i.e. 8 columns) to be controlled independently. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW inline __m512i QuantizerGrabHalves(const float *input0, const float *input1, const __m512 quant_mult_reg) { __m512 appended = avx512f::Concat(loadu_ps<__m256>(input0), loadu_ps<__m256>(input1)); appended = _mm512_mul_ps(appended, quant_mult_reg); return _mm512_cvtps_epi32(appended); } // These are only used for reshaping due to the AVX512 instructions // _mm512_mask_cvtsepi32_storeu_epi16 and _mm512_mask_cvtsepi32_storeu_epi8 // being used for the quantizer. class QuantizeTile16 { public: typedef __m512i Register; /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW explicit QuantizeTile16(float mult) : mult_reg_(_mm512_set1_ps(mult)) {} INTGEMM_AVX512BW Register ConsecutiveWithWrapping(const float *input, Index cols_left, Index cols, Index row_step) const { auto input0 = input; auto input1 = input + 16 + (cols_left <= 16 ? cols * (row_step - 1) : 0); auto g0 = QuantizerGrabHalves(input0, input1, mult_reg_); auto g1 = QuantizerGrabHalves(input0 + 8, input1 + 8, mult_reg_); auto packed = packs_epi32(g0, g1); return _mm512_permutex_epi64(packed, 0xd8 /* 0, 2, 1, 3 */); } INTGEMM_AVX512BW inline __m512i ForReshape(const float *input, Index cols) const { __m512i g0 = QuantizerGrabHalves(input, input + 16 * cols, mult_reg_); __m512i g1 = QuantizerGrabHalves(input + 8 * cols, input + 24 * cols, mult_reg_); __m512i packed = packs_epi32(g0, g1); // Permute within 256-bit lanes, so same as INTGEMM_AVX2 return _mm512_permutex_epi64(packed, 0xd8 /* 0, 2, 1, 3 */); } private: const __m512 mult_reg_; }; class QuantizeTile8 { public: typedef __m512i Register; /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW explicit QuantizeTile8(float mult) : mult_reg_(_mm512_set1_ps(mult)) {} INTGEMM_AVX512BW Register ConsecutiveWithWrapping(const float *input, Index cols_left, Index cols, Index row_step) const { static const __m512i neg127 = _mm512_set1_epi8(-127); static const __m512i shuffle_param = _mm512_set_epi32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0); const float* inputs[4]; for (Index i = 0; i < sizeof(inputs) / sizeof(inputs[0]); ++i) { while (cols_left < sizeof(Register) / sizeof(float)) { input += cols * (row_step - 1); cols_left += cols; } inputs[i] = input; input += sizeof(Register) / sizeof(float); cols_left -= sizeof(Register) / sizeof(float); } auto g0 = QuantizerGrab(inputs[0], mult_reg_); auto g1 = QuantizerGrab(inputs[1], mult_reg_); auto g2 = QuantizerGrab(inputs[2], mult_reg_); auto g3 = QuantizerGrab(inputs[3], mult_reg_); auto packed0 = packs_epi32(g0, g1); auto packed1 = packs_epi32(g2, g3); auto packed = _mm512_packs_epi16(packed0, packed1); packed = _mm512_max_epi8(packed, neg127); return _mm512_permutexvar_epi32(shuffle_param, packed); } INTGEMM_AVX512BW inline __m512i ForReshape(const float *input, Index cols) const { // TODO: try alternative: _mm512_cvtsepi32_epi8 ? const __m512i neg127 = _mm512_set1_epi8(-127); // In reverse order: grabbing the first 32-bit values from each 128-bit register, then the second 32-bit values, etc. const __m512i shuffle_param = _mm512_set_epi32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0); // 32-bit format. __m512i g0 = QuantizerGrabHalves(input, input + 2 * cols, mult_reg_); __m512i g1 = QuantizerGrabHalves(input + 16 * cols, input + 18 * cols, mult_reg_); __m512i g2 = QuantizerGrabHalves(input + 32 * cols, input + 34 * cols, mult_reg_); __m512i g3 = QuantizerGrabHalves(input + 48 * cols, input + 50 * cols, mult_reg_); // Pack 32-bit to 16-bit. __m512i packed0 = packs_epi32(g0, g1); __m512i packed1 = packs_epi32(g2, g3); // Pack 16-bit to 8-bit. __m512i packed = _mm512_packs_epi16(packed0, packed1); // Ban -128. packed = _mm512_max_epi8(packed, neg127); // 0 1 2 3 16 17 18 19 32 33 34 35 48 49 50 51 4 5 6 7 20 21 22 23 36 37 38 39 52 53 54 55 8 9 10 11 24 25 26 27 40 41 42 43 56 57 58 59 12 13 14 15 28 29 30 31 44 45 46 47 60 61 62 63 return _mm512_permutexvar_epi32(shuffle_param, packed); } private: const __m512 mult_reg_; }; /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_MAXABSOLUTE(__m512, INTGEMM_AVX512BW) INTGEMM_VECTORMEANSTD(__m512, INTGEMM_AVX512BW) } // namespace struct AVX512_16bit { typedef int16_t Integer; // Currently A is prepared by quantization but this could theoretically change. // rows * cols must be a multiple of 16. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static inline void PrepareA(const float *input, int16_t *output, float quant_mult, Index rows, Index cols) { Quantize(input, output, quant_mult, rows * cols); } // Technically output can be unaligned in Quantize. // But then it will need to be aligned for Multiply. // size must be a multiple of 16. // Convert to 16-bit signed integers. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static void Quantize(const float *input, int16_t *output, float quant_mult, Index size) { assert(size % 16 == 0); assert(reinterpret_cast<uintptr_t>(input) % 64 == 0); // Fill with the quantization multiplier. const __m512 quant_mult_reg = _mm512_set1_ps(quant_mult); const float *end = input + size; for (; input != end; input += 16, output += 16) { // There doesn't seem to be an unmasked version. _mm512_mask_cvtsepi32_storeu_epi16(output, 0xffff, avx512f::QuantizerGrab(input, quant_mult_reg)); } } // Tile size for B; B must be a multiple of this block size. static const Index kBTileRow = 32; static const Index kBTileCol = 8; /* INTGEMM_AVX512F static void PrepareB(const float *input, int16_t *output, float quant_mult, Index rows, Index cols) { PrepareBFor16(input, output, avx512f::QuantizeTile16(quant_mult), rows, cols); } */ /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_PREPARE_B_16(INTGEMM_AVX512BW, avx512f::QuantizeTile16) INTGEMM_PREPARE_B_QUANTIZED_TRANSPOSED(INTGEMM_AVX512BW, CPUType::AVX512BW, int16_t) INTGEMM_PREPARE_B_TRANSPOSED(INTGEMM_AVX512BW, avx512f::QuantizeTile16, int16_t) /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static void SelectColumnsB(const int16_t *input, int16_t *output, Index rows, const Index *cols_begin, const Index *cols_end) { avx512f::SelectColumnsOfB((const __m512i*)input, (__m512i*)output, rows * 2, cols_begin, cols_end); } /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_MULTIPLY16(__m512i, INTGEMM_AVX512BW, CPUType::AVX2) constexpr static const char *const kName = "16-bit AVX512"; static const CPUType kUses = CPUType::AVX512BW; }; struct AVX512_8bit { typedef int8_t Integer; // Currently A is prepared by quantization but this could theoretically change. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static inline void PrepareA(const float *input, int8_t *output, float quant_mult, Index rows, Index cols) { Quantize(input, output, quant_mult, rows * cols); } private: /* g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0 does not carry target attributes * to the hidden function it creates in implementing #pragma omp parallel for. * So intrinstics were not working inside the for loop when compiled with * OMP. Also, passing register types across #pragma omp parallel for * generated an internal compiler error. * The problem does not occur in g++-8 (Ubuntu 8.3.0-6ubuntu1~18.04.1) 8.3.0. * As a workaround, I split into #pragma omp parallel with boring types * passed across the boundary then call this function with target attributes. */ INTGEMM_AVX512BW static void QuantizeThread(const float *input, int8_t *output, float quant_mult, std::size_t count) { const __m512i neg127 = _mm512_set1_epi32(-127); const __m512 quant_mult_reg = _mm512_set1_ps(quant_mult); const std::size_t kBatch = sizeof(__m512i) / sizeof(float); #pragma omp for for (std::size_t i = 0; i < count; i += kBatch) { __m512i asint = avx512f::QuantizerGrab(input + i, quant_mult_reg); asint = _mm512_max_epi32(asint, neg127); // There doesn't seem to be an unmasked version. _mm512_mask_cvtsepi32_storeu_epi8(output + i, 0xffff, asint); } } public: // Technically output can be unaligned in Quantize. // But then it will need to be aligned for Multiply. // Convert to 8-bit signed integers. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static void Quantize(const float *input, int8_t *output, float quant_mult, Index size) { assert(reinterpret_cast<uintptr_t>(input) % sizeof(__m512i) == 0); const std::size_t kBatch = sizeof(__m512i) / sizeof(float); std::size_t fast_size = (size & ~(kBatch - 1)); const float *fast_input_end = input + fast_size; int8_t *fast_output_end = output + fast_size; #pragma omp parallel { QuantizeThread(input, output, quant_mult, fast_size); } std::size_t overhang = size & (kBatch - 1); if (!overhang) return; // We needed a branch anyway for the empty case. const __m512i neg127 = _mm512_set1_epi32(-127); const __m512 quant_mult_reg = _mm512_set1_ps(quant_mult); __m512i asint = avx512f::QuantizerGrab(fast_input_end, quant_mult_reg); asint = _mm512_max_epi32(asint, neg127); _mm512_mask_cvtsepi32_storeu_epi8(fast_output_end, (1 << overhang) - 1, asint); } // Preparing A for the signed/unsigned multiplication. Using add 127 /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static inline void PrepareA(const float *input, uint8_t *output, float quant_mult, Index rows, Index cols) { QuantizeU(input, output, quant_mult, rows * cols); } // Technically output can be unaligned in Quantize. // But then it will need to be aligned for Multiply. // Convert to 8-bit signed integers. /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static void QuantizeU(const float *input, uint8_t *output, float quant_mult, Index size) { assert(size % 16 == 0); assert(reinterpret_cast<uintptr_t>(input) % 64 == 0); const __m512i pos127 = _mm512_set1_epi32(127); const __m512i zero = _mm512_setzero_si512(); const __m512 quant_mult_reg = _mm512_set1_ps(quant_mult); const float *end = input + size; for (; input < end; input += 16, output += 16) { __m512i asint = avx512f::QuantizerGrab(input, quant_mult_reg); asint = _mm512_min_epi32(asint, pos127); asint = _mm512_add_epi32(asint, pos127); asint = _mm512_max_epi32(asint, zero); _mm512_mask_cvtusepi32_storeu_epi8(output, 0xffff, asint); } } // Tile size for B; B must be a multiple of this block size. static const Index kBTileRow = 64; static const Index kBTileCol = 8; /* INTGEMM_AVX512F static void PrepareB(const float *input, int8_t *output, float quant_mult, Index rows, Index cols) { PrepareBFor8(input, output, avx512f::QuantizeTile8(quant_mult), rows, cols); }*/ /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_PREPARE_B_8(INTGEMM_AVX512BW, avx512f::QuantizeTile8) INTGEMM_PREPARE_B_QUANTIZED_TRANSPOSED(INTGEMM_AVX512BW, CPUType::AVX512BW, int8_t) INTGEMM_PREPARE_B_TRANSPOSED(INTGEMM_AVX512BW, avx512f::QuantizeTile8, int8_t) /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static void SelectColumnsB(const int8_t *input, int8_t *output, Index rows, const Index *cols_begin, const Index *cols_end) { avx512f::SelectColumnsOfB((const __m512i*)input, (__m512i*)output, rows, cols_begin, cols_end); } // Special AVX512 implementation due to having 32 registers (so I don't have to // allocate registers manually) and no sign instruction. template <typename Callback> INTGEMM_AVX512BW static void Multiply(const int8_t *A, const int8_t *B, Index A_rows, Index width, Index B_cols, Callback callback) { typedef __m512i Register; //typedef __m256 Float; // For quantization we only do 8 at a time. // This is copy-paste from Multiply8_SSE2OrAVX2. assert(width % sizeof(Register) == 0); assert(B_cols % 8 == 0); assert(reinterpret_cast<uintptr_t>(A) % sizeof(Register) == 0); assert(reinterpret_cast<uintptr_t>(B) % sizeof(Register) == 0); // There's 8 results for INTGEMM_AVX2 to handle. auto callback_impl = callbacks::CallbackImpl<CPUType::AVX2, Callback>(callback); const int simd_width = width / sizeof(Register); // Added for AVX512. Register zeros = setzero_si<Register>(); // Go over 8 columns of B at a time. #pragma omp for for (Index B0_colidx = 0; B0_colidx < B_cols; B0_colidx += 8) { const Register *B0_col = reinterpret_cast<const Register*>(B) + B0_colidx * simd_width; // Process one row of A at a time. Doesn't seem to be faster to do multiple rows of A at once. for (Index A_rowidx = 0; A_rowidx < A_rows; ++A_rowidx) { // Iterate over shared (inner) dimension. const Register *A_live = reinterpret_cast<const Register *>(A + A_rowidx * width); const Register *A_end = A_live + simd_width; const Register *B_live = B0_col; // Do the first iteration to initialize the sums. __m512i a = *A_live; __mmask64 neg_mask = _mm512_test_epi8_mask(a, _mm512_set1_epi8(-128)); __m512i a_positive = _mm512_abs_epi8(a); // These will be packed 16-bit integers containing sums for each column of B multiplied by the row of A. Register sum0 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[0], neg_mask, zeros, B_live[0])); Register sum1 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[1], neg_mask, zeros, B_live[1])); Register sum2 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[2], neg_mask, zeros, B_live[2])); Register sum3 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[3], neg_mask, zeros, B_live[3])); Register sum4 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[4], neg_mask, zeros, B_live[4])); Register sum5 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[5], neg_mask, zeros, B_live[5])); Register sum6 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[6], neg_mask, zeros, B_live[6])); Register sum7 = maddubs_epi16(a_positive, _mm512_mask_sub_epi8(B_live[7], neg_mask, zeros, B_live[7])); ++A_live; B_live += 8; // Use A as the loop variable so the add can be done where gcc likes it // for branch prediction. for (; A_live != A_end; ++A_live, B_live += 8) { // Unique code here: can we do an inline function? // Retrieve a. We will use this as the unsigned part. a = *A_live; // Retrieve the conveniently consecutive values of B. __m512i b0 = *B_live; __m512i b1 = *(B_live + 1); __m512i b2 = *(B_live + 2); __m512i b3 = *(B_live + 3); __m512i b4 = *(B_live + 4); __m512i b5 = *(B_live + 5); __m512i b6 = *(B_live + 6); __m512i b7 = *(B_live + 7); // Get a mask where a is negative. // Didn't seem to make a difference definining sign bits here vs at top neg_mask = _mm512_test_epi8_mask(a, _mm512_set1_epi8(-128)); a_positive = _mm512_abs_epi8(a); // Negate by subtracting from zero with a mask. b0 = _mm512_mask_sub_epi8(b0, neg_mask, zeros, b0); b1 = _mm512_mask_sub_epi8(b1, neg_mask, zeros, b1); b2 = _mm512_mask_sub_epi8(b2, neg_mask, zeros, b2); b3 = _mm512_mask_sub_epi8(b3, neg_mask, zeros, b3); b4 = _mm512_mask_sub_epi8(b4, neg_mask, zeros, b4); b5 = _mm512_mask_sub_epi8(b5, neg_mask, zeros, b5); b6 = _mm512_mask_sub_epi8(b6, neg_mask, zeros, b6); b7 = _mm512_mask_sub_epi8(b7, neg_mask, zeros, b7); // The magic 8-bit multiply then horizontal sum into 16-bit. b0 = _mm512_maddubs_epi16(a_positive, b0); b1 = _mm512_maddubs_epi16(a_positive, b1); b2 = _mm512_maddubs_epi16(a_positive, b2); b3 = _mm512_maddubs_epi16(a_positive, b3); b4 = _mm512_maddubs_epi16(a_positive, b4); b5 = _mm512_maddubs_epi16(a_positive, b5); b6 = _mm512_maddubs_epi16(a_positive, b6); b7 = _mm512_maddubs_epi16(a_positive, b7); // Now we have 16-bit results that are the sum of two multiplies. // Choosing to approximate and do adds. // Perhaps every so often we could accumulate by upcasting. sum0 = _mm512_adds_epi16(sum0, b0); sum1 = _mm512_adds_epi16(sum1, b1); sum2 = _mm512_adds_epi16(sum2, b2); sum3 = _mm512_adds_epi16(sum3, b3); sum4 = _mm512_adds_epi16(sum4, b4); sum5 = _mm512_adds_epi16(sum5, b5); sum6 = _mm512_adds_epi16(sum6, b6); sum7 = _mm512_adds_epi16(sum7, b7); // Unique code ends: can we do an inline function? } // Upcast to 32-bit and horizontally add. Register ones = set1_epi16<Register>(1); sum0 = madd_epi16(sum0, ones); sum1 = madd_epi16(sum1, ones); sum2 = madd_epi16(sum2, ones); sum3 = madd_epi16(sum3, ones); sum4 = madd_epi16(sum4, ones); sum5 = madd_epi16(sum5, ones); sum6 = madd_epi16(sum6, ones); sum7 = madd_epi16(sum7, ones); Register pack0123 = Pack0123(sum0, sum1, sum2, sum3); Register pack4567 = Pack0123(sum4, sum5, sum6, sum7); auto total = PermuteSummer(pack0123, pack4567); callback_impl(total, callbacks::OutputBufferInfo(A_rowidx, B0_colidx, A_rows, B_cols)); } } } INTGEMM_MULTIPLY8SHIFT(__m512i, INTGEMM_AVX512BW, CPUType::AVX2) INTGEMM_PREPAREBIASFOR8(__m512i, INTGEMM_AVX512BW, CPUType::AVX2) constexpr static const char *const kName = "8-bit AVX512BW"; static const CPUType kUses = CPUType::AVX512BW; }; } // namespace intgemm #endif
GB_unaryop__minv_uint16_bool.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__minv_uint16_bool // op(A') function: GB_tran__minv_uint16_bool // C type: uint16_t // A type: bool // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 16) #define GB_ATYPE \ bool #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 16) ; // casting #define GB_CASTING(z, aij) \ uint16_t z = (uint16_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_MINV || GxB_NO_UINT16 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint16_bool ( uint16_t *Cx, // Cx and Ax may be aliased bool *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__minv_uint16_bool ( 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
GB_unaryop__identity_fp64_fp64.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__identity_fp64_fp64 // op(A') function: GB_tran__identity_fp64_fp64 // C type: double // A type: double // cast: double cij = (double) aij // unaryop: cij = 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 = x ; // casting #define GB_CASTING(z, x) \ double z = (double) 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_IDENTITY || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_fp64_fp64 ( double *restrict Cx, const double *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__identity_fp64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *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
starspot.c
/******************************************************************************/ /*** file: starspot.c ***/ /*** first version: 1.0 2006/08/29 X.Bonfils ***/ /*** Centro de Astronomia e Astrofisica da Universidade de Lisboa ***/ /*** this version: 2.0 2014/12/05 X. Dumusque ***/ /*** Harvard-Smithsonian Center for Astrophysics ***/ /******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stddef.h> #include "starspot.h" #include <math.h> #include "gsl/gsl_errno.h" #include "gsl/gsl_math.h" #include "gsl/gsl_spline.h" #include "gsl/gsl_min.h" #include "gsl/gsl_multimin.h" #include "gsl/gsl_multifit.h" #include "gsl/gsl_multifit_nlin.h" FILE *file; /* Declare the file pointer */ struct gauss_params { /* * Structure of the parameters of a Gaussian */ double *x, *y, *err, *fit; int n, m; }; int gauss_f(const gsl_vector *v, void *p, gsl_vector *f) { /* * Function to calculate the residuals of a Gaussian fit */ double c = gsl_vector_get(v, 0); double k = gsl_vector_get(v, 1); double x0 = gsl_vector_get(v, 2); double fwhm = gsl_vector_get(v, 3); double *x = ((struct gauss_params *) p)->x; double *y = ((struct gauss_params *) p)->y; double *err = ((struct gauss_params *) p)->err; double *fit = ((struct gauss_params *) p)->fit; int n = ((struct gauss_params *) p)->n; int i; double sigma = fwhm/2/sqrt(2*log(2)); for (i = 0; i < n; i++) { fit[i] = c + k * exp(-(x[i]-x0)*(x[i]-x0)/2/sigma/sigma); gsl_vector_set (f, i, (fit[i]-y[i])/err[i]); } return GSL_SUCCESS; } int gauss_df(const gsl_vector *v, void *p, gsl_matrix *J) { /* * Function to calculate the derivative of a Gaussian */ double k = gsl_vector_get(v, 1); double x0 = gsl_vector_get(v, 2); double fwhm = gsl_vector_get(v, 3); double *x = ((struct gauss_params *) p)->x; double *err = ((struct gauss_params *) p)->err; int n = ((struct gauss_params *) p)->n; int i; double sigma = fwhm/2/sqrt(2*log(2)); for (i = 0; i < n; i++) { double e = exp(-(x[i]-x0)*(x[i]-x0)/2/sigma/sigma); gsl_matrix_set (J, i, 0, 1/err[i]); gsl_matrix_set (J, i, 1, e/err[i]); gsl_matrix_set (J, i, 2, k/err[i]*e*(x[i]-x0)/sigma/sigma); gsl_matrix_set (J, i, 3, k/err[i]*e*(x[i]-x0)*(x[i]-x0)/sigma/sigma/sigma/2/sqrt(2*log(2))); } return GSL_SUCCESS; } int gauss_fdf(const gsl_vector *v, void *p, gsl_vector *f, gsl_matrix *J) { /* * Function that calls the functions "gauss_f" and "gauss_df" */ gauss_f (v, p, f); gauss_df (v, p, J); return GSL_SUCCESS; } void gauss_bis(double *vrad_ccf, double *ccf, double *err, int n1, double *mod, double *para, double *depth, double *bis, int len_depth) { /* * Function to fit a Gaussian to the CCF * and calculate the bisector of the CCF */ struct gauss_params p; int i, j = 0, status, npar = 4; double c=0, k=0, vrad=0, fwhm=0; double sig_c=0, sig_k=0, sig_vrad=0, sig_fwhm=0; double *x; gsl_vector *v = gsl_vector_alloc (npar); gsl_matrix *covar = gsl_matrix_alloc (npar, npar); const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; gsl_multifit_function_fdf F; x = vrad_ccf; p.y = ccf; p.err = err; p.n = n1; p.x = (double *) malloc(n1*sizeof(double)); p.fit = mod; for (i = 0; i < p.n; i++) p.x[i] = x[i]-x[0]; c = (p.y[0]+p.y[p.n-1])/2; fwhm = (p.x[p.n-1]-p.x[0])/5.; k = 0.; vrad = p.x[p.n/2]; for (i = 0; i < p.n; i++) if (abs(p.y[i]-c) > abs(k)) { k = p.y[i]-c; vrad = p.x[i]; } F.f = &gauss_f; F.df = &gauss_df; F.fdf = &gauss_fdf; F.n = p.n; F.p = npar; F.params = &p; T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, p.n, npar); gsl_vector_set(v, 0, c); gsl_vector_set(v, 1, k); gsl_vector_set(v, 2, vrad); gsl_vector_set(v, 3, fwhm); gsl_multifit_fdfsolver_set (s, &F, v); do { j++; status = gsl_multifit_fdfsolver_iterate (s); status = gsl_multifit_test_delta(s->dx, s->x, 0.0, 1e-5); } while (status == GSL_CONTINUE && j < 10000); gsl_matrix *J = gsl_matrix_alloc(p.n, npar); gsl_multifit_fdfsolver_jac(s, J); gsl_multifit_covar (J, 0.0, covar); // gsl_multifit_covar (s->J, 0.0, covar); c = gsl_vector_get(s->x, 0); sig_c = sqrt(gsl_matrix_get(covar,0,0)); k = gsl_vector_get(s->x, 1); sig_k = sqrt(gsl_matrix_get(covar,1,1)); vrad = gsl_vector_get(s->x, 2); sig_vrad = sqrt(gsl_matrix_get(covar,2,2)); fwhm = gsl_vector_get(s->x, 3); sig_fwhm = sqrt(gsl_matrix_get(covar,3,3)); /* Bisector part : */ // Declarations... double sigma = fwhm/2./pow(2.*log(2.),.5), vr, v0=vrad+x[0]; double dCCFdRV, d2CCFdRV2, d2RVdCCF2; double *norm_CCF, *p0, *p1, *p2; // Allocations... norm_CCF = (double *)malloc(sizeof(double)*p.n); p0 = (double *)malloc(sizeof(double)*p.n); p1 = (double *)malloc(sizeof(double)*p.n); p2 = (double *)malloc(sizeof(double)*p.n); // Initialization... for (i=0; i<p.n; i++) norm_CCF[i] = -c/k*(1.-p.y[i]/c); for (i=0; i<p.n-1; i++) { vr = (x[i]+x[i+1])/2.; dCCFdRV = -(vr-v0)/pow(sigma,2)*exp(-pow((vr-v0),2)/2./pow(sigma,2)); d2CCFdRV2 = (pow((vr-v0),2)/pow(sigma,2)-1)/pow(sigma,2)*exp(-pow((vr-v0),2)/2/pow(sigma,2)); d2RVdCCF2 = -d2CCFdRV2/pow(dCCFdRV,3); p2[i] = d2RVdCCF2/2; p1[i] = (x[i+1]-x[i]-p2[i]*(pow(norm_CCF[i+1],2)-pow(norm_CCF[i],2)))/(norm_CCF[i+1]-norm_CCF[i]); p0[i] = x[i]-p1[i]*norm_CCF[i]-p2[i]*pow(norm_CCF[i],2); };//}; int ind_max = 0, i_b, i_r; for (i=0; i<p.n; i++) if (norm_CCF[i]>norm_CCF[ind_max]) ind_max=i; for (i=0; i<len_depth; i++) { i_b = ind_max; i_r = ind_max; while ((norm_CCF[i_b] > depth[i]) && (i_b > 1)) i_b--; while ((norm_CCF[i_r+1] > depth[i]) && (i_r < (p.n-2))) i_r++; bis[i] = (p0[i_b]+p0[i_r]) + (p1[i_b]+p1[i_r])*depth[i] + (p2[i_b]+p2[i_r])*pow(depth[i],2); bis[i] /= 2.; }; int n2=0, n3=0; double RV_top=0., RV_bottom=0., span=0.; for (i=0; i<len_depth; i++) { if ((depth[i]>=0.1) && (depth[i] <= 0.4)) { n2++; RV_top += bis[i];}; if ((depth[i]>=0.6) && (depth[i] <= 0.9)) { n3++; RV_bottom += bis[i];}; }; RV_top /= n2; RV_bottom /= n3; span = RV_top-RV_bottom; vrad = vrad+vrad_ccf[0]; para[0] = c; para[1] = k; para[2] = vrad; para[3] = fwhm; para[4] = sig_c; para[5] = sig_k; para[6] = sig_vrad; para[7] = sig_fwhm; para[8] = span; gsl_vector_free(v); gsl_matrix_free(covar); gsl_multifit_fdfsolver_free(s); free(p.x); free(norm_CCF); free(p0); free(p1); free(p2); } void gauss_v0(double *vrad_ccf, double *ccf, double *err, int n1, double *mod, double *para) { /* * Function to fit a Gaussian to the CCF * and return the center RV */ struct gauss_params p; int i, j = 0, status, npar = 4; double c=0, k=0, vrad=0, fwhm=0; double *x; gsl_vector *v = gsl_vector_alloc (npar); gsl_matrix *covar = gsl_matrix_alloc (npar, npar); const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; gsl_multifit_function_fdf F; x = vrad_ccf; p.y = ccf; p.err = err; p.n = n1; p.x = (double *) malloc(n1*sizeof(double)); p.fit = mod; for (i = 0; i < p.n; i++) p.x[i] = x[i]-x[0]; c = (p.y[0]+p.y[p.n-1])/2; fwhm = (p.x[p.n-1]-p.x[0])/5.; k = 0.; vrad = p.x[p.n/2]; for (i = 0; i < p.n; i++) if (abs(p.y[i]-c) > abs(k)) { k = p.y[i]-c; vrad = p.x[i]; } F.f = &gauss_f; F.df = &gauss_df; F.fdf = &gauss_fdf; F.n = p.n; F.p = npar; F.params = &p; T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, p.n, npar); gsl_vector_set(v, 0, c); gsl_vector_set(v, 1, k); gsl_vector_set(v, 2, vrad); gsl_vector_set(v, 3, fwhm); gsl_multifit_fdfsolver_set (s, &F, v); do { j++; status = gsl_multifit_fdfsolver_iterate (s); status = gsl_multifit_test_delta(s->dx, s->x, 0.0, 1e-5); } while (status == GSL_CONTINUE && j < 10000); gsl_matrix *J = gsl_matrix_alloc(p.n, npar); gsl_multifit_fdfsolver_jac(s, J); gsl_multifit_covar (J, 0.0, covar); // gsl_multifit_covar (s->J, 0.0, covar); vrad = gsl_vector_get(s->x, 2); //sig_vrad = sqrt(gsl_matrix_get(covar,2,2)); vrad = vrad+vrad_ccf[0]; para[0] = vrad; gsl_vector_free(v); gsl_matrix_free(covar); gsl_multifit_fdfsolver_free(s); free(p.x); } double rndup(double n,int nb_decimal) { /* * Function to round up a double type at nb_decimal */ double t; t=n*pow(10,nb_decimal) - floor(n*pow(10,nb_decimal)); if (t>=0.5) { n*=pow(10,nb_decimal);//where n is the multi-decimal double n = ceil(n); n/=pow(10,nb_decimal); } else { n*=pow(10,nb_decimal);//where n is the multi-decimal double n = floor(n); n/=pow(10,nb_decimal); } return n; } double Delta_lambda(double line_width, double lambda_line0) { /* * Calculates the broadening of a spectral line (or shift) taking into account * the velocity and the wavelength. line_width in [m/s] and lambda_line0 in [Angstrom] */ double c=299792458.; double line_spread=0.; double beta; // relativist case beta = line_width/c; line_spread = -1 * lambda_line0 * (1 - sqrt((1+beta)/(1-beta))); return line_spread; } void shifting_CCF(double *lambda, double *CCF, double *CCF_blueshifted, double v_shift,int n1) { /* * Shift the CCF with a given velocity v_shift, doing a linear interpolation */ int i; double *CCF_derivative; CCF_derivative = (double *) malloc(n1*sizeof(double)); for (i=0;i<n1;i++) { CCF_derivative[i] = 0.0; CCF_blueshifted[i] = 0.0; } // Calculates the CCF derivative if (lambda[1]-lambda[0] == 0) CCF_derivative[0] = 0; else CCF_derivative[0] = (CCF[1] - CCF[0])/(lambda[1]-lambda[0]); for (i=1;i<n1-1;i++) { if (lambda[i+1]-lambda[i] == 0) CCF_derivative[i] = CCF_derivative[i-1]; else { CCF_derivative[i] = (CCF[i+1] - CCF[i])/(lambda[i+1]-lambda[i]); } } CCF_derivative[i] = 0.; // Calculates the new values of the shifted CCF doing a linear interpolation for (i=0;i<n1;i++) { if ((v_shift >= 0) || (i == 0)) { CCF_blueshifted[i] = CCF[i] - v_shift * CCF_derivative[i]; // dy/dx = derivative => dy = derivative*dx } else if (v_shift < 0) { CCF_blueshifted[i] = CCF[i] - v_shift * CCF_derivative[i-1]; // dy/dx = derivative => dy = derivative*dx } } free(CCF_derivative); } // Calculates the Planck function double loi_Planck(double lambda0, int Temp) { double c = 299792458.; // speed of light m/s double h = 6.62606896e-34; // Planck constant double k_b = 1.380e-23; // Boltzmann constant return 2*h*pow(c,2)*1./pow(lambda0,5)*1./(exp((h*c)/(lambda0*k_b*Temp))-1); } void itot(double v, double i, double limba1, double limba2, double modif_bis_quad, double modif_bis_lin, double modif_bis_cte, int grid, double *vrad_ccf, double *intensity_ccf, double v_interval, int n_v, int n, double *f_star, double *sum_star) { /* * Calculates the flux and CCF in each cell of the grid and integrate * over the entire stellar disc to have the integrated flux and CCF */ // double omega, delta_grid, delta_v; // double y, z, delta, r_cos, limb; // int iy, j, iz, diff_CCF_non_v_and_v,n_v_shifted_quotient; // double n_v_shifted, n_v_shifted_remainder; // double *intensity_ccf_shift; // // intensity_ccf_shift = (double *)malloc(sizeof(double)*n); // // /* Conversions */ // i = i * pi/180. ; // [degree] --> [radian] // // omega = v; // delta_grid = 2./grid; // step of the grid. grid goes from -1 to 1, therefore 2 in total // // v_interval is from the velocity 0 to the edge of the spectrum taking into account minimal or maximal rotation (width - v to 0 or 0 to width + v). // // n_v is the number of points for all the CCF from minimum rotation to maximum one (from width - v to width + v). // // n_v represent therefore the double than v_interval, we therefore have to multiply v_interval by 2. // delta_v = 2.*v_interval/(n_v-1); //step in speed of the CCF. There is (n_v-1) intervals // // /* Calculates the total stellar intensity (without spots) */ // // // Scan of each cell on the grid // for (iy=0; iy<=grid; iy++) // y-scan // { // y = -1. + iy*delta_grid; // y between -1 et 1 // // Give the velocity of rotation for the given grid cell as a function of y. // // For y=-1 => Vrot min, for y=1 => Vrot max, and for y=0 => Vrot = 0. // delta = y * omega * sin(i); // // for (iz=0; iz<=grid; iz++) // z-scan // { // z = -1. + iz*delta_grid;// z between -1 et 1 // // projected radius on the sky smaller than 1, // // which means that we are on the stellar disc // if ((y*y+z*z)<=1.) // { // /* limb-darkening */ // // sqrt(r^2-(y^2+z^2)) where r=1. // // This is equal to 1 at the disc center, and 0 on the limb. // // Often referred in the literature as cos(theta) // r_cos = pow(1.-(y*y+z*z),.5); // // // intensity due to limb-darkening (Mandel & Agol 2002) // limb = 1. - limba1*(1-r_cos) - limba2*(1-r_cos)*(1-r_cos); // // //The CCF is defined between -20 and +20 km/s with a sampling "delta_v" // // of 0.1 km/s, and with boundaries normalized at 1. // // To account for stellar rotation in each cell of the simulation, // // the CCF will be shifted depending on the position of the cell // // on the stellar disc. To shift the CCF by a RV of x km/s, // // we will first shift the CCF by // // "n_v_shifted_quotient" = int(x/sampling) steps, // // and then interpolate the CCF with the remaining velocity // // "n_v_shifted_remainder" // // This will be done by shifting the CCF by // // an integer of steps and then interpolating the CCF // // to match the correct velocity // // The sampling of the CCF is every 100 m/s, // // so 2 km/s corresponds to a shift of 20 steps. // // // by how much steps the CCF is shifted due to rotation // n_v_shifted = delta/delta_v; // // n_v_shifted_quotient = rndup(n_v_shifted, 0); // n_v_shifted_remainder = (delta - n_v_shifted_quotient*delta_v); // // double v_shift = n_v_shifted_remainder; // //shifting the CCF with the remainder of n_v_shifted, // // the quotient will be taken into account by shifting // // all the points of the spectrum // shifting_CCF(vrad_ccf, intensity_ccf, intensity_ccf_shift, v_shift, n); // // // difference in number of steps between the CCF // // without any rotation and the one with rotation // diff_CCF_non_v_and_v = (n_v - n) / 2.; // // // To take into account the rotation, // // we increase the width of the CCF. // // Because the original CCF is only defined between -20 and +20 km/s, // // we have to extrapolate on each side of the boundaries of the CCF // for (j=0;j<diff_CCF_non_v_and_v+n_v_shifted_quotient;j++) // { // // extrapolation on the left of the CCF // // with the value of the left boundary, // // weighted by the limb-darkening // f_star[j] += intensity_ccf_shift[0]*limb; // } // for (j=diff_CCF_non_v_and_v+n_v_shifted_quotient;j<n+(diff_CCF_non_v_and_v+n_v_shifted_quotient);j++) // { // // value of the CCF, weighted by the limb-darkening // f_star[j] += (intensity_ccf_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)]) * limb; // } // for (j=n+(diff_CCF_non_v_and_v+n_v_shifted_quotient);j<n_v;j++) // { // // extrapolation on the right of the CCF // // with the value of the right boundary, // // weighted by the limb-darkening // f_star[j] += intensity_ccf_shift[n-1]*limb; // } // // calculates the total flux taking into account the limb-darkening // // (intensity_ccf_shift[0] is very close to 1) // *sum_star += intensity_ccf_shift[0]*limb; // } // } // } // // // Free memory // free(intensity_ccf_shift); } void starmap(double v, double i, double limba1, double limba2, int grid, double **Fmap, double **Vmap) { /* * Calculates the flux F and velocity V maps of the star * taking into account the rotational velocity, * the stellar inclination and the limb-darkening * v [km/s] stellar rotation * i [degree] inclination of the rotational axis / sky plane * limba1 [0-1.] linear coefficient of the quadratic limb-darkening law * limba1 [0-1.] quadratic coefficient of the quadratic limb-darkening law * grid * Fmap [arb. unit] Flux map (2D array) * Vmap [km/s] Velocity map (2D array) */ double r_cos, limb, y, z, delta_grid, delta_v; int iy, iz; v = v*sin(i/180.*pi); //Projected rotational velocity delta_grid = 2./grid; //The stellar disc goes from -1 to 1, therefore 2 delta_v = 2.*v/grid; //The stellar disc goes from -1 to 1, therefore 2 for (iy=0; iy<grid; iy++) // y-axis scan... { y = -1 + iy*delta_grid; for (iz=0; iz<grid; iz++) // z-axis scan { z = -1 + iz*delta_grid; if ((y*y+z*z)<1) // If the { //limb-darkening r_cos = pow(1.-(y*y+z*z),.5); limb = 1. - limba1*(1-r_cos) - limba2*(1-r_cos)*(1-r_cos); Fmap[iy][iz]= limb; Vmap[iy][iz]= -v+iy*delta_v; } else { Fmap[iy][iz]=0; Vmap[iy][iz]=-9999; } } } } void spot_init(double s, double longitude, double latitude, double inclination, int nrho, double **xyz) { /* Position of the spot initialized at the disc center (star rotates around the z axis) s [spot radius] longitude [degree] latitude [degree] inclination [degree] i=0 -> pole-on (North) i=90 -> equator-on nrho : Spot circumference resolution xyz : real position of the spot xyz2 : position of the spot at the disc center */ double *rho, rho_step, **xyz2; int j; /* Conversion [deg] -> [rad] */ longitude *= pi/180.; latitude *= pi/180.; inclination *= pi/180.; // In this initial disc center position, // we calculate the coordinates (x,y,z) of points // of the active region's circumference rho = (double *)malloc(sizeof(double)*nrho); xyz2 = (double **)malloc(sizeof(double *)*nrho); for (j=0; j<nrho; j++) xyz2[j] = (double *)malloc(sizeof(double)*3); // A circular active region has a resolution given by nrho, // which implies that we will have a point on the disc circumference // every 2*pi/(nrho-1) // -1 because there is (nrho-1) intervals rho_step = 2.*pi/(nrho-1); #pragma omp parallel for if(nrho>500) for (j=0; j<nrho; j++) rho[j] = -pi + j*rho_step; //rho goes from -pi to pi //x=sqrt(r^2-s^2), where r is the radius. r=1 therefore r^2=1 // The active region is on the surface, so very close to x=1. // However with the curvature of the sphere, the circumference of // the active region is at x=sqrt(r^2-s^2) #pragma omp parallel for if(nrho>500) for (j=0; j<nrho; j++) { xyz2[j][0] = pow(1-s*s,.5); xyz2[j][1] = s*cos(rho[j]); //projection of the circumference on the y axis xyz2[j][2] = s*sin(rho[j]); //projection of the circumference on the z axis } // to account for the real projection of the spot, // we rotate the star and look how the coordinates of the // circumference of the spot change position // according to latitude, longitude and inclination. // It consists of three rotations // // Conventions : // - when inclination=0 the star rotates around z axis // - line of sight is along x-axis // - sky plane = yz-plane // // Be Rx(alpha), Ry(beta), Rz(gamma) the rotations around the x, y and z axis // with angles alpha, beta and gamma // (counter-clockwise direction when looking toward the origin). // // The rotations to apply are: // Ry(inclination) x Rz(longitude) x Ry(latitude) x X(x,y,z) // // | cos(b) 0 sin(b) | | cos(g) -sin(g) 0 | // Ry(b) = | 0 1 0 | Rz(g) = | sin(g) cos(g) 0 | // | -sin(b) 0 cos(b) | | 0 0 1 | // // // |x'| | cos(b2)cos(g)cos(b)-sin(b)sin(b2) -sin(g)cos(b2) cos(b2)cos(g)sin(b)+sin(b2)cos(b) | |x| // |y'| = | sin(g)cos(b) cos(g) sin(g)sin(b) | x |y| // |z'| | -sin(b2)cos(g)cos(b)-cos(b2)sin(b) sin(b2)sin(g) -sin(b2)cos(g)sin(b)+cos(b2)cos(b) | |z| double b = -latitude; double g = longitude; double b2 = pi/2.-inclination; double R[3][3] = {{cos(b2)*cos(g)*cos(b)-sin(b)*sin(b2), -sin(g)*cos(b2), cos(b2)*cos(g)*sin(b)+sin(b2)*cos(b)}, {sin(g)*cos(b), cos(g), sin(g)*sin(b)}, {-sin(b2)*cos(g)*cos(b)-cos(b2)*sin(b), sin(b2)*sin(g), -sin(b2)*cos(g)*sin(b)+cos(b2)*cos(b)}}; // calculates the real xyz position of the active region // after rotating the star to have the initial equatorial active region // at the correct longitude and latitude, // taking into account the stellar inclination #pragma omp parallel for if(nrho>500) for (j=0; j<nrho; j++) { xyz[j][0] = R[0][0]*xyz2[j][0] + R[0][1]*xyz2[j][1] + R[0][2]*xyz2[j][2]; xyz[j][1] = R[1][0]*xyz2[j][0] + R[1][1]*xyz2[j][1] + R[1][2]*xyz2[j][2]; xyz[j][2] = R[2][0]*xyz2[j][0] + R[2][1]*xyz2[j][1] + R[2][2]*xyz2[j][2]; } // Free memory free(rho); for (j=0; j<nrho; j++) free(xyz2[j]); free(xyz2); } void spot_phase(double **xyz, double inclination, int nrho, double phase, double **xyz2) { int i; double psi = -phase*(2*pi); //the phase is between 0 and 1, so psi is in radian between -2pi and 0. inclination = inclination*pi/180.; // in radian double axe[3] = {cos(inclination),0,sin(inclination)}; //projection of the rotation axis on the xyz coordinate //The rotation around the axis (axe[0],axe[1],axe[2]) of an angle psi is given by the following matrix //There is some sign difference here with respect to Wikipaedia for example because in this case psi is //defined negative (c.f. a few lines before). In this case, cos(-psi)=cos(psi) -> no sign change, //but sin(-psi)=-sin(psi) -> sign change. double R[3][3] = {{(1-cos(psi))*axe[0]*axe[0] + cos(psi), (1-cos(psi))*axe[0]*axe[1] + sin(psi)*axe[2], (1-cos(psi))*axe[0]*axe[2] - sin(psi)*axe[1]}, {(1-cos(psi))*axe[1]*axe[0] - sin(psi)*axe[2], (1-cos(psi))*axe[1]*axe[1] + cos(psi), (1-cos(psi))*axe[1]*axe[2] + sin(psi)*axe[0]}, {(1-cos(psi))*axe[2]*axe[0] + sin(psi)*axe[1], (1-cos(psi))*axe[2]*axe[1] - sin(psi)*axe[0], (1-cos(psi))*axe[2]*axe[2] + cos(psi)}}; #pragma omp parallel for if(nrho>500) for (i=0; i<nrho; i++) //calculates the xyz position of the active region circumference at phase psi { xyz2[i][0] = R[0][0]*xyz[i][0] + R[0][1]*xyz[i][1] + R[0][2]*xyz[i][2]; xyz2[i][1] = R[1][0]*xyz[i][0] + R[1][1]*xyz[i][1] + R[1][2]*xyz[i][2]; xyz2[i][2] = R[2][0]*xyz[i][0] + R[2][1]*xyz[i][1] + R[2][2]*xyz[i][2]; } } int spot_area(double **xlylzl, int nrho, int grid, int *iminy, int *iminz, int *imaxy, int *imaxz) { // Determine a smaller yz-area of the stellar disk, where the active region is // The different cases are : // - the active region is completely visible (all x of the circumference >=0) // - the active region is completely invisible (all x of the circumference <0) // - the active region is on the disk edge and partially visible only int j, visible=0; double grid_step = 2./grid; //The stellar disc goes from -1 to 1, therefore 2 double miny=1, minz=1, maxy=-1, maxz=-1; // init to 'opposite'-extreme values int counton=0, countoff=0; // count how many points of the circumference are // visible and how many are invisible for (j=0; j<nrho; j++) //scan each point of the circumference if (xlylzl[j][0]>=0) { // if x>=0 counton += 1; // select the extreme points of the circumference if (xlylzl[j][1]<miny) miny = xlylzl[j][1]; if (xlylzl[j][2]<minz) minz = xlylzl[j][2]; if (xlylzl[j][1]>maxy) maxy = xlylzl[j][1]; if (xlylzl[j][2]>maxz) maxz = xlylzl[j][2]; } else countoff = 1; if ((counton>0)&&(countoff>0)) { // There are both visible and invisible points // --> active region is on the edge // In this situation there are cases where the yz-area define above is // actually smaller than the real area of the active region on the stellar disk. // The minima/maxima are over/under-estimated if the active region is on one of the // axis (y or z). Because if on the y axis, the minimum (or maximum) won t be on the circumference of the active region. Same for z axis if (miny*maxy<0) { //active region on the z-axis because one point is on the positive side of z, and the other on the negative side of z if (minz<0) minz=-1; //active region on the bottom-z axis (z<0) else maxz=1;} //active region on the top-z axis (z>=0) if (minz*maxz<0) { //active region on the y-axis because one point is on the positive side of y, and the other on the negative side of z if (miny<0) miny=-1; //active region on the left hand-y axis (y<0) else maxy=1;} //active region on the right hand-y axis (y>=0) }; if (counton==0) visible = 0; else visible = 1; // Indices of miny, minz,... on the grid *iminy = floor((1.+miny)/grid_step); //floor(x) returns the largest integral value that is not greater than x. //floor of 2.3 is 2.0, floor of 3.8 is 3.0, floor of -2.3 is -3.0, floor of -3.8 is -4.0 *iminz = floor((1.+minz)/grid_step); *imaxy = ceil((1.+maxy)/grid_step); //ceil(x) returns the smallest integral value that is not less than x. //ceil of 2.3 is 3, ceil of 3.8 is 4.0, ceil of -2.3 is -2.0, ceil of -3.8 is -3.0 *imaxz = ceil((1.+maxz)/grid_step); return visible; } void spot_scan(double v, double i, double limba1, double limba2, double modif_bis_quad, double modif_bis_lin, double modif_bis_cte, int grid, double *vrad_ccf, double *intensity_ccf, double *intensity_ccf_spot, double v_interval, int n_v, int n, double s, double longitude, double phase, double latitude, int iminy, int iminz, int imaxy, int imaxz, double *f_spot_flux, double *f_spot_bconv, double *f_spot_tot, double *sum_spot, int magn_feature_type, int T_star, int T_diff_spot) { /* Scan of the yz-area where the spot is. * For each grid-point (y,z) we need to check whether it belongs to the spot * or not. Sadly, we do not know the projected geometry of the spot in its * actual position. Thus, we have to do an inverse rotation to replace the * grid point where it would be in the initial configuration. Indeed, in the * initial configuration, the spot has a well known geometry of a circle * centered on the x-axis. */ int j, iy, iz,diff_CCF_non_v_and_v,n_v_shifted_quotient; double n_v_shifted, n_v_shifted_remainder; double y, z; double delta_grid=2./grid, delta, r_cos; double limb, delta_v = 2.*v_interval/(n_v-1); double *xayaza; // actual coordinates double *xiyizi; // coordinates transformed back to the initial configuration double *intensity_ccf_spot_shift; double *intensity_ccf_shift; int T_spot,T_plage; double intensity,loi_Planck_star; //the wavelength of the Kitt peak spectrum goes from 3921.2441 to 6665.5789, // the mean being 5293.4115 loi_Planck_star = loi_Planck(5293.4115e-10, T_star); xayaza = (double *)malloc(sizeof(double)*3); xiyizi = (double *)malloc(sizeof(double)*3); intensity_ccf_shift = (double *)malloc(sizeof(double)*n); intensity_ccf_spot_shift = (double *)malloc(sizeof(double)*n); // Scan of each cell on the grid for (iy=iminy; iy<imaxy; iy++) // y-scan { y = -1.+iy*delta_grid; // y between -1 et 1 delta = y * v * sin(i*pi/180.); // Give the velocity of the rotation for the given grid cell as a function of y. // For y=-1 => Vrot min, for y=1 => Vrot max, and for y=0 => Vrot = 0. xayaza[1] = y; for (iz=iminz; iz<imaxz; iz++) // z-scan { z = -1.+iz*delta_grid; // z between -1 et 1 if (z*z+y*y<1.) //projected radius on the sky smaller than 1, which means that we are on the stellar disc { xayaza[0] = pow(1.-(y*y+z*z),.5); //sqrt(r^2-(y^2+z^2)) where r=1. This is equal to 1 at the disc center, and 0 on the limb. //This is often referred in the literature as cos(theta) xayaza[2] = z; // xayaza --> xiyizi: Rotate the star so that the spot is on the disc center spot_inverse_rotation(xayaza,longitude,latitude,i,phase,xiyizi); // if inside the active region when scanning the grid if (xiyizi[0]*xiyizi[0]>=1.-s*s) // x^2 >= 1-s^2, which means that you are inside the active region { //limb-darkening r_cos = pow(1.-(y*y+z*z),.5); //sqrt(r^2-(y^2+z^2)) where r=1. This is equal to 1 at the disc center, and 0 on the limb. //This is often referred in the literature as cos(theta) limb = 1. - limba1*(1-r_cos) - limba2*(1-r_cos)*(1-r_cos); //intensity due to limb-darkening (Mandel & Agol 2002) // intensity of the spot (magn_feature_type==0) or the plage (magn_feature_type==1) if (magn_feature_type==0) { T_spot = T_star-T_diff_spot; intensity = loi_Planck(5293.4115e-10,T_spot)/loi_Planck_star; //the wavelength of the Kitt peak spectrum goes from 3921.2441+6665.5789, the mean being 5293.4115 } else { T_plage = T_star+250.9-407.7*r_cos+190.9*pow(r_cos,2); //plages are brighter on the limb Meunier 2010 intensity = loi_Planck(5293.4115e-10,T_plage)/loi_Planck_star; //the wavelength of the Kitt peak spectrum goes from 3921.2441+6665.5789, the mean being 5293.4115 } n_v_shifted = delta/delta_v; // by how much steps the CCF is shifted due to rotation n_v_shifted_quotient = rndup(n_v_shifted,0); // integer number of steps n_v_shifted_remainder = (delta - n_v_shifted_quotient*delta_v); // remainder of the division between delta and the integer number of steps double v_shift = n_v_shifted_remainder; //shifting the CCF with the remainder of n_v_shifted, the quotient will be taken into account by shifting all the points of the spectrum shifting_CCF(vrad_ccf, intensity_ccf, intensity_ccf_shift, v_shift,n); shifting_CCF(vrad_ccf, intensity_ccf_spot, intensity_ccf_spot_shift, v_shift,n); diff_CCF_non_v_and_v = (n_v - n) / 2.; //difference in number of step between the CCF without any rotation and the one with rotation // To take into account the rotation, we increase the width of the CCF. Because the original CCF is only defined between -20 and +20 km/s, // we have to extrapolate on each side of the boundaries of the CCF. In this case, we calculate the "non contribution" to the CCF. // For the region inside the active region, we calculate the contribution of the quiet photosphere and then suppress the contribution of the active region. // It will then be easy to include the contribution of the active region by just subtracting the "non contribution" to the integrated contribution of the // star without active region calculated with the "itot" function for (j=0;j<diff_CCF_non_v_and_v+n_v_shifted_quotient;j++) { // extrapolation on the left of the CCF with the value of the left boundary, weighted by the limb-darkening and the active region intensity // We also consider limb-darkening for spots because we also observe them with different stellar depth depending on their position f_spot_flux[j] += intensity_ccf_shift[0]*limb*(1 - intensity);// only flux effect f_spot_bconv[j] += intensity_ccf_shift[0]*limb*(1 - 1); // only convective blueshift effect. The convective blueshift does not affect the boundaries of the CCF f_spot_tot[j] += intensity_ccf_shift[0]*limb*(1 - intensity);// combined effect } for (j=diff_CCF_non_v_and_v+n_v_shifted_quotient;j<n+(diff_CCF_non_v_and_v+n_v_shifted_quotient);j++) { // value of the CCF, weighted by the limb-darkening and the active region intensity // We also consider limb-darkening for spots because we also observe them with different stellar depth depending on their position f_spot_flux[j] += intensity_ccf_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)]*limb - intensity * (intensity_ccf_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)])*limb; // only flux effect f_spot_bconv[j] += intensity_ccf_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)]*limb - (intensity_ccf_spot_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)])*limb; // only convective blueshift effect f_spot_tot[j] += intensity_ccf_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)]*limb - intensity * (intensity_ccf_spot_shift[j-(diff_CCF_non_v_and_v+n_v_shifted_quotient)])*limb; // combined effect } for (j=n+(diff_CCF_non_v_and_v+n_v_shifted_quotient);j<n_v;j++) { // extrapolation on the right of the CCF with the value of the right boundary, weighted by the limb-darkening and the active region intensity // We also consider limb-darkening for spots because we also observe them with different stellar depth depending on their position f_spot_flux[j] += intensity_ccf_shift[n-1]*limb*(1 - intensity);// only flux effect f_spot_bconv[j] += intensity_ccf_shift[n-1]*limb*(1 - 1); // only convective blueshift effect. The convective blueshift does not affect the boundaries of the CCF f_spot_tot[j] += intensity_ccf_shift[n-1]*limb*(1 - intensity);// combined effect } // calculates the "non contributing" total flux of the active region taking into account the limb-darkening and the active region intensity *sum_spot += intensity_ccf_shift[0]*limb*(1.-intensity); } } } } free(xayaza); free(xiyizi); free(intensity_ccf_shift); free(intensity_ccf_spot_shift); } void spot_inverse_rotation(double *xyz, double longitude, double latitude, double inclination, double phase, double *xiyizi) { /* * Relocate a point (x,y,z) to the 'initial' configuration * i.e. when the active region is on the disc center * * This consists in rotating the point, according to latitude, longitude, * inclination and phase, but in the reverse order. * // // Conventions : // - when inclination=0 the star rotates around z axis // (i.e. rotation axis and z axis are indistinct), // - line of sight is along x-axis // - sky plane = yz-plane */ double g2 = --phase*(2*pi); // inverse phase ([0-1] -> [rad]) double i = inclination * pi/180.; double b = latitude * pi/180.; double g = -longitude * pi/180.; double b2 = -(pi/2.-i); double R[3][3] = {{(1-cos(g2))*cos(i)*cos(i) + cos(g2), sin(g2)*sin(i), (1-cos(g2))*cos(i)*sin(i)}, {-sin(g2)*sin(i), cos(g2), sin(g2)*cos(i)}, {(1-cos(g2))*sin(i)*cos(i), -sin(g2)*cos(i), (1-cos(g2))*sin(i)*sin(i) + cos(g2)}}; double R2[3][3] = {{cos(b)*cos(g)*cos(b2)-sin(b2)*sin(b), -sin(g)*cos(b), cos(b)*cos(g)*sin(b2)+sin(b)*cos(b2)}, {sin(g)*cos(b2), cos(g), sin(g)*sin(b2)}, {-sin(b)*cos(g)*cos(b2)-cos(b)*sin(b2), sin(b)*sin(g), -sin(b)*cos(g)*sin(b2)+cos(b)*cos(b2)}}; //rotation for the latitude, longitude, inclination and phase, which is a combination of R and R2 double R3[3][3] = {{R2[0][0]*R[0][0]+R2[0][1]*R[1][0]+R2[0][2]*R[2][0], R2[0][0]*R[0][1]+R2[0][1]*R[1][1]+R2[0][2]*R[2][1], R2[0][0]*R[0][2]+R2[0][1]*R[1][2]+R2[0][2]*R[2][2]}, {R2[1][0]*R[0][0]+R2[1][1]*R[1][0]+R2[1][2]*R[2][0], R2[1][0]*R[0][1]+R2[1][1]*R[1][1]+R2[1][2]*R[2][1], R2[1][0]*R[0][2]+R2[1][1]*R[1][2]+R2[1][2]*R[2][2]}, {R2[2][0]*R[0][0]+R2[2][1]*R[1][0]+R2[2][2]*R[2][0], R2[2][0]*R[0][1]+R2[2][1]*R[1][1]+R2[2][2]*R[2][1], R2[2][0]*R[0][2]+R2[2][1]*R[1][2]+R2[2][2]*R[2][2]}}; //Coordinates of the active region circumference when it is in the disc center xiyizi[0] = R3[0][0]*xyz[0] + R3[0][1]*xyz[1] + R3[0][2]*xyz[2]; xiyizi[1] = R3[1][0]*xyz[0] + R3[1][1]*xyz[1] + R3[1][2]*xyz[2]; xiyizi[2] = R3[2][0]*xyz[0] + R3[2][1]*xyz[1] + R3[2][2]*xyz[2]; } void spot_scan_npsi(double **xyz, int nrho, double *psi, int npsi, double v, double inclination, double limba1, double limba2, double modif_bis_quad, double modif_bis_lin, double modif_bis_cte, int grid, double *vrad_ccf, double *intensity_ccf, double *intensity_ccf_spot, double v_interval, int n_v, int n, double s, double longitude, double latitude, double **f_spot_flux, double **f_spot_bconv, double **f_spot_tot, double *sum_spot, int magn_feature_type, int T_star, int T_diff_spot) { /* * Scans the yz-area where the spot is for different phases (psi) and * returns the spot's "non-contribution" to the total flux and its * "non-contribution" to the ccf, for each phase. * Thus the result is to be subtracted to the output of the itot() function. */ //tbd before: //spot_init(s, longitude, latitude, inclination, nrho, xyz) #out: xyz int ipsi, j; int iminy, iminz, imaxy, imaxz, vis; double **xyz2 = (double **)malloc(sizeof(double *)*nrho); for (j=0; j<nrho; j++) xyz2[j] = (double *)malloc(sizeof(double)*3); for (ipsi=0; ipsi<npsi; ipsi++) { spot_phase(xyz, inclination, nrho, psi[ipsi], xyz2); vis = spot_area(xyz2, nrho, grid, &iminy, &iminz, &imaxy, &imaxz); if (vis==1) { // printf("%f\n", s); spot_scan(v, inclination, limba1, limba2, modif_bis_quad, modif_bis_lin, modif_bis_cte, grid, vrad_ccf, intensity_ccf, intensity_ccf_spot,v_interval, n_v, n, s, longitude, psi[ipsi], latitude, iminy, iminz, imaxy, imaxz, f_spot_flux[ipsi], f_spot_bconv[ipsi], f_spot_tot[ipsi], &sum_spot[ipsi],magn_feature_type,T_star,T_diff_spot); } } for (j=0; j<nrho; j++) free(xyz2[j]); free(xyz2); } void spot_scan_npsi2(double **xyz, int nrho, double *psi, int npsi, double v, double inclination, double limba1, double limba2, double modif_bis_quad, double modif_bis_lin, double modif_bis_cte, int grid, double *vrad_ccf, double *intensity_ccf, double *intensity_ccf_spot, double v_interval, int n_v, int n, double *s, double longitude, double latitude, double **f_spot_flux, double **f_spot_bconv, double **f_spot_tot, double *sum_spot, int magn_feature_type, int T_star, int T_diff_spot) { /* * Scans the yz-area where the spot is for different phases (psi) and * returns the spot's "non-contribution" to the total flux and its * "non-contribution" to the ccf, for each phase. * Thus the result is to be subtracted to the output of the itot() function. */ //tbd before: //spot_init(s, longitude, latitude, inclination, nrho, xyz) #out: xyz int ipsi, j; int iminy, iminz, imaxy, imaxz, vis; double **xyz2 = (double **)malloc(sizeof(double *)*nrho); for (j=0; j<nrho; j++) xyz2[j] = (double *)malloc(sizeof(double)*3); #pragma omp parallel if(npsi>99) { // printf("%d\n", omp_get_num_threads()); #pragma omp for private(vis, iminy, iminz, imaxy, imaxz) for (ipsi=0; ipsi<npsi; ipsi++) { spot_phase(xyz, inclination, nrho, psi[ipsi], xyz2); vis = spot_area(xyz2, nrho, grid, &iminy, &iminz, &imaxy, &imaxz); if (vis==1) { spot_scan(v, inclination, limba1, limba2, modif_bis_quad, modif_bis_lin, modif_bis_cte, grid, vrad_ccf, intensity_ccf, intensity_ccf_spot,v_interval, n_v, n, s[ipsi], longitude, psi[ipsi], latitude, iminy, iminz, imaxy, imaxz, f_spot_flux[ipsi], f_spot_bconv[ipsi], f_spot_tot[ipsi], &sum_spot[ipsi],magn_feature_type,T_star,T_diff_spot); } } } for (j=0; j<nrho; j++) free(xyz2[j]); free(xyz2); }
GB_unaryop__ainv_int32_int8.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__ainv_int32_int8 // op(A') function: GB_tran__ainv_int32_int8 // C type: int32_t // A type: int8_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ int32_t z = (int32_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_AINV || GxB_NO_INT32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int32_int8 ( int32_t *Cx, // Cx and Ax may be aliased int8_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__ainv_int32_int8 ( 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
main.c
#include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <omp.h> #include <time.h> #include <sys/types.h> #include <unistd.h> #define PLOTTING false // Struct representing a Pixel with RGB values typedef struct { unsigned char red, green, blue; } PPMPixel; // Struct representing an image in PPM format typedef struct { int width, height; PPMPixel *data; } PPMImage; // Struct to store coordiantes typedef struct { int x, y; } Point; static int32_t s_randtbl[32] = { 3, -1726662223, 379960547, 1735697613, 1040273694, 1313901226, 1627687941, -179304937, -2073333483, 1780058412, -1989503057, -615974602, 344556628, 939512070, -1249116260, 1507946756, -812545463, 154635395, 1388815473, -1926676823, 525320961, -1009028674, 968117788, -123449607, 1284210865, 435012392, -2017506339, -911064859, -370259173, 1132637927, 1398500161, -205601318, }; typedef struct Seed{ int32_t randtbl[32]; int32_t *fptr; int32_t *rptr; int32_t *end_ptr; int32_t *state; } Seed; // The random function you could used in your project instead of the C 'rand' function. unsigned int my_rand(Seed *seed) { int32_t *fptr = seed->fptr; int32_t *rptr = seed->rptr; int32_t *end_ptr = seed->end_ptr; unsigned int val; val = *fptr += (unsigned int) *rptr; ++fptr; if (fptr >= end_ptr) { fptr = seed->state; ++rptr; } else { ++rptr; if (rptr >= end_ptr) rptr = seed->state; } seed->fptr = fptr; seed->rptr = rptr; return val; } void init_seed(Seed *seed) { for(int i = 0; i < 32; ++i) { seed->randtbl[i] = s_randtbl[i]; } seed->fptr = &(seed->randtbl[2]); seed->rptr = &(seed->randtbl[1]); seed->end_ptr = &(seed->randtbl[sizeof (seed->randtbl) / sizeof (seed->randtbl[0])]); seed->state = &(seed->randtbl[1]); unsigned int init = (time(NULL) << omp_get_thread_num()); seed->state[0] = init; int32_t *dst = seed->state; int32_t word = init; int kc = 32; for(int i = 1; i < kc; ++i) { long int hi = word / 127773; long int lo = word % 127773; word = 16807 * lo - 2836 * hi; if (word < 0) word += 2147483647; *++dst = word; } seed->fptr = &(seed->state[3]); seed->rptr = &(seed->state[0]); kc *= 10; while (--kc >= 0) { my_rand(seed); } } //Struct representing a node in a linked list //Is used as a stack typedef struct stackNode { Point data; struct stackNode *next; } stackNode; /* * Function: push * ---------------------------- * Appends a stackNode containing `newPoint` at the beginning of * a linked list accessed by the `head` pointer * * *head: pointer to a stackNode representing the beginning of the list * newPoint: Point to be added as data to the new stackNode * * returns: new head pointer of type `stackNode` pointing at the start of the list */ stackNode *push(stackNode *head, Point newPoint) { stackNode *newNode = malloc(sizeof(stackNode)); if (newNode == NULL) { perror("Error! memory not allocated."); exit(EXIT_FAILURE); } newNode->data = newPoint; newNode->next = head; head = newNode; return head; } /* * Function: pop * ---------------------------- * Removes a stackNode containing at the beginning of * a linked list accessed by the `head` pointer. * Stores the data of the stackNode in the pointer *point * * *head: pointer to a stackNode representing the beginning of the list * *point: Point storing the data of the removed stackNode * * returns: new head pointer pointing at the start of the list */ stackNode *pop(stackNode *head, Point *point) { stackNode *oldCell = head; *point = head->data; head = head->next; oldCell->next = NULL; free(oldCell); return head; } /* * Function: writePPM * ---------------------------- * Creates a file of the PPM image format * * filename: name of the file the image will be saved at * img: image to write to file * * returns: / */ void writePPM(const char *filename, PPMImage *img) { FILE *fp; fp = fopen(filename, "wb"); if (!fp) { fprintf(stderr, "Unable to open file '%s'\n", filename); exit(EXIT_FAILURE); } //write the header file //image format fprintf(fp, "P6 "); //image size fprintf(fp, "%d %d ", img->width, img->height); // rgb component depth fprintf(fp, "%d\n", 255); // pixel data fwrite(img->data, 3 * img->height, img->width, fp); fclose(fp); } /* * Function: floodFillConnected * ---------------------------- * If the cell in a grid is made of conducting material, assign the cell * at (x, y) the value 2 . Uses a stack to emulate recursion and connects * each neighboring conducting cell together by assigning it the value 2. * * grid: pointer to a square array of integer values of size N*N * x: integer between 0 and N-1, specifying a row in the grid * y: integer between 0 and N-1, specifying a column in the grid * N: size of one side of the grid * * returns: / */ void floodFillConnected(int *grid, int x, int y, int N) { stackNode *head = calloc(sizeof(stackNode), sizeof(stackNode)); if (head == NULL) { perror("Error! memory not allocated."); exit(EXIT_FAILURE); } head->next = NULL; // Push first point on the Stack head = push(head, (Point){x, y}); Point *newPoint = malloc(sizeof(Point)); if (newPoint == NULL) { perror("Error! memory not allocated."); free(head->next); free(head); exit(EXIT_FAILURE); } //While the stack is not empty while (head != NULL) { //Pop a point from the stack and push its neighbours on head = pop(head, newPoint); int x_ = newPoint->x; int y_ = newPoint->y; if (grid[N * x_ + y_] == 1) { //The cell is conducting and connected grid[N * x_ + y_] = 2; if (y_ + 1 < N) { head = push(head, (Point){x_, y_ + 1}); } if (y_ - 1 >= 0) { head = push(head, (Point){x_, y_ - 1}); } if (x_ + 1 < N) { head = push(head, (Point){x_ + 1, y_}); } if (x_ - 1 >= 0) { head = push(head, (Point){x_ - 1, y_}); } } } free(head); free(newPoint); } /* * Function: isGridConducting * ---------------------------- * Check if the whole grid is conducting by verifying if there * is a connected path of cells between the right and left side * of the grid. * * grid: pointer to a square array of integer values of size N*N * N: size of one side of the grid * * returns: 1 if the grid is conducting, 0 if not */ int isGridConducting(int *grid, int N) { int x; // Start a call on all the leftmost cells // to create a path of conducting cells from left to right for (x = 0; x < N; x++) { floodFillConnected(grid, x, 0, N); } // Check if any of the rightmost cells are conducting // If one is found, the grid is conducting for (x = 0; x < N; x++) { if (grid[N * x + (N - 1)] == 2) { return 1; } } return 0; } /* * Function: createImage * ---------------------------- * Creates a PPMImage from the grid and saves it to disk in ppm format * The pixels are either black, grey or orange depending on their conductiv * properties * * grid: pointer to a square array of integer values of size N*N * N: size of one side of the grid * image: pointer to an instance of PPMImage object * filename: name of the file the image will be saved at * * * returns: true if the grid is conducting, false if not */ void createImage(int *grid, int N, PPMImage *image, const char *filename) { PPMPixel grey = {128, 128, 128}; PPMPixel black = {0, 0, 0}; PPMPixel orange = {255, 165, 0}; image->width = N; image->height = N; for (long i = 0; i < N * N; i++) { //Non-conducting if (grid[i] == 0) { image->data[i] = grey; } //Conducting but not connected else if (grid[i] == 1) { image->data[i] = black; } //Conducting and connected else if (grid[i] == 2) { image->data[i] = orange; } } writePPM(filename, image); } /* * Fill the empty grid randomly with an amount of`nbConductingFibers`conducting * fibers that are 3 cells long * * grid: pointer to a square array of integer values of size N*N * nbConductingFibers: integer specifying the number of conducting fibers * in the grid * N: size of one side of the grid * * returns: / */ void createConductingFibers(int *grid, unsigned int nbConductingFibers, unsigned int N) { Seed seed; init_seed(&seed); long* randomIndex = malloc(N*N*sizeof(long)); if(randomIndex == NULL) { perror("Error! memory not allocated."); free(grid); exit(EXIT_FAILURE); } //Array containing cell number that will be conductive for(long i=0; i < N* N; i ++){ randomIndex[i] = i; } //Shuffle array for (long i = 0; i < N*N - 1; i++) { long index = i + my_rand(&seed) % (N*N - i); long temp = randomIndex[index]; randomIndex[index] = randomIndex[i]; randomIndex[i] = temp; } for (long i = 0; i < nbConductingFibers; i++) { int dir = my_rand(&seed) % 2; grid[randomIndex[i]] = 1; // Set vertical neighbours to 1 if (dir == 1) { //Check boundary conditions if (randomIndex[i] - N >= 0) { grid[randomIndex[i] - N] = 1; } if (randomIndex[i] + N < N * N) { grid[randomIndex[i] + N] = 1; } } // Set horizontal neighbours to 1 else { //Check boundary conditions if (randomIndex[i] % N != 0) { grid[randomIndex[i] - 1] = 1; } if ((randomIndex[i] + 1) % N != 0) { grid[randomIndex[i] + 1] = 1; } } } } /* * Function: monteCarlo * ---------------------------- * Computes the number of conducting grids out of `M` grids. * * grid: pointer to a square array of integer values of size N*N * nbConductingFibers: integer specifying the number of conducting fibers * in the grid * N: size of one side of the grid * M: number of grids to check * * returns: number of conducting grids */ int monteCarlo(unsigned int nbConductingFibers, int N, int M) { unsigned int nbConducting = 0; unsigned int numberOfThreads; int thread_id; int *grid = NULL; double *wtime = 0; #pragma omp parallel private(grid, thread_id) { #pragma omp single { numberOfThreads = omp_get_num_threads(); wtime = malloc(numberOfThreads * sizeof(double)); if(wtime == NULL){ perror("Error! memory not allocated."); exit(EXIT_FAILURE); } } grid = malloc(N * N * sizeof(int)); if (grid == NULL) { perror("Error! memory not allocated."); free(wtime); exit(EXIT_FAILURE); } thread_id = omp_get_thread_num(); wtime[thread_id] = omp_get_wtime(); #pragma omp for schedule(runtime) reduction(+:nbConducting) for(int j = 0; j < M; j++){ memset(grid, 0, N * N * sizeof(int)); createConductingFibers(grid, nbConductingFibers, N); nbConducting += isGridConducting(grid, N); } wtime[thread_id] = (omp_get_wtime() - wtime[thread_id]) * 1000; } double totalTime = 0; for(int i = 0; i< numberOfThreads; i++){ totalTime += wtime[i]; // printf("Thread %d timeElapsed: %lf\n", i, wtime[i]); } // Get the scheduling type and chunk size that was omp_sched_t kind; int chunk; omp_get_schedule(&kind, &chunk); const char *kind_verbose[4]; kind_verbose[0] = "static"; kind_verbose[1] = "dynamic"; kind_verbose[2] = "guided"; kind_verbose[3] = "auto"; if(PLOTTING){ printf("%u ", numberOfThreads); printf("%0.lf ", totalTime/numberOfThreads); printf("%s ", kind_verbose[kind-1]); printf("%d ", chunk); }else{ printf("Number of threads: %u\n", numberOfThreads); printf("Average time per thread: %0.lf ms\n", totalTime/numberOfThreads); } return nbConducting; } int main(int argc, char **argv) { unsigned int flag, N, M; float d; assert(argc >= 4); // Check number of arguments //Scan arguments sscanf(argv[1], "%u", &flag); sscanf(argv[2], "%u", &N); sscanf(argv[3], "%f", &d); //Check argument validity assert((flag == 0) || (flag == 1)); assert(N > 0); assert(d >= 0 && d <= 1); // Deadline if(flag == 1){ assert(argc == 5); sscanf(argv[4], "%u", &M); assert(M > 0); if(PLOTTING){ printf("%u %u %.3f %u ", flag, N, d, M); }else{ printf("Args : Flag: %u N: %u d: %.3f M: %u\n", flag, N, d, M); } // Intermediate deadline }else{ if(PLOTTING){ printf("%u %u %.3f \n", flag, N, d); }else{ printf("Args : Flag: %u N: %u d: %.3f\n", flag, N, d); } } srand(time(NULL)); long nbConductingFibers =(float) d *(N * N); if(flag == 0){ //Intermediate deadline PPMImage *image = malloc(sizeof(PPMImage)); if (image == NULL) { perror("Error! memory not allocated."); exit(EXIT_FAILURE); } image->data = malloc(N * N * sizeof(PPMPixel)); if (image->data == NULL) { perror("Error! memory not allocated."); free(image); exit(EXIT_FAILURE); } int *grid = malloc(N * N * sizeof(int)); if (grid == NULL) { perror("Error! memory not allocated."); free(image->data); free(image); exit(EXIT_FAILURE); } createConductingFibers(grid, nbConductingFibers,N); unsigned int gridConductivity = isGridConducting(grid, N); printf("Grid is conducting? : %s\n", gridConductivity ? "Yes!" : "No!"); // -----------Creating image------------------ createImage(grid, N, image, "conductingMaterial.ppm"); free(grid); free(image->data); free(image); }else{ //Deadline unsigned int nbConducting = monteCarlo(nbConductingFibers, N, M); float probability = (float)nbConducting / M; if(PLOTTING){ printf("%.3f\n", probability); } else{ printf("Probability of conductivity: %.3f (%d/%d)\n", probability, nbConducting, M); } } }
dscale.c
#include "dscale.h" #include "dzscal.h" fint dscale_(const fnat m[static restrict 1], const fnat n[static restrict 1], double A[static restrict VDL], const fnat ldA[static restrict 1], const fint e[static restrict 1]) { #ifndef NDEBUG if (IS_NOT_VFPENV) return -6; if (*m & VDL_1) return -1; if (IS_NOT_ALIGNED(A)) return -3; if (*ldA < *m) return -4; if (*ldA & VDL_1) return -4; #endif /* !NDEBUG */ if (!*e) return 0; const double e_ = (double)*e; #ifdef _OPENMP #pragma omp parallel for default(none) shared(m,n,A,ldA,e_) DZSCAL_LOOP(A,ldA); return 1; #else /* !_OPENMP */ register const VD s = _mm512_set1_pd(e_); DZSCAL_LOOP(A,ldA); return 0; #endif /* ?_OPENMP */ }
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 @ 2010 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/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" /* 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; 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 */ (void) 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 */ (void) 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(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; ssize_t i; 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: ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidOption","`%s'","Should not call this function"); return((KernelInfo *) NULL); 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); if (kernel->next == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); if (kernel->next->next == (KernelInfo *) NULL) return(DestroyKernelInfo(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) { 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; ssize_t x,r; 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) { 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) { 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; 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: { ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidOption","`%s'","Not a Primitive Morphology Method"); 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)) { 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(); const Quantum *magick_restrict p; Quantum *magick_restrict q; 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++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait morphology_traits, traits; const MagickRealType *magick_restrict k; const Quantum *magick_restrict pixels; 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(); const Quantum *magick_restrict p; Quantum *magick_restrict q; 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++) { 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; const MagickRealType *magick_restrict k; const Quantum *magick_restrict pixels, *magick_restrict quantum_pixels; 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++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; 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++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits; const MagickRealType *magick_restrict k; const Quantum *magick_restrict pixels; 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--) { const Quantum *magick_restrict p; Quantum *magick_restrict q; 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--) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits; const MagickRealType *magick_restrict k; const Quantum *magick_restrict pixels; 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(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(stderr, "\n"); /* add end-of-line from previous */ (void) (void) FormatLocaleFile(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(stderr, " Total %.20g",(double) kernel_changed); if (verbose != MagickFalse && stage_loop < stage_limit) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */ #if 0 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image); (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image); (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image); (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image); (void) FormatLocaleFile(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(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(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(stderr, " (re-iterate)"); else (void) FormatLocaleFile(stderr, " (done)"); } rslt_image = curr_image; /* return result, and re-iterate */ } else if ( rslt_image == (Image *) NULL) { if (verbose != MagickFalse) (void) FormatLocaleFile(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(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(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; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); 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 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 */ { ssize_t i,j,x,y; 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 */ { 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; 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(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) { double pos_scale, neg_scale; 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(stderr, "Kernel"); if ( kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c ); (void) FormatLocaleFile(stderr, " \"%s", CommandOptionToMnemonic(MagickKernelOptions, k->type) ); if ( fabs(k->angle) >= MagickEpsilon ) (void) FormatLocaleFile(stderr, "@%lg", k->angle); (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long) k->width,(unsigned long) k->height,(long) k->x,(long) k->y); (void) FormatLocaleFile(stderr, " with values from %.*lg to %.*lg\n", GetMagickPrecision(), k->minimum, GetMagickPrecision(), k->maximum); (void) FormatLocaleFile(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(stderr, " (Zero-Summing)\n"); else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Normalized)\n"); else (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n", GetMagickPrecision(), k->positive_range+k->negative_range); for (i=v=0; v < k->height; v++) { (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v ); for (u=0; u < k->width; u++, i++) if (IsNaN(k->values[i])) (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan"); else (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3, GetMagickPrecision(), (double) k->values[i]); (void) FormatLocaleFile(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) { 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; }
exact_rhs.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB BT code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include "header.h" //--------------------------------------------------------------------- // compute the right hand side based on exact solution //--------------------------------------------------------------------- void exact_rhs() { double dtemp[5], xi, eta, zeta, dtpp; int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1; #pragma omp parallel default(shared) private(i,j,k,m,zeta,eta,xi,\ dtpp,im1,ip1,jm1,jp1,km1,kp1,dtemp) { //--------------------------------------------------------------------- // initialize //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = 0; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { for (m = 0; m < 5; m++) { forcing[k][j][i][m] = 0.0; } } } } //--------------------------------------------------------------------- // xi-direction flux differences //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = 1; k <= grid_points[2]-2; k++) { zeta = (double)(k) * dnzm1; for (j = 1; j <= grid_points[1]-2; j++) { eta = (double)(j) * dnym1; for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)(i) * dnxm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[i][m] = dtemp[m]; } dtpp = 1.0 / dtemp[0]; for (m = 1; m < 5; m++) { buf[i][m] = dtpp * dtemp[m]; } cuf[i] = buf[i][1] * buf[i][1]; buf[i][0] = cuf[i] + buf[i][2] * buf[i][2] + buf[i][3] * buf[i][3]; q[i] = 0.5*(buf[i][1]*ue[i][1] + buf[i][2]*ue[i][2] + buf[i][3]*ue[i][3]); } for (i = 1; i <= grid_points[0]-2; i++) { im1 = i-1; ip1 = i+1; forcing[k][j][i][0] = forcing[k][j][i][0] - tx2*( ue[ip1][1]-ue[im1][1] )+ dx1tx1*(ue[ip1][0]-2.0*ue[i][0]+ue[im1][0]); forcing[k][j][i][1] = forcing[k][j][i][1] - tx2 * ( (ue[ip1][1]*buf[ip1][1]+c2*(ue[ip1][4]-q[ip1]))- (ue[im1][1]*buf[im1][1]+c2*(ue[im1][4]-q[im1])))+ xxcon1*(buf[ip1][1]-2.0*buf[i][1]+buf[im1][1])+ dx2tx1*( ue[ip1][1]-2.0* ue[i][1]+ue[im1][1]); forcing[k][j][i][2] = forcing[k][j][i][2] - tx2 * ( ue[ip1][2]*buf[ip1][1]-ue[im1][2]*buf[im1][1])+ xxcon2*(buf[ip1][2]-2.0*buf[i][2]+buf[im1][2])+ dx3tx1*( ue[ip1][2]-2.0*ue[i][2] +ue[im1][2]); forcing[k][j][i][3] = forcing[k][j][i][3] - tx2*( ue[ip1][3]*buf[ip1][1]-ue[im1][3]*buf[im1][1])+ xxcon2*(buf[ip1][3]-2.0*buf[i][3]+buf[im1][3])+ dx4tx1*( ue[ip1][3]-2.0* ue[i][3]+ ue[im1][3]); forcing[k][j][i][4] = forcing[k][j][i][4] - tx2*( buf[ip1][1]*(c1*ue[ip1][4]-c2*q[ip1])- buf[im1][1]*(c1*ue[im1][4]-c2*q[im1]))+ 0.5*xxcon3*(buf[ip1][0]-2.0*buf[i][0]+ buf[im1][0])+ xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+ xxcon5*(buf[ip1][4]-2.0*buf[i][4]+buf[im1][4])+ dx5tx1*( ue[ip1][4]-2.0* ue[i][4]+ ue[im1][4]); } //--------------------------------------------------------------------- // Fourth-order dissipation //--------------------------------------------------------------------- for (m = 0; m < 5; m++) { i = 1; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (5.0*ue[i][m] - 4.0*ue[i+1][m] +ue[i+2][m]); i = 2; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (-4.0*ue[i-1][m] + 6.0*ue[i][m] - 4.0*ue[i+1][m] + ue[i+2][m]); } for (i = 3; i <= grid_points[0]-4; i++) { for (m = 0; m < 5; m++) { forcing[k][j][i][m] = forcing[k][j][i][m] - dssp* (ue[i-2][m] - 4.0*ue[i-1][m] + 6.0*ue[i][m] - 4.0*ue[i+1][m] + ue[i+2][m]); } } for (m = 0; m < 5; m++) { i = grid_points[0]-3; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[i-2][m] - 4.0*ue[i-1][m] + 6.0*ue[i][m] - 4.0*ue[i+1][m]); i = grid_points[0]-2; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[i-2][m] - 4.0*ue[i-1][m] + 5.0*ue[i][m]); } } } //--------------------------------------------------------------------- // eta-direction flux differences //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = 1; k <= grid_points[2]-2; k++) { zeta = (double)(k) * dnzm1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (double)(i) * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)(j) * dnym1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[j][m] = dtemp[m]; } dtpp = 1.0/dtemp[0]; for (m = 1; m < 5; m++) { buf[j][m] = dtpp * dtemp[m]; } cuf[j] = buf[j][2] * buf[j][2]; buf[j][0] = cuf[j] + buf[j][1] * buf[j][1] + buf[j][3] * buf[j][3]; q[j] = 0.5*(buf[j][1]*ue[j][1] + buf[j][2]*ue[j][2] + buf[j][3]*ue[j][3]); } for (j = 1; j <= grid_points[1]-2; j++) { jm1 = j-1; jp1 = j+1; forcing[k][j][i][0] = forcing[k][j][i][0] - ty2*( ue[jp1][2]-ue[jm1][2] )+ dy1ty1*(ue[jp1][0]-2.0*ue[j][0]+ue[jm1][0]); forcing[k][j][i][1] = forcing[k][j][i][1] - ty2*( ue[jp1][1]*buf[jp1][2]-ue[jm1][1]*buf[jm1][2])+ yycon2*(buf[jp1][1]-2.0*buf[j][1]+buf[jm1][1])+ dy2ty1*( ue[jp1][1]-2.0* ue[j][1]+ ue[jm1][1]); forcing[k][j][i][2] = forcing[k][j][i][2] - ty2*( (ue[jp1][2]*buf[jp1][2]+c2*(ue[jp1][4]-q[jp1]))- (ue[jm1][2]*buf[jm1][2]+c2*(ue[jm1][4]-q[jm1])))+ yycon1*(buf[jp1][2]-2.0*buf[j][2]+buf[jm1][2])+ dy3ty1*( ue[jp1][2]-2.0*ue[j][2] +ue[jm1][2]); forcing[k][j][i][3] = forcing[k][j][i][3] - ty2*( ue[jp1][3]*buf[jp1][2]-ue[jm1][3]*buf[jm1][2])+ yycon2*(buf[jp1][3]-2.0*buf[j][3]+buf[jm1][3])+ dy4ty1*( ue[jp1][3]-2.0*ue[j][3]+ ue[jm1][3]); forcing[k][j][i][4] = forcing[k][j][i][4] - ty2*( buf[jp1][2]*(c1*ue[jp1][4]-c2*q[jp1])- buf[jm1][2]*(c1*ue[jm1][4]-c2*q[jm1]))+ 0.5*yycon3*(buf[jp1][0]-2.0*buf[j][0]+ buf[jm1][0])+ yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+ yycon5*(buf[jp1][4]-2.0*buf[j][4]+buf[jm1][4])+ dy5ty1*(ue[jp1][4]-2.0*ue[j][4]+ue[jm1][4]); } //--------------------------------------------------------------------- // Fourth-order dissipation //--------------------------------------------------------------------- for (m = 0; m < 5; m++) { j = 1; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (5.0*ue[j][m] - 4.0*ue[j+1][m] +ue[j+2][m]); j = 2; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (-4.0*ue[j-1][m] + 6.0*ue[j][m] - 4.0*ue[j+1][m] + ue[j+2][m]); } for (j = 3; j <= grid_points[1]-4; j++) { for (m = 0; m < 5; m++) { forcing[k][j][i][m] = forcing[k][j][i][m] - dssp* (ue[j-2][m] - 4.0*ue[j-1][m] + 6.0*ue[j][m] - 4.0*ue[j+1][m] + ue[j+2][m]); } } for (m = 0; m < 5; m++) { j = grid_points[1]-3; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[j-2][m] - 4.0*ue[j-1][m] + 6.0*ue[j][m] - 4.0*ue[j+1][m]); j = grid_points[1]-2; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[j-2][m] - 4.0*ue[j-1][m] + 5.0*ue[j][m]); } } } //--------------------------------------------------------------------- // zeta-direction flux differences //--------------------------------------------------------------------- #pragma omp for schedule(static) for (j = 1; j <= grid_points[1]-2; j++) { eta = (double)(j) * dnym1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (double)(i) * dnxm1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)(k) * dnzm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[k][m] = dtemp[m]; } dtpp = 1.0/dtemp[0]; for (m = 1; m < 5; m++) { buf[k][m] = dtpp * dtemp[m]; } cuf[k] = buf[k][3] * buf[k][3]; buf[k][0] = cuf[k] + buf[k][1] * buf[k][1] + buf[k][2] * buf[k][2]; q[k] = 0.5*(buf[k][1]*ue[k][1] + buf[k][2]*ue[k][2] + buf[k][3]*ue[k][3]); } for (k = 1; k <= grid_points[2]-2; k++) { km1 = k-1; kp1 = k+1; forcing[k][j][i][0] = forcing[k][j][i][0] - tz2*( ue[kp1][3]-ue[km1][3] )+ dz1tz1*(ue[kp1][0]-2.0*ue[k][0]+ue[km1][0]); forcing[k][j][i][1] = forcing[k][j][i][1] - tz2 * ( ue[kp1][1]*buf[kp1][3]-ue[km1][1]*buf[km1][3])+ zzcon2*(buf[kp1][1]-2.0*buf[k][1]+buf[km1][1])+ dz2tz1*( ue[kp1][1]-2.0* ue[k][1]+ ue[km1][1]); forcing[k][j][i][2] = forcing[k][j][i][2] - tz2 * ( ue[kp1][2]*buf[kp1][3]-ue[km1][2]*buf[km1][3])+ zzcon2*(buf[kp1][2]-2.0*buf[k][2]+buf[km1][2])+ dz3tz1*(ue[kp1][2]-2.0*ue[k][2]+ue[km1][2]); forcing[k][j][i][3] = forcing[k][j][i][3] - tz2 * ( (ue[kp1][3]*buf[kp1][3]+c2*(ue[kp1][4]-q[kp1]))- (ue[km1][3]*buf[km1][3]+c2*(ue[km1][4]-q[km1])))+ zzcon1*(buf[kp1][3]-2.0*buf[k][3]+buf[km1][3])+ dz4tz1*( ue[kp1][3]-2.0*ue[k][3] +ue[km1][3]); forcing[k][j][i][4] = forcing[k][j][i][4] - tz2 * ( buf[kp1][3]*(c1*ue[kp1][4]-c2*q[kp1])- buf[km1][3]*(c1*ue[km1][4]-c2*q[km1]))+ 0.5*zzcon3*(buf[kp1][0]-2.0*buf[k][0] +buf[km1][0])+ zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+ zzcon5*(buf[kp1][4]-2.0*buf[k][4]+buf[km1][4])+ dz5tz1*( ue[kp1][4]-2.0*ue[k][4]+ ue[km1][4]); } //--------------------------------------------------------------------- // Fourth-order dissipation //--------------------------------------------------------------------- for (m = 0; m < 5; m++) { k = 1; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (5.0*ue[k][m] - 4.0*ue[k+1][m] +ue[k+2][m]); k = 2; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (-4.0*ue[k-1][m] + 6.0*ue[k][m] - 4.0*ue[k+1][m] + ue[k+2][m]); } for (k = 3; k <= grid_points[2]-4; k++) { for (m = 0; m < 5; m++) { forcing[k][j][i][m] = forcing[k][j][i][m] - dssp* (ue[k-2][m] - 4.0*ue[k-1][m] + 6.0*ue[k][m] - 4.0*ue[k+1][m] + ue[k+2][m]); } } for (m = 0; m < 5; m++) { k = grid_points[2]-3; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[k-2][m] - 4.0*ue[k-1][m] + 6.0*ue[k][m] - 4.0*ue[k+1][m]); k = grid_points[2]-2; forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[k-2][m] - 4.0*ue[k-1][m] + 5.0*ue[k][m]); } } } //--------------------------------------------------------------------- // now change the sign of the forcing function, //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = 1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { forcing[k][j][i][m] = -1.0 * forcing[k][j][i][m]; } } } } } //end parallel }
fib.c
#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <omp.h> #include <sys/time.h> static uint64_t par_res, seq_res; int cutoff_value; #define FIB_NUM_PRECOMP 50 uint64_t fib_results[FIB_NUM_PRECOMP] = { /*{{{*/ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049 }; /*}}}*/ // Forward declarations static uint64_t fib_seq(int n); static uint64_t fib(int n, int d); int main(int argc, char** argv); /*static*/ uint64_t fib(int n, int d) { /*{{{*/ uint64_t x, y; if (n < 2) return n; if (d < cutoff_value) { #pragma omp task shared(x) firstprivate(n, d) x = fib(n - 1, d + 1); #pragma omp task shared(y) firstprivate(n, d) y = fib(n - 2, d + 1); #pragma omp taskwait } else { x = fib_seq(n - 1); y = fib_seq(n - 2); } return x + y; } /*}}}*/ static uint64_t fib_seq(int n) { /*{{{*/ if (n < 2) return n; return fib_seq(n - 1) + fib_seq(n - 2); } /*}}}*/ long get_usecs(void) {/*{{{*/ struct timeval t; gettimeofday(&t, ((void *) 0)); return t.tv_sec * 1000000 + t.tv_usec; }/*}}}*/ int main(int argc, char** argv) { /*{{{*/ if (argc > 3) { fprintf(stderr, "Usage: %s number cut_off\n", argv[0]); exit(1); } cutoff_value = 15; int num = 42; if (argc > 1) num = atoi(argv[1]); if (argc > 2) cutoff_value = atoi(argv[2]); fprintf(stderr, "Computing fib %d %d ...\n", num, cutoff_value); long par_time_start = get_usecs(); #pragma omp parallel { #pragma omp single { #pragma omp task par_res = fib(num, 0); #pragma omp taskwait } } long par_time_end = get_usecs(); double par_time = (double)(par_time_end - par_time_start) / 1000000; fprintf(stderr, "Execution time = %f s\n", par_time); #ifdef CHECK_RESULT fprintf(stderr, "Checking ...\n"); if (num > FIB_NUM_PRECOMP) seq_res = fib_seq(num); else { long seq_time_start = get_usecs(); seq_res = fib_results[num]; long seq_time_end = get_usecs(); double seq_time = (double)(seq_time_end - seq_time_start) / 1000000; fprintf(stderr, "Seq. execution time = %f s\n", seq_time); } if (par_res == seq_res) fprintf(stderr, "%s(%d,%d), check result = %s\n", argv[0], num, cutoff_value, "SUCCESS"); else fprintf(stderr, "%s(%d,%d), check result = %s\n", argv[0], num, cutoff_value, "FAILURE"); #endif return 0; } /*}}}*/
backup.c
// DFT Stefano: N = 8000, ser = 5 sec, omp (2 cores, HT) = 2 sec, optimisation = ? // void norm(real_t data[], int_t len, int_t factor); // void setarr(real_t data[], int_t len, real_t value); // void setrnd(real_t arr[], int_t len); // void setsin(real_t arr[], int_t len); // void setdist(real_t arr[], int_t len); // /* normalise array (divide every element by a factor given as parameter) */ // void norm(real_t data[], int_t len, int_t factor) // { // real_t invfac = (real_t)1.f / factor; // #ifdef MY_OMP // #pragma omp simd // #endif // for(int_t i = 0; i < len; ++i) // { // data[i] *= invfac; // } // } // /* set array elements to a constant value (given as parameter) */ // void setarr(real_t arr[], int_t len, real_t value) // { // #ifdef MY_OMP // #pragma omp simd // #endif // for(int_t i = 0; i < len; ++i) // { // arr[i] = value; // } // } // /* set array elements to random values (scaled by length) */ // void setrnd(real_t arr[], int_t len) // { // real_t invlen = (real_t)1.f / len; // #ifdef MY_OMP // #pragma omp simd // #endif // for(int_t i = 0; i < len; ++i) // { // arr[i] = rand() * invlen; // } // } // /* set array elements to one period of a sine function */ // void setsin(real_t arr[], int_t len) // { // for(int_t i = 0; i < len; ++i) // { // arr[i] = sin((real_t)(2 * M_PI * i / len)); // } // } // /* set array elements to a distorted sine function */ // void setdist(real_t arr[], int_t len) // { // real_t scale = 4 * (real_t)M_PI / len; // #ifdef MY_OMP // #pragma omp simd // #endif // for(int_t i = 0; i < len; ++i) // { // arr[i] = sin(i * scale) + (real_t)0.2f * sin(40 * i * scale); // } // } // invert bits for each index. // n is number of samples and a the array of the samples /*void invert_bits(complex_t a[], int_t n) { int_t mv = n / 2; int_t k, rev = 0; complex_t b; for (int_t i = 1; i < n; i++) // run tru all the indexes from 1 to n { k = i; mv = n / 2; rev = 0; while (k > 0) // invert the actual index { if ((k % 2) > 0) { rev += mv; } k = k / 2; mv = mv / 2; } // switch the actual sample and the bitinverted one if (i < rev) { b = a[rev]; a[rev] = a[i]; a[i] = b; } } }*/ // void fft_unroll(struct cmplx_t* d, struct cmplx_t** T, int_t len, int dir); /* bit-reversal algorithm using Grey Code from Jennifer Elaan */ // void reversey(int* b, int len) // { // int i, jp, jn, k, s; // int tmp; // jp = 0; // jn = 0; // /* // bsr = bit scan reverse, exists in x86 since Haswell // bsf = bit scan forward, --------- '' -------------- // */ // s = bsr(len) - 1; // for(i = 1; i < len; i++) // { // k = bsf(i); // jp ^= (1<<k); // jn ^= (1<<(s-k)); // if(jp<jn) // { // tmp = b[jp]; // b[jp] = b[jn]; // b[jn] = tmp; // } // } // } /* experimenting with manual loop unrolling - WIP */ // void fft_unroll(struct cmplx_t* __restrict__ d, // struct cmplx_t** __restrict__ T, // int_t len, int dir) // { // int_t ll = len >> 1; // for(int_t M = 1, j = 0, len_M = ll; M <= ll; M <<= 1, ++j, len_M >>= 1) // { // for (int_t i = 0; i < len_M; ++i) // { // int_t l0 = (i << (j+1)); // int_t r0 = l0 + M; // for (int_t k = 0, l = l0, r = r0; // k < M-UNROLL && l < ll; // k += UNROLL, l += UNROLL, r += UNROLL) // { // /* printf("l = %lu, r = %lu\n", l, r); */ // real_t Xev_re[UNROLL] = { RE(d[l]), RE(d[l+1]), // RE(d[l+2]), RE(d[l+3]) }; // real_t Xev_im[UNROLL] = { dir * IM(d[l]), dir * IM(d[l+1]), // dir * IM(d[l+2]), dir * IM(d[l+3]) }; // real_t tmp[UNROLL] = { dir * IM(d[r]), dir * IM(d[r+1]), // dir * IM(d[r+2]), dir * IM(d[r+3]) }; // real_t Xod_re[UNROLL] = // { RE(d[r]) * RE(T[j][k]) - tmp[0] * IM(T[j][k]), // RE(d[r+1]) * RE(T[j][k+1]) - tmp[1] * IM(T[j][k+1]), // RE(d[r+2]) * RE(T[j][k+2]) - tmp[2] * IM(T[j][k+2]), // RE(d[r+3]) * RE(T[j][k+3]) - tmp[3] * IM(T[j][k+3]) }; // real_t Xod_im[UNROLL] = // { RE(d[r]) * IM(T[j][k]) + tmp[0] * RE(T[j][k]), // RE(d[r+1]) * IM(T[j][k+1]) + tmp[1] * RE(T[j][k+1]), // RE(d[r+2]) * IM(T[j][k+2]) + tmp[2] * RE(T[j][k+2]), // RE(d[r+3]) * IM(T[j][k+3]) + tmp[3] * RE(T[j][k+3]) }; // RE(d[l]) = Xev_re[0] + Xod_re[0]; // RE(d[l+1]) = Xev_re[1] + Xod_re[1]; // RE(d[l+2]) = Xev_re[2] + Xod_re[2]; // RE(d[l+2]) = Xev_re[3] + Xod_re[3]; // IM(d[l]) = dir * (Xev_im[0] + Xod_im[0]); // IM(d[l+1]) = dir * (Xev_im[1] + Xod_im[1]); // IM(d[l+2]) = dir * (Xev_im[2] + Xod_im[2]); // IM(d[l+3]) = dir * (Xev_im[3] + Xod_im[3]); // RE(d[r]) = Xev_re[0] - Xod_re[0]; // RE(d[r+1]) = Xev_re[1] - Xod_re[1]; // RE(d[r+2]) = Xev_re[2] - Xod_re[2]; // RE(d[r+3]) = Xev_re[3] - Xod_re[3]; // IM(d[r]) = dir * (Xev_im[0] - Xod_im[0]); // IM(d[r+1]) = dir * (Xev_im[1] - Xod_im[1]); // IM(d[r+2]) = dir * (Xev_im[2] - Xod_im[2]); // IM(d[r+3]) = dir * (Xev_im[3] - Xod_im[3]); // } // } // } // }
fft.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 } /**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* 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 */ /**********************************************************************************************/ /* * Original code from the Cilk project * * Copyright (c) 2000 Massachusetts Institute of Technology * Copyright (c) 2000 Matteo Frigo */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "bots.h" #include "app-desc.h" /* Definitions and operations for complex numbers */ /* * compute the W coefficients (that is, powers of the root of 1) * and store them into an array. */ void compute_w_coefficients(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; #pragma omp task untied compute_w_coefficients(n, a, ab, W); #pragma omp task untied compute_w_coefficients(n, ab + 1, b, W); #pragma omp taskwait ; } } void compute_w_coefficients_seq(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; compute_w_coefficients_seq(n, a, ab, W); compute_w_coefficients_seq(n, ab + 1, b, W); } } /* * Determine (in a stupid way) if n is divisible by eight, then by four, else * find the smallest prime factor of n. */ int factor(int n) { int r; if (n < 2) return 1; if (n == 64 || n == 128 || n == 256 || n == 1024 || n == 2048 || n == 4096) return 8; if ((n & 15) == 0) return 16; if ((n & 7) == 0) return 8; if ((n & 3) == 0) return 4; if ((n & 1) == 0) return 2; /* try odd numbers up to n (computing the sqrt may be slower) */ for (r = 3; r < n; r += 2) if (n % r == 0) return r; /* n is prime */ return n; } void unshuffle(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; #pragma omp task untied unshuffle(a, ab, in, out, r, m); #pragma omp task untied unshuffle(ab, b, in, out, r, m); #pragma omp taskwait ; } } void unshuffle_seq(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; unshuffle_seq(a, ab, in, out, r, m); unshuffle_seq(ab, b, in, out, r, m); } } void fft_twiddle_gen1(COMPLEX * in, COMPLEX * out, COMPLEX * W, int r, int m, int nW, int nWdnti, int nWdntm) { int j, k; COMPLEX *jp, *kp; for (k = 0, kp = out; k < r; ++k, kp += m) { REAL r0, i0, rt, it, rw, iw; int l1 = nWdnti + nWdntm * k; int l0; r0 = i0 = 0.0; for (j = 0, jp = in, l0 = 0; j < r; ++j, jp += m) { rw = c_re(W[l0]); iw = c_im(W[l0]); rt = c_re(*jp); it = c_im(*jp); r0 += rt * rw - it * iw; i0 += rt * iw + it * rw; l0 += l1; if (l0 > nW) l0 -= nW; } c_re(*kp) = r0; c_im(*kp) = i0; } } void fft_twiddle_gen(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { #pragma omp task untied fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; #pragma omp task untied fft_twiddle_gen(i, i2, in, out, W, nW, nWdn, r, m); #pragma omp task untied fft_twiddle_gen(i2, i1, in, out, W, nW, nWdn, r, m); } #pragma omp taskwait ; } void fft_twiddle_gen_seq(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; fft_twiddle_gen_seq(i, i2, in, out, W, nW, nWdn, r, m); fft_twiddle_gen_seq(i2, i1, in, out, W, nW, nWdn, r, m); } } /* machine-generated code begins here */ void fft_base_2(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(in[0]); i1_0 = c_im(in[0]); r1_1 = c_re(in[1]); i1_1 = c_im(in[1]); c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[1]) = (r1_0 - r1_1); c_im(out[1]) = (i1_0 - i1_1); } void fft_twiddle_2(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_2(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_2(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; fft_twiddle_2_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_2_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_2(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_2(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_2(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_2_seq(a, ab, in, out, m); fft_unshuffle_2_seq(ab, b, in, out, m); } } void fft_base_4(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(in[0]); i2_0 = c_im(in[0]); r2_2 = c_re(in[2]); i2_2 = c_im(in[2]); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; r2_1 = c_re(in[1]); i2_1 = c_im(in[1]); r2_3 = c_re(in[3]); i2_3 = c_im(in[3]); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[2]) = (r1_0 - r1_1); c_im(out[2]) = (i1_0 - i1_1); c_re(out[1]) = (r1_2 + i1_3); c_im(out[1]) = (i1_2 - r1_3); c_re(out[3]) = (r1_2 - i1_3); c_im(out[3]) = (i1_2 + r1_3); } void fft_twiddle_4(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_4(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_4(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; fft_twiddle_4_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_4_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_4(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_4(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_4(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_4_seq(a, ab, in, out, m); fft_unshuffle_4_seq(ab, b, in, out, m); } } void fft_base_8(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(in[0]); i3_0 = c_im(in[0]); r3_4 = c_re(in[4]); i3_4 = c_im(in[4]); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; r3_2 = c_re(in[2]); i3_2 = c_im(in[2]); r3_6 = c_re(in[6]); i3_6 = c_im(in[6]); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; r3_1 = c_re(in[1]); i3_1 = c_im(in[1]); r3_5 = c_re(in[5]); i3_5 = c_im(in[5]); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; r3_3 = c_re(in[3]); i3_3 = c_im(in[3]); r3_7 = c_re(in[7]); i3_7 = c_im(in[7]); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[4]) = (r1_0 - r1_1); c_im(out[4]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[5]) = (r1_2 - tmpr); c_im(out[5]) = (i1_2 - tmpi); c_re(out[2]) = (r1_4 + i1_5); c_im(out[2]) = (i1_4 - r1_5); c_re(out[6]) = (r1_4 - i1_5); c_im(out[6]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 - tmpi); c_re(out[7]) = (r1_6 - tmpr); c_im(out[7]) = (i1_6 + tmpi); } } void fft_twiddle_8(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_8(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_8(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_8_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_8_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_8(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_8(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_8(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_8_seq(a, ab, in, out, m); fft_unshuffle_8_seq(ab, b, in, out, m); } } void fft_base_16(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(in[0]); i4_0 = c_im(in[0]); r4_8 = c_re(in[8]); i4_8 = c_im(in[8]); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; r4_4 = c_re(in[4]); i4_4 = c_im(in[4]); r4_12 = c_re(in[12]); i4_12 = c_im(in[12]); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; r4_2 = c_re(in[2]); i4_2 = c_im(in[2]); r4_10 = c_re(in[10]); i4_10 = c_im(in[10]); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; r4_6 = c_re(in[6]); i4_6 = c_im(in[6]); r4_14 = c_re(in[14]); i4_14 = c_im(in[14]); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; r4_1 = c_re(in[1]); i4_1 = c_im(in[1]); r4_9 = c_re(in[9]); i4_9 = c_im(in[9]); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; r4_5 = c_re(in[5]); i4_5 = c_im(in[5]); r4_13 = c_re(in[13]); i4_13 = c_im(in[13]); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; r4_3 = c_re(in[3]); i4_3 = c_im(in[3]); r4_11 = c_re(in[11]); i4_11 = c_im(in[11]); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; r4_7 = c_re(in[7]); i4_7 = c_im(in[7]); r4_15 = c_re(in[15]); i4_15 = c_im(in[15]); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[8]) = (r1_0 - r1_1); c_im(out[8]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[9]) = (r1_2 - tmpr); c_im(out[9]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[10]) = (r1_4 - tmpr); c_im(out[10]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[11]) = (r1_6 - tmpr); c_im(out[11]) = (i1_6 - tmpi); c_re(out[4]) = (r1_8 + i1_9); c_im(out[4]) = (i1_8 - r1_9); c_re(out[12]) = (r1_8 - i1_9); c_im(out[12]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 - tmpi); c_re(out[13]) = (r1_10 - tmpr); c_im(out[13]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 - tmpi); c_re(out[14]) = (r1_12 - tmpr); c_im(out[14]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 - tmpi); c_re(out[15]) = (r1_14 - tmpr); c_im(out[15]) = (i1_14 + tmpi); } } void fft_twiddle_16(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_16(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_16(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_16_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_16_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_16(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_16(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_16(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_16_seq(a, ab, in, out, m); fft_unshuffle_16_seq(ab, b, in, out, m); } } void fft_base_32(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(in[0]); i5_0 = c_im(in[0]); r5_16 = c_re(in[16]); i5_16 = c_im(in[16]); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; r5_8 = c_re(in[8]); i5_8 = c_im(in[8]); r5_24 = c_re(in[24]); i5_24 = c_im(in[24]); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; r5_4 = c_re(in[4]); i5_4 = c_im(in[4]); r5_20 = c_re(in[20]); i5_20 = c_im(in[20]); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; r5_12 = c_re(in[12]); i5_12 = c_im(in[12]); r5_28 = c_re(in[28]); i5_28 = c_im(in[28]); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; r5_2 = c_re(in[2]); i5_2 = c_im(in[2]); r5_18 = c_re(in[18]); i5_18 = c_im(in[18]); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; r5_10 = c_re(in[10]); i5_10 = c_im(in[10]); r5_26 = c_re(in[26]); i5_26 = c_im(in[26]); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; r5_6 = c_re(in[6]); i5_6 = c_im(in[6]); r5_22 = c_re(in[22]); i5_22 = c_im(in[22]); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; r5_14 = c_re(in[14]); i5_14 = c_im(in[14]); r5_30 = c_re(in[30]); i5_30 = c_im(in[30]); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; r5_1 = c_re(in[1]); i5_1 = c_im(in[1]); r5_17 = c_re(in[17]); i5_17 = c_im(in[17]); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; r5_9 = c_re(in[9]); i5_9 = c_im(in[9]); r5_25 = c_re(in[25]); i5_25 = c_im(in[25]); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; r5_5 = c_re(in[5]); i5_5 = c_im(in[5]); r5_21 = c_re(in[21]); i5_21 = c_im(in[21]); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; r5_13 = c_re(in[13]); i5_13 = c_im(in[13]); r5_29 = c_re(in[29]); i5_29 = c_im(in[29]); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; r5_3 = c_re(in[3]); i5_3 = c_im(in[3]); r5_19 = c_re(in[19]); i5_19 = c_im(in[19]); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; r5_11 = c_re(in[11]); i5_11 = c_im(in[11]); r5_27 = c_re(in[27]); i5_27 = c_im(in[27]); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; r5_7 = c_re(in[7]); i5_7 = c_im(in[7]); r5_23 = c_re(in[23]); i5_23 = c_im(in[23]); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; r5_15 = c_re(in[15]); i5_15 = c_im(in[15]); r5_31 = c_re(in[31]); i5_31 = c_im(in[31]); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[16]) = (r1_0 - r1_1); c_im(out[16]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[17]) = (r1_2 - tmpr); c_im(out[17]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[18]) = (r1_4 - tmpr); c_im(out[18]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[19]) = (r1_6 - tmpr); c_im(out[19]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(out[4]) = (r1_8 + tmpr); c_im(out[4]) = (i1_8 + tmpi); c_re(out[20]) = (r1_8 - tmpr); c_im(out[20]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 + tmpi); c_re(out[21]) = (r1_10 - tmpr); c_im(out[21]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 + tmpi); c_re(out[22]) = (r1_12 - tmpr); c_im(out[22]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 + tmpi); c_re(out[23]) = (r1_14 - tmpr); c_im(out[23]) = (i1_14 - tmpi); c_re(out[8]) = (r1_16 + i1_17); c_im(out[8]) = (i1_16 - r1_17); c_re(out[24]) = (r1_16 - i1_17); c_im(out[24]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(out[9]) = (r1_18 + tmpr); c_im(out[9]) = (i1_18 - tmpi); c_re(out[25]) = (r1_18 - tmpr); c_im(out[25]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(out[10]) = (r1_20 + tmpr); c_im(out[10]) = (i1_20 - tmpi); c_re(out[26]) = (r1_20 - tmpr); c_im(out[26]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(out[11]) = (r1_22 + tmpr); c_im(out[11]) = (i1_22 - tmpi); c_re(out[27]) = (r1_22 - tmpr); c_im(out[27]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(out[12]) = (r1_24 + tmpr); c_im(out[12]) = (i1_24 - tmpi); c_re(out[28]) = (r1_24 - tmpr); c_im(out[28]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(out[13]) = (r1_26 + tmpr); c_im(out[13]) = (i1_26 - tmpi); c_re(out[29]) = (r1_26 - tmpr); c_im(out[29]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(out[14]) = (r1_28 + tmpr); c_im(out[14]) = (i1_28 - tmpi); c_re(out[30]) = (r1_28 - tmpr); c_im(out[30]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(out[15]) = (r1_30 + tmpr); c_im(out[15]) = (i1_30 - tmpi); c_re(out[31]) = (r1_30 - tmpr); c_im(out[31]) = (i1_30 + tmpi); } } void fft_twiddle_32(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_32(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_32(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_32_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_32_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_32(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_32(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_32(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_32_seq(a, ab, in, out, m); fft_unshuffle_32_seq(ab, b, in, out, m); } } /* end of machine-generated code */ /* * Recursive complex FFT on the n complex components of the array in: * basic Cooley-Tukey algorithm, with some improvements for * n power of two. The result is placed in the array out. n is arbitrary. * The algorithm runs in time O(n*(r1 + ... + rk)) where r1, ..., rk * are prime numbers, and r1 * r2 * ... * rk = n. * * n: size of the input * in: pointer to input * out: pointer to output * factors: list of factors of n, precomputed * W: twiddle factors * nW: size of W, that is, size of the original transform * */ void fft_aux(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) { #pragma omp task untied fft_unshuffle_32(0, m, in, out, m); } else if (r == 16) { #pragma omp task untied fft_unshuffle_16(0, m, in, out, m); } else if (r == 8) { #pragma omp task untied fft_unshuffle_8(0, m, in, out, m); } else if (r == 4) { #pragma omp task untied fft_unshuffle_4(0, m, in, out, m); } else if (r == 2) { #pragma omp task untied fft_unshuffle_2(0, m, in, out, m); } else unshuffle(0, m, in, out, r, m); #pragma omp taskwait ; for (k = 0; k < n; k += m) { #pragma omp task untied firstprivate(k) fft_aux(m, out + k, in + k, factors + 1, W, nW); } #pragma omp taskwait ; } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) { #pragma omp task untied fft_twiddle_2(0, m, in, out, W, nW, nW / n, m); } else if (r == 4) { #pragma omp task untied fft_twiddle_4(0, m, in, out, W, nW, nW / n, m); } else if (r == 8) { #pragma omp task untied fft_twiddle_8(0, m, in, out, W, nW, nW / n, m); } else if (r == 16) { #pragma omp task untied fft_twiddle_16(0, m, in, out, W, nW, nW / n, m); } else if (r == 32) { #pragma omp task untied fft_twiddle_32(0, m, in, out, W, nW, nW / n, m); } else { #pragma omp task untied fft_twiddle_gen(0, m, in, out, W, nW, nW / n, r, m); } #pragma omp taskwait ; return; } void fft_aux_seq(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) fft_unshuffle_32_seq(0, m, in, out, m); else if (r == 16) fft_unshuffle_16_seq(0, m, in, out, m); else if (r == 8) fft_unshuffle_8_seq(0, m, in, out, m); else if (r == 4) fft_unshuffle_4_seq(0, m, in, out, m); else if (r == 2) fft_unshuffle_2_seq(0, m, in, out, m); else unshuffle_seq(0, m, in, out, r, m); for (k = 0; k < n; k += m) { fft_aux_seq(m, out + k, in + k, factors + 1, W, nW); } } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) fft_twiddle_2_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 4) fft_twiddle_4_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 8) fft_twiddle_8_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 16) fft_twiddle_16_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 32) fft_twiddle_32_seq(0, m, in, out, W, nW, nW / n, m); else fft_twiddle_gen_seq(0, m, in, out, W, nW, nW / n, r, m); return; } /* * user interface for fft_aux */ void fft(int n, COMPLEX * in, COMPLEX * out) { int *factors = (int *)malloc(40 * sizeof(int)); // int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; bots_message("Computing coefficients "); const unsigned long long full_program_start = current_time_ns(); { W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); #pragma omp parallel { #pragma omp single { #pragma omp task untied { compute_w_coefficients(n, 0, n / 2, W); } } } bots_message(" completed!\n"); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); bots_message("Computing FFT "); #pragma omp parallel { #pragma omp single { #pragma omp task untied { fft_aux(n, in, out, factors, W, n); } } } free(W); } ; const unsigned long long full_program_end = current_time_ns(); printf("full_program %llu ns\n", full_program_end - full_program_start); bots_message(" completed!\n"); return; } void fft_seq(int n, COMPLEX * in, COMPLEX * out) { int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); compute_w_coefficients_seq(n, 0, n / 2, W); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); fft_aux_seq(n, in, out, factors, W, n); free(W); return; } int test_correctness(int n, COMPLEX *out1, COMPLEX *out2) { int i; double a,d,error = 0.0; for (i = 0; i < n; ++i) { a = sqrt((c_re(out1[i]) - c_re(out2[i])) * (c_re(out1[i]) - c_re(out2[i])) + (c_im(out1[i]) - c_im(out2[i])) * (c_im(out1[i]) - c_im(out2[i]))); d = sqrt(c_re(out2[i]) * c_re(out2[i]) + c_im(out2[i]) * c_im(out2[i])); if (d < -1.0e-10 || d > 1.0e-10) a /= d; if (a > error) error = a; } bots_message("relative error=%e\n", error); if (error > 1e-3) return BOTS_RESULT_UNSUCCESSFUL; else return BOTS_RESULT_SUCCESSFUL; }
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright @ 2009 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; size_t columns, number_channels, rows; ssize_t y; 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); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images->next,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } image->depth=32UL; AppendImageToList(&complex_images,image); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { complex_images=DestroyImageList(complex_images); return(complex_images); } /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(images,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; number_channels=MagickMin(MagickMin(MagickMin( Ar_image->number_channels,Ai_image->number_channels),MagickMin( Br_image->number_channels,Bi_image->number_channels)),MagickMin( Cr_image->number_channels,Ci_image->number_channels)); Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; columns=MagickMin(Cr_image->columns,Ci_image->columns); rows=MagickMin(Cr_image->rows,Ci_image->rows); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,rows,1L) #endif for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; Quantum *magick_restrict Ci, *magick_restrict Cr; ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { ssize_t i; for (i=0; i < (ssize_t) number_channels; i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Ai[i]); break; } case DivideComplexOperator: { double gamma; gamma=QuantumRange*PerceptibleReciprocal(QuantumScale*Br[i]*Br[i]+ QuantumScale*Bi[i]*Bi[i]+snr); Cr[i]=gamma*(QuantumScale*Ar[i]*Br[i]+QuantumScale*Ai[i]*Bi[i]); Ci[i]=gamma*(QuantumScale*Ai[i]*Br[i]-QuantumScale*Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(QuantumScale*Ar[i]*Ar[i]+QuantumScale*Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=(QuantumScale*Ar[i]*Br[i]-QuantumScale*Ai[i]*Bi[i]); Ci[i]=(QuantumScale*Ai[i]*Br[i]+QuantumScale*Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width*sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; Quantum *q; ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; const Quantum *p; ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize forward transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; const Quantum *p; ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; Quantum *q; ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
diagsm_x_csc_n_col.c
#include "alphasparse/opt.h" #include "alphasparse/kernel.h" #include "alphasparse/util.h" #include <memory.h> alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *A, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, ALPHA_Number *y, const ALPHA_INT ldy) {//assume A is square ALPHA_Number* diag=(ALPHA_Number*) alpha_malloc(A->rows*sizeof(ALPHA_Number)); memset(diag, '\0', A->rows * sizeof(ALPHA_Number)); ALPHA_INT num_thread = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT c = 0; c < A->cols; c++) { for (ALPHA_INT ai = A->cols_start[c]; ai < A->cols_end[c]; ai++) { ALPHA_INT ar = A->row_indx[ai]; if (ar == c) { diag[c] = A->values[ai]; } } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT c = 0; c < columns; ++c) { for (ALPHA_INT r = 0; r < A->rows; ++r) { ALPHA_Number t; alpha_mul(t, alpha, x[index2(c, r, ldx)]); alpha_div(y[index2(c, r, ldy)], t, diag[r]); } } alpha_free(diag); return ALPHA_SPARSE_STATUS_SUCCESS; }
cuda-drv.c
// // cuda driver routines in C #include <stdio.h> #include <stdlib.h> #include <math.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <sys/time.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef USE_MPI #include <mpi.h> #else #include "mpi-dummy.h" #endif #include "cuda-drv.h" #include "cudalib.h" extern FILE* fp_prof; // from common/ofmo-prof.h static MPI_Comm CUDA_MPI_COMM = MPI_COMM_NULL; /* ------------------------------------- */ MPI_Comm cuda_Mpi_Comm(void) { return CUDA_MPI_COMM; } /* ------------------------------------- */ int cuda_Init(const int ndev, const int myrank, const int nprocs, const MPI_Comm comm) { int ret = 0; #ifdef _OPENMP #pragma omp master #endif { CUDA_MPI_COMM = comm; ret = cuda_Init_Sub(ndev, myrank, nprocs); } #ifdef _OPENMP #pragma omp barrier #endif return ret; } int cuda_Reconfig(const int myrank, const int nprocs, const MPI_Comm comm) { int ret = 0; int ndev = -1; #ifdef _OPENMP #pragma omp master #endif { CUDA_MPI_COMM = comm; ret = cuda_Init_Sub(ndev, myrank, nprocs); } #ifdef _OPENMP #pragma omp barrier #endif return ret; } int cuda_Finalize(void) { int ret = 0; #ifdef _OPENMP #pragma omp master #endif { ret = cuda_Finalize_Sub(); CUDA_MPI_COMM = MPI_COMM_WORLD; } #ifdef _OPENMP #pragma omp barrier #endif return ret; } /* ------------------------------------- */ void cuda_Barrier(void) { MPI_Comm comm = cuda_Mpi_Comm(); int master = TRUE; #ifdef _OPENMP master = (omp_get_thread_num() == 0); #pragma omp barrier #endif #ifdef USE_MPI if(master) MPI_Barrier(comm); #endif #ifdef _OPENMP #pragma omp barrier #endif } double cuda_Wtime(void) { #ifdef USE_MPI return MPI_Wtime(); #else struct timeval TV; gettimeofday(&TV, NULL); return(TV.tv_sec + (double)TV.tv_usec*1.0e-6); #endif } /* ------------------------------------- */
GB_binop__bor_int64.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__bor_int64) // A.*B function (eWiseMult): GB (_AemultB_08__bor_int64) // A.*B function (eWiseMult): GB (_AemultB_02__bor_int64) // A.*B function (eWiseMult): GB (_AemultB_04__bor_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_int64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bor_int64) // C+=b function (dense accum): GB (_Cdense_accumb__bor_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_int64) // C=scalar+B GB (_bind1st__bor_int64) // C=scalar+B' GB (_bind1st_tran__bor_int64) // C=A+scalar GB (_bind2nd__bor_int64) // C=A'+scalar GB (_bind2nd_tran__bor_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_BOR || GxB_NO_INT64 || GxB_NO_BOR_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__bor_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__bor_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__bor_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bor_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__bor_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__bor_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__bor_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__bor_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__bor_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__bor_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__bor_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__bor_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
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 % % John Cristy % % July 1998 % % % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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 "magick/studio.h" #include "magick/annotate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.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/property.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" /* Define declarations. */ #define BezierQuantum 200 /* 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 _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 MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *); static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *); static size_t TracePath(PrimitiveInfo *,const char *); static void TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(PrimitiveInfo *,const size_t), TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo, PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 *) AcquireMagickMemory(sizeof(*draw_info)); if (draw_info == (DrawInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); 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; clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info)); if (clone_info == (DrawInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); if (clone_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->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, &draw_info->fill_pattern->exception); else if (draw_info->tile != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->tile,0,0,MagickTrue, &draw_info->tile->exception); clone_info->tile=NewImageList(); /* tile is deprecated */ if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,&draw_info->stroke_pattern->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; draw_info->dash_pattern[x] != 0.0; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL, sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) CopyMagickMemory(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) CopyMagickMemory(clone_info->gradient.stops, draw_info->gradient.stops,(size_t) number_stops* sizeof(*clone_info->gradient.stops)); } if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); clone_info->bounds=draw_info->bounds; clone_info->clip_units=draw_info->clip_units; clone_info->render=draw_info->render; clone_info->opacity=draw_info->opacity; clone_info->element_reference=draw_info->element_reference; clone_info->debug=IsEventLogging(); 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 DrawInfo *draw_info, % 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 CompareEdges(const void *x,const void *y) { register const EdgeInfo *p, *q; /* Compare two edges. */ p=(const EdgeInfo *) x; q=(const EdgeInfo *) y; if ((p->points[0].y-MagickEpsilon) > q->points[0].y) return(1); if ((p->points[0].y+MagickEpsilon) < q->points[0].y) return(-1); if ((p->points[0].x-MagickEpsilon) > q->points[0].x) return(1); if ((p->points[0].x+MagickEpsilon) < q->points[0].x) return(-1); if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)- (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0) return(1); return(-1); } #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 DrawInfo *magick_unused(draw_info),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((size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) ResetMagickMemory(&point,0,sizeof(point)); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); 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) || ((path_info[i].point.y == point.y) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((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),CompareEdges); 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 DrawInfo *magick_unused(draw_info),const PrimitiveInfo *primitive_info) { 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 PointPrimitive: case ColorPrimitive: case MattePrimitive: case TextPrimitive: case ImagePrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) return((PathInfo *) NULL); coordinates=0; 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) { coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; } coordinates--; /* Eliminate duplicate points. */ if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon)) { path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; if ((fabs(p.x-primitive_info[i].point.x) < MagickEpsilon) && (fabs(p.y-primitive_info[i].point.y) < MagickEpsilon)) continue; /* Mark the p point as open if it does not match the q. */ 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); 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) { if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); 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->tile != (Image *) NULL) draw_info->tile=DestroyImage(draw_info->tile); 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); draw_info->signature=(~MagickSignature); 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) CopyMagickMemory(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) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % */ 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); } static inline ssize_t MagickAbsoluteValue(const ssize_t x) { if (x < 0) return(-x); return(x); } 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); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; ExceptionInfo *exception; MagickBooleanType status; MagickPixelPacket zero; PointInfo extent[4], min, max, point; register ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickSignature); 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++) { 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) == 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); GetMagickPixelPacket(image,&zero); exception=(&image->exception); 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,4) shared(status) \ magick_threads(source,image,1,1) #endif for (y=start; y <= stop; y++) { MagickPixelPacket composite, pixel; PointInfo point; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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 == (PixelPacket *) NULL) continue; indexes=GetCacheViewAuthenticIndexQueue(image_view); 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; (void) InterpolateMagickPixelPacket(source,source_view, UndefinedInterpolatePixel,point.x,point.y,&pixel,exception); SetMagickPixelPacket(image,q,indexes+x_offset,&composite); MagickPixelCompositeOver(&pixel,pixel.opacity,&composite, composite.opacity,&composite); SetPixelPacket(image,&composite,q,indexes+x_offset); x_offset++; q++; } 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: % % void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, % PolygonInfo *polygon_info) % % 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. % */ static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, const PolygonInfo *polygon_info) { double mid; DrawInfo *clone_info; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; register ssize_t i; SegmentInfo bounds; ssize_t coordinates; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) QueryColorDatabase("#0000",&clone_info->fill,&image->exception); resolution.x=DefaultResolution; resolution.y=DefaultResolution; 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/72.0)*ExpandAffine(&clone_info->affine)* clone_info->stroke_width/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) (void) QueryColorDatabase("red",&clone_info->stroke, &image->exception); else (void) QueryColorDatabase("green",&clone_info->stroke, &image->exception); 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; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info); } } (void) QueryColorDatabase("blue",&clone_info->stroke,&image->exception); 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; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info); clone_info=DestroyDrawInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 *name) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the name of the clip path. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name) { char clip_mask[MaxTextExtent]; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(clip_mask,MaxTextExtent,"%s",name); value=GetImageArtifact(image,clip_mask); if (value == (const char *) NULL) return(MagickFalse); if (image->clip_mask == (Image *) NULL) { Image *clip_mask; clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue, &image->exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) SetImageClipMask(image,clip_mask); clip_mask=DestroyImage(clip_mask); } (void) QueryColorDatabase("#00000000",&image->clip_mask->background_color, &image->exception); image->clip_mask->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(image->clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorDatabase("#ffffff",&clone_info->fill,&image->exception); clone_info->clip_mask=(char *) NULL; status=DrawImage(image->clip_mask,clone_info); status|=NegateImage(image->clip_mask,MagickFalse); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + 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) % % 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. % % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image) { 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"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+1UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=draw_info->dash_offset != 0.0 ? 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]+(n == 0 ? -0.5 : 0.5)); 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; 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((double) dx,dy); if (length == 0.0) { n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (total_length+length) <= maximum_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/maximum_length); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); j=1; } else { if ((j+1) > (ssize_t) (2*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/maximum_length); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/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); } n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((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); } 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 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) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % */ static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=StringToDouble(point,&p); return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue); } static inline void TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->point=point; } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char key[2*MaxTextExtent], keyword[MaxTextExtent], geometry[MaxTextExtent], name[MaxTextExtent], pattern[MaxTextExtent], *primitive, *token; const char *q; double angle, factor, primitive_extent; DrawInfo **graphic_context; MagickBooleanType proceed, status; PointInfo point; PixelPacket start_color; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t length, number_points; ssize_t j, k, n; /* Ensure the annotation info is valid. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else primitive=FileToString(draw_info->primitive+1,~0,&image->exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",primitive); n=0; /* 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=6553; 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); } 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); (void) QueryColorDatabase("#000000",&start_color,&image->exception); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetMagickToken(q,&q,keyword); 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); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetMagickToken(q,&q,token); affine.sx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.rx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.ry=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.sy=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.tx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.ty=StringToDouble(token,(char **) NULL); 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) { GetMagickToken(q,&q,token); (void) QueryColorDatabase(token,&graphic_context[n]->border_color, &image->exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("clip-path",keyword) == 0) { /* Create clip mask. */ GetMagickToken(q,&q,token); (void) CloneString(&graphic_context[n]->clip_mask,token); (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask); break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; GetMagickToken(q,&q,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) { status=MagickFalse; break; } graphic_context[n]->decorate=(DecorationType) decorate; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { GetMagickToken(q,&q,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetMagickToken(q,&q,token); (void) FormatLocaleString(pattern,MaxTextExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern); else { status=QueryColorDatabase(token,&graphic_context[n]->fill, &image->exception); if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MaxTextExtent); graphic_context[n]->fill_pattern= ReadImage(pattern_info,&image->exception); CatchException(&image->exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { GetMagickToken(q,&q,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->fill.opacity=ClampToQuantum((MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token,(char **) NULL))); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->weight=StringToUnsignedLong(token); if (LocaleCompare(token,"all") == 0) graphic_context[n]->weight=0; if (LocaleCompare(token,"bold") == 0) graphic_context[n]->weight=700; if (LocaleCompare(token,"bolder") == 0) if (graphic_context[n]->weight <= 800) graphic_context[n]->weight+=100; if (LocaleCompare(token,"lighter") == 0) if (graphic_context[n]->weight >= 100) graphic_context[n]->weight-=100; if (LocaleCompare(token,"normal") == 0) graphic_context[n]->weight=400; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetMagickToken(q,&q,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->interline_spacing=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->interword_spacing=StringToDouble(token, (char **) NULL); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->kerning=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) { primitive_type=LinePrimitive; break; } status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("matte",keyword) == 0) { primitive_type=MattePrimitive; break; } status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetMagickToken(q,&q,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetMagickToken(q,&q,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->opacity=ClampToQuantum((MagickRealType) QuantumRange*(1.0-((1.0-QuantumScale*graphic_context[n]->opacity)* factor*StringToDouble(token,(char **) NULL)))); graphic_context[n]->fill.opacity=graphic_context[n]->opacity; graphic_context[n]->stroke.opacity=graphic_context[n]->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) { GetMagickToken(q,&q,token); if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) break; if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),DrawError, "UnbalancedGraphicContextPushPop","`%s'",token); n=0; break; } if (graphic_context[n]->clip_mask != (char *) NULL) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) (void) SetImageClipMask(image,(Image *) NULL); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("pattern",token) == 0) break; status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { GetMagickToken(q,&q,token); if (LocaleCompare("clip-path",token) == 0) { char name[MaxTextExtent]; GetMagickToken(q,&q,token); (void) FormatLocaleString(name,MaxTextExtent,"%s",token); for (p=q; *q != '\0'; ) { GetMagickToken(q,&q,token); if (LocaleCompare(token,"pop") != 0) continue; GetMagickToken(q,(const char **) NULL,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) SetImageArtifact(image,name,token); GetMagickToken(q,&q,token); break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MaxTextExtent], name[MaxTextExtent], type[MaxTextExtent]; SegmentInfo segment; GetMagickToken(q,&q,token); (void) CopyMagickString(name,token,MaxTextExtent); GetMagickToken(q,&q,token); (void) CopyMagickString(type,token,MaxTextExtent); GetMagickToken(q,&q,token); segment.x1=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); segment.y1=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); segment.x2=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); segment.y2=StringToDouble(token,(char **) NULL); if (LocaleCompare(type,"radial") == 0) { GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); } for (p=q; *q != '\0'; ) { GetMagickToken(q,&q,token); if (LocaleCompare(token,"pop") != 0) continue; GetMagickToken(q,(const char **) NULL,token); if (LocaleCompare(token,"gradient") != 0) continue; 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,MaxTextExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MaxTextExtent, "%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); GetMagickToken(q,&q,token); break; } if (LocaleCompare("pattern",token) == 0) { RectangleInfo bounds; GetMagickToken(q,&q,token); (void) CopyMagickString(name,token,MaxTextExtent); GetMagickToken(q,&q,token); bounds.x=(ssize_t) ceil(StringToDouble(token,(char **) NULL)- 0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); bounds.y=(ssize_t) ceil(StringToDouble(token,(char **) NULL)- 0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); bounds.width=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); bounds.height=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); for (p=q; *q != '\0'; ) { GetMagickToken(q,&q,token); if (LocaleCompare(token,"pop") != 0) continue; GetMagickToken(q,(const char **) NULL,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MaxTextExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double) bounds.height,(double) bounds.x,(double) bounds.y); (void) SetImageArtifact(image,key,geometry); GetMagickToken(q,&q,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(&image->exception, GetMagickModule(),ResourceLimitError, "MemoryAllocationFailed","`%s'",image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); break; } if (LocaleCompare("defs",token) == 0) 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) { GetMagickToken(q,&q,token); angle=StringToDouble(token,(char **) NULL); 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) { GetMagickToken(q,&q,token); affine.sx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.sy=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("skewX",keyword) == 0) { GetMagickToken(q,&q,token); angle=StringToDouble(token,(char **) NULL); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetMagickToken(q,&q,token); angle=StringToDouble(token,(char **) NULL); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelPacket stop_color; GetMagickToken(q,&q,token); (void) QueryColorDatabase(token,&stop_color,&image->exception); (void) GradientImage(image,LinearGradient,ReflectSpread, &start_color,&stop_color); start_color=stop_color; GetMagickToken(q,&q,token); break; } if (LocaleCompare("stroke",keyword) == 0) { GetMagickToken(q,&q,token); (void) FormatLocaleString(pattern,MaxTextExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern); else { status=QueryColorDatabase(token,&graphic_context[n]->stroke, &image->exception); if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MaxTextExtent); graphic_context[n]->stroke_pattern= ReadImage(pattern_info,&image->exception); CatchException(&image->exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetMagickToken(q,&q,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 *p; p=q; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2UL*x+1UL), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(&image->exception, GetMagickModule(),ResourceLimitError, "MemoryAllocationFailed","`%s'",image->filename); break; } for (j=0; j < x; j++) { GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, (char **) NULL); } 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; } GetMagickToken(q,&q,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->dash_offset=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { GetMagickToken(q,&q,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->stroke.opacity=ClampToQuantum((MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token,(char **) NULL))); break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->stroke_width=StringToDouble(token, (char **) NULL); 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; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->text_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetMagickToken(q,&q,token); (void) QueryColorDatabase(token,&graphic_context[n]->undercolor, &image->exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetMagickToken(q,&q,token); affine.tx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.ty=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) || (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0)) { 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 (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s", (int) (q-p),p); continue; } /* Parse the primitive attributes. */ i=0; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; GetMagickToken(q,&q,token); point.x=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); point.y=StringToDouble(token,(char **) NULL); GetMagickToken(q,(const char **) NULL,token); if (*token == ',') GetMagickToken(q,&q,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; i++; if (i < (ssize_t) number_points) continue; number_points<<=1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); break; } } primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].text=(char *) NULL; /* 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. */ length=primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { length*=5; break; } case RoundRectanglePrimitive: { length*=5+8*BezierQuantum; break; } case BezierPrimitive: { if (primitive_info[j].coordinates > 107) (void) ThrowMagickException(&image->exception,GetMagickModule(), DrawError,"TooManyBezierCoordinates","`%s'",token); length=BezierQuantum*primitive_info[j].coordinates; break; } case PathPrimitive: { char *s, *t; GetMagickToken(q,&q,token); length=1; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } length++; } length=length*BezierQuantum/2; break; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } default: break; } if ((size_t) (i+length) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=length+1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } } switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } 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; } 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; } 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; } TraceRoundRectangle(primitive_info+j,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; } TraceArc(primitive_info+j,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; } TraceEllipse(primitive_info+j,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; } TraceCircle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: break; case PolygonPrimitive: { primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } TraceBezier(primitive_info+j,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { i=(ssize_t) (j+TracePath(primitive_info+j,token)); break; } case ColorPrimitive: case MattePrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetMagickToken(q,&q,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) { status=MagickFalse; break; } primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') GetMagickToken(q,&q,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetMagickToken(q,&q,token); primitive_info[j].text=AcquireString(token); break; } } if (primitive_info == (PrimitiveInfo *) NULL) break; if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),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]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask); (void) DrawPrimitive(image,graphic_context[n],primitive_info); } if (primitive_info->text != (char *) NULL) primitive_info->text=(char *) RelinquishMagickMemory( primitive_info->text); proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); primitive=DestroyString(primitive); 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); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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) % % A description of each parameter follows: % % o image: the image. % % o _info: the draw info. % */ 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: { double length, offset; PointInfo v; v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; length=sqrt(v.x*v.x+v.y*v.y); if (gradient->spread == RepeatSpread) return(length); offset=length/gradient->radius; return(offset); } } return(0.0); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; ExceptionInfo *exception; MagickBooleanType status; MagickPixelPacket zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); 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; exception=(&image->exception); GetMagickPixelPacket(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { double alpha, offset; MagickPixelPacket composite, pixel; register IndexPacket *restrict indexes; register ssize_t i, x; register PixelPacket *restrict q; ssize_t j; 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); pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset/=length; for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { SetMagickPixelPacket(image,q,indexes+x,&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/=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); MagickPixelCompositeBlend(&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/=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); MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { double repeat; MagickBooleanType antialias; 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=repeat/length; } 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; } MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } MagickPixelCompositeOver(&composite,composite.opacity,&pixel, pixel.opacity,&pixel); SetPixelPacket(image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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) % % 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. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern) { char property[MaxTextExtent]; const char *geometry, *path; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); 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,MaxTextExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MaxTextExtent,"%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); image_info=DestroyImageInfo(image_info); (void) QueryColorDatabase("#00000000",&(*pattern)->background_color, &image->exception); (void) SetImageBackgroundColor(*pattern); 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) CloneString(&clone_info->primitive,path); status=DrawImage(*pattern,clone_info); 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) % % 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 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 DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { PathInfo *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) ResetMagickMemory(polygon_info,0,(size_t) GetMagickResourceLimit(ThreadResource)*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(draw_info,primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(draw_info,path_info); if (polygon_info[i] == (PolygonInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static double GetOpacityPixel(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_opacity) { double alpha, beta, distance, subpath_opacity; PointInfo delta; register EdgeInfo *p; register const PointInfo *q; register ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_opacity=0.0; subpath_opacity=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=1.0/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_opacity < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_opacity=1.0; else { beta=1.0; if (distance != 1.0) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_opacity < ((alpha-0.25)*(alpha-0.25))) *stroke_opacity=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_opacity >= 1.0)) continue; if (distance <= 0.0) { subpath_opacity=1.0; continue; } if (distance > 1.0) continue; if (beta == 0.0) { beta=1.0; if (distance != 1.0) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_opacity < (alpha*alpha)) subpath_opacity=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_opacity >= 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; 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_opacity); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { CacheView *image_view; double mid; ExceptionInfo *exception; MagickBooleanType fill, status; PolygonInfo **restrict polygon_info; register EdgeInfo *p; register ssize_t i; SegmentInfo bounds; ssize_t start, stop, y; /* Compute bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates == 0) return(MagickTrue); polygon_info=AcquirePolygonThreadSet(draw_info,primitive_info); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); if (0) DrawBoundingRectangles(image,draw_info,polygon_info[0]); 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)*draw_info->stroke_width/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.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >= image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=(mid+1.0); bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >= image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=(mid+1.0); bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >= image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=(mid+1.0); bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >= image->rows ? (double) image->rows-1 : bounds.y2; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); if (primitive_info->coordinates == 1) { /* Draw point. */ start=(ssize_t) ceil(bounds.y1-0.5); stop=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=start; y <= stop; y++) { MagickBooleanType sync; register PixelPacket *restrict q; register ssize_t x; ssize_t start, stop; if (status == MagickFalse) continue; start=(ssize_t) ceil(bounds.x1-0.5); stop=(ssize_t) floor(bounds.x2+0.5); x=start; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop-x+1),1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for ( ; x <= stop; x++) { if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) ceil(primitive_info->point.y-0.5))) (void) GetStrokeColor(draw_info,x,y,q); q++; } 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. */ if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); start=(ssize_t) ceil(bounds.y1-0.5); stop=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=start; y <= stop; y++) { const int id = GetOpenMPThreadId(); double fill_opacity, stroke_opacity; PixelPacket fill_color, stroke_color; register PixelPacket *restrict q; register ssize_t x; ssize_t start, stop; if (status == MagickFalse) continue; start=(ssize_t) ceil(bounds.x1-0.5); stop=(ssize_t) floor(bounds.x2+0.5); q=GetCacheViewAuthenticPixels(image_view,start,y,(size_t) (stop-start+1),1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=start; x <= stop; x++) { /* Fill and/or stroke. */ fill_opacity=GetOpacityPixel(polygon_info[id],mid,fill, draw_info->fill_rule,x,y,&stroke_opacity); if (draw_info->stroke_antialias == MagickFalse) { fill_opacity=fill_opacity > 0.25 ? 1.0 : 0.0; stroke_opacity=stroke_opacity > 0.25 ? 1.0 : 0.0; } (void) GetFillColor(draw_info,x,y,&fill_color); fill_opacity=(double) (QuantumRange-fill_opacity*(QuantumRange- fill_color.opacity)); MagickCompositeOver(&fill_color,(MagickRealType) fill_opacity,q, (MagickRealType) q->opacity,q); (void) GetStrokeColor(draw_info,x,y,&stroke_color); stroke_opacity=(double) (QuantumRange-stroke_opacity*(QuantumRange- stroke_color.opacity)); MagickCompositeOver(&stroke_color,(MagickRealType) stroke_opacity,q, (MagickRealType) q->opacity,q); q++; } 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) % % 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 void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, q, point; 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 PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.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 MattePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "MattePrimitive %.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; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.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) { CacheView *image_view; ExceptionInfo *exception; 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); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelGray(&draw_info->fill) == MagickFalse) || (IsPixelGray(&draw_info->stroke) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace); status=MagickTrue; exception=(&image->exception); x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case PointPrimitive: { PixelPacket fill_color; PixelPacket *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 == (PixelPacket *) NULL) break; (void) GetFillColor(draw_info,x,y,&fill_color); MagickCompositeOver(&fill_color,(MagickRealType) fill_color.opacity,q, (MagickRealType) q->opacity,q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelPacket *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; (void) GetFillColor(draw_info,x,y,q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelPacket target; (void) GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) == MagickFalse) { q++; continue; } (void) GetFillColor(draw_info,x,y,q); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { MagickPixelPacket target; (void) GetOneVirtualMagickPixel(image,x,y,&target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(MagickRealType) draw_info->border_color.red; target.green=(MagickRealType) draw_info->border_color.green; target.blue=(MagickRealType) draw_info->border_color.blue; } (void) FloodfillPaintImage(image,DefaultChannels,draw_info,&target,x, y,primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue); break; } case ResetMethod: { MagickBooleanType sync; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) GetFillColor(draw_info,x,y,q); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case MattePrimitive: { if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); switch (primitive_info->method) { case PointMethod: default: { PixelPacket pixel; PixelPacket *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; (void) GetFillColor(draw_info,x,y,&pixel); SetPixelOpacity(q,pixel.opacity); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelPacket pixel, target; (void) GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) == MagickFalse) { q++; continue; } (void) GetFillColor(draw_info,x,y,&pixel); SetPixelOpacity(q,pixel.opacity); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { MagickPixelPacket target; (void) GetOneVirtualMagickPixel(image,x,y,&target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(MagickRealType) draw_info->border_color.red; target.green=(MagickRealType) draw_info->border_color.green; target.blue=(MagickRealType) draw_info->border_color.blue; } (void) FloodfillPaintImage(image,OpacityChannel,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue); break; } case ResetMethod: { MagickBooleanType sync; PixelPacket pixel; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) GetFillColor(draw_info,x,y,&pixel); SetPixelOpacity(q,pixel.opacity); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case TextPrimitive: { char geometry[MaxTextExtent]; 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,MaxTextExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status=AnnotateImage(image,clone_info); clone_info=DestroyDrawInfo(clone_info); break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MaxTextExtent]; Image *composite_image; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_image=ReadInlineImage(clone_info,primitive_info->text, &image->exception); else { (void) CopyMagickString(clone_info->filename,primitive_info->text, MaxTextExtent); composite_image=ReadImage(clone_info,&image->exception); } clone_info=DestroyImageInfo(clone_info); if (composite_image == (Image *) NULL) break; (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))) { char geometry[MaxTextExtent]; /* Resize image. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g!", primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; (void) TransformImage(&composite_image,(char *) NULL,geometry); } if (composite_image->matte == MagickFalse) (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel); if (draw_info->opacity != OpaqueOpacity) (void) SetImageOpacity(composite_image,draw_info->opacity); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry, &image->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) (void) DrawAffineImage(image,composite_image,&affine); else (void) CompositeImage(image,draw_info->compose,composite_image, geometry.x,geometry.y); composite_image=DestroyImage(composite_image); 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) && (draw_info->dash_pattern[0] != 0.0) && ((scale*draw_info->stroke_width) >= MagickEpsilon) && (draw_info->stroke.opacity != (Quantum) TransparentOpacity)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.opacity=(Quantum) TransparentOpacity; status=DrawPolygonPrimitive(image,clone_info,primitive_info); clone_info=DestroyDrawInfo(clone_info); (void) DrawDashPolygon(draw_info,primitive_info,image); break; } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; if ((mid > 1.0) && (draw_info->stroke.opacity != (Quantum) TransparentOpacity)) { MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; closed_path= (primitive_info[i-1].point.x == primitive_info[0].point.x) && (primitive_info[i-1].point.y == primitive_info[0].point.y) ? MagickTrue : MagickFalse; i=(ssize_t) primitive_info[0].coordinates; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { (void) DrawPolygonPrimitive(image,draw_info,primitive_info); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.opacity=(Quantum) TransparentOpacity; status=DrawPolygonPrimitive(image,clone_info,primitive_info); clone_info=DestroyDrawInfo(clone_info); status|=DrawStrokePolygon(image,draw_info,primitive_info); break; } status=DrawPolygonPrimitive(image,draw_info,primitive_info); break; } } image_view=DestroyCacheView(image_view); 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 void DrawRoundLinecap(Image *image,const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { 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+=(double) (10.0*MagickEpsilon); linecap[2].point.x+=(double) (10.0*MagickEpsilon); linecap[2].point.y+=(double) (10.0*MagickEpsilon); linecap[3].point.y+=(double) (10.0*MagickEpsilon); linecap[4].primitive=UndefinedPrimitive; (void) DrawPolygonPrimitive(image,draw_info,linecap); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { DrawInfo *clone_info; MagickBooleanType closed_path, 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,&clone_info->stroke_pattern->exception); clone_info->stroke.opacity=(Quantum) TransparentOpacity; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { stroke_polygon=TraceStrokePolygon(draw_info,p); status=DrawPolygonPrimitive(image,clone_info,stroke_polygon); stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); q=p+p->coordinates-1; closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ? MagickTrue : MagickFalse; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { DrawRoundLinecap(image,draw_info,p); DrawRoundLinecap(image,draw_info,q); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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) ResetMagickMemory(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) { const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorDatabase("#000F",&draw_info->fill,exception); (void) QueryColorDatabase("#FFF0",&draw_info->stroke,exception); draw_info->stroke_antialias=clone_info->antialias; draw_info->stroke_width=1.0; draw_info->opacity=OpaqueOpacity; draw_info->fill_rule=EvenOddRule; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; 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; draw_info->pointsize=12.0; if (clone_info->pointsize != 0.0) draw_info->pointsize=clone_info->pointsize; draw_info->undercolor.opacity=(Quantum) TransparentOpacity; draw_info->border_color=clone_info->border_color; draw_info->compose=OverCompositeOp; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,(char **) NULL); draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&draw_info->fill,exception); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&draw_info->stroke,exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&draw_info->undercolor,exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); exception=DestroyExceptionInfo(exception); draw_info->signature=MagickSignature; 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 void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radii; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radii.x=fabs(center.x-start.x); radii.y=fabs(center.y-start.y); TraceEllipse(primitive_info,center,radii,degrees); } static void TraceArcPath(PrimitiveInfo *primitive_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; PointInfo center, points[3], radii; register double cosine, sine; register PrimitiveInfo *p; register ssize_t i; size_t arc_segments; if ((start.x == end.x) && (start.y == end.y)) { TracePoint(primitive_info,end); return; } radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((radii.x == 0.0) || (radii.y == 0.0)) { TraceLine(primitive_info,start,end); return; } 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) { TraceLine(primitive_info,start,end); return; } 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; 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)))); 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; TraceBezier(p,4); p+=p->coordinates; } primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceBezier(PrimitiveInfo *primitive_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coeficients. */ 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) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=(size_t) MagickMin((double) quantum/number_coordinates, (double) BezierQuantum); control_points=quantum*number_coordinates; coefficients=(double *) AcquireQuantumMemory((size_t) number_coordinates,sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory((size_t) control_points, sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); /* 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++) { TracePoint(p,points[i]); p+=p->coordinates; } TracePoint(p,end); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); } static void TraceCircle(PrimitiveInfo *primitive_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; TraceEllipse(primitive_info,start,offset,degrees); } static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo stop,const PointInfo degrees) { double delta, step, y; PointInfo angle, point; register PrimitiveInfo *p; register ssize_t i; /* Ellipses are just short segmented polys. */ if ((stop.x == 0.0) && (stop.y == 0.0)) { TracePoint(primitive_info,start); return; } delta=2.0/MagickMax(stop.x,stop.y); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/(4*(MagickPI/delta/2+0.5)); angle.x=DegreesToRadians(degrees.x); y=degrees.y; while (y < degrees.x) y+=360.0; angle.y=(double) (DegreesToRadians(y)-MagickEpsilon); for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y; TracePoint(p,point); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y; TracePoint(p,point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { TracePoint(primitive_info,start); if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return; } TracePoint(primitive_info+1,end); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; } static size_t TracePath(PrimitiveInfo *primitive_info,const char *path) { char token[MaxTextExtent]; const char *p; double x, y; int attribute, last_attribute; PointInfo end, points[4], point, start; PrimitiveType primitive_type; register PrimitiveInfo *q; register ssize_t i; size_t number_coordinates, z_count; attribute=0; point.x=0.0; point.y=0.0; start.x=0.0; start.y=0.0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { 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; MagickBooleanType large_arc, sweep; PointInfo arc; /* Compute arc points. */ do { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); arc.x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); arc.y=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); angle=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); TraceArcPath(q,point,end,arc,angle,large_arc,sweep); 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': { /* Compute bezier points. */ do { points[0]=point; for (i=1; i < 4; i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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]; TraceBezier(q,4); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { do { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { if (q != primitive_info) { primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; } i=0; do { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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++; TracePoint(q,point); q+=q->coordinates; if ((i != 0) && (attribute == (int) 'M')) { TracePoint(q,point); q+=q->coordinates; } } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Compute bezier points. */ do { points[0]=point; for (i=1; i < 3; i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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]; TraceBezier(q,3); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Compute bezier points. */ 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++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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]=points[2]; points[1]=points[3]; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Compute bezier points. */ 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++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=points[2]; points[1]=points[3]; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { do { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { point=start; TracePoint(q,point); q+=q->coordinates; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; z_count++; break; } default: { if (isalpha((int) ((unsigned char) attribute)) != 0) (void) FormatLocaleFile(stderr,"attribute not recognized: %c\n", attribute); break; } } } 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 void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { PointInfo point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; TracePoint(p,start); p+=p->coordinates; point.x=start.x; point.y=end.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,end); p+=p->coordinates; point.x=end.x; point.y=start.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,start); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceRoundRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, offset, point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; offset.x=fabs(end.x-start.x); offset.y=fabs(end.y-start.y); if (arc.x > (0.5*offset.x)) arc.x=0.5*offset.x; if (arc.y > (0.5*offset.y)) arc.y=0.5*offset.y; point.x=start.x+offset.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+offset.x-arc.x; point.y=start.y+offset.y-arc.y; degrees.x=0.0; degrees.y=90.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+offset.y-arc.y; degrees.x=90.0; degrees.y=180.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; TracePoint(p,primitive_info->point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void 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); } static inline double DrawEpsilonReciprocal(const double x) { #define DrawEpsilon (1.0e-10) double sign = x < 0.0 ? -1.0 : 1.0; return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon)); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { typedef struct _LineSegment { double p, q; } LineSegment; double delta_theta, dot_product, mid, miterlimit; LineSegment dx, dy, inverse_slope, slope, theta; 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; path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) || (polygon_primitive == (PrimitiveInfo *) NULL)) return((PrimitiveInfo *) NULL); (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t) number_vertices*sizeof(*polygon_primitive)); closed_path= (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) && (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ? MagickTrue : MagickFalse; 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) n=(ssize_t) number_vertices-1L; slope.p=DrawEpsilonReciprocal(dx.p)*dy.p; inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p)); mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) 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=DrawEpsilonReciprocal(dx.q)*dy.q; inverse_slope.q=(-1.0*DrawEpsilonReciprocal(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); } if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) { max_strokes+=6*BezierQuantum+360; path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes, sizeof(*path_q)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) { polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return((PrimitiveInfo *) NULL); } } 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))))); 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=(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))))); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(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); }
GB_unop__identity_int16_fc64.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__identity_int16_fc64) // op(A') function: GB (_unop_tran__identity_int16_fc64) // C type: int16_t // A type: GxB_FC64_t // cast: int16_t cij = GB_cast_to_int16_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_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) \ int16_t z = GB_cast_to_int16_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = GB_cast_to_int16_t (creal (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_fc64) ( int16_t *Cx, // Cx and Ax may be aliased const GxB_FC64_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++) { GxB_FC64_t aij = Ax [p] ; int16_t z = GB_cast_to_int16_t (creal (aij)) ; Cx [p] = 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 ; GxB_FC64_t aij = Ax [p] ; int16_t z = GB_cast_to_int16_t (creal (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_int16_fc64) ( 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_unaryop__abs_fp64_int64.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__abs_fp64_int64 // op(A') function: GB_tran__abs_fp64_int64 // C type: double // A type: int64_t // cast: double cij = (double) aij // unaryop: cij = fabs (aij) #define GB_ATYPE \ int64_t #define GB_CTYPE \ double // 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 = fabs (x) ; // casting #define GB_CASTING(z, aij) \ double z = (double) 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_ABS || GxB_NO_FP64 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_fp64_int64 ( double *Cx, // Cx and Ax may be aliased int64_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__abs_fp64_int64 ( 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
convolution_packn_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 convolution_packn_fp16s_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat32m2_t _sum = vfmv_v_f_f32m2(0.f, vl); if (bias_data_ptr) { _sum = vle32_v_f32m2(bias_data_ptr + p * packn, vl); } const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * packn; for (int k = 0; k < maxk; k++) { const __fp16* slptr = sptr + space_ofs[k] * packn; for (int l = 0; l < packn; l++) { float val = (float)*slptr++; vfloat32m2_t _w0 = vfwcvt_f_f_v_f32m2(vle16_v_f16m1(kptr, vl), vl); _sum = vfmacc_vf_f32m2(_sum, val, _w0, vl); kptr += packn; } } } _sum = activation_ps(_sum, activation_type, activation_params, vl); vse16_v_f16m1(outptr + j * packn, vfncvt_f_f_w_f16m1(_sum, vl), vl); } outptr += outw * packn; } } } static void convolution_packn_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data_fp16, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const __fp16* bias_data_ptr = bias_data_fp16; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat16m1_t _sum = vfmv_v_f_f16m1(0.f, vl); if (bias_data_ptr) { _sum = vle16_v_f16m1(bias_data_ptr + p * packn, vl); } const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * packn; for (int k = 0; k < maxk; k++) { const __fp16* slptr = sptr + space_ofs[k] * packn; for (int l = 0; l < packn; l++) { __fp16 val = *slptr++; vfloat16m1_t _w0 = vle16_v_f16m1(kptr, vl); _sum = vfmacc_vf_f16m1(_sum, val, _w0, vl); kptr += packn; } } } _sum = activation_ps(_sum, activation_type, activation_params, vl); vse16_v_f16m1(outptr + j * packn, _sum, vl); } outptr += outw * packn; } } }
GB_binop__first_fc32.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__first_fc32 // A.*B function (eWiseMult): GB_AemultB__first_fc32 // A*D function (colscale): GB_AxD__first_fc32 // D*A function (rowscale): GB_DxB__first_fc32 // C+=B function (dense accum): GB_Cdense_accumB__first_fc32 // C+=b function (dense accum): GB_Cdense_accumb__first_fc32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__first_fc32 // C=scalar+B GB_bind1st__first_fc32 // C=scalar+B' GB_bind1st_tran__first_fc32 // C=A+scalar (none) // C=A'+scalar (none) // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_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) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_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 ; // 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_FIRST || GxB_NO_FC32 || GxB_NO_FIRST_FC32) //------------------------------------------------------------------------------ // 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__first_fc32 ( 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__first_fc32 ( 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 #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__first_fc32 ( 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 GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_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__first_fc32 ( 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 GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_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__first_fc32 ( 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 GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_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__first_fc32 ( 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__first_fc32 ( 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__first_fc32 ( 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 GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { ; ; Cx [p] = x ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( 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 ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; Cx [p] = aij ; } return (GrB_SUCCESS) ; #endif } #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) \ { \ ; ; \ Cx [pC] = x ; \ } GrB_Info GB_bind1st_tran__first_fc32 ( 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 \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = aij ; \ } GrB_Info (none) ( 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 GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
omp-fibonacci.c
#include <stdio.h> #include <omp.h> int f(int n) { int i, j; if (n<2) return n; #pragma omp task shared(i) firstprivate(n) i = f(n-1); #pragma omp task shared(j) firstprivate(n) j = f(n-2); #pragma omp taskwait return i+j; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: %s n\n", argv[0]); return 1; } int n = atoi(argv[1]); #pragma omp parallel shared(n) { #pragma omp single printf("f(%d) = %d\n", n, f(n)); } }
nest_lock.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> int main() { //need to use an OpenMP construct so that OMPT will be initialized #pragma omp parallel num_threads(1) print_ids(0); omp_nest_lock_t nest_lock; printf("%" PRIu64 ": &nest_lock: %lli\n", ompt_get_thread_data()->value, (ompt_wait_id_t)(uintptr_t) &nest_lock); omp_init_nest_lock(&nest_lock); print_fuzzy_address(1); omp_set_nest_lock(&nest_lock); print_fuzzy_address(2); omp_set_nest_lock(&nest_lock); print_fuzzy_address(3); omp_unset_nest_lock(&nest_lock); print_fuzzy_address(4); omp_unset_nest_lock(&nest_lock); print_fuzzy_address(5); omp_destroy_nest_lock(&nest_lock); print_fuzzy_address(6); // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_acquire' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_acquired' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_released' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_nest_lock' // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_init_nest_lock: wait_id=[[WAIT_ID:[0-9]+]], hint={{[0-9]+}}, impl={{[0-9]+}}, codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_nest_lock: wait_id=[[WAIT_ID]], hint={{[0-9]+}}, impl={{[0-9]+}}, codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_acquired_nest_lock_first: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_nest_lock: wait_id=[[WAIT_ID]], hint={{[0-9]+}}, impl={{[0-9]+}}, codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_acquired_nest_lock_next: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS]] // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_release_nest_lock_prev: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_release_nest_lock_last: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_destroy_nest_lock: wait_id=[[WAIT_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // CHECK-NEXT: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] return 0; }
laplace.h
#ifndef LAPLACE_H #define LAPLACE_H void laplace(const Storage3D& in, Storage3D& out) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { for (int64_t k = 0; k < domain_height; ++k) { out(i, j, k) = -4.0 * in(i, j, k) + ((in(i - 1, j, k) + in(i + 1, j, k)) + (in(i, j + 1, k) + in(i, j - 1, k))); } } } } void laplace_fullfusion(const Storage3D& in, Storage3D& out) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { for (int64_t k = 0; k < domain_height; ++k) { out(i, j, k) = -4.0 * in(i, j, k) + ((in(i - 1, j, k) + in(i + 1, j, k)) + (in(i, j + 1, k) + in(i, j - 1, k))); } } } } void laplace_partialfusion(const Storage3D& in, Storage3D& out) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { for (int64_t k = 0; k < domain_height; ++k) { out(i, j, k) = -4.0 * in(i, j, k) + ((in(i - 1, j, k) + in(i + 1, j, k)) + (in(i, j + 1, k) + in(i, j - 1, k))); } } } } void laplace_openmp(const Storage3D& in, Storage3D& out) { #pragma omp parallel for for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { for (int64_t k = 0; k < domain_height; ++k) { out(i, j, k) = -4.0 * in(i, j, k) + ((in(i - 1, j, k) + in(i + 1, j, k)) + (in(i, j + 1, k) + in(i, j - 1, k))); } } } } #endif // LAPLACE_H
3d7pt_var.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 with variable coefficients * 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, m, 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]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][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] = 32; tile_size[1] = 32; tile_size[2] = 32; tile_size[3] = 2048; 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); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][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,16);t1++) { lbp=max(ceild(t1,2),ceild(32*t1-Nt+3,32)); ubp=min(floord(Nt+Nz-4,32),floord(16*t1+Nz+13,32)); #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(32*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(16*t1+Ny+29,32)),floord(32*t2+Ny+28,32)),floord(32*t1-32*t2+Nz+Ny+27,32));t3++) { for (t4=max(max(max(0,ceild(t1-127,128)),ceild(32*t2-Nz-2044,2048)),ceild(32*t3-Ny-2044,2048));t4<=min(min(min(min(floord(Nt+Nx-4,2048),floord(16*t1+Nx+29,2048)),floord(32*t2+Nx+28,2048)),floord(32*t3+Nx+28,2048)),floord(32*t1-32*t2+Nz+Nx+27,2048));t4++) { for (t5=max(max(max(max(max(0,16*t1),32*t1-32*t2+1),32*t2-Nz+2),32*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,16*t1+31),32*t2+30),32*t3+30),2048*t4+2046),32*t1-32*t2+Nz+29);t5++) { for (t6=max(max(32*t2,t5+1),-32*t1+32*t2+2*t5-31);t6<=min(min(32*t2+31,-32*t1+32*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(2048*t4,t5+1); ubv=min(2048*t4+2047,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-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, "variable no-symmetry") #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(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
LAGraph_BF_full.c
//------------------------------------------------------------------------------ // LAGraph_BF_full.c: Bellman-Ford single-source shortest paths, returns tree //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // See additional acknowledgments in the LICENSE file, // or contact permission@sei.cmu.edu for the full terms. // Contributed by Jinhao Chen and Timothy A. Davis, Texas A&M University //------------------------------------------------------------------------------ // LAGraph_BF_full: Bellman-Ford single source shortest paths, returning both // the path lengths and the shortest-path tree. // LAGraph_BF_full performs a Bellman-Ford to find out shortest path, parent // nodes along the path and the hops (number of edges) in the path from given // source vertex s in the range of [0, n) on graph given as matrix A with size // n*n. The sparse matrix A has entry A(i, j) if there is an edge from vertex i // to vertex j with weight w, then A(i, j) = w. Furthermore, LAGraph_BF_full // requires A(i, i) = 0 for all 0 <= i < n. // LAGraph_BF_full returns GrB_SUCCESS if successful, and GrB_NO_VALUE if it // detects the existence of negative- weight cycle. The GrB_Vector d(k), pi(k) // and h(k) (i.e., *pd_output, *ppi_output and *ph_output respectively) will // be NULL when negative-weight cycle detected. Otherwise, the vector d has // d(k) as the shortest distance from s to k. pi(k) = p+1, where p is the // parent node of k-th node in the shortest path. In particular, pi(s) = 0. // h(k) = hop(s, k), the number of edges from s to k in the shortest path. //------------------------------------------------------------------------------ #define LG_FREE_ALL \ { \ GrB_free(&d); \ GrB_free(&dtmp); \ GrB_free(&Atmp); \ GrB_free(&BF_Tuple3); \ GrB_free(&BF_lMIN_Tuple3); \ GrB_free(&BF_PLUSrhs_Tuple3); \ GrB_free(&BF_EQ_Tuple3); \ GrB_free(&BF_lMIN_Tuple3_Monoid); \ GrB_free(&BF_lMIN_PLUSrhs_Tuple3); \ LAGraph_Free ((void**)&I, NULL); \ LAGraph_Free ((void**)&J, NULL); \ LAGraph_Free ((void**)&w, NULL); \ LAGraph_Free ((void**)&W, NULL); \ LAGraph_Free ((void**)&h, NULL); \ LAGraph_Free ((void**)&pi, NULL); \ } #include <LAGraph.h> #include <LAGraphX.h> #include <LG_internal.h> // from src/utility typedef void (*LAGraph_binary_function) (void *, const void *, const void *) ; //------------------------------------------------------------------------------ // data type for each entry of the adjacent matrix A and "distance" vector d; // <INFINITY,INFINITY,INFINITY> corresponds to nonexistence of a path, and // the value <0, 0, NULL> corresponds to a path from a vertex to itself //------------------------------------------------------------------------------ typedef struct { double w; // w corresponds to a path weight. GrB_Index h; // h corresponds to a path size or number of hops. GrB_Index pi;// pi corresponds to the penultimate vertex along a path. // vertex indexed as 1, 2, 3, ... , V, and pi = 0 (as nil) // for u=v, and pi = UINT64_MAX (as inf) for (u,v) not in E } BF_Tuple3_struct; //------------------------------------------------------------------------------ // 2 binary functions, z=f(x,y), where Tuple3xTuple3 -> Tuple3 //------------------------------------------------------------------------------ void BF_lMIN ( BF_Tuple3_struct *z, const BF_Tuple3_struct *x, const BF_Tuple3_struct *y ) { if (x->w < y->w || (x->w == y->w && x->h < y->h) || (x->w == y->w && x->h == y->h && x->pi < y->pi)) { if (z != x) { *z = *x; } } else { *z = *y; } } void BF_PLUSrhs ( BF_Tuple3_struct *z, const BF_Tuple3_struct *x, const BF_Tuple3_struct *y ) { z->w = x->w + y->w ; z->h = x->h + y->h ; z->pi = (x->pi != UINT64_MAX && y->pi != 0) ? y->pi : x->pi ; } void BF_EQ ( bool *z, const BF_Tuple3_struct *x, const BF_Tuple3_struct *y ) { (*z) = (x->w == y->w && x->h == y->h && x->pi == y->pi) ; } // Given a n-by-n adjacency matrix A and a source vertex s. // If there is no negative-weight cycle reachable from s, return the distances // of shortest paths from s and parents along the paths as vector d. Otherwise, // returns d=NULL if there is a negtive-weight cycle. // pd_output is pointer to a GrB_Vector, where the i-th entry is d(s,i), the // sum of edges length in the shortest path // ppi_output is pointer to a GrB_Vector, where the i-th entry is pi(i), the // parent of i-th vertex in the shortest path // ph_output is pointer to a GrB_Vector, where the i-th entry is h(s,i), the // number of edges from s to i in the shortest path // A has zeros on diagonal and weights on corresponding entries of edges // s is given index for source vertex GrB_Info LAGraph_BF_full ( GrB_Vector *pd_output, //the pointer to the vector of distance GrB_Vector *ppi_output, //the pointer to the vector of parent GrB_Vector *ph_output, //the pointer to the vector of hops const GrB_Matrix A, //matrix for the graph const GrB_Index s //given index of the source ) { GrB_Info info; char *msg = NULL ; // tmp vector to store distance vector after n (i.e., V) loops GrB_Vector d = NULL, dtmp = NULL; GrB_Matrix Atmp = NULL; GrB_Type BF_Tuple3; GrB_BinaryOp BF_lMIN_Tuple3; GrB_BinaryOp BF_PLUSrhs_Tuple3; GrB_BinaryOp BF_EQ_Tuple3; GrB_Monoid BF_lMIN_Tuple3_Monoid; GrB_Semiring BF_lMIN_PLUSrhs_Tuple3; GrB_Index nrows, ncols, n, nz; // n = # of row/col, nz = # of nnz in graph GrB_Index *I = NULL, *J = NULL; // for col/row indices of entries from A GrB_Index *h = NULL, *pi = NULL; double *w = NULL; BF_Tuple3_struct *W = NULL; LG_ASSERT (A != NULL && pd_output != NULL && ppi_output != NULL && ph_output != NULL, GrB_NULL_POINTER) ; *pd_output = NULL; *ppi_output = NULL; *ph_output = NULL; GRB_TRY (GrB_Matrix_nrows (&nrows, A)) ; GRB_TRY (GrB_Matrix_ncols (&ncols, A)) ; GRB_TRY (GrB_Matrix_nvals (&nz, A)); LG_ASSERT_MSG (nrows == ncols, -1002, "A must be square") ; n = nrows; LG_ASSERT_MSG (s < n, GrB_INVALID_INDEX, "invalid source node") ; //-------------------------------------------------------------------------- // create all GrB_Type GrB_BinaryOp GrB_Monoid and GrB_Semiring //-------------------------------------------------------------------------- // GrB_Type GRB_TRY (GrB_Type_new(&BF_Tuple3, sizeof(BF_Tuple3_struct))); // GrB_BinaryOp GRB_TRY (GrB_BinaryOp_new(&BF_EQ_Tuple3, (LAGraph_binary_function) (&BF_EQ), GrB_BOOL, BF_Tuple3, BF_Tuple3)); GRB_TRY (GrB_BinaryOp_new(&BF_lMIN_Tuple3, (LAGraph_binary_function) (&BF_lMIN), BF_Tuple3, BF_Tuple3, BF_Tuple3)); GRB_TRY (GrB_BinaryOp_new(&BF_PLUSrhs_Tuple3, (LAGraph_binary_function)(&BF_PLUSrhs), BF_Tuple3, BF_Tuple3, BF_Tuple3)); // GrB_Monoid BF_Tuple3_struct BF_identity = (BF_Tuple3_struct) { .w = INFINITY, .h = UINT64_MAX, .pi = UINT64_MAX }; GRB_TRY (GrB_Monoid_new_UDT(&BF_lMIN_Tuple3_Monoid, BF_lMIN_Tuple3, &BF_identity)); //GrB_Semiring GRB_TRY (GrB_Semiring_new(&BF_lMIN_PLUSrhs_Tuple3, BF_lMIN_Tuple3_Monoid, BF_PLUSrhs_Tuple3)); //-------------------------------------------------------------------------- // allocate arrays used for tuplets //-------------------------------------------------------------------------- LAGRAPH_TRY (LAGraph_Malloc ((void **) &I, nz, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &J, nz, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &w, nz, sizeof(double), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &W, nz, sizeof(BF_Tuple3_struct), msg)) ; //-------------------------------------------------------------------------- // create matrix Atmp based on A, while its entries become BF_Tuple3 type //-------------------------------------------------------------------------- GRB_TRY (GrB_Matrix_extractTuples_FP64(I, J, w, &nz, A)); int nthreads, nthreads_outer, nthreads_inner ; LG_TRY (LAGraph_GetNumThreads (&nthreads_outer, &nthreads_inner, msg)) ; nthreads = nthreads_outer * nthreads_inner ; printf ("nthreads %d\n", nthreads) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (GrB_Index k = 0; k < nz; k++) { if (w[k] == 0) //diagonal entries { W[k] = (BF_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; } else { W[k] = (BF_Tuple3_struct) { .w = w[k], .h = 1, .pi = I[k] + 1 }; } } GRB_TRY (GrB_Matrix_new(&Atmp, BF_Tuple3, n, n)); GRB_TRY (GrB_Matrix_build_UDT(Atmp, I, J, W, nz, BF_lMIN_Tuple3)); //-------------------------------------------------------------------------- // create and initialize "distance" vector d //-------------------------------------------------------------------------- GRB_TRY (GrB_Vector_new(&d, BF_Tuple3, n)); // initial distance from s to itself BF_Tuple3_struct d0 = (BF_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; GRB_TRY (GrB_Vector_setElement_UDT(d, &d0, s)); //-------------------------------------------------------------------------- // start the Bellman Ford process //-------------------------------------------------------------------------- // copy d to dtmp in order to create a same size of vector GRB_TRY (GrB_Vector_dup(&dtmp, d)); bool same= false; // variable indicating if d == dtmp int64_t iter = 0; // number of iterations // terminate when no new path is found or more than V-1 loops while (!same && iter < n - 1) { // execute semiring on d and A, and save the result to dtmp GRB_TRY (GrB_vxm(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, d, Atmp, GrB_NULL)); LG_TRY (LAGraph_Vector_IsEqual_op(&same, dtmp, d, BF_EQ_Tuple3, NULL)); if (!same) { GrB_Vector ttmp = dtmp; dtmp = d; d = ttmp; } iter ++; } // check for negative-weight cycle only when there was a new path in the // last loop, otherwise, there can't be a negative-weight cycle. if (!same) { // execute semiring again to check for negative-weight cycle GRB_TRY (GrB_vxm(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, d, Atmp, GrB_NULL)); // if d != dtmp, then there is a negative-weight cycle in the graph LG_TRY (LAGraph_Vector_IsEqual_op(&same, dtmp, d, BF_EQ_Tuple3, NULL)); if (!same) { // printf("A negative-weight cycle found. \n"); LG_FREE_ALL; return (GrB_NO_VALUE) ; } } //-------------------------------------------------------------------------- // extract tuple from "distance" vector d and create GrB_Vectors for output //-------------------------------------------------------------------------- GRB_TRY (GrB_Vector_extractTuples_UDT (I, (void *) W, &nz, d)); LAGRAPH_TRY (LAGraph_Malloc ((void **) &h , nz, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &pi, nz, sizeof(GrB_Index), msg)) ; for (GrB_Index k = 0; k < nz; k++) { w [k] = W[k].w ; h [k] = W[k].h ; pi[k] = W[k].pi; } GRB_TRY (GrB_Vector_new(pd_output, GrB_FP64, n)); GRB_TRY (GrB_Vector_new(ppi_output, GrB_UINT64, n)); GRB_TRY (GrB_Vector_new(ph_output, GrB_UINT64, n)); GRB_TRY (GrB_Vector_build_FP64 (*pd_output , I, w , nz,GrB_MIN_FP64 )); GRB_TRY (GrB_Vector_build_UINT64(*ppi_output, I, pi, nz,GrB_MIN_UINT64)); GRB_TRY (GrB_Vector_build_UINT64(*ph_output , I, h , nz,GrB_MIN_UINT64)); LG_FREE_ALL; return (GrB_SUCCESS) ; }
GB_unaryop__identity_uint16_uint64.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__identity_uint16_uint64 // op(A') function: GB_tran__identity_uint16_uint64 // C type: uint16_t // A type: uint64_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_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_IDENTITY || GxB_NO_UINT16 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint16_uint64 ( uint16_t *restrict Cx, const uint64_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__identity_uint16_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *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
residual.flux.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ // This version fissions the FV stencil into the 6 fluxes associate with each direction for each cell. In order to avoid // redundant computation, each flux is calculated only once. However, in order to avoid writing all these fluxes to memory and // then rereading them to complete the laplacian, the calculation of fluxes and summation in the laplacian are performed in a // pipelined wavefront. To further enhance performance, the ij loops are fused (ghost zones are clobbered) and OpenMP simd // pragmas are utilized. Finally, compiler specific hints and directives are utilized to facilitate simdization and nontemporal // stores. //------------------------------------------------------------------------------------------------------------------------------ #if (BLOCKCOPY_TILE_I != 10000) #error operators.flux.c cannot block the unit stride dimension (BLOCKCOPY_TILE_I!=10000). #endif //------------------------------------------------------------------------------------------------------------------------------ void residual(level_type * level, int res_id, int x_id, int rhs_id, double a, double b){ // BLOCKCOPY_TILE_J+1 is required for flux_j, but BLOCKCOPY_TILE_J+2 seems to be faster (avoids prefetcher/coherency effects??) if(level->fluxes==NULL){posix_memalign( (void**)&(level->fluxes), 512, (4)*(level->num_threads)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride)*sizeof(double) );} // exchange the boundary for x in prep for Ax... exchange_boundary(level,x_id,stencil_get_shape()); apply_BCs(level,x_id,stencil_get_shape()); // now do residual/restriction proper... double _timeStart = getTime(); double h2inv = 1.0/(level->h*level->h); // loop over all block/tiles this process owns... #pragma omp parallel if(level->num_my_blocks>1) { int block; int threadID=omp_get_thread_num(); int num_threads=omp_get_num_threads(); #if 0 // [flux][thread][ij] layout double * __restrict__ flux_i = level->fluxes + (0*level->num_threads + threadID)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride); double * __restrict__ flux_j = level->fluxes + (1*level->num_threads + threadID)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride); double * __restrict__ flux_k[2] = {level->fluxes + (2*level->num_threads + threadID)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride), level->fluxes + (3*level->num_threads + threadID)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride)}; #else // [thread][flux][ij] layout double * __restrict__ flux_i = level->fluxes + (4*threadID + 0)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride); double * __restrict__ flux_j = level->fluxes + (4*threadID + 1)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride); double * __restrict__ flux_k[2] = {level->fluxes + (4*threadID + 2)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride), level->fluxes + (4*threadID + 3)*(BLOCKCOPY_TILE_J+2)*(level->box_jStride)}; #endif #if 1 // static, chunksize == 1... try to exploit constructive locality in the cache int blockStart = threadID; int blockEnd = level->num_my_blocks; int blockStride = num_threads; #else // static uniform int blockStart = level->num_my_blocks*(threadID )/num_threads; int blockEnd = level->num_my_blocks*(threadID+1)/num_threads; int blockStride = 1; #endif for(block=blockStart;block<blockEnd;block+=blockStride){ const int box = level->my_blocks[block].read.box; const int jlo = level->my_blocks[block].read.j; const int klo = level->my_blocks[block].read.k; const int jdim = level->my_blocks[block].dim.j; const int kdim = level->my_blocks[block].dim.k; const int ghosts = level->my_boxes[box].ghosts; const int jStride = level->my_boxes[box].jStride; const int kStride = level->my_boxes[box].kStride; const double * __restrict__ rhs = level->my_boxes[box].vectors[ rhs_id] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); const double * __restrict__ alpha = level->my_boxes[box].vectors[VECTOR_ALPHA ] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); const double * __restrict__ beta_i = level->my_boxes[box].vectors[VECTOR_BETA_I] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); const double * __restrict__ beta_j = level->my_boxes[box].vectors[VECTOR_BETA_J] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); const double * __restrict__ beta_k = level->my_boxes[box].vectors[VECTOR_BETA_K] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); const double * __restrict__ x = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); // i.e. [0] = first non ghost zone point double * __restrict__ res = level->my_boxes[box].vectors[ res_id] + ghosts*(1+jStride+kStride) + (jlo*jStride + klo*kStride); #ifdef __INTEL_COMPILER // superfluous with OMP4 simd (?) //__assume_aligned(x ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(rhs ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(alpha ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(beta_i ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(beta_j ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(beta_k ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(res ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(flux_i ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(flux_j ,BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(flux_k[0],BOX_ALIGN_JSTRIDE*sizeof(double)); //__assume_aligned(flux_k[1],BOX_ALIGN_JSTRIDE*sizeof(double)); __assume( (jStride) % BOX_ALIGN_JSTRIDE == 0); // e.g. jStride%4==0 or jStride%8==0, hence x+jStride is aligned __assume( (kStride) % BOX_ALIGN_JSTRIDE == 0); __assume( jStride >= BOX_ALIGN_JSTRIDE); __assume( kStride >= BOX_ALIGN_JSTRIDE); __assume( jdim > 0); __assume( kdim > 0); #elif __xlC__ __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), x ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), rhs ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), alpha ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), beta_i ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), beta_j ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), beta_k ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), res ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), flux_i ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), flux_j ); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), flux_k[0]); __alignx(BOX_ALIGN_JSTRIDE*sizeof(double), flux_k[1]); #endif int ij,k; double * __restrict__ flux_klo = flux_k[0]; // startup / prolog... calculate flux_klo (bottom of cell)... #if (_OPENMP>=201307) #pragma omp simd aligned(beta_k,x,flux_klo:BOX_ALIGN_JSTRIDE*sizeof(double)) #endif #ifdef __INTEL_COMPILER #pragma loop_count min=BOX_ALIGN_JSTRIDE, avg=512 #endif for(ij=0;ij<jdim*jStride;ij++){ flux_klo[ij] = beta_dxdk(x,ij); // k==0 } // wavefront loop... for(k=0;k<kdim;k++){ double * __restrict__ flux_klo = flux_k[(k )&0x1]; double * __restrict__ flux_khi = flux_k[(k+1)&0x1]; #if 1 // calculate flux_i and flux_j together #if (_OPENMP>=201307) #pragma omp simd aligned(beta_i,beta_j,x,flux_i,flux_j:BOX_ALIGN_JSTRIDE*sizeof(double)) #endif #ifdef __INTEL_COMPILER #pragma loop_count min=BOX_ALIGN_JSTRIDE, avg=512 #endif for(ij=0;ij<(jdim+1)*jStride;ij++){ int ijk = ij + k*kStride; flux_i[ij] = beta_dxdi(x,ijk); flux_j[ij] = beta_dxdj(x,ijk); } #else // calculate flux_i #if (_OPENMP>=201307) #pragma omp simd aligned(beta_i,x,flux_i:BOX_ALIGN_JSTRIDE*sizeof(double)) #endif #ifdef __INTEL_COMPILER #pragma loop_count min=BOX_ALIGN_JSTRIDE, avg=512 #endif for(ij=0;ij<jdim*jStride;ij++){ int ijk = ij + k*kStride; flux_i[ij] = beta_dxdi(x,ijk); } // calculate flux_j #if (_OPENMP>=201307) #pragma omp simd aligned(beta_j,x,flux_j:BOX_ALIGN_JSTRIDE*sizeof(double)) #endif #ifdef __INTEL_COMPILER #pragma loop_count min=BOX_ALIGN_JSTRIDE, avg=512 #endif for(ij=0;ij<(jdim+1)*jStride;ij++){ int ijk = ij + k*kStride; flux_j[ij] = beta_dxdj(x,ijk); } #endif // calculate flux_khi (top of cell) #if (_OPENMP>=201307) #pragma omp simd aligned(beta_k,x,flux_khi:BOX_ALIGN_JSTRIDE*sizeof(double)) #endif #ifdef __INTEL_COMPILER #pragma loop_count min=BOX_ALIGN_JSTRIDE, avg=512 #endif for(ij=0;ij<jdim*jStride;ij++){ int ijk = ij + k*kStride; flux_khi[ij] = beta_dxdk(x,ijk+kStride); } // residual... #if (_OPENMP>=201307) #pragma omp simd aligned(flux_i,flux_j,flux_klo,flux_khi,alpha,rhs,x,res:BOX_ALIGN_JSTRIDE*sizeof(double)) #endif #ifdef __INTEL_COMPILER #pragma loop_count min=BOX_ALIGN_JSTRIDE, avg=512 #pragma vector nontemporal // generally, we don't expect to reuse res #endif for(ij=0;ij<jdim*jStride;ij++){ int ijk = ij + k*kStride; double Lx = - flux_i[ ij] + flux_i[ ij+ 1] - flux_j[ ij] + flux_j[ ij+jStride] - flux_klo[ij] + flux_khi[ij ]; #ifdef USE_HELMHOLTZ double Ax = a*alpha[ijk]*x[ijk] - b*Lx; #else double Ax = -b*Lx; #endif res[ijk] = rhs[ijk]-Ax; } } // kdim } // block } // omp level->timers.residual += (double)(getTime()-_timeStart); }
blas.c
#include "blas.h" #include "utils.h" #include <math.h> #include <assert.h> #include <float.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void reorg_cpu(float *x, int out_w, int out_h, int out_c, int batch, int stride, int forward, float *out) { int b,i,j,k; int in_c = out_c/(stride*stride); //printf("\n out_c = %d, out_w = %d, out_h = %d, stride = %d, forward = %d \n", out_c, out_w, out_h, stride, forward); //printf(" in_c = %d, in_w = %d, in_h = %d \n", in_c, out_w*stride, out_h*stride); for(b = 0; b < batch; ++b){ for(k = 0; k < out_c; ++k){ for(j = 0; j < out_h; ++j){ for(i = 0; i < out_w; ++i){ int in_index = i + out_w*(j + out_h*(k + out_c*b)); int c2 = k % in_c; int offset = k / in_c; int w2 = i*stride + offset % stride; int h2 = j*stride + offset / stride; int out_index = w2 + out_w*stride*(h2 + out_h*stride*(c2 + in_c*b)); if(forward) out[out_index] = x[in_index]; // used by default for forward (i.e. forward = 0) else out[in_index] = x[out_index]; } } } } } void flatten(float *x, int size, int layers, int batch, int forward) { float* swap = (float*)xcalloc(size * layers * batch, sizeof(float)); int i,c,b; for(b = 0; b < batch; ++b){ for(c = 0; c < layers; ++c){ for(i = 0; i < size; ++i){ int i1 = b*layers*size + c*size + i; int i2 = b*layers*size + i*layers + c; if (forward) swap[i2] = x[i1]; else swap[i1] = x[i2]; } } } memcpy(x, swap, size*layers*batch*sizeof(float)); free(swap); } void weighted_sum_cpu(float *a, float *b, float *s, int n, float *c) { int i; for(i = 0; i < n; ++i){ c[i] = s[i]*a[i] + (1-s[i])*(b ? b[i] : 0); } } void weighted_delta_cpu(float *a, float *b, float *s, float *da, float *db, float *ds, int n, float *dc) { int i; for(i = 0; i < n; ++i){ if(da) da[i] += dc[i] * s[i]; if(db) db[i] += dc[i] * (1-s[i]); ds[i] += dc[i] * (a[i] - b[i]); } } static float relu(float src) { if (src > 0) return src; return 0; } void shortcut_multilayer_cpu(int size, int src_outputs, int batch, int n, int *outputs_of_layers, float **layers_output, float *out, float *in, float *weights, int nweights, WEIGHTS_NORMALIZATION_T weights_normalization) { // nweights - l.n or l.n*l.c or (l.n*l.c*l.h*l.w) const int layer_step = nweights / (n + 1); // 1 or l.c or (l.c * l.h * l.w) int step = 0; if (nweights > 0) step = src_outputs / layer_step; // (l.c * l.h * l.w) or (l.w*l.h) or 1 int id; #pragma omp parallel for for (id = 0; id < size; ++id) { int src_id = id; const int src_i = src_id % src_outputs; src_id /= src_outputs; int src_b = src_id; float sum = 1, max_val = -FLT_MAX; int i; if (weights && weights_normalization) { if (weights_normalization == SOFTMAX_NORMALIZATION) { for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (max_val < w) max_val = w; } } const float eps = 0.0001; sum = eps; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) sum += relu(w); else if (weights_normalization == SOFTMAX_NORMALIZATION) sum += expf(w - max_val); } } if (weights) { float w = weights[src_i / step]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; out[id] = in[id] * w; // [0 or c or (c, h ,w)] } else out[id] = in[id]; // layers for (i = 0; i < n; ++i) { int add_outputs = outputs_of_layers[i]; if (src_i < add_outputs) { int add_index = add_outputs*src_b + src_i; int out_index = id; float *add = layers_output[i]; if (weights) { const int weights_index = src_i / step + (i + 1)*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; out[out_index] += add[add_index] * w; // [0 or c or (c, h ,w)] } else out[out_index] += add[add_index]; } } } } void backward_shortcut_multilayer_cpu(int size, int src_outputs, int batch, int n, int *outputs_of_layers, float **layers_delta, float *delta_out, float *delta_in, float *weights, float *weight_updates, int nweights, float *in, float **layers_output, WEIGHTS_NORMALIZATION_T weights_normalization) { // nweights - l.n or l.n*l.c or (l.n*l.c*l.h*l.w) const int layer_step = nweights / (n + 1); // 1 or l.c or (l.c * l.h * l.w) int step = 0; if (nweights > 0) step = src_outputs / layer_step; // (l.c * l.h * l.w) or (l.w*l.h) or 1 int id; #pragma omp parallel for for (id = 0; id < size; ++id) { int src_id = id; int src_i = src_id % src_outputs; src_id /= src_outputs; int src_b = src_id; float grad = 1, sum = 1, max_val = -FLT_MAX;; int i; if (weights && weights_normalization) { if (weights_normalization == SOFTMAX_NORMALIZATION) { for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (max_val < w) max_val = w; } } const float eps = 0.0001; sum = eps; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) sum += relu(w); else if (weights_normalization == SOFTMAX_NORMALIZATION) sum += expf(w - max_val); } /* grad = 0; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float delta_w = delta_in[id] * in[id]; const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) grad += delta_w * relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) grad += delta_w * expf(w - max_val) / sum; } */ } if (weights) { float w = weights[src_i / step]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; delta_out[id] += delta_in[id] * w; // [0 or c or (c, h ,w)] weight_updates[src_i / step] += delta_in[id] * in[id] * grad; } else delta_out[id] += delta_in[id]; // layers for (i = 0; i < n; ++i) { int add_outputs = outputs_of_layers[i]; if (src_i < add_outputs) { int add_index = add_outputs*src_b + src_i; int out_index = id; float *layer_delta = layers_delta[i]; if (weights) { float *add = layers_output[i]; const int weights_index = src_i / step + (i + 1)*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; layer_delta[add_index] += delta_in[id] * w; // [0 or c or (c, h ,w)] weight_updates[weights_index] += delta_in[id] * add[add_index] * grad; } else layer_delta[add_index] += delta_in[id]; } } } } void shortcut_cpu(int batch, int w1, int h1, int c1, float *add, int w2, int h2, int c2, float *out) { int stride = w1/w2; int sample = w2/w1; assert(stride == h1/h2); assert(sample == h2/h1); if(stride < 1) stride = 1; if(sample < 1) sample = 1; int minw = (w1 < w2) ? w1 : w2; int minh = (h1 < h2) ? h1 : h2; int minc = (c1 < c2) ? c1 : c2; int i,j,k,b; for(b = 0; b < batch; ++b){ for(k = 0; k < minc; ++k){ for(j = 0; j < minh; ++j){ for(i = 0; i < minw; ++i){ int out_index = i*sample + w2*(j*sample + h2*(k + c2*b)); int add_index = i*stride + w1*(j*stride + h1*(k + c1*b)); out[out_index] += add[add_index]; } } } } } void mean_cpu(float *x, int batch, int filters, int spatial, float *mean) { float scale = 1./(batch * spatial); int i,j,k; for(i = 0; i < filters; ++i){ mean[i] = 0; for(j = 0; j < batch; ++j){ for(k = 0; k < spatial; ++k){ int index = j*filters*spatial + i*spatial + k; mean[i] += x[index]; } } mean[i] *= scale; } } void variance_cpu(float *x, float *mean, int batch, int filters, int spatial, float *variance) { float scale = 1./(batch * spatial - 1); int i,j,k; for(i = 0; i < filters; ++i){ variance[i] = 0; for(j = 0; j < batch; ++j){ for(k = 0; k < spatial; ++k){ int index = j*filters*spatial + i*spatial + k; variance[i] += pow((x[index] - mean[i]), 2); } } variance[i] *= scale; } } void normalize_cpu(float *x, float *mean, float *variance, int batch, int filters, int spatial) { int b, f, i; for(b = 0; b < batch; ++b){ for(f = 0; f < filters; ++f){ for(i = 0; i < spatial; ++i){ int index = b*filters*spatial + f*spatial + i; x[index] = (x[index] - mean[f])/(sqrt(variance[f] + .00001f)); } } } } void const_cpu(int N, float ALPHA, float *X, int INCX) { int i; for(i = 0; i < N; ++i) X[i*INCX] = ALPHA; } void mul_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] *= X[i*INCX]; } void pow_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] = pow(X[i*INCX], ALPHA); } void axpy_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] += ALPHA*X[i*INCX]; } void scal_cpu(int N, float ALPHA, float *X, int INCX) { int i; for(i = 0; i < N; ++i) X[i*INCX] *= ALPHA; } void scal_add_cpu(int N, float ALPHA, float BETA, float *X, int INCX) { int i; for (i = 0; i < N; ++i) X[i*INCX] = X[i*INCX] * ALPHA + BETA; } void fill_cpu(int N, float ALPHA, float *X, int INCX) { int i; if (INCX == 1 && ALPHA == 0) { memset(X, 0, N * sizeof(float)); } else { for (i = 0; i < N; ++i) X[i*INCX] = ALPHA; } } void deinter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT) { int i, j; int index = 0; for(j = 0; j < B; ++j) { for(i = 0; i < NX; ++i){ if(X) X[j*NX + i] += OUT[index]; ++index; } for(i = 0; i < NY; ++i){ if(Y) Y[j*NY + i] += OUT[index]; ++index; } } } void inter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT) { int i, j; int index = 0; for(j = 0; j < B; ++j) { for(i = 0; i < NX; ++i){ OUT[index++] = X[j*NX + i]; } for(i = 0; i < NY; ++i){ OUT[index++] = Y[j*NY + i]; } } } void copy_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] = X[i*INCX]; } void mult_add_into_cpu(int N, float *X, float *Y, float *Z) { int i; for(i = 0; i < N; ++i) Z[i] += X[i]*Y[i]; } void smooth_l1_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; float abs_val = fabs(diff); if(abs_val < 1) { error[i] = diff * diff; delta[i] = diff; } else { error[i] = 2*abs_val - 1; delta[i] = (diff > 0) ? 1 : -1; } } } void l1_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; error[i] = fabs(diff); delta[i] = diff > 0 ? 1 : -1; } } void softmax_x_ent_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float t = truth[i]; float p = pred[i]; error[i] = (t) ? -log(p) : 0; delta[i] = t-p; } } void logistic_x_ent_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float t = truth[i]; float p = pred[i]; error[i] = -t*log(p) - (1-t)*log(1-p); delta[i] = t-p; } } void l2_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; error[i] = diff * diff; delta[i] = diff; } } float dot_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; float dot = 0; for(i = 0; i < N; ++i) dot += X[i*INCX] * Y[i*INCY]; return dot; } void softmax(float *input, int n, float temp, float *output, int stride) { int i; float sum = 0; float largest = -FLT_MAX; for(i = 0; i < n; ++i){ if(input[i*stride] > largest) largest = input[i*stride]; } for(i = 0; i < n; ++i){ float e = exp(input[i*stride]/temp - largest/temp); sum += e; output[i*stride] = e; } for(i = 0; i < n; ++i){ output[i*stride] /= sum; } } void softmax_cpu(float *input, int n, int batch, int batch_offset, int groups, int group_offset, int stride, float temp, float *output) { int g, b; for(b = 0; b < batch; ++b){ for(g = 0; g < groups; ++g){ softmax(input + b*batch_offset + g*group_offset, n, temp, output + b*batch_offset + g*group_offset, stride); } } } void upsample_cpu(float *in, int w, int h, int c, int batch, int stride, int forward, float scale, float *out) { int i, j, k, b; for (b = 0; b < batch; ++b) { for (k = 0; k < c; ++k) { for (j = 0; j < h*stride; ++j) { for (i = 0; i < w*stride; ++i) { int in_index = b*w*h*c + k*w*h + (j / stride)*w + i / stride; int out_index = b*w*h*c*stride*stride + k*w*h*stride*stride + j*w*stride + i; if (forward) out[out_index] = scale*in[in_index]; else in[in_index] += scale*out[out_index]; } } } } } void constrain_cpu(int size, float ALPHA, float *X) { int i; for (i = 0; i < size; ++i) { X[i] = fminf(ALPHA, fmaxf(-ALPHA, X[i])); } } void fix_nan_and_inf_cpu(float *input, size_t size) { int i; for (i = 0; i < size; ++i) { float val = input[i]; if (isnan(val) || isinf(val)) input[i] = 1.0f / i; // pseudo random value } } void get_embedding(float *src, int src_w, int src_h, int src_c, int embedding_size, int cur_w, int cur_h, int cur_n, int cur_b, float *dst) { int i; for (i = 0; i < embedding_size; ++i) { const int src_index = cur_b*(src_c*src_h*src_w) + cur_n*(embedding_size*src_h*src_w) + i*src_h*src_w + cur_h*(src_w) + cur_w; const float val = src[src_index]; dst[i] = val; //printf(" val = %f, ", val); } } // Euclidean_norm float math_vector_length(float *A, unsigned int feature_size) { float sum = 0; int i; for (i = 0; i < feature_size; ++i) { sum += A[i] * A[i]; } float vector_length = sqrtf(sum); return vector_length; } float cosine_similarity(float *A, float *B, unsigned int feature_size) { float mul = 0.0, d_a = 0.0, d_b = 0.0; int i; for(i = 0; i < feature_size; ++i) { mul += A[i] * B[i]; d_a += A[i] * A[i]; d_b += B[i] * B[i]; } float similarity; float divider = sqrtf(d_a) * sqrtf(d_b); if (divider > 0) similarity = mul / divider; else similarity = 0; return similarity; } int get_sim_P_index(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { return -1; // not found } return z; // found } int check_sim(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { return 0; // not found } return 1; // found } float find_sim(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { printf(" Error: find_sim(): sim isn't found: i = %d, j = %d, z = %d \n", i, j, z); getchar(); } return contrast_p[z].sim; } float find_P_constrastive(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { printf(" Error: find_P_constrastive(): P isn't found: i = %d, j = %d, z = %d \n", i, j, z); getchar(); } return contrast_p[z].P; } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive_f_det(size_t il, int *labels, float **z, unsigned int feature_size, float temperature, contrastive_params *contrast_p, int contrast_p_size) { const float sim = contrast_p[il].sim; const size_t i = contrast_p[il].i; const size_t j = contrast_p[il].j; const float numerator = expf(sim / temperature); float denominator = 0; int k; for (k = 0; k < contrast_p_size; ++k) { contrastive_params cp = contrast_p[k]; //if (k != i && labels[k] != labels[i]) { //if (k != i) { if (cp.i != i && cp.j == j) { //const float sim_den = cp.sim; ////const float sim_den = find_sim(k, l, contrast_p, contrast_p_size); // cosine_similarity(z[k], z[l], feature_size); //denominator += expf(sim_den / temperature); denominator += cp.exp_sim; } } float result = 0.9999; if (denominator != 0) result = numerator / denominator; if (result > 1) result = 0.9999; return result; } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive_f(size_t i, size_t l, int *labels, float **z, unsigned int feature_size, float temperature, contrastive_params *contrast_p, int contrast_p_size) { if (i == l) { fprintf(stderr, " Error: in P_constrastive must be i != l, while i = %d, l = %d \n", i, l); getchar(); } const float sim = find_sim(i, l, contrast_p, contrast_p_size); // cosine_similarity(z[i], z[l], feature_size); const float numerator = expf(sim / temperature); float denominator = 0; int k; for (k = 0; k < contrast_p_size; ++k) { contrastive_params cp = contrast_p[k]; //if (k != i && labels[k] != labels[i]) { //if (k != i) { if (cp.i != i && cp.j == l) { //const float sim_den = cp.sim; ////const float sim_den = find_sim(k, l, contrast_p, contrast_p_size); // cosine_similarity(z[k], z[l], feature_size); //denominator += expf(sim_den / temperature); denominator += cp.exp_sim; } } float result = 0.9999; if (denominator != 0) result = numerator / denominator; if (result > 1) result = 0.9999; return result; } void grad_contrastive_loss_positive_f(size_t i, int *class_ids, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *delta, int wh, contrastive_params *contrast_p, int contrast_p_size) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j] && labels[i] >= 0) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f, labels[i] = %d \n", N, temperature, vec_len, labels[i]); getchar(); return; } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j] && labels[i] >= 0) { //printf(" i = %d, j = %d, num_of_samples = %d, labels[i] = %d, labels[j] = %d \n", // i, j, num_of_samples, labels[i], labels[j]); const int sim_P_i = get_sim_P_index(i, j, contrast_p, contrast_p_size); if (sim_P_i < 0) continue; const float sim = contrast_p[sim_P_i].sim; const float P = contrast_p[sim_P_i].P; //if (!check_sim(i, j, contrast_p, contrast_p_size)) continue; //const float sim = find_sim(i, j, contrast_p, contrast_p_size); //cos_sim[i*num_of_samples + j]; // cosine_similarity(z[i], z[j], feature_size); //const float P = find_P_constrastive(i, j, contrast_p, contrast_p_size); //p_constrastive[i*num_of_samples + j]; // P_constrastive(i, j, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 - sim; int m; //const float d = mult*(sim * z[i][m] - z[j][m]) * (1 - P); // 1 for (m = 0; m < feature_size; ++m) { //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // my //const float d = mult*(sim * z[i][m] + sim * z[j][m] - z[j][m]) *(1 - P); // 1+2 const float d = mult*(sim * z[i][m] - z[j][m]) *(1 - P); // 1 (70%) //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // 2 // printf(" pos: z[j][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[j][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } } } } void grad_contrastive_loss_negative_f(size_t i, int *class_ids, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *delta, int wh, contrastive_params *contrast_p, int contrast_p_size, int neg_max) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j] && labels[i] >= 0) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f, labels[i] = %d \n", N, temperature, vec_len, labels[i]); getchar(); return; } const float mult = 1 / ((N - 1) * temperature * vec_len); int neg_counter = 0; for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (labels[i] >= 0 && labels[i] == labels[j] && i != j) { size_t k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && k != j && labels[k] != labels[i]) { if (k != i && k != j && labels[k] != labels[i] && class_ids[j] == class_ids[k]) { neg_counter++; const int sim_P_i = get_sim_P_index(i, k, contrast_p, contrast_p_size); if (sim_P_i < 0) continue; const float sim = contrast_p[sim_P_i].sim; const float P = contrast_p[sim_P_i].P; //if (!check_sim(i, k, contrast_p, contrast_p_size)) continue; //const float sim = find_sim(i, k, contrast_p, contrast_p_size); //cos_sim[i*num_of_samples + k]; // cosine_similarity(z[i], z[k], feature_size); //const float P = find_P_constrastive(i, k, contrast_p, contrast_p_size); //p_constrastive[i*num_of_samples + k]; // P_constrastive(i, k, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 + sim; int m; //const float d = mult*(z[k][m] + sim * z[i][m]) * P; // my1 for (m = 0; m < feature_size; ++m) { //const float d = mult*(z[k][m] + sim * z[i][m]) * P; // 1 (70%) //const float d = mult*(z[k][m] - sim * z[k][m] - sim * z[i][m]) * P; // 1+2 const float d = mult*(z[k][m] - sim * z[i][m]) * P; // 1 (70%) //const float d = mult*(z[k][m] - sim * z[k][m]) * P; // 2 //printf(" neg: z[k][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[k][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } if (neg_counter >= neg_max) return; } } } } } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive(size_t i, size_t l, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *exp_cos_sim) { if (i == l) { fprintf(stderr, " Error: in P_constrastive must be i != l, while i = %d, l = %d \n", i, l); getchar(); } //const float sim = cos_sim[i*num_of_samples + l]; // cosine_similarity(z[i], z[l], feature_size); //const float numerator = expf(sim / temperature); const float numerator = exp_cos_sim[i*num_of_samples + l]; float denominator = 0; int k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && labels[k] != labels[i]) { if (k != i) { //const float sim_den = cos_sim[k*num_of_samples + l]; // cosine_similarity(z[k], z[l], feature_size); //denominator += expf(sim_den / temperature); denominator += exp_cos_sim[k*num_of_samples + l]; } } float result = numerator / denominator; return result; } // i - id of the current sample in mini_batch // labels[num_of_samples] - array with class_id for each sample in the current mini_batch // z[feature_size][num_of_samples] - array of arrays with contrastive features (output of conv-layer, f.e. 128 floats for each sample) // delta[feature_size] - array with deltas for backpropagation // temperature - scalar temperature param (temperature > 0), f.e. temperature = 0.07: Supervised Contrastive Learning void grad_contrastive_loss_positive(size_t i, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *p_constrastive, float *delta, int wh) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j]) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f \n", N, temperature, vec_len); getchar(); } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j]) { //printf(" i = %d, j = %d, num_of_samples = %d, labels[i] = %d, labels[j] = %d \n", // i, j, num_of_samples, labels[i], labels[j]); const float sim = cos_sim[i*num_of_samples + j]; // cosine_similarity(z[i], z[j], feature_size); const float P = p_constrastive[i*num_of_samples + j]; // P_constrastive(i, j, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 - sim; int m; for (m = 0; m < feature_size; ++m) { const float d = mult*(sim * z[i][m] - z[j][m]) * (1 - P); // good //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // bad // printf(" pos: z[j][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[j][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } } } } // i - id of the current sample in mini_batch // labels[num_of_samples] - array with class_id for each sample in the current mini_batch // z[feature_size][num_of_samples] - array of arrays with contrastive features (output of conv-layer, f.e. 128 floats for each sample) // delta[feature_size] - array with deltas for backpropagation // temperature - scalar temperature param (temperature > 0), f.e. temperature = 0.07: Supervised Contrastive Learning void grad_contrastive_loss_negative(size_t i, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *p_constrastive, float *delta, int wh) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j]) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f \n", N, temperature, vec_len); getchar(); } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j]) { size_t k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && k != j && labels[k] != labels[i]) { if (k != i && k != j && labels[k] >= 0) { const float sim = cos_sim[i*num_of_samples + k]; // cosine_similarity(z[i], z[k], feature_size); const float P = p_constrastive[i*num_of_samples + k]; // P_constrastive(i, k, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 + sim; int m; for (m = 0; m < feature_size; ++m) { const float d = mult*(z[k][m] - sim * z[i][m]) * P; // good //const float d = mult*(z[k][m] - sim * z[k][m]) * P; // bad //printf(" neg: z[k][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[k][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } } } } } }
wino_conv_kernel_x86.c
/* * 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. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: haoluo@openailab.com */ #include "wino_conv_kernel_x86.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "utility/sys_port.h" #include "utility/float.h" #include "utility/log.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #define TILE 4 #define ELEM_SIZE ((TILE + 2) * (TILE + 2)) #define WINO_MAX(a, b) ((a) > (b) ? (a) : (b)) #define WINO_MIN(a, b) ((a) < (b) ? (a) : (b)) static void relu(float* data, int size, int activation) { for (int i = 0; i < size; i++) { data[i] = WINO_MAX(data[i], ( float )0); if (activation > 0) { data[i] = WINO_MIN(data[i], ( float )activation); } } } static int get_private_mem_size(struct tensor* filter, struct conv_param* param) { int output_c = filter->dims[0]; int input_c = filter->dims[1]; int trans_ker_size = (unsigned long)output_c * input_c * ELEM_SIZE * sizeof(float); return trans_ker_size + 128; // caution } static void pad_0_align_2D(float* dst, float* src, int m, int n, int m_align, int n_align, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, (unsigned long)m * n * sizeof(float)); return; } for (i = 0; i < m; ++i) { memcpy(dst + (i + pad_h) * n_align + pad_w, src + i * n, n * sizeof(float)); } } // pad 0 in right and down side on 3D static void pad_0_align_3D(float* dst, float* src, int m, int n, int m_align, int n_align, int c, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, (unsigned long)c * m * n * sizeof(float)); return; } for (i = 0; i < c; ++i) { pad_0_align_2D(dst + i * m_align * n_align, src + i * m * n, m, n, m_align, n_align, pad_h, pad_w); } } static void delete_0_2D(float* dst, float* src, int m_align, int n_align, int m, int n, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, (unsigned long)m * n * sizeof(float)); return; } for (i = 0; i < m; ++i) { memcpy(dst + i * n, src + (i + pad_h) * n_align + pad_w, n * sizeof(float)); } } // pad 0 in right and down side on 3D static void delete_0_3D(float* dst, float* src, int m_align, int n_align, int m, int n, int c, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, (unsigned long)c * m * n * sizeof(float)); return; } for (i = 0; i < c; ++i) { delete_0_2D(dst + i * m * n, src + i * m_align * n_align, m_align, n_align, m, n, pad_h, pad_w); } } void conv3x3s1_winograd43_sse(float* bottom_blob, float* top_blob, float* kernel_tm_test, float* dot_block, float* transform_input, float* output_bordered, float* _bias, int w, int h, int inch, int outw, int outh, int outch, int num_thread) { size_t elemsize = sizeof(float); const float* bias = _bias; // pad to 4n+2, winograd F(4,3) float* bottom_blob_bordered = bottom_blob; int outw_align = (outw + 3) / 4 * 4; int outh_align = (outh + 3) / 4 * 4; w = outw_align + 2; h = outh_align + 2; // BEGIN transform input float* bottom_blob_tm = NULL; { int w_tm = outw_align / 4 * 6; int h_tm = outh_align / 4 * 6; int nColBlocks = h_tm / 6; // may be the block num in Feathercnn int nRowBlocks = w_tm / 6; const int tiles = nColBlocks * nRowBlocks; const int tiles_n = 4 * inch * tiles; bottom_blob_tm = transform_input; // 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 // 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 #if __AVX__ __m256 _1_n = _mm256_set1_ps(-1); __m256 _2_p = _mm256_set1_ps(2); __m256 _2_n = _mm256_set1_ps(-2); __m256 _4_p = _mm256_set1_ps(4); __m256 _4_n = _mm256_set1_ps(-4); __m256 _5_n = _mm256_set1_ps(-5); #endif #pragma omp parallel for num_threads(num_thread) for (int q = 0; q < inch; q++) { const float* img = bottom_blob_bordered + q * w * h; 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* out_tm0 = bottom_blob_tm + 4 * inch * (j * nRowBlocks + i) + 4 * q; float* out_tm1 = out_tm0 + tiles_n; float* out_tm2 = out_tm0 + 2 * tiles_n; float* out_tm3 = out_tm0 + 3 * tiles_n; float* out_tm4 = out_tm0 + 4 * tiles_n; float* out_tm5 = out_tm0 + 5 * tiles_n; float* out_tm6 = out_tm0 + 6 * tiles_n; float* out_tm7 = out_tm0 + 7 * tiles_n; float* out_tm8 = out_tm0 + 8 * tiles_n; #if __AVX__ __m256 _d0, _d1, _d2, _d3, _d4, _d5; __m256 _w0, _w1, _w2, _w3, _w4, _w5; __m256 _t0, _t1, _t2, _t3, _t4, _t5; __m256 _n0, _n1, _n2, _n3, _n4, _n5; // load _d0 = _mm256_loadu_ps(r0); _d1 = _mm256_loadu_ps(r1); _d2 = _mm256_loadu_ps(r2); _d3 = _mm256_loadu_ps(r3); _d4 = _mm256_loadu_ps(r4); _d5 = _mm256_loadu_ps(r5); // w = B_t * d _w0 = _mm256_mul_ps(_d0, _4_p); _w0 = _mm256_fmadd_ps(_d2, _5_n, _w0); _w0 = _mm256_add_ps(_w0, _d4); _w1 = _mm256_mul_ps(_d1, _4_n); _w1 = _mm256_fmadd_ps(_d2, _4_n, _w1); _w1 = _mm256_add_ps(_w1, _d3); _w1 = _mm256_add_ps(_w1, _d4); _w2 = _mm256_mul_ps(_d1, _4_p); _w2 = _mm256_fmadd_ps(_d2, _4_n, _w2); _w2 = _mm256_fmadd_ps(_d3, _1_n, _w2); _w2 = _mm256_add_ps(_w2, _d4); _w3 = _mm256_mul_ps(_d1, _2_n); _w3 = _mm256_fmadd_ps(_d2, _1_n, _w3); _w3 = _mm256_fmadd_ps(_d3, _2_p, _w3); _w3 = _mm256_add_ps(_w3, _d4); _w4 = _mm256_mul_ps(_d1, _2_p); _w4 = _mm256_fmadd_ps(_d2, _1_n, _w4); _w4 = _mm256_fmadd_ps(_d3, _2_n, _w4); _w4 = _mm256_add_ps(_w4, _d4); _w5 = _mm256_mul_ps(_d1, _4_p); _w5 = _mm256_fmadd_ps(_d3, _5_n, _w5); _w5 = _mm256_add_ps(_w5, _d5); // transpose d to d_t #ifdef _WIN32 { _t0.m256_f32[0] = _w0.m256_f32[0]; _t1.m256_f32[0] = _w0.m256_f32[1]; _t2.m256_f32[0] = _w0.m256_f32[2]; _t3.m256_f32[0] = _w0.m256_f32[3]; _t4.m256_f32[0] = _w0.m256_f32[4]; _t5.m256_f32[0] = _w0.m256_f32[5]; _t0.m256_f32[1] = _w1.m256_f32[0]; _t1.m256_f32[1] = _w1.m256_f32[1]; _t2.m256_f32[1] = _w1.m256_f32[2]; _t3.m256_f32[1] = _w1.m256_f32[3]; _t4.m256_f32[1] = _w1.m256_f32[4]; _t5.m256_f32[1] = _w1.m256_f32[5]; _t0.m256_f32[2] = _w2.m256_f32[0]; _t1.m256_f32[2] = _w2.m256_f32[1]; _t2.m256_f32[2] = _w2.m256_f32[2]; _t3.m256_f32[2] = _w2.m256_f32[3]; _t4.m256_f32[2] = _w2.m256_f32[4]; _t5.m256_f32[2] = _w2.m256_f32[5]; _t0.m256_f32[3] = _w3.m256_f32[0]; _t1.m256_f32[3] = _w3.m256_f32[1]; _t2.m256_f32[3] = _w3.m256_f32[2]; _t3.m256_f32[3] = _w3.m256_f32[3]; _t4.m256_f32[3] = _w3.m256_f32[4]; _t5.m256_f32[3] = _w3.m256_f32[5]; _t0.m256_f32[4] = _w4.m256_f32[0]; _t1.m256_f32[4] = _w4.m256_f32[1]; _t2.m256_f32[4] = _w4.m256_f32[2]; _t3.m256_f32[4] = _w4.m256_f32[3]; _t4.m256_f32[4] = _w4.m256_f32[4]; _t5.m256_f32[4] = _w4.m256_f32[5]; _t0.m256_f32[5] = _w5.m256_f32[0]; _t1.m256_f32[5] = _w5.m256_f32[1]; _t2.m256_f32[5] = _w5.m256_f32[2]; _t3.m256_f32[5] = _w5.m256_f32[3]; _t4.m256_f32[5] = _w5.m256_f32[4]; _t5.m256_f32[5] = _w5.m256_f32[5]; } #else { _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]; } #endif // d = B_t * d_t _n0 = _mm256_mul_ps(_t0, _4_p); _n0 = _mm256_fmadd_ps(_t2, _5_n, _n0); _n0 = _mm256_add_ps(_n0, _t4); _n1 = _mm256_mul_ps(_t1, _4_n); _n1 = _mm256_fmadd_ps(_t2, _4_n, _n1); _n1 = _mm256_add_ps(_n1, _t3); _n1 = _mm256_add_ps(_n1, _t4); _n2 = _mm256_mul_ps(_t1, _4_p); _n2 = _mm256_fmadd_ps(_t2, _4_n, _n2); _n2 = _mm256_fmadd_ps(_t3, _1_n, _n2); _n2 = _mm256_add_ps(_n2, _t4); _n3 = _mm256_mul_ps(_t1, _2_n); _n3 = _mm256_fmadd_ps(_t2, _1_n, _n3); _n3 = _mm256_fmadd_ps(_t3, _2_p, _n3); _n3 = _mm256_add_ps(_n3, _t4); _n4 = _mm256_mul_ps(_t1, _2_p); _n4 = _mm256_fmadd_ps(_t2, _1_n, _n4); _n4 = _mm256_fmadd_ps(_t3, _2_n, _n4); _n4 = _mm256_add_ps(_n4, _t4); _n5 = _mm256_mul_ps(_t1, _4_p); _n5 = _mm256_fmadd_ps(_t3, _5_n, _n5); _n5 = _mm256_add_ps(_n5, _t5); // save to out_tm float output_n0[8] = {0.f}; _mm256_storeu_ps(output_n0, _n0); float output_n1[8] = {0.f}; _mm256_storeu_ps(output_n1, _n1); float output_n2[8] = {0.f}; _mm256_storeu_ps(output_n2, _n2); float output_n3[8] = {0.f}; _mm256_storeu_ps(output_n3, _n3); float output_n4[8] = {0.f}; _mm256_storeu_ps(output_n4, _n4); float output_n5[8] = {0.f}; _mm256_storeu_ps(output_n5, _n5); out_tm0[0] = output_n0[0]; out_tm0[1] = output_n0[1]; out_tm0[2] = output_n0[2]; out_tm0[3] = output_n0[3]; out_tm1[0] = output_n0[4]; out_tm1[1] = output_n0[5]; out_tm1[2] = output_n1[0]; out_tm1[3] = output_n1[1]; out_tm2[0] = output_n1[2]; out_tm2[1] = output_n1[3]; out_tm2[2] = output_n1[4]; out_tm2[3] = output_n1[5]; out_tm3[0] = output_n2[0]; out_tm3[1] = output_n2[1]; out_tm3[2] = output_n2[2]; out_tm3[3] = output_n2[3]; out_tm4[0] = output_n2[4]; out_tm4[1] = output_n2[5]; out_tm4[2] = output_n3[0]; out_tm4[3] = output_n3[1]; out_tm5[0] = output_n3[2]; out_tm5[1] = output_n3[3]; out_tm5[2] = output_n3[4]; out_tm5[3] = output_n3[5]; out_tm6[0] = output_n4[0]; out_tm6[1] = output_n4[1]; out_tm6[2] = output_n4[2]; out_tm6[3] = output_n4[3]; out_tm7[0] = output_n4[4]; out_tm7[1] = output_n4[5]; out_tm7[2] = output_n5[0]; out_tm7[3] = output_n5[1]; out_tm8[0] = output_n5[2]; out_tm8[1] = output_n5[3]; out_tm8[2] = output_n5[4]; out_tm8[3] = output_n5[5]; #else 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 { out_tm0[0] = d0[0]; out_tm0[1] = d0[1]; out_tm0[2] = d0[2]; out_tm0[3] = d0[3]; out_tm1[0] = d0[4]; out_tm1[1] = d0[5]; out_tm1[2] = d1[0]; out_tm1[3] = d1[1]; out_tm2[0] = d1[2]; out_tm2[1] = d1[3]; out_tm2[2] = d1[4]; out_tm2[3] = d1[5]; out_tm3[0] = d2[0]; out_tm3[1] = d2[1]; out_tm3[2] = d2[2]; out_tm3[3] = d2[3]; out_tm4[0] = d2[4]; out_tm4[1] = d2[5]; out_tm4[2] = d3[0]; out_tm4[3] = d3[1]; out_tm5[0] = d3[2]; out_tm5[1] = d3[3]; out_tm5[2] = d3[4]; out_tm5[3] = d3[5]; out_tm6[0] = d4[0]; out_tm6[1] = d4[1]; out_tm6[2] = d4[2]; out_tm6[3] = d4[3]; out_tm7[0] = d4[4]; out_tm7[1] = d4[5]; out_tm7[2] = d5[0]; out_tm7[3] = d5[1]; out_tm8[0] = d5[2]; out_tm8[1] = d5[3]; out_tm8[2] = d5[4]; out_tm8[3] = d5[5]; } #endif // __AVX__ r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; } } } } // BEGIN dot float* top_blob_tm = NULL; { int w_tm = outw_align / 4 * 6; int h_tm = outh_align / 4 * 6; int nColBlocks = h_tm / 6; // may be the block num in Feathercnn int nRowBlocks = w_tm / 6; const int tiles = nColBlocks * nRowBlocks; const int tiles_n = 36 * tiles; top_blob_tm = dot_block; #pragma omp parallel for num_threads(num_thread) for (int r = 0; r < 9; r++) { int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; for (int pp = 0; pp < nn_outch; pp++) { int p = pp << 3; float* output0_tm = top_blob_tm + tiles_n * p; float* output1_tm = top_blob_tm + tiles_n * (p + 1); float* output2_tm = top_blob_tm + tiles_n * (p + 2); float* output3_tm = top_blob_tm + tiles_n * (p + 3); float* output4_tm = top_blob_tm + tiles_n * (p + 4); float* output5_tm = top_blob_tm + tiles_n * (p + 5); float* output6_tm = top_blob_tm + tiles_n * (p + 6); float* output7_tm = top_blob_tm + tiles_n * (p + 7); output0_tm = output0_tm + r * 4; output1_tm = output1_tm + r * 4; output2_tm = output2_tm + r * 4; output3_tm = output3_tm + r * 4; output4_tm = output4_tm + r * 4; output5_tm = output5_tm + r * 4; output6_tm = output6_tm + r * 4; output7_tm = output7_tm + r * 4; for (int i = 0; i < tiles; i++) { const float* kptr = kernel_tm_test + 4 * r * inch * outch + p / 8 * inch * 32; const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i); #if __AVX__ || __SSE__ #if __AVX__ float zero_val = 0.f; __m128 _sum0 = _mm_broadcast_ss(&zero_val); __m128 _sum1 = _mm_broadcast_ss(&zero_val); __m128 _sum2 = _mm_broadcast_ss(&zero_val); __m128 _sum3 = _mm_broadcast_ss(&zero_val); __m128 _sum4 = _mm_broadcast_ss(&zero_val); __m128 _sum5 = _mm_broadcast_ss(&zero_val); __m128 _sum6 = _mm_broadcast_ss(&zero_val); __m128 _sum7 = _mm_broadcast_ss(&zero_val); #else __m128 _sum0 = _mm_set1_ps(0.f); __m128 _sum1 = _mm_set1_ps(0.f); __m128 _sum2 = _mm_set1_ps(0.f); __m128 _sum3 = _mm_set1_ps(0.f); __m128 _sum4 = _mm_set1_ps(0.f); __m128 _sum5 = _mm_set1_ps(0.f); __m128 _sum6 = _mm_set1_ps(0.f); __m128 _sum7 = _mm_set1_ps(0.f); #endif int q = 0; for (; q + 3 < inch; q = q + 4) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _r1 = _mm_loadu_ps(r0 + 4); __m128 _r2 = _mm_loadu_ps(r0 + 8); __m128 _r3 = _mm_loadu_ps(r0 + 12); __m128 _k0 = _mm_loadu_ps(kptr); __m128 _k1 = _mm_loadu_ps(kptr + 4); __m128 _k2 = _mm_loadu_ps(kptr + 8); __m128 _k3 = _mm_loadu_ps(kptr + 12); __m128 _k4 = _mm_loadu_ps(kptr + 16); __m128 _k5 = _mm_loadu_ps(kptr + 20); __m128 _k6 = _mm_loadu_ps(kptr + 24); __m128 _k7 = _mm_loadu_ps(kptr + 28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r0, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r0, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r0, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r0, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r0, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r0, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r0, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7)); #endif kptr += 32; _k0 = _mm_loadu_ps(kptr); _k1 = _mm_loadu_ps(kptr + 4); _k2 = _mm_loadu_ps(kptr + 8); _k3 = _mm_loadu_ps(kptr + 12); _k4 = _mm_loadu_ps(kptr + 16); _k5 = _mm_loadu_ps(kptr + 20); _k6 = _mm_loadu_ps(kptr + 24); _k7 = _mm_loadu_ps(kptr + 28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r1, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r1, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r1, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r1, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r1, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r1, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r1, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r1, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r1, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r1, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r1, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r1, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r1, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r1, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r1, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r1, _k7)); #endif kptr += 32; _k0 = _mm_loadu_ps(kptr); _k1 = _mm_loadu_ps(kptr + 4); _k2 = _mm_loadu_ps(kptr + 8); _k3 = _mm_loadu_ps(kptr + 12); _k4 = _mm_loadu_ps(kptr + 16); _k5 = _mm_loadu_ps(kptr + 20); _k6 = _mm_loadu_ps(kptr + 24); _k7 = _mm_loadu_ps(kptr + 28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r2, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r2, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r2, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r2, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r2, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r2, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r2, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r2, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r2, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r2, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r2, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r2, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r2, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r2, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r2, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r2, _k7)); #endif kptr += 32; _k0 = _mm_loadu_ps(kptr); _k1 = _mm_loadu_ps(kptr + 4); _k2 = _mm_loadu_ps(kptr + 8); _k3 = _mm_loadu_ps(kptr + 12); _k4 = _mm_loadu_ps(kptr + 16); _k5 = _mm_loadu_ps(kptr + 20); _k6 = _mm_loadu_ps(kptr + 24); _k7 = _mm_loadu_ps(kptr + 28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r3, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r3, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r3, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r3, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r3, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r3, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r3, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r3, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r3, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r3, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r3, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r3, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r3, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r3, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r3, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r3, _k7)); #endif kptr += 32; r0 += 16; } for (; q < inch; q++) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _k0 = _mm_loadu_ps(kptr); __m128 _k1 = _mm_loadu_ps(kptr + 4); __m128 _k2 = _mm_loadu_ps(kptr + 8); __m128 _k3 = _mm_loadu_ps(kptr + 12); __m128 _k4 = _mm_loadu_ps(kptr + 16); __m128 _k5 = _mm_loadu_ps(kptr + 20); __m128 _k6 = _mm_loadu_ps(kptr + 24); __m128 _k7 = _mm_loadu_ps(kptr + 28); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r0, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r0, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r0, _k3, _sum3); _sum4 = _mm_fmadd_ps(_r0, _k4, _sum4); _sum5 = _mm_fmadd_ps(_r0, _k5, _sum5); _sum6 = _mm_fmadd_ps(_r0, _k6, _sum6); _sum7 = _mm_fmadd_ps(_r0, _k7, _sum7); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3)); _sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4)); _sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5)); _sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6)); _sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7)); #endif kptr += 32; r0 += 4; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output1_tm, _sum1); _mm_storeu_ps(output2_tm, _sum2); _mm_storeu_ps(output3_tm, _sum3); _mm_storeu_ps(output4_tm, _sum4); _mm_storeu_ps(output5_tm, _sum5); _mm_storeu_ps(output6_tm, _sum6); _mm_storeu_ps(output7_tm, _sum7); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; float sum4[4] = {0}; float sum5[4] = {0}; float sum6[4] = {0}; float sum7[4] = {0}; for (int q = 0; q < inch; q++) { for (int n = 0; n < 4; n++) { sum0[n] += r0[n] * kptr[n]; sum1[n] += r0[n] * kptr[n + 4]; sum2[n] += r0[n] * kptr[n + 8]; sum3[n] += r0[n] * kptr[n + 12]; sum4[n] += r0[n] * kptr[n + 16]; sum5[n] += r0[n] * kptr[n + 20]; sum6[n] += r0[n] * kptr[n + 24]; sum7[n] += r0[n] * kptr[n + 28]; } kptr += 32; r0 += 4; } for (int n = 0; n < 4; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; output4_tm[n] = sum4[n]; output5_tm[n] = sum5[n]; output6_tm[n] = sum6[n]; output7_tm[n] = sum7[n]; } #endif // __AVX__ output0_tm += 36; output1_tm += 36; output2_tm += 36; output3_tm += 36; output4_tm += 36; output5_tm += 36; output6_tm += 36; output7_tm += 36; } } nn_outch = (outch - remain_outch_start) >> 2; for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* output0_tm = top_blob_tm + tiles_n * p; float* output1_tm = top_blob_tm + tiles_n * (p + 1); float* output2_tm = top_blob_tm + tiles_n * (p + 2); float* output3_tm = top_blob_tm + tiles_n * (p + 3); output0_tm = output0_tm + r * 4; output1_tm = output1_tm + r * 4; output2_tm = output2_tm + r * 4; output3_tm = output3_tm + r * 4; for (int i = 0; i < tiles; i++) { const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4) * inch * 16; const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i); #if __AVX__ || __SSE__ #if __AVX__ float zero_val = 0.f; __m128 _sum0 = _mm_broadcast_ss(&zero_val); __m128 _sum1 = _mm_broadcast_ss(&zero_val); __m128 _sum2 = _mm_broadcast_ss(&zero_val); __m128 _sum3 = _mm_broadcast_ss(&zero_val); #else __m128 _sum0 = _mm_set1_ps(0.f); __m128 _sum1 = _mm_set1_ps(0.f); __m128 _sum2 = _mm_set1_ps(0.f); __m128 _sum3 = _mm_set1_ps(0.f); #endif for (int q = 0; q < inch; q++) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _k0 = _mm_loadu_ps(kptr); __m128 _k1 = _mm_loadu_ps(kptr + 4); __m128 _k2 = _mm_loadu_ps(kptr + 8); __m128 _k3 = _mm_loadu_ps(kptr + 12); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); _sum1 = _mm_fmadd_ps(_r0, _k1, _sum1); _sum2 = _mm_fmadd_ps(_r0, _k2, _sum2); _sum3 = _mm_fmadd_ps(_r0, _k3, _sum3); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3)); #endif kptr += 16; r0 += 4; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output1_tm, _sum1); _mm_storeu_ps(output2_tm, _sum2); _mm_storeu_ps(output3_tm, _sum3); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; for (int q = 0; q < inch; q++) { for (int n = 0; n < 4; n++) { sum0[n] += r0[n] * kptr[n]; sum1[n] += r0[n] * kptr[n + 4]; sum2[n] += r0[n] * kptr[n + 8]; sum3[n] += r0[n] * kptr[n + 12]; } kptr += 16; r0 += 4; } for (int n = 0; n < 4; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; } #endif // __AVX__ output0_tm += 36; output1_tm += 36; output2_tm += 36; output3_tm += 36; } } remain_outch_start += nn_outch << 2; for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm + 36 * tiles * p; output0_tm = output0_tm + r * 4; for (int i = 0; i < tiles; i++) { const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4 + p % 4) * inch * 4; const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i); #if __AVX__ || __SSE__ #if __AVX__ float zero_val = 0.f; __m128 _sum0 = _mm_broadcast_ss(&zero_val); #else __m128 _sum0 = _mm_set1_ps(0.f); #endif for (int q = 0; q < inch; q++) { __m128 _r0 = _mm_loadu_ps(r0); __m128 _k0 = _mm_loadu_ps(kptr); #if __AVX__ _sum0 = _mm_fmadd_ps(_r0, _k0, _sum0); #else _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0)); #endif kptr += 4; r0 += 4; } _mm_storeu_ps(output0_tm, _sum0); #else float sum0[4] = {0}; for (int q = 0; q < inch; q++) { for (int n = 0; n < 4; n++) { sum0[n] += r0[n] * kptr[n]; } kptr += 4; r0 += 4; } for (int n = 0; n < 4; n++) { output0_tm[n] = sum0[n]; } #endif // __AVX__ || __SSE__ output0_tm += 36; } } } } // END dot // BEGIN transform output float* top_blob_bordered = NULL; if (outw_align == outw && outh_align == outh) { top_blob_bordered = top_blob; } else { top_blob_bordered = output_bordered; } { // 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_align / 4 * 6; int h_tm = outh_align / 4 * 6; int nColBlocks = h_tm / 6; // may be the block num in Feathercnn int nRowBlocks = w_tm / 6; const int tiles = nColBlocks * nRowBlocks; #pragma omp parallel for num_threads(num_thread) for (int p = 0; p < outch; p++) { float* out_tile = top_blob_tm + 36 * tiles * p; float* outRow0 = top_blob_bordered + outw_align * outh_align * p; float* outRow1 = outRow0 + outw_align; float* outRow2 = outRow0 + outw_align * 2; float* outRow3 = outRow0 + outw_align * 3; const float bias0 = bias ? bias[p] : 0.f; for (int j = 0; j < nColBlocks; j++) { for (int i = 0; i < nRowBlocks; i++) { // TODO AVX2 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]; o1[n] = d1[n] - d2[n] + 2 * d3[n] - 2 * d4[n]; o2[n] = d1[n] + d2[n] + 4 * d3[n] + 4 * d4[n]; o3[n] = d1[n] - d2[n] + 8 * d3[n] - 8 * d4[n] + d5[n]; } // save to top blob tm for (int n = 0; n < 4; n++) { outRow0[n] = o0[n] + bias0; outRow1[n] = o1[n] + bias0; outRow2[n] = o2[n] + bias0; outRow3[n] = o3[n] + bias0; } out_tile += 36; outRow0 += 4; outRow1 += 4; outRow2 += 4; outRow3 += 4; } outRow0 += outw_align * 3; outRow1 += outw_align * 3; outRow2 += outw_align * 3; outRow3 += outw_align * 3; } } } // END transform output if (outw_align != outw || outh_align != outw) { delete_0_3D(top_blob, top_blob_bordered, outh_align, outw_align, outh, outw, outch, 0, 0); } } void conv3x3s1_winograd43_transform_kernel_sse(const float* kernel, float* kernel_wino, int inch, int outch) { float* kernel_tm = ( float* )sys_malloc((unsigned long)6 * 6 * inch * outch * sizeof(float)); // 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 = kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm + p * inch * 36 + q * 36; // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3] = {0}; 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]; } } } } float* kernel_tm_test = kernel_wino; for (int r = 0; r < 9; r++) { int p = 0; for (; p + 7 < outch; p += 8) { const float* kernel0 = ( const float* )kernel_tm + p * inch * 36; const float* kernel1 = ( const float* )kernel_tm + (p + 1) * inch * 36; const float* kernel2 = ( const float* )kernel_tm + (p + 2) * inch * 36; const float* kernel3 = ( const float* )kernel_tm + (p + 3) * inch * 36; const float* kernel4 = ( const float* )kernel_tm + (p + 4) * inch * 36; const float* kernel5 = ( const float* )kernel_tm + (p + 5) * inch * 36; const float* kernel6 = ( const float* )kernel_tm + (p + 6) * inch * 36; const float* kernel7 = ( const float* )kernel_tm + (p + 7) * inch * 36; float* ktmp = kernel_tm_test + p / 8 * inch * 32; for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[r * 4 + 0]; ktmp[1] = kernel0[r * 4 + 1]; ktmp[2] = kernel0[r * 4 + 2]; ktmp[3] = kernel0[r * 4 + 3]; ktmp[4] = kernel1[r * 4 + 0]; ktmp[5] = kernel1[r * 4 + 1]; ktmp[6] = kernel1[r * 4 + 2]; ktmp[7] = kernel1[r * 4 + 3]; ktmp[8] = kernel2[r * 4 + 0]; ktmp[9] = kernel2[r * 4 + 1]; ktmp[10] = kernel2[r * 4 + 2]; ktmp[11] = kernel2[r * 4 + 3]; ktmp[12] = kernel3[r * 4 + 0]; ktmp[13] = kernel3[r * 4 + 1]; ktmp[14] = kernel3[r * 4 + 2]; ktmp[15] = kernel3[r * 4 + 3]; ktmp[16] = kernel4[r * 4 + 0]; ktmp[17] = kernel4[r * 4 + 1]; ktmp[18] = kernel4[r * 4 + 2]; ktmp[19] = kernel4[r * 4 + 3]; ktmp[20] = kernel5[r * 4 + 0]; ktmp[21] = kernel5[r * 4 + 1]; ktmp[22] = kernel5[r * 4 + 2]; ktmp[23] = kernel5[r * 4 + 3]; ktmp[24] = kernel6[r * 4 + 0]; ktmp[25] = kernel6[r * 4 + 1]; ktmp[26] = kernel6[r * 4 + 2]; ktmp[27] = kernel6[r * 4 + 3]; ktmp[28] = kernel7[r * 4 + 0]; ktmp[29] = kernel7[r * 4 + 1]; ktmp[30] = kernel7[r * 4 + 2]; ktmp[31] = kernel7[r * 4 + 3]; ktmp += 32; kernel0 += 36; kernel1 += 36; kernel2 += 36; kernel3 += 36; kernel4 += 36; kernel5 += 36; kernel6 += 36; kernel7 += 36; } } for (; p + 3 < outch; p += 4) { const float* kernel0 = ( const float* )kernel_tm + p * inch * 36; const float* kernel1 = ( const float* )kernel_tm + (p + 1) * inch * 36; const float* kernel2 = ( const float* )kernel_tm + (p + 2) * inch * 36; const float* kernel3 = ( const float* )kernel_tm + (p + 3) * inch * 36; float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4) * inch * 16; for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[r * 4 + 0]; ktmp[1] = kernel0[r * 4 + 1]; ktmp[2] = kernel0[r * 4 + 2]; ktmp[3] = kernel0[r * 4 + 3]; ktmp[4] = kernel1[r * 4 + 0]; ktmp[5] = kernel1[r * 4 + 1]; ktmp[6] = kernel1[r * 4 + 2]; ktmp[7] = kernel1[r * 4 + 3]; ktmp[8] = kernel2[r * 4 + 0]; ktmp[9] = kernel2[r * 4 + 1]; ktmp[10] = kernel2[r * 4 + 2]; ktmp[11] = kernel2[r * 4 + 3]; ktmp[12] = kernel3[r * 4 + 0]; ktmp[13] = kernel3[r * 4 + 1]; ktmp[14] = kernel3[r * 4 + 2]; ktmp[15] = kernel3[r * 4 + 3]; ktmp += 16; kernel0 += 36; kernel1 += 36; kernel2 += 36; kernel3 += 36; } } for (; p < outch; p++) { const float* kernel0 = ( const float* )kernel_tm + p * inch * 36; float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4 + p % 4) * inch * 4; for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[r * 4 + 0]; ktmp[1] = kernel0[r * 4 + 1]; ktmp[2] = kernel0[r * 4 + 2]; ktmp[3] = kernel0[r * 4 + 3]; ktmp += 4; kernel0 += 36; } } kernel_tm_test += 4 * inch * outch; } free(kernel_tm); } int wino_conv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param) { int batch = input_tensor->dims[0]; int input_c = input_tensor->dims[1]; int input_h = input_tensor->dims[2]; int input_w = input_tensor->dims[3]; int output_c = output_tensor->dims[1]; int output_h = output_tensor->dims[2]; int output_w = output_tensor->dims[3]; int pad_h = param->pad_h0; int pad_w = param->pad_w0; float* kernel = ( float* )filter_tensor->data; if (!priv_info->external_interleave_mem) { int mem_size = get_private_mem_size(filter_tensor, param); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } int block_h = (output_h + TILE - 1) / TILE; int block_w = (output_w + TILE - 1) / TILE; int block = block_h * block_w; int padded_inh = TILE * block_h + 2; int padded_inw = TILE * block_w + 2; int pad_inhw = padded_inh * padded_inw; int outw = block_w * TILE; int outh = block_h * TILE; priv_info->input_pad = ( float* )sys_malloc((unsigned long)batch * input_c * pad_inhw * sizeof(float)); memset(priv_info->input_pad, 0, (unsigned long)batch * input_c * pad_inhw * sizeof(float)); priv_info->dot_block = ( float* )sys_malloc(ELEM_SIZE * (unsigned long)block * output_c * sizeof(float)); priv_info->transform_input = ( float* )sys_malloc(ELEM_SIZE * (unsigned long)block * input_c * sizeof(float)); priv_info->output_bordered = NULL; if (outw != output_w || outh != output_h) { priv_info->output_bordered = ( float* )sys_malloc((unsigned long)outw * outh * output_c * sizeof(float)); } conv3x3s1_winograd43_transform_kernel_sse(kernel, ( float* )priv_info->interleave_buffer, input_c, output_c); return 0; } int wino_conv_hcl_postrun(struct conv_priv_info* priv_info) { if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; } if (priv_info->input_pad) { sys_free(priv_info->input_pad); priv_info->input_pad = NULL; } if (priv_info->dot_block) { sys_free(priv_info->dot_block); priv_info->dot_block = NULL; } if (priv_info->transform_input) { sys_free(priv_info->transform_input); priv_info->transform_input = NULL; } if (priv_info->output_bordered) { sys_free(priv_info->output_bordered); priv_info->output_bordered = NULL; } return 0; } int wino_conv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param, int num_thread, int cpu_affinity) { /* param */ int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int pad_h0 = param->pad_h0; int pad_w0 = param->pad_w0; int act_type = param->activation; int group = param->group; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1]; int in_c_g = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_c * in_h * in_w; int input_size_g = in_c_g * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int out_c = output_tensor->dims[1]; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int out_c_align = ((out_c + 3) & -4); /* wino param */ int block_h = (out_h + TILE - 1) / TILE; int block_w = (out_w + TILE - 1) / TILE; int block_hw = block_h * block_w; int padded_in_h = block_h * TILE + 2; int padded_in_w = block_w * TILE + 2; int padded_in_hw = padded_in_h * padded_in_w; /* buffer addr */ float* input = ( float* )input_tensor->data; float* output = ( float* )output_tensor->data; float* biases = NULL; if (bias_tensor != NULL) biases = ( float* )bias_tensor->data; for (int i = 0; i < batch; i++) { for (int g = 0; g < group; g++) { pad_0_align_3D((float*)priv_info->input_pad + i * in_c * padded_in_h * padded_in_w, input + i * in_c * in_h * in_w, in_h, in_w, padded_in_h, padded_in_w, in_c, pad_h0, pad_w0); conv3x3s1_winograd43_sse((float*)priv_info->input_pad + i * in_c * padded_in_h * padded_in_w + g * input_size_g, output + i * out_c * out_h * out_w, (float*)priv_info->interleave_buffer, (float*)priv_info->dot_block, (float*)priv_info->transform_input, (float*)priv_info->output_bordered, biases, padded_in_w, padded_in_h, in_c, out_w, out_h, out_c, num_thread); } } if (act_type >= 0) { relu(output, batch * output_size, act_type); } return 0; }
rnn_impl.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. */ /*! * Copyright (c) 2015 by Contributors * \file rnn_impl.h * \brief * \author Shu Zhang */ #ifndef MXNET_OPERATOR_RNN_IMPL_H_ #define MXNET_OPERATOR_RNN_IMPL_H_ #include <dmlc/logging.h> #include <dmlc/parameter.h> #include <mxnet/operator.h> #include <algorithm> #include <map> #include <vector> #include <string> #include <utility> #include "./math.h" #include "./math_functions-inl.h" #include "./operator_common.h" #include "./mshadow_op.h" #include "./linalg.h" namespace mxnet { namespace op { template<typename DType> inline DType sigmoid(DType x) { return 1.0f / (1.0f + exp(-x)); } template<typename DType> void LstmForwardTrainingSingleLayer(DType* ws, DType* rs, bool state_outputs, bool bid, const int T, const int N, const int I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, const Tensor<cpu, 2, DType> &cx, const Tensor<cpu, 3, DType> &y, DType* w_ptr, DType* b_ptr, DType* hy_ptr, DType* cy_ptr) { using namespace mshadow; const Tensor<cpu, 2, DType> wx(w_ptr, Shape2(H * 4, I)); const Tensor<cpu, 2, DType> wh(w_ptr + I * H * 4, Shape2(H * 4, H)); const Tensor<cpu, 2, DType> bx(b_ptr, Shape2(4, H)); const Tensor<cpu, 2, DType> bh(b_ptr + H * 4, Shape2(4, H)); const Tensor<cpu, 2, DType> yx_flat(ws, Shape2(T * N, 4 * H)); const Tensor<cpu, 2, DType> yh_flat(ws + T * N * H * 4, Shape2(N, 4 * H)); const Tensor<cpu, 4, DType> yx(yx_flat.dptr_, Shape4(T, N, 4, H)); const Tensor<cpu, 3, DType> yh(yh_flat.dptr_, Shape3(N, 4, H)); Tensor<cpu, 2, DType> h(yh_flat.dptr_ + N * H * 4, Shape2(N, H)); DType *c_ptr = bid ? rs + T * N * H * 7 : rs; Tensor<cpu, 3, DType> c(c_ptr, Shape3(T, N, H)); Tensor<cpu, 4, DType> ifgo(c_ptr + T * N * H, Shape4(T, N, H, 4)); const int offset = bid ? H : 0; const DType alpha = 1.0; const DType beta = 0.0; const int cell_size = N * H; linalg_gemm(x, wx, yx_flat, alpha, beta, false, true); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (int i = 0; i < T; ++i) { int t = bid ? T - 1 - i : i; linalg_gemm(i ? h : hx, wh, yh_flat, alpha, beta, false, true); #pragma omp parallel for num_threads(omp_threads) for (int jk = 0; jk < cell_size; ++jk) { int j = jk / H; int k = jk % H; DType it = sigmoid<DType>(yx[t][j][0][k] + yh[j][0][k] + bx[0][k] + bh[0][k]); DType ft = sigmoid<DType>(yx[t][j][1][k] + yh[j][1][k] + bx[1][k] + bh[1][k]); DType gt = tanh(yx[t][j][2][k] + yh[j][2][k] + bx[2][k] + bh[2][k]); DType ot = sigmoid<DType>(yx[t][j][3][k] + yh[j][3][k] + bx[3][k] + bh[3][k]); DType ct = (i ? c[i-1][j][k] : cx[j][k]) * ft + it * gt; DType ht = ot * tanh(ct); h[j][k] = ht; // reserve y[t][j][k + offset] = ht; c[i][j][k] = ct; ifgo[i][j][k][0] = it; ifgo[i][j][k][1] = ft; ifgo[i][j][k][2] = gt; ifgo[i][j][k][3] = ot; if (i == T - 1 && state_outputs) { hy_ptr[jk] = ht; cy_ptr[jk] = ct; } } } } template <typename DType> void LstmForwardTraining(DType* ws, DType* rs, bool state_outputs, const int L, const int D, const int T, const int N, const int I, const int H, DType* x_ptr, DType* hx_ptr, DType* cx_ptr, DType* w_ptr, DType* b_ptr, DType* y_ptr, DType* hy_ptr, DType* cy_ptr) { const int total_layers = D * L; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> cx(cx_ptr, Shape3(total_layers, N, H)); const int b_size = 2 * H * 4; const int r_size = D * T * N * H * 6; const int y_offset = T * N * H * 5; const int cell_size = N * H; int idx = 0; // state & cell state's idx; for (int i = 0; i < L; ++i) { const int input_size = i ? H * D : I; const int w_size = (input_size + H) * H * 4; Tensor<cpu, 2, DType> x(x_ptr, Shape2(T * N, input_size)); Tensor<cpu, 3, DType> y(rs + y_offset, Shape3(T, N, H * D)); LstmForwardTrainingSingleLayer<DType>(ws, rs, state_outputs, false, T, N, input_size, H, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); if (D == 2) { w_ptr += w_size; b_ptr += b_size; ++idx; if (state_outputs) { hy_ptr += cell_size; cy_ptr += cell_size; } LstmForwardTrainingSingleLayer<DType>(ws, rs, state_outputs, true, T, N, input_size, H, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); } if (i != L - 1) { w_ptr += w_size; b_ptr += b_size; x_ptr = y.dptr_; rs += r_size; ++idx; if (state_outputs) { hy_ptr += cell_size; cy_ptr += cell_size; } } } memcpy(y_ptr, rs + y_offset, T * N * H * D * sizeof(DType)); } template<typename DType> void LstmForwardInferenceSingleLayer(DType* ws, bool state_outputs, bool bid, const int T, const int N, const int I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, const Tensor<cpu, 2, DType> &cx, const Tensor<cpu, 3, DType> &y, DType* w_ptr, DType* b_ptr, DType* hy_ptr, DType* cy_ptr) { using namespace mshadow; const Tensor<cpu, 2, DType> wx(w_ptr, Shape2(H * 4, I)); const Tensor<cpu, 2, DType> wh(w_ptr + I * H * 4, Shape2(H * 4, H)); const Tensor<cpu, 2, DType> bx(b_ptr, Shape2(4, H)); const Tensor<cpu, 2, DType> bh(b_ptr + H * 4, Shape2(4, H)); Tensor<cpu, 2, DType> yx_flat(ws, Shape2(T * N, H * 4)); Tensor<cpu, 2, DType> yh_flat(ws + T * N * H * 4, Shape2(N, H * 4)); const Tensor<cpu, 4, DType> yx(yx_flat.dptr_, Shape4(T, N, 4, H)); const Tensor<cpu, 3, DType> yh(yh_flat.dptr_, Shape3(N, 4, H)); Tensor<cpu, 2, DType> h(yh_flat.dptr_ + N * H * 4, Shape2(N, H)); Tensor<cpu, 2, DType> c(h.dptr_ + N * H, Shape2(N, H)); const int offset = bid ? H : 0; const DType alpha = 1.0; const DType beta = 0.0; const int cell_size = N * H; linalg_gemm(x, wx, yx_flat, alpha, beta, false, true); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (int i = 0; i < T; ++i) { int t = bid ? T - 1 - i : i; linalg_gemm(i ? h : hx, wh, yh_flat, alpha, beta, false, true); #pragma omp parallel for num_threads(omp_threads) for (int jk = 0; jk < cell_size; ++jk) { int j = jk / H; int k = jk % H; DType it = sigmoid<DType>(yx[t][j][0][k] + yh[j][0][k] + bx[0][k] + bh[0][k]); DType ft = sigmoid<DType>(yx[t][j][1][k] + yh[j][1][k] + bx[1][k] + bh[1][k]); DType gt = tanh(yx[t][j][2][k] + yh[j][2][k] + bx[2][k] + bh[2][k]); DType ot = sigmoid<DType>(yx[t][j][3][k] + yh[j][3][k] + bx[3][k] + bh[3][k]); DType ct = (i ? c[j][k] : cx[j][k]) * ft + it * gt; DType ht = ot * tanh(ct); y[t][j][k + offset] = ht; if (i == T - 1 && state_outputs) { hy_ptr[jk] = ht; cy_ptr[jk] = ct; } else { h[j][k] = ht; c[j][k] = ct; } } } } template <typename DType> void LstmForwardInference(DType* ws, bool state_outputs, const int L, const int D, const int T, const int N, const int I, const int H, DType* x_ptr, DType* hx_ptr, DType* cx_ptr, DType* w_ptr, DType* b_ptr, DType* y_ptr, DType* hy_ptr, DType* cy_ptr) { const int total_layers = D * L; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> cx(cx_ptr, Shape3(total_layers, N, H)); const int b_size = 2 * H * 4; const int cell_size = N * H; DType* y_tmp_ptr = ws + (T + 1) * cell_size * 4 + cell_size * 2; DType* y_cur_ptr = y_ptr; int idx = 0; // state & cell state's idx; bool flag = L % 2 ? false : true; for (int i = 0; i < L; ++i) { const int input_size = i ? H * D : I; const int w_size = (input_size + H) * H * 4; // If bidirectional, need space to save current layer output y. if (D == 2) { y_cur_ptr = flag ? y_tmp_ptr : y_ptr; flag = !flag; } Tensor<cpu, 2, DType> x(x_ptr, Shape2(T * N, input_size)); Tensor<cpu, 3, DType> y(y_cur_ptr, Shape3(T, N, H * D)); LstmForwardInferenceSingleLayer<DType>(ws, state_outputs, false, T, N, input_size, H, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); // If bidirectional, then calculate the reverse direction's forward result. if (D == 2) { w_ptr += w_size; b_ptr += b_size; ++idx; if (state_outputs) { hy_ptr += cell_size; cy_ptr += cell_size; } LstmForwardInferenceSingleLayer<DType>(ws, state_outputs, true, T, N, input_size, H, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); } // Don't need to move pointer in the last layer. if (i != L - 1) { w_ptr += w_size; b_ptr += b_size; x_ptr = y_cur_ptr; ++idx; if (state_outputs) { hy_ptr += cell_size; cy_ptr += cell_size; } } } } template <typename DType> void LstmBackwardSingleLayer(DType* ws, DType* rs, DType* tmp_buf, bool bid, const int T, const int N, const int I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, const Tensor<cpu, 2, DType> &cx, const Tensor<cpu, 3, DType> &y, const Tensor<cpu, 3, DType> &dy, const Tensor<cpu, 2, DType> &dx, const Tensor<cpu, 2, DType> &dhx, const Tensor<cpu, 2, DType> &dcx, DType* dhy_ptr, DType* dcy_ptr, DType* w_ptr, DType* dw_ptr, DType* db_ptr, int req_data, int req_params, int req_state, int req_statecell) { using namespace mshadow; const Tensor<cpu, 2, DType> wx(w_ptr, Shape2(H * 4, I)); const Tensor<cpu, 2, DType> wh(w_ptr + I * H * 4, Shape2(H * 4, H)); Tensor<cpu, 2, DType> dwx(dw_ptr, Shape2(H * 4, I)); Tensor<cpu, 2, DType> dwh(dw_ptr + I * H * 4, Shape2(H * 4, H)); Tensor<cpu, 1, DType> dbx(db_ptr, Shape1(H * 4)); Tensor<cpu, 1, DType> dbh(dbx.dptr_ + H * 4, Shape1(H * 4)); DType *c_ptr = bid ? rs + T * N * H * 7 : rs; const Tensor<cpu, 3, DType> c(c_ptr, Shape3(T, N, H)); const Tensor<cpu, 4, DType> ifgo(c_ptr + T * N * H, Shape4(T, N, H, 4)); memset(dwh.dptr_, 0, H * H * 4 * sizeof(DType)); memset(dbx.dptr_, 0, H * 4 * sizeof(DType)); memset(dbh.dptr_, 0, H * 4 * sizeof(DType)); Tensor<cpu, 4, DType> difgo(ws, Shape4(T, N, 4, H)); Tensor<cpu, 2, DType> dh(ws + T * N * H * 4, Shape2(N, H)); Tensor<cpu, 2, DType> dc(dh.dptr_ + N * H, Shape2(N, H)); Tensor<cpu, 2, DType> htmp(dc.dptr_ + N * H, Shape2(N, H)); const int offset = bid ? H : 0; const DType alpha = 1.0; const DType beta0 = 0.0; const DType beta1 = 1.0; const DType beta2 = 2.0; const int cell_size = N * H; if (dhy_ptr != NULL) { memcpy(dh.dptr_, dhy_ptr, cell_size * sizeof(DType)); } if (dcy_ptr != NULL) { memcpy(dc.dptr_, dcy_ptr, cell_size * sizeof(DType)); } const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (int i = T - 1; i >= 0; --i) { int t = bid ? T - 1 - i : i; int tnext = bid ? t + 1 : t - 1; const Tensor<cpu, 2, DType>& dhnext = i ? dh : dhx; const Tensor<cpu, 2, DType>& dcnext = i ? dc : dcx; const Tensor<cpu, 2, DType>& hnext = i ? htmp : hx; const Tensor<cpu, 2, DType>& cnext = i ? c[i - 1] : cx; #pragma omp parallel for num_threads(omp_threads) for (int jk = 0; jk < cell_size; ++jk) { int j = jk / H; int k = jk % H; DType tc = tanh(c[i][j][k]); DType it = ifgo[i][j][k][0]; DType ft = ifgo[i][j][k][1]; DType gt = ifgo[i][j][k][2]; DType ot = ifgo[i][j][k][3]; dh[j][k] += dy[t][j][k + offset]; dc[j][k] += dh[j][k] * ot * (1 - tc * tc); difgo[t][j][0][k] = dc[j][k] * gt * it * (1 - it); difgo[t][j][1][k] = dc[j][k] * cnext[j][k] * ft * (1 - ft); difgo[t][j][2][k] = dc[j][k] * it * (1 - gt * gt); difgo[t][j][3][k] = dh[j][k] * tc * ot * (1 - ot); if (req_statecell != kNullOp || i > 0) { dcnext[j][k] = dc[j][k] * ft; } if (i) { htmp[j][k] = y[tnext][j][k + offset]; } } Tensor<cpu, 2, DType> dyh(difgo[t].dptr_, Shape2(N, H * 4)); if (req_state != kNullOp || i > 0) { linalg_gemm(dyh, wh, dhnext, alpha, beta0, false, false); } if (req_params != kNullOp) { if (req_params != kAddTo) { linalg_gemm(dyh, hnext, dwh, alpha, beta1, true, false); } else { linalg_gemm(dyh, hnext, dwh, alpha, beta2, true, false); // generate dwx every time step for AddTo Tensor<cpu, 2, DType> x_t(x.dptr_ + i * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> dyx_t(difgo.dptr_ + i * N * H * 4, Shape2(N, H * 4)); linalg_gemm(dyx_t, x_t, dwx, alpha, beta2, true, false); } } } Tensor<cpu, 2, DType> dyx(difgo.dptr_, Shape2(T * N, H * 4)); if (req_data != kNullOp) { linalg_gemm(dyx, wx, dx, alpha, bid ? beta1 : beta0, false, false); } if (req_params != kNullOp && req_params != kAddTo) { linalg_gemm(dyx, x, dwx, alpha, beta0, true, false); } const int row = T * N; const int col = H * 4; if (req_params != kNullOp) { if (req_params != kAddTo) { for (int i = 0; i < row; ++i) { #pragma omp parallel for num_threads(omp_threads) for (int j = 0; j < col; ++j) { dbx[j] += dyx[i][j]; dbh[j] = dbx[j]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf, Shape2(col, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + col * T, Shape2(col, T)); memset(tmp_dbx.dptr_, 0, col * T * sizeof(DType)); memset(tmp_dbh.dptr_, 0, col * T * sizeof(DType)); for (int t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int j = 0; j < col; ++j) { for (int i = 0; i < N; ++i) { tmp_dbx[j][t] += dyx[t * N + i][j]; tmp_dbh[j][t] = tmp_dbx[j][t]; } } #pragma omp parallel for num_threads(omp_threads) for (int j = 0; j < col; ++j) { dbx[j] += tmp_dbx[j][t] + dbx[j]; dbh[j] += tmp_dbh[j][t] + dbh[j]; } } } } } template <typename DType> void LstmBackward(DType* ws, DType* rs, const int L, const int D, const int T, const int N, const int I, const int H, DType* x_ptr, DType* hx_ptr, DType* cx_ptr, DType* w_ptr, DType* y_ptr, DType* dy_ptr, DType* dhy_ptr, DType* dcy_ptr, DType* dx_ptr, DType* dhx_ptr, DType* dcx_ptr, DType* dw_ptr, DType* db_ptr, int req_data, int req_params, int req_state, int req_statecell) { DType* tmp_buf = ws; DType* ws2 = tmp_buf + 8 * T * H; const int total_layers = D * L; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> cx(cx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> dhx(dhx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> dcx(dcx_ptr, Shape3(total_layers, N, H)); const int b_size = 2 * H * 4; const int r_size = D * T * N * H * 6; const int y_offset = T * N * H * 5; const int w_size1 = (I + H) * H * 4; // first layer const int w_size2 = (D * H + H) * H * 4; // other layers const int cell_size = N * H; DType* dy_tmp_ptr = ws2 + T * cell_size * 4 + cell_size * 3; for (int i = L - 1; i >= 0; --i) { const int input_size = i ? H * D : I; const int w_size = i ? w_size2 : w_size1; int idx = i * D; DType* w_cur_ptr = i ? w_ptr + (w_size1 + (i - 1) * w_size2) * D : w_ptr; DType* dw_cur_ptr = i ? dw_ptr + (w_size1 + (i - 1) * w_size2) * D : dw_ptr; DType* db_cur_ptr = db_ptr + i * b_size * D; DType* rs_cur_ptr = rs + i * r_size; DType* dhy_cur_ptr = dhy_ptr ? dhy_ptr + i * cell_size * D : NULL; DType* dcy_cur_ptr = dcy_ptr ? dcy_ptr + i * cell_size * D : NULL; Tensor<cpu, 3, DType> y(rs_cur_ptr + y_offset, Shape3(T, N, H * D)); Tensor<cpu, 3, DType> dy(dy_ptr, Shape3(T, N, H * D)); Tensor<cpu, 2, DType> x(i ? y.dptr_ - r_size : x_ptr, Shape2(T * N, input_size)); Tensor<cpu, 2, DType> dx(i ? dy_tmp_ptr : dx_ptr, Shape2(T * N, input_size)); LstmBackwardSingleLayer<DType>(ws2, rs_cur_ptr, tmp_buf, false, T, N, input_size, H, x, hx[idx], cx[idx], y, dy, dx, dhx[idx], dcx[idx], dhy_cur_ptr, dcy_cur_ptr, w_cur_ptr, dw_cur_ptr, db_cur_ptr, req_data, req_params, req_state, req_statecell); if (D == 2) { w_cur_ptr += w_size; dw_cur_ptr += w_size; db_cur_ptr += b_size; ++idx; dhy_cur_ptr = dhy_ptr ? dhy_cur_ptr + cell_size : NULL; dcy_cur_ptr = dcy_ptr ? dcy_cur_ptr + cell_size : NULL; LstmBackwardSingleLayer<DType>(ws2, rs_cur_ptr, tmp_buf, true, T, N, input_size, H, x, hx[idx], cx[idx], y, dy, dx, dhx[idx], dcx[idx], dhy_cur_ptr, dcy_cur_ptr, w_cur_ptr, dw_cur_ptr, db_cur_ptr, req_data, req_params, req_state, req_statecell); } dy_ptr = dx.dptr_; } } template<typename DType> void GruForwardInferenceSingleLayer(DType* ws, DType* tmp_buf, bool state_outputs, const int D, const int T, const int N, const int I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* bx_ptr, DType* bh_ptr, DType* y_ptr, DType* hy_ptr) { DType* ht = y_ptr; DType* ht_1 = y_ptr; DType* back_ht_1 = y_ptr + (T-1) * N * H * D + H; DType* back_ht = back_ht_1; DType* gemmC1 = ws; // [D, T, N, 3 * H] DType* gemmC2 = gemmC1 + D * T * N * 3 * H; // N * 3 * H DType* rt = gemmC2 + N * 3 * H; DType* zt = rt + N * H; DType* nt = zt + N * H; DType* back_wx_ptr = wx_ptr + I * 3 * H + H * 3 * H; DType* back_wh_ptr = wh_ptr + I * 3 * H + H * 3 * H; DType* back_bx_ptr = (bx_ptr != NULL)? bx_ptr + 3 * H * 2 : NULL; DType* back_bh_ptr = (bh_ptr != NULL)? bh_ptr + 3 * H * 2: NULL; DType* back_gemmC1 = gemmC1 + T * N * 3 * H; DType* gemmC1_t = gemmC1; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> bx(bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> bh(bh_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> back_bx(back_bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_bh(back_bh_ptr, Shape2(3, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (D == 1) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * H + j] = hx[i][j]; } } else { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * D * H + j] = hx[i][j]; back_ht_1[i * D * H + j] = hx[N + i][j]; } } Tensor<cpu, 2, DType> dgemmC1(ws, Shape2(T * N, 3 * H)); Tensor<cpu, 2, DType> dgemmC2(gemmC2, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> dback_gemmC1(back_gemmC1, Shape2(T * N, 3 * H)); // x * wx.T : [T * N, I] * [I, 3 * H] DType alpha = 1.0; DType beta = 0.0; linalg_gemm(x, wx, dgemmC1, alpha, beta, false, true); if (D == 2) { linalg_gemm(x, back_wx, dback_gemmC1, alpha, beta, false, true); } for (int t = 0; t < T; t++) { // perform the first direction, X * wx and H * wh for each step // ht-1 * wh, ht-1:[N, H] wh:[3 * H, H] Tensor<cpu, 2, DType> dht_1(ht_1, Shape2(N, D * H)); if (D == 1) { linalg_gemm(dht_1, wh, dgemmC2, alpha, beta, false, true); } else { Tensor<cpu, 3, DType> dht_1_tmp = Tensor<cpu, 3, DType>(reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dht_1_tmp = reshape(dht_1.T(), Shape3(D, H, N)); linalg_gemm(dht_1_tmp[0], wh, dgemmC2, alpha, beta, true, true); } gemmC1_t = gemmC1 + t * N * 3 * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int rtb = i * 3 * H; int ztb = i * 3 * H + H; int ntb = i * 3 * H + 2 * H; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + bx[0][j] + bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + bx[1][j] + bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + bh[2][j])); ht[i * D * H + j] = (1-zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * ht_1[i * D * H + j]; } } ht_1 = ht; ht = ht + D * H * N; // perform the second direction if (D == 2) { gemmC1_t = back_gemmC1 + (T - 1 - t) * N * 3 * H; Tensor<cpu, 2, DType> dback_ht_1(back_ht_1, Shape2(N, D * H)); Tensor<cpu, 3, DType> dback_ht_1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dback_ht_1_tmp = reshape(dback_ht_1.T(), Shape3(D, H, N)); linalg_gemm(dback_ht_1_tmp[0], back_wh, dgemmC2, alpha, beta, true, true); #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int rtb = i * 3 * H; int ztb = i * 3 * H + H; int ntb = i * 3 * H + 2 * H; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + back_bx[0][j] + back_bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + back_bx[1][j]+ back_bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + back_bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + back_bh[2][j])); back_ht[i * D * H + j] = (1 - zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * back_ht_1[i * D * H + j]; } } back_ht_1 = back_ht; back_ht = back_ht - D * H * N; } } // copy last state to hy, from(N, H * D) to (D, N, H) if (state_outputs) { if (D == 1) { DType* y_start = y_ptr + (T - 1) * N * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * H + j]; } } else { DType* y_start = y_ptr + (T - 1) * N * H * D; DType* y_back_start = y_ptr + H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * D * H + j]; hy_ptr[N * H + i * H + j] = y_back_start[i * D * H + j]; } } } } template <typename DType> void GruForwardInference(DType* ws, bool state_outputs, const int L, const int D, const int T, const int N, int I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* y_ptr, DType* hy_ptr) { DType* wx = w_ptr; DType* wh = wx + I * H * 3; DType* bx = wh + H * H * 3 + (D - 1) * (H * H * 3 + I * H * 3) + (L - 1) * ((D + 1) * H) * H * 3 * D; DType* bh = bx + H * 3; DType* y_tmp = ws; DType* y_l = x_ptr; DType* tmp_buf = y_tmp + D * T * N * H; DType* ws2 = y_tmp + D * T * N * H + D * H * N; DType* wx_l = wx; DType* wh_l = wh; DType* bx_l = bx; DType* bh_l = bh; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(D * L, N, H)); DType* hy_l = hy_ptr; for (int l = 0; l < L; l++) { Tensor<cpu, 2, DType> x_l(y_l, Shape2(T * N, I)); if ((L + l) % 2) { y_l = y_ptr; } else { y_l = y_tmp; } Tensor<cpu, 2, DType> hx_l = hx[D * l]; GruForwardInferenceSingleLayer<DType>(ws2, tmp_buf, state_outputs, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, bx_l, bh_l, y_l, hy_l); hy_l = hy_l + D * N * H; bx_l = bx_l + 3 * H * D * 2; bh_l = bh_l + 3 * H * D * 2; wx_l = wx_l + I * H * 3 * D + H * H * 3 * D; if (l == 0) { I = D * H; } wh_l = wx_l + I * 3 * H; } } template<typename DType> void GruForwardTrainingSingleLayer(DType* ws, DType* tmp_buf, bool state_outputs, const int D, const int T, const int N, const int I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* bx_ptr, DType* bh_ptr, DType* gateR, DType* gateZ, DType* gateN, DType* Mnh, DType* y_ptr, DType* hy_ptr) { DType* ht = y_ptr; DType* ht_1 = y_ptr; DType* back_ht_1 = y_ptr + (T - 1)* N * H * D + H; DType* back_ht = back_ht_1; DType* gemmC1 = ws; // [D, T, N, 3 * H] DType* gemmC2 = gemmC1 + D * T * N * 3 * H; // N * 3 * H DType* rt = gateR; DType* zt = gateZ; DType* nt = gateN; DType* back_wx_ptr = wx_ptr + I * 3 * H + H * 3 * H; DType* back_wh_ptr = wh_ptr + I * 3 * H + H * 3 * H; DType* back_bx_ptr = (bx_ptr != NULL)? bx_ptr + 3 * H * 2 : NULL; DType* back_bh_ptr = (bh_ptr != NULL)? bh_ptr + 3 * H * 2 : NULL; DType* back_gateR = gateR + T * N * H; DType* back_gateZ = gateZ + T * N * H; DType* back_gateN = gateN + T * N * H; DType* back_Mnh = Mnh + T * N * H; DType* back_gemmC1 = gemmC1 + T * N * 3 * H; DType* gemmC1_t = gemmC1; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> bx(bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> bh(bh_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> back_bx(back_bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_bh(back_bh_ptr, Shape2(3, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (D == 1) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * H + j] = hx[i][j]; } } else { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * D * H + j] = hx[i][j]; back_ht_1[i * D * H + j] = hx[N + i][j]; } } Tensor<cpu, 2, DType> dgemmC1(ws, Shape2(T * N, 3 * H)); Tensor<cpu, 2, DType> dgemmC2(gemmC2, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> dback_gemmC1(back_gemmC1, Shape2(T * N, 3 * H)); // x * wx.T : [T * N, I] * [I, 3 * H] DType alpha = 1.0; DType beta = 0.0; linalg_gemm(x, wx, dgemmC1, alpha, beta, false, true); if (D == 2) { linalg_gemm(x, back_wx, dback_gemmC1, alpha, beta, false, true); } for (int t = 0; t < T; t++) { // perform the first direction, X * wx and H * wh for each step // ht-1 * wh, ht-1:[N, H] wh:[3 * H, H] Tensor<cpu, 2, DType> dht_1(ht_1, Shape2(N, D * H)); if (D == 1) { linalg_gemm(dht_1, wh, dgemmC2, alpha, beta, false, true); } else { Tensor<cpu, 3, DType> dht_1_tmp = Tensor<cpu, 3, DType>(reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dht_1_tmp = reshape(dht_1.T(), Shape3(D, H, N)); linalg_gemm(dht_1_tmp[0], wh, dgemmC2, alpha, beta, true, true); } rt = gateR + t * N * H; zt = gateZ + t * N * H; nt = gateN + t * N * H; gemmC1_t = gemmC1 + t * N * 3 * H; DType* Mnht = Mnh + t * N * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int rtb = i * 3 * H; int ztb = i * 3 * H + H; int ntb = i * 3 * H + 2 * H; Mnht[i * H + j] = gemmC2[ntb + j] + bh[2][j]; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + bx[0][j] + bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + bx[1][j] + bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + bh[2][j])); ht[i * D * H + j] = (1-zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * ht_1[i * D * H + j]; } } ht_1 = ht; ht = ht + D * H * N; // perform the second direction if (D == 2) { rt = back_gateR + (T - 1 - t) * N * H; zt = back_gateZ + (T - 1 - t) * N * H; nt = back_gateN + (T - 1 - t) * N * H; gemmC1_t = back_gemmC1 + (T - 1 - t) * N * 3 * H; Tensor<cpu, 2, DType> dback_ht_1(back_ht_1, Shape2(N, D * H)); Tensor<cpu, 3, DType> dback_ht_1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dback_ht_1_tmp = reshape(dback_ht_1.T(), Shape3(D, H, N)); linalg_gemm(dback_ht_1_tmp[0], back_wh, dgemmC2, alpha, beta, true, true); DType* back_Mnht = back_Mnh + (T - 1 - t) * N * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int rtb = i * 3 * H; int ztb = i * 3 * H + H; int ntb = i * 3 * H + 2 * H; back_Mnht[i * H + j] = gemmC2[ntb + j] + back_bh[2][j]; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + back_bx[0][j] + back_bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + back_bx[1][j] + back_bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + back_bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + back_bh[2][j])); back_ht[i * D * H + j] = (1 - zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * back_ht_1[i * D * H + j]; } } back_ht_1 = back_ht; back_ht = back_ht - D * H * N; } } // copy last state to hy, from(N, H * D) to (D, N, H) if (state_outputs) { if (D == 1) { DType* y_start = y_ptr + (T - 1) * N * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * H + j]; } } else { DType* y_start = y_ptr + (T - 1) * N * H * D; DType* y_back_start = y_ptr + H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * D * H + j]; hy_ptr[N * H + i * H + j] = y_back_start[i * D * H + j]; } } } } template <typename DType> void GruForwardTraining(DType* ws, DType* rs, bool state_outputs, const int L, const int D, const int T, const int N, int I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* y_ptr, DType* hy_ptr) { DType* wx = w_ptr; DType* wh = wx + I * H * 3; DType* bx = wh + H * H * 3 + (D - 1) * (H * H * 3 + I * H * 3) + (L - 1) * ((D + 1) * H) * H * 3 * D; DType* bh = bx + H * 3; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(D * L, N, H)); DType* hy_l = hy_ptr; DType* gateR_l = rs; DType* gateZ_l = gateR_l + L * T * D * N * H; DType* gateN_l = gateZ_l + L * T * D * N * H; DType* y_l = gateN_l + L * T * D * N * H; DType* Mnh_l = y_l + L * T * N * H * D; DType* tmp_buf = Mnh_l + L * D * T * N * H; DType* ws2 = Mnh_l + L * D * T * N * H + D * H * N; DType* wx_l = wx; DType* wh_l = wh; DType* bx_l = bx; DType* bh_l = bh; DType* y_tmp = x_ptr; for (int l = 0; l < L; l++) { if (l != 0) { y_tmp = y_l; y_l = y_l + T * N * H * D; } Tensor<cpu, 2, DType> x_l(y_tmp, Shape2(T * N, I)); Tensor<cpu, 2, DType> hx_l = hx[D * l]; GruForwardTrainingSingleLayer<DType>(ws2, tmp_buf, state_outputs, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, bx_l, bh_l, gateR_l, gateZ_l, gateN_l, Mnh_l, y_l, hy_l); gateR_l = gateR_l + T * D * N * H; gateZ_l = gateZ_l + T * D * N * H; gateN_l = gateN_l + T * D * N * H; Mnh_l = Mnh_l + T * D * N * H; hy_l = hy_l + D * N * H; bx_l = bx_l + 3 * H * D * 2; bh_l = bh_l + 3 * H * D * 2; wx_l = wx_l + I * H * 3 * D + H * H * 3 * D; if (l == 0) { I = D * H; } wh_l = wx_l + I * 3 * H; } memcpy(y_ptr, y_l, T * N * H * D * sizeof(DType)); } template <typename DType> void GruBackwardSingleLayer(DType* ws, DType* tmp_buf, const int D, const int T, const int N, const int I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* y_ptr, DType* dy_ptr, DType* dhy_ptr, DType* gateR, DType* gateZ, DType* gateN, DType* Mnh, DType* dx, DType* dhx, DType* dwx, DType* dwh, DType* dbx, DType* dbh, int req_data, int req_params, int req_state) { DType* dyt; DType* ht1; // [N, D, H] DType* rt; DType* zt; DType* nt; DType* dat; DType* dart; DType* dar = ws; // [T, N, 3 * H] DType* da = dar + T * N * 3 * H; // [T, N, 3 * H] DType* dht1 = da + T * N * 3 * H; // [D, N, H] DType* hx_ = dht1 + D * N * H; // [N, D, H] DType* Mnht = Mnh; DType* back_ht1; DType* back_dht1 = dht1 + N * H; // [N, H] DType* back_Mnht = Mnh + T * N * H; DType* back_gateR = gateR + T * N * H; DType* back_gateZ = gateZ + T * N * H; DType* back_gateN = gateN + T * N * H; DType* back_wx_ptr = wx_ptr + I * 3 * H + H * 3 * H; DType* back_wh_ptr = wh_ptr + I * 3 * H + H * 3 * H; DType* back_dwx = dwx + I * 3 * H + H * 3 * H; DType* back_dwh = dwh + I * 3 * H + H * 3 * H; DType* back_dbx = dbx + 3 * H * 2; DType* back_dbh = dbh + 3 * H * 2; DType alpha = 1.0; DType beta = 0.0; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 3, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N * H; ++i) { if (dhy_ptr) { dht1[i] = dhy_ptr[i]; } else { dht1[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { hx_[i * D * H + j] = hx[i][j]; } } if (D == 2) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N * H; ++i) { if (dhy_ptr) { back_dht1[i] = dhy_ptr[N * H + i]; } else { back_dht1[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { hx_[i * D * H + H + j] = hx[N + i][j]; } } } for (int t = T - 1; t >= 0; --t) { if (t) { ht1 = y_ptr + (t - 1) * N * D * H; } else { ht1 = hx_; } // add dy[T, N, D, H] to dhy[D, N, H] dyt = dy_ptr + t * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { dht1[i * H + j] += dyt[i * D * H + j]; } } rt = gateR + t * N * H; zt = gateZ + t * N * H; nt = gateN + t * N * H; Mnht = Mnh + t * N * H; dat = da + t * N * 3 * H; dart = dar + t * N * 3 * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int nid = i * 3 * H + 2 * H + j; int zid = i * 3 * H + H + j; int rid = i * 3 * H + j; int id = i * H + j; dat[nid] = dht1[id] * (1 - zt[id]) * (1 - nt[id] * nt[id]); dart[zid] = dat[zid] = dht1[id] * (ht1[i * D * H + j] - nt[id]) * zt[id] * (1 - zt[id]); dart[rid] = dat[rid] = dat[nid] * Mnht[id] * rt[id] * (1 - rt[id]); dart[nid] = dat[nid] * rt[id]; dht1[id] = dht1[id] * zt[id]; } } if (req_params != kNullOp) { alpha = 1.0; beta = 1.0; // dht1 = dart * wh [N, H] = [N, 3 * H] * [3 * H, H] Tensor<cpu, 2, DType> d_dht1(dht1, Shape2(N, H)); Tensor<cpu, 2, DType> d_dart(dart, Shape2(N, 3 * H)); linalg_gemm(d_dart, wh, d_dht1, alpha, beta, false, false); if (req_params == kAddTo) { beta = 2.0; // dwx = da.T * x [3 * H, I] = [3 * H, N] * [N, I] for AddTo Tensor<cpu, 2, DType> d_xt(x.dptr_ + t * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> d_dat(dat, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> d_dwx(dwx, Shape2(3 * H, I)); linalg_gemm(d_dat, d_xt, d_dwx, alpha, beta, true, false); } // dwh = dart.T * ht1 [3 * H, H] = [3 * H, N] * [N, H] Tensor<cpu, 2, DType> d_ht1(ht1, Shape2(N, D * H)); Tensor<cpu, 2, DType> d_dwh(dwh, Shape2(3 * H, H)); Tensor<cpu, 3, DType> d_ht1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); d_ht1_tmp = reshape(d_ht1.T(), Shape3(D, H, N)); linalg_gemm(d_dart, d_ht1_tmp[0], d_dwh, alpha, beta, true, true); } } if (req_params != kNullOp) { // dbx = e * da [1, 3 * H] = [1, N] * [N, 3 * H] if (req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (int j = 0; j < N * T; ++j) { dbx[i] += da[j * 3 * H + i]; dbh[i] += dar[j * 3 * H + i]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf + T * N * D * H, Shape2(H * 3, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + T * N * D * H + 3 * H * T, Shape2(H * 3, T)); memset(tmp_dbx.dptr_, 0, H * T * 3 * sizeof(DType)); memset(tmp_dbh.dptr_, 0, H * T * 3 * sizeof(DType)); for (int t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (int j = 0; j < N; ++j) { tmp_dbx[i][t] += da[t * N * 3 * H + j * 3 * H + i]; tmp_dbh[i][t] += dar[t * N * 3 * H + j * 3 * H + i]; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { dbx[i] += tmp_dbx[i][t] + dbx[i]; dbh[i] += tmp_dbh[i][t] + dbh[i]; } } } } alpha = 1.0; beta = 0.0; // dx = da * wx [T * N, I] = [T * N, 3 * H] * [3 * H, I] Tensor<cpu, 2, DType> d_da(da, Shape2(T * N, 3 * H)); if (req_data != kNullOp) { Tensor<cpu, 2, DType> d_dx(dx, Shape2(T * N, I)); linalg_gemm(d_da, wx, d_dx, alpha, beta, false, false); } // dwx = da.T * x [3 * H, I] = [3 * H, T * N] * [T * N, I] if (req_params != kNullOp && req_params != kAddTo) { Tensor<cpu, 2, DType> d_dwx(dwx, Shape2(3 * H, I)); linalg_gemm(d_da, x, d_dwx, alpha, beta, true, false); } if (D == 2) { for (int t = 0; t < T; ++t) { if (t == T-1) { back_ht1 = hx_; } else { back_ht1 = y_ptr + (t + 1) * N * D * H; } // add dy[T, N, D, H] to dhy[D, N, H] dyt = dy_ptr + t * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { back_dht1[i * H + j] += dyt[i * D * H + H + j]; } } rt = back_gateR + t * N * H; zt = back_gateZ + t * N * H; nt = back_gateN + t * N * H; back_Mnht = Mnh + (T + t) * N * H; dat = da + t * N * 3 * H; dart = dar + t * N * 3 * H; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int nid = i * 3 * H + 2 * H + j; int zid = i * 3 * H + H + j; int rid = i * 3 * H + j; int id = i * H + j; dat[nid] = back_dht1[id] * (1 - zt[id]) * (1 - nt[id] * nt[id]); dart[zid] = dat[zid] = back_dht1[id] * (back_ht1[i * D * H + H + j] - nt[id]) * zt[id] * (1 - zt[id]); dart[rid] = dat[rid] = dat[nid] * back_Mnht[id] * rt[id] * (1 - rt[id]); dart[nid] = dat[nid] * rt[id]; back_dht1[id] = back_dht1[id] * zt[id]; } } if (req_params != kNullOp) { alpha = 1.0; beta = 1.0; // dht1 = da * wh [N, H] = [N, 3 * H] * [3 * H, H] Tensor<cpu, 2, DType> d_dart(dart, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> d_back_dht1(back_dht1, Shape2(N, H)); linalg_gemm(d_dart, back_wh, d_back_dht1, alpha, beta, false, false); // dwh = da.T * ht1 [3 * H, H] = [3 * H, N] * [N, H] Tensor<cpu, 2, DType> d_back_dwh(back_dwh, Shape2(3 * H, H)); Tensor<cpu, 2, DType> d_back_ht1(back_ht1 + H, Shape2(N, D * H)); Tensor<cpu, 3, DType> d_back_ht1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); d_back_ht1_tmp = reshape(d_back_ht1.T(), Shape3(D, H, N)); if (req_params == kAddTo) { beta = 2.0; // dwx = da.T * x [3 * H, I] = [3 * H, N] * [N, I] for AddTo Tensor<cpu, 2, DType> d_xt(x.dptr_ + t * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> d_dat(dat, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> d_back_dwx(back_dwx, Shape2(3 * H, I)); linalg_gemm(d_dat, d_xt, d_back_dwx, alpha, beta, true, false); } linalg_gemm(d_dart, d_back_ht1_tmp[0], d_back_dwh, alpha, beta, true, true); } } if (req_params != kNullOp) { // dbx = e * da [1, 3 * H] = [1, N] * [N, 3 * H] if (req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (int j = 0; j < N * T; ++j) { back_dbx[i] += da[j * 3 * H + i]; back_dbh[i] += dar[j * 3 * H + i]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf + T * N * D * H, Shape2(H * 3, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + T * N * D * H + 3 * H * T, Shape2(H * 3, T)); memset(tmp_dbx.dptr_, 0, H * T * 3 * sizeof(DType)); memset(tmp_dbh.dptr_, 0, H * T * 3 * sizeof(DType)); for (int t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (int j = 0; j < N; ++j) { tmp_dbx[i][t] += da[t * N * 3 * H + j * 3 * H + i]; tmp_dbh[i][t] += dar[t * N * 3 * H + j * 3 * H + i]; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { back_dbx[i] += tmp_dbx[i][t] + back_dbx[i]; back_dbh[i] += tmp_dbh[i][t] + back_dbh[i]; } } } } alpha = 1.0; beta = 1.0; // dxt = da * wx [T * N, I] = [T * N, 3 * H] * [3 * H, I] Tensor<cpu, 2, DType> d_da2(da, Shape2(T * N, 3 * H)); if (req_data != kNullOp) { Tensor<cpu, 2, DType> d_dx(dx, Shape2(T * N, I)); linalg_gemm(d_da2, back_wx, d_dx, alpha, beta, false, false); } alpha = 1.0; beta = 0.0; // dwx = da.T * x [3 * H, I] = [3 * H, T * N] * [T * N, I] if (req_params != kNullOp && req_params != kAddTo) { Tensor<cpu, 2, DType> d_back_dwx(back_dwx, Shape2(3 * H, I)); linalg_gemm(d_da2, x, d_back_dwx, alpha, beta, true, false); } } if (req_state != kNullOp) { memcpy(dhx, dht1, N * H * D * sizeof(DType)); } } template <typename DType> void GruBackward(DType* ws, DType* rs, const int L, const int D, const int T, const int N, int I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* dy_ptr, DType* dhy_ptr, DType* dx_ptr, DType* dhx_ptr, DType* dw_ptr, int req_data, int req_params, int req_state) { DType* wx = w_ptr; DType* dwx = dw_ptr; DType* dwh = dwx + I * H * 3; DType* dbx = dwh + H * H * 3 + (D - 1) * (H * H * 3 + I * H * 3) + (L - 1) * ((D + 1) * H) * H * 3 * D; DType* gateR_l = rs + (L - 1) * T * D * N * H; DType* gateZ_l = gateR_l + L * T * D * N * H; DType* gateN_l = gateZ_l + L * T * D * N * H; DType* y_l = gateN_l + L * T * D * N * H; DType* Mnh_l = y_l + L * T * N * H * D; DType* tmp_buf = Mnh_l + L * D * T * N * H; DType* dx_l = tmp_buf + T * N * D * H + 3 * H * T * 2; DType* ws2 = dx_l + T * N * D * H; DType* wx_l = (L == 1)? wx : wx + (L - 2) * D * (D + 1) * H * 3 * H + D * I * 3 * H + D * H * 3 * H; DType* wh_l = wx_l; if (L == 1) { wh_l = wh_l + I * H * 3; } else { wh_l = wh_l + (D * H) * H * 3; } DType* dhy_l = NULL; if (dhy_ptr) dhy_l = dhy_ptr + (L - 1) * D * N * H; DType* dwx_l = (L == 1)? dwx : dwx + (L - 2) * D * (D + 1) * H * 3 * H + D * I * 3 * H + D * H * 3 * H; DType* dwh_l = NULL; if (L == 1) { dwh_l = dwx_l + I * H * 3; } else { dwh_l = dwx_l + (D * H) * H * 3; } DType* dbx_l = dbx + (L - 1) * D * 3 * H * 2; DType* dbh_l = dbx_l + 3 * H; DType* dhx_l = dhx_ptr + (L - 1) * D * N * H; DType* dy_l = dy_ptr; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(L, D * N, H)); int inputsize = I; DType* y_tmp = y_l - T * N * H * D; for (int l = L - 1; l >= 0; --l) { if (l == 0) { I = inputsize; y_tmp = x_ptr; dx_l = dx_ptr; } else { I = D * H; } Tensor<cpu, 2, DType> hx_l = hx[l]; Tensor<cpu, 2, DType> x_l(y_tmp, Shape2(T * N, I)); GruBackwardSingleLayer<DType>(ws2, tmp_buf, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, y_l, dy_l, dhy_l, gateR_l, gateZ_l, gateN_l, Mnh_l, dx_l, dhx_l, dwx_l, dwh_l, dbx_l, dbh_l, req_data, req_params, req_state); if (l > 0) { memcpy(dy_l, dx_l, T * N * H * D * sizeof(DType)); gateR_l = gateR_l - T * D * N * H; gateZ_l = gateZ_l - T * D * N * H; gateN_l = gateN_l - T * D * N * H; Mnh_l = Mnh_l - T * D * N * H; dhx_l = dhx_l - D * N * H; if (dhy_l) dhy_l = dhy_l - D * N * H; y_l = y_l - T * N * H * D; y_tmp = y_l; if (l == 1) { wx_l = wx_l - (inputsize + H) * H * 3 * D; wh_l = wx_l + inputsize * 3 * H; dwx_l = dwx_l - (inputsize + H) * H * 3 * D; dwh_l = dwx_l + inputsize * 3 * H; } else { wx_l = wx_l - (I + H) * H * 3 * D; wh_l = wx_l + I * 3 * H; dwx_l = dwx_l - (I + H) * H * 3 * D; dwh_l = dwx_l + I * 3 * H; } dbx_l = dbx_l - D * 3 * H * 2; dbh_l = dbx_l + 3 * H; } } } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_RNN_IMPL_H_
DRB099-targetparallelfor2-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. */ #include <stdio.h> /* use of omp target + map + array sections derived from pointers */ void foo (double* a, double* b, int N) { int i; #pragma omp target map(to:a[0:N]) map(from:b[0:N]) #pragma omp parallel for for (i=0;i< N ;i++) b[i]=a[i]*(double)i; } int main(int argc, char* argv[]) { int i; int len = 1000; double a[len], b[len]; for (i=0; i<len; i++) { a[i]= ((double)i)/2.0; b[i]=0.0; } foo(a, b, len); printf("b[50]=%f\n",b[50]); return 0; }
MatrixProductOpenMP.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <omp.h> #include <time.h> const int MAX = 10; void run(int m, int size, char *name) { // Define my value int B[m][m], C[m * m]; int **A = (int**) malloc(sizeof(int*) * m); int *A_data = (int*) malloc(sizeof(int) * m * m); // Ensure matrix is contiguous memset(A_data, 0, m * m * sizeof(*A_data)); for (int i = 0; i < m; i++) { A[i] = &(A_data[m * i]); } srand((unsigned int)time(NULL)); // Generate A and B for(int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { A[i][j] = rand() % MAX + 1; B[i][j] = rand() % MAX + 1; } } /* printf("A = \n"); for(int i = 0; i<m; i++) { for (int j = 0; j < m; j++) { printf("\t%d", B[i][j]); } printf("\n"); } printf("B = \n"); for(int i = 0; i<m; i++) { for (int j = 0; j < m; j++) { printf("\t%d", B[i][j]); } printf("\n"); } */ // Zero out C for(int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { C[i * m + j] = 0; } } #pragma omp barrier double start = omp_get_wtime(); #pragma omp parallel num_threads(size) shared(A, B, C, m) #pragma omp for schedule(static) for(int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < m; k++) { C[i * m + j] = C[i * m + j] + (A[i][k] * B[k][j]); } } } #pragma omp barrier double end = omp_get_wtime(); printf("%s, %d, %d, %lf\n", name, size, m, end - start); /* printf("C = AB\n"); for(int i = 0; i< m; i++) { for (int j = 0; j < m; j++) { printf("\t%d", C[i * m + j]); } printf("\n"); } */ } int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage: %s MATRIX_SIZE NUM_PROCESSES NAME\n", argv[0]); exit(1); } int m = atoi(argv[1]); int size = atoi(argv[2]); char* name = argv[3]; int rank; if (size > m) { printf("No. of processes %d is greater than matrix size %d.\n",size, m); } else if (m % size) { printf("Matrix size %d is not a multiple of process count %d.\n", m, size); } else { run(m, size, name); } return 0; }
elgamal_test.c
#include <ristretto_elgamal.h> #include <omp.h> #include <time.h> #include <stdio.h> /* * This executable program loads the key and the map and performs some basic checks. */ int main() { ristretto255_scalar_t sk_1[59]; ristretto255_scalar_t sk_2[59]; ristretto255_point_t pk_1[59]; ristretto255_point_t pk_2[59]; ristretto255_point_t pk[59]; printf("\033[0;32m[INFO]\033[0m Loading the two key pairs and the merged public key...\n"); LoadPrivKey(sk_1, "./priv_1.key"); LoadPrivKey(sk_2, "./priv_2.key"); LoadPubKey(pk_1, "./pub_1.key"); LoadPubKey(pk_2, "./pub_2.key"); LoadPubKey(pk, "./pub.key"); printf("\033[0;32m[INFO]\033[0m The key pairs have been loaded.\n"); fastecexp_state st_pk1[60]; fastecexp_state st_pk2[60]; fastecexp_state st_pk[60]; char filename[59][150]; printf("\033[0;32m[INFO]\033[0m Loading the precomputation tables for PK1...\n"); #pragma omp parallel for for (int i = 0; i < 59; i++) { sprintf(filename[i], "/table/pub_1_%d.tab", i); TableLoad(&st_pk1[i], filename[i]); } printf("\033[0;32m[INFO]\033[0m PK1's precomputation tables have been loaded.\n"); TableLoad(&st_pk1[59], "/table/pub_1_59.tab"); printf("\033[0;32m[INFO]\033[0m Loading the precomputation tables for PK2...\n"); #pragma omp parallel for for (int i = 0; i < 59; i++) { sprintf(filename[i], "/table/pub_2_%d.tab", i); TableLoad(&st_pk2[i], filename[i]); } printf("\033[0;32m[INFO]\033[0m PK2's precomputation tables have been loaded.\n"); TableLoad(&st_pk2[59], "/table/pub_2_59.tab"); printf("\033[0;32m[INFO]\033[0m Loading the precomputation tables for PK...\n"); #pragma omp parallel for for (int i = 0; i < 59; i++) { sprintf(filename[i], "/table/pub_%d.tab", i); TableLoad(&st_pk[i], filename[i]); } printf("\033[0;32m[INFO]\033[0m PK's precomputation tables have been loaded.\n"); TableLoad(&st_pk[59], "/table/pub_59.tab"); int BLOCK = 36; ristretto255_point_t output[59 * BLOCK]; uint8_t input[1827 * BLOCK]; uint8_t recovered[1827 * BLOCK]; size_t actual_size; FILE *rand_src = fopen("/dev/urandom", "rb"); fread(input, 1827 * BLOCK - 1, 1, rand_src); fclose(rand_src); struct timespec t_start, t_end; printf("\033[0;32m[INFO]\033[0m Testing encoding + decoding, without encryption or decryption.\n"); ristretto_elgamal_encode(output, input, 1827 * BLOCK - 1, 1827 * BLOCK); // warmup clock_gettime(CLOCK_REALTIME, &t_start); for (int i = 0; i < 10; i++) ristretto_elgamal_encode(output, input, 1827 * BLOCK - 1, 1827 * BLOCK); clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Encoding time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); memset(recovered, 0, 1827 * BLOCK); clock_gettime(CLOCK_REALTIME, &t_start); for (int i = 0; i < 10; i++) ristretto_elgamal_decode(recovered, output, 59 * BLOCK, &actual_size, 1827 * BLOCK); clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Decoding time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); for (int i = 0; i < 1827 * BLOCK - 1; i++) { if (recovered[i] != input[i]) { printf("\033[0;31m[ERROR]\033[0m recovered[%d] = %d, should be %d, point of problem: %d\n", i, recovered[i], input[i], (i + 31) / 32); } } printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld\n", actual_size); printf("\033[0;32m[INFO]\033[0m Testing encoding + encryption + decryption + decoding, without rerandomization, focusing on key 1.\n"); ristretto255_point_t ct[60 * BLOCK]; ristretto255_point_t recovered_output[59 * BLOCK]; clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Encrypt(&ct[i * 60], &output[i * 59], st_pk1, rand_src); } } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Encryption time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); ristretto255_point_t ct_rand[60 * BLOCK]; clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Rerand_to_cache(&ct_rand[i * 60], st_pk1, rand_src); } } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Rerand, offline time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Rerand_use_cache(&ct[i * 60], &ct_rand[i * 60]); } } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Rerand, online time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Decrypt(&recovered_output[i * 59], &ct[i * 60], sk_1); } } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Decryption time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); memset(recovered, 0, 1827 * BLOCK); ristretto_elgamal_decode(recovered, recovered_output, 59 * BLOCK, &actual_size, 1827 * BLOCK); for (int i = 0; i < 1827 * BLOCK - 1; i++) { if (recovered[i] != input[i]) { printf("\033[0;31m[ERROR]\033[0m recovered[%d] = %d, should be %d, point of problem: %d.\n", i, recovered[i], input[i], (i + 31) / 32); break; } } printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld.\n", actual_size); printf("\033[0;32m[INFO]\033[0m Testing encoding + encryption +rerandomization + decryption + decoding, focusing on key 1.\n"); ristretto255_point_t ct_rerand[60 * BLOCK]; #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Encrypt(&ct[i * 60], &output[i * 59], st_pk1, rand_src); } clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Rerand(&ct_rerand[i * 60], &ct[i * 60], st_pk1, rand_src); } } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Rerandomization time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Decrypt(&recovered_output[i * 59], &ct_rerand[i * 60], sk_1); } memset(recovered, 0, 1827 * BLOCK); ristretto_elgamal_decode(recovered, recovered_output, 59 * BLOCK, &actual_size, 1827 * BLOCK); for (int i = 0; i < 1827 * BLOCK - 1; i++) { if (recovered[i] != input[i]) { printf("\033[0;31m[ERROR]\033[0m recovered[%d] = %d, should be %d, point of problem: %d.\n", i, recovered[i], input[i], (i + 31) / 32); } } printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld.\n", actual_size); printf("\033[0;32m[INFO]\033[0m Testing encoding + encryption +rerandomization + decryption + decoding, with distributed decryption.\n"); #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Encrypt(&ct[i * 60], &output[i * 59], st_pk, rand_src); } /* * serialize it! */ unsigned char *str = malloc(sizeof(char) * Serialize_Malicious_Size(60 * BLOCK)); clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { Serialize_Malicious(str, ct, 60 * BLOCK); } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Serialization -- malicious time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); /* * then recover it back. */ clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { Deserialize_Malicious(ct, str, 60 * BLOCK); } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Deserialization -- malicious time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Rerand(&ct_rerand[i * 60], &ct[i * 60], st_pk, rand_src); } /* * serialize it! */ unsigned char *str2 = malloc(sizeof(char) * Serialize_Honest_Size(60 * BLOCK)); clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { Serialize_Honest(str2, ct_rerand, 60 * BLOCK); } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Serialization -- honest time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); /* * then recover it back. */ clock_gettime(CLOCK_REALTIME, &t_start); for (int pp = 0; pp < 10; pp++) { Deserialize_Honest(ct_rerand, str2, 60 * BLOCK); } clock_gettime(CLOCK_REALTIME, &t_end); printf("\033[0;32m[INFO]\033[0m Deserialization -- honest time: %lf.\n", t_end.tv_sec - t_start.tv_sec + (t_end.tv_nsec - t_start.tv_nsec) / 1000000000.); #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Rerand(&ct[i * 60], &ct_rerand[i * 60], st_pk, rand_src); } #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { Decrypt(&recovered_output[i * 59], &ct[i * 60], sk_2); } ristretto255_point_t recovered_output2[59 * BLOCK]; ristretto255_point_t distributed_decryption_ct[BLOCK][1]; for (int i = 0; i < BLOCK; i++) { PartDec1(distributed_decryption_ct[i], &ct[i * 60]); } #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { PartDec2(&recovered_output2[i * 59], distributed_decryption_ct[i], sk_1); } #pragma omp parallel for for (int i = 0; i < BLOCK; i++) { PartDec3(&recovered_output2[i * 59], &recovered_output[i * 59]); } memset(recovered, 0, 1827 * BLOCK); ristretto_elgamal_decode(recovered, recovered_output2, 59 * BLOCK, &actual_size, 1827 * BLOCK); for (int i = 0; i < 1827 * BLOCK - 1; i++) { if (recovered[i] != input[i]) { printf("\033[0;32m[INFO]\033[0m recovered[%d] = %d, should be %d, point of problem: %d.\n", i, recovered[i], input[i], (i + 31) / 32); break; } } printf("\033[0;32m[INFO]\033[0m Recovered actual_size = %ld.\n", actual_size); fclose(rand_src); for (int i = 0; i < 59; i++) { TableRelease(&st_pk1[i]); TableRelease(&st_pk2[i]); TableRelease(&st_pk[i]); } free(str); free(str2); return 0; }
for-4.c
/* { dg-options "-std=gnu99 -fopenmp" } */ extern void abort (void); #define M(x, y, z) O(x, y, z) #define O(x, y, z) x ## _ ## y ## _ ## z #define F taskloop #define G taskloop #define S #define N(x) M(x, G, normal) #include "for-2.h" #undef S #undef N #undef F #undef G #define F taskloop simd #define G taskloop_simd #define S #define N(x) M(x, G, normal) #include "for-2.h" #undef S #undef N #undef F #undef G int main () { int err = 0; #pragma omp parallel reduction(|:err) #pragma omp single { if (test_taskloop_normal () || test_taskloop_simd_normal ()) err = 1; } if (err) abort (); return 0; }
miniblas.kernel_runtime.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include "local_header.h" #include "openmp_pscmc_inc.h" #include "miniblas.kernel_inc.h" int openmp_blas_sum_init (openmp_pscmc_env * pe ,openmp_blas_sum_struct * kerstr ){ return 0 ;} void openmp_blas_sum_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_sum_struct )); } int openmp_blas_sum_get_num_compute_units (openmp_blas_sum_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_sum_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_sum_exec (openmp_blas_sum_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_sum_scmc_kernel ( ( kerstr )->y , ( kerstr )->rdcd , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_sum_scmc_set_parameter_y (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_rdcd (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->rdcd = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_y_cpu_core (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_numvec (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_XLEN (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_YLEN (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_ZLEN (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_ovlp (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_xblock (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_yblock (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_zblock (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_sum_scmc_set_parameter_num_ele (openmp_blas_sum_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_dot_init (openmp_pscmc_env * pe ,openmp_blas_dot_struct * kerstr ){ return 0 ;} void openmp_blas_dot_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_dot_struct )); } int openmp_blas_dot_get_num_compute_units (openmp_blas_dot_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_dot_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_dot_exec (openmp_blas_dot_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_dot_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( kerstr )->rdcd , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_dot_scmc_set_parameter_y (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_x (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_rdcd (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->rdcd = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_y_cpu_core (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_numvec (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_XLEN (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_YLEN (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_ZLEN (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_ovlp (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_xblock (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_yblock (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_zblock (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_dot_scmc_set_parameter_num_ele (openmp_blas_dot_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_findmax_init (openmp_pscmc_env * pe ,openmp_blas_findmax_struct * kerstr ){ return 0 ;} void openmp_blas_findmax_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_findmax_struct )); } int openmp_blas_findmax_get_num_compute_units (openmp_blas_findmax_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_findmax_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_findmax_exec (openmp_blas_findmax_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_findmax_scmc_kernel ( ( kerstr )->y , ( kerstr )->rdcd , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_findmax_scmc_set_parameter_y (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_rdcd (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->rdcd = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_y_cpu_core (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_numvec (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_XLEN (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_YLEN (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_ZLEN (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_ovlp (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_xblock (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_yblock (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_zblock (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_findmax_scmc_set_parameter_num_ele (openmp_blas_findmax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_mulxy_init (openmp_pscmc_env * pe ,openmp_blas_mulxy_struct * kerstr ){ return 0 ;} void openmp_blas_mulxy_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_mulxy_struct )); } int openmp_blas_mulxy_get_num_compute_units (openmp_blas_mulxy_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_mulxy_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_mulxy_exec (openmp_blas_mulxy_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_mulxy_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_mulxy_scmc_set_parameter_y (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_x (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_y_cpu_core (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_numvec (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_XLEN (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_YLEN (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_ZLEN (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_ovlp (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_xblock (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_yblock (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_zblock (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_mulxy_scmc_set_parameter_num_ele (openmp_blas_mulxy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_axpby_init (openmp_pscmc_env * pe ,openmp_blas_axpby_struct * kerstr ){ return 0 ;} void openmp_blas_axpby_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_axpby_struct )); } int openmp_blas_axpby_get_num_compute_units (openmp_blas_axpby_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_axpby_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_axpby_exec (openmp_blas_axpby_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_axpby_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( ( kerstr )->a)[0] , ( ( kerstr )->b)[0] , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_axpby_scmc_set_parameter_y (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_x (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_a (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->a = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_b (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->b = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_y_cpu_core (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_numvec (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_XLEN (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_YLEN (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_ZLEN (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_ovlp (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_xblock (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_yblock (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_zblock (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_axpby_scmc_set_parameter_num_ele (openmp_blas_axpby_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_axpy_init (openmp_pscmc_env * pe ,openmp_blas_axpy_struct * kerstr ){ return 0 ;} void openmp_blas_axpy_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_axpy_struct )); } int openmp_blas_axpy_get_num_compute_units (openmp_blas_axpy_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_axpy_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_axpy_exec (openmp_blas_axpy_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_axpy_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( ( kerstr )->a)[0] , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_axpy_scmc_set_parameter_y (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_x (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_a (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->a = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_y_cpu_core (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_numvec (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_XLEN (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_YLEN (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_ZLEN (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_ovlp (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_xblock (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_yblock (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_zblock (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_axpy_scmc_set_parameter_num_ele (openmp_blas_axpy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_yisax_init (openmp_pscmc_env * pe ,openmp_blas_yisax_struct * kerstr ){ return 0 ;} void openmp_blas_yisax_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_yisax_struct )); } int openmp_blas_yisax_get_num_compute_units (openmp_blas_yisax_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_yisax_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_yisax_exec (openmp_blas_yisax_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_yisax_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( ( kerstr )->a)[0] , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_yisax_scmc_set_parameter_y (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_x (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_a (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->a = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_y_cpu_core (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_numvec (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_XLEN (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_YLEN (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_ZLEN (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_ovlp (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_xblock (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_yblock (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_zblock (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_yisax_scmc_set_parameter_num_ele (openmp_blas_yisax_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_invy_init (openmp_pscmc_env * pe ,openmp_blas_invy_struct * kerstr ){ return 0 ;} void openmp_blas_invy_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_invy_struct )); } int openmp_blas_invy_get_num_compute_units (openmp_blas_invy_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_invy_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_invy_exec (openmp_blas_invy_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_invy_scmc_kernel ( ( kerstr )->y , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_invy_scmc_set_parameter_y (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_y_cpu_core (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_numvec (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_XLEN (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_YLEN (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_ZLEN (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_ovlp (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_xblock (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_yblock (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_zblock (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_invy_scmc_set_parameter_num_ele (openmp_blas_invy_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_get_ITG_Potential_init (openmp_pscmc_env * pe ,openmp_blas_get_ITG_Potential_struct * kerstr ){ return 0 ;} void openmp_blas_get_ITG_Potential_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_get_ITG_Potential_struct )); } int openmp_blas_get_ITG_Potential_get_num_compute_units (openmp_blas_get_ITG_Potential_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_get_ITG_Potential_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_get_ITG_Potential_exec (openmp_blas_get_ITG_Potential_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_get_ITG_Potential_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( kerstr )->u , ( ( kerstr )->minus_over_q_e)[0] , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_get_ITG_Potential_scmc_set_parameter_y (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_x (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_u (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->u = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_minus_over_q_e (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->minus_over_q_e = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_y_cpu_core (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_numvec (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_XLEN (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_YLEN (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_ZLEN (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_ovlp (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_xblock (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_yblock (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_zblock (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_get_ITG_Potential_scmc_set_parameter_num_ele (openmp_blas_get_ITG_Potential_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_yisconst_init (openmp_pscmc_env * pe ,openmp_blas_yisconst_struct * kerstr ){ return 0 ;} void openmp_blas_yisconst_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_yisconst_struct )); } int openmp_blas_yisconst_get_num_compute_units (openmp_blas_yisconst_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_yisconst_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_yisconst_exec (openmp_blas_yisconst_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_yisconst_scmc_kernel ( ( kerstr )->y , ( ( kerstr )->a)[0] , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_yisconst_scmc_set_parameter_y (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_a (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->a = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_y_cpu_core (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_numvec (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_XLEN (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_YLEN (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_ZLEN (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_ovlp (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_xblock (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_yblock (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_zblock (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_yisconst_scmc_set_parameter_num_ele (openmp_blas_yisconst_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_yiszero_init (openmp_pscmc_env * pe ,openmp_blas_yiszero_struct * kerstr ){ return 0 ;} void openmp_blas_yiszero_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_yiszero_struct )); } int openmp_blas_yiszero_get_num_compute_units (openmp_blas_yiszero_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_yiszero_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_yiszero_exec (openmp_blas_yiszero_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_yiszero_scmc_kernel ( ( kerstr )->y , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_yiszero_scmc_set_parameter_y (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_y_cpu_core (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_numvec (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_XLEN (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_YLEN (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_ZLEN (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_ovlp (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_xblock (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_yblock (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_zblock (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_yiszero_scmc_set_parameter_num_ele (openmp_blas_yiszero_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_mulxy_numele3_init (openmp_pscmc_env * pe ,openmp_blas_mulxy_numele3_struct * kerstr ){ return 0 ;} void openmp_blas_mulxy_numele3_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_mulxy_numele3_struct )); } int openmp_blas_mulxy_numele3_get_num_compute_units (openmp_blas_mulxy_numele3_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_mulxy_numele3_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_mulxy_numele3_exec (openmp_blas_mulxy_numele3_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_mulxy_numele3_scmc_kernel ( ( kerstr )->y , ( kerstr )->x , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_mulxy_numele3_scmc_set_parameter_y (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_x (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->x = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_y_cpu_core (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_numvec (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_XLEN (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_YLEN (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_ZLEN (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_ovlp (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_xblock (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_yblock (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_zblock (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_mulxy_numele3_scmc_set_parameter_num_ele (openmp_blas_mulxy_numele3_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_blas_yiszero_synced_init (openmp_pscmc_env * pe ,openmp_blas_yiszero_synced_struct * kerstr ){ return 0 ;} void openmp_blas_yiszero_synced_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_blas_yiszero_synced_struct )); } int openmp_blas_yiszero_synced_get_num_compute_units (openmp_blas_yiszero_synced_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_blas_yiszero_synced_get_xlen (){ return IDX_OPT_MAX ;} int openmp_blas_yiszero_synced_exec (openmp_blas_yiszero_synced_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_blas_yiszero_synced_scmc_kernel ( ( kerstr )->y , ( ( kerstr )->y_cpu_core)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->xblock)[0] , ( ( kerstr )->yblock)[0] , ( ( kerstr )->zblock)[0] , ( ( kerstr )->num_ele)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_blas_yiszero_synced_scmc_set_parameter_y (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_y_cpu_core (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->y_cpu_core = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_numvec (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_XLEN (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_YLEN (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_ZLEN (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_ovlp (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_xblock (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xblock = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_yblock (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yblock = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_zblock (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zblock = pm->d_data); } int openmp_blas_yiszero_synced_scmc_set_parameter_num_ele (openmp_blas_yiszero_synced_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); }
BlockCorr.c
#include <math.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include "list.h" #include "BlockCorr.h" // compute pearson correlation coefficient between time series at positions i1 and i2 in d (of length l) // NOTE: result may be nan, if the variance of any of the time series is zero, or if // any of the time series contains nans double pearson2(const double *d, const long int i, const long int j, const long int l) { long int k; double sum_i = 0.0, sum_j = 0.0, sum_ii = 0.0, sum_jj = 0.0, sum_ij = 0.0; #pragma omp simd for (k = 0; k < l; k++) { sum_i += d[i*l+k]; sum_j += d[j*l+k]; sum_ii += d[i*l+k]*d[i*l+k]; sum_jj += d[j*l+k]*d[j*l+k]; sum_ij += d[i*l+k]*d[j*l+k]; } return (l*sum_ij-sum_i*sum_j)/sqrt((l*sum_ii-sum_i*sum_i)*(l*sum_jj-sum_j*sum_j)); } // compute n-by-n correlation matrix for complete data set d with n rows and l columns double *pearson(const double *d, long int n, long int l) { double *sums = (double *) calloc(n, sizeof (double)); double *sumsqs = (double *) calloc(n, sizeof (double)); double *sqsums = (double *) calloc(n, sizeof (double)); double *coef = (double *) calloc(n*n, sizeof (double)); if (!coef || !sums || !sumsqs || !sqsums) return NULL; #pragma omp parallel for for (long int i = 0; i < n; i++) { #pragma omp simd for (long k = 0; k < l; k++) { sums[i] += d[i*l+k]; sumsqs[i] += d[i*l+k]*d[i*l+k]; } } #pragma omp simd for (long int i = 0; i < n; i++) { sqsums[i] = sums[i]*sums[i]; } #pragma omp parallel for for (long int ij = 0; ij < n*(n-1)/2; ij++) { double sum_ij = 0.0; long int i = ij / n; long int j = ij % n; if (j <= i) { i = n - i - 2; j = n - j - 1; } #pragma omp simd for (long int k = 0; k < l; k++) { sum_ij += d[i*l+k]*d[j*l+k]; } coef[i*n+j] = (l*sum_ij-sums[i]*sums[j])/sqrt((l*sumsqs[i]-sqsums[i])*(l*sumsqs[j]-sqsums[j])); coef[j*n+i] = coef[i*n+j]; } #pragma omp simd for (long int i = 0; i < n; i++) { coef[i*n+i] = 1.0; } free(sums); free(sumsqs); free(sqsums); return coef; } // compute upper triangular part of the correlation matrix // and store as a vector of length n*(n+1)/2 double * pearson_triu(const double *d, long int n, long int l) { long int i, j, k; double *sums = (double *) calloc(n, sizeof (double)); double *sumsqs = (double *) calloc(n, sizeof (double)); double *coef = (double *) calloc(n*(n+1)/2, sizeof (double)); double sum_ij; if (!coef) return NULL; #pragma omp parallel for for (i = 0; i < n; i++) { #pragma omp simd for (k = 0; k < l; k++) { sums[i] += d[i*l+k]; sumsqs[i] += d[i*l+k]*d[i*l+k]; } } #pragma omp parallel for collapse(2) private (sum_ij) schedule(dynamic) for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (i > j) continue; sum_ij = 0.0; #pragma omp simd for (k = 0; k < l; k++) { sum_ij += d[i*l+k]*d[j*l+k]; } coef[i*n-i*(i+1)/2+j] = (l*sum_ij-sums[i]*sums[j])/sqrt((l*sumsqs[i]-sums[i]*sums[i])*(l*sumsqs[j]-sums[j]*sums[j])); } } free(sums); free(sumsqs); return coef; } // find equivalence classes in a time series data set // // d: data set with n rows (time series) and l columns (time steps) // alpha: transitivity threshold // kappa: minimum cluster size // max_nan: maximum number of nans within a pivot time series long int *cluster(const double *d, long int n, long int l, double alpha, long int kappa, long int max_nan) { long int corr_count, pivot, i, nan_count; long int *membs; double rho; llist_li timeseries_l; llist_li *clustermemb_pos_l; llist_li *clustermemb_neg_l; llist_li *noise_l; llist_ptr cluster_l; llist_item_li *iter_li, *iter_li_next; llist_item_ptr *iter_ptr; membs = (long int *) calloc(n, sizeof (long int)); if (!membs) { return NULL; } // initialize time series index list llist_li_init(&timeseries_l); for (i = 0; i < n; i++) { llist_li_push_back(&timeseries_l, i); } // initialize cluster list llist_ptr_init(&cluster_l); // initialize noise cluster and add to cluster list (always at position 1) noise_l = (llist_li *) malloc(sizeof(llist_li)); if (!noise_l) return NULL; llist_li_init(noise_l); llist_ptr_push_back(&cluster_l, noise_l); // iterate over all time series until none is left corr_count = 0; while (llist_li_size(&timeseries_l) > 0) { printf("\r% 9ld left...", llist_li_size(&timeseries_l)); pivot = llist_li_front(&timeseries_l); // check if pivot contains too many nans to be considered a pivot nan_count = 0; for (i = 0; i < l; i++) if (isnan(d[pivot*l+i])) nan_count++; if (nan_count > max_nan) { // add pivot to noise cluster llist_li_relink(timeseries_l.last, &timeseries_l, noise_l); continue; } // initialize positive and negative clusters clustermemb_pos_l = (llist_li *) malloc(sizeof(llist_li)); if (!clustermemb_pos_l) return NULL; llist_li_init(clustermemb_pos_l); clustermemb_neg_l = (llist_li *) malloc(sizeof(llist_li)); if (!clustermemb_neg_l) return NULL; llist_li_init(clustermemb_neg_l); // compute all correlations between pivot and remaining time series // and create positive and negative protoclusters iter_li = timeseries_l.first; while (iter_li != NULL) { iter_li_next = iter_li->next; // store successor before relinking rho = pearson2(d, pivot, iter_li->data, l); corr_count++; if (isnan(rho)) { // NOTE: we add the tested time series to the noise cluster, this might not be // a good idea if nan value occurs because there are no overlapping valid time steps // in pivot and tested time series llist_li_relink(iter_li, &timeseries_l, noise_l); } else { if (rho >= alpha) llist_li_relink(iter_li, &timeseries_l, clustermemb_pos_l); if (rho <= -alpha) llist_li_relink(iter_li, &timeseries_l, clustermemb_neg_l); } iter_li = iter_li_next; } // check whether protoclusters fulfill the minimium size constraints if (llist_li_size(clustermemb_pos_l) >= kappa) { // add to final clustering llist_ptr_push_back(&cluster_l, clustermemb_pos_l); } else { // relink all time series to noise cluster llist_li_relink_all(clustermemb_pos_l, noise_l); free(clustermemb_pos_l); } if (llist_li_size(clustermemb_neg_l) >= kappa) { // add to final clustering llist_ptr_push_back(&cluster_l, clustermemb_neg_l); } else { // relink all time series to noise cluster llist_li_relink_all(clustermemb_neg_l, noise_l); free(clustermemb_neg_l); } } printf("\rclustering finished with %ld correlation computations.\n", corr_count); // prepare output array with cluster assignments // skip noise cluster (membs id=0 during initialization) i = 1; iter_ptr = cluster_l.first->next; while (iter_ptr != NULL) { iter_li = ((llist_li *) iter_ptr->data)->first; while (iter_li != NULL) { membs[iter_li->data] = i; iter_li = iter_li->next; } llist_li_destroy((llist_li *) iter_ptr->data); free(iter_ptr->data); iter_ptr = iter_ptr->next; i++; } llist_ptr_destroy(&cluster_l); llist_li_destroy(&timeseries_l); return membs; } // assumes that the key really is somewhere in the array long int binary_search_li(long int key, long int *arr, long int len) { long int liml, limr, rpos; liml = 0; limr = len-1; do { rpos = (liml+limr)/2; if (arr[rpos] < key) { liml = rpos + 1; } else if (arr[rpos] > key) { limr = rpos - 1; } else { break; // found it } } while (liml <= limr); return rpos; } // COREQ // find equivalence classes in a time series data set and estimate correlations // NOTE: no kappa, no noise cluster estimation, no negative clusters, no NaN handling // // INPUT // d: data set with n rows (time series) and l columns (time steps) // n, l: see above // alpha: transitivity threshold // est_strat: estimation strategy (pivot-based, average-based) // // OUTPUT // membs: uninitialized pointer to array for class memberships // pivots: uninitialized pointer to array for pivot indices // cluster_corrs: uninitialized pointer to array for class correlations (upper triangular indexing) // n_clus: total number of resulting clusters // corr_comps: total number of correlation computations required for clustering/estimation long int * coreq(const double *d, long int n, long int l, double alpha, coreq_estimation_strategy_t est_strat, long int **membs, long int **pivots, double **cluster_corrs, long int *n_clus, long int *corr_comps) { long int pivot, remaining, i, j, k, rpos, sample_size; double rho, sum_ij; llist_li timeseries_l; // holds all unprocessed time series llist_li pivot_l; // holds all pivot objects selected so far llist_li *clustermemb_l; // holds all time series assigned to a cluster llist_ptr cluster_l; // holds all clusters llist_ptr correlations_idx_l; // holds corrs between all pivots and time series (indices) llist_ptr correlations_val_l; // holds corrs between all pivots and time series (correlations) llist_li correlations_cnt_l; // holds the number of entries in the previous lists llist_item_li *iter_li, *iter_li_next; llist_item_ptr *iter_ptr, *iter_idx, *iter_val; long int **cluster_arr; // hold all clusters with their members long int *cluster_size_arr; // hold all cluster sizes // precompute some data statistics for fast correlation computation double *sums = (double *) calloc(n, sizeof (double)); double *sumsqs = (double *) calloc(n, sizeof (double)); if ((!sums) || (!sumsqs)) return NULL; #pragma omp parallel for for (i = 0; i < n; i++) { #pragma omp simd for (k = 0; k < l; k++) { sums[i] += d[i*l+k]; sumsqs[i] += d[i*l+k]*d[i*l+k]; } } *membs = (long int *) calloc(n, sizeof(long int)); if (!*membs) return NULL; // initialize time series index list llist_li_init(&timeseries_l); for (i = 0; i < n; i++) { llist_li_push_back(&timeseries_l, i); } // initialize lists llist_ptr_init(&cluster_l); llist_ptr_init(&correlations_idx_l); llist_ptr_init(&correlations_val_l); llist_li_init(&correlations_cnt_l); llist_li_init(&pivot_l); // iterate over all time series until none is left *corr_comps = 0; while (llist_li_size(&timeseries_l) > 0) { remaining = llist_li_size(&timeseries_l); printf("\r% 9ld left...", remaining); // select pivot time series and create its correlation container pivot = llist_li_front(&timeseries_l); llist_li_push_back(&pivot_l, pivot); llist_ptr_push_back(&correlations_idx_l, (long int *) calloc(remaining, sizeof (long int))); llist_ptr_push_back(&correlations_val_l, (double *) calloc(remaining, sizeof (double))); llist_li_push_back(&correlations_cnt_l, remaining); // initialize cluster container clustermemb_l = (llist_li *) malloc(sizeof (llist_li)); if (!clustermemb_l) return NULL; llist_li_init(clustermemb_l); // compute all correlations between pivot and remaining time series iter_li = timeseries_l.first; i = 0; while (iter_li != NULL) { iter_li_next = iter_li->next; // store successor before relinking // compute correlation sum_ij = 0.0; #pragma omp simd for (k = 0; k < l; k++) { sum_ij += d[pivot*l+k]*d[(iter_li->data)*l+k]; } rho = (l*sum_ij-sums[pivot]*sums[iter_li->data])/sqrt((l*sumsqs[pivot]-sums[pivot]*sums[pivot]) *(l*sumsqs[iter_li->data]-sums[iter_li->data]*sums[iter_li->data])); (*corr_comps)++; ((long int *) llist_ptr_back(&correlations_idx_l))[i] = iter_li->data; ((double *) llist_ptr_back(&correlations_val_l))[i] = rho; // add time series to cluster if (rho >= alpha) { llist_li_relink(iter_li, &timeseries_l, clustermemb_l); } iter_li = iter_li_next; i++; } // add to final clustering llist_ptr_push_back(&cluster_l, clustermemb_l); } *n_clus = llist_li_size(&pivot_l); printf("\rclustering finished with %ld correlation computations --- %ld clusters detected\n", *corr_comps, *n_clus); // prepare output array with cluster assignments // and buffer all clusters in cluster_arr for O(1) access to members cluster_arr = (long int **) calloc(*n_clus, sizeof (long int *)); cluster_size_arr = (long int *) calloc(*n_clus, sizeof (long int)); i = 0; iter_ptr = cluster_l.first; while (iter_ptr != NULL) { cluster_arr[i] = (long int *) calloc(llist_li_size((llist_li *) iter_ptr->data), sizeof (long int)); cluster_size_arr[i] = llist_li_size((llist_li *) iter_ptr->data); j = 0; iter_li = ((llist_li *) iter_ptr->data)->first; while (iter_li != NULL) { cluster_arr[i][j] = iter_li->data; (*membs)[iter_li->data] = i; iter_li = iter_li->next; j++; } llist_li_destroy((llist_li *) iter_ptr->data); free(iter_ptr->data); iter_ptr = iter_ptr->next; i++; } // prepare output array with pivots *pivots = (long int *) calloc(*n_clus, sizeof (long int)); i = 0; iter_li = pivot_l.first; while (iter_li != NULL) { (*pivots)[i] = iter_li->data; iter_li = iter_li->next; i++; } // prepare output array with correlation estimates in O(K*(K+1)/2 * log2(N) * log2(N)) // NOTE: we use binary search to look up the precomputed pivot-time series correlations; // no additional correlation computations are necessary, which would require O(K*(K+1)/2 * T * log2(N)) *cluster_corrs = (double *) calloc((*n_clus)*(*n_clus+1)/2, sizeof (double)); iter_idx = correlations_idx_l.first; iter_val = correlations_val_l.first; iter_li = correlations_cnt_l.first; for (i = 0; i < (*n_clus); i++) { // loop over all pairs of pivots for (j = i; j < (*n_clus); j++) { switch (est_strat) { case COREQ_PIVOT: // search for pivot j in the correlation index list of pivot i rpos = binary_search_li((*pivots)[j], ((long int *) iter_idx->data), iter_li->data); // retrieve pivot i-j correlation from position correlation value list at position rpos (*cluster_corrs)[i*(*n_clus)-i*(i+1)/2+j] = ((double *) iter_val->data)[rpos]; break; case COREQ_PIVOT_GUARANTEE: // same as above, but with scaling alpha-dependent scaling factor rpos = binary_search_li((*pivots)[j], ((long int *) iter_idx->data), iter_li->data); (*cluster_corrs)[i*(*n_clus)-i*(i+1)/2+j] = 0.5*(1.0+alpha*alpha) * ((double *) iter_val->data)[rpos]; break; case COREQ_AVERAGE: default: // sample log2(N_k) precomputed correlations and use average as estimate sample_size = fmax(1,ceil(log2(cluster_size_arr[j]))); (*cluster_corrs)[i*(*n_clus)-i*(i+1)/2+j] = 0; for (k = 0; k < sample_size; k++) { // sample random member of cluster j long int sample = rand() % cluster_size_arr[j]; rpos = binary_search_li(cluster_arr[j][sample], ((long int *) iter_idx->data), iter_li->data); (*cluster_corrs)[i*(*n_clus)-i*(i+1)/2+j] += ((double *) iter_val->data)[rpos]; } (*cluster_corrs)[i*(*n_clus)-i*(i+1)/2+j] /= sample_size; } } iter_idx = iter_idx->next; iter_val = iter_val->next; iter_li = iter_li->next; } // destroy correlation containers iter_ptr = correlations_idx_l.first; while (iter_ptr != NULL) { free(iter_ptr->data); iter_ptr = iter_ptr->next; } iter_ptr = correlations_val_l.first; while (iter_ptr != NULL) { free(iter_ptr->data); iter_ptr = iter_ptr->next; } // destroy cluster buffer array for (i = 0; i < *n_clus; i++) { free(cluster_arr[i]); } free(cluster_arr); free(cluster_size_arr); llist_ptr_destroy(&cluster_l); llist_ptr_destroy(&correlations_idx_l); llist_ptr_destroy(&correlations_val_l); llist_li_destroy(&correlations_cnt_l); llist_li_destroy(&timeseries_l); llist_li_destroy(&pivot_l); free(sums); free(sumsqs); return *membs; } // compute aggregated losses for evaluation: // absolute deviation, squared deviation, maximum deviation // // d: data set with n rows and l columns (may be NULL if corr_triu specified) // corr_triu: precomputed true correlations in triu array (may be NULL if d specified) // corr_clus_triu: precomputed cluster correlations in triu array // membs: cluster membership vector of length n // n: number of time series (rows in d) // l: number of time steps (columns in d) // k: number of clusters int compute_loss(const double *d, const double *corr_triu, const double *corr_clus_triu, const long int *membs, long int n, long int l, long int k, double *loss_abs, double *loss_sq, double *loss_max, long int *elements) { long int i, j, ii, jj; double corr_est, corr_tru; double loss_abs0 = 0., loss_sq0 = 0., loss_max0 = 0.; long int elements0 = 0; int abort = 0; if ((d == NULL) && (corr_triu == NULL)) { return -1; } #pragma omp parallel for private(i, j, corr_tru, corr_est, ii, jj) \ reduction(+:loss_abs0,loss_sq0,elements0) \ reduction(max:loss_max0) \ schedule(dynamic) for (i = 0; i < n; i++) { if ((membs[i] < 0) || (membs[i] >= k)) { // Invalid cluster index (must have range 0, ..., k-1). Noise cluster 0 missing? abort = 1; #pragma omp flush (abort) } for (j = i; j < n; j++) { // for error handling #pragma omp flush (abort) if (abort) continue; if ((membs[j] < 0) || (membs[j] >= k)) { // Invalid cluster index (must have range 0, ..., k-1). Noise cluster 0 missing? abort = 1; #pragma omp flush (abort) } if (corr_triu != NULL) { // use precomputed correlation corr_tru = corr_triu[i*n-(i*(i+1))/2+j]; // triu indexing (with diagonal) } else { corr_tru = pearson2(d, i, j, l); } ii = fminl(membs[i], membs[j]); // triu index formula below for ii<jj jj = fmaxl(membs[i], membs[j]); corr_est = corr_clus_triu[ii*k-ii*(ii+1)/2+jj]; // triu indexing (with diagonal) if (!(isnan(corr_tru) || isnan(corr_est))) { elements0 += 1; loss_abs0 += fabs(corr_tru-corr_est); loss_sq0 += (corr_tru-corr_est)*(corr_tru-corr_est); if (loss_max0 < fabs(corr_tru-corr_est)) { loss_max0 = fabs(corr_tru-corr_est); } } } } if (abort) { return -2; } *loss_abs = loss_abs0; *loss_sq = loss_sq0; *loss_max = loss_max0; *elements = elements0; return 0; }
GB_binop__minus_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__minus_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__minus_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__minus_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__minus_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint16) // A*D function (colscale): GB (_AxD__minus_uint16) // D*A function (rowscale): GB (_DxB__minus_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__minus_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__minus_uint16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint16) // C=scalar+B GB (_bind1st__minus_uint16) // C=scalar+B' GB (_bind1st_tran__minus_uint16) // C=A+scalar GB (_bind2nd__minus_uint16) // C=A'+scalar GB (_bind2nd_tran__minus_uint16) // C type: uint16_t // 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 \ 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) \ 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) \ 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 = (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_MINUS || GxB_NO_UINT16 || GxB_NO_MINUS_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__minus_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__minus_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__minus_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__minus_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__minus_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 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__minus_uint16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__minus_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__minus_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__minus_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__minus_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__minus_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__minus_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 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] = (x - bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__minus_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 ; 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 ; 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__minus_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__minus_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
declare_mapper_messages.c
// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s // RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 %s int temp; // expected-note {{'temp' declared here}} struct vec { // expected-note {{definition of 'struct vec' is not complete until the closing '}'}} int len; #pragma omp declare mapper(id: struct vec v) map(v.len) // expected-error {{incomplete definition of type 'struct vec'}} double *data; }; #pragma omp declare mapper // expected-error {{expected '(' after 'declare mapper'}} #pragma omp declare mapper { // expected-error {{expected '(' after 'declare mapper'}} #pragma omp declare mapper( // expected-error {{expected a type}} expected-error {{expected declarator on 'omp declare mapper' directive}} #pragma omp declare mapper(# // expected-error {{expected a type}} expected-error {{expected declarator on 'omp declare mapper' directive}} #pragma omp declare mapper(struct v // expected-error {{expected declarator on 'omp declare mapper' directive}} #pragma omp declare mapper(struct vec // expected-error {{expected declarator on 'omp declare mapper' directive}} #pragma omp declare mapper(S v // expected-error {{unknown type name 'S'}} #pragma omp declare mapper(struct vec v // expected-error {{expected ')'}} expected-note {{to match this '('}} #pragma omp declare mapper(aa:struct vec v) // expected-error {{expected at least one clause on '#pragma omp declare mapper' directive}} #pragma omp declare mapper(bb:struct vec v) private(v) // expected-error {{expected at least one clause on '#pragma omp declare mapper' directive}} // expected-error {{unexpected OpenMP clause 'private' in directive '#pragma omp declare mapper'}} #pragma omp declare mapper(cc:struct vec v) map(v) ( // expected-warning {{extra tokens at the end of '#pragma omp declare mapper' are ignored}} #pragma omp declare mapper(++: struct vec v) map(v.len) // expected-error {{illegal OpenMP user-defined mapper identifier}} #pragma omp declare mapper(id1: struct vec v) map(v.len, temp) // expected-error {{only variable v is allowed in map clauses of this 'omp declare mapper' directive}} #pragma omp declare mapper(default : struct vec kk) map(kk.data[0:2]) // expected-note {{previous definition is here}} #pragma omp declare mapper(struct vec v) map(v.len) // expected-error {{redefinition of user-defined mapper for type 'struct vec' with name 'default'}} #pragma omp declare mapper(int v) map(v) // expected-error {{mapper type must be of struct, union or class type}} int fun(int arg) { #pragma omp declare mapper(id: struct vec v) map(v.len) { #pragma omp declare mapper(id: struct vec v) map(v.len) // expected-note {{previous definition is here}} #pragma omp declare mapper(id: struct vec v) map(v.len) // expected-error {{redefinition of user-defined mapper for type 'struct vec' with name 'id'}} { #pragma omp declare mapper(id: struct vec v) map(v.len) allocate(v) // expected-error {{unexpected OpenMP clause 'allocate' in directive '#pragma omp declare mapper'}} struct vec vv, v1; #pragma omp target map(mapper) // expected-error {{use of undeclared identifier 'mapper'}} {} #pragma omp target map(mapper:vv) // expected-error {{expected '(' after 'mapper'}} {} #pragma omp target map(mapper( :vv) // expected-error {{expected expression}} expected-error {{expected ')'}} expected-warning {{implicit declaration of function 'mapper' is invalid in C99}} expected-note {{to match this '('}} {} #pragma omp target map(mapper(aa :vv) // expected-error {{use of undeclared identifier 'aa'}} expected-error {{expected ')'}} expected-warning {{implicit declaration of function 'mapper' is invalid in C99}} expected-note {{to match this '('}} {} #pragma omp target map(mapper(ab) :vv) // expected-error {{missing map type}} expected-error {{cannot find a valid user-defined mapper for type 'struct vec' with name 'ab'}} {} #pragma omp target map(mapper(aa) :vv) // expected-error {{missing map type}} {} #pragma omp target map(mapper(aa) to:vv) map(close mapper(aa) from:v1) {} #pragma omp target update to(mapper) // expected-error {{expected '(' after 'mapper'}} expected-error {{expected expression}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update to(mapper() // expected-error {{illegal OpenMP user-defined mapper identifier}} expected-error {{expected expression}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update to(mapper:vv) // expected-error {{expected '(' after 'mapper'}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update to(mapper(:vv) // expected-error {{illegal OpenMP user-defined mapper identifier}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update to(mapper(aa :vv) // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update to(mapper(ab):vv) // expected-error {{cannot find a valid user-defined mapper for type 'struct vec' with name 'ab'}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update to(mapper(aa):vv) #pragma omp target update from(mapper) // expected-error {{expected '(' after 'mapper'}} expected-error {{expected expression}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update from(mapper() // expected-error {{illegal OpenMP user-defined mapper identifier}} expected-error {{expected expression}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update from(mapper:vv) // expected-error {{expected '(' after 'mapper'}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update from(mapper(:vv) // expected-error {{illegal OpenMP user-defined mapper identifier}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update from(mapper(aa :vv) // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update from(mapper(ab):vv) // expected-error {{cannot find a valid user-defined mapper for type 'struct vec' with name 'ab'}} expected-error {{expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'}} #pragma omp target update from(mapper(aa) a:vv) // expected-warning {{missing ':' after ) - ignoring}} #pragma omp target update from(mapper(aa):vv) } } return arg; }
stepper.c
#include "stepper.h" #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <stdbool.h> #include <omp.h> #include <stdio.h> #define BLOCK_SIZE 4 //ldoc on /** * ## Implementation * * ### Structure allocation */ central2d_t* central2d_init(float w, float h, int nx, int ny, int nfield, flux_t flux, speed_t speed, float cfl) { // We extend to a four cell buffer to avoid BC comm on odd time steps int ng = 4; central2d_t* sim = (central2d_t*) malloc(sizeof(central2d_t)); sim->nx = nx; sim->ny = ny; sim->ng = ng; sim->nfield = nfield; sim->dx = w/nx; sim->dy = h/ny; sim->flux = flux; sim->speed = speed; sim->cfl = cfl; int nx_all = nx + 2*ng; int ny_all = ny + 2*ng; int nc = nx_all * ny_all; int N = nfield * nc; sim->u = (float*) malloc((4*N + 6*nx_all)* sizeof(float)); sim->v = sim->u + N; sim->f = sim->u + 2*N; sim->g = sim->u + 3*N; sim->scratch = sim->u + 4*N; return sim; } void central2d_free(central2d_t* sim) { free(sim->u); free(sim); } int central2d_offset(central2d_t* sim, int k, int ix, int iy) { int nx = sim->nx, ny = sim->ny, ng = sim->ng; int nx_all = nx + 2*ng; int ny_all = ny + 2*ng; return (k*ny_all+(ng+iy))*nx_all+(ng+ix); } /** * ### Boundary conditions * * In finite volume methods, boundary conditions are typically applied by * setting appropriate values in ghost cells. For our framework, we will * apply periodic boundary conditions; that is, waves that exit one side * of the domain will enter from the other side. * * We apply the conditions by assuming that the cells with coordinates * `nghost <= ix <= nx+nghost` and `nghost <= iy <= ny+nghost` are * "canonical", and setting the values for all other cells `(ix,iy)` * to the corresponding canonical values `(ix+p*nx,iy+q*ny)` for some * integers `p` and `q`. */ static inline void copy_subgrid(float* restrict dst, const float* restrict src, int nx, int ny, int stride1, int stride2) { for (int iy = 0; iy < ny; ++iy) for (int ix = 0; ix < nx; ++ix) dst[iy*stride1+ix] = src[iy*stride2+ix]; } static inline void copy_subgrid_allfield(float* restrict dst, const float* restrict src, int nx, int ny, int c1, int c2, int stride1, int stride2, int nfield) { for (int k = 0; k < nfield; ++k) { copy_subgrid(dst+k*c1, src+k*c2, nx, ny, stride1, stride2); } } static inline void print_grid(const float* restrict u, int nx, int ny, int stride) { for (int ix = 0; ix < nx; ++ix) { for (int iy = 0; iy < ny; ++iy) { printf("%.2f ", u[iy*stride+ix]); } printf("\n"); } printf("\n"); } void central2d_periodic_full(float* restrict u, int nx, int ny, int ng, int nfield) { // Stride and number per field int s = nx + 2*ng; int field_stride = (ny+2*ng)*s; // Offsets of left, right, top, and bottom data blocks and ghost blocks int l = nx, lg = 0; int r = ng, rg = nx+ng; int b = ny*s, bg = 0; int t = ng*s, tg = (nx+ng)*s; // Copy data into ghost cells on each side for (int k = 0; k < nfield; ++k) { float* uk = u + k*field_stride; copy_subgrid(uk+lg, uk+l, ng, ny+2*ng, s, s); copy_subgrid(uk+rg, uk+r, ng, ny+2*ng, s, s); copy_subgrid(uk+tg, uk+t, nx+2*ng, ng, s, s); copy_subgrid(uk+bg, uk+b, nx+2*ng, ng, s, s); } } void central2d_periodic(float* restrict u, const float* restrict src, int nx, int ny, int ng, int partx, int party, int px, int py, int nfield, int tbatch) { // Stride and number per field int ngu = ng*tbatch; int backng = ng*(tbatch-1); int s = nx + 2*ngu; int s2 = nx*partx + 2*ng; int field_stride = (ny+2*ngu)*s; int field_stride2 = (ny*party+2*ng)*s2; // Copy data into ghost cells on each side for (int k = 0; k < nfield; ++k) { float* uk = u + k*field_stride; const float* srck = src + k*field_stride2; int modxl = (px == 0? partx : px); int modxr = (px == partx-1? 0 : px+1); int modyb = (py == 0? party : py); int modyt = (py == party-1? 0 : py+1); copy_subgrid(uk, srck+(modyb*ny-backng)*s2+(modxl*nx-backng), ngu, ngu, s, s2); copy_subgrid(uk+ngu*s, srck+(ng+py*ny)*s2+modxl*nx-backng, ngu, ny, s, s2); copy_subgrid(uk+(ngu+ny)*s, srck+(ng+modyt*ny)*s2+modxl*nx-backng, ngu, ngu, s, s2); copy_subgrid(uk+ngu, srck+(modyb*ny-backng)*s2+px*nx+ng, nx, ngu, s, s2); copy_subgrid(uk+ngu*s+ngu, srck+(ng+py*ny)*s2+px*nx+ng, nx, ny, s, s2); copy_subgrid(uk+(ngu+ny)*s+ngu, srck+(ng+modyt*ny)*s2+px*nx+ng, nx, ngu, s, s2); copy_subgrid(uk+ngu+nx, srck+(modyb*ny-backng)*s2+modxr*nx+ng, ngu, ngu, s, s2); copy_subgrid(uk+ngu*s+nx+ngu, srck+(ng+py*ny)*s2+modxr*nx+ng, ngu, ny, s, s2); copy_subgrid(uk+(ngu+ny)*s+ngu+nx, srck+(ng+modyt*ny)*s2+modxr*nx+ng, ngu, ngu, s, s2); } } /** * ### Derivatives with limiters * * In order to advance the time step, we also need to estimate * derivatives of the fluxes and the solution values at each cell. * In order to maintain stability, we apply a limiter here. * * The minmod limiter *looks* like it should be expensive to computer, * since superficially it seems to require a number of branches. * We do something a little tricky, getting rid of the condition * on the sign of the arguments using the `copysign` instruction. * If the compiler does the "right" thing with `max` and `min` * for floating point arguments (translating them to branch-free * intrinsic operations), this implementation should be relatively fast. */ // Branch-free computation of minmod of two numbers times 2s static inline float xmin2s(float s, float a, float b) { float sa = copysignf(s, a); float sb = copysignf(s, b); float abs_a = fabsf(a); float abs_b = fabsf(b); float min_abs = (abs_a < abs_b ? abs_a : abs_b); return (sa+sb) * min_abs; } // Limited combined slope estimate static inline float limdiff(float um, float u0, float up) { const float theta = 2.0; const float quarter = 0.25; float du1 = u0-um; // Difference to left float du2 = up-u0; // Difference to right float duc = up-um; // Twice centered difference return xmin2s( quarter, xmin2s(theta, du1, du2), duc ); } // Compute limited derivs static inline void limited_deriv1(float* restrict du, const float* restrict u, int ncell) { for (int i = 0; i < ncell; ++i) du[i] = limdiff(u[i-1], u[i], u[i+1]); } // Compute limited derivs across stride static inline void limited_derivk(float* restrict du, const float* restrict u, int ncell, int stride) { assert(stride > 0); for (int i = 0; i < ncell; ++i) du[i] = limdiff(u[i-stride], u[i], u[i+stride]); } /** * ### Advancing a time step * * Take one step of the numerical scheme. This consists of two pieces: * a first-order corrector computed at a half time step, which is used * to obtain new $F$ and $G$ values; and a corrector step that computes * the solution at the full step. For full details, we refer to the * [Jiang and Tadmor paper][jt]. * * The `compute_step` function takes two arguments: the `io` flag * which is the time step modulo 2 (0 if even, 1 if odd); and the `dt` * flag, which actually determines the time step length. We need * to know the even-vs-odd distinction because the Jiang-Tadmor * scheme alternates between a primary grid (on even steps) and a * staggered grid (on odd steps). This means that the data at $(i,j)$ * in an even step and the data at $(i,j)$ in an odd step represent * values at different locations in space, offset by half a space step * in each direction. Every other step, we shift things back by one * mesh cell in each direction, essentially resetting to the primary * indexing scheme. * * We're slightly tricky in the corrector in that we write * $$ * v(i,j) = (s(i+1,j) + s(i,j)) - (d(i+1,j)-d(i,j)) * $$ * where $s(i,j)$ comprises the $u$ and $x$-derivative terms in the * update formula, and $d(i,j)$ the $y$-derivative terms. This cuts * the arithmetic cost a little (not that it's that big to start). * It also makes it more obvious that we only need four rows worth * of scratch space. */ // Predictor half-step static void central2d_predict(float* restrict v, float* restrict scratch, const float* restrict u, const float* restrict f, const float* restrict g, float dtcdx2, float dtcdy2, int nx, int ny, int nfield) { float* restrict fx = scratch; float* restrict gy = scratch+nx; for (int k = 0; k < nfield; ++k) { for (int iy = 1; iy < ny-1; ++iy) { int offset = (k*ny+iy)*nx+1; limited_deriv1(fx+1, f+offset, nx-2); limited_derivk(gy+1, g+offset, nx-2, nx); for (int ix = 1; ix < nx-1; ++ix) { int offset = (k*ny+iy)*nx+ix; v[offset] = u[offset] - dtcdx2 * fx[ix] - dtcdy2 * gy[ix]; } } } } // Corrector static void central2d_correct_sd(float* restrict s, float* restrict d, const float* restrict ux, const float* restrict uy, const float* restrict u, const float* restrict f, const float* restrict g, float dtcdx2, float dtcdy2, int xlo, int xhi) { for (int ix = xlo; ix < xhi; ++ix) s[ix] = 0.2500f * (u [ix] + u [ix+1]) + 0.0625f * (ux[ix] - ux[ix+1]) + dtcdx2 * (f [ix] - f [ix+1]); for (int ix = xlo; ix < xhi; ++ix) d[ix] = 0.0625f * (uy[ix] + uy[ix+1]) + dtcdy2 * (g [ix] + g [ix+1]); } // Corrector static void central2d_correct(float* restrict v, float* restrict scratch, const float* restrict u, const float* restrict f, const float* restrict g, float dtcdx2, float dtcdy2, int xlo, int xhi, int ylo, int yhi, int nx, int ny, int nfield) { assert(0 <= xlo && xlo < xhi && xhi <= nx); assert(0 <= ylo && ylo < yhi && yhi <= ny); float* restrict ux = scratch; float* restrict uy = scratch + nx; float* restrict s0 = scratch + 2*nx; float* restrict d0 = scratch + 3*nx; float* restrict s1 = scratch + 4*nx; float* restrict d1 = scratch + 5*nx; for (int k = 0; k < nfield; ++k) { float* restrict vk = v + k*ny*nx; const float* restrict uk = u + k*ny*nx; const float* restrict fk = f + k*ny*nx; const float* restrict gk = g + k*ny*nx; limited_deriv1(ux+1, uk+ylo*nx+1, nx-2); limited_derivk(uy+1, uk+ylo*nx+1, nx-2, nx); central2d_correct_sd(s1, d1, ux, uy, uk + ylo*nx, fk + ylo*nx, gk + ylo*nx, dtcdx2, dtcdy2, xlo, xhi); for (int iy = ylo; iy < yhi; ++iy) { float* tmp; tmp = s0; s0 = s1; s1 = tmp; tmp = d0; d0 = d1; d1 = tmp; limited_deriv1(ux+1, uk+(iy+1)*nx+1, nx-2); limited_derivk(uy+1, uk+(iy+1)*nx+1, nx-2, nx); central2d_correct_sd(s1, d1, ux, uy, uk + (iy+1)*nx, fk + (iy+1)*nx, gk + (iy+1)*nx, dtcdx2, dtcdy2, xlo, xhi); for (int ix = xlo; ix < xhi; ++ix) vk[iy*nx+ix] = (s1[ix]+s0[ix])-(d1[ix]-d0[ix]); } } } static void central2d_step(float* restrict u, float* restrict v, float* restrict scratch, float* restrict f, float* restrict g, int io, int nx, int ny, int ng, int nfield, flux_t flux, speed_t speed, float dt, float dx, float dy) { int nx_all = nx + 2*ng; int ny_all = ny + 2*ng; float dtcdx2 = 0.5 * dt / dx; float dtcdy2 = 0.5 * dt / dy; flux(f, g, u, nx_all * ny_all, nx_all * ny_all); central2d_predict(v, scratch, u, f, g, dtcdx2, dtcdy2, nx_all, ny_all, nfield); // Flux values of f and g at half step for (int iy = 1; iy < ny_all-1; ++iy) { int jj = iy*nx_all+1; flux(f+jj, g+jj, v+jj, nx_all-2, nx_all * ny_all); } central2d_correct(v+io*(nx_all+1), scratch, u, f, g, dtcdx2, dtcdy2, ng-io, nx+ng-io, ng-io, ny+ng-io, nx_all, ny_all, nfield); } static void central2d_step_batch(float* restrict u, float* restrict v, float* restrict scratch, float* restrict f, float* restrict g, int nx, int ny, int ng, int nfield, flux_t flux, speed_t speed, float dt, float dx, float dy, int tbatch) { for (int b = 0; b < tbatch; ++b) { central2d_step(u, v, scratch, f, g, 0, nx+2*(ng*tbatch-(2*b+1)*ng/2), ny+2*(ng*tbatch-(2*b+1)*ng/2), (2*b+1)*ng/2, nfield, flux, speed, dt, dx, dy); central2d_step(v, u, scratch, f, g, 1, nx+2*ng*(tbatch-b-1), ny+2*ng*(tbatch-b-1), ng*(b+1), nfield, flux, speed, dt, dx, dy); } } /** * ### Advance a fixed time * * The `run` method advances from time 0 (initial conditions) to time * `tfinal`. Note that `run` can be called repeatedly; for example, * we might want to advance for a period of time, write out a picture, * advance more, and write another picture. In this sense, `tfinal` * should be interpreted as an offset from the time represented by * the simulator at the start of the call, rather than as an absolute time. * * We always take an even number of steps so that the solution * at the end lives on the main grid instead of the staggered grid. */ static int central2d_xrun(float* restrict u, float* restrict v, float* restrict scratch, float* restrict f, float* restrict g, int nx, int ny, int ng, int nfield, flux_t flux, speed_t speed, float tfinal, float dx, float dy, float cfl, int threads) { int nstep = 0; int tbatch = 1; int nx_all = nx + 2*ng; int ny_all = ny + 2*ng; int c = nx_all * ny_all; int N = nfield * c; int partx = 2; int party = fmaxf(1, BLOCK_SIZE*threads/partx); omp_set_num_threads(threads); int sx = nx/partx; int sy = ny/party; int sx_all = sx + 2*tbatch*ng; int sy_all = sy + 2*tbatch*ng; int pc = sx_all * sy_all; int pN = nfield * pc; bool done = false; float t = 0; static float *pu; #pragma omp threadprivate(pu) #pragma omp parallel { pu = (float*) malloc((4*pN + 6*sx_all)* sizeof(float)); } while (!done) { float cxy[2] = {1.0e-15f, 1.0e-15f}; speed(cxy, u, nx_all * ny_all, nx_all * ny_all); float dt = cfl / fmaxf(cxy[0]/dx, cxy[1]/dy); if (t + 2*tbatch*dt >= tfinal) { dt = (tfinal-t)/2/tbatch; done = true; } #pragma omp parallel for collapse(2) for (int py = 0; py < party; py++) { for (int px = 0; px < partx; px++) { int thread = omp_get_thread_num(); float *pv = pu + pN; float *pf = pu+ 2*pN; float *pg = pu + 3*pN; float *pscratch = pu + 4*pN; central2d_periodic(pu, u, sx, sy, ng, partx, party, px, py, nfield, tbatch); central2d_step_batch(pu, pv, pscratch, pf, pg, sx, sy, ng, nfield, flux, speed, dt, dx, dy, tbatch); copy_subgrid_allfield(u+nx_all*(ng+py*sy)+(ng+px*sx),pu+tbatch*ng*sx_all+ng*tbatch, sx,sy,c,pc,nx_all,sx_all,nfield); } } t += 2*dt*tbatch; nstep += 2*tbatch; } #pragma omp parallel { free(pu); } return nstep; } int central2d_run(central2d_t* sim, float tfinal, int threads) { return central2d_xrun(sim->u, sim->v, sim->scratch, sim->f, sim->g, sim->nx, sim->ny, sim->ng, sim->nfield, sim->flux, sim->speed, tfinal, sim->dx, sim->dy, sim->cfl, threads); }
core_strtri.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/core_blas/core_ztrtri.c, normal z -> s, Fri Sep 28 17:38:24 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_trtri * * Computes the inverse of an upper or lower * triangular matrix A. * ******************************************************************************* * * @param[in] uplo * = PlasmaUpper: Upper triangle of A is stored; * = PlasmaLower: Lower triangle of A is stored. * * @param[in] diag * = PlasmaNonUnit: A is non-unit triangular; * = PlasmaUnit: A is unit triangular. * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] A * On entry, the triangular matrix A. If uplo = 'U', the * leading n-by-n upper triangular part of the array A * contains the upper triangular matrix, and the strictly * lower triangular part of A is not referenced. If uplo = * 'L', the leading n-by-n lower triangular part of the array * A contains the lower triangular matrix, and the strictly * upper triangular part of A is not referenced. If diag = * 'U', the diagonal elements of A are also not referenced and * are assumed to be 1. On exit, the (triangular) inverse of * the original matrix. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * * @retval PlasmaSuccess on successful exit * @retval < 0 if -i, the i-th argument had an illegal value * @retval > 0 if i, A(i,i) is exactly zero. The triangular * matrix is singular and its inverse can not be computed. * ******************************************************************************/ __attribute__((weak)) int plasma_core_strtri(plasma_enum_t uplo, plasma_enum_t diag, int n, float *A, int lda) { return LAPACKE_strtri_work(LAPACK_COL_MAJOR, lapack_const(uplo), lapack_const(diag), n, A, lda); } /******************************************************************************/ void plasma_core_omp_strtri(plasma_enum_t uplo, plasma_enum_t diag, int n, float *A, int lda, int iinfo, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A[0:lda*n]) { if (sequence->status == PlasmaSuccess) { int info = plasma_core_strtri(uplo, diag, n, A, lda); if (info != 0) plasma_request_fail(sequence, request, iinfo+info); } } }
1_parallel_push_pop_stack.c
/* Program : 1 Author : Anish Topic : Write a C program using OpenMP features to create two parallel threads. The first thread should push the first ‘N’ natural numbers into a stack in sequence, and the second thread should pop the numbers from the stack. */ #include<stdio.h> #include<omp.h> #include<stdlib.h> int main() { int n,a; printf("\n ENTER THE VALUE OF N \n"); scanf("%d",&n); int id,d,Q[n],top=-1; omp_set_dynamic(0); #pragma omp parallel num_threads(2) { id=omp_get_thread_num(); if(id==0) //push { while(1) { #pragma omp critical { if(top<n-1) { printf("\n ENTER A NUMBER \n"); scanf("%d",&a); Q[++top]=a; printf("\n INSERTED ITEM IS %d",a); } else printf("\n NO SPACE"); fgetc(stdin); } } } else { while(1) //pop { #pragma omp critical { if(top!=-1) { d=Q[top]; top--; printf("\n DELETED ITEM IS %d",d); } else printf("\n NO ITEMS TO DELETE"); fgetc(stdin); } } } } return 0; }
GridInit.c
#include "XSbench_header.h" #ifdef MPI #include<mpi.h> #endif GridPoint * generate_hash_table( NuclideGridPoint ** nuclide_grids, long n_isotopes, long n_gridpoints, long hash_bins ) { printf("Generating Hash Grid...\n"); #ifdef HPE_MMAP GridPoint * energy_grid = (GridPoint *)mmap_wrapper( "hash", "energy_grid", hash_bins * sizeof( GridPoint ) ); int * full = (int *) mmap_wrapper( "hash", "full", n_isotopes * hash_bins * sizeof(int) ); #else GridPoint * energy_grid = (GridPoint *)malloc( hash_bins * sizeof( GridPoint ) ); int * full = (int *) malloc( n_isotopes * hash_bins * sizeof(int) ); #endif for( long i = 0; i < hash_bins; i++ ) energy_grid[i].xs_ptrs = &full[n_isotopes * i]; double du = 1.0 / hash_bins; // For each energy level in the hash table #pragma omp parallel for for( long e = 0; e < hash_bins; e++ ) { double energy = e * du; // We need to determine the bounding energy levels for all isotopes for( long i = 0; i < n_isotopes; i++ ) { energy_grid[e].xs_ptrs[i] = grid_search_nuclide( n_gridpoints, energy, nuclide_grids[i], 0, n_gridpoints-1); } } return energy_grid; } // Generates randomized energy grid for each nuclide // Note that this is done as part of initialization (serial), so // rand() is used. void generate_grids( NuclideGridPoint ** nuclide_grids, long n_isotopes, long n_gridpoints ) { for( long i = 0; i < n_isotopes; i++ ) for( long j = 0; j < n_gridpoints; j++ ) { nuclide_grids[i][j].energy =((double)rand()/(double)RAND_MAX); nuclide_grids[i][j].total_xs =((double)rand()/(double)RAND_MAX); nuclide_grids[i][j].elastic_xs =((double)rand()/(double)RAND_MAX); nuclide_grids[i][j].absorbtion_xs=((double)rand()/(double)RAND_MAX); nuclide_grids[i][j].fission_xs =((double)rand()/(double)RAND_MAX); nuclide_grids[i][j].nu_fission_xs=((double)rand()/(double)RAND_MAX); } } // Verification version of this function (tighter control over RNG) void generate_grids_v( NuclideGridPoint ** nuclide_grids, long n_isotopes, long n_gridpoints ) { for( long i = 0; i < n_isotopes; i++ ) for( long j = 0; j < n_gridpoints; j++ ) { nuclide_grids[i][j].energy = rn_v(); nuclide_grids[i][j].total_xs = rn_v(); nuclide_grids[i][j].elastic_xs = rn_v(); nuclide_grids[i][j].absorbtion_xs= rn_v(); nuclide_grids[i][j].fission_xs = rn_v(); nuclide_grids[i][j].nu_fission_xs= rn_v(); } } // Sorts the nuclide grids by energy (lowest -> highest) void sort_nuclide_grids( NuclideGridPoint ** nuclide_grids, long n_isotopes, long n_gridpoints ) { int (*cmp) (const void *, const void *); cmp = NGP_compare; for( long i = 0; i < n_isotopes; i++ ) qsort( nuclide_grids[i], n_gridpoints, sizeof(NuclideGridPoint), cmp ); // error debug check /* for( int i = 0; i < n_isotopes; i++ ) { printf("NUCLIDE %d ==============================\n", i); for( int j = 0; j < n_gridpoints; j++ ) printf("E%d = %lf\n", j, nuclide_grids[i][j].energy); } */ } // Allocates unionized energy grid, and assigns union of energy levels // from nuclide grids to it. GridPoint * generate_energy_grid( long n_isotopes, long n_gridpoints, NuclideGridPoint ** nuclide_grids) { int mype = 0; #ifdef MPI MPI_Comm_rank(MPI_COMM_WORLD, &mype); #endif if( mype == 0 ) printf("Generating Unionized Energy Grid...\n"); long n_unionized_grid_points = n_isotopes*n_gridpoints; int (*cmp) (const void *, const void *); cmp = NGP_compare; #ifdef HPE_MMAP GridPoint * energy_grid = (GridPoint *)mmap_wrapper( "unionized", "energy_grid", n_unionized_grid_points * sizeof( GridPoint ) ); #else GridPoint * energy_grid = (GridPoint *)malloc( n_unionized_grid_points * sizeof( GridPoint ) ); #endif if( mype == 0 ) printf("Copying and Sorting all nuclide grids...\n"); NuclideGridPoint ** n_grid_sorted = gpmatrix( n_isotopes, n_gridpoints ); memcpy( n_grid_sorted[0], nuclide_grids[0], n_isotopes*n_gridpoints* sizeof( NuclideGridPoint ) ); qsort( &n_grid_sorted[0][0], n_unionized_grid_points, sizeof(NuclideGridPoint), cmp); if( mype == 0 ) printf("Assigning energies to unionized grid...\n"); for( long i = 0; i < n_unionized_grid_points; i++ ) energy_grid[i].energy = n_grid_sorted[0][i].energy; gpmatrix_free(n_grid_sorted); #ifdef HPE_MMAP int * full = (int *) mmap_wrapper("unionized", "full", n_isotopes * n_unionized_grid_points * sizeof(int) ); #else int * full = (int *) malloc( n_isotopes * n_unionized_grid_points * sizeof(int) ); #endif if( full == NULL ) { fprintf(stderr,"ERROR - Out Of Memory!\n"); exit(1); } for( long i = 0; i < n_unionized_grid_points; i++ ) energy_grid[i].xs_ptrs = &full[n_isotopes * i]; // debug error checking /* for( int i = 0; i < n_unionized_grid_points; i++ ) printf("E%d = %lf\n", i, energy_grid[i].energy); */ return energy_grid; } // Initializes the unionized energy grid, by locating the appropriate // location in the nulicde grid for each entry on the unionized grid. // This function should not be profiling when doing performance analysis or tuning. // This is because this function does not really represent // a real function in OpenMC, it is only necessary to initialize the UEG // in this mini-app for later use in the simulation region of the code. // Analysts who find that this function is eating up a large portion of the runtime // should exclude it from their analysis, or otherwise wash it out by increasing // the amount of time spent in the simulation portion of the application by running // more lookups with the "-l" command line argument. // This function is not parallelized due to false sharing issues that arrise when writing // to the UEG. void initialization_do_not_profile_set_grid_ptrs( GridPoint * restrict energy_grid, NuclideGridPoint ** restrict nuclide_grids, long n_isotopes, long n_gridpoints ) { int mype = 0; #ifdef MPI MPI_Comm_rank(MPI_COMM_WORLD, &mype); #endif if( mype == 0 ) printf("Assigning pointers to Unionized Energy Grid...\n"); int * idx_low = (int *) calloc( n_isotopes, sizeof(int)); double * energy_high = (double *) malloc( n_isotopes * sizeof(double)); for( int i = 0; i < n_isotopes; i++ ) energy_high[i] = nuclide_grids[i][1].energy; for( long e = 0; e < n_isotopes * n_gridpoints; e++ ) { double unionized_energy = energy_grid[e].energy; for( long i = 0; i < n_isotopes; i++ ) { if( unionized_energy < energy_high[i] ) energy_grid[e].xs_ptrs[i] = idx_low[i]; else if( idx_low[i] == n_gridpoints - 2 ) energy_grid[e].xs_ptrs[i] = idx_low[i]; else { idx_low[i]++; energy_grid[e].xs_ptrs[i] = idx_low[i]; energy_high[i] = nuclide_grids[i][idx_low[i]+1].energy; } } } free(idx_low); free(energy_high); /* Alternative method with high stride access, less efficient //#pragma omp parallel for schedule(dynamic,1) for( long i = 0; i < n_isotopes; i++ ) { int nuclide_grid_idx_low = 0; double nuclide_energy_high = nuclide_grids[i][nuclide_grid_idx_low+1].energy; // Loop over entries in the UEG for( long e = 0; e < n_isotopes * n_gridpoints; e++ ) { double unionized_energy = energy_grid[e].energy; if( unionized_energy < nuclide_energy_high ) energy_grid[e].xs_ptrs[i] = nuclide_grid_idx_low; else if( nuclide_grid_idx_low == n_gridpoints - 2 ) energy_grid[e].xs_ptrs[i] = nuclide_grid_idx_low; else { nuclide_grid_idx_low++; energy_grid[e].xs_ptrs[i] = nuclide_grid_idx_low; nuclide_energy_high = nuclide_grids[i][nuclide_grid_idx_low+1].energy; } } } */ }
Stmt.h
//===--- Stmt.h - Classes for representing statements -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Stmt interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMT_H #define LLVM_CLANG_AST_STMT_H #include "clang/AST/DeclGroup.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/CapturedStmt.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include <string> namespace llvm { class FoldingSetNodeID; } namespace clang { class ASTContext; class Attr; class CapturedDecl; class Decl; class Expr; class IdentifierInfo; class LabelDecl; class ParmVarDecl; class PrinterHelper; struct PrintingPolicy; class QualType; class RecordDecl; class SourceManager; class StringLiteral; class SwitchStmt; class Token; class VarDecl; //===--------------------------------------------------------------------===// // ExprIterator - Iterators for iterating over Stmt* arrays that contain // only Expr*. This is needed because AST nodes use Stmt* arrays to store // references to children (to be compatible with StmtIterator). //===--------------------------------------------------------------------===// class Stmt; class Expr; class ExprIterator { Stmt** I; public: ExprIterator(Stmt** i) : I(i) {} ExprIterator() : I(0) {} ExprIterator& operator++() { ++I; return *this; } ExprIterator operator-(size_t i) { return I-i; } ExprIterator operator+(size_t i) { return I+i; } Expr* operator[](size_t idx); // FIXME: Verify that this will correctly return a signed distance. signed operator-(const ExprIterator& R) const { return I - R.I; } Expr* operator*() const; Expr* operator->() const; bool operator==(const ExprIterator& R) const { return I == R.I; } bool operator!=(const ExprIterator& R) const { return I != R.I; } bool operator>(const ExprIterator& R) const { return I > R.I; } bool operator>=(const ExprIterator& R) const { return I >= R.I; } }; class ConstExprIterator { const Stmt * const *I; public: ConstExprIterator(const Stmt * const *i) : I(i) {} ConstExprIterator() : I(0) {} ConstExprIterator& operator++() { ++I; return *this; } ConstExprIterator operator+(size_t i) const { return I+i; } ConstExprIterator operator-(size_t i) const { return I-i; } const Expr * operator[](size_t idx) const; signed operator-(const ConstExprIterator& R) const { return I - R.I; } const Expr * operator*() const; const Expr * operator->() const; bool operator==(const ConstExprIterator& R) const { return I == R.I; } bool operator!=(const ConstExprIterator& R) const { return I != R.I; } bool operator>(const ConstExprIterator& R) const { return I > R.I; } bool operator>=(const ConstExprIterator& R) const { return I >= R.I; } }; //===----------------------------------------------------------------------===// // AST classes for statements. //===----------------------------------------------------------------------===// /// Stmt - This represents one statement. /// class Stmt { public: enum StmtClass { NoStmtClass = 0, #define STMT(CLASS, PARENT) CLASS##Class, #define STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class, #define LAST_STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class #define ABSTRACT_STMT(STMT) #include "clang/AST/StmtNodes.inc" }; // Make vanilla 'new' and 'delete' illegal for Stmts. protected: void* operator new(size_t bytes) throw() { llvm_unreachable("Stmts cannot be allocated with regular 'new'."); } void operator delete(void* data) throw() { llvm_unreachable("Stmts cannot be released with regular 'delete'."); } class StmtBitfields { friend class Stmt; /// \brief The statement class. unsigned sClass : 8; }; enum { NumStmtBits = 8 }; class CompoundStmtBitfields { friend class CompoundStmt; unsigned : NumStmtBits; unsigned NumStmts : 32 - NumStmtBits; }; class ExprBitfields { friend class Expr; friend class DeclRefExpr; // computeDependence friend class InitListExpr; // ctor friend class DesignatedInitExpr; // ctor friend class BlockDeclRefExpr; // ctor friend class ASTStmtReader; // deserialization friend class CXXNewExpr; // ctor friend class DependentScopeDeclRefExpr; // ctor friend class CXXConstructExpr; // ctor friend class CallExpr; // ctor friend class OffsetOfExpr; // ctor friend class ObjCMessageExpr; // ctor friend class ObjCArrayLiteral; // ctor friend class ObjCDictionaryLiteral; // ctor friend class ShuffleVectorExpr; // ctor friend class ParenListExpr; // ctor friend class CXXUnresolvedConstructExpr; // ctor friend class CXXDependentScopeMemberExpr; // ctor friend class OverloadExpr; // ctor friend class PseudoObjectExpr; // ctor friend class AtomicExpr; // ctor unsigned : NumStmtBits; unsigned ValueKind : 2; unsigned ObjectKind : 2; unsigned TypeDependent : 1; unsigned ValueDependent : 1; unsigned InstantiationDependent : 1; unsigned ContainsUnexpandedParameterPack : 1; }; enum { NumExprBits = 16 }; class CharacterLiteralBitfields { friend class CharacterLiteral; unsigned : NumExprBits; unsigned Kind : 2; }; enum APFloatSemantics { IEEEhalf, IEEEsingle, IEEEdouble, x87DoubleExtended, IEEEquad, PPCDoubleDouble }; class FloatingLiteralBitfields { friend class FloatingLiteral; unsigned : NumExprBits; unsigned Semantics : 3; // Provides semantics for APFloat construction unsigned IsExact : 1; }; class UnaryExprOrTypeTraitExprBitfields { friend class UnaryExprOrTypeTraitExpr; unsigned : NumExprBits; unsigned Kind : 2; unsigned IsType : 1; // true if operand is a type, false if an expression. }; class DeclRefExprBitfields { friend class DeclRefExpr; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; unsigned HasQualifier : 1; unsigned HasTemplateKWAndArgsInfo : 1; unsigned HasFoundDecl : 1; unsigned HadMultipleCandidates : 1; unsigned RefersToEnclosingLocal : 1; }; class CastExprBitfields { friend class CastExpr; unsigned : NumExprBits; unsigned Kind : 6; unsigned BasePathSize : 32 - 6 - NumExprBits; }; class CallExprBitfields { friend class CallExpr; unsigned : NumExprBits; unsigned NumPreArgs : 1; }; class ExprWithCleanupsBitfields { friend class ExprWithCleanups; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; unsigned NumObjects : 32 - NumExprBits; }; class PseudoObjectExprBitfields { friend class PseudoObjectExpr; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; // These don't need to be particularly wide, because they're // strictly limited by the forms of expressions we permit. unsigned NumSubExprs : 8; unsigned ResultIndex : 32 - 8 - NumExprBits; }; class ObjCIndirectCopyRestoreExprBitfields { friend class ObjCIndirectCopyRestoreExpr; unsigned : NumExprBits; unsigned ShouldCopy : 1; }; class InitListExprBitfields { friend class InitListExpr; unsigned : NumExprBits; /// Whether this initializer list originally had a GNU array-range /// designator in it. This is a temporary marker used by CodeGen. unsigned HadArrayRangeDesignator : 1; }; class TypeTraitExprBitfields { friend class TypeTraitExpr; friend class ASTStmtReader; friend class ASTStmtWriter; unsigned : NumExprBits; /// \brief The kind of type trait, which is a value of a TypeTrait enumerator. unsigned Kind : 8; /// \brief If this expression is not value-dependent, this indicates whether /// the trait evaluated true or false. unsigned Value : 1; /// \brief The number of arguments to this type trait. unsigned NumArgs : 32 - 8 - 1 - NumExprBits; }; union { // FIXME: this is wasteful on 64-bit platforms. void *Aligner; StmtBitfields StmtBits; CompoundStmtBitfields CompoundStmtBits; ExprBitfields ExprBits; CharacterLiteralBitfields CharacterLiteralBits; FloatingLiteralBitfields FloatingLiteralBits; UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits; DeclRefExprBitfields DeclRefExprBits; CastExprBitfields CastExprBits; CallExprBitfields CallExprBits; ExprWithCleanupsBitfields ExprWithCleanupsBits; PseudoObjectExprBitfields PseudoObjectExprBits; ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits; InitListExprBitfields InitListExprBits; TypeTraitExprBitfields TypeTraitExprBits; }; friend class ASTStmtReader; friend class ASTStmtWriter; public: // Only allow allocation of Stmts using the allocator in ASTContext // or by doing a placement new. void* operator new(size_t bytes, const ASTContext& C, unsigned alignment = 8); void* operator new(size_t bytes, const ASTContext* C, unsigned alignment = 8) { return operator new(bytes, *C, alignment); } void* operator new(size_t bytes, void* mem) throw() { return mem; } void operator delete(void*, const ASTContext&, unsigned) throw() { } void operator delete(void*, const ASTContext*, unsigned) throw() { } void operator delete(void*, size_t) throw() { } void operator delete(void*, void*) throw() { } public: /// \brief A placeholder type used to construct an empty shell of a /// type, that will be filled in later (e.g., by some /// de-serialization). struct EmptyShell { }; private: /// \brief Whether statistic collection is enabled. static bool StatisticsEnabled; protected: /// \brief Construct an empty statement. explicit Stmt(StmtClass SC, EmptyShell) { StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } public: Stmt(StmtClass SC) { StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } StmtClass getStmtClass() const { return static_cast<StmtClass>(StmtBits.sClass); } const char *getStmtClassName() const; /// SourceLocation tokens are not useful in isolation - they are low level /// value objects created/interpreted by SourceManager. We assume AST /// clients will have a pointer to the respective SourceManager. SourceRange getSourceRange() const LLVM_READONLY; SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; // global temp stats (until we have a per-module visitor) static void addStmtClass(const StmtClass s); static void EnableStatistics(); static void PrintStats(); /// \brief Dumps the specified AST fragment and all subtrees to /// \c llvm::errs(). LLVM_ATTRIBUTE_USED void dump() const; LLVM_ATTRIBUTE_USED void dump(SourceManager &SM) const; void dump(raw_ostream &OS, SourceManager &SM) const; /// dumpColor - same as dump(), but forces color highlighting. LLVM_ATTRIBUTE_USED void dumpColor() const; /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST /// back to its original source language syntax. void dumpPretty(const ASTContext &Context) const; void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation = 0) const; /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only /// works on systems with GraphViz (Mac OS X) or dot+gv installed. void viewAST() const; /// Skip past any implicit AST nodes which might surround this /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes. Stmt *IgnoreImplicit(); const Stmt *stripLabelLikeStatements() const; Stmt *stripLabelLikeStatements() { return const_cast<Stmt*>( const_cast<const Stmt*>(this)->stripLabelLikeStatements()); } /// Child Iterators: All subclasses must implement 'children' /// to permit easy iteration over the substatements/subexpessions of an /// AST node. This permits easy iteration over all nodes in the AST. typedef StmtIterator child_iterator; typedef ConstStmtIterator const_child_iterator; typedef StmtRange child_range; typedef ConstStmtRange const_child_range; child_range children(); const_child_range children() const { return const_cast<Stmt*>(this)->children(); } child_iterator child_begin() { return children().first; } child_iterator child_end() { return children().second; } const_child_iterator child_begin() const { return children().first; } const_child_iterator child_end() const { return children().second; } /// \brief Produce a unique representation of the given statement. /// /// \param ID once the profiling operation is complete, will contain /// the unique representation of the given statement. /// /// \param Context the AST context in which the statement resides /// /// \param Canonical whether the profile should be based on the canonical /// representation of this statement (e.g., where non-type template /// parameters are identified by index/level rather than their /// declaration pointers) or the exact representation of the statement as /// written in the source. void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const; }; /// DeclStmt - Adaptor class for mixing declarations with statements and /// expressions. For example, CompoundStmt mixes statements, expressions /// and declarations (variables, types). Another example is ForStmt, where /// the first statement can be an expression or a declaration. /// class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; public: DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {} /// \brief Build an empty declaration statement. explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) { } /// isSingleDecl - This method returns true if this DeclStmt refers /// to a single Decl. bool isSingleDecl() const { return DG.isSingleDecl(); } const Decl *getSingleDecl() const { return DG.getSingleDecl(); } Decl *getSingleDecl() { return DG.getSingleDecl(); } const DeclGroupRef getDeclGroup() const { return DG; } DeclGroupRef getDeclGroup() { return DG; } void setDeclGroup(DeclGroupRef DGR) { DG = DGR; } SourceLocation getStartLoc() const { return StartLoc; } void setStartLoc(SourceLocation L) { StartLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return StartLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DeclStmtClass; } // Iterators over subexpressions. child_range children() { return child_range(child_iterator(DG.begin(), DG.end()), child_iterator(DG.end(), DG.end())); } typedef DeclGroupRef::iterator decl_iterator; typedef DeclGroupRef::const_iterator const_decl_iterator; decl_iterator decl_begin() { return DG.begin(); } decl_iterator decl_end() { return DG.end(); } const_decl_iterator decl_begin() const { return DG.begin(); } const_decl_iterator decl_end() const { return DG.end(); } typedef std::reverse_iterator<decl_iterator> reverse_decl_iterator; reverse_decl_iterator decl_rbegin() { return reverse_decl_iterator(decl_end()); } reverse_decl_iterator decl_rend() { return reverse_decl_iterator(decl_begin()); } }; /// NullStmt - This is the null statement ";": C99 6.8.3p3. /// class NullStmt : public Stmt { SourceLocation SemiLoc; /// \brief True if the null statement was preceded by an empty macro, e.g: /// @code /// #define CALL(x) /// CALL(0); /// @endcode bool HasLeadingEmptyMacro; public: NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false) : Stmt(NullStmtClass), SemiLoc(L), HasLeadingEmptyMacro(hasLeadingEmptyMacro) {} /// \brief Build an empty null statement. explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty), HasLeadingEmptyMacro(false) { } SourceLocation getSemiLoc() const { return SemiLoc; } void setSemiLoc(SourceLocation L) { SemiLoc = L; } bool hasLeadingEmptyMacro() const { return HasLeadingEmptyMacro; } SourceLocation getLocStart() const LLVM_READONLY { return SemiLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SemiLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == NullStmtClass; } child_range children() { return child_range(); } friend class ASTStmtReader; friend class ASTStmtWriter; }; /// CompoundStmt - This represents a group of statements like { stmt stmt }. /// class CompoundStmt : public Stmt { Stmt** Body; SourceLocation LBracLoc, RBracLoc; public: CompoundStmt(const ASTContext &C, ArrayRef<Stmt*> Stmts, SourceLocation LB, SourceLocation RB); // \brief Build an empty compound statement with a location. explicit CompoundStmt(SourceLocation Loc) : Stmt(CompoundStmtClass), Body(0), LBracLoc(Loc), RBracLoc(Loc) { CompoundStmtBits.NumStmts = 0; } // \brief Build an empty compound statement. explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty), Body(0) { CompoundStmtBits.NumStmts = 0; } void setStmts(const ASTContext &C, Stmt **Stmts, unsigned NumStmts); bool body_empty() const { return CompoundStmtBits.NumStmts == 0; } unsigned size() const { return CompoundStmtBits.NumStmts; } typedef Stmt** body_iterator; body_iterator body_begin() { return Body; } body_iterator body_end() { return Body + size(); } Stmt *body_back() { return !body_empty() ? Body[size()-1] : 0; } void setLastStmt(Stmt *S) { assert(!body_empty() && "setLastStmt"); Body[size()-1] = S; } typedef Stmt* const * const_body_iterator; const_body_iterator body_begin() const { return Body; } const_body_iterator body_end() const { return Body + size(); } const Stmt *body_back() const { return !body_empty() ? Body[size()-1] : 0; } typedef std::reverse_iterator<body_iterator> reverse_body_iterator; reverse_body_iterator body_rbegin() { return reverse_body_iterator(body_end()); } reverse_body_iterator body_rend() { return reverse_body_iterator(body_begin()); } typedef std::reverse_iterator<const_body_iterator> const_reverse_body_iterator; const_reverse_body_iterator body_rbegin() const { return const_reverse_body_iterator(body_end()); } const_reverse_body_iterator body_rend() const { return const_reverse_body_iterator(body_begin()); } SourceLocation getLocStart() const LLVM_READONLY { return LBracLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RBracLoc; } SourceLocation getLBracLoc() const { return LBracLoc; } void setLBracLoc(SourceLocation L) { LBracLoc = L; } SourceLocation getRBracLoc() const { return RBracLoc; } void setRBracLoc(SourceLocation L) { RBracLoc = L; } static bool classof(const Stmt *T) { return T->getStmtClass() == CompoundStmtClass; } // Iterators child_range children() { return child_range(&Body[0], &Body[0]+CompoundStmtBits.NumStmts); } const_child_range children() const { return child_range(&Body[0], &Body[0]+CompoundStmtBits.NumStmts); } }; // SwitchCase is the base class for CaseStmt and DefaultStmt, class SwitchCase : public Stmt { protected: // A pointer to the following CaseStmt or DefaultStmt class, // used by SwitchStmt. SwitchCase *NextSwitchCase; SourceLocation KeywordLoc; SourceLocation ColonLoc; SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc) : Stmt(SC), NextSwitchCase(0), KeywordLoc(KWLoc), ColonLoc(ColonLoc) {} SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC), NextSwitchCase(0) {} public: const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; } SwitchCase *getNextSwitchCase() { return NextSwitchCase; } void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; } SourceLocation getKeywordLoc() const { return KeywordLoc; } void setKeywordLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } Stmt *getSubStmt(); const Stmt *getSubStmt() const { return const_cast<SwitchCase*>(this)->getSubStmt(); } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass || T->getStmtClass() == DefaultStmtClass; } }; class CaseStmt : public SwitchCase { enum { LHS, RHS, SUBSTMT, END_EXPR }; Stmt* SubExprs[END_EXPR]; // The expression for the RHS is Non-null for // GNU "case 1 ... 4" extension SourceLocation EllipsisLoc; public: CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc) : SwitchCase(CaseStmtClass, caseLoc, colonLoc) { SubExprs[SUBSTMT] = 0; SubExprs[LHS] = reinterpret_cast<Stmt*>(lhs); SubExprs[RHS] = reinterpret_cast<Stmt*>(rhs); EllipsisLoc = ellipsisLoc; } /// \brief Build an empty switch case statement. explicit CaseStmt(EmptyShell Empty) : SwitchCase(CaseStmtClass, Empty) { } SourceLocation getCaseLoc() const { return KeywordLoc; } void setCaseLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getEllipsisLoc() const { return EllipsisLoc; } void setEllipsisLoc(SourceLocation L) { EllipsisLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } Expr *getLHS() { return reinterpret_cast<Expr*>(SubExprs[LHS]); } Expr *getRHS() { return reinterpret_cast<Expr*>(SubExprs[RHS]); } Stmt *getSubStmt() { return SubExprs[SUBSTMT]; } const Expr *getLHS() const { return reinterpret_cast<const Expr*>(SubExprs[LHS]); } const Expr *getRHS() const { return reinterpret_cast<const Expr*>(SubExprs[RHS]); } const Stmt *getSubStmt() const { return SubExprs[SUBSTMT]; } void setSubStmt(Stmt *S) { SubExprs[SUBSTMT] = S; } void setLHS(Expr *Val) { SubExprs[LHS] = reinterpret_cast<Stmt*>(Val); } void setRHS(Expr *Val) { SubExprs[RHS] = reinterpret_cast<Stmt*>(Val); } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY { // Handle deeply nested case statements with iteration instead of recursion. const CaseStmt *CS = this; while (const CaseStmt *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt())) CS = CS2; return CS->getSubStmt()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[END_EXPR]); } }; class DefaultStmt : public SwitchCase { Stmt* SubStmt; public: DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt) : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {} /// \brief Build an empty default statement. explicit DefaultStmt(EmptyShell Empty) : SwitchCase(DefaultStmtClass, Empty) { } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setSubStmt(Stmt *S) { SubStmt = S; } SourceLocation getDefaultLoc() const { return KeywordLoc; } void setDefaultLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} static bool classof(const Stmt *T) { return T->getStmtClass() == DefaultStmtClass; } // Iterators child_range children() { return child_range(&SubStmt, &SubStmt+1); } }; inline SourceLocation SwitchCase::getLocEnd() const { if (const CaseStmt *CS = dyn_cast<CaseStmt>(this)) return CS->getLocEnd(); return cast<DefaultStmt>(this)->getLocEnd(); } /// LabelStmt - Represents a label, which has a substatement. For example: /// foo: return; /// class LabelStmt : public Stmt { LabelDecl *TheDecl; Stmt *SubStmt; SourceLocation IdentLoc; public: LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt) : Stmt(LabelStmtClass), TheDecl(D), SubStmt(substmt), IdentLoc(IL) { } // \brief Build an empty label statement. explicit LabelStmt(EmptyShell Empty) : Stmt(LabelStmtClass, Empty) { } SourceLocation getIdentLoc() const { return IdentLoc; } LabelDecl *getDecl() const { return TheDecl; } void setDecl(LabelDecl *D) { TheDecl = D; } const char *getName() const; Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setIdentLoc(SourceLocation L) { IdentLoc = L; } void setSubStmt(Stmt *SS) { SubStmt = SS; } SourceLocation getLocStart() const LLVM_READONLY { return IdentLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} child_range children() { return child_range(&SubStmt, &SubStmt+1); } static bool classof(const Stmt *T) { return T->getStmtClass() == LabelStmtClass; } }; /// \brief Represents an attribute applied to a statement. /// /// Represents an attribute applied to a statement. For example: /// [[omp::for(...)]] for (...) { ... } /// class AttributedStmt : public Stmt { Stmt *SubStmt; SourceLocation AttrLoc; unsigned NumAttrs; const Attr *Attrs[1]; friend class ASTStmtReader; AttributedStmt(SourceLocation Loc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt) : Stmt(AttributedStmtClass), SubStmt(SubStmt), AttrLoc(Loc), NumAttrs(Attrs.size()) { memcpy(this->Attrs, Attrs.data(), Attrs.size() * sizeof(Attr*)); } explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs) : Stmt(AttributedStmtClass, Empty), NumAttrs(NumAttrs) { memset(Attrs, 0, NumAttrs * sizeof(Attr*)); } public: static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); // \brief Build an empty attributed statement. static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs); SourceLocation getAttrLoc() const { return AttrLoc; } ArrayRef<const Attr*> getAttrs() const { return ArrayRef<const Attr*>(Attrs, NumAttrs); } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } SourceLocation getLocStart() const LLVM_READONLY { return AttrLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} child_range children() { return child_range(&SubStmt, &SubStmt + 1); } static bool classof(const Stmt *T) { return T->getStmtClass() == AttributedStmtClass; } }; /// IfStmt - This represents an if/then/else. /// class IfStmt : public Stmt { enum { VAR, COND, THEN, ELSE, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation IfLoc; SourceLocation ElseLoc; public: IfStmt(const ASTContext &C, SourceLocation IL, VarDecl *var, Expr *cond, Stmt *then, SourceLocation EL = SourceLocation(), Stmt *elsev = 0); /// \brief Build an empty if/then/else statement explicit IfStmt(EmptyShell Empty) : Stmt(IfStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "if" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// if (int x = foo()) { /// printf("x is %d", x); /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this IfStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt *>(E); } const Stmt *getThen() const { return SubExprs[THEN]; } void setThen(Stmt *S) { SubExprs[THEN] = S; } const Stmt *getElse() const { return SubExprs[ELSE]; } void setElse(Stmt *S) { SubExprs[ELSE] = S; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Stmt *getThen() { return SubExprs[THEN]; } Stmt *getElse() { return SubExprs[ELSE]; } SourceLocation getIfLoc() const { return IfLoc; } void setIfLoc(SourceLocation L) { IfLoc = L; } SourceLocation getElseLoc() const { return ElseLoc; } void setElseLoc(SourceLocation L) { ElseLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return IfLoc; } SourceLocation getLocEnd() const LLVM_READONLY { if (SubExprs[ELSE]) return SubExprs[ELSE]->getLocEnd(); else return SubExprs[THEN]->getLocEnd(); } // Iterators over subexpressions. The iterators will include iterating // over the initialization expression referenced by the condition variable. child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } static bool classof(const Stmt *T) { return T->getStmtClass() == IfStmtClass; } }; /// SwitchStmt - This represents a 'switch' stmt. /// class SwitchStmt : public Stmt { enum { VAR, COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // This points to a linked list of case and default statements. SwitchCase *FirstCase; SourceLocation SwitchLoc; /// If the SwitchStmt is a switch on an enum value, this records whether /// all the enum values were covered by CaseStmts. This value is meant to /// be a hint for possible clients. unsigned AllEnumCasesCovered : 1; public: SwitchStmt(const ASTContext &C, VarDecl *Var, Expr *cond); /// \brief Build a empty switch statement. explicit SwitchStmt(EmptyShell Empty) : Stmt(SwitchStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "switch" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// switch (int x = foo()) { /// case 0: break; /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this SwitchStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Stmt *getBody() const { return SubExprs[BODY]; } const SwitchCase *getSwitchCaseList() const { return FirstCase; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt *>(E); } Stmt *getBody() { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SwitchCase *getSwitchCaseList() { return FirstCase; } /// \brief Set the case list for this switch statement. void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; } SourceLocation getSwitchLoc() const { return SwitchLoc; } void setSwitchLoc(SourceLocation L) { SwitchLoc = L; } void setBody(Stmt *S, SourceLocation SL) { SubExprs[BODY] = S; SwitchLoc = SL; } void addSwitchCase(SwitchCase *SC) { assert(!SC->getNextSwitchCase() && "case/default already added to a switch"); SC->setNextSwitchCase(FirstCase); FirstCase = SC; } /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a /// switch over an enum value then all cases have been explicitly covered. void setAllEnumCasesCovered() { AllEnumCasesCovered = 1; } /// Returns true if the SwitchStmt is a switch of an enum value and all cases /// have been explicitly covered. bool isAllEnumCasesCovered() const { return (bool) AllEnumCasesCovered; } SourceLocation getLocStart() const LLVM_READONLY { return SwitchLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } static bool classof(const Stmt *T) { return T->getStmtClass() == SwitchStmtClass; } }; /// WhileStmt - This represents a 'while' stmt. /// class WhileStmt : public Stmt { enum { VAR, COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation WhileLoc; public: WhileStmt(const ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body, SourceLocation WL); /// \brief Build an empty while statement. explicit WhileStmt(EmptyShell Empty) : Stmt(WhileStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "while" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// while (int x = random()) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this WhileStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return WhileLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == WhileStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// DoStmt - This represents a 'do/while' stmt. /// class DoStmt : public Stmt { enum { BODY, COND, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation DoLoc; SourceLocation WhileLoc; SourceLocation RParenLoc; // Location of final ')' in do stmt condition. public: DoStmt(Stmt *body, Expr *cond, SourceLocation DL, SourceLocation WL, SourceLocation RP) : Stmt(DoStmtClass), DoLoc(DL), WhileLoc(WL), RParenLoc(RP) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[BODY] = body; } /// \brief Build an empty do-while statement. explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) { } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getDoLoc() const { return DoLoc; } void setDoLoc(SourceLocation L) { DoLoc = L; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return DoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DoStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of /// the init/cond/inc parts of the ForStmt will be null if they were not /// specified in the source. /// class ForStmt : public Stmt { enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt. SourceLocation ForLoc; SourceLocation LParenLoc, RParenLoc; public: ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, SourceLocation RP); /// \brief Build an empty for statement. explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) { } Stmt *getInit() { return SubExprs[INIT]; } /// \brief Retrieve the variable declared in this "for" statement, if any. /// /// In the following example, "y" is the condition variable. /// \code /// for (int x = random(); int y = mangle(x); ++x) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this ForStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getInit() const { return SubExprs[INIT]; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); } const Stmt *getBody() const { return SubExprs[BODY]; } void setInit(Stmt *S) { SubExprs[INIT] = S; } void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getForLoc() const { return ForLoc; } void setForLoc(SourceLocation L) { ForLoc = L; } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return ForLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ForStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// GotoStmt - This represents a direct goto. /// class GotoStmt : public Stmt { LabelDecl *Label; SourceLocation GotoLoc; SourceLocation LabelLoc; public: GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL) : Stmt(GotoStmtClass), Label(label), GotoLoc(GL), LabelLoc(LL) {} /// \brief Build an empty goto statement. explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) { } LabelDecl *getLabel() const { return Label; } void setLabel(LabelDecl *D) { Label = D; } SourceLocation getGotoLoc() const { return GotoLoc; } void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getLabelLoc() const { return LabelLoc; } void setLabelLoc(SourceLocation L) { LabelLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return GotoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GotoStmtClass; } // Iterators child_range children() { return child_range(); } }; /// IndirectGotoStmt - This represents an indirect goto. /// class IndirectGotoStmt : public Stmt { SourceLocation GotoLoc; SourceLocation StarLoc; Stmt *Target; public: IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target) : Stmt(IndirectGotoStmtClass), GotoLoc(gotoLoc), StarLoc(starLoc), Target((Stmt*)target) {} /// \brief Build an empty indirect goto statement. explicit IndirectGotoStmt(EmptyShell Empty) : Stmt(IndirectGotoStmtClass, Empty) { } void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getGotoLoc() const { return GotoLoc; } void setStarLoc(SourceLocation L) { StarLoc = L; } SourceLocation getStarLoc() const { return StarLoc; } Expr *getTarget() { return reinterpret_cast<Expr*>(Target); } const Expr *getTarget() const {return reinterpret_cast<const Expr*>(Target);} void setTarget(Expr *E) { Target = reinterpret_cast<Stmt*>(E); } /// getConstantTarget - Returns the fixed target of this indirect /// goto, if one exists. LabelDecl *getConstantTarget(); const LabelDecl *getConstantTarget() const { return const_cast<IndirectGotoStmt*>(this)->getConstantTarget(); } SourceLocation getLocStart() const LLVM_READONLY { return GotoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return Target->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == IndirectGotoStmtClass; } // Iterators child_range children() { return child_range(&Target, &Target+1); } }; /// ContinueStmt - This represents a continue. /// class ContinueStmt : public Stmt { SourceLocation ContinueLoc; public: ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass), ContinueLoc(CL) {} /// \brief Build an empty continue statement. explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) { } SourceLocation getContinueLoc() const { return ContinueLoc; } void setContinueLoc(SourceLocation L) { ContinueLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return ContinueLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return ContinueLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ContinueStmtClass; } // Iterators child_range children() { return child_range(); } }; /// BreakStmt - This represents a break. /// class BreakStmt : public Stmt { SourceLocation BreakLoc; public: BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass), BreakLoc(BL) {} /// \brief Build an empty break statement. explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) { } SourceLocation getBreakLoc() const { return BreakLoc; } void setBreakLoc(SourceLocation L) { BreakLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return BreakLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return BreakLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == BreakStmtClass; } // Iterators child_range children() { return child_range(); } }; /// ReturnStmt - This represents a return, optionally of an expression: /// return; /// return 4; /// /// Note that GCC allows return with no argument in a function declared to /// return a value, and it allows returning a value in functions declared to /// return void. We explicitly model this in the AST, which means you can't /// depend on the return type of the function and the presence of an argument. /// class ReturnStmt : public Stmt { Stmt *RetExpr; SourceLocation RetLoc; const VarDecl *NRVOCandidate; public: ReturnStmt(SourceLocation RL) : Stmt(ReturnStmtClass), RetExpr(0), RetLoc(RL), NRVOCandidate(0) { } ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate) : Stmt(ReturnStmtClass), RetExpr((Stmt*) E), RetLoc(RL), NRVOCandidate(NRVOCandidate) {} /// \brief Build an empty return expression. explicit ReturnStmt(EmptyShell Empty) : Stmt(ReturnStmtClass, Empty) { } const Expr *getRetValue() const; Expr *getRetValue(); void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt*>(E); } SourceLocation getReturnLoc() const { return RetLoc; } void setReturnLoc(SourceLocation L) { RetLoc = L; } /// \brief Retrieve the variable that might be used for the named return /// value optimization. /// /// The optimization itself can only be performed if the variable is /// also marked as an NRVO object. const VarDecl *getNRVOCandidate() const { return NRVOCandidate; } void setNRVOCandidate(const VarDecl *Var) { NRVOCandidate = Var; } SourceLocation getLocStart() const LLVM_READONLY { return RetLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RetExpr ? RetExpr->getLocEnd() : RetLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ReturnStmtClass; } // Iterators child_range children() { if (RetExpr) return child_range(&RetExpr, &RetExpr+1); return child_range(); } }; /// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt. /// class AsmStmt : public Stmt { protected: SourceLocation AsmLoc; /// \brief True if the assembly statement does not have any input or output /// operands. bool IsSimple; /// \brief If true, treat this inline assembly as having side effects. /// This assembly statement should not be optimized, deleted or moved. bool IsVolatile; unsigned NumOutputs; unsigned NumInputs; unsigned NumClobbers; Stmt **Exprs; AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, unsigned numclobbers) : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile), NumOutputs(numoutputs), NumInputs(numinputs), NumClobbers(numclobbers) { } friend class ASTStmtReader; public: /// \brief Build an empty inline-assembly statement. explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty), Exprs(0) { } SourceLocation getAsmLoc() const { return AsmLoc; } void setAsmLoc(SourceLocation L) { AsmLoc = L; } bool isSimple() const { return IsSimple; } void setSimple(bool V) { IsSimple = V; } bool isVolatile() const { return IsVolatile; } void setVolatile(bool V) { IsVolatile = V; } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } //===--- Asm String Analysis ---===// /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// unsigned getNumOutputs() const { return NumOutputs; } /// getOutputConstraint - Return the constraint string for the specified /// output operand. All output constraints are known to be non-empty (either /// '=' or '+'). StringRef getOutputConstraint(unsigned i) const; /// isOutputPlusConstraint - Return true if the specified output constraint /// is a "+" constraint (which is both an input and an output) or false if it /// is an "=" constraint (just an output). bool isOutputPlusConstraint(unsigned i) const { return getOutputConstraint(i)[0] == '+'; } const Expr *getOutputExpr(unsigned i) const; /// getNumPlusOperands - Return the number of output operands that have a "+" /// constraint. unsigned getNumPlusOperands() const; //===--- Input operands ---===// unsigned getNumInputs() const { return NumInputs; } /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. StringRef getInputConstraint(unsigned i) const; const Expr *getInputExpr(unsigned i) const; //===--- Other ---===// unsigned getNumClobbers() const { return NumClobbers; } StringRef getClobber(unsigned i) const; static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass || T->getStmtClass() == MSAsmStmtClass; } // Input expr iterators. typedef ExprIterator inputs_iterator; typedef ConstExprIterator const_inputs_iterator; inputs_iterator begin_inputs() { return &Exprs[0] + NumOutputs; } inputs_iterator end_inputs() { return &Exprs[0] + NumOutputs + NumInputs; } const_inputs_iterator begin_inputs() const { return &Exprs[0] + NumOutputs; } const_inputs_iterator end_inputs() const { return &Exprs[0] + NumOutputs + NumInputs; } // Output expr iterators. typedef ExprIterator outputs_iterator; typedef ConstExprIterator const_outputs_iterator; outputs_iterator begin_outputs() { return &Exprs[0]; } outputs_iterator end_outputs() { return &Exprs[0] + NumOutputs; } const_outputs_iterator begin_outputs() const { return &Exprs[0]; } const_outputs_iterator end_outputs() const { return &Exprs[0] + NumOutputs; } child_range children() { return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs); } }; /// This represents a GCC inline-assembly statement extension. /// class GCCAsmStmt : public AsmStmt { SourceLocation RParenLoc; StringLiteral *AsmStr; // FIXME: If we wanted to, we could allocate all of these in one big array. StringLiteral **Constraints; StringLiteral **Clobbers; IdentifierInfo **Names; friend class ASTStmtReader; public: GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, IdentifierInfo **names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, SourceLocation rparenloc); /// \brief Build an empty inline-assembly statement. explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty), Constraints(0), Clobbers(0), Names(0) { } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } //===--- Asm String Analysis ---===// const StringLiteral *getAsmString() const { return AsmStr; } StringLiteral *getAsmString() { return AsmStr; } void setAsmString(StringLiteral *E) { AsmStr = E; } /// AsmStringPiece - this is part of a decomposed asm string specification /// (for use with the AnalyzeAsmString function below). An asm string is /// considered to be a concatenation of these parts. class AsmStringPiece { public: enum Kind { String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%". Operand // Operand reference, with optional modifier %c4. }; private: Kind MyKind; std::string Str; unsigned OperandNo; public: AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {} AsmStringPiece(unsigned OpNo, char Modifier) : MyKind(Operand), Str(), OperandNo(OpNo) { Str += Modifier; } bool isString() const { return MyKind == String; } bool isOperand() const { return MyKind == Operand; } const std::string &getString() const { assert(isString()); return Str; } unsigned getOperandNo() const { assert(isOperand()); return OperandNo; } /// getModifier - Get the modifier for this operand, if present. This /// returns '\0' if there was no modifier. char getModifier() const { assert(isOperand()); return Str[0]; } }; /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing /// it into pieces. If the asm string is erroneous, emit errors and return /// true, otherwise return false. This handles canonicalization and /// translation of strings from GCC syntax to LLVM IR syntax, and handles //// flattening of named references like %[foo] to Operand AsmStringPiece's. unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces, const ASTContext &C, unsigned &DiagOffs) const; /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; } StringRef getOutputName(unsigned i) const { if (IdentifierInfo *II = getOutputIdentifier(i)) return II->getName(); return StringRef(); } StringRef getOutputConstraint(unsigned i) const; const StringLiteral *getOutputConstraintLiteral(unsigned i) const { return Constraints[i]; } StringLiteral *getOutputConstraintLiteral(unsigned i) { return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// IdentifierInfo *getInputIdentifier(unsigned i) const { return Names[i + NumOutputs]; } StringRef getInputName(unsigned i) const { if (IdentifierInfo *II = getInputIdentifier(i)) return II->getName(); return StringRef(); } StringRef getInputConstraint(unsigned i) const; const StringLiteral *getInputConstraintLiteral(unsigned i) const { return Constraints[i + NumOutputs]; } StringLiteral *getInputConstraintLiteral(unsigned i) { return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getInputExpr(i); } private: void setOutputsAndInputsAndClobbers(const ASTContext &C, IdentifierInfo **Names, StringLiteral **Constraints, Stmt **Exprs, unsigned NumOutputs, unsigned NumInputs, StringLiteral **Clobbers, unsigned NumClobbers); public: //===--- Other ---===// /// getNamedOperand - Given a symbolic operand reference like %[foo], /// translate this into a numeric value needed to reference the same operand. /// This returns -1 if the operand name is invalid. int getNamedOperand(StringRef SymbolicName) const; StringRef getClobber(unsigned i) const; StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; } const StringLiteral *getClobberStringLiteral(unsigned i) const { return Clobbers[i]; } SourceLocation getLocStart() const LLVM_READONLY { return AsmLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass; } }; /// This represents a Microsoft inline-assembly statement extension. /// class MSAsmStmt : public AsmStmt { SourceLocation LBraceLoc, EndLoc; StringRef AsmStr; unsigned NumAsmToks; Token *AsmToks; StringRef *Constraints; StringRef *Clobbers; friend class ASTStmtReader; public: MSAsmStmt(const ASTContext &C, SourceLocation asmloc, SourceLocation lbraceloc, bool issimple, bool isvolatile, ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs, ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs, StringRef asmstr, ArrayRef<StringRef> clobbers, SourceLocation endloc); /// \brief Build an empty MS-style inline-assembly statement. explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty), NumAsmToks(0), AsmToks(0), Constraints(0), Clobbers(0) { } SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation L) { LBraceLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } bool hasBraces() const { return LBraceLoc.isValid(); } unsigned getNumAsmToks() { return NumAsmToks; } Token *getAsmToks() { return AsmToks; } //===--- Asm String Analysis ---===// StringRef getAsmString() const { return AsmStr; } /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// StringRef getOutputConstraint(unsigned i) const { assert(i < NumOutputs); return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// StringRef getInputConstraint(unsigned i) const { assert(i < NumInputs); return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getInputExpr(i); } //===--- Other ---===// ArrayRef<StringRef> getAllConstraints() const { return ArrayRef<StringRef>(Constraints, NumInputs + NumOutputs); } ArrayRef<StringRef> getClobbers() const { return ArrayRef<StringRef>(Clobbers, NumClobbers); } ArrayRef<Expr*> getAllExprs() const { return ArrayRef<Expr*>(reinterpret_cast<Expr**>(Exprs), NumInputs + NumOutputs); } StringRef getClobber(unsigned i) const { return getClobbers()[i]; } private: void initialize(const ASTContext &C, StringRef AsmString, ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints, ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers); public: SourceLocation getLocStart() const LLVM_READONLY { return AsmLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == MSAsmStmtClass; } child_range children() { return child_range(&Exprs[0], &Exprs[0]); } }; class SEHExceptStmt : public Stmt { SourceLocation Loc; Stmt *Children[2]; enum { FILTER_EXPR, BLOCK }; SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); friend class ASTReader; friend class ASTStmtReader; explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) { } public: static SEHExceptStmt* Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block); SourceLocation getLocStart() const LLVM_READONLY { return getExceptLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getExceptLoc() const { return Loc; } SourceLocation getEndLoc() const { return getBlock()->getLocEnd(); } Expr *getFilterExpr() const { return reinterpret_cast<Expr*>(Children[FILTER_EXPR]); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Children[BLOCK]); } child_range children() { return child_range(Children,Children+2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHExceptStmtClass; } }; class SEHFinallyStmt : public Stmt { SourceLocation Loc; Stmt *Block; SEHFinallyStmt(SourceLocation Loc, Stmt *Block); friend class ASTReader; friend class ASTStmtReader; explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) { } public: static SEHFinallyStmt* Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block); SourceLocation getLocStart() const LLVM_READONLY { return getFinallyLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getFinallyLoc() const { return Loc; } SourceLocation getEndLoc() const { return Block->getLocEnd(); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); } child_range children() { return child_range(&Block,&Block+1); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHFinallyStmtClass; } }; class SEHTryStmt : public Stmt { bool IsCXXTry; SourceLocation TryLoc; Stmt *Children[2]; enum { TRY = 0, HANDLER = 1 }; SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try' SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); friend class ASTReader; friend class ASTStmtReader; explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) { } public: static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); SourceLocation getLocStart() const LLVM_READONLY { return getTryLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getTryLoc() const { return TryLoc; } SourceLocation getEndLoc() const { return Children[HANDLER]->getLocEnd(); } bool getIsCXXTry() const { return IsCXXTry; } CompoundStmt* getTryBlock() const { return cast<CompoundStmt>(Children[TRY]); } Stmt *getHandler() const { return Children[HANDLER]; } /// Returns 0 if not defined SEHExceptStmt *getExceptHandler() const; SEHFinallyStmt *getFinallyHandler() const; child_range children() { return child_range(Children,Children+2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHTryStmtClass; } }; /// \brief This captures a statement into a function. For example, the following /// pragma annotated compound statement can be represented as a CapturedStmt, /// and this compound statement is the body of an anonymous outlined function. /// @code /// #pragma omp parallel /// { /// compute(); /// } /// @endcode class CapturedStmt : public Stmt { public: /// \brief The different capture forms: by 'this' or by reference, etc. enum VariableCaptureKind { VCK_This, VCK_ByRef }; /// \brief Describes the capture of either a variable or 'this'. class Capture { llvm::PointerIntPair<VarDecl *, 1, VariableCaptureKind> VarAndKind; SourceLocation Loc; public: /// \brief Create a new capture. /// /// \param Loc The source location associated with this capture. /// /// \param Kind The kind of capture (this, ByRef, ...). /// /// \param Var The variable being captured, or null if capturing this. /// Capture(SourceLocation Loc, VariableCaptureKind Kind, VarDecl *Var = 0) : VarAndKind(Var, Kind), Loc(Loc) { switch (Kind) { case VCK_This: assert(Var == 0 && "'this' capture cannot have a variable!"); break; case VCK_ByRef: assert(Var && "capturing by reference must have a variable!"); break; } } /// \brief Determine the kind of capture. VariableCaptureKind getCaptureKind() const { return VarAndKind.getInt(); } /// \brief Retrieve the source location at which the variable or 'this' was /// first used. SourceLocation getLocation() const { return Loc; } /// \brief Determine whether this capture handles the C++ 'this' pointer. bool capturesThis() const { return getCaptureKind() == VCK_This; } /// \brief Determine whether this capture handles a variable. bool capturesVariable() const { return getCaptureKind() != VCK_This; } /// \brief Retrieve the declaration of the variable being captured. /// /// This operation is only valid if this capture does not capture 'this'. VarDecl *getCapturedVar() const { assert(!capturesThis() && "No variable available for 'this' capture"); return VarAndKind.getPointer(); } friend class ASTStmtReader; }; private: /// \brief The number of variable captured, including 'this'. unsigned NumCaptures; /// \brief The pointer part is the implicit the outlined function and the /// int part is the captured region kind, 'CR_Default' etc. llvm::PointerIntPair<CapturedDecl *, 1, CapturedRegionKind> CapDeclAndKind; /// \brief The record for captured variables, a RecordDecl or CXXRecordDecl. RecordDecl *TheRecordDecl; /// \brief Construct a captured statement. CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); /// \brief Construct an empty captured statement. CapturedStmt(EmptyShell Empty, unsigned NumCaptures); Stmt **getStoredStmts() const { return reinterpret_cast<Stmt **>(const_cast<CapturedStmt *>(this) + 1); } Capture *getStoredCaptures() const; void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; } public: static CapturedStmt *Create(const ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); static CapturedStmt *CreateDeserialized(const ASTContext &Context, unsigned NumCaptures); /// \brief Retrieve the statement being captured. Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; } const Stmt *getCapturedStmt() const { return const_cast<CapturedStmt *>(this)->getCapturedStmt(); } /// \brief Retrieve the outlined function declaration. CapturedDecl *getCapturedDecl() { return CapDeclAndKind.getPointer(); } const CapturedDecl *getCapturedDecl() const { return const_cast<CapturedStmt *>(this)->getCapturedDecl(); } /// \brief Set the outlined function declaration. void setCapturedDecl(CapturedDecl *D) { assert(D && "null CapturedDecl"); CapDeclAndKind.setPointer(D); } /// \brief Retrieve the captured region kind. CapturedRegionKind getCapturedRegionKind() const { return CapDeclAndKind.getInt(); } /// \brief Set the captured region kind. void setCapturedRegionKind(CapturedRegionKind Kind) { CapDeclAndKind.setInt(Kind); } /// \brief Retrieve the record declaration for captured variables. const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; } /// \brief Set the record declaration for captured variables. void setCapturedRecordDecl(RecordDecl *D) { assert(D && "null RecordDecl"); TheRecordDecl = D; } /// \brief True if this variable has been captured. bool capturesVariable(const VarDecl *Var) const; /// \brief An iterator that walks over the captures. typedef Capture *capture_iterator; typedef const Capture *const_capture_iterator; /// \brief Retrieve an iterator pointing to the first capture. capture_iterator capture_begin() { return getStoredCaptures(); } const_capture_iterator capture_begin() const { return getStoredCaptures(); } /// \brief Retrieve an iterator pointing past the end of the sequence of /// captures. capture_iterator capture_end() const { return getStoredCaptures() + NumCaptures; } /// \brief Retrieve the number of captures, including 'this'. unsigned capture_size() const { return NumCaptures; } /// \brief Iterator that walks over the capture initialization arguments. typedef Expr **capture_init_iterator; /// \brief Retrieve the first initialization argument. capture_init_iterator capture_init_begin() const { return reinterpret_cast<Expr **>(getStoredStmts()); } /// \brief Retrieve the iterator pointing one past the last initialization /// argument. capture_init_iterator capture_init_end() const { return capture_init_begin() + NumCaptures; } SourceLocation getLocStart() const LLVM_READONLY { return getCapturedStmt()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getCapturedStmt()->getLocEnd(); } SourceRange getSourceRange() const LLVM_READONLY { return getCapturedStmt()->getSourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CapturedStmtClass; } child_range children(); friend class ASTStmtReader; }; } // end namespace clang #endif
paraGraph.h
#ifndef __PARAGRAPH_H__ #define __PARAGRAPH_H__ #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <omp.h> #include "vertex_set.h" #include "graph.h" #include "mic.h" /* * edgeMap -- * * Students will implement this function. * * The input argument f is a class with the following methods defined: * bool update(Vertex src, Vertex dst) * bool cond(Vertex v) * * See apps/bfs.cpp for an example of such a class definition. * * When the argument removeDuplicates is false, the implementation of * edgeMap need not remove duplicate vertices from the VertexSet it * creates when iterating over edges. This is a performance * optimization when the application knows (and can tell ParaGraph) * that f.update() guarantees that duplicate vertices cannot appear in * the output vertex set. * * Further notes: the implementation of edgeMap is templated on the * type of this object, which allows for higher performance code * generation as these methods will be inlined. */ template <class F> static VertexSet *edgeMap(Graph g, VertexSet *u, F &f, bool removeDuplicates=true) { int numNodes = u->numNodes; int numEdges = num_edges(g); int size = u->size; int outSize = 0; //stores the results of applying functions on vertices //and scanning those results int* results = (int*) malloc(sizeof(int) * numNodes); //get number of outgoing edges to be used for top down - bottom up heuristic //and determining chunk size if(u->type == DENSE){ #pragma omp parallel for reduction(+:outSize) for(int i = 0; i < numNodes; i++){ if(u->verticesDense[i]){ outSize += outgoing_size(g,i); } } } else{ #pragma omp parallel for reduction(+:outSize) for(int i = 0; i < size; i++){ outSize += outgoing_size(g, u->verticesSparse[i]); } } VertexSet* set; //zero out results to make sure clean before we use #pragma omp parallel for schedule(static) for(int i = 0; i < u->numNodes; i++){ results[i] = 0; } //determining an appropriate chunk size based on the average number of edges //per node int chunkSize; int avgEdgeFrontier = outSize / size; int avgEdgeGraph = numEdges / numNodes; //casing on chunk size based on the average number of edges per node //compared to the average degree of a node in the graph if (avgEdgeFrontier > avgEdgeGraph){ chunkSize = 512; } else { chunkSize = 128; } //threshold for top down = bottom up heuristic int threshold = 20; //Bottom up if(outSize > numEdges / threshold){ int total = 0; //dense representation for bottom up implementation convertToDense(u); #pragma omp parallel for reduction(+:total) schedule(dynamic, chunkSize) for(int i = 0; i < numNodes; i++){ int count = 0; const Vertex* start = incoming_begin(g,i); const Vertex* end = incoming_end(g,i); for(const Vertex* v = start; v < end; v++){ if(!f.cond(i)){ break; } if(u->verticesDense[*v] && f.update(*v, i) && !results[i]){ results[i] = 1; count++; } } total += count; } set = newVertexSet(DENSE, total, numNodes); //no critical section needed because dense rep //means all threads writing to their own space #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ set->verticesDense[i] = (results[i] == 1); } set->size = total; } //Top down else{ int* scanResults = (int*) malloc(sizeof(int) * numNodes); int total = 0; //concerting to sparse for top-down implementation convertToSparse(u); #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ scanResults[i] = 0; } #pragma omp parallel for reduction(+:total) schedule(dynamic,chunkSize) for(int i = 0; i < size; i++){ int count = 0; Vertex src = u->verticesSparse[i]; const Vertex* start = outgoing_begin(g, src); const Vertex* end = outgoing_end(g, src); for(const Vertex* v = start; v < end; v++){ if(f.cond(*v) && f.update(src, *v) && !results[*v]){ results[*v] = 1; scanResults[*v] = 1; count++; } } total += count; } set = newVertexSet(SPARSE, total, numNodes); //scanning in order to add to our sparse set in parallel scan(numNodes, scanResults); #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ if(results[i]){ int idx = scanResults[i] - 1; set->verticesSparse[idx] = i; } } set->size = total; free(scanResults); } free(results); return set; } /* * vertexMap -- * * Students will implement this function. * * The input argument f is a class with the following methods defined: * bool operator()(Vertex v) * * See apps/kBFS.cpp for an example implementation. * * Note that you'll call the function on a vertex as follows: * Vertex v; * bool result = f(v) * * If returnSet is false, then the implementation of vertexMap should * return NULL (it need not build and create a vertex set) */ template <class F> static VertexSet *vertexMap(VertexSet *u, F &f, bool returnSet=true) { int numNodes = u->numNodes; if(!returnSet){ if(u->type == DENSE){ #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ if(u->verticesDense[i]){ f(i); } } } else{ #pragma omp parallel for schedule(static) for(int i = 0; i < u->size; i++){ f(u->verticesSparse[i]); } } return NULL; } bool* results = (bool*) malloc(sizeof(bool) * numNodes); #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ results[i] = false; } //always create dense set VertexSet* set; int total = 0; if(u->type == DENSE){ #pragma omp parallel for reduction(+:total) schedule(static) for(int i = 0; i < numNodes; i++){ int count = 0; if(u->verticesDense[i] && f(i)){ results[i] = true; count = 1; } total += count; } set = newVertexSet(DENSE, total, numNodes); #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ if(results[i]){ set->verticesDense[i] = true; } } set->size = total; } else{ #pragma omp parallel for reduction(+:total) schedule(static) for(int i = 0; i < u->size; i++){ int count = 0; if(f(u->verticesSparse[i])){ results[u->verticesSparse[i]] = true; count = 1; } total += count; } set = newVertexSet(DENSE, total, numNodes); #pragma omp parallel for schedule(static) for(int i = 0; i < numNodes; i++){ if(results[i]){ set->verticesDense[i] = true; } } set->size = total; } free(results); return set; } #endif /* __PARAGRAPH_H__ */
fSENSE_MEX.c
/************************************************************************** MEX function to compute the approximate gradient of the absolute value Author: R. Marc Lebel Contact: mlebel@gmail.com Date: 11/2010 Useage: imgS = absgradMEX(img,sens) Input: img: numeric array (single/double; real/complex) sens: sensitivity maps Output: imgS: multichanel image **************************************************************************/ #include "mex.h" #include <math.h> #include <string.h> #include "fast_mxArray_setup.c" #ifdef __GNU__ #include <omp.h> #endif #ifndef MAXCORES #define MAXCORES 1 #endif void mexFunction(int nlhs, mxArray *left[], int nrhs, const mxArray *right[]) { /* Declare variables */ mwSize i, j, k, t; long long r; mwSize np, nv, ns, nt, nr; mwSize indS, indIMG, indIMGS, indXY, indXYZ, indXYZT, indT1, indT2, indT3; mwSize nD, *sizeOUT; mxClassID precision; double *pSZd, *pIMGrd, *pIMGid, *pSrd, *pSid, *pIMGSrd, *pIMGSid; float *pSZf, *pIMGrf, *pIMGif, *pSrf, *pSif, *pIMGSrf, *pIMGSif; /* Get size */ nD = 5; /*mexPrintf("nD: %i\n",nD); */ if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) { pSZd = mxGetPr(right[2]); np = (int)pSZd[0]; nv = (int)pSZd[1]; ns = (int)pSZd[2]; nt = (int)pSZd[3]; nr = (int)pSZd[4]; } else { pSZf = mxGetData(right[2]); np = (int)pSZf[0]; nv = (int)pSZf[1]; ns = (int)pSZf[2]; nt = (int)pSZf[3]; nr = (int)pSZf[4]; } /*mexPrintf("size: %i x %i x %i x %i x %i\n",np,nv,ns,nt,nr);*/ /* Perform strange memory copy to replicate the size (needed for create_array_d/f) */ sizeOUT = (mwSize *)mxMalloc(nD*sizeof(mwSize)); sizeOUT[0] = np; sizeOUT[1] = nv; sizeOUT[2] = ns; sizeOUT[3] = nt; sizeOUT[4] = nr; /*mexPrintf("sizeOUT: %i x %i x %i x %i x %i\n",sizeOUT[0],sizeOUT[1],sizeOUT[2],sizeOUT[3],sizeOUT[4]);*/ /* Test for complex and obtain data class */ if (!(mxIsComplex(right[0]) & mxIsComplex(right[1]))) mexErrMsgTxt("Inputs need to be complex"); precision = mxGetClassID(right[0]); /* Get pointers to input array and create output */ if (precision == mxDOUBLE_CLASS) { pIMGrd = mxGetPr(right[0]); pIMGid = mxGetPi(right[0]); pSrd = mxGetPr(right[1]); pSid = mxGetPi(right[1]); /* Create output and assign pointers */ /*create_array_d(&(left[0]), &pIMGSrd, &pIMGSid, nD, sizeOUT, mxCOMPLEX, 0);*/ left[0] = mxCreateNumericArray(nD,sizeOUT,precision,mxCOMPLEX); pIMGSrd = mxGetPr(left[0]); pIMGSid = mxGetPi(left[0]); } else { pIMGrf = mxGetData(right[0]); pIMGif = mxGetImagData(right[0]); pSrf = mxGetData(right[1]); pSif = mxGetImagData(right[1]); /* Create output and assign pointers */ /*create_array_f(&(left[0]), &pIMGSrf, &pIMGSif, nD, sizeOUT, mxCOMPLEX, 0);*/ left[0] = mxCreateNumericArray(nD,sizeOUT,precision,mxCOMPLEX); pIMGSrf = mxGetData(left[0]); pIMGSif = mxGetImagData(left[0]); } #ifdef __GNU__ /* Set number of threads */ omp_set_num_threads(MAXCORES); #endif /* Loop through elements */ indXY = np*nv; indXYZ = np*nv*ns; indXYZT = np*nv*ns*nt; if (precision == mxDOUBLE_CLASS) { #pragma omp parallel for private(i,j,k,t,r,indT1,indT2,indT3,indIMG,indIMGS,indS) for (r=0; r<nr; r++) { for (t=0; t<nt; t++) { for (k=0; k<ns; k++) { for (j=0; j<nv; j++) { indT1 = t*indXYZ + k*indXY + j*np; indT2 = r*indXYZT + t*indXYZ + k*indXY + j*np; indT3 = r*indXYZ + k*indXY + j*np; for (i=0; i<np; i++) { indIMGS = indT2 + i; indIMG = indT1 + i; indS = indT3 + i; pIMGSrd[indIMGS] = pIMGrd[indIMG]*pSrd[indS] - pIMGid[indIMG]*pSid[indS]; pIMGSid[indIMGS] = pIMGrd[indIMG]*pSid[indS] + pIMGid[indIMG]*pSrd[indS]; } } } } } } else { #pragma omp parallel for private(i,j,k,t,r,indT1,indT2,indT3,indIMG,indIMGS,indS) for (r=0; r<nr; r++) { for (t=0; t<nt; t++) { for (k=0; k<ns; k++) { for (j=0; j<nv; j++) { indT1 = t*indXYZ + k*indXY + j*np; indT2 = r*indXYZT + t*indXYZ + k*indXY + j*np; indT3 = r*indXYZ + k*indXY + j*np; for (i=0; i<np; i++) { indIMGS = indT2 + i; indIMG = indT1 + i; indS = indT3 + i; pIMGSrf[indIMGS] = pIMGrf[indIMG]*pSrf[indS] - pIMGif[indIMG]*pSif[indS]; pIMGSif[indIMGS] = pIMGrf[indIMG]*pSif[indS] + pIMGif[indIMG]*pSrf[indS]; } } } } } } /* Free memory */ mxFree(sizeOUT); }
GB_binop__times_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__times_int32) // A.*B function (eWiseMult): GB (_AemultB_08__times_int32) // A.*B function (eWiseMult): GB (_AemultB_02__times_int32) // A.*B function (eWiseMult): GB (_AemultB_04__times_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__times_int32) // A*D function (colscale): GB (_AxD__times_int32) // D*A function (rowscale): GB (_DxB__times_int32) // C+=B function (dense accum): GB (_Cdense_accumB__times_int32) // C+=b function (dense accum): GB (_Cdense_accumb__times_int32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_int32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_int32) // C=scalar+B GB (_bind1st__times_int32) // C=scalar+B' GB (_bind1st_tran__times_int32) // C=A+scalar GB (_bind2nd__times_int32) // C=A'+scalar GB (_bind2nd_tran__times_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_TIMES || GxB_NO_INT32 || GxB_NO_TIMES_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__times_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__times_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__times_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__times_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__times_int32) ( 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 } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__times_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 *restrict Cx = (int32_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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
bins_dynamic_mpi.h
// // Project Name: Kratos // Last Modified by: $Author: pooyan $ // Date: $Date: 2007-03-27 17:02:19 $ // Revision: $Revision: 1.1.1.1 $ // // #if !defined(KRATOS_BINS_DYNAMIC_MPI_CONTAINER_H_INCLUDE) #define KRATOS_BINS_DYNAMIC_MPI_CONTAINER_H_INCLUDE #include "mpi.h" #include "spatial_containers/tree.h" #include "includes/serializer.h" #include "utilities/timer.h" namespace Kratos { /// This class its an implementation of BinsDynamic using MPI /** * Use the seam way you use the generic BinsDynamic */ template<class TConfigure> class BinsDynamicMpi { public: enum { Dimension = TConfigure::Dimension }; typedef TConfigure Configure; typedef typename TConfigure::PointType PointType; typedef typename TConfigure::PointVector ContainerType; typedef typename TConfigure::PointIterator IteratorType; typedef typename TConfigure::DistanceIterator DistanceIteratorType; typedef typename TConfigure::PtrPointType PointerType; typedef typename TConfigure::DistanceFunction DistanceFunction; typedef std::vector<PointerType> PointVector; typedef std::vector<PointVector> CellsContainerType; typedef typename PointVector::iterator PointIterator; typedef TreeNode<Dimension,PointType,PointerType,IteratorType,DistanceIteratorType> TreeNodeType; typedef typename TreeNodeType::CoordinateType CoordinateType; // double typedef typename TreeNodeType::SizeType SizeType; // std::size_t typedef typename TreeNodeType::IndexType IndexType; // std::size_t typedef TreeNodeType LeafType; typedef typename TreeNodeType::IteratorIteratorType IteratorIteratorType; typedef typename TreeNodeType::SearchStructureType SearchStructureType; typedef Tvector<IndexType,Dimension> CellType; typedef Kratos::SearchUtils::SearchNearestInRange<PointType,PointerType,PointIterator,DistanceFunction,CoordinateType> SearchNearestInRange; typedef Kratos::SearchUtils::SearchRadiusInRange<PointType,PointIterator,DistanceIteratorType,DistanceFunction,SizeType,CoordinateType,IteratorType> SearchRadiusInRange; typedef Kratos::SearchUtils::SearchBoxInRange<PointType,PointIterator,SizeType,Dimension,IteratorType> SearchBoxInRange; typedef Kratos::SearchUtils::SquaredDistanceFunction<Dimension,PointType> SquaredDistanceFunction; /// Pointer definition of BinsDynamicMpi KRATOS_CLASS_POINTER_DEFINITION(BinsDynamicMpi); /// Default constructor. /** * Empy constructor, you shouldn't use this unless you know what you are doing. */ BinsDynamicMpi() : mPointBegin(this->NullIterator()), mPointEnd(this->NullIterator()), mNumPoints(0) {}; /// ModelPart Constructor. /** * Creates and initializes BinsDynamic using the LocalMesh of the ModelPart provided as argument. * @param StaticMesh The geometry used to generate the Bins * @param ParticMesh Not used atm * @param BoxSize Size of the box * @param BucketSize default = 1 */ BinsDynamicMpi( ModelPart * StaticMesh, ModelPart * ParticMesh, CoordinateType BoxSize, SizeType BucketSize = 1 ) { MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); IteratorType mPointIterator; this->StaticMesh = StaticMesh; if (mpi_size != 1) { mPointBegin = new PointType* [StaticMesh->GetCommunicator().LocalMesh().NumberOfNodes()]; mPointEnd = mPointBegin + StaticMesh->GetCommunicator().LocalMesh().NumberOfNodes(); std::cout << "Local Mesh has: " << StaticMesh->GetCommunicator().LocalMesh().NumberOfNodes() << " Nodes" << std::endl; std::cout << "Ghost Mesh has: " << StaticMesh->GetCommunicator().GhostMesh().NumberOfNodes() << " Nodes" << std::endl; std::cout << "Full Mesh has: " << StaticMesh->NumberOfNodes() << " Nodes" << std::endl; mPointIterator = mPointBegin; for( ModelPart::NodesContainerType::iterator inode = StaticMesh->GetCommunicator().LocalMesh().NodesBegin(); inode != StaticMesh->GetCommunicator().LocalMesh().NodesEnd(); inode++, mPointIterator++) { PointType auxPoint; auxPoint[0] = inode->X(); auxPoint[1] = inode->Y(); auxPoint[2] = inode->Z(); (*mPointIterator) = new PointType(auxPoint); // std::cout << "(" << mpi_rank << ") "<< inode->Id() << " - " << inode->X() << " " << inode->Y() << " " << inode->Z() << std::endl; } } else { mPointBegin = new PointType* [StaticMesh->NumberOfNodes()]; mPointEnd = mPointBegin + StaticMesh->NumberOfNodes(); mPointIterator = mPointBegin; for( ModelPart::NodesContainerType::iterator inode = StaticMesh->NodesBegin(); inode != StaticMesh->NodesEnd(); inode++, mPointIterator++) { PointType auxPoint; auxPoint[0] = inode->X(); auxPoint[1] = inode->Y(); auxPoint[2] = inode->Z(); (*mPointIterator) = new PointType(auxPoint); } } if(mPointBegin==mPointEnd) return; mNumPoints = std::distance(mPointBegin,mPointEnd); CalculateBoundingBox(); CalculateCellSize(BoxSize); AllocateCellsContainer(); GenerateBins(); GenerateCommunicationGraph(); } //************************************************************************ /// Destructor. virtual ~BinsDynamicMpi() { char msg[12] = {'b','i','n','s','_','X','.','t','i','m','e','\0'}; msg[5] = '0' + mpi_rank; Timer::SetOuputFile(msg); Timer::PrintTimingInformation(); } //************************************************************************ /// Pointer to first element. IteratorType Begin() { return mPointBegin; } //************************************************************************ /// Pointer to last element. IteratorType End() { return mPointBegin; } //************************************************************************ /// Size of specific dimension. CoordinateType CellSize( SizeType const& iDim ) { return mCellSize[iDim]; } //************************************************************************ /// Number of cells of specific dimension. SizeType NumCell( SizeType const& iDim ) { return mN[iDim]; } //************************************************************************ /// Calcutes bounding box of particles in bins void CalculateBoundingBox() { for(SizeType i = 0 ; i < Dimension ; i++) { mMinPoint[i] = (**mPointBegin)[i]; mMaxPoint[i] = (**mPointBegin)[i]; } for(IteratorType Point = mPointBegin ; Point != mPointEnd ; Point++) { for(SizeType i = 0 ; i < Dimension ; i++) { if( (**Point)[i] < mMinPoint[i] ) mMinPoint[i] = (**Point)[i]; if( (**Point)[i] > mMaxPoint[i] ) mMaxPoint[i] = (**Point)[i]; } } } //************************************************************************ /// Calcutes cell Size void CalculateCellSize() { CoordinateType delta[Dimension]; CoordinateType alpha[Dimension]; CoordinateType mult_delta = 1.00; SizeType index = 0; for(SizeType i = 0 ; i < Dimension ; i++) { delta[i] = mMaxPoint[i] - mMinPoint[i]; if ( delta[i] > delta[index] ) index = i; delta[i] = (delta[i] == 0.00) ? 1.00 : delta[i]; } for(SizeType i = 0 ; i < Dimension ; i++){ alpha[i] = delta[i] / delta[index]; mult_delta *= alpha[i]; } mN[index] = static_cast<SizeType>( pow(static_cast<CoordinateType>(SearchUtils::PointerDistance(mPointBegin,mPointEnd)/mult_delta), 1.00/Dimension)+1 ); for(SizeType i = 0 ; i < Dimension ; i++){ if(i!=index) { mN[i] = static_cast<SizeType>(alpha[i] * mN[index]); mN[i] = ( mN[i] == 0 ) ? 1 : mN[i]; } } // for(SizeType i = 0 ; i < Dimension ; i++){ // mN[i] *= mpi_size; // } for(SizeType i = 0 ; i < Dimension ; i++){ mCellSize[i] = delta[i] / mN[i]; mInvCellSize[i] = 1.00 / mCellSize[i]; } } //************************************************************************ /// Calcutes cell Size gived the container box void CalculateCellSize( CoordinateType BoxSize ) { for(SizeType i = 0 ; i < Dimension ; i++){ mCellSize[i] = BoxSize; mInvCellSize[i] = 1.00 / mCellSize[i]; mN[i] = static_cast<SizeType>( (mMaxPoint[i]-mMinPoint[i]) / mCellSize[i]) + 1; } } //************************************************************************ void AllocateCellsContainer() { SizeType Size = 1; for(SizeType i = 0 ; i < Dimension ; i++) Size *= mN[i]; // Resize Global Container mPoints.resize(Size); } //************************************************************************ void GenerateBins(){ for(IteratorType i_point = mPointBegin ; i_point != mPointEnd ; i_point++) mPoints[CalculateIndex(**i_point)].push_back(*i_point); } void GenerateCommunicationGraph() { double * MpiMinPoints = new double[mpi_size * Dimension]; double * MpiMaxPoints = new double[mpi_size * Dimension]; double * MyMinPoint = new double[Dimension]; double * MyMaxPoint = new double[Dimension]; for(size_t i = 0; i < Dimension; i++) { MyMinPoint[i] = mMinPoint[i]; MyMaxPoint[i] = mMaxPoint[i]; } mpi_connectivity = vector<int>(mpi_size); mpi_MinPoints = vector<vector<double> >(mpi_size, vector<double>(Dimension)); mpi_MaxPoints = vector<vector<double> >(mpi_size, vector<double>(Dimension)); MPI_Allgather(MyMinPoint,Dimension,MPI_DOUBLE,MpiMinPoints,Dimension,MPI_DOUBLE,MPI_COMM_WORLD); MPI_Allgather(MyMaxPoint,Dimension,MPI_DOUBLE,MpiMaxPoints,Dimension,MPI_DOUBLE,MPI_COMM_WORLD); for(int i = 0; i < mpi_size; i++) { mpi_connectivity[i] = 0; for(size_t j = 0; j < Dimension; j++) { mpi_MinPoints[i][j] = MpiMinPoints[i * Dimension + j]; mpi_MaxPoints[i][j] = MpiMaxPoints[i * Dimension + j]; } } delete [] MpiMinPoints; delete [] MpiMaxPoints; delete [] MyMinPoint; delete [] MyMaxPoint; } void PrepareCommunications(int * NumberOfSendElements,int * NumberOfRecvElements,int * msgSendSize,int * msgRecvSize) { MPI_Alltoall(msgSendSize,1,MPI_INT,msgRecvSize,1,MPI_INT,MPI_COMM_WORLD); MPI_Alltoall(NumberOfSendElements,1,MPI_INT,NumberOfRecvElements,1,MPI_INT,MPI_COMM_WORLD); } void AsyncSendAndRecive(std::string messages[],int * msgSendSize,int * msgRecvSize) { int NumberOfCommunicationEvents = 0; int NumberOfCommunicationEventsIndex = 0; char * recvBuffers[mpi_size]; for(int j = 0; j < mpi_size; j++) { if(j != mpi_rank && msgRecvSize[j]) NumberOfCommunicationEvents++; if(j != mpi_rank && msgSendSize[j]) NumberOfCommunicationEvents++; } MPI_Request * reqs = new MPI_Request[NumberOfCommunicationEvents]; MPI_Status * stats = new MPI_Status[NumberOfCommunicationEvents]; //Set up all receive and send events for(int i = 0; i < mpi_size; i++) { if(i != mpi_rank && msgRecvSize[i]) { recvBuffers[i] = (char *)malloc(sizeof(char) * msgRecvSize[i]); MPI_Irecv(recvBuffers[i],msgRecvSize[i],MPI_CHAR,i,0,MPI_COMM_WORLD,&reqs[NumberOfCommunicationEventsIndex++]); } if(i != mpi_rank && msgSendSize[i]) { char * mpi_send_buffer = (char *)malloc(sizeof(char) * msgSendSize[i]); memcpy(mpi_send_buffer,messages[i].c_str(),msgSendSize[i]); MPI_Isend(mpi_send_buffer,msgSendSize[i],MPI_CHAR,i,0,MPI_COMM_WORLD,&reqs[NumberOfCommunicationEventsIndex++]); } } //wait untill all communications finish MPI_Waitall(NumberOfCommunicationEvents, reqs, stats); for(int i = 0; i < mpi_size; i++) { if(i != mpi_rank && msgRecvSize[i]) messages[i] = std::string(recvBuffers[i],msgRecvSize[i]); } delete [] reqs; delete [] stats; } //************************************************************************ IndexType CalculatePosition( CoordinateType const& ThisCoord, SizeType ThisDimension ) { CoordinateType d_index = (ThisCoord - mMinPoint[ThisDimension]) * mInvCellSize[ThisDimension]; IndexType index = static_cast<IndexType>( (d_index < 0.00) ? 0.00 : d_index ); return (index > mN[ThisDimension]-1) ? mN[ThisDimension]-1 : index; } //************************************************************************ IndexType CalculateIndex( PointType const& ThisPoint ) { IndexType Index = 0; for(SizeType iDim = Dimension-1 ; iDim > 0 ; iDim--){ Index += CalculatePosition(ThisPoint[iDim],iDim); Index *= mN[iDim-1]; } Index += CalculatePosition(ThisPoint[0],0); return Index; } //************************************************************************ IndexType CalculateIndex( CellType const& ThisIndex ) { IndexType Index = 0; for(SizeType iDim = Dimension-1 ; iDim > 0 ; iDim--){ Index += ThisIndex[iDim]; Index *= mN[iDim-1]; } Index += ThisIndex[0]; return Index; } //************************************************************************ CellType CalculateCell( PointType const& ThisPoint ){ CellType Cell; for(SizeType i = 0 ; i < Dimension ; i++) Cell[i] = CalculatePosition(ThisPoint[i],i); return Cell; } CellType CalculateCell( PointType const& ThisPoint, CoordinateType Radius ){ CellType Cell; for(SizeType i = 0 ; i < Dimension ; i++) Cell[i] = CalculatePosition(ThisPoint[i]+Radius,i); return Cell; } //************************************************************************ void AddPoint( PointerType const& ThisPoint ){ mPoints[CalculateIndex(*ThisPoint)].push_back(ThisPoint); mNumPoints++; } //************************************************************************ void MPI_ExistPoint( PointerType const& ThisPoint, PointerType ResultNearest, CoordinateType const Tolerance = static_cast<CoordinateType>(10.0*DBL_EPSILON) ) { PointerType Nearest, remoteNearest[mpi_size], resultNearest[mpi_size], remoteThisPoint[mpi_size]; CoordinateType Distance, remoteDistance[mpi_size], resultDistance[mpi_size]; bool Found, remoteFound[mpi_size], resultFound[mpi_size]; int msgSendSize = 0; int msgRecvSize = 0; int msgResSendSize = 0; int msgResRecvSize = 0; std::cout << "(" << mpi_rank << ") --- " << (*ThisPoint) << " --- " << std::endl; Serializer particleSerializer; particleSerializer.save("nodes",ThisPoint); std::stringstream* serializer_buffer; serializer_buffer = (std::stringstream *)particleSerializer.pGetBuffer(); msgSendSize = serializer_buffer->str().size(); MPI_Allreduce(&msgSendSize,&msgRecvSize,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD); char * mpi_send_buffer = new char[(msgRecvSize+1)]; char * mpi_recv_buffer = new char[(msgRecvSize+1) * mpi_size]; strcpy (mpi_send_buffer, serializer_buffer->str().c_str()); mpi_send_buffer[msgSendSize] = '\0'; MPI_Allgather(mpi_send_buffer,(msgRecvSize+1),MPI_CHAR,mpi_recv_buffer,(msgRecvSize+1),MPI_CHAR,MPI_COMM_WORLD); for(int i = 0; i < mpi_size; i++) { Serializer recvParticleSerializer; serializer_buffer = (std::stringstream *)recvParticleSerializer.pGetBuffer(); for(int j = 0; mpi_recv_buffer[(msgRecvSize+1)*i+j] != '\0'; j++) { (*serializer_buffer) << mpi_recv_buffer[(msgRecvSize+1)*i+j]; } remoteThisPoint[i] = new PointType(); remoteNearest[i] = new PointType(); remoteDistance[i] = static_cast<CoordinateType>(DBL_MAX); recvParticleSerializer.load("nodes",remoteThisPoint[i]); std::cout << "(" << mpi_rank << ")" << " Restored Par: " << "(" << remoteThisPoint[i]->X() << " " << remoteThisPoint[i]->Y() << " " << remoteThisPoint[i]->Z() << ")" << std::endl; SearchStructureType remote_Box( CalculateCell(*remoteThisPoint[i],-Tolerance), CalculateCell(*remoteThisPoint[i],Tolerance), mN ); SearchNearestInBox( *remoteThisPoint[i], remoteNearest[i], remoteDistance[i], remote_Box, remoteFound[i] ); std::cout << "(" << mpi_rank << ") Found point: (" << remoteThisPoint[i]->X() << " " << remoteThisPoint[i]->Y() << " " << remoteThisPoint[i]->Z() << ") from process(" << i << "): " << (*(remoteNearest[i])) << " with dist: " << remoteDistance[i] << std::endl; } std::stringstream * res_serializer_buffer[mpi_size]; for(int i = 0; i < mpi_size; i++) { Serializer resSerializer; resSerializer.save("nodes",remoteNearest[i]); res_serializer_buffer[i] = (std::stringstream *)resSerializer.pGetBuffer(); msgResSendSize = res_serializer_buffer[i]->str().size(); msgResSendSize = msgResSendSize > msgResRecvSize ? msgResSendSize : msgResRecvSize; MPI_Allreduce(&msgResSendSize,&msgResRecvSize,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD); } char mpi_res_send_buffer[((msgResRecvSize + 1) * mpi_size)]; char mpi_res_recv_buffer[((msgResRecvSize + 1) * mpi_size)]; for(int i = 0; i < mpi_size; i++) { strcpy(&mpi_res_send_buffer[(msgResRecvSize + 1) * i], res_serializer_buffer[i]->str().c_str()); mpi_res_send_buffer[(msgResRecvSize + 1) * i + res_serializer_buffer[i]->str().size()] = '\0'; } MPI_Alltoall(mpi_res_send_buffer,(msgResRecvSize+1),MPI_CHAR,mpi_res_recv_buffer,(msgResRecvSize+1),MPI_CHAR,MPI_COMM_WORLD); MPI_Alltoall(remoteDistance,1,MPI_DOUBLE,resultDistance,1,MPI_DOUBLE,MPI_COMM_WORLD); MPI_Alltoall(remoteFound,1,MPI_BYTE,resultFound,1,MPI_BYTE,MPI_COMM_WORLD); for (int i = 0; i < mpi_size; i++) { Serializer recvResParticleSerializer; serializer_buffer = (std::stringstream *)recvResParticleSerializer.pGetBuffer(); for(int j = 0; mpi_res_recv_buffer[(msgResRecvSize+1)*i+j] != '\0'; j++) { (*serializer_buffer) << mpi_res_recv_buffer[(msgResRecvSize+1)*i+j]; } resultNearest[i] = new PointType(); recvResParticleSerializer.load("nodes",resultNearest[i]); std::cout << "(" << mpi_rank << ") Result point from process (" << i << "): (" << resultNearest[i]->X() << " " << resultNearest[i]->Y() << " " << resultNearest[i]->Z() << ") with dist: " << resultDistance[i] << std::endl; } Nearest = resultNearest[0]; Distance = resultDistance[0]; Found = resultFound[0]; for(int i = 1; i < mpi_size; i++) { if(resultFound[i] && resultDistance[i] < Distance) { Nearest = resultNearest[0]; Distance = resultDistance[0]; Found = resultFound[0]; } } ResultNearest = this->NullPointer(); if(Found) ResultNearest = Nearest; delete [] mpi_send_buffer; delete [] mpi_recv_buffer; } //************************************************************************ /////////////////////////////////////////////////////////////////////////// // MPI Single Input Search /////////////////////////////////////////////////////////////////////////// void MPISingleSearchInRadiusTest(const SizeType& NumberOfPoints, const SizeType& MaxNumberOfResults, const double& Radius, const SizeType& times) { PointerType PointInput = new PointType[NumberOfPoints]; for(int i = 0; i < NumberOfPoints; i++) { PointType temp; temp[0] = (i+1)/NumberOfPoints; temp[1] = (i+1)/NumberOfPoints; temp[2] = 0; PointInput[i] = PointType(temp); } std::vector<SizeType> NumberOfResults(NumberOfPoints); std::vector<std::vector<PointerType> > Results(NumberOfPoints, std::vector<PointerType>(MaxNumberOfResults)); std::vector<std::vector<double> > ResultsDistances(NumberOfPoints, std::vector<double>(MaxNumberOfResults,0)); MPI_SearchInRadius(&PointInput[NumberOfPoints/2], Radius, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults); MPI_Barrier(MPI_COMM_WORLD); } void MPI_SearchInRadius( PointerType const& ThisPoints, CoordinateType const& Radius, std::vector<std::vector<PointerType> >& Results, std::vector<std::vector<double> >& ResultsDistances, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults) { CoordinateType Radius2 = Radius * Radius; SearchInRadiusMpiWrapperSingle( ThisPoints, 1, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults ); } //************************************************************************ // SizeType MPI_SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, IteratorType Results, // DistanceIteratorType ResultsDistances, SizeType const& MaxNumberOfResults, SearchStructureType& Box ) // { // CoordinateType Radius2 = Radius * Radius; // SizeType NumberOfResults = 0; // Box.Set( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); // SearchInRadiusMpiWrapper( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box ); // return NumberOfResults; // } //************************************************************************ // SizeType MPI_SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, // DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults ) // { // SearchStructureType Box( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); // SearchInRadiusMpiWrapper( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box); // } //************************************************************************ // SizeType MPI_SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, // DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructureType& Box ) // { // Box.Set( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); // SearchInRadiusMpiWrapper( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box); // } /////////////////////////////////////////////////////////////////////////// // MPI Single Input END /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // MPI Multiple Input Search /////////////////////////////////////////////////////////////////////////// void MPIMultiSearchInRadiusTest(const SizeType& NumberOfPoints, const SizeType& MaxNumberOfResults, const double& Radius, const SizeType& times) { //MultiSearch Test Timer::Start("ALL"); PointerType PointInput = new PointType[NumberOfPoints]; for (ModelPart::ElementsContainerType::iterator el_it = StaticMesh->ElementsBegin(); el_it != StaticMesh->ElementsEnd() && el_it-StaticMesh->ElementsBegin() < NumberOfPoints; el_it++) { PointType temp; Geometry<Node < 3 > >& geom = el_it->GetGeometry(); temp[0] = (geom[0].X() + geom[1].X() + geom[2].X() + geom[3].X())/4; temp[1] = (geom[0].Y() + geom[1].Y() + geom[2].Y() + geom[3].Y())/4; temp[2] = (geom[0].Z() + geom[1].Z() + geom[2].Z() + geom[3].Z())/4; PointInput[el_it-StaticMesh->ElementsBegin()] = PointType(temp); } int rest = 0; for(size_t i = 0; i < times; i++) { std::vector<SizeType> NumberOfResults(NumberOfPoints); std::vector<std::vector<PointerType> > Results(NumberOfPoints, std::vector<PointerType>(MaxNumberOfResults)); std::vector<std::vector<double> > ResultsDistances(NumberOfPoints, std::vector<double>(MaxNumberOfResults,0)); MPI_SearchInRadius(PointInput, NumberOfPoints, Radius, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults); MPI_Barrier(MPI_COMM_WORLD); if(i == times-1) { size_t max = 0; size_t min = MaxNumberOfResults; //Check Results for(size_t i = 0; i < NumberOfPoints; i++) { rest += NumberOfResults[i]; max = NumberOfResults[i] > max ? NumberOfResults[i] : max; min = NumberOfResults[i] < min ? NumberOfResults[i] : min; } std::cout << "(" << mpi_rank << ") Found: " << rest << " results, aprox " << rest/NumberOfPoints << " results per point. Max: " << max << " Min: " << min << std::endl; } } int total_size = 0; int total_resu = 0; int local_size = NumberOfPoints; int local_resu = rest; MPI_Allreduce(&local_size,&total_size,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); MPI_Allreduce(&local_resu,&total_resu,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD); if(mpi_rank == 0) std::cout << "Total Point search: " << total_size << " " << total_resu << std::endl; Timer::Stop("ALL"); } void MPI_SearchInRadius( PointerType const& ThisPoints, SizeType const& NumberOfPoints, CoordinateType const& Radius, std::vector<std::vector<PointerType> >& Results, std::vector<std::vector<double> >& ResultsDistances, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults) { CoordinateType Radius2 = Radius * Radius; SearchInRadiusMpiWrapperSingle( ThisPoints, NumberOfPoints, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults ); } /// Act as wrapper between external function and its implementation /** * This function provides all mpi functionality requiered to execute the parallel multi input searchInRaidus. * the method implemented by this function is one-to-many. It means all particles not found in the local * processes are send to all process intersecting the search radius of the particle * @param ThisPoints List of points to be search * @param NumberOfPoints Number of points to be search * @param Radius Radius of search * @param Radius2 Radius of search^2 * @param Results List of results * @param ResultsDistances Distance of the results * @param NumberOfResults Number of results * @param MaxNumberOfResults Maximum number of results returned for each point */ void SearchInRadiusMpiWrapperSingle( PointerType const& ThisPoints, SizeType const& NumberOfPoints, CoordinateType const& Radius, CoordinateType const& Radius2, std::vector<std::vector<PointerType> >& Results, std::vector<std::vector<double> >& ResultsDistances, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults ) { std::vector<std::vector<PointerType> > remoteResults(mpi_size, std::vector<PointerType>(0)); std::vector<std::vector<PointerType> > SearchPetitions(mpi_size, std::vector<PointerType>(0)); std::vector<std::vector<PointerType> > SearchResults(mpi_size, std::vector<PointerType>(0)); std::vector<std::vector<PointerType> > SendPointToProcess(mpi_size, std::vector<PointerType>(0)); std::string messages[mpi_size]; int NumberOfSendPoints[mpi_size]; int NumberOfRecvPoints[mpi_size]; std::vector<bool> SendPoint(NumberOfPoints*mpi_size); int msgSendSize[mpi_size]; int msgRecvSize[mpi_size]; PointerType CommunicationToken = new PointType(); CommunicationToken->X() = std::numeric_limits<double>::max(); for(int i = 0; i < mpi_size; i++) { NumberOfSendPoints[i] = 0; msgSendSize[i] = 0; } //Local search Timer::Start("Calculate Local"); for(size_t i = 0; i < NumberOfPoints; i++) { IteratorType ResultsPointer = &Results[i][0]; double * ResultsDistancesPointer = &ResultsDistances[i][0]; NumberOfResults[i] = 0; SearchStructureType Box( CalculateCell(ThisPoints[i],-Radius), CalculateCell(ThisPoints[i],Radius), mN ); SearchInRadiusLocal(ThisPoints[i],Radius,Radius2,ResultsPointer,ResultsDistancesPointer,NumberOfResults[i],MaxNumberOfResults,Box); //For each point with results < MaxResults and each process excluding ourself if(NumberOfResults[i] < MaxNumberOfResults) { for(int j = 0; j < mpi_size; j++) { if(j != mpi_rank) { int intersect = 0; for(size_t k = 0; k < Dimension; k++) if((ThisPoints[i][k]+Radius >= mpi_MaxPoints[j][k] && ThisPoints[i][k]-Radius <= mpi_MaxPoints[j][k]) || (ThisPoints[i][k]+Radius >= mpi_MinPoints[j][k] && ThisPoints[i][k]-Radius <= mpi_MinPoints[j][k]) || (ThisPoints[i][k]-Radius >= mpi_MinPoints[j][k] && ThisPoints[i][k]+Radius <= mpi_MaxPoints[j][k]) ) intersect++; SendPoint[j*NumberOfPoints+i] = 0; if(intersect == Dimension) { SendPoint[j*NumberOfPoints+i]=1; NumberOfSendPoints[j]++; } } } } } for(int i = 0; i < mpi_size; i++) { if(i != mpi_rank && NumberOfSendPoints[i]) { int k = 0; SendPointToProcess[i].resize(NumberOfSendPoints[i]); for(size_t j = 0; j < NumberOfPoints; j++) if(SendPoint[i*NumberOfPoints+j]) SendPointToProcess[i][k++] = &ThisPoints[j]; } } Timer::Stop("Calculate Local"); Timer::Start("Transfer Particles"); // for(int i = 0; i < mpi_size; i++) // { // if(mpi_rank != i) // TConfigure::Save(SendPointToProcess[i],messages[i]); // msgSendSize[i] = messages[i].size(); // } // // PrepareCommunications(msgSendSize,msgRecvSize,NumberOfSendPoints,NumberOfRecvPoints); // AsyncSendAndRecive(messages,msgSendSize,msgRecvSize); // // for(int i = 0; i < mpi_size; i++) // { // if(mpi_rank != i && messages[i].size()) // TConfigure::Load(SearchPetitions[i],messages[i]); // } TConfigure::AsyncSendAndRecive(SendPointToProcess,SearchPetitions,msgSendSize,msgRecvSize); Timer::Stop("Transfer Particles"); Timer::Start("Calculate Remote"); //Calculate remote points for(int i = 0; i < mpi_size; i++) { if(i != mpi_rank && msgRecvSize[i]) { int accum_results = 0; NumberOfRecvPoints[i] = SearchPetitions[i].size(); std::vector<PointerType>& remoteSearchPetitions = SearchPetitions[i]; remoteResults[i].resize((MaxNumberOfResults+1)*NumberOfRecvPoints[i]); for(int j = 0; j < NumberOfRecvPoints[i]; j++) { IteratorType remoteResultsPointer = &remoteResults[i][accum_results]; PointType remotePointPointer = *remoteSearchPetitions[j]; SizeType thisNumberOfResults = 0; SearchStructureType Box( CalculateCell(remotePointPointer,-Radius), CalculateCell(remotePointPointer,Radius), mN ); SearchInRadiusLocal(remotePointPointer,Radius,Radius2,remoteResultsPointer,thisNumberOfResults,MaxNumberOfResults,Box); accum_results += thisNumberOfResults; remoteResults[i][accum_results++] = CommunicationToken; } remoteResults[i].resize(accum_results); NumberOfSendPoints[i] = accum_results; } } Timer::Stop("Calculate Remote"); Timer::Start("Transfer Results"); for(int i = 0; i < mpi_size; i++) { if(mpi_rank != i) TConfigure::Save(remoteResults[i],messages[i]); msgSendSize[i] = messages[i].size(); } PrepareCommunications(msgSendSize,msgRecvSize,NumberOfSendPoints,NumberOfRecvPoints); AsyncSendAndRecive(messages,msgSendSize,msgRecvSize); for(int i = 0; i < mpi_size; i++) { if(mpi_rank != i && messages[i].size()) TConfigure::Load(SearchResults[i],messages[i]); } Timer::Stop("Transfer Results"); Timer::Start("Prepare-C"); for (int i = 0; i < mpi_size; i++) { if (i != mpi_rank) { std::vector<PointerType>& remoteSearchResults = SearchResults[i]; int result_iterator = 0; for(size_t j = 0; j < NumberOfPoints; j++) { if(SendPoint[i*NumberOfPoints+j]) { int token = 0; for(; !token && result_iterator < NumberOfRecvPoints[i]; result_iterator++) { PointType& a = ThisPoints[j]; PointType& b = *remoteSearchResults[result_iterator]; if(b.X() == std::numeric_limits<double>::max()) token = 1; if (!token) { double dist = DistanceFunction()(a,b); if (dist <= Radius2) { if (NumberOfResults[j] < MaxNumberOfResults) { Results[j][NumberOfResults[j]] = remoteSearchResults[result_iterator]; ResultsDistances[j][NumberOfResults[j]] = dist; NumberOfResults[j]++; } } } } } } } } Timer::Stop("Prepare-C"); } /////////////////////////////////////////////////////////////////////////// // MPI Search In Radius /////////////////////////////////////////////////////////////////////////// PointerType ExistPoint( PointerType const& ThisPoint, CoordinateType const Tolerance = static_cast<CoordinateType>(10.0*DBL_EPSILON) ) { PointerType Nearest; CoordinateType Distance = static_cast<CoordinateType>(DBL_MAX); bool Found; SearchStructureType Box( CalculateCell(*ThisPoint,-Tolerance), CalculateCell(*ThisPoint,Tolerance), mN ); SearchNearestInBox( *ThisPoint, Nearest, Distance, Box, Found ); if(Found) return Nearest; return this->NullPointer(); } //************************************************************************ PointerType SearchNearestPoint( PointType const& ThisPoint ) { if( mPointBegin == mPointEnd ) return this->NullPointer(); PointerType Result = *mPointBegin; CoordinateType ResultDistance = static_cast<CoordinateType>(DBL_MAX); SearchStructureType Box( CalculateCell(ThisPoint), mN ); SearchNearestPointLocal( ThisPoint, Result, ResultDistance, Box ); return Result; } //************************************************************************ PointerType SearchNearestPoint( PointType const& ThisPoint, CoordinateType ResultDistance ) { if( mPointBegin == mPointEnd ) return this->NullPointer(); PointerType Result = *mPointBegin; ResultDistance = static_cast<CoordinateType>(DBL_MAX); SearchStructureType Box( CalculateCell(ThisPoint), mN ); SearchNearestPointLocal( ThisPoint, Result, ResultDistance, Box); return Result; } //************************************************************************ // New Thread Safe!!! PointerType SearchNearestPoint( PointType const& ThisPoint, CoordinateType& rResultDistance, SearchStructureType& Box ) { PointerType Result = *mPointBegin; //static_cast<PointerType>(NULL); rResultDistance = static_cast<CoordinateType>(DBL_MAX); Box.Set( CalculateCell(ThisPoint), mN ); SearchNearestPointLocal( ThisPoint, Result, rResultDistance, Box); return Result; } //************************************************************************ void SearchNearestPoint( PointType const& ThisPoint, PointerType& rResult, CoordinateType& rResultDistance ) { SearchStructureType Box; Box.Set( CalculateCell(ThisPoint), mN ); SearchNearestPointLocal(ThisPoint,rResult,rResultDistance,Box); } //************************************************************************ void SearchNearestPoint( PointType const& ThisPoint, PointerType& rResult, CoordinateType& rResultDistance, SearchStructureType& Box ) { // This case is when BinStatic is a LeafType in Other Spacial Structure // Then, it is possible a better Result before this search Box.Set( CalculateCell(ThisPoint), mN ); SearchNearestPointLocal( ThisPoint, rResult, rResultDistance, Box ); } //************************************************************************ void SearchNearestPointLocal( PointType const& ThisPoint, PointerType& rResult, CoordinateType& rResultDistance, SearchStructureType& Box ) { if( mPointBegin == mPointEnd ) return; bool Found = false; // set mBox Box.Set( CalculateCell(ThisPoint), mN ); // initial search ++Box; SearchNearestInBox( ThisPoint, rResult, rResultDistance, Box, Found ); // increase mBox and try again while(!Found) { ++Box; SearchNearestInBox( ThisPoint, rResult, rResultDistance, Box, Found ); } } //************************************************************************ SizeType SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, IteratorType Results, DistanceIteratorType ResultsDistances, SizeType const& MaxNumberOfResults ) { CoordinateType Radius2 = Radius * Radius; SizeType NumberOfResults = 0; SearchStructureType Box( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } //************************************************************************ SizeType SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, IteratorType Results, DistanceIteratorType ResultsDistances, SizeType const& MaxNumberOfResults, SearchStructureType& Box ) { CoordinateType Radius2 = Radius * Radius; SizeType NumberOfResults = 0; Box.Set( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } //************************************************************************ void SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults ) { SearchStructureType Box( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box); } //************************************************************************ void SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructureType& Box ) { Box.Set( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box); } //************************************************************************ // **** THREAD SAFE // Dimension = 1 void SearchInRadiusLocal( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,ResultsDistances,NumberOfResults,MaxNumberOfResults); } // Dimension = 2 void SearchInRadiusLocal( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,ResultsDistances,NumberOfResults,MaxNumberOfResults); } // Dimension = 3 void SearchInRadiusLocal( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,ResultsDistances,NumberOfResults,MaxNumberOfResults); } //************************************************************************ /////////////////////////////////////////////////////////////////////////// // Multiple Input Search /////////////////////////////////////////////////////////////////////////// void MultiSearchInRadiusTest(const SizeType& NumberOfPoints, const SizeType& MaxNumberOfResults, const double& Radius, const SizeType& times) { //MultiSearch Test Timer::Start("ALL"); PointerType PointInput = new PointType[NumberOfPoints]; // std::vector<IteratorType Results>(NumberOfPoints * MaxNumberOfResults); // std::vector<std::vector<PointerType> > Results(NumberOfPoints, std::vector<PointerType>(MaxNumberOfResults)); // std::vector<std::vector<double> > ResultsDistances(NumberOfPoints, std::vector<double>(MaxNumberOfResults,0)); for (ModelPart::ElementsContainerType::iterator el_it = StaticMesh->ElementsBegin(); el_it != StaticMesh->ElementsEnd() && el_it-StaticMesh->ElementsBegin() < NumberOfPoints; el_it++) { PointType temp; Geometry<Node < 3 > >& geom = el_it->GetGeometry(); temp[0] = (geom[0].X() + geom[1].X() + geom[2].X() + geom[3].X())/4; temp[1] = (geom[0].Y() + geom[1].Y() + geom[2].Y() + geom[3].Y())/4; temp[2] = (geom[0].Z() + geom[1].Z() + geom[2].Z() + geom[3].Z())/4; PointInput[el_it-StaticMesh->ElementsBegin()] = PointType(temp); } int rest = 0; #pragma omp parallel for reduction(+:rest) for(size_t i = 0; i < NumberOfPoints; i++) { IteratorType Results = new PointerType[MaxNumberOfResults]; DistanceIteratorType Distances = new double[MaxNumberOfResults]; PointType mypoint = PointInput[i]; // IteratorType rest += SearchInRadius(mypoint, Radius, Results, Distances, MaxNumberOfResults); } std::cout << "Rest: " << rest << std::endl; Timer::Stop("ALL"); } SizeType SearchInRadius( PointerType const& ThisPoints, SizeType const& NumberOfPoints, CoordinateType const& Radius, std::vector<std::vector<PointerType> > Results, std::vector<std::vector<double> > ResultsDistances, SizeType const& MaxNumberOfResults ) { CoordinateType Radius2 = Radius * Radius; SizeType NumberOfResults = 0; /*SearchStructureType Box[NumberOfPoints]*/; // for(size_t i = 0; i < NumberOfPoints; i++) // Box[i] = SearchStructureType( CalculateCell(ThisPoints[i],-Radius), CalculateCell(ThisPoints[i],Radius), mN ); // SearchInRadiusLocal( ThisPoints, NumberOfPoints, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults/*, Box*/ ); return NumberOfResults; } //************************************************************************ SizeType SearchInRadius( PointerType const& ThisPoints, SizeType const& NumberOfPoints, CoordinateType const& Radius, IteratorType Results, DistanceIteratorType ResultsDistances, SizeType const& MaxNumberOfResults, SearchStructureType Box[] ) { CoordinateType Radius2 = Radius * Radius; SizeType NumberOfResults = 0; for(size_t i = 0; i < NumberOfPoints; i++) Box[i].Set( CalculateCell(ThisPoints[i],-Radius), CalculateCell(ThisPoints[i],Radius), mN ); SearchInRadiusLocal( ThisPoints, NumberOfPoints, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } //************************************************************************ void SearchInRadius( PointerType const& ThisPoints, SizeType const& NumberOfPoints, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults ) { SearchStructureType Box[NumberOfPoints]; for(size_t i = 0; i < NumberOfPoints; i++) Box[i] = SearchStructureType( CalculateCell(ThisPoints[i],-Radius), CalculateCell(ThisPoints[i],Radius), mN ); SearchInRadiusLocal( ThisPoints, NumberOfPoints, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Box); } //************************************************************************ void SearchInRadius( PointerType const& ThisPoints, SizeType const& NumberOfPoints, CoordinateType const& Radius, CoordinateType const& Radius2, std::vector<std::vector<PointerType> >& Results, std::vector<std::vector<double> >& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults /*, SearchStructureType Box[]*/ ) { // for(size_t i = 0; i < NumberOfPoints; i++) // Box[i].Set( CalculateCell(ThisPoints[i],-Radius), CalculateCell(ThisPoints[i],Radius), mN ); SearchInRadiusLocal( ThisPoints, NumberOfPoints, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults); } //************************************************************************ // Dimension = 1 void SearchInRadiusLocal( PointerType const& ThisPoint, SizeType const& NumberOfPoints, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { for(size_t i = 0; i < NumberOfPoints; i++) { SizeType thisNumberOfResults = 0; IteratorType ResulPointer = &Results[NumberOfResults]; DistanceIteratorType ResultsDistancesPointer = &ResultsDistances[NumberOfResults]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,ResultsDistances,NumberOfResults,MaxNumberOfResults); NumberOfResults += thisNumberOfResults; } } // Dimension = 2 void SearchInRadiusLocal( PointerType const& ThisPoint, SizeType const& NumberOfPoints, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { for(size_t i = 0; i < NumberOfPoints; i++) { SizeType thisNumberOfResults = 0; IteratorType ResulPointer = &Results[NumberOfResults]; DistanceIteratorType ResultsDistancesPointer = &ResultsDistances[NumberOfResults]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,ResultsDistances,NumberOfResults,MaxNumberOfResults); NumberOfResults += thisNumberOfResults; } } // Dimension = 3 void SearchInRadiusLocal( PointerType const& ThisPoint, SizeType const& NumberOfPoints, CoordinateType const& Radius, CoordinateType const& Radius2, std::vector<std::vector<PointerType> > Results, std::vector<std::vector<double> > ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults /*, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3> * const& Box*/ ) { int ompSafe_NumberOfResults = 0; // #pragma omp parallel for reduction(+:ompSafe_NumberOfResults) for(size_t i = 0; i < NumberOfPoints; i++) { SizeType thisNumberOfResults = 0; IteratorType ResulPointer = &Results[i][0]; DistanceIteratorType ResultsDistancesPointer = &ResultsDistances[i][0]; SearchStructureType Box; Box.Set( CalculateCell(ThisPoint[i],-Radius), CalculateCell(ThisPoint[i],Radius), mN ); for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) { SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint[i],Radius2,ResulPointer,ResultsDistancesPointer,thisNumberOfResults,MaxNumberOfResults); } ompSafe_NumberOfResults += thisNumberOfResults; } NumberOfResults = ompSafe_NumberOfResults; } /////////////////////////////////////////////////////////////////////////// // Thread Safe ? /////////////////////////////////////////////////////////////////////////// //************************************************************************ SizeType SearchInRadius( PointType const& ThisPoint, CoordinateType Radius, IteratorType Results, SizeType MaxNumberOfResults ) { CoordinateType Radius2 = Radius * Radius; SizeType NumberOfResults = 0; SearchStructureType Box( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } //************************************************************************ SizeType SearchInRadius( PointType const& ThisPoint, CoordinateType Radius, IteratorType Results, SizeType MaxNumberOfResults, SearchStructureType& Box ) { CoordinateType Radius2 = Radius * Radius; SizeType NumberOfResults = 0; Box.Set( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } //************************************************************************ void SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults ) { SearchStructureType Box( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Box ); } //************************************************************************ void SearchInRadius( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructureType& Box ) { Box.Set( CalculateCell(ThisPoint,-Radius), CalculateCell(ThisPoint,Radius), mN ); SearchInRadiusLocal( ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Box ); } //************************************************************************ // **** THREAD SAFE // Dimension = 1 void SearchInRadiusLocal( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I++ ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,NumberOfResults,MaxNumberOfResults); } // Dimension = 2 void SearchInRadiusLocal( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I++ ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,NumberOfResults,MaxNumberOfResults); } // Dimension = 3 void SearchInRadiusLocal( PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I++ ) SearchRadiusInRange()(mPoints[I].begin(),mPoints[I].end(),ThisPoint,Radius2,Results,NumberOfResults,MaxNumberOfResults); } //************************************************************************ //************************************************************************ // Dimension = 1 void SearchNearestInBox( PointType const& ThisPoint, PointerType& ResultPoint, CoordinateType& ResultDistance, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box, bool& Found ) { Found = false; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchNearestInRange()( mPoints[I].begin(), mPoints[I].end(), ThisPoint, ResultPoint, ResultDistance, Found ); } // Dimension = 2 void SearchNearestInBox( PointType const& ThisPoint, PointerType& ResultPoint, CoordinateType& ResultDistance, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box, bool& Found ) { Found = false; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchNearestInRange()( mPoints[I].begin(), mPoints[I].end(), ThisPoint, ResultPoint, ResultDistance, Found ); } // Dimension = 3 void SearchNearestInBox( PointType const& ThisPoint, PointerType& ResultPoint, CoordinateType& ResultDistance, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box, bool& Found ) { Found = false; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchNearestInRange()( mPoints[I].begin(), mPoints[I].end(), ThisPoint, ResultPoint, ResultDistance, Found ); } //************************************************************************ //************************************************************************ SizeType SearchInBox( PointType const& SearchMinPoint, PointType const& SearchMaxPoint, IteratorType Results, SizeType MaxNumberOfResults ) { SizeType NumberOfResults = 0; SearchStructureType Box( CalculateCell(SearchMinPoint), CalculateCell(SearchMaxPoint), mN ); SearchInBoxLocal( SearchMinPoint, SearchMaxPoint, Results, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } //************************************************************************ void SearchInBox(PointType const& SearchMinPoint, PointType const& SearchMaxPoint, IteratorType& Results, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults ) { NumberOfResults = 0; SearchStructureType Box( CalculateCell(SearchMinPoint), CalculateCell(SearchMaxPoint), mN ); SearchInBoxLocal( SearchMinPoint, SearchMaxPoint, Results, NumberOfResults, MaxNumberOfResults, Box ); } //************************************************************************ // Dimension = 1 void SearchInBoxLocal( PointType const& SearchMinPoint, PointType const& SearchMaxPoint, IteratorType& ResultsPoint, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchBoxInRange()(SearchMinPoint,SearchMaxPoint,mPoints[I].begin(),mPoints[I].end(),ResultsPoint,NumberOfResults,MaxNumberOfResults); } // Dimension = 2 void SearchInBoxLocal( PointType const& SearchMinPoint, PointType const& SearchMaxPoint, IteratorType& ResultsPoint, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchBoxInRange()(SearchMinPoint,SearchMaxPoint,mPoints[I].begin(),mPoints[I].end(),ResultsPoint,NumberOfResults,MaxNumberOfResults); } // Dimension = 3 void SearchInBoxLocal( PointType const& SearchMinPoint, PointType const& SearchMaxPoint, IteratorType& ResultsPoint, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) SearchBoxInRange()(SearchMinPoint,SearchMaxPoint,mPoints[I].begin(),mPoints[I].end(),ResultsPoint,NumberOfResults,MaxNumberOfResults); } //************************************************************************ /// Turn back information as a string. virtual std::string Info() const { return "BinsDynamicMpi"; } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { rOStream << "BinsDynamicMpi"; } /// Print object's data. virtual void PrintData(std::ostream& rOStream, std::string const& Perfix = std::string()) const { rOStream << Perfix << "Bin[" << SearchUtils::PointerDistance(mPointBegin, mPointEnd) << "] : " << std::endl; for(typename CellsContainerType::const_iterator i_cell = mPoints.begin() ; i_cell != mPoints.end() ; i_cell++) { rOStream << Perfix << "[ " ; for(typename PointVector::const_iterator i_point = i_cell->begin() ; i_point != i_cell->end() ; i_point++) rOStream << **i_point << " "; rOStream << " ]" << std::endl; } rOStream << std::endl; } /// Print Size of Container void PrintSize( std::ostream& rout ){ rout << " BinsSize: "; for(SizeType i = 0 ; i < Dimension ; i++) rout << "[" << mN[i] << "]"; rout << std::endl; } /// Print Limits Points of the Container void PrintBox( std::ostream& rout ){ rout << " BinsBox: Min ["; mMinPoint.Print(rout); rout << "]; Max ["; mMaxPoint.Print(rout); rout << "]; Size ["; mCellSize.Print(rout); rout << "]" << std::endl; } /// Assignment operator. BinsDynamicMpi& operator=(BinsDynamicMpi const& rOther); /// Copy constructor. BinsDynamicMpi(BinsDynamicMpi const& rOther); private: IteratorType mPointBegin; IteratorType mPointEnd; Tvector<CoordinateType,Dimension> mMinPoint; Tvector<CoordinateType,Dimension> mMaxPoint; Tvector<CoordinateType,Dimension> mCellSize; Tvector<CoordinateType,Dimension> mInvCellSize; Tvector<SizeType,Dimension> mN; SizeType mNumPoints; ModelPart * StaticMesh; // Bins Access Vector ( vector<Iterator> ) CellsContainerType mPoints; // Work Variables ( For non-copy of Search Variables ) //BinBox SearchBox; //MPI interface int mpi_rank; int mpi_size; //MPI Communication vector<int> mpi_connectivity; vector<vector<double> > mpi_MinPoints; vector<vector<double> > mpi_MaxPoints; public: // static TreeNodeType* Construct(IteratorType PointsBegin, IteratorType PointsEnd, PointType MaxPoint, PointType MinPoint, SizeType BucketSize) // { // // SizeType number_of_points = SearchUtils::PointerDistance(PointsBegin,PointsEnd); // if (number_of_points == 0) // return NULL; // else // { // return new BinsDynamicMpi( PointsBegin, PointsEnd, MinPoint, MaxPoint, BucketSize ); // } // // } }; template<class TConfigure> std::ostream & operator<<( std::ostream& rOStream, BinsDynamicMpi<TConfigure>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintSize(rOStream); rThis.PrintData(rOStream); return rOStream; } } #endif // KRATOS_BINS_DYNAMIC_MPI_CONTAINER_H_INCLUD
npdot.c
#include <stdlib.h> #include <string.h> //#include <omp.h> #include "config.h" #include "vhf/fblas.h" #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) /* * numpy.dot may call unoptimized blas */ void NPdgemm(const char trans_a, const char trans_b, const int m, const int n, const int k, const int lda, const int ldb, const int ldc, const int offseta, const int offsetb, const int offsetc, double *a, double *b, double *c, const double alpha, const double beta) { a += offseta; b += offsetb; c += offsetc; size_t stride; int nthread = 1; int i, di, nblk; if ((k/m) > 3 && (k/n) > 3) { // parallelize k const double D0 = 0; double *cpriv; int ij, j, stride_b; if (trans_a == 'N') { stride = lda; } else { stride = 1; } if (trans_b == 'N') { stride_b = 1; } else { stride_b = ldb; } if (beta == 0) { for (i = 0; i < n; i++) { memset(c+i*ldc, 0, sizeof(double)*m); } } else { for (i = 0; i < n; i++) { for (j = 0; j < m; j++, ij++) { c[i*ldc+j] *= beta; } } } #pragma omp parallel default(none) \ shared(a, b, c, stride, stride_b, nthread, nblk) \ private(i, ij, j, di, cpriv) { nthread = omp_get_num_threads(); nblk = MAX((k+nthread-1) / nthread, 1); cpriv = malloc(sizeof(double) * m * n); #pragma omp for for (i = 0; i < nthread; i++) { di = MIN(nblk, k-i*nblk); if (di > 0) { dgemm_(&trans_a, &trans_b, &m, &n, &di, &alpha, a+stride*i*nblk, &lda, b+stride_b*i*nblk, &ldb, &D0, cpriv, &m); } } #pragma omp critical if (di > 0) { for (ij = 0, i = 0; i < n; i++) { for (j = 0; j < m; j++, ij++) { c[i*ldc+j] += cpriv[ij]; } } } free(cpriv); } } else if (m > n+4) { // parallelize m if (trans_a == 'N') { stride = 1; } else { stride = lda; } #pragma omp parallel default(none) \ shared(a, b, c, stride, nthread, nblk) \ private(i, di) { nthread = omp_get_num_threads(); nblk = MAX((m+nthread-1) / nthread, 1); nthread = (m+nblk-1) / nblk; #pragma omp for for (i = 0; i < nthread; i++) { di = MIN(nblk, m-i*nblk); if (di > 0) { dgemm_(&trans_a, &trans_b, &di, &n, &k, &alpha, a+stride*i*nblk, &lda, b, &ldb, &beta, c+i*nblk, &ldc); } } } } else { // parallelize n if (trans_b == 'N') { stride = ldb; } else { stride = 1; } #pragma omp parallel default(none) \ shared(a, b, c, stride, nthread, nblk) \ private(i, di) { nthread = omp_get_num_threads(); nblk = MAX((n+nthread-1) / nthread, 1); nthread = (n+nblk-1) / nblk; #pragma omp for for (i = 0; i < nthread; i++) { di = MIN(nblk, n-i*nblk); if (di > 0) { dgemm_(&trans_a, &trans_b, &m, &di, &k, &alpha, a, &lda, b+stride*i*nblk, &ldb, &beta, c+ldc*i*nblk, &ldc); } } } } }
main.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 <io.h> #include <math.h> #include <float.h> #include <limits.h> #include "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 1000000 #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; size_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. */ double mysecond() { struct timeval tp; gettimeofday(&tp, NULL); 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; size_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) = %zu\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
BlockMatching_private_main.h
#include <algorithm> #include <cfloat> #include <cmath> #include <cstdio> #include <iostream> #include <list> #include <new> #include <stdexcept> #if defined(_OPENMP) #include <omp.h> #endif // ----- Algorithm ----- template <class T> void BlockMatching<T>::block_matching(const int search_range, const double coeff_MAD, const double coeff_ZNCC) { if (_connected_regions_current.size() > 0) { block_matching_arbitrary_shaped(search_range, coeff_MAD, coeff_ZNCC); } else { block_matching_lattice(search_range, coeff_MAD, coeff_ZNCC); } } template <class T> void BlockMatching<T>::block_matching_lattice(const int search_range, const double coeff_MAD, const double coeff_ZNCC) { double (BlockMatching<T>::*MAD_func)(const ImgVector<T>&, const ImgVector<T>&, const int, const int, const int, const int) = &BlockMatching<T>::MAD; double (BlockMatching<T>::*NCC_func)(const ImgVector<T>&, const ImgVector<T>&, const int, const int, const int, const int) = &BlockMatching<T>::ZNCC; if (this->isNULL()) { std::cerr << "void BlockMatching<T>::block_matching_lattice(const int) : _block_size < 0" << std::endl; throw std::logic_error("void BlockMatching<T>::block_matching(const int) : this is NULL"); } else if (_block_size < 0) { std::cerr << "void BlockMatching<T>::block_matching_lattice(const int) : _block_size < 0" << std::endl; throw std::logic_error("void BlockMatching<T>::block_matching(const int) : _block_size < 0"); } // Initialize // Reset Motion Vector _motion_vector_time.reset(_cells_width, _cells_height); _motion_vector_prev.reset(_cells_width, _cells_height); if (_image_next.isNULL() == false) { _motion_vector_next.reset(_cells_width, _cells_height); } // Set reference_images std::vector<ImgVector<T>*> reference_images; std::vector<ImgVector<VECTOR_2D<double> > *> motion_vectors; reference_images.push_back(&_image_prev); motion_vectors.push_back(&_motion_vector_prev); if (_image_next.isNULL() == false) { reference_images.push_back(&_image_next); motion_vectors.push_back(&_motion_vector_next); } // Compute Motion Vectors for previous and next frame for (size_t ref = 0; ref < reference_images.size(); ref++) { #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) unsigned int finished = 0; unsigned int progress = .0; printf(" Block Matching : 0.0%%\x1b[1A\n"); #endif #ifdef _OPENMP #pragma omp parallel for #endif for (int Y_b = 0; Y_b < _cells_height; Y_b++) { int y_b = Y_b * _block_size; for (int X_b = 0; X_b < _cells_width; X_b++) { int x_b = X_b * _block_size; int x_start, x_end; int y_start, y_end; // Compute start and end coordinates if (search_range < 0) { x_start = 1 - _block_size; x_end = _width - 1; y_start = 1 - _block_size; y_end = _height - 1; } else { x_start = std::max(x_b - (search_range / 2), 1 - _block_size); x_end = std::min(x_b + search_range / 2, _width - 1); y_start = std::max(y_b - (search_range / 2), 1 - _block_size); y_end = std::min(y_b + search_range / 2, _height - 1); } double E_min = DBL_MAX; VECTOR_2D<double> MV(.0, .0); for (int y = y_start; y <= y_end; y++) { for (int x = x_start; x <= x_end; x++) { VECTOR_2D<double> v_tmp(double(x - x_b), double(y - y_b)); double MAD = (this->*MAD_func)( *(reference_images[ref]), _image_current, x, y, x_b, y_b); double ZNCC = (this->*NCC_func)( *(reference_images[ref]), _image_current, x, y, x_b, y_b); double E_tmp = coeff_MAD * MAD + coeff_ZNCC * (1.0 - ZNCC); if (E_tmp < E_min) { E_min = E_tmp; MV = v_tmp; } else if (fabs(E_tmp - E_min) < 1.0E-6 && norm_squared(MV) >= norm_squared(v_tmp)) { E_min = E_tmp; MV = v_tmp; } } } if (_subpixel_scale > 1) { // Sub-pixel scale search of infimum VECTOR_2D<double> MV_subpel(.0, .0); double MAD_min = DBL_MAX; for (int y = -_subpixel_scale + 1; y < _subpixel_scale; y++) { for (int x = -_subpixel_scale + 1; x < _subpixel_scale; x++) { VECTOR_2D<double> v_tmp(double(x) / double(_subpixel_scale), double(y) / double(_subpixel_scale)); double MAD = MAD_cubic( *(reference_images[ref]), _image_current, double(x_b) + MV.x + v_tmp.x, double(y_b) + MV.y + v_tmp.y, double(x_b), double(y_b)); if (MAD < MAD_min) { MAD_min = MAD; MV_subpel = v_tmp; } else if (fabs(MAD - MAD_min) < 1.0E-6 && norm_squared(MV_subpel) >= norm_squared(v_tmp)) { MAD_min = MAD; MV_subpel = v_tmp; } } } MV += MV_subpel; } motion_vectors[ref]->at(X_b, Y_b) = MV; } #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) double ratio = double(++finished) / _cells_height; if (round(ratio * 1000.0) > progress) { progress = static_cast<unsigned int>(round(ratio * 1000.0)); // Take account of Over-Run printf("\r Block Matching : %5.1f%%\x1b[1A\n", progress * 0.1); } #endif } #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) printf("\n"); #endif } // Output if (_image_next.isNULL() == false) { // Use bi-directional motion estimation for (int Y_b = 0; Y_b < _cells_height; Y_b++) { for (int X_b = 0; X_b < _cells_width; X_b++) { VECTOR_2D<double> mv_p = _motion_vector_prev.get(X_b, Y_b); VECTOR_2D<double> mv_n = _motion_vector_next.get(X_b, Y_b); double diff_prev = 0.0; double diff_next = 0.0; for (int dy = 0; dy < _block_size; dy++) { int y = _block_size * Y_b + dy; for (int dx = 0; dx < _block_size; dx++) { int x = _block_size * X_b + dx; diff_prev += norm(_image_prev.get_zeropad_cubic(x + mv_p.x, y + mv_p.y) - _image_current.get(x, y)); diff_next += norm(_image_next.get_zeropad_cubic(x + mv_n.x, y + mv_n.y) - _image_current.get(x, y)); } } if (diff_prev <= diff_next) { _motion_vector_time.at(X_b, Y_b).x = _motion_vector_prev.at(X_b, Y_b).x; _motion_vector_time.at(X_b, Y_b).y = _motion_vector_prev.at(X_b, Y_b).y; _motion_vector_time.at(X_b, Y_b).t = -1; } else { _motion_vector_time.at(X_b, Y_b).x = _motion_vector_next.at(X_b, Y_b).x; _motion_vector_time.at(X_b, Y_b).y = _motion_vector_next.at(X_b, Y_b).y; _motion_vector_time.at(X_b, Y_b).t = 1; } } } } else { // Use forward motion estimation for (size_t n = 0; n < _motion_vector_prev.size(); n++) { _motion_vector_time[n].x = _motion_vector_prev[n].x; _motion_vector_time[n].y = _motion_vector_prev[n].y; _motion_vector_time[n].t = -1; } } } template <class T> void BlockMatching<T>::block_matching_arbitrary_shaped(const int search_range, const double coeff_MAD, const double coeff_ZNCC) { double (BlockMatching<T>::*MAD_func)(const ImgVector<T>&, const ImgVector<T>&, const int, const int, const std::vector<VECTOR_2D<int> >&) = &BlockMatching<T>::MAD_region; double (BlockMatching<T>::*NCC_func)(const ImgVector<T>&, const ImgVector<T>&, const int, const int, const std::vector<VECTOR_2D<int> >&) = &BlockMatching<T>::ZNCC_region; //double (BlockMatching<T>::*MAD_func)(const ImgVector<T>&, const ImgVector<T>&, const int, const int, const std::vector<VECTOR_2D<int> >&) = &BlockMatching<T>::MAD_region_nearest_intensity; //double (BlockMatching<T>::*NCC_func)(const ImgVector<T>&, const ImgVector<T>&, const int, const int, const std::vector<VECTOR_2D<int> >&) = &BlockMatching<T>::ZNCC_region_nearest_intensity; if (this->isNULL()) { std::cerr << "void BlockMatching<T>::block_matching_region(const ImgVector<int>*, const int) : this is NULL" << std::endl; throw std::logic_error("void BlockMatching<T>::block_matching_region(const ImgVector<int>*, const int) : this is NULL"); } // MV are expanded on entire image pixels _motion_vector_time.reset(_width, _height); _motion_vector_prev.reset(_width, _height); if (_image_next.isNULL() == false) { _motion_vector_next.reset(_width, _height); } // Set reference_images std::vector<ImgVector<T> *> reference_images; std::vector<ImgVector<VECTOR_2D<double> > *> motion_vectors; reference_images.push_back(&_image_prev); motion_vectors.push_back(&_motion_vector_prev); if (_image_next.isNULL() == false) { reference_images.push_back(&_image_next); motion_vectors.push_back(&_motion_vector_next); } // Compute Motion Vectors for (size_t ref = 0; ref < reference_images.size(); ref++) { #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) size_t finished_regions = 0; size_t progress = .0; printf(" Block Matching : 0.0%%\x1b[1A\n"); #endif for (size_t n = 0; n < _connected_regions_current.size(); n++) { VECTOR_2D<double> MV(.0, .0); double E_min = DBL_MAX; // Search minimum value { int x; #ifdef _OPENMP #pragma omp parallel for #endif for (x = 0; x < search_range * search_range; x++) { int y_diff = x / search_range - search_range / 2; int x_diff = x % search_range - search_range / 2; VECTOR_2D<double> v_tmp(x_diff, y_diff); double MAD = (this->*MAD_func)( *(reference_images[ref]), _image_current, x_diff, y_diff, _connected_regions_current[n]); double ZNCC = (this->*NCC_func)( *(reference_images[ref]), _image_current, x_diff, y_diff, _connected_regions_current[n]); double E_tmp = coeff_MAD * MAD + coeff_ZNCC * (1.0 - ZNCC); #ifdef _OPENMP #pragma omp critical #endif { if (E_tmp < E_min) { E_min = E_tmp; MV = v_tmp; } else if (fabs(E_tmp - E_min) < 1.0E-6) { if (norm_squared(v_tmp) < norm_squared(MV)) { E_min = E_tmp; MV = v_tmp; } } } } } if (_subpixel_scale > 1) { // Sub-pixel scale search of infimum VECTOR_2D<double> MV_subpel(.0, .0); double MAD_min = DBL_MAX; for (int y = -_subpixel_scale + 1; y < _subpixel_scale; y++) { for (int x = -_subpixel_scale + 1; x < _subpixel_scale; x++) { VECTOR_2D<double> v_tmp( double(x) / double(_subpixel_scale), double(y) / double(_subpixel_scale)); double MAD = MAD_region_cubic( *(reference_images[ref]), _image_current, MV.x + v_tmp.x, MV.y + v_tmp.y, _connected_regions_current[n]); if (MAD < MAD_min) { MAD_min = MAD; MV_subpel = v_tmp; } else if (fabs(MAD - MAD_min) < 1.0E-6 && norm_squared(MV_subpel) >= norm_squared(v_tmp)) { MAD_min = MAD; MV_subpel = v_tmp; } } } MV += MV_subpel; } for (VECTOR_2D<int>& r : _connected_regions_current[n]) { motion_vectors[ref]->at(r.x, r.y) = MV; } #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) double ratio = double(++finished_regions) / _connected_regions_current.size(); if (round(ratio * 1000.0) > progress) { progress = static_cast<unsigned int>(round(ratio * 1000.0)); // Take account of Over-Run printf("\r Block Matching : %5.1f%%\x1b[1A\n", progress * 0.1); } #endif } #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) printf("\n"); #endif } for (size_t n = 0; n < _connected_regions_current.size(); n++) { for (VECTOR_2D<int>& r : _connected_regions_current[n]) { if (_image_next.isNULL()) { // Use forward motion estimation _motion_vector_time.at(r.x, r.y).x = _motion_vector_prev.get(r.x, r.y).x; _motion_vector_time.at(r.x, r.y).y = _motion_vector_prev.get(r.x, r.y).y; _motion_vector_time.at(r.x, r.y).t = -1; } else { // Use bi-directional motion estimation VECTOR_2D<double> mv_p = _motion_vector_prev.get(r.x, r.y); VECTOR_2D<double> mv_n = _motion_vector_next.get(r.x, r.y); double diff_prev = norm(_image_prev.get_zeropad_cubic(r.x + mv_p.x, r.y + mv_p.y) - _image_current.get(r.x, r.y)); double diff_next = norm(_image_next.get_zeropad_cubic(r.x + mv_n.x, r.y + mv_n.y) - _image_current.get(r.x, r.y)); if (diff_prev <= diff_next) { // Use forward motion vector _motion_vector_time.at(r.x, r.y).x = _motion_vector_prev.get(r.x, r.y).x; _motion_vector_time.at(r.x, r.y).y = _motion_vector_prev.get(r.x, r.y).y; _motion_vector_time.at(r.x, r.y).t = -1; } else { _motion_vector_time.at(r.x, r.y).x = _motion_vector_next.get(r.x, r.y).x; _motion_vector_time.at(r.x, r.y).y = _motion_vector_next.get(r.x, r.y).y; _motion_vector_time.at(r.x, r.y).t = 1; } } } } #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) printf("\n Block Matching : Finished\n"); #endif } // ----- Interpolation ----- template <class T> void BlockMatching<T>::vector_interpolation(const std::list<VECTOR_2D<int> >& flat_blocks, ImgVector<bool>* estimated) { for (std::list<VECTOR_2D<int> >::const_iterator itr_flat_blocks = flat_blocks.begin(); itr_flat_blocks != flat_blocks.end(); ++itr_flat_blocks) { int X_b = itr_flat_blocks->x; int Y_b = itr_flat_blocks->y; int x_b = X_b * _block_size; int y_b = Y_b * _block_size; double MAD_min = 10.0; double MAD_tmp; // Compare 4 adjacent if (estimated->get_mirror(X_b, Y_b - 1) && (MAD_tmp = this->MAD(_image_prev, _image_prev, x_b, y_b, x_b, y_b - _block_size)) < MAD_min) { _motion_vector_prev.at(X_b, Y_b) = _motion_vector_prev.get_mirror(X_b, Y_b - 1); MAD_min = MAD_tmp; } if (estimated->get_mirror(X_b - 1, Y_b) && (MAD_tmp = this->MAD(_image_prev, _image_prev, x_b, y_b, x_b - _block_size, y_b)) < MAD_min) { _motion_vector_prev.at(X_b, Y_b) = _motion_vector_prev.get_mirror(X_b - 1, Y_b); MAD_min = MAD_tmp; } if (estimated->get_mirror(X_b, Y_b + 1) && (MAD_tmp = this->MAD(_image_prev, _image_prev, x_b, y_b, x_b, y_b + _block_size)) < MAD_min) { _motion_vector_prev.at(X_b, Y_b) = _motion_vector_prev.get_mirror(X_b, Y_b + 1); MAD_min = MAD_tmp; } if (estimated->get_mirror(X_b + 1, Y_b) && (MAD_tmp = this->MAD(_image_prev, _image_prev, x_b, y_b, x_b + _block_size, y_b)) < MAD_min) { _motion_vector_prev.at(X_b, Y_b) = _motion_vector_prev.get_mirror(X_b + 1, Y_b); MAD_min = MAD_tmp; } estimated->at(X_b, Y_b) = true; } } // ----- Correlation ----- template <class T> double BlockMatching<T>::MAD(const ImgVector<T>& reference, const ImgVector<T>& interest, const int x_ref, const int y_ref, const int x_int, const int y_int) { double sad = 0; for (int y = 0; y < _block_size; y++) { for (int x = 0; x < _block_size; x++) { sad += norm( reference.get_zeropad(x_ref + x, y_ref + y) - interest.get_zeropad(x_int + x, y_int + y)); } } return sad / double(_block_size * _block_size); } template <class T> double BlockMatching<T>::MAD_cubic(const ImgVector<T>& reference, const ImgVector<T>& interest, const double x_ref, const double y_ref, const double x_int, const double y_int) { double sad = 0; for (int y = 0; y < _block_size; y++) { for (int x = 0; x < _block_size; x++) { sad += norm( reference.get_mirror_cubic(x_ref + x, y_ref + y) - interest.get_mirror_cubic(x_int + x, y_int + y)); } } return sad / double(_block_size * _block_size); } template <class T> double BlockMatching<T>::ZNCC(const ImgVector<T>& reference, const ImgVector<T>& interest, const int x_ref, const int y_ref, const int x_int, const int y_int) { double N = _block_size * _block_size; T sum_reference = T(); T sum_interest = T(); double sum_sq_reference = 0; double sum_sq_interest = 0; double sum_sq_reference_interest = 0; for (int y = 0; y < _block_size; y++) { for (int x = 0; x < _block_size; x++) { sum_reference += reference.get_zeropad(x_ref + x, y_ref + y); sum_interest += interest.get_zeropad(x_int + x, y_int + y); sum_sq_reference += inner_prod( reference.get_zeropad(x_ref + x, y_ref + y), reference.get_zeropad(x_ref + x, y_ref + y)); sum_sq_interest += inner_prod( interest.get_zeropad(x_int + x, y_int + y), interest.get_zeropad(x_int + x, y_int + y)); sum_sq_reference_interest += inner_prod( reference.get_zeropad(x_ref + x, y_ref + y), interest.get_zeropad(x_int + x, y_int + y)); } } return (N * sum_sq_reference_interest - inner_prod(sum_reference, sum_interest)) / (sqrt((N * sum_sq_reference - inner_prod(sum_reference, sum_reference)) * (N * sum_sq_interest - inner_prod(sum_interest, sum_interest))) + DBL_EPSILON); } template <class T> double BlockMatching<T>::MAD_region(const ImgVector<T>& reference, const ImgVector<T>& interest, const int x_diff, const int y_diff, const std::vector<VECTOR_2D<int> >& region_interest) { double N = .0; double sad = .0; for (const VECTOR_2D<int>& r : region_interest) { N += 1.0; sad += norm( interest.get_zeropad(r.x, r.y) - reference.get_zeropad(r.x + x_diff, r.y + y_diff)); } return sad / N; } template <class T> double BlockMatching<T>::MAD_region_cubic(const ImgVector<T>& reference, const ImgVector<T>& interest, const double x_diff, const double y_diff, const std::vector<VECTOR_2D<int> >& region_interest) { double N = .0; double sad = .0; for (const VECTOR_2D<int>& r : region_interest) { N += 1.0; sad += norm( interest.get_zeropad(r.x, r.y) - reference.get_mirror_cubic(double(r.x) + x_diff, double(r.y) + y_diff)); } return sad / N; } template <class T> double BlockMatching<T>::ZNCC_region(const ImgVector<T>& reference, const ImgVector<T>& interest, const int x_diff, const int y_diff, const std::vector<VECTOR_2D<int> >& region_interest) { double N = .0; T sum_reference = T(); T sum_interest = T(); double sum_sq_reference = .0; double sum_sq_interest = .0; double sum_sq_reference_interest = .0; for (const VECTOR_2D<int>& r_int : region_interest) { VECTOR_2D<int> r(r_int.x + x_diff, r_int.y + y_diff); N += 1.0; // Previous frame sum_reference += reference.get_zeropad(r.x, r.y); sum_sq_reference += inner_prod( reference.get_zeropad(r.x, r.y) , reference.get_zeropad(r.x, r.y)); // Next frame sum_interest += interest.get_zeropad(r_int.x, r_int.y); sum_sq_interest += inner_prod( interest.get_zeropad(r_int.x, r_int.y) , interest.get_zeropad(r_int.x, r_int.y)); // Co-frame sum_sq_reference_interest += inner_prod( reference.get_zeropad(r.x, r.y) , interest.get_zeropad(r_int.x, r_int.y)); } // Calculate Covariance return (N * sum_sq_reference_interest - inner_prod(sum_reference, sum_interest)) / (sqrt((N * sum_sq_reference - inner_prod(sum_reference, sum_reference)) * (N * sum_sq_interest - inner_prod(sum_interest, sum_interest))) + DBL_EPSILON); } /* Regions concerning correlation method * * Compute correlation only with the regions which have near intensity. */ template <class T> double BlockMatching<T>::MAD_region_nearest_intensity(const int x_diff, const int y_diff, const std::vector<VECTOR_2D<int> >& region_interest) { double N = .0; double sad = .0; for (const VECTOR_2D<int>& r_int : region_interest) { VECTOR_2D<int> r(r_int.x + x_diff, r_int.y + y_diff); double coeff = norm( _color_quantized_current.get(r_int.x, r_int.y) - _color_quantized_prev.get_zeropad(r.x, r.y)); N += coeff; sad += coeff * norm( _image_current.get(r_int.x, r_int.y - _image_prev.get_zeropad(r.x, r.y))); } return sad / N; } template <class T> double BlockMatching<T>::ZNCC_region_nearest_intensity(const int x_diff, const int y_diff, const std::vector<VECTOR_2D<int> >& region_interest) { double N = .0; T sum_prev = T(); T sum_current = T(); double sum_sq_prev = .0; double sum_sq_current = .0; double sum_sq_prev_current = .0; for (const VECTOR_2D<int>& r_int : region_interest) { VECTOR_2D<int> r(r_int.x + x_diff, r_int.y + y_diff); double coeff = 1.0 - norm( _color_quantized_current.get(r_int.x, r_int.y) - _color_quantized_prev.get_zeropad(r.x, r.y)); N += coeff; // Previous frame sum_prev += coeff * _image_prev.get_zeropad(r.x, r.y); sum_sq_prev += coeff * _image_prev.get_zeropad(r.x, r.y) * _image_prev.get_zeropad(r.x, r.y); // Next frame sum_current += coeff * _image_current.get_zeropad(r_int.x, r_int.y); sum_sq_current += coeff * _image_current.get_zeropad(r_int.x, r_int.y) * _image_current.get_zeropad(r_int.x, r_int.y); // Co-frame sum_sq_prev_current += coeff * _image_prev.get_zeropad(r.x, r.y) * _image_current.get_zeropad(r_int.x, r_int.y); } // Calculate Covariance return (N * sum_sq_prev_current - sum_prev * sum_current) / (sqrt((N * sum_sq_prev - sum_prev * sum_prev) * (N * sum_sq_current - sum_current * sum_current)) + DBL_EPSILON); }
convolution_3x3_pack4to1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. 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_winograd63_transform_kernel_pack4to1_sse(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch, const Option& opt) { // winograd63 transform kernel Mat kernel_tm; kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) 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, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; 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]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 64-inch-outch // dst = 4a-inch/4a-64-outch; kernel_tm_pack4.create(4 * inch / 4, 64, outch / 4 + outch % 4, (size_t)4u * 4, 4); int p = 0; for (; p + 3 < outch; p += 4) { const Mat k0 = kernel_tm.channel(p); const Mat k1 = kernel_tm.channel(p + 1); const Mat k2 = kernel_tm.channel(p + 2); const Mat k3 = kernel_tm.channel(p + 3); Mat g0 = kernel_tm_pack4.channel(p / 4); for (int k = 0; k < 64; k++) { float* g00 = g0.row(k); for (int q = 0; q + 3 < inch; q += 4) { const float* k00 = k0.row(q); const float* k01 = k0.row(q + 1); const float* k02 = k0.row(q + 2); const float* k03 = k0.row(q + 3); const float* k10 = k1.row(q); const float* k11 = k1.row(q + 1); const float* k12 = k1.row(q + 2); const float* k13 = k1.row(q + 3); const float* k20 = k2.row(q); const float* k21 = k2.row(q + 1); const float* k22 = k2.row(q + 2); const float* k23 = k2.row(q + 3); const float* k30 = k3.row(q); const float* k31 = k3.row(q + 1); const float* k32 = k3.row(q + 2); const float* k33 = k3.row(q + 3); g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k01[k]; g00[5] = k11[k]; g00[6] = k21[k]; g00[7] = k31[k]; g00[8] = k02[k]; g00[9] = k12[k]; g00[10] = k22[k]; g00[11] = k32[k]; g00[12] = k03[k]; g00[13] = k13[k]; g00[14] = k23[k]; g00[15] = k33[k]; g00 += 16; } } } for (; p < outch; p++) { const Mat k0 = kernel_tm.channel(p); Mat g0 = kernel_tm_pack4.channel(p / 4 + p % 4); for (int k = 0; k < 64; k++) { float* g00 = g0.row(k); for (int q = 0; q + 3 < inch; q += 4) { const float* k00 = k0.row(q); const float* k01 = k0.row(q + 1); const float* k02 = k0.row(q + 2); const float* k03 = k0.row(q + 3); g00[0] = k00[k]; g00[1] = k01[k]; g00[2] = k02[k]; g00[3] = k03[k]; g00 += 4; } } } } static void conv3x3s1_winograd63_pack4to1_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; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); conv3x3s1_winograd63_transform_input_pack4_sse(bottom_blob_bordered, bottom_blob_tm, opt); } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = h_tm / 8 * w_tm / 8; // permute // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 64, elemsize, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { float* tmpptr = tm2.row(i / 8); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x8 __m128 _r0 = _mm_load_ps(r0); __m128 _r1 = _mm_load_ps(r0 + 4); __m128 _r2 = _mm_load_ps(r0 + 4 * 2); __m128 _r3 = _mm_load_ps(r0 + 4 * 3); __m128 _r4 = _mm_load_ps(r0 + 4 * 4); __m128 _r5 = _mm_load_ps(r0 + 4 * 5); __m128 _r6 = _mm_load_ps(r0 + 4 * 6); __m128 _r7 = _mm_load_ps(r0 + 4 * 7); _MM_TRANSPOSE4_PS(_r0, _r1, _r2, _r3); _MM_TRANSPOSE4_PS(_r4, _r5, _r6, _r7); _mm_store_ps(tmpptr, _r0); _mm_store_ps(tmpptr + 4, _r4); _mm_store_ps(tmpptr + 4 * 2, _r1); _mm_store_ps(tmpptr + 4 * 3, _r5); _mm_store_ps(tmpptr + 4 * 4, _r2); _mm_store_ps(tmpptr + 4 * 5, _r6); _mm_store_ps(tmpptr + 4 * 6, _r3); _mm_store_ps(tmpptr + 4 * 7, _r7); r0 += bottom_blob_tm.cstep * 4; tmpptr += 32; } } for (; i + 3 < tiles; i += 4) { float* tmpptr = tm2.row(i / 8 + (i % 8) / 4); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x4 __m128 _r0 = _mm_load_ps(r0); __m128 _r1 = _mm_load_ps(r0 + 4); __m128 _r2 = _mm_load_ps(r0 + 4 * 2); __m128 _r3 = _mm_load_ps(r0 + 4 * 3); _MM_TRANSPOSE4_PS(_r0, _r1, _r2, _r3); _mm_store_ps(tmpptr, _r0); _mm_store_ps(tmpptr + 4, _r1); _mm_store_ps(tmpptr + 4 * 2, _r2); _mm_store_ps(tmpptr + 4 * 3, _r3); r0 += bottom_blob_tm.cstep * 4; tmpptr += 16; } } for (; i < tiles; i++) { float* tmpptr = tm2.row(i / 8 + (i % 8) / 4 + i % 4); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { __m128 _val = _mm_load_ps(r0); _mm_store_ps(tmpptr, _val); r0 += bottom_blob_tm.cstep * 4; tmpptr += 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 64, outch, 4u, 1, opt.workspace_allocator); int nn_outch = outch >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); const Mat kernel01_tm = kernel_tm.channel(p / 4); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 8); const float* kptr = kernel01_tm.row(r); int nn = inch * 4; // inch always > 0 __m128 _sum0 = _mm_setzero_ps(); __m128 _sum1 = _mm_setzero_ps(); __m128 _sum2 = _mm_setzero_ps(); __m128 _sum3 = _mm_setzero_ps(); __m128 _sum4 = _mm_setzero_ps(); __m128 _sum5 = _mm_setzero_ps(); __m128 _sum6 = _mm_setzero_ps(); __m128 _sum7 = _mm_setzero_ps(); for (int j = 0; j < nn; j++) { __m128 _val0 = _mm_load_ps(r0); __m128 _val1 = _mm_load_ps(r0 + 4); __m128 _w0 = _mm_load1_ps(kptr); __m128 _w1 = _mm_load1_ps(kptr + 1); __m128 _w2 = _mm_load1_ps(kptr + 2); __m128 _w3 = _mm_load1_ps(kptr + 3); _sum0 = _mm_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm_comp_fmadd_ps(_val1, _w0, _sum1); _sum2 = _mm_comp_fmadd_ps(_val0, _w1, _sum2); _sum3 = _mm_comp_fmadd_ps(_val1, _w1, _sum3); _sum4 = _mm_comp_fmadd_ps(_val0, _w2, _sum4); _sum5 = _mm_comp_fmadd_ps(_val1, _w2, _sum5); _sum6 = _mm_comp_fmadd_ps(_val0, _w3, _sum6); _sum7 = _mm_comp_fmadd_ps(_val1, _w3, _sum7); r0 += 8; kptr += 4; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output0_tm + 4, _sum1); _mm_storeu_ps(output1_tm, _sum2); _mm_storeu_ps(output1_tm + 4, _sum3); _mm_storeu_ps(output2_tm, _sum4); _mm_storeu_ps(output2_tm + 4, _sum5); _mm_storeu_ps(output3_tm, _sum6); _mm_storeu_ps(output3_tm + 4, _sum7); output0_tm += 8; output1_tm += 8; output2_tm += 8; output3_tm += 8; } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 8 + (i % 8) / 4); const float* kptr = kernel01_tm.row(r); int nn = inch * 4; // inch always > 0 __m128 _sum0 = _mm_setzero_ps(); __m128 _sum1 = _mm_setzero_ps(); __m128 _sum2 = _mm_setzero_ps(); __m128 _sum3 = _mm_setzero_ps(); for (int j = 0; j < nn; j++) { __m128 _val0 = _mm_load_ps(r0); __m128 _w0 = _mm_load1_ps(kptr); __m128 _w1 = _mm_load1_ps(kptr + 1); __m128 _w2 = _mm_load1_ps(kptr + 2); __m128 _w3 = _mm_load1_ps(kptr + 3); _sum0 = _mm_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm_comp_fmadd_ps(_val0, _w1, _sum1); _sum2 = _mm_comp_fmadd_ps(_val0, _w2, _sum2); _sum3 = _mm_comp_fmadd_ps(_val0, _w3, _sum3); r0 += 4; kptr += 4; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output1_tm, _sum1); _mm_storeu_ps(output2_tm, _sum2); _mm_storeu_ps(output3_tm, _sum3); output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); const float* kptr = kernel01_tm.row(r); int nn = inch * 4; // inch always > 0 __m128 _sum = _mm_setzero_ps(); for (int j = 0; j < nn; j++) { __m128 _val0 = _mm_load1_ps(r0); __m128 _w0 = _mm_load_ps(kptr); _sum = _mm_comp_fmadd_ps(_val0, _w0, _sum); r0 += 1; kptr += 4; } float sum[4]; _mm_storeu_ps(sum, _sum); output0_tm[0] = sum[0]; output1_tm[0] = sum[1]; output2_tm[0] = sum[2]; output3_tm[0] = sum[3]; output0_tm += 1; output1_tm += 1; output2_tm += 1; output3_tm += 1; } } } int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p / 4 + p % 4); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 8); const float* kptr = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 __m128 _sum0 = _mm_setzero_ps(); __m128 _sum1 = _mm_setzero_ps(); for (int j = 0; j < nn; j++) { __m128 _val0 = _mm_load_ps(r0); __m128 _val1 = _mm_load_ps(r0 + 4); __m128 _w0 = _mm_load1_ps(kptr); _sum0 = _mm_comp_fmadd_ps(_w0, _val0, _sum0); _sum1 = _mm_comp_fmadd_ps(_w0, _val1, _sum1); r0 += 8; kptr += 1; } _mm_storeu_ps(output0_tm, _sum0); _mm_storeu_ps(output0_tm + 4, _sum1); output0_tm += 8; } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 8 + (i % 8) / 4); const float* kptr = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 __m128 _sum0 = _mm_setzero_ps(); for (int j = 0; j < nn; j++) { __m128 _val0 = _mm_load_ps(r0); __m128 _w0 = _mm_load1_ps(kptr); _sum0 = _mm_comp_fmadd_ps(_w0, _val0, _sum0); r0 += 4; kptr += 1; } _mm_storeu_ps(output0_tm, _sum0); output0_tm += 4; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4); const float* kptr = kernel0_tm.row(r); __m128 _sum0 = _mm_setzero_ps(); for (int q = 0; q < inch; q++) { __m128 _val0 = _mm_load_ps(r0); __m128 _w0 = _mm_load_ps(kptr); _sum0 = _mm_comp_fmadd_ps(_val0, _w0, _sum0); r0 += 4; kptr += 4; } float sum0 = _mm_reduce_add_ps(_sum0); output0_tm[0] = sum0; output0_tm++; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, 1, opt.workspace_allocator); } { conv3x3s1_winograd63_transform_output_sse(top_blob_tm, top_blob_bordered, bias, opt); } // 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); }
ex03.c
/* Copyright (c) 2019 CSC Training */ /* Copyright (c) 2021 ENCCS */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif int main() { int num_devices = omp_get_num_devices(); printf("Number of available devices %d\n", num_devices); #pragma omp target #pragma omp teams num_teams(2) thread_limit(3) #pragma omp parallel { if (omp_is_initial_device()) { printf("Running on host\n"); } else { int nteams= omp_get_num_teams(); int nthreads= omp_get_num_threads(); printf("Running on device with %d teams in total and %d threads in each team\n",nteams,nthreads); } } }
CALPHADConcSolverBinaryThreePhase.h
#ifndef included_CALPHADConcSolverBinaryThreePhase #define included_CALPHADConcSolverBinaryThreePhase #include "NewtonSolver.h" #include "datatypes.h" namespace Thermo4PFM { class CALPHADConcSolverBinaryThreePhase : public NewtonSolver<3, CALPHADConcSolverBinaryThreePhase, JacobianDataType> { public: #ifdef HAVE_OPENMP_OFFLOAD #pragma omp declare target #endif /// compute "internal" concentrations cL, cS1, cS2 by solving KKS /// equations /// conc: initial guess and final solution (concentration in each phase) int ComputeConcentration(double* const conc, const double tol, const int max_iters, const double alpha = 1.) { return NewtonSolver::ComputeSolution(conc, tol, max_iters, alpha); } /// setup model paramater values to be used by solver, /// including composition "c0" and phase fraction "hphi" /// to solve for void setup(const double c0, const double hphi0, const double hphi1, const double hphi2, const double RT, const CalphadDataType* const Lmix_L_, const CalphadDataType* const Lmix_S0_, const CalphadDataType* const Lmix_S1_, const CalphadDataType* const fA, const CalphadDataType* const fB); /// evaluate RHS of the system of eqautions to solve for /// specific to this solver void RHS(const double* const x, double* const fvec); /// evaluate Jacobian of system of equations /// specific to this solver void Jacobian(const double* const x, JacobianDataType** const fjac); #ifdef HAVE_OPENMP_OFFLOAD #pragma omp end declare target #endif private: /// /// Nominal composition to solve for /// double c0_; /// /// phase fractions to solve for /// double hphi0_; double hphi1_; double hphi2_; double scaledRT_; /// /// 4 L coefficients for 3 possible phases (L, S0, S1) /// CalphadDataType Lmix_L_[4]; CalphadDataType Lmix_S0_[4]; CalphadDataType Lmix_S1_[4]; /// /// energies of 2 species, in three phases each /// CalphadDataType fA_[3]; CalphadDataType fB_[3]; // internal functions to help evaluate RHS and Jacobian void computeXi(const double* const c, double xi[3]) const; void computeDxiDc(const double* const c, double dxidc[3]) const; }; } #endif
GB_unaryop__abs_uint16_bool.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__abs_uint16_bool // op(A') function: GB_tran__abs_uint16_bool // C type: uint16_t // A type: bool // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_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_ABS || GxB_NO_UINT16 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint16_bool ( uint16_t *restrict Cx, const bool *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__abs_uint16_bool ( 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
feature_group.h
/*! * Copyright (c) 2017 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_FEATURE_GROUP_H_ #define LIGHTGBM_FEATURE_GROUP_H_ #include <LightGBM/bin.h> #include <LightGBM/meta.h> #include <LightGBM/utils/random.h> #include <cstdio> #include <memory> #include <vector> namespace LightGBM { class Dataset; class DatasetLoader; /*! \brief Using to store data and providing some operations on one feature group*/ class FeatureGroup { public: friend Dataset; friend DatasetLoader; /*! * \brief Constructor * \param num_feature number of features of this group * \param bin_mappers Bin mapper for features * \param num_data Total number of data * \param is_enable_sparse True if enable sparse feature */ FeatureGroup(int num_feature, int8_t is_multi_val, std::vector<std::unique_ptr<BinMapper>>* bin_mappers, data_size_t num_data) : num_feature_(num_feature), is_multi_val_(is_multi_val > 0), is_sparse_(false) { CHECK_EQ(static_cast<int>(bin_mappers->size()), num_feature); // use bin at zero to store most_freq_bin num_total_bin_ = 1; bin_offsets_.emplace_back(num_total_bin_); auto& ref_bin_mappers = *bin_mappers; for (int i = 0; i < num_feature_; ++i) { bin_mappers_.emplace_back(ref_bin_mappers[i].release()); auto num_bin = bin_mappers_[i]->num_bin(); if (bin_mappers_[i]->GetMostFreqBin() == 0) { num_bin -= 1; } num_total_bin_ += num_bin; bin_offsets_.emplace_back(num_total_bin_); } CreateBinData(num_data, is_multi_val_, true, false); } FeatureGroup(const FeatureGroup& other, int num_data) { num_feature_ = other.num_feature_; is_multi_val_ = other.is_multi_val_; is_sparse_ = other.is_sparse_; num_total_bin_ = other.num_total_bin_; bin_offsets_ = other.bin_offsets_; bin_mappers_.reserve(other.bin_mappers_.size()); for (auto& bin_mapper : other.bin_mappers_) { bin_mappers_.emplace_back(new BinMapper(*bin_mapper)); } CreateBinData(num_data, is_multi_val_, !is_sparse_, is_sparse_); } FeatureGroup(std::vector<std::unique_ptr<BinMapper>>* bin_mappers, data_size_t num_data) : num_feature_(1), is_multi_val_(false) { CHECK_EQ(static_cast<int>(bin_mappers->size()), 1); // use bin at zero to store default_bin num_total_bin_ = 1; bin_offsets_.emplace_back(num_total_bin_); auto& ref_bin_mappers = *bin_mappers; for (int i = 0; i < num_feature_; ++i) { bin_mappers_.emplace_back(ref_bin_mappers[i].release()); auto num_bin = bin_mappers_[i]->num_bin(); if (bin_mappers_[i]->GetMostFreqBin() == 0) { num_bin -= 1; } num_total_bin_ += num_bin; bin_offsets_.emplace_back(num_total_bin_); } CreateBinData(num_data, false, false, false); } /*! * \brief Constructor from memory * \param memory Pointer of memory * \param num_all_data Number of global data * \param local_used_indices Local used indices, empty means using all data */ FeatureGroup(const void* memory, data_size_t num_all_data, const std::vector<data_size_t>& local_used_indices) { const char* memory_ptr = reinterpret_cast<const char*>(memory); // get is_sparse is_multi_val_ = *(reinterpret_cast<const bool*>(memory_ptr)); memory_ptr += VirtualFileWriter::AlignedSize(sizeof(is_multi_val_)); is_sparse_ = *(reinterpret_cast<const bool*>(memory_ptr)); memory_ptr += VirtualFileWriter::AlignedSize(sizeof(is_sparse_)); num_feature_ = *(reinterpret_cast<const int*>(memory_ptr)); memory_ptr += VirtualFileWriter::AlignedSize(sizeof(num_feature_)); // get bin mapper bin_mappers_.clear(); bin_offsets_.clear(); // start from 1, due to need to store zero bin in this slot num_total_bin_ = 1; bin_offsets_.emplace_back(num_total_bin_); for (int i = 0; i < num_feature_; ++i) { bin_mappers_.emplace_back(new BinMapper(memory_ptr)); auto num_bin = bin_mappers_[i]->num_bin(); if (bin_mappers_[i]->GetMostFreqBin() == 0) { num_bin -= 1; } num_total_bin_ += num_bin; bin_offsets_.emplace_back(num_total_bin_); memory_ptr += bin_mappers_[i]->SizesInByte(); } data_size_t num_data = num_all_data; if (!local_used_indices.empty()) { num_data = static_cast<data_size_t>(local_used_indices.size()); } if (is_multi_val_) { for (int i = 0; i < num_feature_; ++i) { int addi = bin_mappers_[i]->GetMostFreqBin() == 0 ? 0 : 1; if (bin_mappers_[i]->sparse_rate() >= kSparseThreshold) { multi_bin_data_.emplace_back(Bin::CreateSparseBin(num_data, bin_mappers_[i]->num_bin() + addi)); } else { multi_bin_data_.emplace_back(Bin::CreateDenseBin(num_data, bin_mappers_[i]->num_bin() + addi)); } multi_bin_data_.back()->LoadFromMemory(memory_ptr, local_used_indices); memory_ptr += multi_bin_data_.back()->SizesInByte(); } } else { if (is_sparse_) { bin_data_.reset(Bin::CreateSparseBin(num_data, num_total_bin_)); } else { bin_data_.reset(Bin::CreateDenseBin(num_data, num_total_bin_)); } // get bin data bin_data_->LoadFromMemory(memory_ptr, local_used_indices); } } /*! \brief Destructor */ ~FeatureGroup() { } /*! * \brief Push one record, will auto convert to bin and push to bin data * \param tid Thread id * \param idx Index of record * \param value feature value of record */ inline void PushData(int tid, int sub_feature_idx, data_size_t line_idx, double value) { uint32_t bin = bin_mappers_[sub_feature_idx]->ValueToBin(value); if (bin == bin_mappers_[sub_feature_idx]->GetMostFreqBin()) { return; } if (bin_mappers_[sub_feature_idx]->GetMostFreqBin() == 0) { bin -= 1; } if (is_multi_val_) { multi_bin_data_[sub_feature_idx]->Push(tid, line_idx, bin + 1); } else { bin += bin_offsets_[sub_feature_idx]; bin_data_->Push(tid, line_idx, bin); } } void ReSize(int num_data) { if (!is_multi_val_) { bin_data_->ReSize(num_data); } else { for (int i = 0; i < num_feature_; ++i) { multi_bin_data_[i]->ReSize(num_data); } } } inline void CopySubrow(const FeatureGroup* full_feature, const data_size_t* used_indices, data_size_t num_used_indices) { if (!is_multi_val_) { bin_data_->CopySubrow(full_feature->bin_data_.get(), used_indices, num_used_indices); } else { for (int i = 0; i < num_feature_; ++i) { multi_bin_data_[i]->CopySubrow(full_feature->multi_bin_data_[i].get(), used_indices, num_used_indices); } } } inline BinIterator* SubFeatureIterator(int sub_feature) { uint32_t most_freq_bin = bin_mappers_[sub_feature]->GetMostFreqBin(); if (!is_multi_val_) { uint32_t min_bin = bin_offsets_[sub_feature]; uint32_t max_bin = bin_offsets_[sub_feature + 1] - 1; return bin_data_->GetIterator(min_bin, max_bin, most_freq_bin); } else { int addi = bin_mappers_[sub_feature]->GetMostFreqBin() == 0 ? 0 : 1; uint32_t min_bin = 1; uint32_t max_bin = bin_mappers_[sub_feature]->num_bin() - 1 + addi; return multi_bin_data_[sub_feature]->GetIterator(min_bin, max_bin, most_freq_bin); } } inline void FinishLoad() { if (is_multi_val_) { OMP_INIT_EX(); #pragma omp parallel for schedule(guided) for (int i = 0; i < num_feature_; ++i) { OMP_LOOP_EX_BEGIN(); multi_bin_data_[i]->FinishLoad(); OMP_LOOP_EX_END(); } OMP_THROW_EX(); } else { bin_data_->FinishLoad(); } } /*! * \brief Returns a BinIterator that can access the entire feature group's raw data. * The RawGet() function of the iterator should be called for best efficiency. * \return A pointer to the BinIterator object */ inline BinIterator* FeatureGroupIterator() { if (is_multi_val_) { return nullptr; } uint32_t min_bin = bin_offsets_[0]; uint32_t max_bin = bin_offsets_.back() - 1; uint32_t most_freq_bin = 0; return bin_data_->GetIterator(min_bin, max_bin, most_freq_bin); } inline size_t FeatureGroupSizesInByte() { return bin_data_->SizesInByte(); } inline void* FeatureGroupData() { if (is_multi_val_) { return nullptr; } return bin_data_->get_data(); } inline data_size_t Split(int sub_feature, const uint32_t* threshold, int num_threshold, bool default_left, const data_size_t* data_indices, data_size_t cnt, data_size_t* lte_indices, data_size_t* gt_indices) const { uint32_t default_bin = bin_mappers_[sub_feature]->GetDefaultBin(); uint32_t most_freq_bin = bin_mappers_[sub_feature]->GetMostFreqBin(); if (!is_multi_val_) { uint32_t min_bin = bin_offsets_[sub_feature]; uint32_t max_bin = bin_offsets_[sub_feature + 1] - 1; if (bin_mappers_[sub_feature]->bin_type() == BinType::NumericalBin) { auto missing_type = bin_mappers_[sub_feature]->missing_type(); if (num_feature_ == 1) { return bin_data_->Split(max_bin, default_bin, most_freq_bin, missing_type, default_left, *threshold, data_indices, cnt, lte_indices, gt_indices); } else { return bin_data_->Split(min_bin, max_bin, default_bin, most_freq_bin, missing_type, default_left, *threshold, data_indices, cnt, lte_indices, gt_indices); } } else { if (num_feature_ == 1) { return bin_data_->SplitCategorical(max_bin, most_freq_bin, threshold, num_threshold, data_indices, cnt, lte_indices, gt_indices); } else { return bin_data_->SplitCategorical( min_bin, max_bin, most_freq_bin, threshold, num_threshold, data_indices, cnt, lte_indices, gt_indices); } } } else { int addi = bin_mappers_[sub_feature]->GetMostFreqBin() == 0 ? 0 : 1; uint32_t max_bin = bin_mappers_[sub_feature]->num_bin() - 1 + addi; if (bin_mappers_[sub_feature]->bin_type() == BinType::NumericalBin) { auto missing_type = bin_mappers_[sub_feature]->missing_type(); return multi_bin_data_[sub_feature]->Split( max_bin, default_bin, most_freq_bin, missing_type, default_left, *threshold, data_indices, cnt, lte_indices, gt_indices); } else { return multi_bin_data_[sub_feature]->SplitCategorical( max_bin, most_freq_bin, threshold, num_threshold, data_indices, cnt, lte_indices, gt_indices); } } } /*! * \brief From bin to feature value * \param bin * \return FeatureGroup value of this bin */ inline double BinToValue(int sub_feature_idx, uint32_t bin) const { return bin_mappers_[sub_feature_idx]->BinToValue(bin); } /*! * \brief Save binary data to file * \param file File want to write */ void SaveBinaryToFile(const VirtualFileWriter* writer) const { writer->AlignedWrite(&is_multi_val_, sizeof(is_multi_val_)); writer->AlignedWrite(&is_sparse_, sizeof(is_sparse_)); writer->AlignedWrite(&num_feature_, sizeof(num_feature_)); for (int i = 0; i < num_feature_; ++i) { bin_mappers_[i]->SaveBinaryToFile(writer); } if (is_multi_val_) { for (int i = 0; i < num_feature_; ++i) { multi_bin_data_[i]->SaveBinaryToFile(writer); } } else { bin_data_->SaveBinaryToFile(writer); } } /*! * \brief Get sizes in byte of this object */ size_t SizesInByte() const { size_t ret = VirtualFileWriter::AlignedSize(sizeof(is_multi_val_)) + VirtualFileWriter::AlignedSize(sizeof(is_sparse_)) + VirtualFileWriter::AlignedSize(sizeof(num_feature_)); for (int i = 0; i < num_feature_; ++i) { ret += bin_mappers_[i]->SizesInByte(); } if (!is_multi_val_) { ret += bin_data_->SizesInByte(); } else { for (int i = 0; i < num_feature_; ++i) { ret += multi_bin_data_[i]->SizesInByte(); } } return ret; } /*! \brief Disable copy */ FeatureGroup& operator=(const FeatureGroup&) = delete; /*! \brief Deep copy */ FeatureGroup(const FeatureGroup& other) { num_feature_ = other.num_feature_; is_multi_val_ = other.is_multi_val_; is_sparse_ = other.is_sparse_; num_total_bin_ = other.num_total_bin_; bin_offsets_ = other.bin_offsets_; bin_mappers_.reserve(other.bin_mappers_.size()); for (auto& bin_mapper : other.bin_mappers_) { bin_mappers_.emplace_back(new BinMapper(*bin_mapper)); } if (!is_multi_val_) { bin_data_.reset(other.bin_data_->Clone()); } else { multi_bin_data_.clear(); for (int i = 0; i < num_feature_; ++i) { multi_bin_data_.emplace_back(other.multi_bin_data_[i]->Clone()); } } } private: void CreateBinData(int num_data, bool is_multi_val, bool force_dense, bool force_sparse) { if (is_multi_val) { multi_bin_data_.clear(); for (int i = 0; i < num_feature_; ++i) { int addi = bin_mappers_[i]->GetMostFreqBin() == 0 ? 0 : 1; if (bin_mappers_[i]->sparse_rate() >= kSparseThreshold) { multi_bin_data_.emplace_back(Bin::CreateSparseBin( num_data, bin_mappers_[i]->num_bin() + addi)); } else { multi_bin_data_.emplace_back( Bin::CreateDenseBin(num_data, bin_mappers_[i]->num_bin() + addi)); } } is_multi_val_ = true; } else { if (force_sparse || (!force_dense && num_feature_ == 1 && bin_mappers_[0]->sparse_rate() >= kSparseThreshold)) { is_sparse_ = true; bin_data_.reset(Bin::CreateSparseBin(num_data, num_total_bin_)); } else { is_sparse_ = false; bin_data_.reset(Bin::CreateDenseBin(num_data, num_total_bin_)); } is_multi_val_ = false; } } /*! \brief Number of features */ int num_feature_; /*! \brief Bin mapper for sub features */ std::vector<std::unique_ptr<BinMapper>> bin_mappers_; /*! \brief Bin offsets for sub features */ std::vector<uint32_t> bin_offsets_; /*! \brief Bin data of this feature */ std::unique_ptr<Bin> bin_data_; std::vector<std::unique_ptr<Bin>> multi_bin_data_; /*! \brief True if this feature is sparse */ bool is_multi_val_; bool is_sparse_; int num_total_bin_; }; } // namespace LightGBM #endif // LIGHTGBM_FEATURE_GROUP_H_
ballAlgOMP.c
#include "../lib/msort.h" #include "ballAlg.h" #include "pointArith.h" #include <stdlib.h> extern int nDims; int buildTreeOMP(double **points, long nPoints, int nThreads) { if (nPoints == 0) return -1; double *center = (double *) mallocSafe(sizeof(double) * nDims); if (nPoints == 1) { copy(points[0], center); return newNode(center, 0, -1, -1); } double maxD; const int iA = calcFurthestIdx(points, nPoints, points[0], &maxD); const int iB = calcFurthestIdx(points, nPoints, points[iA], &maxD); double *subBA = (double *) mallocSafe(sizeof(double) * nDims); double *projectionsPoints = (double *) mallocSafe(sizeof(double) * nDims * nPoints); double **projections = (double **) mallocSafe(sizeof(double *) * nPoints); double **pointsTmp = (double **) mallocSafe(sizeof(double *) * nPoints); sub(points[iB], points[iA], subBA); const double squaredSubBA = innerProduct(subBA, subBA); for (long i = 0; i < nPoints; i++) { projections[i] = projectionsPoints + (i * nDims); if (i == iA || i == iB) { copy(points[i], projections[i]); } else { projection(points[i], points[iA], subBA, squaredSubBA, projections[i]); } } msort(projections, nPoints, pointsTmp); if (nPoints % 2 == 0) { middle(projections[nPoints / 2 - 1], projections[nPoints / 2], center); } else { copy(projections[nPoints / 2], center); } const double radius = distance(center, points[calcFurthestIdx(points, nPoints, center, &maxD)]); int nPointsL = 0; int nPointsR = 0; // Reusing Previous Allocated Arrays double **pointsL = projections; double **pointsR = pointsTmp; partitionTree(projectionsPoints, center[0], points, nPoints, pointsL, &nPointsL, pointsR, &nPointsR); pointsL = realloc(pointsL, sizeof(double *) * nPointsL); pointsR = realloc(pointsR, sizeof(double *) * nPointsR); free(subBA); free(projectionsPoints); int nidL, nidR; #pragma omp task shared(nidL) if (nThreads > 1) nidL = buildTreeOMP(pointsL, nPointsL, nThreads / 2); nidR = buildTreeOMP(pointsR, nPointsR, nThreads - nThreads / 2); #pragma omp taskwait free(projections); free(pointsTmp); return newNode(center, radius, nidL, nidR); }
morn_matrix.c
/* Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com> Licensed under the Apache License, Version 2.0; 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. */ #include "morn_math.h" struct HandleVectorCreate { MVector *vec; MChain *property; int64_t reserve[8]; int writeable; int size; MMemory *memory; }; void endVectorCreate(struct HandleVectorCreate *handle) { mException((handle->vec==NULL),EXIT,"invalid vector"); if(handle->property!=NULL) mChainRelease(handle->property); if(handle->memory != NULL) mMemoryRelease(handle->memory); memset(handle->vec,0,sizeof(MVector)); // mFree(((MList **)(handle->vec))-1); } #define HASH_VectorCreate 0xfc0b887c MVector *VectorCreate(int size,float *data) { MVector *vec = (MVector *)ObjectAlloc(sizeof(MVector)); MHandle *hdl=mHandle(vec,VectorCreate); struct HandleVectorCreate *handle = (struct HandleVectorCreate *)(hdl->handle); handle->vec = vec; if(size<0) size = 0; vec->size = size; if(size==0) { mException((!INVALID_POINTER(data)),EXIT,"invalid input"); } else if(INVALID_POINTER(data)) { handle->memory = mMemoryCreate(1,size*sizeof(float),MORN_HOST); handle->size = size; vec->data = handle->memory->data[0]; } else vec->data = data; mPropertyFunction(vec,"device",mornMemoryDevice,handle->memory); return vec; } void mVectorRelease(MVector *vec) { ObjectFree(vec); } void VectorRedefine(MVector *vec,int size,float *data) { mException(INVALID_POINTER(vec),EXIT,"invalid input"); if(size <= 0) size = vec->size; if(size!=vec->size)mHandleReset(vec); int same_size = (size <= vec->size); int reuse = (data==vec->data); int flag = (vec->size >0); vec->size=size; if(same_size&&reuse) return; struct HandleVectorCreate *handle = (struct HandleVectorCreate *)(ObjHandle(vec,0)->handle); if(same_size&&(data==NULL)&&(handle->size>0)) return; mException(reuse&&flag&&(handle->size==0),EXIT,"invalid redefine"); handle->size=0; if(size <= 0) {mException((data!=NULL)&&(!reuse),EXIT,"invalid input"); vec->data = NULL; return;} if(reuse) data=NULL; if(data!=NULL){vec->data = data; return;} if(size>handle->size) { handle->size = size; if(handle->memory==NULL) { handle->memory = mMemoryCreate(1,size*sizeof(float),MORN_HOST); mPropertyFunction(vec,"device",mornMemoryDevice,handle->memory); } else mMemoryRedefine(handle->memory,1,size*sizeof(float),DFLT); vec->data = handle->memory->data[0]; } } void _PrintMat(char *name,MMatrix *mat) { printf("%s:row=%d,col=%d:\n",name,mat->row,mat->col); int i,j; for(j=0;j<mat->row;j++) { for(i=0;i<mat->col;i++) printf("\t%f",mat->data[j][i]); printf("\n"); } } struct HandleMatrixCreate { MMatrix *mat; MChain *property; int64_t reserve[8]; int writeable; int row; int col; float **index; MMemory *memory; }; void endMatrixCreate(struct HandleMatrixCreate *handle) { mException((handle->mat == NULL),EXIT,"invalid matrix"); if(handle->property!= NULL) mChainRelease(handle->property); if(handle->index != NULL) mFree(handle->index); if(handle->memory != NULL) mMemoryRelease(handle->memory); memset(handle->mat,0,sizeof(MMatrix)); // mFree(((MList **)(handle->mat))-1); } #define HASH_MatrixCreate 0xe48fad76 MMatrix *MatrixCreate(int row,int col,float **data) { MMatrix *mat = (MMatrix *)ObjectAlloc(sizeof(MMatrix)); MHandle *hdl=mHandle(mat,MatrixCreate); struct HandleMatrixCreate *handle = (struct HandleMatrixCreate *)(hdl->handle); handle->mat = mat; if(col <0) {col = 0;} mat->col = col; if(row <0) {row = 0;} mat->row = row; if(row == 0) { mException((!INVALID_POINTER(data)),EXIT,"invalid input"); return mat; } if(!INVALID_POINTER(data)) { mat->data = data; return mat; } handle->index = (float **)mMalloc(row*sizeof(float *)); handle->row = row; if(col == 0) { mException((!INVALID_POINTER(data)),EXIT,"invalid input"); memset(handle->index,0,row*sizeof(float *)); } else { if(handle->memory == NULL)handle->memory = mMemoryCreate(1,row*col*sizeof(float),MORN_HOST); mException(handle->memory->num!=1,EXIT,"invalid image memory"); mMemoryIndex(handle->memory,row,col*sizeof(float),(void ***)(&(handle->index)),1); handle->col = col; } mat->data = handle->index; mPropertyFunction(mat,"device",mornMemoryDevice,handle->memory); return mat; } MMemoryBlock *mMatrixMemory(MMatrix *mat) { int size = mat->row*mat->col*sizeof(float); float *data = &(mat->data[0][0]); struct HandleMatrixCreate *handle= (struct HandleMatrixCreate *)(ObjHandle(mat,0)->handle); if(handle->memory == NULL) { handle->memory = mMemoryCreate(1,size,MORN_HOST); mPropertyFunction(mat,"device",mornMemoryDevice,handle->memory); } MMemoryBlock *mem = handle->memory->data[0]; if(mem->size!=size) mMemoryIndex(handle->memory,mat->row,mat->col*sizeof(float),(void ***)(&(handle->index)),1); // printf("handle->memory->data[0] if(mem->data!=data) memcpy(mem->data,data,size); return mem; } void mMatrixRelease(MMatrix *mat) { ObjectFree(mat); } void MatrixRedefine(MMatrix *mat,int row,int col,float **data) { mException((INVALID_POINTER(mat)),EXIT,"invalid input"); if(row<=0) row = mat->row; if(col<=0) col = mat->col; if((row!=mat->row)||(col!=mat->col)) mHandleReset(mat); int same_size=((row<=mat->row)&&(col<=mat->col)); int reuse = (data==mat->data); int flag=(mat->row)&&(mat->col); mat->row = row; mat->col = col; if(same_size&&reuse) return; struct HandleMatrixCreate *handle= (struct HandleMatrixCreate *)(ObjHandle(mat,0)->handle); if(same_size&&(data==NULL)&&(handle->col>0)) return; mException(reuse&&flag&&(handle->col==0),EXIT,"invalid redefine"); handle->col=0; if((row == 0)||(col==0)) {mException((data!=NULL)&&(!reuse),EXIT,"invalid input"); mat->data=NULL; return;} if(reuse) data=NULL; if(row>handle->row) { if(handle->index != NULL) mFree(handle->index); handle->index = NULL; } if(handle->index == NULL) { handle->index = (float **)mMalloc(row*sizeof(float *)); handle->row = row; } mat->data = handle->index; if(!INVALID_POINTER(data)) {memcpy(handle->index,data,row*sizeof(float *));return;} if(handle->memory == NULL) { handle->memory = mMemoryCreate(1,row*col*sizeof(float),MORN_HOST); mPropertyFunction(mat,"device",mornMemoryDevice,handle->memory); } else mMemoryRedefine(handle->memory,1,row*col*sizeof(float),DFLT); mMemoryIndex(handle->memory,row,col*sizeof(float),(void ***)(&(handle->index)),1); handle->col = col; } void m_UnitMatrix(MMatrix *mat,int size) { mException(mat==NULL,EXIT,"invalid input matrix"); if(size<0) { size = mat->row; mException(size!=mat->col,EXIT,"invalid input"); } else mMatrixRedefine(mat,size,size,mat->data); int i; #pragma omp parallel for for(i=0;i<size;i++) { memset(mat->data[i],0,size*sizeof(float)); mat->data[i][i] = 1.0f; } } void m_MatrixTranspose(MMatrix *mat,MMatrix *dst) { mException((INVALID_MAT(mat)),EXIT,"invalid input"); int i,j; int dst_col = mat->row; int dst_row = mat->col; MMatrix *p = dst; if((INVALID_POINTER(dst))||(dst==mat)) dst = mMatrixCreate(dst_row,dst_col,NULL); else mMatrixRedefine(dst,dst_row,dst_col,dst->data); float **s=mat->data; float **d=dst->data; int r=dst_row&0x03; int c=dst_col&0x03; for(j=0;j<r;j++) { for(i=0;i<c;i++) d[j][i]=s[i][j]; for(i=c;i<dst_col;i+=4) { d[j][i]=s[i][j];d[j][i+1]=s[i+1][j];d[j][i+2]=s[i+2][j];d[j][i+3]=s[i+3][j]; } } #pragma omp parallel for for(j=r;j<dst_row;j+=4) { for(i=0;i<c;i++) { d[j][i]=s[i][j];d[j+1][i]=s[i][j+1];d[j+2][i]=s[i][j+2];d[j+3][i]=s[i][j+3]; } for(i=c;i<dst_col;i+=4) { d[j ][i]=s[i][j ];d[j ][i+1]=s[i+1][j ];d[j ][i+2]=s[i+2][j ];d[j ][i+3]=s[i+3][j ]; d[j+1][i]=s[i][j+1];d[j+1][i+1]=s[i+1][j+1];d[j+1][i+2]=s[i+2][j+1];d[j+1][i+3]=s[i+3][j+1]; d[j+2][i]=s[i][j+2];d[j+2][i+1]=s[i+1][j+2];d[j+2][i+2]=s[i+2][j+2];d[j+2][i+3]=s[i+3][j+2]; d[j+3][i]=s[i][j+3];d[j+3][i+1]=s[i+1][j+3];d[j+3][i+2]=s[i+2][j+3];d[j+3][i+3]=s[i+3][j+3]; } } if(p!=dst) { mObjectExchange(mat,dst,MMatrix); mMatrixRelease(dst); } } void VectorAdd(float *vec1,float *vec2,float *dst,int num) { int i; for(i=0;i<num;i++) dst[i] = vec1[i]+vec2[i]; } void mVectorAdd(MVector *vec1,MVector *vec2,MVector *dst) { int i; mException((INVALID_VEC(vec1)||INVALID_VEC(vec2)||(vec1->size !=vec2->size)),EXIT,"invalid input"); if(INVALID_POINTER(dst)) dst = vec1; else mVectorRedefine(dst,vec1->size,dst->data,vec1->device); for(i=0;i<vec1->size;i++) dst->data[i] = vec1->data[i] + vec2->data[i]; } void mMatrixAdd(MMatrix *mat1,MMatrix *mat2,MMatrix *dst) { int j; mException(INVALID_MAT(mat1)||INVALID_MAT(mat2),EXIT,"invalid input"); mException((mat1->row!=mat2->row)||(mat1->col!=mat2->col),EXIT,"invalid input"); if(INVALID_POINTER(dst)) dst = mat1; else mMatrixRedefine(dst,mat1->row,mat1->col,dst->data,DFLT); #pragma omp parallel for for(j=0;j<dst->row;j++) for(int i=0;i<dst->col;i++) dst->data[j][i] = mat1->data[j][i]+mat2->data[j][i]; } void mMatrixSub(MMatrix *mat1,MMatrix *mat2,MMatrix *dst) { int j; mException(INVALID_MAT(mat1)||INVALID_MAT(mat2),EXIT,"invalid input"); mException((mat1->row!=mat2->row)||(mat1->col!=mat2->col),EXIT,"invalid input"); if(INVALID_POINTER(dst)) dst = mat1; else mMatrixRedefine(dst,mat1->row,mat1->col,dst->data,DFLT); #pragma omp parallel for for(j=0;j<dst->row;j++) for(int i=0;i<dst->col;i++) dst->data[j][i] = mat1->data[j][i]+mat2->data[j][i]; } float VectorMul(float *vec1,float *vec2,int num) { int i; float sum; sum = 0.0f; for(i=0;i<num;i++) sum = sum + vec1[i]*vec2[i]; return sum; } float mVectorMul(MVector *vec1,MVector *vec2) { int i; float result; mException((INVALID_VEC(vec1)||INVALID_VEC(vec2)||(vec1->size !=vec2->size)),EXIT,"invalid input"); result = 0.0f; for(i=0;i<vec1->size;i++) result = result + vec1->data[i]*vec2->data[i]; return result; } void VectorScalarMul(float *vec1,float *vec2,float *dst,int num) { int i; for(i=0;i<num;i++) dst[i] = vec1[i]*vec2[i]; } void mVectorScalarMul(MVector *vec1,MVector *vec2,MVector *dst) { int i; mException((INVALID_VEC(vec1)||INVALID_VEC(vec2)||(vec1->size !=vec2->size)),EXIT,"invalid input"); if(INVALID_POINTER(dst)) dst = vec1; else mVectorRedefine(dst,vec1->size,dst->data,vec1->device); for(i=0;i<vec1->size;i++) dst->data[i] = vec1->data[i] * vec2->data[i]; } void MatrixVectorMul(MMatrix *mat,float *vec,float *dst) { int i,j; int num_in,num_out; num_in = mat->col; num_out = mat->row; memset(dst,0,num_out*sizeof(float)); for(i=0;i<num_out;i++) for(j=0;j<num_in;j++) dst[i] = dst[i] + vec[j]*mat->data[i][j]; } void mMatrixVectorMul(MMatrix *mat,MVector *vec,MVector *dst) { int i,j; int num_in; int num_out; MVector *p= dst; mException((INVALID_MAT(mat)||INVALID_VEC(vec)),EXIT,"invalid input"); num_in = mat->col; mException((vec->size != num_in),EXIT,"invalid input"); num_out = mat->row; if(INVALID_POINTER(dst)||(dst == vec)) dst = mVectorCreate(num_out,NULL,vec->device); else mVectorRedefine(dst,num_out,dst->data,vec->device); for(i=0;i<num_out;i++) { dst->data[i] = 0.0f; for(j=0;j<num_in;j++) dst->data[i] = dst->data[i] + vec->data[j]*mat->data[i][j]; } if(p!=dst) { mObjectExchange(dst,vec,MVector); mVectorRelease(dst); } } void VectorMatrixMul(float *vec,MMatrix *mat,float *dst) { int i,j; int num_in,num_out; num_in = mat->row; num_out = mat->col; memset(dst,0,num_out*sizeof(float)); for(j=0;j<num_in;j++) for(i=0;i<num_out;i++) dst[i] = dst[i] + vec[j]*mat->data[j][i]; } void mVectorMatrixMul(MVector *vec,MMatrix *mat,MVector *dst) { int i,j; int num_in; int num_out; MVector *p; mException(((INVALID_MAT(mat))||(INVALID_VEC(vec))),EXIT,"invalid input"); p = dst; num_in = mat->row; mException((vec->size != num_in),EXIT,"invalid input"); num_out = mat->col; if(INVALID_POINTER(dst)||(dst == vec)) dst = mVectorCreate(num_out,NULL,vec->device); else mVectorRedefine(dst,num_out,dst->data,vec->device); for(i=0;i<num_out;i++) { dst->data[i] = 0.0f; for(j=0;j<num_in;j++) dst->data[i] = dst->data[i] + vec->data[j]*mat->data[j][i]; } if(p!=dst) { mObjectExchange(vec,dst,MVector); mVectorRelease(dst); } } void mMatrixScalar(MMatrix *src,MMatrix *dst,float k,float b) { mException((src==NULL),EXIT,"invalid input"); if(dst==NULL) dst=src; for(int j=0;j<src->row;j++)for(int i=0;i<src->col;i++) dst->data[j][i] = src->data[j][i]*k+b; } void mMatrixScalarMul(MMatrix *mat1,MMatrix *mat2,MMatrix *dst) { int i,j; mException((INVALID_MAT(mat1)||INVALID_MAT(mat2)),EXIT,"invalid input"); mException((mat1->row != mat2->row)||(mat1->col != mat2->col),EXIT,"invalid input"); if(INVALID_POINTER(dst)) dst = mat1; else mMatrixRedefine(dst,mat1->row,mat1->col,dst->data,DFLT); for(j=0;j<mat1->row;j++) for(i=0;i<mat1->col;i++) dst->data[j][i] = mat1->data[j][i]*mat2->data[j][i]; } /* void mMatrixMul0(MMatrix *mat1,MMatrix *mat2,MMatrix *dst) { int i,j,k; int dst_col,dst_row; int num; MMatrix *p; float data; float *psrc,*pdst; mException((INVALID_MAT(mat1))||(INVALID_MAT(mat2)),EXIT,"invalid input"); mException((mat1->col != mat2->row),EXIT,"invalid operate"); num = mat1->col; dst_col = mat2->col; dst_row = mat1->row; p = dst; if((INVALID_POINTER(dst))||(dst==mat1)||(dst==mat2)) dst = mMatrixCreate(dst_row,dst_col,NULL); else mMatrixRedefine(dst,dst_row,dst_col,dst->data); for(j=0;j<dst_row;j++) { pdst = dst->data[j]; { data = mat1->data[j][0]; psrc = mat2->data[0]; for(k=0;k<dst_col-8;k=k+8) { pdst[k] = data*psrc[k]; pdst[k+1] = data*psrc[k+1]; pdst[k+2] = data*psrc[k+2]; pdst[k+3] = data*psrc[k+3]; pdst[k+4] = data*psrc[k+4]; pdst[k+5] = data*psrc[k+5]; pdst[k+6] = data*psrc[k+6]; pdst[k+7] = data*psrc[k+7]; } for(;k<dst_col;k++) pdst[k] = data*psrc[k]; } for(i=1;i<num;i++) { data = mat1->data[j][i]; psrc = mat2->data[i]; for(k=0;k<dst_col-8;k=k+8) { pdst[k] += data*psrc[k]; pdst[k+1] += data*psrc[k+1]; pdst[k+2] += data*psrc[k+2]; pdst[k+3] += data*psrc[k+3]; pdst[k+4] += data*psrc[k+4]; pdst[k+5] += data*psrc[k+5]; pdst[k+6] += data*psrc[k+6]; pdst[k+7] += data*psrc[k+7]; } for(;k<dst_col;k++) pdst[k] += data*psrc[k]; } } if(p != dst) { if(p == mat2) { mMatrixExchange(mat2,dst); mMatrixRelease(dst); } else { mMatrixExchange(mat1,dst); mMatrixRelease(dst); } } } */ void mMatrixMul(MMatrix *mat1,MMatrix *mat2,MMatrix *dst) { mException((INVALID_MAT(mat1))||(INVALID_MAT(mat2)),EXIT,"invalid input"); mException((mat1->col != mat2->row),EXIT,"invalid operate"); int num = mat1->col; int dst_col = mat2->col; int dst_row = mat1->row; MMatrix *p = dst; if((INVALID_POINTER(dst))||(dst==mat1)||(dst==mat2)) dst = mMatrixCreate(dst_row,dst_col); else mMatrixRedefine(dst,dst_row,dst_col,dst->data); int flag = num&0x03; if(flag==0) flag = 4; int i,j,k; float data1,data2,data3,data4; float *psrc1,*psrc2,*psrc3,*psrc4; float *pdst; #pragma omp parallel for for(j=0;j<dst_row;j++) { pdst = dst->data[j]; data1 = mat1->data[j][0]; psrc1 = mat2->data[0]; for(k=0;k<dst_col;k++) pdst[k] = data1*psrc1[k]; for(i=1;i<flag;i++) { data1 = mat1->data[j][i]; psrc1 = mat2->data[i]; for(k=0;k<dst_col;k++) pdst[k]+= data1*psrc1[k]; } for(i=flag;i<num;i=i+4) { data1 = mat1->data[j][i ]; psrc1 = mat2->data[i ]; data2 = mat1->data[j][i+1]; psrc2 = mat2->data[i+1]; data3 = mat1->data[j][i+2]; psrc3 = mat2->data[i+2]; data4 = mat1->data[j][i+3]; psrc4 = mat2->data[i+3]; for(k=0;k<dst_col;k++) pdst[k] += data1*psrc1[k]+data2*psrc2[k]+data3*psrc3[k]+data4*psrc4[k]; } } if(p != dst) { if(p == mat2) {mObjectExchange(mat2,dst,MMatrix); mMatrixRelease(dst);} else {mObjectExchange(mat1,dst,MMatrix); mMatrixRelease(dst);} } } float mMatrixDetValue(MMatrix *mat) { int i,j,k; int num; double *buff; double w; double value; double **data; mException((INVALID_MAT(mat)),EXIT,"invalid input"); num = mat->row; mException((mat->col != num),EXIT,"invalid operate"); if(num == 1) return mat->data[0][0]; if(num == 2) { value = mat->data[0][0]*mat->data[1][1]-mat->data[1][0]*mat->data[0][1]; return value; } if(num == 3) { value = mat->data[0][0]*(mat->data[1][1]*mat->data[2][2]-mat->data[1][2]*mat->data[2][1]) + mat->data[0][1]*(mat->data[1][2]*mat->data[2][0]-mat->data[1][0]*mat->data[2][2]) + mat->data[0][2]*(mat->data[1][0]*mat->data[2][1]-mat->data[1][1]*mat->data[2][0]); return value; } data = (double **)mMalloc((num+1)*sizeof(double *)); data[0] = (double *)mMalloc(num*num*sizeof(double)); for(j=0;j<num;j++) { for(i=0;i<num;i++) data[j][i] = (double)(mat->data[j][i]); data[j+1] = data[j]+num; } // data = mMatrixCreate(num,num,NULL); // for(j=0;j<num;j++) // memcpy(data->data[j],mat->data[j],num*sizeof(float)); // PrintMat(data); // #define DATA(y,x) (data[y][x]) value = 1.0; // 高斯消元 for(k=0;k<num;k++) { if(data[k][k]==0) { for(j=k+1;j<num;j++) if(data[j][k]!=0) { buff = data[k]; data[k] = data[j]; data[j] = buff; value = 0-value; break; } // 如果无解则返回0 if(j==num) { mFree(data); mFree(data[0]); return 0.0f; } } value = value * data[k][k]; for(j=k+1;j<num;j++) // if(data[j][k]!=0) { w = data[j][k]/data[k][k]; for(i=k+1;i<num;i++) data[j][i] = data[j][i]-w*data[k][i]; } // printf("aaaaaaaaaa %d:%f\n",k,data[k][k]); // PrintMat(data); } mFree(data[0]); mFree(data); return (float)value; } int mMatrixInverse(MMatrix *mat,MMatrix *inv) { int i,j,k; int num; double *buff; double w; double **data; // MMatrix *data; MMatrix *p; mException((INVALID_MAT(mat)),EXIT,"invalid input"); num = mat->row; mException((mat->col != num),EXIT,"invalid operate"); p = inv; if((INVALID_POINTER(inv))||(inv == mat)) inv = mMatrixCreate(num,num,NULL); else mMatrixRedefine(inv,num,num,inv->data,DFLT); data = (double **)mMalloc((num+1)*sizeof(double *)); data[0] = (double *)mMalloc((num+num)*num*sizeof(double)); for(j=0;j<num;j++) { for(i=0;i<num;i++) data[j][i] = (double)(mat->data[j][i]); memset(data[j]+num,0,num*sizeof(double)); data[j][num+j] = -1.0; data[j+1] = data[j]+num+num; } // data = mMatrixCreate(num,num+num,NULL); // for(j=0;j<num;j++) // { // memcpy(data->data[j],mat->data[j],num*sizeof(float)); // memset(data->data[j] + num,0,num*sizeof(float)); // data->data[j][num+j] = -1.0; // } // PrintMat(data); // #define DATA(y,x) (data->data[y][x]) // 高斯消元 for(k=0;k<num;k++) { if(data[k][k]==0) { for(j=k+1;j<num;j++) if(data[j][k]!=0) { buff = data[k]; data[k] = data[j]; data[j] = buff; break; } // 如果无解则返回0 if(j==num) { mFree(data); mFree(data[0]); if(p!=inv) mMatrixRelease(inv); return 0.0; } } for(j=k+1;j<num;j++) if(data[j][k]!=0) { w = data[j][k]/data[k][k]; // data[j][k]=0; for(i=k+1;i<num+num;i++) data[j][i] = data[j][i]-w*data[k][i]; } // printf("aaaaaaaaaa %d\n",k); // PrintMat(data); } for(k=0;k<num;k++) { for(j=num-1;j>=0;j--) { data[j][num+k] = 0-data[j][num+k]; for(i=num-1;i>j;i--) data[j][num+k] = data[j][num+k] - data[j][i]*data[i][num+k]; data[j][num+k] = data[j][num+k]/data[j][j]; inv->data[j][k] = (float)data[j][num+k]; } } mFree(data[0]); mFree(data); if(p!=inv) { mObjectExchange(inv,mat,MMatrix); mMatrixRelease(inv); } return 1; } int mLinearEquation(MMatrix *mat,float *answer) { int i,j,k; float *buff; float w; MMatrix *data; mException((INVALID_MAT(mat))||(INVALID_POINTER(answer)),EXIT,"invalid input"); mException(((mat->col - mat->row)!=1),EXIT,"invalid operate"); int num = mat->row; if(num == 1) { mException((mat->data[0][0]==0.0f),EXIT,"invalid input"); *answer = (0.0f-mat->data[0][1])/mat->data[0][0]; return 1; } data = mMatrixCreate(num,num+1,NULL); for(j=0;j<num;j++) memcpy(data->data[j],mat->data[j],(num+1)*sizeof(float)); #define DATA(y,x) (data->data[y][x]) // 高斯消元 for(k=0;k<num;k++) { if(DATA(k,k)==0) { for(j=k+1;j<num;j++) if(DATA(j,k)!=0) { buff = data->data[k]; data->data[k] = data->data[j]; data->data[j] = buff; break; } // 如果无解则返回0 if(j==num) { mMatrixRelease(data); return 0; } } for(j=k+1;j<num;j++) if(DATA(j,k)!=0) { w = DATA(j,k)/DATA(k,k); DATA(j,k)=0; for(i=k+1;i<num+1;i++) DATA(j,i) = DATA(j,i)-w*DATA(k,i); } } // 答案求解 for(j=num-1;j>=0;j--) { answer[j] = 0-DATA(j,num); for(i=num-1;i>j;i--) answer[j] = answer[j] - DATA(j,i)*answer[i]; answer[j] = answer[j]/DATA(j,j); } mMatrixRelease(data); return 1; }
GB_binop__lor_int16.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__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_08__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_02__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_04__lor_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lor_int16) // A*D function (colscale): GB (_AxD__lor_int16) // D*A function (rowscale): GB (_DxB__lor_int16) // C+=B function (dense accum): GB (_Cdense_accumB__lor_int16) // C+=b function (dense accum): GB (_Cdense_accumb__lor_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lor_int16) // C=scalar+B GB (_bind1st__lor_int16) // C=scalar+B' GB (_bind1st_tran__lor_int16) // C=A+scalar GB (_bind2nd__lor_int16) // C=A'+scalar GB (_bind2nd_tran__lor_int16) // C type: int16_t // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = ((aij != 0) || (bij != 0)) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_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) \ int16_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) \ int16_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) \ int16_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 != 0) || (y != 0)) ; // 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_LOR || GxB_NO_INT16 || GxB_NO_LOR_INT16) //------------------------------------------------------------------------------ // 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__lor_int16) ( 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__lor_int16) ( 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__lor_int16) ( 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 int16_t int16_t bwork = (*((int16_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__lor_int16) ( 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 int16_t *restrict Cx = (int16_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__lor_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_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__lor_int16) ( 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) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_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__lor_int16) ( 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__lor_int16) ( 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__lor_int16) ( 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__lor_int16) ( 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__lor_int16) ( 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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_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 ; int16_t bij = GBX (Bx, p, false) ; 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__lor_int16) ( 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 ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; 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 typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) || (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lor_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) || (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lor_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
par_relax_more.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) ******************************************************************************/ /****************************************************************************** * * a few more relaxation schemes: Chebychev, FCF-Jacobi, CG - * these do not go through the CF interface (hypre_BoomerAMGRelaxIF) * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "float.h" /****************************************************************************** * * use Gershgorin discs to estimate smallest and largest eigenvalues * A is assumed to be symmetric * For SPD matrix, it returns [0, max_eig = max (aii + ri)], * ri is radius of disc centered at a_ii * For SND matrix, it returns [min_eig = min (aii - ri), 0] * * scale > 0: compute eigen estimate of D^{-1/2}*A*D^{-1/2}, where * D = diag(A) for SPD matrix, D = -diag(A) for SND * * scale = 1: The algorithm is performed on D^{-1}*A, since it * has the same eigenvalues as D^{-1/2}*A*D^{-1/2} * scale = 2: The algorithm is performed on D^{-1/2}*A*D^{-1/2} (TODO) * *****************************************************************************/ HYPRE_Int hypre_ParCSRMaxEigEstimateHost( hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal? */ HYPRE_Real *max_eig, HYPRE_Real *min_eig ) { HYPRE_Int A_num_rows = hypre_ParCSRMatrixNumRows(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A)); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(hypre_ParCSRMatrixDiag(A)); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(hypre_ParCSRMatrixOffd(A)); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A)); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(hypre_ParCSRMatrixOffd(A)); HYPRE_Real *diag = NULL; HYPRE_Int i, j; HYPRE_Real e_max, e_min; HYPRE_Real send_buf[2], recv_buf[2]; HYPRE_MemoryLocation memory_location = hypre_ParCSRMatrixMemoryLocation(A); if (scale > 1) { diag = hypre_TAlloc(HYPRE_Real, A_num_rows, memory_location); } for (i = 0; i < A_num_rows; i++) { HYPRE_Real a_ii = 0.0, r_i = 0.0, lower, upper; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { if (A_diag_j[j] == i) { a_ii = A_diag_data[j]; } else { r_i += hypre_abs(A_diag_data[j]); } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { r_i += hypre_abs(A_offd_data[j]); } lower = a_ii - r_i; upper = a_ii + r_i; if (scale == 1) { lower /= hypre_abs(a_ii); upper /= hypre_abs(a_ii); } if (i) { e_max = hypre_max(e_max, upper); e_min = hypre_min(e_min, lower); } else { e_max = upper; e_min = lower; } } send_buf[0] = -e_min; send_buf[1] = e_max; /* get e_min e_max across procs */ hypre_MPI_Allreduce(send_buf, recv_buf, 2, HYPRE_MPI_REAL, hypre_MPI_MAX, hypre_ParCSRMatrixComm(A)); e_min = -recv_buf[0]; e_max = recv_buf[1]; /* return */ if ( hypre_abs(e_min) > hypre_abs(e_max) ) { *min_eig = e_min; *max_eig = hypre_min(0.0, e_max); } else { *min_eig = hypre_max(e_min, 0.0); *max_eig = e_max; } hypre_TFree(diag, memory_location); return hypre_error_flag; } /** * @brief Estimates the max eigenvalue using infinity norm. Will determine * whether or not to use host or device internally * * @param[in] A Matrix to relax with * @param[in] to scale by diagonal * @param[out] Maximum eigenvalue */ HYPRE_Int hypre_ParCSRMaxEigEstimate(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Real *max_eig, HYPRE_Real *min_eig) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ParCSRMaxEigEstimate"); #endif HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); HYPRE_Int ierr = 0; if (exec == HYPRE_EXEC_HOST) { ierr = hypre_ParCSRMaxEigEstimateHost(A,scale,max_eig,min_eig); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) else { ierr = hypre_ParCSRMaxEigEstimateDevice(A,scale,max_eig,min_eig); } #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; } /** * @brief Uses CG to get the eigenvalue estimate. Will determine whether to use * host or device internally * * @param[in] A Matrix to relax with * @param[in] scale Gets the eigenvalue est of D^{-1/2} A D^{-1/2} * @param[in] max_iter Maximum number of iterations for CG * @param[out] max_eig Estimated max eigenvalue * @param[out] min_eig Estimated min eigenvalue */ HYPRE_Int hypre_ParCSRMaxEigEstimateCG(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int max_iter, HYPRE_Real *max_eig, HYPRE_Real *min_eig) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ParCSRMaxEigEstimateCG"); #endif HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1(hypre_ParCSRMatrixMemoryLocation(A)); HYPRE_Int ierr = 0; if (exec == HYPRE_EXEC_HOST) { ierr = hypre_ParCSRMaxEigEstimateCGHost(A, scale, max_iter, max_eig, min_eig); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) else { ierr = hypre_ParCSRMaxEigEstimateCGDevice(A, scale, max_iter, max_eig, min_eig); } #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; } /** * @brief Uses CG to get the eigenvalue estimate on the host * * @param[in] A Matrix to relax with * @param[in] scale Gets the eigenvalue est of D^{-1/2} A D^{-1/2} * @param[in] max_iter Maximum number of iterations for CG * @param[out] max_eig Estimated max eigenvalue * @param[out] min_eig Estimated min eigenvalue */ HYPRE_Int hypre_ParCSRMaxEigEstimateCGHost( hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int max_iter, HYPRE_Real *max_eig, HYPRE_Real *min_eig ) { HYPRE_Int i, j, err; hypre_ParVector *p; hypre_ParVector *s; hypre_ParVector *r; hypre_ParVector *ds; hypre_ParVector *u; HYPRE_Real *tridiag = NULL; HYPRE_Real *trioffd = NULL; HYPRE_Real lambda_max ; HYPRE_Real beta, gamma = 0.0, alpha, sdotp, gamma_old, alphainv; HYPRE_Real lambda_min; HYPRE_Real *s_data, *p_data, *ds_data, *u_data; HYPRE_Int local_size = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); /* check the size of A - don't iterate more than the size */ HYPRE_BigInt size = hypre_ParCSRMatrixGlobalNumRows(A); if (size < (HYPRE_BigInt) max_iter) { max_iter = (HYPRE_Int) size; } /* create some temp vectors: p, s, r , ds, u*/ r = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(r); p = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(p); s = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(s); ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(ds); u = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(u); /* point to local data */ s_data = hypre_VectorData(hypre_ParVectorLocalVector(s)); p_data = hypre_VectorData(hypre_ParVectorLocalVector(p)); ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds)); u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); /* make room for tri-diag matrix */ tridiag = hypre_CTAlloc(HYPRE_Real, max_iter+1, HYPRE_MEMORY_HOST); trioffd = hypre_CTAlloc(HYPRE_Real, max_iter+1, HYPRE_MEMORY_HOST); for (i=0; i < max_iter + 1; i++) { tridiag[i] = 0; trioffd[i] = 0; } /* set residual to random */ hypre_ParVectorSetRandomValues(r,1); if (scale) { hypre_CSRMatrixExtractDiagonal(hypre_ParCSRMatrixDiag(A), ds_data, 4); } else { /* set ds to 1 */ hypre_ParVectorSetConstantValues(ds,1.0); } /* gamma = <r,Cr> */ gamma = hypre_ParVectorInnerProd(r,p); /* for the initial filling of the tridiag matrix */ beta = 1.0; i = 0; while (i < max_iter) { /* s = C*r */ /* TO DO: C = diag scale */ hypre_ParVectorCopy(r, s); /*gamma = <r,Cr> */ gamma_old = gamma; gamma = hypre_ParVectorInnerProd(r,s); if (i==0) { beta = 1.0; /* p_0 = C*r */ hypre_ParVectorCopy(s, p); } else { /* beta = gamma / gamma_old */ beta = gamma / gamma_old; /* p = s + beta p */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j=0; j < local_size; j++) { p_data[j] = s_data[j] + beta*p_data[j]; } } if (scale) { /* s = D^{-1/2}A*D^{-1/2}*p */ for (j = 0; j < local_size; j++) { u_data[j] = ds_data[j] * p_data[j]; } hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, s); for (j = 0; j < local_size; j++) { s_data[j] = ds_data[j] * s_data[j]; } } else { /* s = A*p */ hypre_ParCSRMatrixMatvec(1.0, A, p, 0.0, s); } /* <s,p> */ sdotp = hypre_ParVectorInnerProd(s,p); /* alpha = gamma / <s,p> */ alpha = gamma/sdotp; /* get tridiagonal matrix */ alphainv = 1.0/alpha; tridiag[i+1] = alphainv; tridiag[i] *= beta; tridiag[i] += alphainv; trioffd[i+1] = alphainv; trioffd[i] *= sqrt(beta); /* x = x + alpha*p */ /* don't need */ /* r = r - alpha*s */ hypre_ParVectorAxpy( -alpha, s, r); i++; } /* eispack routine - eigenvalues return in tridiag and ordered*/ hypre_LINPACKcgtql1(&i,tridiag,trioffd,&err); lambda_max = tridiag[i-1]; lambda_min = tridiag[0]; /* hypre_printf("linpack max eig est = %g\n", lambda_max);*/ /* hypre_printf("linpack min eig est = %g\n", lambda_min);*/ hypre_TFree(tridiag, HYPRE_MEMORY_HOST); hypre_TFree(trioffd, HYPRE_MEMORY_HOST); hypre_ParVectorDestroy(r); hypre_ParVectorDestroy(s); hypre_ParVectorDestroy(p); hypre_ParVectorDestroy(ds); hypre_ParVectorDestroy(u); /* return */ *max_eig = lambda_max; *min_eig = lambda_min; return hypre_error_flag; } /****************************************************************************** Chebyshev relaxation Can specify order 1-4 (this is the order of the resid polynomial)- here we explicitly code the coefficients (instead of iteratively determining) variant 0: standard chebyshev this is rlx 11 if scale = 0, and 16 if scale == 1 variant 1: modified cheby: T(t)* f(t) where f(t) = (1-b/t) this is rlx 15 if scale = 0, and 17 if scale == 1 ratio indicates the percentage of the whole spectrum to use (so .5 means half, and .1 means 10percent) *******************************************************************************/ HYPRE_Int hypre_ParCSRRelax_Cheby(hypre_ParCSRMatrix *A, /* matrix to relax with */ hypre_ParVector *f, /* right-hand side */ HYPRE_Real max_eig, HYPRE_Real min_eig, HYPRE_Real fraction, HYPRE_Int order, /* polynomial order */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int variant, hypre_ParVector *u, /* initial/updated approximation */ hypre_ParVector *v, /* temporary vector */ hypre_ParVector *r /*another temp vector */) { HYPRE_Real *coefs = NULL; HYPRE_Real *ds_data = NULL; hypre_ParVector *tmp_vec = NULL; hypre_ParVector *orig_u_vec = NULL; hypre_ParCSRRelax_Cheby_Setup(A, max_eig, min_eig, fraction, order, scale, variant, &coefs, &ds_data); orig_u_vec = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize_v2(orig_u_vec, hypre_ParCSRMatrixMemoryLocation(A)); if (scale) { tmp_vec = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize_v2(tmp_vec, hypre_ParCSRMatrixMemoryLocation(A)); } hypre_ParCSRRelax_Cheby_Solve(A, f, ds_data, coefs, order, scale, variant, u, v, r, orig_u_vec, tmp_vec); hypre_TFree(ds_data, hypre_ParCSRMatrixMemoryLocation(A)); hypre_TFree(coefs, HYPRE_MEMORY_HOST); hypre_ParVectorDestroy(orig_u_vec); hypre_ParVectorDestroy(tmp_vec); return hypre_error_flag; } /*-------------------------------------------------------------------------- * CG Smoother *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRRelax_CG( HYPRE_Solver solver, hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int num_its) { HYPRE_PCGSetMaxIter(solver, num_its); /* max iterations */ HYPRE_PCGSetTol(solver, 0.0); /* max iterations */ HYPRE_ParCSRPCGSolve(solver, (HYPRE_ParCSRMatrix)A, (HYPRE_ParVector)f, (HYPRE_ParVector)u); #if 0 { HYPRE_Int myid; HYPRE_Int num_iterations; HYPRE_Real final_res_norm; hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid); HYPRE_PCGGetNumIterations(solver, &num_iterations); HYPRE_PCGGetFinalRelativeResidualNorm(solver, &final_res_norm); if (myid ==0) { hypre_printf(" -----CG PCG Iterations = %d\n", num_iterations); hypre_printf(" -----CG PCG Final Relative Residual Norm = %e\n", final_res_norm); } } #endif return hypre_error_flag; } /* tql1.f -- this is the eispack translation - from Barry Smith in Petsc Note that this routine always uses real numbers (not complex) even if the underlying matrix is Hermitian. This is because the Lanczos process applied to Hermitian matrices always produces a real, symmetric tridiagonal matrix. */ HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int *n,HYPRE_Real *d,HYPRE_Real *e,HYPRE_Int *ierr) { /* System generated locals */ HYPRE_Int i__1,i__2; HYPRE_Real d__1,d__2,c_b10 = 1.0; /* Local variables */ HYPRE_Real c,f,g,h; HYPRE_Int i,j,l,m; HYPRE_Real p,r,s,c2,c3 = 0.0; HYPRE_Int l1,l2; HYPRE_Real s2 = 0.0; HYPRE_Int ii; HYPRE_Real dl1,el1; HYPRE_Int mml; HYPRE_Real tst1,tst2; /* THIS SUBROUTINE IS A TRANSLATION OF THE ALGOL PROCEDURE TQL1, */ /* NUM. MATH. 11, 293-306(1968) BY BOWDLER, MARTIN, REINSCH, AND */ /* WILKINSON. */ /* HANDBOOK FOR AUTO. COMP., VOL.II-LINEAR ALGEBRA, 227-240(1971). */ /* THIS SUBROUTINE FINDS THE EIGENVALUES OF A SYMMETRIC */ /* TRIDIAGONAL MATRIX BY THE QL METHOD. */ /* ON INPUT */ /* N IS THE ORDER OF THE MATRIX. */ /* D CONTAINS THE DIAGONAL ELEMENTS OF THE INPUT MATRIX. */ /* E CONTAINS THE SUBDIAGONAL ELEMENTS OF THE INPUT MATRIX */ /* IN ITS LAST N-1 POSITIONS. E(1) IS ARBITRARY. */ /* ON OUTPUT */ /* D CONTAINS THE EIGENVALUES IN ASCENDING ORDER. IF AN */ /* ERROR EXIT IS MADE, THE EIGENVALUES ARE CORRECT AND */ /* ORDERED FOR INDICES 1,2,...IERR-1, BUT MAY NOT BE */ /* THE SMALLEST EIGENVALUES. */ /* E HAS BEEN DESTROYED. */ /* IERR IS SET TO */ /* ZERO FOR NORMAL RETURN, */ /* J IF THE J-TH EIGENVALUE HAS NOT BEEN */ /* DETERMINED AFTER 30 ITERATIONS. */ /* CALLS CGPTHY FOR DSQRT(A*A + B*B) . */ /* QUESTIONS AND COMMENTS SHOULD BE DIRECTED TO BURTON S. GARBOW, */ /* MATHEMATICS AND COMPUTER SCIENCE DIV, ARGONNE NATIONAL LABORATORY */ /* THIS VERSION DATED AUGUST 1983. */ /* ------------------------------------------------------------------ */ HYPRE_Real ds; --e; --d; *ierr = 0; if (*n == 1) { goto L1001; } i__1 = *n; for (i = 2; i <= i__1; ++i) { e[i - 1] = e[i]; } f = 0.; tst1 = 0.; e[*n] = 0.; i__1 = *n; for (l = 1; l <= i__1; ++l) { j = 0; h = (d__1 = d[l],fabs(d__1)) + (d__2 = e[l],fabs(d__2)); if (tst1 < h) { tst1 = h; } /* .......... LOOK FOR SMALL SUB-DIAGONAL ELEMENT .......... */ i__2 = *n; for (m = l; m <= i__2; ++m) { tst2 = tst1 + (d__1 = e[m],fabs(d__1)); if (tst2 == tst1) { goto L120; } /* .......... E(N) IS ALWAYS ZERO,SO THERE IS NO EXIT */ /* THROUGH THE BOTTOM OF THE LOOP .......... */ } L120: if (m == l) { goto L210; } L130: if (j == 30) { goto L1000; } ++j; /* .......... FORM SHIFT .......... */ l1 = l + 1; l2 = l1 + 1; g = d[l]; p = (d[l1] - g) / (e[l] * 2.); r = hypre_LINPACKcgpthy(&p,&c_b10); ds = 1.0; if (p < 0.0) ds = -1.0; d[l] = e[l] / (p + ds*r); d[l1] = e[l] * (p + ds*r); dl1 = d[l1]; h = g - d[l]; if (l2 > *n) { goto L145; } i__2 = *n; for (i = l2; i <= i__2; ++i) { d[i] -= h; } L145: f += h; /* .......... QL TRANSFORMATION .......... */ p = d[m]; c = 1.; c2 = c; el1 = e[l1]; s = 0.; mml = m - l; /* .......... FOR I=M-1 STEP -1 UNTIL L DO -- .......... */ i__2 = mml; for (ii = 1; ii <= i__2; ++ii) { c3 = c2; c2 = c; s2 = s; i = m - ii; g = c * e[i]; h = c * p; r = hypre_LINPACKcgpthy(&p,&e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; tst2 = tst1 + (d__1 = e[l],fabs(d__1)); if (tst2 > tst1) { goto L130; } L210: p = d[l] + f; /* .......... ORDER EIGENVALUES .......... */ if (l == 1) { goto L250; } /* .......... FOR I=L STEP -1 UNTIL 2 DO -- .......... */ i__2 = l; for (ii = 2; ii <= i__2; ++ii) { i = l + 2 - ii; if (p >= d[i - 1]) { goto L270; } d[i] = d[i - 1]; } L250: i = 1; L270: d[i] = p; } goto L1001; /* .......... SET ERROR -- NO CONVERGENCE TO AN */ /* EIGENVALUE AFTER 30 ITERATIONS .......... */ L1000: *ierr = l; L1001: return 0; } /* cgtql1_ */ HYPRE_Real hypre_LINPACKcgpthy(HYPRE_Real *a,HYPRE_Real *b) { /* System generated locals */ HYPRE_Real ret_val,d__1,d__2,d__3; /* Local variables */ HYPRE_Real p,r,s,t,u; /* FINDS DSQRT(A**2+B**2) WITHOUT OVERFLOW OR DESTRUCTIVE UNDERFLOW */ /* Computing MAX */ d__1 = fabs(*a),d__2 = fabs(*b); p = hypre_max(d__1,d__2); if (!p) { goto L20; } /* Computing MIN */ d__2 = fabs(*a),d__3 = fabs(*b); /* Computing 2nd power */ d__1 = hypre_min(d__2,d__3) / p; r = d__1 * d__1; L10: t = r + 4.; if (t == 4.) { goto L20; } s = r / t; u = s * 2. + 1.; p = u * p; /* Computing 2nd power */ d__1 = s / u; r = d__1 * d__1 * r; goto L10; L20: ret_val = p; return ret_val; } /* cgpthy_ */
omp_task_depend_resize_hashmap.c
// RUN: %libomp-compile && env KMP_ENABLE_TASK_THROTTLING=0 %libomp-run #include<omp.h> #include<stdlib.h> #include<string.h> // The first hashtable static size is 997 #define NUM_DEPS 4000 int main() { int *deps = calloc(NUM_DEPS, sizeof(int)); int i; int failed = 0; #pragma omp parallel #pragma omp master { for (i = 0; i < NUM_DEPS; i++) { #pragma omp task firstprivate(i) depend(inout: deps[i]) { deps[i] = 1; } #pragma omp task firstprivate(i) depend(inout: deps[i]) { deps[i] = 2; } } } for (i = 0; i < NUM_DEPS; i++) { if (deps[i] != 2) failed++; } return failed; }
GB_unop__identity_uint32_uint32.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_uint32_uint32 // op(A') function: GB_unop_tran__identity_uint32_uint32 // C type: uint32_t // A type: uint32_t // cast: uint32_t cij = aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_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) \ uint32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 1 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint32_uint32 ( uint32_t *Cx, // Cx and Ax may be aliased const uint32_t *Ax, const int8_t *GB_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) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; uint32_t z = 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 ; uint32_t aij = Ax [p] ; uint32_t z = 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_uint32_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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_binop__pow_fc32.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__pow_fc32) // A.*B function (eWiseMult): GB (_AemultB_08__pow_fc32) // A.*B function (eWiseMult): GB (_AemultB_02__pow_fc32) // A.*B function (eWiseMult): GB (_AemultB_04__pow_fc32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_fc32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pow_fc32) // C+=b function (dense accum): GB (_Cdense_accumb__pow_fc32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_fc32) // C=scalar+B GB (_bind1st__pow_fc32) // C=scalar+B' GB (_bind1st_tran__pow_fc32) // C=A+scalar GB (_bind2nd__pow_fc32) // C=A'+scalar GB (_bind2nd_tran__pow_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // A pattern? 0 // B type: GxB_FC32_t // B pattern? 0 // BinaryOp: cij = GB_cpowf (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_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) \ GxB_FC32_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) \ GxB_FC32_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) \ GxB_FC32_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 = GB_cpowf (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // 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_POW || GxB_NO_FC32 || GxB_NO_POW_FC32) //------------------------------------------------------------------------------ // 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__pow_fc32) ( 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__pow_fc32) ( 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__pow_fc32) ( 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 GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_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, 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 GxB_FC32_t *restrict Cx = (GxB_FC32_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, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *restrict Cx = (GxB_FC32_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__pow_fc32) ( 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) ; GxB_FC32_t alpha_scalar ; GxB_FC32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((GxB_FC32_t *) alpha_scalar_in)) ; beta_scalar = (*((GxB_FC32_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__pow_fc32) ( 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__pow_fc32) ( 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__pow_fc32) ( 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__pow_fc32) ( 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__pow_fc32) ( 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 GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_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 ; GxB_FC32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_cpowf (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__pow_fc32) ( 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 ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_cpowf (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) \ { \ GxB_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_cpowf (x, aij) ; \ } GrB_Info GB (_bind1st_tran__pow_fc32) ( 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 \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_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) \ { \ GxB_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_cpowf (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__pow_fc32) ( 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 GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
perftest.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "api/libperf.h" #include "lib/libperf_int.h" #include <ucs/sys/string.h> #include <ucs/sys/sys.h> #include <ucs/sys/sock.h> #include <ucs/debug/log.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <getopt.h> #include <string.h> #include <sys/types.h> #include <sys/poll.h> #include <locale.h> #if defined (HAVE_MPI) # include <mpi.h> #elif defined (HAVE_RTE) # include<rte.h> #endif #define MAX_BATCH_FILES 32 #define MAX_CPUS 1024 #define TL_RESOURCE_NAME_NONE "<none>" #define TEST_PARAMS_ARGS "t:n:s:W:O:w:D:i:H:oSCIqM:r:T:d:x:A:BUm:" #define TEST_ID_UNDEFINED -1 enum { TEST_FLAG_PRINT_RESULTS = UCS_BIT(0), TEST_FLAG_PRINT_TEST = UCS_BIT(1), TEST_FLAG_SET_AFFINITY = UCS_BIT(8), TEST_FLAG_NUMERIC_FMT = UCS_BIT(9), TEST_FLAG_PRINT_FINAL = UCS_BIT(10), TEST_FLAG_PRINT_CSV = UCS_BIT(11) }; typedef struct sock_rte_group { int is_server; int connfd; } sock_rte_group_t; typedef struct test_type { const char *name; ucx_perf_api_t api; ucx_perf_cmd_t command; ucx_perf_test_type_t test_type; const char *desc; const char *overhead_lat; unsigned window_size; } test_type_t; typedef struct perftest_params { ucx_perf_params_t super; int test_id; } perftest_params_t; struct perftest_context { perftest_params_t params; const char *server_addr; int port; int mpi; unsigned num_cpus; unsigned cpus[MAX_CPUS]; unsigned flags; unsigned num_batch_files; char *batch_files[MAX_BATCH_FILES]; char *test_names[MAX_BATCH_FILES]; sock_rte_group_t sock_rte_group; }; test_type_t tests[] = { {"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "active message latency", "latency", 1}, {"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency", "latency", 1}, {"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG, "atomic add latency", "latency", 1}, {"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate", "latency", 1}, {"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / rate", "latency", 1}, {"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / rate", "latency", 1}, {"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / rate", "latency", 1}, {"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "active message bandwidth / message rate", "overhead", 1}, {"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth / message rate", "overhead", 1}, {"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add message rate", "overhead", 1}, {"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG, "tag match latency", "latency", 1}, {"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag match bandwidth", "overhead", 32}, {"tag_sync_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_PINGPONG, "tag sync match latency", "latency", 1}, {"tag_sync_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag sync match bandwidth", "overhead", 32}, {"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency", "latency", 1}, {"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth", "overhead", 32}, {"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate", "latency", 1}, {"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add bandwidth / message rate", "overhead", 1}, {"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / bandwidth / rate", "latency", 1}, {"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / bandwidth / rate", "latency", 1}, {"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / bandwidth / rate", "latency", 1}, {"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI, "stream bandwidth", "overhead", 1}, {"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG, "stream latency", "latency", 1}, {NULL} }; static int sock_io(int sock, ssize_t (*sock_call)(int, void *, size_t, int), int poll_events, void *data, size_t size, void (*progress)(void *arg), void *arg, const char *name) { size_t total = 0; struct pollfd pfd; int ret; while (total < size) { pfd.fd = sock; pfd.events = poll_events; pfd.revents = 0; ret = poll(&pfd, 1, 1); /* poll for 1ms */ if (ret > 0) { ucs_assert(ret == 1); ucs_assert(pfd.revents & poll_events); ret = sock_call(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("%s() failed: %m", name); return -1; } total += ret; } else if ((ret < 0) && (errno != EINTR)) { ucs_error("poll(fd=%d) failed: %m", sock); return -1; } /* progress user context */ if (progress != NULL) { progress(arg); } } return 0; } static int safe_send(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { typedef ssize_t (*sock_call)(int, void *, size_t, int); return sock_io(sock, (sock_call)send, POLLOUT, data, size, progress, arg, "send"); } static int safe_recv(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { return sock_io(sock, recv, POLLIN, data, size, progress, arg, "recv"); } static void print_progress(char **test_names, unsigned num_names, const ucx_perf_result_t *result, unsigned flags, int final, int is_server, int is_multi_thread) { static const char *fmt_csv; static const char *fmt_numeric; static const char *fmt_plain; unsigned i; if (!(flags & TEST_FLAG_PRINT_RESULTS) || (!final && (flags & TEST_FLAG_PRINT_FINAL))) { return; } if (flags & TEST_FLAG_PRINT_CSV) { for (i = 0; i < num_names; ++i) { printf("%s,", test_names[i]); } } #if _OPENMP if (!final) { printf("[thread %d]", omp_get_thread_num()); } else if (flags & TEST_FLAG_PRINT_RESULTS) { printf("Final: "); } #endif if (is_multi_thread && final) { fmt_csv = "%4.0f,%.3f,%.2f,%.0f\n"; fmt_numeric = "%'18.0f %29.3f %22.2f %'24.0f\n"; fmt_plain = "%18.0f %29.3f %22.2f %23.0f\n"; printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.total_average * 1000000.0, result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.total_average); } else { fmt_csv = "%4.0f,%.3f,%.3f,%.3f,%.2f,%.2f,%.0f,%.0f\n"; fmt_numeric = "%'18.0f %9.3f %9.3f %9.3f %11.2f %10.2f %'11.0f %'11.0f\n"; fmt_plain = "%18.0f %9.3f %9.3f %9.3f %11.2f %10.2f %11.0f %11.0f\n"; printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.typical * 1000000.0, result->latency.moment_average * 1000000.0, result->latency.total_average * 1000000.0, result->bandwidth.moment_average / (1024.0 * 1024.0), result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.moment_average, result->msgrate.total_average); } fflush(stdout); } static void print_header(struct perftest_context *ctx) { const char *overhead_lat_str; const char *test_data_str; const char *test_api_str; test_type_t *test; unsigned i; test = (ctx->params.test_id == TEST_ID_UNDEFINED) ? NULL : &tests[ctx->params.test_id]; if ((ctx->flags & TEST_FLAG_PRINT_TEST) && (test != NULL)) { if (test->api == UCX_PERF_API_UCT) { test_api_str = "transport layer"; switch (ctx->params.super.uct.data_layout) { case UCT_PERF_DATA_LAYOUT_SHORT: test_data_str = "short"; break; case UCT_PERF_DATA_LAYOUT_BCOPY: test_data_str = "bcopy"; break; case UCT_PERF_DATA_LAYOUT_ZCOPY: test_data_str = "zcopy"; break; default: test_data_str = "(undefined)"; break; } } else if (test->api == UCX_PERF_API_UCP) { test_api_str = "protocol layer"; test_data_str = "(automatic)"; /* TODO contig/stride/stream */ } else { return; } printf("+------------------------------------------------------------------------------------------+\n"); printf("| API: %-60s |\n", test_api_str); printf("| Test: %-60s |\n", test->desc); printf("| Data layout: %-60s |\n", test_data_str); printf("| Send memory: %-60s |\n", ucs_memory_type_names[ctx->params.super.send_mem_type]); printf("| Recv memory: %-60s |\n", ucs_memory_type_names[ctx->params.super.recv_mem_type]); printf("| Message size: %-60zu |\n", ucx_perf_get_message_size(&ctx->params.super)); } if (ctx->flags & TEST_FLAG_PRINT_CSV) { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { for (i = 0; i < ctx->num_batch_files; ++i) { printf("%s,", ucs_basename(ctx->batch_files[i])); } printf("iterations,typical_lat,avg_lat,overall_lat,avg_bw,overall_bw,avg_mr,overall_mr\n"); } } else { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { overhead_lat_str = (test == NULL) ? "overhead" : test->overhead_lat; printf("+--------------+--------------+-----------------------------+---------------------+-----------------------+\n"); printf("| | | %8s (usec) | bandwidth (MB/s) | message rate (msg/s) |\n", overhead_lat_str); printf("+--------------+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); printf("| Stage | # iterations | typical | average | overall | average | overall | average | overall |\n"); printf("+--------------+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); } else if (ctx->flags & TEST_FLAG_PRINT_TEST) { printf("+------------------------------------------------------------------------------------------+\n"); } } } static void print_test_name(struct perftest_context *ctx) { char buf[200]; unsigned i, pos; if (!(ctx->flags & TEST_FLAG_PRINT_CSV) && (ctx->num_batch_files > 0)) { strcpy(buf, "+--------------+---------+---------+---------+----------+----------+-----------+-----------+"); pos = 1; for (i = 0; i < ctx->num_batch_files; ++i) { if (i != 0) { buf[pos++] = '/'; } memcpy(&buf[pos], ctx->test_names[i], ucs_min(strlen(ctx->test_names[i]), sizeof(buf) - pos - 1)); pos += strlen(ctx->test_names[i]); } if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("%s\n", buf); } } } static void print_memory_type_usage(void) { ucs_memory_type_t it; for (it = UCS_MEMORY_TYPE_HOST; it < UCS_MEMORY_TYPE_LAST; it++) { if (ucx_perf_mem_type_allocators[it] != NULL) { printf(" %s - %s\n", ucs_memory_type_names[it], ucs_memory_type_descs[it]); } } } static void usage(const struct perftest_context *ctx, const char *program) { static const char* api_names[] = { [UCX_PERF_API_UCT] = "UCT", [UCX_PERF_API_UCP] = "UCP" }; test_type_t *test; int UCS_V_UNUSED rank; #ifdef HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (ctx->mpi && (rank != 0)) { return; } #endif #if defined (HAVE_MPI) printf(" Note: test can be also launched as an MPI application\n"); printf("\n"); #elif defined (HAVE_RTE) printf(" Note: this test can be also launched as an libRTE application\n"); printf("\n"); #endif printf(" Usage: %s [ server-hostname ] [ options ]\n", program); printf("\n"); printf(" Common options:\n"); printf(" -t <test> test to run:\n"); for (test = tests; test->name; ++test) { printf(" %13s - %s %s\n", test->name, api_names[test->api], test->desc); } printf("\n"); printf(" -s <size> list of scatter-gather sizes for single message (%zu)\n", ctx->params.super.msg_size_list[0]); printf(" for example: \"-s 16,48,8192,8192,14\"\n"); printf(" -m <send mem type>[,<recv mem type>]\n"); printf(" memory type of message for sender and receiver (host)\n"); print_memory_type_usage(); printf(" -n <iters> number of iterations to run (%"PRIu64")\n", ctx->params.super.max_iter); printf(" -w <iters> number of warm-up iterations (%"PRIu64")\n", ctx->params.super.warmup_iter); printf(" -c <cpulist> set affinity to this CPU list (separated by comma) (off)\n"); printf(" -O <count> maximal number of uncompleted outstanding sends\n"); printf(" -i <offset> distance between consecutive scatter-gather entries (%zu)\n", ctx->params.super.iov_stride); printf(" -T <threads> number of threads in the test (%d)\n", ctx->params.super.thread_count); printf(" -o do not progress the responder in one-sided tests\n"); printf(" -B register memory with NONBLOCK flag\n"); printf(" -b <file> read and execute tests from a batch file: every line in the\n"); printf(" file is a test to run, first word is test name, the rest of\n"); printf(" the line is command-line arguments for the test.\n"); printf(" -p <port> TCP port to use for data exchange (%d)\n", ctx->port); #ifdef HAVE_MPI printf(" -P <0|1> disable/enable MPI mode (%d)\n", ctx->mpi); #endif printf(" -h show this help message\n"); printf("\n"); printf(" Output format:\n"); printf(" -N use numeric formatting (thousands separator)\n"); printf(" -f print only final numbers\n"); printf(" -v print CSV-formatted output\n"); printf("\n"); printf(" UCT only:\n"); printf(" -d <device> device to use for testing\n"); printf(" -x <tl> transport to use for testing\n"); printf(" -D <layout> data layout for sender side:\n"); printf(" short - short messages (default, cannot be used for get)\n"); printf(" bcopy - copy-out (cannot be used for atomics)\n"); printf(" zcopy - zero-copy (cannot be used for atomics)\n"); printf(" iov - scatter-gather list (iovec)\n"); printf(" -W <count> flow control window size, for active messages (%u)\n", ctx->params.super.uct.fc_window); printf(" -H <size> active message header size (%zu)\n", ctx->params.super.am_hdr_size); printf(" -A <mode> asynchronous progress mode (thread_spinlock)\n"); printf(" thread_spinlock - separate progress thread with spin locking\n"); printf(" thread_mutex - separate progress thread with mutex locking\n"); printf(" signal - signal-based timer\n"); printf("\n"); printf(" UCP only:\n"); printf(" -M <thread> thread support level for progress engine (single)\n"); printf(" single - only the master thread can access\n"); printf(" serialized - one thread can access at a time\n"); printf(" multi - multiple threads can access\n"); printf(" -D <layout>[,<layout>]\n"); printf(" data layout for sender and receiver side (contig)\n"); printf(" contig - Continuous datatype\n"); printf(" iov - Scatter-gather list\n"); printf(" -C use wild-card tag for tag tests\n"); printf(" -U force unexpected flow by using tag probe\n"); printf(" -r <mode> receive mode for stream tests (recv)\n"); printf(" recv : Use ucp_stream_recv_nb\n"); printf(" recv_data : Use ucp_stream_recv_data_nb\n"); printf(" -I create context with wakeup feature enabled\n"); printf("\n"); printf(" NOTE: When running UCP tests, transport and device should be specified by\n"); printf(" environment variables: UCX_TLS and UCX_[SELF|SHM|NET]_DEVICES.\n"); printf("\n"); } static ucs_status_t parse_ucp_datatype_params(const char *opt_arg, ucp_perf_datatype_t *datatype) { const char *iov_type = "iov"; const size_t iov_type_size = strlen("iov"); const char *contig_type = "contig"; const size_t contig_type_size = strlen("contig"); if (0 == strncmp(opt_arg, iov_type, iov_type_size)) { *datatype = UCP_PERF_DATATYPE_IOV; } else if (0 == strncmp(opt_arg, contig_type, contig_type_size)) { *datatype = UCP_PERF_DATATYPE_CONTIG; } else { return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_mem_type(const char *opt_arg, ucs_memory_type_t *mem_type) { ucs_memory_type_t it; for (it = UCS_MEMORY_TYPE_HOST; it < UCS_MEMORY_TYPE_LAST; it++) { if(!strcmp(opt_arg, ucs_memory_type_names[it]) && (ucx_perf_mem_type_allocators[it] != NULL)) { *mem_type = it; return UCS_OK; } } ucs_error("Unsupported memory type: \"%s\"", opt_arg); return UCS_ERR_INVALID_PARAM; } static ucs_status_t parse_mem_type_params(const char *opt_arg, ucs_memory_type_t *send_mem_type, ucs_memory_type_t *recv_mem_type) { const char *delim = ","; char *token = strtok((char*)opt_arg, delim); if (UCS_OK != parse_mem_type(token, send_mem_type)) { return UCS_ERR_INVALID_PARAM; } token = strtok(NULL, delim); if (NULL == token) { *recv_mem_type = *send_mem_type; return UCS_OK; } else { return parse_mem_type(token, recv_mem_type); } } static ucs_status_t parse_message_sizes_params(const char *opt_arg, ucx_perf_params_t *params) { const char delim = ','; size_t *msg_size_list, token_num, token_it; char *optarg_ptr, *optarg_ptr2; optarg_ptr = (char *)opt_arg; token_num = 0; /* count the number of given message sizes */ while ((optarg_ptr = strchr(optarg_ptr, delim)) != NULL) { ++optarg_ptr; ++token_num; } ++token_num; msg_size_list = realloc(params->msg_size_list, sizeof(*params->msg_size_list) * token_num); if (NULL == msg_size_list) { return UCS_ERR_NO_MEMORY; } params->msg_size_list = msg_size_list; optarg_ptr = (char *)opt_arg; errno = 0; for (token_it = 0; token_it < token_num; ++token_it) { params->msg_size_list[token_it] = strtoul(optarg_ptr, &optarg_ptr2, 10); if (((ERANGE == errno) && (ULONG_MAX == params->msg_size_list[token_it])) || ((errno != 0) && (params->msg_size_list[token_it] == 0)) || (optarg_ptr == optarg_ptr2)) { free(params->msg_size_list); params->msg_size_list = NULL; /* prevent double free */ ucs_error("Invalid option substring argument at position %lu", token_it); return UCS_ERR_INVALID_PARAM; } optarg_ptr = optarg_ptr2 + 1; } params->msg_size_cnt = token_num; return UCS_OK; } static ucs_status_t init_test_params(perftest_params_t *params) { memset(params, 0, sizeof(*params)); params->super.api = UCX_PERF_API_LAST; params->super.command = UCX_PERF_CMD_LAST; params->super.test_type = UCX_PERF_TEST_TYPE_LAST; params->super.thread_mode = UCS_THREAD_MODE_SINGLE; params->super.thread_count = 1; params->super.async_mode = UCS_ASYNC_THREAD_LOCK_TYPE; params->super.wait_mode = UCX_PERF_WAIT_MODE_LAST; params->super.max_outstanding = 0; params->super.warmup_iter = 10000; params->super.am_hdr_size = 8; params->super.alignment = ucs_get_page_size(); params->super.max_iter = 1000000l; params->super.max_time = 0.0; params->super.report_interval = 1.0; params->super.flags = UCX_PERF_TEST_FLAG_VERBOSE; params->super.uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW; params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; params->super.send_mem_type = UCS_MEMORY_TYPE_HOST; params->super.recv_mem_type = UCS_MEMORY_TYPE_HOST; params->super.msg_size_cnt = 1; params->super.iov_stride = 0; params->super.ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG; params->super.ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG; strcpy(params->super.uct.dev_name, TL_RESOURCE_NAME_NONE); strcpy(params->super.uct.tl_name, TL_RESOURCE_NAME_NONE); params->super.msg_size_list = calloc(params->super.msg_size_cnt, sizeof(*params->super.msg_size_list)); if (params->super.msg_size_list == NULL) { return UCS_ERR_NO_MEMORY; } params->super.msg_size_list[0] = 8; params->test_id = TEST_ID_UNDEFINED; return UCS_OK; } static ucs_status_t parse_test_params(perftest_params_t *params, char opt, const char *opt_arg) { char *optarg2 = NULL; test_type_t *test; unsigned i; switch (opt) { case 'd': ucs_snprintf_zero(params->super.uct.dev_name, sizeof(params->super.uct.dev_name), "%s", opt_arg); return UCS_OK; case 'x': ucs_snprintf_zero(params->super.uct.tl_name, sizeof(params->super.uct.tl_name), "%s", opt_arg); return UCS_OK; case 't': for (i = 0; tests[i].name != NULL; ++i) { test = &tests[i]; if (!strcmp(opt_arg, test->name)) { params->super.api = test->api; params->super.command = test->command; params->super.test_type = test->test_type; params->test_id = i; break; } } if (params->test_id == TEST_ID_UNDEFINED) { ucs_error("Invalid option argument for -t"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'D': if (!strcmp(opt_arg, "short")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; } else if (!strcmp(opt_arg, "bcopy")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_BCOPY; } else if (!strcmp(opt_arg, "zcopy")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_ZCOPY; } else if (UCS_OK == parse_ucp_datatype_params(opt_arg, &params->super.ucp.send_datatype)) { optarg2 = strchr(opt_arg, ','); if (optarg2) { if (UCS_OK != parse_ucp_datatype_params(optarg2 + 1, &params->super.ucp.recv_datatype)) { return UCS_ERR_INVALID_PARAM; } } } else { ucs_error("Invalid option argument for -D"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'i': params->super.iov_stride = atol(opt_arg); return UCS_OK; case 'n': params->super.max_iter = atol(opt_arg); return UCS_OK; case 's': return parse_message_sizes_params(opt_arg, &params->super); case 'H': params->super.am_hdr_size = atol(opt_arg); return UCS_OK; case 'W': params->super.uct.fc_window = atoi(opt_arg); return UCS_OK; case 'O': params->super.max_outstanding = atoi(opt_arg); return UCS_OK; case 'w': params->super.warmup_iter = atol(opt_arg); return UCS_OK; case 'o': params->super.flags |= UCX_PERF_TEST_FLAG_ONE_SIDED; return UCS_OK; case 'B': params->super.flags |= UCX_PERF_TEST_FLAG_MAP_NONBLOCK; return UCS_OK; case 'q': params->super.flags &= ~UCX_PERF_TEST_FLAG_VERBOSE; return UCS_OK; case 'C': params->super.flags |= UCX_PERF_TEST_FLAG_TAG_WILDCARD; return UCS_OK; case 'U': params->super.flags |= UCX_PERF_TEST_FLAG_TAG_UNEXP_PROBE; return UCS_OK; case 'I': params->super.flags |= UCX_PERF_TEST_FLAG_WAKEUP; return UCS_OK; case 'M': if (!strcmp(opt_arg, "single")) { params->super.thread_mode = UCS_THREAD_MODE_SINGLE; return UCS_OK; } else if (!strcmp(opt_arg, "serialized")) { params->super.thread_mode = UCS_THREAD_MODE_SERIALIZED; return UCS_OK; } else if (!strcmp(opt_arg, "multi")) { params->super.thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; } else { ucs_error("Invalid option argument for -M"); return UCS_ERR_INVALID_PARAM; } case 'T': params->super.thread_count = atoi(opt_arg); return UCS_OK; case 'A': if (!strcmp(opt_arg, "thread") || !strcmp(opt_arg, "thread_spinlock")) { params->super.async_mode = UCS_ASYNC_MODE_THREAD_SPINLOCK; return UCS_OK; } else if (!strcmp(opt_arg, "thread_mutex")) { params->super.async_mode = UCS_ASYNC_MODE_THREAD_MUTEX; return UCS_OK; } else if (!strcmp(opt_arg, "signal")) { params->super.async_mode = UCS_ASYNC_MODE_SIGNAL; return UCS_OK; } else { ucs_error("Invalid option argument for -A"); return UCS_ERR_INVALID_PARAM; } case 'r': if (!strcmp(opt_arg, "recv_data")) { params->super.flags |= UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; return UCS_OK; } else if (!strcmp(opt_arg, "recv")) { params->super.flags &= ~UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; return UCS_OK; } return UCS_ERR_INVALID_PARAM; case 'm': if (UCS_OK != parse_mem_type_params(opt_arg, &params->super.send_mem_type, &params->super.recv_mem_type)) { return UCS_ERR_INVALID_PARAM; } return UCS_OK; default: return UCS_ERR_INVALID_PARAM; } } static ucs_status_t adjust_test_params(perftest_params_t *params, const char *error_prefix) { test_type_t *test; if (params->test_id == TEST_ID_UNDEFINED) { ucs_error("%smissing test name", error_prefix); return UCS_ERR_INVALID_PARAM; } test = &tests[params->test_id]; if (params->super.max_outstanding == 0) { params->super.max_outstanding = test->window_size; } return UCS_OK; } static ucs_status_t read_batch_file(FILE *batch_file, const char *file_name, int *line_num, perftest_params_t *params, char** test_name_p) { #define MAX_SIZE 256 #define MAX_ARG_SIZE 2048 ucs_status_t status; char buf[MAX_ARG_SIZE]; char error_prefix[MAX_ARG_SIZE]; int argc; char *argv[MAX_SIZE + 1]; int c; char *p; do { if (fgets(buf, sizeof(buf) - 1, batch_file) == NULL) { return UCS_ERR_NO_ELEM; } ++(*line_num); argc = 0; p = strtok(buf, " \t\n\r"); while (p && (argc < MAX_SIZE)) { argv[argc++] = p; p = strtok(NULL, " \t\n\r"); } argv[argc] = NULL; } while ((argc == 0) || (argv[0][0] == '#')); ucs_snprintf_safe(error_prefix, sizeof(error_prefix), "in batch file '%s' line %d: ", file_name, *line_num); optind = 1; while ((c = getopt (argc, argv, TEST_PARAMS_ARGS)) != -1) { status = parse_test_params(params, c, optarg); if (status != UCS_OK) { ucs_error("%s-%c %s: %s", error_prefix, c, optarg, ucs_status_string(status)); return status; } } status = adjust_test_params(params, error_prefix); if (status != UCS_OK) { return status; } *test_name_p = strdup(argv[0]); return UCS_OK; } static ucs_status_t parse_cpus(char *opt_arg, struct perftest_context *ctx) { char *endptr, *cpu_list = opt_arg; int cpu; ctx->num_cpus = 0; cpu = strtol(cpu_list, &endptr, 10); while (((*endptr == ',') || (*endptr == '\0')) && (ctx->num_cpus < MAX_CPUS)) { if (cpu < 0) { ucs_error("invalid cpu number detected: (%d)", cpu); return UCS_ERR_INVALID_PARAM; } ctx->cpus[ctx->num_cpus++] = cpu; if (*endptr == '\0') { break; } cpu_list = endptr + 1; /* skip the comma */ cpu = strtol(cpu_list, &endptr, 10); } if (*endptr == ',') { ucs_error("number of listed cpus exceeds the maximum supported value (%d)", MAX_CPUS); return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_opts(struct perftest_context *ctx, int mpi_initialized, int argc, char **argv) { ucs_status_t status; int c; ucs_trace_func(""); ucx_perf_global_init(); /* initialize memory types */ status = init_test_params(&ctx->params); if (status != UCS_OK) { return status; } ctx->server_addr = NULL; ctx->num_batch_files = 0; ctx->port = 13337; ctx->flags = 0; ctx->mpi = mpi_initialized; optind = 1; while ((c = getopt (argc, argv, "p:b:Nfvc:P:h" TEST_PARAMS_ARGS)) != -1) { switch (c) { case 'p': ctx->port = atoi(optarg); break; case 'b': if (ctx->num_batch_files < MAX_BATCH_FILES) { ctx->batch_files[ctx->num_batch_files++] = optarg; } break; case 'N': ctx->flags |= TEST_FLAG_NUMERIC_FMT; break; case 'f': ctx->flags |= TEST_FLAG_PRINT_FINAL; break; case 'v': ctx->flags |= TEST_FLAG_PRINT_CSV; break; case 'c': ctx->flags |= TEST_FLAG_SET_AFFINITY; status = parse_cpus(optarg, ctx); if (status != UCS_OK) { return status; } break; case 'P': #ifdef HAVE_MPI ctx->mpi = atoi(optarg) && mpi_initialized; break; #endif case 'h': usage(ctx, ucs_basename(argv[0])); return UCS_ERR_CANCELED; default: status = parse_test_params(&ctx->params, c, optarg); if (status != UCS_OK) { usage(ctx, ucs_basename(argv[0])); return status; } break; } } if (optind < argc) { ctx->server_addr = argv[optind]; } return UCS_OK; } static unsigned sock_rte_group_size(void *rte_group) { return 2; } static unsigned sock_rte_group_index(void *rte_group) { sock_rte_group_t *group = rte_group; return group->is_server ? 0 : 1; } static void sock_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { sock_rte_group_t *group = rte_group; const unsigned magic = 0xdeadbeef; unsigned snc; snc = magic; safe_send(group->connfd, &snc, sizeof(unsigned), progress, arg); snc = 0; safe_recv(group->connfd, &snc, sizeof(unsigned), progress, arg); ucs_assert(snc == magic); } #pragma omp barrier } static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { sock_rte_group_t *group = rte_group; size_t size; int i; size = 0; for (i = 0; i < iovcnt; ++i) { size += iovec[i].iov_len; } safe_send(group->connfd, &size, sizeof(size), NULL, NULL); for (i = 0; i < iovcnt; ++i) { safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len, NULL, NULL); } } static void sock_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { sock_rte_group_t *group = rte_group; int group_index; size_t size; group_index = sock_rte_group_index(rte_group); if (src == group_index) { return; } ucs_assert_always(src == (1 - group_index)); safe_recv(group->connfd, &size, sizeof(size), NULL, NULL); ucs_assert_always(size <= max); safe_recv(group->connfd, buffer, size, NULL, NULL); } static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } static ucx_perf_rte_t sock_rte = { .group_size = sock_rte_group_size, .group_index = sock_rte_group_index, .barrier = sock_rte_barrier, .post_vec = sock_rte_post_vec, .recv = sock_rte_recv, .exchange_vec = (ucx_perf_rte_exchange_vec_func_t)ucs_empty_function, .report = sock_rte_report, }; static ucs_status_t setup_sock_rte(struct perftest_context *ctx) { struct sockaddr_in inaddr; struct hostent *he; ucs_status_t status; int optval = 1; int sockfd, connfd; int ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ucs_error("socket() failed: %m"); status = UCS_ERR_IO_ERROR; goto err; } if (ctx->server_addr == NULL) { optval = 1; status = ucs_socket_setopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (status != UCS_OK) { goto err_close_sockfd; } inaddr.sin_family = AF_INET; inaddr.sin_port = htons(ctx->port); inaddr.sin_addr.s_addr = INADDR_ANY; memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("bind() failed: %m"); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } ret = listen(sockfd, 10); if (ret < 0) { ucs_error("listen() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } printf("Waiting for connection...\n"); /* Accept next connection */ connfd = accept(sockfd, NULL, NULL); if (connfd < 0) { ucs_error("accept() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } close(sockfd); /* release the memory for the list of the message sizes allocated * during the initialization of the default testing parameters */ free(ctx->params.super.msg_size_list); ctx->params.super.msg_size_list = NULL; ret = safe_recv(connfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } if (ctx->params.super.msg_size_cnt != 0) { ctx->params.super.msg_size_list = calloc(ctx->params.super.msg_size_cnt, sizeof(*ctx->params.super.msg_size_list)); if (NULL == ctx->params.super.msg_size_list) { status = UCS_ERR_NO_MEMORY; goto err_close_connfd; } ret = safe_recv(connfd, ctx->params.super.msg_size_list, sizeof(*ctx->params.super.msg_size_list) * ctx->params.super.msg_size_cnt, NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } } ctx->sock_rte_group.connfd = connfd; ctx->sock_rte_group.is_server = 1; } else { he = gethostbyname(ctx->server_addr); if (he == NULL || he->h_addr_list == NULL) { ucs_error("host %s not found: %s", ctx->server_addr, hstrerror(h_errno)); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } inaddr.sin_family = he->h_addrtype; inaddr.sin_port = htons(ctx->port); ucs_assert(he->h_length == sizeof(inaddr.sin_addr)); memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length); memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("connect() failed: %m"); status = UCS_ERR_UNREACHABLE; goto err_close_sockfd; } safe_send(sockfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ctx->params.super.msg_size_cnt != 0) { safe_send(sockfd, ctx->params.super.msg_size_list, sizeof(*ctx->params.super.msg_size_list) * ctx->params.super.msg_size_cnt, NULL, NULL); } ctx->sock_rte_group.connfd = sockfd; ctx->sock_rte_group.is_server = 0; } if (ctx->sock_rte_group.is_server) { ctx->flags |= TEST_FLAG_PRINT_TEST; } else { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = &ctx->sock_rte_group; ctx->params.super.rte = &sock_rte; ctx->params.super.report_arg = ctx; return UCS_OK; err_close_connfd: close(connfd); goto err; err_close_sockfd: close(sockfd); err: return status; } static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx) { close(ctx->sock_rte_group.connfd); return UCS_OK; } #if defined (HAVE_MPI) static unsigned mpi_rte_group_size(void *rte_group) { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } static unsigned mpi_rte_group_index(void *rte_group) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return rank; } static void mpi_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { int group_size, my_rank, i; MPI_Request *reqs; int nreqs = 0; int dummy; int flag; #pragma omp barrier #pragma omp master { /* * Naive non-blocking barrier implementation over send/recv, to call user * progress while waiting for completion. * Not using MPI_Ibarrier to be compatible with MPI-1. */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); /* allocate maximal possible number of requests */ reqs = (MPI_Request*)alloca(sizeof(*reqs) * group_size); if (my_rank == 0) { /* root gathers "ping" from all other ranks */ for (i = 1; i < group_size; ++i) { MPI_Irecv(&dummy, 0, MPI_INT, i /* source */, 1 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } } else { /* every non-root rank sends "ping" and waits for "pong" */ MPI_Send(&dummy, 0, MPI_INT, 0 /* dest */, 1 /* tag */, MPI_COMM_WORLD); MPI_Irecv(&dummy, 0, MPI_INT, 0 /* source */, 2 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } /* Waiting for receive requests */ do { MPI_Testall(nreqs, reqs, &flag, MPI_STATUSES_IGNORE); progress(arg); } while (!flag); if (my_rank == 0) { /* root sends "pong" to all ranks */ for (i = 1; i < group_size; ++i) { MPI_Send(&dummy, 0, MPI_INT, i /* dest */, 2 /* tag */, MPI_COMM_WORLD); } } } #pragma omp barrier } static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { int group_size; int my_rank; int dest, i; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); for (dest = 0; dest < group_size; ++dest) { if (dest == my_rank) { continue; } for (i = 0; i < iovcnt; ++i) { MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest, i == (iovcnt - 1), /* Send last iov with tag == 1 */ MPI_COMM_WORLD); } } *req = (void*)(uintptr_t)1; } static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { MPI_Status status; size_t offset; int my_rank; int count; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (src == my_rank) { return; } offset = 0; do { ucs_assert_always(offset < max); MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_BYTE, &count); offset += count; } while (status.MPI_TAG != 1); } static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } #elif defined (HAVE_RTE) static unsigned ext_rte_group_size(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_size(group); } static unsigned ext_rte_group_index(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_rank(group); } static void ext_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { rte_group_t group = (rte_group_t)rte_group; int rc; rc = rte_barrier(group); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_barrier"); } } #pragma omp barrier } static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec, int iovcnt, void **req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session; rte_iovec_t *r_vec; int i, rc; rc = rte_srs_session_create(group, 0, &session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_create"); } r_vec = calloc(iovcnt, sizeof(rte_iovec_t)); if (r_vec == NULL) { return; } for (i = 0; i < iovcnt; ++i) { r_vec[i].iov_base = iovec[i].iov_base; r_vec[i].type = rte_datatype_uint8_t; r_vec[i].count = iovec[i].iov_len; } rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_set_data"); } *req = session; free(r_vec); } static void ext_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session = (rte_srs_session_t)req; void *rte_buffer = NULL; rte_iovec_t r_vec; uint32_t offset; int size; int rc; rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src), "KEY_PERF", &rte_buffer, &size); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_get_data"); return; } r_vec.iov_base = buffer; r_vec.type = rte_datatype_uint8_t; r_vec.count = max; offset = 0; rte_unpack(&r_vec, rte_buffer, &offset); rc = rte_srs_session_destroy(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_destroy"); } free(rte_buffer); } static void ext_rte_exchange_vec(void *rte_group, void * req) { rte_srs_session_t session = (rte_srs_session_t)req; int rc; rc = rte_srs_exchange_data(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_exchange_data"); } } static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } static ucx_perf_rte_t ext_rte = { .group_size = ext_rte_group_size, .group_index = ext_rte_group_index, .barrier = ext_rte_barrier, .report = ext_rte_report, .post_vec = ext_rte_post_vec, .recv = ext_rte_recv, .exchange_vec = ext_rte_exchange_vec, }; #endif static ucs_status_t setup_mpi_rte(struct perftest_context *ctx) { #if defined (HAVE_MPI) static ucx_perf_rte_t mpi_rte = { .group_size = mpi_rte_group_size, .group_index = mpi_rte_group_index, .barrier = mpi_rte_barrier, .post_vec = mpi_rte_post_vec, .recv = mpi_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = mpi_rte_report, }; int size, rank; ucs_trace_func(""); MPI_Comm_size(MPI_COMM_WORLD, &size); if (size != 2) { ucs_error("This test should run with exactly 2 processes (actual: %d)", size); return UCS_ERR_INVALID_PARAM; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 1) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = NULL; ctx->params.super.rte = &mpi_rte; ctx->params.super.report_arg = ctx; #elif defined (HAVE_RTE) ucs_trace_func(""); ctx->params.rte_group = NULL; ctx->params.rte = &mpi_rte; ctx->params.report_arg = ctx; rte_group_t group; rte_init(NULL, NULL, &group); if (1 == rte_group_rank(group)) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = group; ctx->params.super.rte = &ext_rte; ctx->params.super.report_arg = ctx; #endif return UCS_OK; } static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx) { #ifdef HAVE_RTE rte_finalize(); #endif return UCS_OK; } static ucs_status_t check_system(struct perftest_context *ctx) { ucs_sys_cpuset_t cpuset; unsigned i, count, nr_cpus; int ret; ucs_trace_func(""); ret = sysconf(_SC_NPROCESSORS_CONF); if (ret < 0) { ucs_error("failed to get local cpu count: %m"); return UCS_ERR_INVALID_PARAM; } nr_cpus = ret; memset(&cpuset, 0, sizeof(cpuset)); if (ctx->flags & TEST_FLAG_SET_AFFINITY) { for (i = 0; i < ctx->num_cpus; i++) { if (ctx->cpus[i] >= nr_cpus) { ucs_error("cpu (%u) out of range (0..%u)", ctx->cpus[i], nr_cpus - 1); return UCS_ERR_INVALID_PARAM; } } for (i = 0; i < ctx->num_cpus; i++) { CPU_SET(ctx->cpus[i], &cpuset); } ret = ucs_sys_setaffinity(&cpuset); if (ret) { ucs_warn("sched_setaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } } else { ret = ucs_sys_getaffinity(&cpuset); if (ret) { ucs_warn("sched_getaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } count = 0; for (i = 0; i < CPU_SETSIZE; ++i) { if (CPU_ISSET(i, &cpuset)) { ++count; } } if (count > 2) { ucs_warn("CPU affinity is not set (bound to %u cpus)." " Performance may be impacted.", count); } } return UCS_OK; } static ucs_status_t clone_params(perftest_params_t *dest, const perftest_params_t *src) { size_t msg_size_list_size; *dest = *src; msg_size_list_size = dest->super.msg_size_cnt * sizeof(*dest->super.msg_size_list); dest->super.msg_size_list = malloc(msg_size_list_size); if (dest->super.msg_size_list == NULL) { return ((msg_size_list_size != 0) ? UCS_ERR_NO_MEMORY : UCS_OK); } memcpy(dest->super.msg_size_list, src->super.msg_size_list, msg_size_list_size); return UCS_OK; } static ucs_status_t run_test_recurs(struct perftest_context *ctx, const perftest_params_t *parent_params, unsigned depth) { perftest_params_t params; ucx_perf_result_t result; ucs_status_t status; FILE *batch_file; int line_num; ucs_trace_func("depth=%u, num_files=%u", depth, ctx->num_batch_files); if (parent_params->super.api == UCX_PERF_API_UCP) { if (strcmp(parent_params->super.uct.dev_name, TL_RESOURCE_NAME_NONE)) { ucs_warn("-d '%s' ignored for UCP test; see NOTES section in help message", parent_params->super.uct.dev_name); } if (strcmp(parent_params->super.uct.tl_name, TL_RESOURCE_NAME_NONE)) { ucs_warn("-x '%s' ignored for UCP test; see NOTES section in help message", parent_params->super.uct.tl_name); } } if (depth >= ctx->num_batch_files) { print_test_name(ctx); return ucx_perf_run(&parent_params->super, &result); } batch_file = fopen(ctx->batch_files[depth], "r"); if (batch_file == NULL) { ucs_error("Failed to open batch file '%s': %m", ctx->batch_files[depth]); return UCS_ERR_IO_ERROR; } line_num = 0; do { status = clone_params(&params, parent_params); if (status != UCS_OK) { goto out; } status = read_batch_file(batch_file, ctx->batch_files[depth], &line_num, &params, &ctx->test_names[depth]); if (status == UCS_OK) { run_test_recurs(ctx, &params, depth + 1); free(ctx->test_names[depth]); ctx->test_names[depth] = NULL; } free(params.super.msg_size_list); params.super.msg_size_list = NULL; } while (status == UCS_OK); if (status == UCS_ERR_NO_ELEM) { status = UCS_OK; } out: fclose(batch_file); return status; } static ucs_status_t run_test(struct perftest_context *ctx) { const char *error_prefix; ucs_status_t status; ucs_trace_func(""); setlocale(LC_ALL, "en_US"); /* no batch files, only command line params */ if (ctx->num_batch_files == 0) { error_prefix = (ctx->flags & TEST_FLAG_PRINT_RESULTS) ? "command line: " : ""; status = adjust_test_params(&ctx->params, error_prefix); if (status != UCS_OK) { return status; } } print_header(ctx); status = run_test_recurs(ctx, &ctx->params, 0); if (status != UCS_OK) { ucs_error("Failed to run test: %s", ucs_status_string(status)); } return status; } int main(int argc, char **argv) { struct perftest_context ctx; ucs_status_t status; int mpi_initialized; int mpi_rte; int ret; #ifdef HAVE_MPI int provided; mpi_initialized = !isatty(0) && /* Using MPI_THREAD_FUNNELED since ucx_perftest supports * using multiple threads when only the main one makes * MPI calls (which is also suitable for a single threaded * run). * MPI_THREAD_FUNNELED: * The process may be multi-threaded, but only the main * thread will make MPI calls (all MPI calls are funneled * to the main thread). */ (MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided) == 0); if (mpi_initialized && (provided != MPI_THREAD_FUNNELED)) { printf("MPI_Init_thread failed to set MPI_THREAD_FUNNELED. (provided = %d)\n", provided); ret = -1; goto out; } #else mpi_initialized = 0; #endif /* Parse command line */ status = parse_opts(&ctx, mpi_initialized, argc, argv); if (status != UCS_OK) { ret = (status == UCS_ERR_CANCELED) ? 0 : -127; goto out_msg_size_list; } #ifdef __COVERITY__ /* coverity[dont_call] */ mpi_rte = rand(); /* Shut up deadcode error */ #endif if (ctx.mpi) { mpi_rte = 1; } else { #ifdef HAVE_RTE mpi_rte = 1; #else mpi_rte = 0; #endif } status = check_system(&ctx); if (status != UCS_OK) { ret = -1; goto out_msg_size_list; } /* Create RTE */ status = (mpi_rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx); if (status != UCS_OK) { ret = -1; goto out_msg_size_list; } /* Run the test */ status = run_test(&ctx); if (status != UCS_OK) { ret = -1; goto out_cleanup_rte; } ret = 0; out_cleanup_rte: (mpi_rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx); out_msg_size_list: free(ctx.params.super.msg_size_list); #if HAVE_MPI out: #endif if (mpi_initialized) { #ifdef HAVE_MPI MPI_Finalize(); #endif } return ret; }
ast-dump-openmp-section.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(void) { #pragma omp sections { #pragma omp section ; } } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-section.c:3:1, line:9:1> line:3:6 test 'void (void)' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:17, line:9:1> // CHECK-NEXT: `-OMPSectionsDirective {{.*}} <line:4:1, col:21> // CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3, line:8:3> // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: |-CompoundStmt {{.*}} <line:5:3, line:8:3> // CHECK-NEXT: | `-OMPSectionDirective {{.*}} <line:6:1, col:20> // CHECK-NEXT: | `-NullStmt {{.*}} <line:7:5> // CHECK-NEXT: `-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-section.c:4:1) *const restrict'
Par-34-ParSectionsNoWait.c
/* * This test case is currently not supported in ROSE. * 09/27/2019 * * It is rejected for the nowait clause at the the section construct. */ int main(int argc, char **argv) { int a[4] = {1,2,3,4}; int b[4] = {0, 0, 0, 0}; #pragma omp parallel { #pragma omp sections nowait { #pragma omp section { for (int i = 0; i < 4; ++i) { a[i] = 3*a[i]; } } #pragma omp section { for (int j = 0; j < 4; ++j) { b[j] = a[j]; } } } } return 0; }
GB_binop__ne_uint64.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__ne_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__ne_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__ne_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__ne_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_uint64) // A*D function (colscale): GB (_AxD__ne_uint64) // D*A function (rowscale): GB (_DxB__ne_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__ne_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__ne_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_uint64) // C=scalar+B GB (_bind1st__ne_uint64) // C=scalar+B' GB (_bind1st_tran__ne_uint64) // C=A+scalar GB (_bind2nd__ne_uint64) // C=A'+scalar GB (_bind2nd_tran__ne_uint64) // C type: bool // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_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) \ uint64_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) \ uint64_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_NE || GxB_NO_UINT64 || GxB_NO_NE_UINT64) //------------------------------------------------------------------------------ // 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__ne_uint64) ( 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__ne_uint64) ( 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__ne_uint64) ( 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 uint64_t uint64_t bwork = (*((uint64_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__ne_uint64) ( 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__ne_uint64) ( 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__ne_uint64) ( 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) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_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__ne_uint64) ( 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__ne_uint64) ( 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__ne_uint64) ( 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__ne_uint64) ( 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__ne_uint64) ( 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 ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_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 ; uint64_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__ne_uint64) ( 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 ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__ne_uint64) ( 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 \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__ne_uint64) ( 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 uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
clip.c
#include "msghandling.h" #include "zgl.h" /* fill triangle profile */ /* #define PROFILE */ #define CLIP_XMIN (1 << 0) #define CLIP_XMAX (1 << 1) #define CLIP_YMIN (1 << 2) #define CLIP_YMAX (1 << 3) #define CLIP_ZMIN (1 << 4) #define CLIP_ZMAX (1 << 5) static void gl_transform_to_viewport_clip_c(GLVertex* v) { /* MARK: NOT_INLINED_IN_OG*/ GLContext* c = gl_get_context(); /* coordinates */ { GLfloat winv = 1.0 / v->pc.W; v->zp.x = (GLint)(v->pc.X * winv * c->viewport.scale.X + c->viewport.trans.X); v->zp.y = (GLint)(v->pc.Y * winv * c->viewport.scale.Y + c->viewport.trans.Y); v->zp.z = (GLint)(v->pc.Z * winv * c->viewport.scale.Z + c->viewport.trans.Z); } /* color */ v->zp.r = (GLint)(v->color.v[0] * COLOR_CORRECTED_MULT_MASK + COLOR_MIN_MULT) & COLOR_MASK; v->zp.g = (GLint)(v->color.v[1] * COLOR_CORRECTED_MULT_MASK + COLOR_MIN_MULT) & COLOR_MASK; v->zp.b = (GLint)(v->color.v[2] * COLOR_CORRECTED_MULT_MASK + COLOR_MIN_MULT) & COLOR_MASK; /* texture */ if (c->texture_2d_enabled) { v->zp.s = (GLint)(v->tex_coord.X * (ZB_POINT_S_MAX - ZB_POINT_S_MIN) + ZB_POINT_S_MIN); v->zp.t = (GLint)(v->tex_coord.Y * (ZB_POINT_T_MAX - ZB_POINT_T_MIN) + ZB_POINT_T_MIN); } } #define clip_funcdef(name, sign, dir, dir1, dir2) \ static GLfloat name(V4* c, V4* a, V4* b) { \ GLfloat t, dX, dY, dZ, dW, den; \ dX = (b->X - a->X); \ dY = (b->Y - a->Y); \ dZ = (b->Z - a->Z); \ dW = (b->W - a->W); \ den = -(sign d##dir) + dW; \ if (den == 0) \ t = 0; \ else \ t = (sign a->dir - a->W) / den; \ c->dir1 = a->dir1 + t * d##dir1; \ c->dir2 = a->dir2 + t * d##dir2; \ c->W = a->W + t * dW; \ c->dir = sign c->W; \ return t; \ } clip_funcdef(clip_xmin, -, X, Y, Z) clip_funcdef(clip_xmax, +, X, Y, Z) clip_funcdef(clip_ymin, -, Y, X, Z) clip_funcdef(clip_ymax, +, Y, X, Z) clip_funcdef(clip_zmin, -, Z, X, Y) clip_funcdef(clip_zmax, +, Z, X, Y) static GLfloat (*clip_proc[6])(V4*, V4*, V4*) = {clip_xmin, clip_xmax, clip_ymin, clip_ymax, clip_zmin, clip_zmax}; /* point */ #if TGL_FEATURE_ALT_RENDERMODES == 1 static void gl_add_select1(GLint z1, GLint z2, GLint z3) { GLint min, max; min = max = z1; if (z2 < min) min = z2; if (z3 < min) min = z3; if (z2 > max) max = z2; if (z3 > max) max = z3; gl_add_select(0xffffffff - min, 0xffffffff - max); } #else #define gl_add_select1(a, b, c) /*a comment*/ #endif void gl_draw_point(GLVertex* p0) { GLContext* c = gl_get_context(); if (p0->clip_code == 0) { #if TGL_FEATURE_ALT_RENDERMODES == 1 if (c->render_mode == GL_SELECT) { gl_add_select(p0->zp.z, p0->zp.z); } else if (c->render_mode == GL_FEEDBACK) { gl_add_feedback(GL_POINT_TOKEN, p0, NULL, NULL, 0); } else #endif { ZB_plot(c->zb, &p0->zp); } } } /* line */ /* * Line Clipping */ static void GLinterpolate(GLVertex* q, GLVertex* p0, GLVertex* p1, GLfloat t) { GLint i; q->pc.X = p0->pc.X + (p1->pc.X - p0->pc.X) * t; q->pc.Y = p0->pc.Y + (p1->pc.Y - p0->pc.Y) * t; q->pc.Z = p0->pc.Z + (p1->pc.Z - p0->pc.Z) * t; q->pc.W = p0->pc.W + (p1->pc.W - p0->pc.W) * t; #pragma omp simd for (i = 0; i < 3; i++) q->color.v[i] = p0->color.v[i] + (p1->color.v[i] - p0->color.v[i]) * t; } /* Line Clipping algorithm from 'Computer Graphics', Principles and Practice */ static GLint ClipLine1(GLfloat denom, GLfloat num, GLfloat* tmin, GLfloat* tmax) { GLfloat t; if (denom > 0) { t = num / denom; if (t > *tmax) return 0; if (t > *tmin) *tmin = t; } else if (denom < 0) { t = num / denom; if (t < *tmin) return 0; if (t < *tmax) *tmax = t; } else if (num > 0) return 0; return 1; } void gl_draw_line(GLVertex* p1, GLVertex* p2) { GLContext* c = gl_get_context(); GLfloat dx, dy, dz, dw, x1, y1, z1, w1; GLVertex q1, q2; GLint cc1, cc2; cc1 = p1->clip_code; cc2 = p2->clip_code; if ((cc1 | cc2) == 0) { #if TGL_FEATURE_ALT_RENDERMODES == 1 if (c->render_mode == GL_SELECT) { gl_add_select1(p1->zp.z, p2->zp.z, p2->zp.z); } else if (c->render_mode == GL_FEEDBACK) { gl_add_feedback(GL_LINE_TOKEN, p1, p2, NULL, 0); } else #endif { if (c->zb->depth_test) ZB_line_z(c->zb, &p1->zp, &p2->zp); else ZB_line(c->zb, &p1->zp, &p2->zp); } } else if ((cc1 & cc2) != 0) { return; } else { dx = p2->pc.X - p1->pc.X; dy = p2->pc.Y - p1->pc.Y; dz = p2->pc.Z - p1->pc.Z; dw = p2->pc.W - p1->pc.W; x1 = p1->pc.X; y1 = p1->pc.Y; z1 = p1->pc.Z; w1 = p1->pc.W; GLfloat tmin = 0; GLfloat tmax = 1; if (ClipLine1(dx + dw, -x1 - w1, &tmin, &tmax) && ClipLine1(-dx + dw, x1 - w1, &tmin, &tmax) && ClipLine1(dy + dw, -y1 - w1, &tmin, &tmax) && ClipLine1(-dy + dw, y1 - w1, &tmin, &tmax) && ClipLine1(dz + dw, -z1 - w1, &tmin, &tmax) && ClipLine1(-dz + dw, z1 - w1, &tmin, &tmax)) { GLinterpolate(&q1, p1, p2, tmin); GLinterpolate(&q2, p1, p2, tmax); gl_transform_to_viewport_clip_c(&q1); gl_transform_to_viewport_clip_c(&q2); #if TGL_FEATURE_ALT_RENDERMODES == 1 if (c->render_mode == GL_SELECT) { gl_add_select1(q1.zp.z, q2.zp.z, q2.zp.z); } else if (c->render_mode == GL_FEEDBACK) { gl_add_feedback(GL_LINE_TOKEN, &q1, &q2, NULL, 0); } else #endif { if (c->zb->depth_test) ZB_line_z(c->zb, &q1.zp, &q2.zp); else ZB_line(c->zb, &q1.zp, &q2.zp); } } } } /*Triangles*/ static void updateTmp(GLVertex* q, GLVertex* p0, GLVertex* p1, GLfloat t) { GLContext* c = gl_get_context(); { q->color.v[0] = p0->color.v[0] + (p1->color.v[0] - p0->color.v[0]) * t; q->color.v[1] = p0->color.v[1] + (p1->color.v[1] - p0->color.v[1]) * t; q->color.v[2] = p0->color.v[2] + (p1->color.v[2] - p0->color.v[2]) * t; } #if TGL_OPTIMIZATION_HINT_BRANCH_COST < 1 if (c->texture_2d_enabled) #endif { q->tex_coord.X = p0->tex_coord.X + (p1->tex_coord.X - p0->tex_coord.X) * t; q->tex_coord.Y = p0->tex_coord.Y + (p1->tex_coord.Y - p0->tex_coord.Y) * t; } q->clip_code = gl_clipcode(q->pc.X, q->pc.Y, q->pc.Z, q->pc.W); if (q->clip_code == 0) gl_transform_to_viewport_clip_c(q); } static void gl_draw_triangle_clip(GLVertex* p0, GLVertex* p1, GLVertex* p2, GLint clip_bit); void gl_draw_triangle(GLVertex* p0, GLVertex* p1, GLVertex* p2) { GLContext* c = gl_get_context(); GLint co, cc[3], front; cc[0] = p0->clip_code; cc[1] = p1->clip_code; cc[2] = p2->clip_code; co = cc[0] | cc[1] | cc[2]; /* we handle the non clipped case here to go faster */ if (co == 0) { GLfloat norm; norm = (GLfloat)(p1->zp.x - p0->zp.x) * (GLfloat)(p2->zp.y - p0->zp.y) - (GLfloat)(p2->zp.x - p0->zp.x) * (GLfloat)(p1->zp.y - p0->zp.y); if (norm == 0) return; front = norm < 0.0; front = front ^ c->current_front_face; /* back face culling */ if (c->cull_face_enabled) { /* most used case first */ if (c->current_cull_face == GL_BACK) { if (front == 0) return; c->draw_triangle_front(p0, p1, p2); } else if (c->current_cull_face == GL_FRONT) { if (front != 0) return; c->draw_triangle_back(p0, p1, p2); } else { return; } } else { /* no culling */ if (front) { c->draw_triangle_front(p0, p1, p2); } else { c->draw_triangle_back(p0, p1, p2); } } } else { /* GLint c_and = cc[0] & cc[1] & cc[2];*/ if ((cc[0] & cc[1] & cc[2]) == 0) { /* Don't draw a triangle with no points*/ gl_draw_triangle_clip(p0, p1, p2, 0); } } } static void gl_draw_triangle_clip(GLVertex* p0, GLVertex* p1, GLVertex* p2, GLint clip_bit) { GLint co, c_and, co1, cc[3], edge_flag_tmp, clip_mask; GLVertex* q[3]; cc[0] = p0->clip_code; cc[1] = p1->clip_code; cc[2] = p2->clip_code; co = cc[0] | cc[1] | cc[2]; if (co == 0) { gl_draw_triangle(p0, p1, p2); } else { c_and = cc[0] & cc[1] & cc[2]; /* the triangle is completely outside */ if (c_and != 0) return; /* find the next direction to clip */ while (clip_bit < 6 && (co & (1 << clip_bit)) == 0) { clip_bit++; } /* this test can be true only in case of rounding errors */ if (clip_bit == 6) { /* The 2 bit and the 4 bit.*/ #if 0 tgl_warning("Error:\n");tgl_warning("%f %f %f %f\n",p0->pc.X,p0->pc.Y,p0->pc.Z,p0->pc.W);tgl_warning("%f %f %f %f\n",p1->pc.X,p1->pc.Y,p1->pc.Z,p1->pc.W);tgl_warning("%f %f %f %f\n",p2->pc.X,p2->pc.Y,p2->pc.Z,p2->pc.W); #endif return; } clip_mask = 1 << clip_bit; co1 = (cc[0] ^ cc[1] ^ cc[2]) & clip_mask; if (co1) { /* one point outside */ if (cc[0] & clip_mask) { q[0] = p0; q[1] = p1; q[2] = p2; } else if (cc[1] & clip_mask) { q[0] = p1; q[1] = p2; q[2] = p0; } else { q[0] = p2; q[1] = p0; q[2] = p1; } { GLVertex tmp1, tmp2; GLfloat tt; tt = clip_proc[clip_bit](&tmp1.pc, &q[0]->pc, &q[1]->pc); updateTmp(&tmp1, q[0], q[1], tt); tt = clip_proc[clip_bit](&tmp2.pc, &q[0]->pc, &q[2]->pc); updateTmp(&tmp2, q[0], q[2], tt); tmp1.edge_flag = q[0]->edge_flag; edge_flag_tmp = q[2]->edge_flag; q[2]->edge_flag = 0; gl_draw_triangle_clip(&tmp1, q[1], q[2], clip_bit + 1); tmp2.edge_flag = 1; tmp1.edge_flag = 0; q[2]->edge_flag = edge_flag_tmp; gl_draw_triangle_clip(&tmp2, &tmp1, q[2], clip_bit + 1); } } else { /* two points outside */ if ((cc[0] & clip_mask) == 0) { q[0] = p0; q[1] = p1; q[2] = p2; } else if ((cc[1] & clip_mask) == 0) { q[0] = p1; q[1] = p2; q[2] = p0; } else { q[0] = p2; q[1] = p0; q[2] = p1; } { GLVertex tmp1, tmp2; GLfloat tt; tt = clip_proc[clip_bit](&tmp1.pc, &q[0]->pc, &q[1]->pc); updateTmp(&tmp1, q[0], q[1], tt); tt = clip_proc[clip_bit](&tmp2.pc, &q[0]->pc, &q[2]->pc); updateTmp(&tmp2, q[0], q[2], tt); tmp1.edge_flag = 1; tmp2.edge_flag = q[2]->edge_flag; gl_draw_triangle_clip(q[0], &tmp1, &tmp2, clip_bit + 1); } } } } /* see vertex.c to see how the draw functions are assigned.*/ void gl_draw_triangle_select(GLVertex* p0, GLVertex* p1, GLVertex* p2) { gl_add_select1(p0->zp.z, p1->zp.z, p2->zp.z); } void gl_draw_triangle_feedback(GLVertex* p0, GLVertex* p1, GLVertex* p2) { gl_add_feedback(GL_POLYGON_TOKEN, p0, p1, p2, 0); } #ifdef PROFILE int count_triangles, count_triangles_textured, count_pixels; #warning "Compile with PROFILE slows down everything" #endif /* see vertex.c to see how the draw functions are assigned.*/ void gl_draw_triangle_fill(GLVertex* p0, GLVertex* p1, GLVertex* p2) { GLContext* c = gl_get_context(); if (c->texture_2d_enabled) { /* if(c->current_texture)*/ #if TGL_FEATURE_LIT_TEXTURES == 1 if (c->current_shade_model != GL_SMOOTH) { p1->zp.r = p2->zp.r; p1->zp.g = p2->zp.g; p1->zp.b = p2->zp.b; p0->zp.r = p2->zp.r; p0->zp.g = p2->zp.g; p0->zp.b = p2->zp.b; } #endif ZB_setTexture(c->zb, c->current_texture->images[0].pixmap); #if TGL_FEATURE_BLEND == 1 if (c->zb->enable_blend) ZB_fillTriangleMappingPerspective(c->zb, &p0->zp, &p1->zp, &p2->zp); else ZB_fillTriangleMappingPerspectiveNOBLEND(c->zb, &p0->zp, &p1->zp, &p2->zp); #else ZB_fillTriangleMappingPerspectiveNOBLEND(c->zb, &p0->zp, &p1->zp, &p2->zp); #endif } else if (c->current_shade_model == GL_SMOOTH) { #if TGL_FEATURE_BLEND == 1 if (c->zb->enable_blend) ZB_fillTriangleSmooth(c->zb, &p0->zp, &p1->zp, &p2->zp); else ZB_fillTriangleSmoothNOBLEND(c->zb, &p0->zp, &p1->zp, &p2->zp); #else ZB_fillTriangleSmoothNOBLEND(c->zb, &p0->zp, &p1->zp, &p2->zp); #endif } else { #if TGL_FEATURE_BLEND == 1 if (c->zb->enable_blend) ZB_fillTriangleFlat(c->zb, &p0->zp, &p1->zp, &p2->zp); else ZB_fillTriangleFlatNOBLEND(c->zb, &p0->zp, &p1->zp, &p2->zp); #else ZB_fillTriangleFlatNOBLEND(c->zb, &p0->zp, &p1->zp, &p2->zp); #endif } } /* Render a clipped triangle in line mode */ void gl_draw_triangle_line(GLVertex* p0, GLVertex* p1, GLVertex* p2) { GLContext* c = gl_get_context(); if (c->zb->depth_test) { if (p0->edge_flag) ZB_line_z(c->zb, &p0->zp, &p1->zp); if (p1->edge_flag) ZB_line_z(c->zb, &p1->zp, &p2->zp); if (p2->edge_flag) ZB_line_z(c->zb, &p2->zp, &p0->zp); } else { if (p0->edge_flag) ZB_line(c->zb, &p0->zp, &p1->zp); if (p1->edge_flag) ZB_line(c->zb, &p1->zp, &p2->zp); if (p2->edge_flag) ZB_line(c->zb, &p2->zp, &p0->zp); } } /* Render a clipped triangle in point mode */ void gl_draw_triangle_point(GLVertex* p0, GLVertex* p1, GLVertex* p2) { GLContext* c = gl_get_context(); if (p0->edge_flag) ZB_plot(c->zb, &p0->zp); if (p1->edge_flag) ZB_plot(c->zb, &p1->zp); if (p2->edge_flag) ZB_plot(c->zb, &p2->zp); }
GB_unop__round_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__round_fp64_fp64) // op(A') function: GB (_unop_tran__round_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = round (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 = round (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] = round (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ROUND || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__round_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] = round (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] = round (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__round_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
ktensor.c
/* This file is part of ParTI!. ParTI! 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 3 of the License, or (at your option) any later version. ParTI! 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 Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #include <ParTI.h> #include <stdlib.h> #include <string.h> #include "../error/error.h" int sptNewKruskalTensor(sptKruskalTensor *ktsr, sptIndex nmodes, const sptIndex ndims[], sptIndex rank) { ktsr->nmodes = nmodes; ktsr->rank = rank; ktsr->ndims = (sptIndex*)malloc(nmodes*sizeof(sptIndex)); for(sptIndex i=0; i<nmodes; ++i) ktsr->ndims[i] = ndims[i]; ktsr->lambda = (sptValue*)malloc(rank*sizeof(sptValue)); ktsr->fit = 0.0; return 0; } /** * Shuffle factor matrices row indices. * * @param[in] ktsr Kruskal tensor to be shuffled * @param[out] map_inds is the renumbering mapping * */ void sptKruskalTensorInverseShuffleIndices(sptKruskalTensor * ktsr, sptIndex ** map_inds) { /* Renumber factor matrices rows */ sptIndex new_i; for(sptIndex m=0; m < ktsr->nmodes; ++m) { sptMatrix * mtx = ktsr->factors[m]; sptIndex * mode_map_inds = map_inds[m]; sptValue * tmp_values = malloc(mtx->cap * mtx->stride * sizeof (sptValue)); for(sptIndex i=0; i<mtx->nrows; ++i) { new_i = mode_map_inds[i]; for(sptIndex j=0; j<mtx->ncols; ++j) { tmp_values[i * mtx->stride + j] = mtx->values[new_i * mtx->stride + j]; } } free(mtx->values); mtx->values = tmp_values; } } void sptFreeKruskalTensor(sptKruskalTensor *ktsr) { ktsr->rank = 0; ktsr->fit = 0.0; free(ktsr->ndims); free(ktsr->lambda); for(sptIndex i=0; i<ktsr->nmodes; ++i) sptFreeMatrix(ktsr->factors[i]); free(ktsr->factors); ktsr->nmodes = 0; } double KruskalTensorFit( sptSparseTensor const * const spten, sptValue const * const __restrict lambda, sptMatrix ** mats, sptMatrix ** ata) { sptIndex const nmodes = spten->nmodes; double spten_normsq = SparseTensorFrobeniusNormSquared(spten); // printf("spten_normsq: %lf\n", spten_normsq); double const norm_mats = KruskalTensorFrobeniusNormSquared(nmodes, lambda, ata); // printf("norm_mats: %lf\n", norm_mats); double const inner = SparseKruskalTensorInnerProduct(nmodes, lambda, mats); // printf("inner: %lf\n", inner); double residual = spten_normsq + norm_mats - 2 * inner; // printf("residual: %lf\n", residual); if (residual > 0.0) { residual = sqrt(residual); } double fit = 1 - (residual / sqrt(spten_normsq)); return fit; } // Column-major. /* Compute a Kruskal tensor's norm is compute on "ata"s. Check Tammy's sparse */ double KruskalTensorFrobeniusNormSquared( sptIndex const nmodes, sptValue const * const __restrict lambda, sptMatrix ** ata) // ata: column-major { sptIndex const rank = ata[0]->ncols; sptIndex const stride = ata[0]->stride; sptValue * const __restrict tmp_atavals = ata[nmodes]->values; // Column-major double norm_mats = 0; #ifdef PARTI_USE_OPENMP #pragma omp parallel for #endif for(sptIndex x=0; x < rank*stride; ++x) { tmp_atavals[x] = 1.; } /* Compute Hadamard product for all "ata"s */ for(sptIndex m=0; m < nmodes; ++m) { sptValue const * const __restrict atavals = ata[m]->values; #ifdef PARTI_USE_OPENMP #pragma omp parallel for #endif for(sptIndex i=0; i < rank; ++i) { for(sptIndex j=i; j < rank; ++j) { tmp_atavals[j * stride + i] *= atavals[j * stride + i]; } } } /* compute lambda^T * aTa[MAX_NMODES] * lambda, only compute a half of them because of its symmetric */ #ifdef PARTI_USE_OPENMP #pragma omp parallel for reduction(+:norm_mats) #endif for(sptIndex i=0; i < rank; ++i) { norm_mats += tmp_atavals[i+(i*stride)] * lambda[i] * lambda[i]; for(sptIndex j=i+1; j < rank; ++j) { norm_mats += tmp_atavals[i+(j*stride)] * lambda[i] * lambda[j] * 2; } } return fabs(norm_mats); } // Row-major, compute via MTTKRP result (mats[nmodes]) and mats[nmodes-1]. double SparseKruskalTensorInnerProduct( sptIndex const nmodes, sptValue const * const __restrict lambda, sptMatrix ** mats) { sptIndex const rank = mats[0]->ncols; sptIndex const stride = mats[0]->stride; sptIndex const last_mode = nmodes - 1; sptIndex const I = mats[last_mode]->nrows; // printf("mats[nmodes-1]:\n"); // sptDumpMatrix(mats[nmodes-1], stdout); // printf("mats[nmodes]:\n"); // sptDumpMatrix(mats[nmodes], stdout); sptValue const * const last_vals = mats[last_mode]->values; sptValue const * const tmp_vals = mats[nmodes]->values; sptValue * buffer_accum; double inner = 0; double * const __restrict accum = (double *) malloc(rank*sizeof(*accum)); #ifdef PARTI_USE_OPENMP #pragma omp parallel for #endif for(sptIndex r=0; r < rank; ++r) { accum[r] = 0.0; } #ifdef PARTI_USE_OPENMP #pragma omp parallel { int const nthreads = omp_get_num_threads(); #pragma omp master { buffer_accum = (sptValue *)malloc(nthreads * rank * sizeof(sptValue)); for(sptIndex j=0; j < nthreads * rank; ++j) buffer_accum[j] = 0.0; } } #endif #ifdef PARTI_USE_OPENMP #pragma omp parallel { int const tid = omp_get_thread_num(); int const nthreads = omp_get_num_threads(); sptValue * loc_accum = buffer_accum + tid * rank; #pragma omp for for(sptIndex i=0; i < I; ++i) { for(sptIndex r=0; r < rank; ++r) { loc_accum[r] += last_vals[r+(i*stride)] * tmp_vals[r+(i*stride)]; } } #pragma omp for for(sptIndex j=0; j < rank; ++j) { for(int i=0; i < nthreads; ++i) { accum[j] += buffer_accum[i*rank + j]; } } } #else for(sptIndex i=0; i < I; ++i) { for(sptIndex r=0; r < rank; ++r) { accum[r] += last_vals[r+(i*stride)] * tmp_vals[r+(i*stride)]; } } #endif #ifdef PARTI_USE_OPENMP #pragma omp parallel for reduction(+:inner) #endif for(sptIndex r=0; r < rank; ++r) { inner += accum[r] * lambda[r]; } #ifdef PARTI_USE_OPENMP free(buffer_accum); #endif return inner; }
feast_condition_number_utility.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_FEAST_CONDITION_NUMBER_UTILITY ) #define KRATOS_FEAST_CONDITION_NUMBER_UTILITY /* System includes */ /* External includes */ /* Project includes */ #include "linear_solvers/linear_solver.h" #ifdef INCLUDE_FEAST #include "external_includes/feast_solver.h" #endif namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// This utility uses the FEAST solver to obtain (estimate) the the condition number of a regular matrix /** * Regular matrix: A*A^H=A^H*A */ template<class TSparseSpace = UblasSpace<double, CompressedMatrix, Vector>, class TDenseSpace = UblasSpace<double, Matrix, Vector> > class FEASTConditionNumberUtility { public: ///@name Type Definitions ///@{ typedef Matrix MatrixType; typedef Vector VectorType; typedef std::size_t SizeType; typedef std::size_t IndexType; typedef typename TSparseSpace::MatrixType SparseMatrixType; typedef typename TSparseSpace::VectorType SparseVectorType; typedef typename TDenseSpace::MatrixType DenseMatrixType; typedef typename TDenseSpace::VectorType DenseVectorType; typedef std::complex<double> ComplexType; typedef compressed_matrix<ComplexType> ComplexSparseMatrixType; typedef matrix<ComplexType> ComplexDenseMatrixType; typedef vector<ComplexType> ComplexVectorType; typedef UblasSpace<ComplexType, ComplexSparseMatrixType, ComplexVectorType> ComplexSparseSpaceType; typedef UblasSpace<ComplexType, ComplexDenseMatrixType, ComplexVectorType> ComplexDenseSpaceType; typedef LinearSolver<ComplexSparseSpaceType, ComplexDenseSpaceType> ComplexLinearSolverType; ///@} ///@name Life Cycle ///@{ /* Constructor */ /** Destructor */ ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * Computes the condition number using the maximum and minimum eigenvalue of the system (in moduli) * @param InputMatrix: The matrix to obtain the condition number * @param pLinearSolver: The complex linear solver considered in the FEAST solver * @return condition_number: The condition number obtained */ static inline double ConditionNumber( const MatrixType& InputMatrix, ComplexLinearSolverType::Pointer pLinearSolver = nullptr ) { #ifdef INCLUDE_FEAST typedef FEASTSolver<TSparseSpace, TDenseSpace> FEASTSolverType; Parameters this_params(R"( { "solver_type": "FEAST", "print_feast_output": false, "perform_stochastic_estimate": true, "solve_eigenvalue_problem": true, "lambda_min": 0.0, "lambda_max": 1.0, "echo_level": 0, "number_of_eigenvalues": 0, "search_dimension": 10 })"); const std::size_t size = InputMatrix.size1(); const double normA = TSparseSpace::TwoNorm(InputMatrix); this_params["lambda_max"].SetDouble(normA); this_params["lambda_min"].SetDouble(-normA); this_params["number_of_eigenvalues"].SetInt(size * 2/3 - 1); this_params["search_dimension"].SetInt(3/2 * size + 1); SparseMatrixType copy_matrix = InputMatrix; SparseMatrixType identity_matrix = IdentityMatrix(size, size); // Create the auxilary eigen system DenseMatrixType eigen_vectors; DenseVectorType eigen_values; // Create the FEAST solver FEASTSolverType FEASTSolver(Kratos::make_shared<Parameters>(this_params), pLinearSolver); // Solve the problem FEASTSolver.Solve(copy_matrix, identity_matrix, eigen_values, eigen_vectors); // Size of the eigen values vector const int dim_eigen_values = eigen_values.size(); // We get the moduli of the eigen values #pragma omp parallel for for (int i = 0; i < dim_eigen_values; i++) { eigen_values[i] = std::abs(eigen_values[i]); } // Now we sort the vector std::sort(eigen_values.begin(), eigen_values.end()); // We compute the eigen value double condition_number = 0.0; if (dim_eigen_values > 0) condition_number = eigen_values[dim_eigen_values - 1]/eigen_values[0]; #else const double condition_number = 0.0; KRATOS_ERROR << "YOU MUST COMPILE FEAST IN ORDER TO USE THIS UTILITY" << std::endl; #endif return condition_number; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ ///@} ///@name Friends ///@{ private: ///@name Private static Member Variables ///@{ ///@} ///@name Private member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Private LifeCycle ///@{ ///@} ///@name Unaccessible methods ///@{ FEASTConditionNumberUtility(void); FEASTConditionNumberUtility(FEASTConditionNumberUtility& rSource); }; /* Class FEASTConditionNumberUtility */ ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ } /* namespace Kratos.*/ #endif /* KRATOS_FEAST_CONDITION_NUMBER_UTILITY defined */
tinyexr.h
#ifndef TINYEXR_H_ #define TINYEXR_H_ /* Copyright (c) 2014 - 2020, Syoyo Fujita and many contributors. 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 the Syoyo Fujita 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 <COPYRIGHT HOLDER> 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. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #define NOMINMAX #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_THREAD #define TINYEXR_USE_THREAD (0) // No threaded loading. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_OPENMP #ifdef _OPENMP #define TINYEXR_USE_OPENMP (1) #else #define TINYEXR_USE_OPENMP (0) #endif #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-6) #define TINYEXR_ERROR_CANT_OPEN_FILE (-7) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8) #define TINYEXR_ERROR_INVALID_HEADER (-9) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10) #define TINYEXR_ERROR_CANT_WRITE_FILE (-11) #define TINYEXR_ERROR_SERIALZATION_FAILED (-12) #define TINYEXR_ERROR_LAYER_NOT_FOUND (-13) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 // tile format image; // not zero for only a single-part "normal" tiled file (according to spec.) int tiled; int long_name; // long name attribute // deep image(EXR 2.0); // for a multi-part file, indicates that at least one part is of type deep* (according to spec.) int non_image; int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRBox2i { int min_x; int min_y; int max_x; int max_y; } EXRBox2i; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; EXRBox2i data_window; EXRBox2i display_window; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; // for a single-part file, agree with the version field bit 11 // for a multi-part file, it is consistent with the type of part int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute *custom_attributes; // array of EXRAttribute. size = // `num_custom_attributes`. EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) // name attribute required for multipart files; // must be unique and non empty (according to spec.); // use EXRSetNameAttr for setting value; // max 255 character allowed - excluding terminating zero char name[256]; } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. struct _EXRImage* next_level; // NULL if scanline format or image is the last level. int level_x; // x level index int level_y; // y level index unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { For backward compatibility. Not recommended to use. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // Loads single-frame OpenEXR image by specifying layer name. Assume EXR image // contains A(single channel alpha) or RGB(A) channels. Application must free // image data as returned by `out_rgba` Result image format is: float x RGBA x // width x hight Returns negative value and may set error string in `err` when // there's an error When the specified layer name is not found in the EXR file, // the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`. extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layer_name, const char **err); // // Get layer infos from EXR file. // // @param[out] layer_names List of layer names. Application must free memory // after using this. // @param[out] num_layers The number of layers // @param[out] err Error string(will be filled when the function returns error // code). Free it using FreeEXRErrorMessage after using this value. // // @return TINYEXR_SUCCEES upon success. // extern int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err); // @deprecated { to be removed. } // Simple wrapper API for ParseEXRHeaderFromFile. // checking given file is a EXR file(by just look up header) // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for // others extern int IsEXR(const char *filename); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // Returns the number of resolution levels of the image (including the base) extern int EXRNumLevels(const EXRImage* exr_image); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Set name attribute of EXRHeader struct (it makes a copy) extern void EXRSetNameAttr(EXRHeader *exr_header, const char* name); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Frees internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Frees internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Frees error message extern void FreeEXRErrorMessage(const char *msg); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Saves multi-channel, multi-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // File global attributes (eg. display_window) must be set in the first header. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRMultipartImageToFile(const EXRImage *images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err); // Saves multi-channel, multi-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // File global attributes (eg. display_window) must be set in the first header. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRMultipartImageToMemory(const EXRImage *images, const EXRHeader **exr_headers, unsigned int num_parts, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEFINED #define TINYEXR_IMPLEMENTATION_DEFINED #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> // for UTF-8 #endif #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> // #include <iostream> // debug #include <limits> #include <string> #include <vector> #include <set> // https://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support #if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1900) #define TINYEXR_HAS_CXX11 (1) // C++11 #include <cstdint> #if TINYEXR_USE_THREAD #include <atomic> #include <thread> #endif #endif // __cplusplus > 199711L #if TINYEXR_USE_OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Weverything" #endif #include "zfp.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occurred in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #ifdef _MSC_VER #pragma warning(pop) #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif } // namespace miniz #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static void swap4(int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static void swap4(float *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else float tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #endif static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { return false; } } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(&outLen); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct { int min_x; int min_y; int max_x; int max_y; } Box2iInfo; struct HeaderInfo { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; Box2iInfo data_window; int line_order; Box2iInfo display_window; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tiled; // Non-zero if the part is tiled. int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; // required for multi-part or non-image files std::string name; // required for multi-part or non-image files std::string type; void clear() { channels.clear(); attributes.clear(); data_window.min_x = 0; data_window.min_y = 0; data_window.max_x = 0; data_window.max_y = 0; line_order = 0; display_window.min_x = 0; display_window.min_y = 0; display_window.max_x = 0; display_window.max_y = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tiled = 0; tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; name.clear(); type.clear(); } }; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString(&info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(&info.pixel_type); tinyexr::swap4(&info.x_sampling); tinyexr::swap4(&info.y_sampling); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(&pixel_type); tinyexr::swap4(&x_sampling); tinyexr::swap4(&y_sampling); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressible run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; // Fixes #116: Add bounds check to in buffer. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } // Workaround for issue #112. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`. if (src_size <= 2) { return false; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); if (ret != static_cast<int>(uncompressed_size)) { return false; } // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierarchical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- unsigned int len : 8; // code length 0 unsigned int lit : 24; // lit p size unsigned int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<long long *> fHeap(HUF_ENCSIZE); *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode.data()); memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = (unsigned char)(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode >= ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == (long long)LONG_ZEROCODE_RUN) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= (long long)SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { unsigned int *p = pl->p; pl->p = new unsigned int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new unsigned int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *(unsigned char *)(in++); \ lc += 8; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety // Issue 100. if ((out - 1) < ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; // begin unsigned short *oe = out + no; // end const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) { // // Found : get long code // lc -= l; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = (unsigned char *)buf; b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = (const unsigned char *)buf; return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(), raw->data()); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); if (size_t((ptr - inPtr) + length) > inLen) { return false; } std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; unsigned int precision; unsigned int __pad0; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* unsigned int __pad1; ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0; } }; static bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes, std::string *err) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0)) { if (attributes[i].size == 1) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; break; } else { if (err) { (*err) += "zfpCompressionType attribute must be uchar(1 byte) type.\n"; } return false; } } } if (!foundType) { if (err) { (*err) += "`zfpCompressionType` attribute not found.\n"; } return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } if (err) { (*err) += "`zfpCompressionRate` attribute not found.\n"; } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } if (err) { (*err) += "`zfpCompressionPrecision` attribute not found.\n"; } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } if (err) { (*err) += "`zfpCompressionTolerance` attribute not found.\n"; } } else { if (err) { (*err) += "Unknown value specified for `zfpCompressionType`.\n"; } } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, size_t num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = size_t(dst_width) * size_t(dst_num_lines) * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((size_t(dst_width) & 3U) || (size_t(dst_num_lines) & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, static_cast<unsigned int>(dst_width), static_cast<unsigned int>(dst_num_lines) * static_cast<unsigned int>(num_channels)); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimension */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = size_t(dst_width) * size_t(dst_num_lines); for (size_t c = 0; c < size_t(num_channels); c++) { // decompress 4x4 pixel block. for (size_t y = 0; y < size_t(dst_num_lines); y += 4) { for (size_t x = 0; x < size_t(dst_width); x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (size_t j = 0; j < 4; j++) { for (size_t i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * size_t(dst_width) + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. static bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((size_t(width) & 3U) || (size_t(num_lines) & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, static_cast<unsigned int>(width), static_cast<unsigned int>(num_lines * num_channels)); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = size_t(width) * size_t(num_lines); for (size_t c = 0; c < size_t(num_channels); c++) { // compress 4x4 pixel block. for (size_t y = 0; y < size_t(num_lines); y += 4) { for (size_t x = 0; x < size_t(width); x += 4) { float fblock[16]; for (size_t j = 0; j < 4; j++) { for (size_t i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * size_t(width) + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = static_cast<unsigned int>(zfp_stream_compressed_size(zfp)); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // heuristics #define TINYEXR_DIMENSION_THRESHOLD (1024 * 8192) // TODO(syoyo): Refactor function arguments. static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); if (!ret) { return false; } // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); if (dstLen == 0) { return false; } if (!tinyexr::DecompressRle( reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; std::string e; if (!tinyexr::FindZFPCompressionParam(&zfp_compression_param, attributes, int(num_attributes), &e)) { // This code path should not be reachable. assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } } return true; } static bool DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { // Here, data_width and data_height are the dimensions of the current (sub)level. if (tile_size_x * tile_offset_x > data_width || tile_size_y * tile_offset_y > data_height) { return false; } // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { // ??? return false; } } return true; } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } #ifdef _WIN32 static inline std::wstring UTF8ToWchar(const std::string &str) { int wstr_size = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0); std::wstring wstr(wstr_size, 0); MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0], (int)wstr.size()); return wstr; } #endif static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; bool has_name = false; bool has_type = false; info->name.clear(); info->type.clear(); info->data_window.min_x = 0; info->data_window.min_y = 0; info->data_window.max_x = 0; info->data_window.max_y = 0; info->line_order = 0; // @fixme info->display_window.min_x = 0; info->display_window.min_y = 0; info->display_window.max_x = 0; info->display_window.max_y = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tiled = 0; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { if (err) { (*err) += "Failed to read attribute.\n"; } return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; // For a multipart file, the version field 9th bit is 0. if ((version->tiled || version->multipart || version->non_image) && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); if (x_size > static_cast<unsigned int>(std::numeric_limits<int>::max()) || y_size > static_cast<unsigned int>(std::numeric_limits<int>::max())) { if (err) { (*err) = "Tile sizes were invalid."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; info->tiled = 1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) += "Failed to parse channel info.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window.min_x, &data.at(0), sizeof(int)); memcpy(&info->data_window.min_y, &data.at(4), sizeof(int)); memcpy(&info->data_window.max_x, &data.at(8), sizeof(int)); memcpy(&info->data_window.max_y, &data.at(12), sizeof(int)); tinyexr::swap4(&info->data_window.min_x); tinyexr::swap4(&info->data_window.min_y); tinyexr::swap4(&info->data_window.max_x); tinyexr::swap4(&info->data_window.max_y); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window.min_x, &data.at(0), sizeof(int)); memcpy(&info->display_window.min_y, &data.at(4), sizeof(int)); memcpy(&info->display_window.max_x, &data.at(8), sizeof(int)); memcpy(&info->display_window.max_y, &data.at(12), sizeof(int)); tinyexr::swap4(&info->display_window.min_x); tinyexr::swap4(&info->display_window.min_y); tinyexr::swap4(&info->display_window.max_x); tinyexr::swap4(&info->display_window.max_y); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4(&info->pixel_aspect_ratio); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4(&info->screen_window_center[0]); tinyexr::swap4(&info->screen_window_center[1]); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4(&info->screen_window_width); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(&info->chunk_count); } } else if (attr_name.compare("name") == 0) { if (!data.empty() && data[0]) { data.push_back(0); size_t len = strlen(reinterpret_cast<const char*>(&data[0])); info->name.resize(len); info->name.assign(reinterpret_cast<const char*>(&data[0]), len); has_name = true; } } else if (attr_name.compare("type") == 0) { if (!data.empty() && data[0]) { data.push_back(0); size_t len = strlen(reinterpret_cast<const char*>(&data[0])); info->type.resize(len); info->type.assign(reinterpret_cast<const char*>(&data[0]), len); has_type = true; } } else { // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (version->multipart || version->non_image) { if (!has_name) { ss_err << "\"name\" attribute not found in the header." << std::endl; } if (!has_type) { ss_err << "\"type\" attribute not found in the header." << std::endl; } } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window.min_x = info.display_window.min_x; exr_header->display_window.min_y = info.display_window.min_y; exr_header->display_window.max_x = info.display_window.max_x; exr_header->display_window.max_y = info.display_window.max_y; exr_header->data_window.min_x = info.data_window.min_x; exr_header->data_window.min_y = info.data_window.min_y; exr_header->data_window.max_x = info.data_window.max_x; exr_header->data_window.max_y = info.data_window.max_y; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tiled = info.tiled; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; EXRSetNameAttr(exr_header, info.name.c_str()); if (!info.type.empty()) { if (info.type == "scanlineimage") { assert(!exr_header->tiled); } else if (info.type == "tiledimage") { assert(exr_header->tiled); } else if (info.type == "deeptile") { exr_header->non_image = 1; assert(exr_header->tiled); } else if (info.type == "deepscanline") { exr_header->non_image = 1; assert(!exr_header->tiled); } else { assert(false); } } exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy pointer exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } struct OffsetData { OffsetData() : num_x_levels(0), num_y_levels(0) {} std::vector<std::vector<std::vector <tinyexr::tinyexr_uint64> > > offsets; int num_x_levels; int num_y_levels; }; int LevelIndex(int lx, int ly, int tile_level_mode, int num_x_levels) { switch (tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: return 0; case TINYEXR_TILE_MIPMAP_LEVELS: return lx; case TINYEXR_TILE_RIPMAP_LEVELS: return lx + ly * num_x_levels; default: assert(false); } return 0; } static int LevelSize(int toplevel_size, int level, int tile_rounding_mode) { assert(level >= 0); int b = (int)(1u << (unsigned)level); int level_size = toplevel_size / b; if (tile_rounding_mode == TINYEXR_TILE_ROUND_UP && level_size * b < toplevel_size) level_size += 1; return std::max(level_size, 1); } static int DecodeTiledLevel(EXRImage* exr_image, const EXRHeader* exr_header, const OffsetData& offset_data, const std::vector<size_t>& channel_offset_list, int pixel_data_size, const unsigned char* head, const size_t size, std::string* err) { int num_channels = exr_header->num_channels; int level_index = LevelIndex(exr_image->level_x, exr_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels); int num_y_tiles = (int)offset_data.offsets[level_index].size(); assert(num_y_tiles); int num_x_tiles = (int)offset_data.offsets[level_index][0].size(); assert(num_x_tiles); int num_tiles = num_x_tiles * num_y_tiles; int err_code = TINYEXR_SUCCESS; enum { EF_SUCCESS = 0, EF_INVALID_DATA = 1, EF_INSUFFICIENT_DATA = 2, EF_FAILED_TO_DECODE = 4 }; #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<unsigned> error_flag(EF_SUCCESS); #else unsigned error_flag(EF_SUCCESS); #endif // Although the spec says : "...the data window is subdivided into an array of smaller rectangles...", // the IlmImf library allows the dimensions of the tile to be larger (or equal) than the dimensions of the data window. #if 0 if ((exr_header->tile_size_x > exr_image->width || exr_header->tile_size_y > exr_image->height) && exr_image->level_x == 0 && exr_image->level_y == 0) { if (err) { (*err) += "Failed to decode tile data.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; } #endif exr_image->tiles = static_cast<EXRTile*>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> tile_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_tiles)) { num_threads = int(num_tiles); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int tile_idx = 0; while ((tile_idx = tile_count++) < num_tiles) { #else #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int tile_idx = 0; tile_idx < num_tiles; tile_idx++) { #endif // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); int x_tile = tile_idx % num_x_tiles; int y_tile = tile_idx / num_x_tiles; // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) tinyexr::tinyexr_uint64 offset = offset_data.offsets[level_index][y_tile][x_tile]; if (offset + sizeof(int) * 5 > size) { // Insufficient data size. error_flag |= EF_INSUFFICIENT_DATA; continue; } size_t data_size = size_t(size - (offset + sizeof(int) * 5)); const unsigned char* data_ptr = reinterpret_cast<const unsigned char*>(head + offset); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4(&tile_coordinates[0]); tinyexr::swap4(&tile_coordinates[1]); tinyexr::swap4(&tile_coordinates[2]); tinyexr::swap4(&tile_coordinates[3]); if (tile_coordinates[2] != exr_image->level_x) { // Invalid data. error_flag |= EF_INVALID_DATA; continue; } if (tile_coordinates[3] != exr_image->level_y) { // Invalid data. error_flag |= EF_INVALID_DATA; continue; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(&data_len); if (data_len < 2 || size_t(data_len) > data_size) { // Insufficient data size. error_flag |= EF_INSUFFICIENT_DATA; continue; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; bool ret = tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, exr_image->width, exr_image->height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); if (!ret) { // Failed to decode tile data. error_flag |= EF_FAILED_TO_DECODE; } exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } // num_thread loop for (auto& t : workers) { t.join(); } #else } // parallel for #endif // Even in the event of an error, the reserved memory may be freed. exr_image->num_channels = num_channels; exr_image->num_tiles = static_cast<int>(num_tiles); if (error_flag) err_code = TINYEXR_ERROR_INVALID_DATA; if (err) { if (error_flag & EF_INSUFFICIENT_DATA) { (*err) += "Insufficient data length.\n"; } if (error_flag & EF_FAILED_TO_DECODE) { (*err) += "Failed to decode tile data.\n"; } } return err_code; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const OffsetData& offset_data, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, exr_header->custom_attributes, int(exr_header->num_custom_attributes), err)) { return TINYEXR_ERROR_INVALID_HEADER; } #endif } if (exr_header->data_window.max_x < exr_header->data_window.min_x || exr_header->data_window.max_y < exr_header->data_window.min_y) { if (err) { (*err) += "Invalid data window.\n"; } return TINYEXR_ERROR_INVALID_DATA; } int data_width = exr_header->data_window.max_x - exr_header->data_window.min_x + 1; int data_height = exr_header->data_window.max_y - exr_header->data_window.min_y + 1; // Do not allow too large data_width and data_height. header invalid? { if ((data_width > TINYEXR_DIMENSION_THRESHOLD) || (data_height > TINYEXR_DIMENSION_THRESHOLD)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } if (exr_header->tiled) { if ((exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) || (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD)) { if (err) { std::stringstream ss; ss << "tile with or tile height too large. tile width: " << exr_header->tile_size_x << ", " << "tile height = " << exr_header->tile_size_y << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } } const std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0]; size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<bool> invalid_data(false); #else bool invalid_data(false); #endif if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) { EXRImage* level_image = NULL; for (int level = 0; level < offset_data.num_x_levels; ++level) { if (!level_image) { level_image = exr_image; } else { level_image->next_level = new EXRImage; InitEXRImage(level_image->next_level); level_image = level_image->next_level; } level_image->width = LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level, exr_header->tile_rounding_mode); level_image->height = LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level, exr_header->tile_rounding_mode); level_image->level_x = level; level_image->level_y = level; int ret = DecodeTiledLevel(level_image, exr_header, offset_data, channel_offset_list, pixel_data_size, head, size, err); if (ret != TINYEXR_SUCCESS) return ret; } } else { EXRImage* level_image = NULL; for (int level_y = 0; level_y < offset_data.num_y_levels; ++level_y) for (int level_x = 0; level_x < offset_data.num_x_levels; ++level_x) { if (!level_image) { level_image = exr_image; } else { level_image->next_level = new EXRImage; InitEXRImage(level_image->next_level); level_image = level_image->next_level; } level_image->width = LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level_x, exr_header->tile_rounding_mode); level_image->height = LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level_y, exr_header->tile_rounding_mode); level_image->level_x = level_x; level_image->level_y = level_y; int ret = DecodeTiledLevel(level_image, exr_header, offset_data, channel_offset_list, pixel_data_size, head, size, err); if (ret != TINYEXR_SUCCESS) return ret; } } } else { // scanline format // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> y_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_blocks)) { num_threads = int(num_blocks); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int y = 0; while ((y = y_count++) < int(num_blocks)) { #else #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { #endif size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(&line_no); tinyexr::swap4(&data_len); if (size_t(data_len) > data_size) { invalid_data = true; } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) { // Too large value. Assume this is invalid // 2**20 = 1048576 = heuristic value. invalid_data = true; } else if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example // `data_len < 4` invalid_data = true; } else { // line_no may be negative. int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window.max_y + 1)); int num_lines = end_line_no - line_no; if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window.min_y); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { line_no -= exr_header->data_window.min_y; } if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>( exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif } if (invalid_data) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(&y); tinyexr::swap4(&data_len); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int FloorLog2(unsigned x) { // // For x > 0, floorLog2(y) returns floor(log(x)/log(2)). // int y = 0; while (x > 1) { y += 1; x >>= 1u; } return y; } static int CeilLog2(unsigned x) { // // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)). // int y = 0; int r = 0; while (x > 1) { if (x & 1) r = 1; y += 1; x >>= 1u; } return y + r; } static int RoundLog2(int x, int tile_rounding_mode) { return (tile_rounding_mode == TINYEXR_TILE_ROUND_DOWN) ? FloorLog2(static_cast<unsigned>(x)) : CeilLog2(static_cast<unsigned>(x)); } static int CalculateNumXLevels(const EXRHeader* exr_header) { int min_x = exr_header->data_window.min_x; int max_x = exr_header->data_window.max_x; int min_y = exr_header->data_window.min_y; int max_y = exr_header->data_window.max_y; int num = 0; switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: num = 1; break; case TINYEXR_TILE_MIPMAP_LEVELS: { int w = max_x - min_x + 1; int h = max_y - min_y + 1; num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1; } break; case TINYEXR_TILE_RIPMAP_LEVELS: { int w = max_x - min_x + 1; num = RoundLog2(w, exr_header->tile_rounding_mode) + 1; } break; default: assert(false); } return num; } static int CalculateNumYLevels(const EXRHeader* exr_header) { int min_x = exr_header->data_window.min_x; int max_x = exr_header->data_window.max_x; int min_y = exr_header->data_window.min_y; int max_y = exr_header->data_window.max_y; int num = 0; switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: num = 1; break; case TINYEXR_TILE_MIPMAP_LEVELS: { int w = max_x - min_x + 1; int h = max_y - min_y + 1; num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1; } break; case TINYEXR_TILE_RIPMAP_LEVELS: { int h = max_y - min_y + 1; num = RoundLog2(h, exr_header->tile_rounding_mode) + 1; } break; default: assert(false); } return num; } static void CalculateNumTiles(std::vector<int>& numTiles, int toplevel_size, int size, int tile_rounding_mode) { for (unsigned i = 0; i < numTiles.size(); i++) { int l = LevelSize(toplevel_size, i, tile_rounding_mode); assert(l <= std::numeric_limits<int>::max() - size + 1); numTiles[i] = (l + size - 1) / size; } } static void PrecalculateTileInfo(std::vector<int>& num_x_tiles, std::vector<int>& num_y_tiles, const EXRHeader* exr_header) { int min_x = exr_header->data_window.min_x; int max_x = exr_header->data_window.max_x; int min_y = exr_header->data_window.min_y; int max_y = exr_header->data_window.max_y; int num_x_levels = CalculateNumXLevels(exr_header); int num_y_levels = CalculateNumYLevels(exr_header); num_x_tiles.resize(num_x_levels); num_y_tiles.resize(num_y_levels); CalculateNumTiles(num_x_tiles, max_x - min_x + 1, exr_header->tile_size_x, exr_header->tile_rounding_mode); CalculateNumTiles(num_y_tiles, max_y - min_y + 1, exr_header->tile_size_y, exr_header->tile_rounding_mode); } static void InitSingleResolutionOffsets(OffsetData& offset_data, size_t num_blocks) { offset_data.offsets.resize(1); offset_data.offsets[0].resize(1); offset_data.offsets[0][0].resize(num_blocks); offset_data.num_x_levels = 1; offset_data.num_y_levels = 1; } // Return sum of tile blocks. static int InitTileOffsets(OffsetData& offset_data, const EXRHeader* exr_header, const std::vector<int>& num_x_tiles, const std::vector<int>& num_y_tiles) { int num_tile_blocks = 0; offset_data.num_x_levels = static_cast<int>(num_x_tiles.size()); offset_data.num_y_levels = static_cast<int>(num_y_tiles.size()); switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: case TINYEXR_TILE_MIPMAP_LEVELS: assert(offset_data.num_x_levels == offset_data.num_y_levels); offset_data.offsets.resize(offset_data.num_x_levels); for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { offset_data.offsets[l].resize(num_y_tiles[l]); for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { offset_data.offsets[l][dy].resize(num_x_tiles[l]); num_tile_blocks += num_x_tiles[l]; } } break; case TINYEXR_TILE_RIPMAP_LEVELS: offset_data.offsets.resize(static_cast<size_t>(offset_data.num_x_levels) * static_cast<size_t>(offset_data.num_y_levels)); for (int ly = 0; ly < offset_data.num_y_levels; ++ly) { for (int lx = 0; lx < offset_data.num_x_levels; ++lx) { int l = ly * offset_data.num_x_levels + lx; offset_data.offsets[l].resize(num_y_tiles[ly]); for (size_t dy = 0; dy < offset_data.offsets[l].size(); ++dy) { offset_data.offsets[l][dy].resize(num_x_tiles[lx]); num_tile_blocks += num_x_tiles[lx]; } } } break; default: assert(false); } return num_tile_blocks; } static bool IsAnyOffsetsAreInvalid(const OffsetData& offset_data) { for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) if (reinterpret_cast<const tinyexr::tinyexr_int64&>(offset_data.offsets[l][dy][dx]) <= 0) return true; return false; } static bool isValidTile(const EXRHeader* exr_header, const OffsetData& offset_data, int dx, int dy, int lx, int ly) { if (lx < 0 || ly < 0 || dx < 0 || dy < 0) return false; int num_x_levels = offset_data.num_x_levels; int num_y_levels = offset_data.num_y_levels; switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: if (lx == 0 && ly == 0 && offset_data.offsets.size() > 0 && offset_data.offsets[0].size() > static_cast<size_t>(dy) && offset_data.offsets[0][dy].size() > static_cast<size_t>(dx)) { return true; } break; case TINYEXR_TILE_MIPMAP_LEVELS: if (lx < num_x_levels && ly < num_y_levels && offset_data.offsets.size() > static_cast<size_t>(lx) && offset_data.offsets[lx].size() > static_cast<size_t>(dy) && offset_data.offsets[lx][dy].size() > static_cast<size_t>(dx)) { return true; } break; case TINYEXR_TILE_RIPMAP_LEVELS: { size_t idx = static_cast<size_t>(lx) + static_cast<size_t>(ly)* static_cast<size_t>(num_x_levels); if (lx < num_x_levels && ly < num_y_levels && (offset_data.offsets.size() > idx) && offset_data.offsets[idx].size() > static_cast<size_t>(dy) && offset_data.offsets[idx][dy].size() > static_cast<size_t>(dx)) { return true; } } break; default: return false; } return false; } static void ReconstructTileOffsets(OffsetData& offset_data, const EXRHeader* exr_header, const unsigned char* head, const unsigned char* marker, const size_t size, bool isMultiPartFile, bool isDeep) { int numXLevels = offset_data.num_x_levels; for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { tinyexr::tinyexr_uint64 tileOffset = marker - head; if (isMultiPartFile) { //int partNumber; marker += sizeof(int); } int tileX; memcpy(&tileX, marker, sizeof(int)); tinyexr::swap4(&tileX); marker += sizeof(int); int tileY; memcpy(&tileY, marker, sizeof(int)); tinyexr::swap4(&tileY); marker += sizeof(int); int levelX; memcpy(&levelX, marker, sizeof(int)); tinyexr::swap4(&levelX); marker += sizeof(int); int levelY; memcpy(&levelY, marker, sizeof(int)); tinyexr::swap4(&levelY); marker += sizeof(int); if (isDeep) { tinyexr::tinyexr_int64 packed_offset_table_size; memcpy(&packed_offset_table_size, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_offset_table_size)); marker += sizeof(tinyexr::tinyexr_int64); tinyexr::tinyexr_int64 packed_sample_size; memcpy(&packed_sample_size, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_sample_size)); marker += sizeof(tinyexr::tinyexr_int64); // next Int64 is unpacked sample size - skip that too marker += packed_offset_table_size + packed_sample_size + 8; } else { int dataSize; memcpy(&dataSize, marker, sizeof(int)); tinyexr::swap4(&dataSize); marker += sizeof(int); marker += dataSize; } if (!isValidTile(exr_header, offset_data, tileX, tileY, levelX, levelY)) return; int level_idx = LevelIndex(levelX, levelY, exr_header->tile_level_mode, numXLevels); offset_data.offsets[level_idx][tileY][tileX] = tileOffset; } } } } // marker output is also static int ReadOffsets(OffsetData& offset_data, const unsigned char* head, const unsigned char*& marker, const size_t size, const char** err) { for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { tinyexr::tinyexr_uint64 offset; if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offset_data.offsets[l][dy][dx] = offset; } } } return TINYEXR_SUCCESS; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } if (exr_header->data_window.max_x < exr_header->data_window.min_x || exr_header->data_window.max_x - exr_header->data_window.min_x == std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data width value", err); return TINYEXR_ERROR_INVALID_DATA; } int data_width = exr_header->data_window.max_x - exr_header->data_window.min_x + 1; if (exr_header->data_window.max_y < exr_header->data_window.min_y || exr_header->data_window.max_y - exr_header->data_window.min_y == std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } int data_height = exr_header->data_window.max_y - exr_header->data_window.min_y + 1; // Do not allow too large data_width and data_height. header invalid? { if (data_width > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("data height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } if (exr_header->tiled) { if (exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("tile width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("tile height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } // Read offset tables. OffsetData offset_data; size_t num_blocks = 0; // For a multi-resolution image, the size of the offset table will be calculated from the other attributes of the header. // If chunk_count > 0 then chunk_count must be equal to the calculated tile count. if (exr_header->tiled) { { std::vector<int> num_x_tiles, num_y_tiles; PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_header); num_blocks = InitTileOffsets(offset_data, exr_header, num_x_tiles, num_y_tiles); if (exr_header->chunk_count > 0) { if (exr_header->chunk_count != num_blocks) { tinyexr::SetErrorMessage("Invalid offset table size.", err); return TINYEXR_ERROR_INVALID_DATA; } } } int ret = ReadOffsets(offset_data, head, marker, size, err); if (ret != TINYEXR_SUCCESS) return ret; if (IsAnyOffsetsAreInvalid(offset_data)) { ReconstructTileOffsets(offset_data, exr_header, head, marker, size, exr_header->multipart, exr_header->non_image); } } else if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); InitSingleResolutionOffsets(offset_data, num_blocks); } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } InitSingleResolutionOffsets(offset_data, num_blocks); } if (!exr_header->tiled) { std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0]; for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offset_data, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } #if 1 FreeEXRImage(exr_image); #else // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } #endif } return ret; } } static void GetLayers(const EXRHeader &exr_header, std::vector<std::string> &layer_names) { // Naive implementation // Group channels by layers // go over all channel names, split by periods // collect unique names layer_names.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string full_name(exr_header.channels[c].name); const size_t pos = full_name.find_last_of('.'); if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) { full_name.erase(pos); if (std::find(layer_names.begin(), layer_names.end(), full_name) == layer_names.end()) layer_names.push_back(full_name); } } } struct LayerChannel { explicit LayerChannel(size_t i, std::string n) : index(i), name(n) {} size_t index; std::string name; }; static void ChannelsInLayer(const EXRHeader &exr_header, const std::string layer_name, std::vector<LayerChannel> &channels) { channels.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string ch_name(exr_header.channels[c].name); if (layer_name.empty()) { const size_t pos = ch_name.find_last_of('.'); if (pos != std::string::npos && pos < ch_name.size()) { ch_name = ch_name.substr(pos + 1); } } else { const size_t pos = ch_name.find(layer_name + '.'); if (pos == std::string::npos) continue; if (pos == 0) { ch_name = ch_name.substr(layer_name.size() + 1); } } LayerChannel ch(size_t(c), ch_name); channels.push_back(ch); } } } // namespace tinyexr int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err) { EXRVersion exr_version; EXRHeader exr_header; InitEXRHeader(&exr_header); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } std::vector<std::string> layer_vec; tinyexr::GetLayers(exr_header, layer_vec); (*num_layers) = int(layer_vec.size()); (*layer_names) = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size()))); for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) { #ifdef _MSC_VER (*layer_names)[c] = _strdup(layer_vec[c].c_str()); #else (*layer_names)[c] = strdup(layer_vec[c].c_str()); #endif } FreeEXRHeader(&exr_header); return TINYEXR_SUCCESS; } int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { return LoadEXRWithLayer(out_rgba, width, height, filename, /* layername */ NULL, err); } int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layername, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to open EXR file or read version info from EXR file. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } // TODO: Probably limit loading to layers (channels) selected by layer index { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; std::vector<std::string> layer_names; tinyexr::GetLayers(exr_header, layer_names); std::vector<tinyexr::LayerChannel> channels; tinyexr::ChannelsInLayer( exr_header, layername == NULL ? "" : std::string(layername), channels); if (channels.size() < 1) { tinyexr::SetErrorMessage("Layer Not Found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_LAYER_NOT_FOUND; } size_t ch_count = channels.size() < 4 ? channels.size() : 4; for (size_t c = 0; c < ch_count; c++) { const tinyexr::LayerChannel &ch = channels[c]; if (ch.name == "R") { idxR = int(ch.index); } else if (ch.name == "G") { idxG = int(ch.index); } else if (ch.name == "B") { idxB = int(ch.index); } else if (ch.name == "A") { idxA = int(ch.index); } } if (channels.size() == 1) { int chIdx = int(channels.front().index); // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * static_cast<int>(exr_header.tile_size_x) + i; const int jj = exr_image.tiles[it].offset_y * static_cast<int>(exr_header.tile_size_y) + j; const int idx = ii + jj * static_cast<int>(exr_image.width); // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[chIdx][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // Assume RGB(A) if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int IsEXR(const char *filename) { EXRVersion exr_version; int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return ret; } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { tinyexr::SetErrorMessage(err_str, err); } } ConvertHeader(exr_header, info); exr_header->multipart = version->multipart ? 1 : 0; exr_header->non_image = version->non_image ? 1 : 0; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to parse EXR version. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } // TODO(syoyo): Refactor removing same code as used in LoadEXR(). if (exr_header.num_channels == 1) { // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // TODO(syoyo): Support non RGBA image. if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); // TODO(syoyo): return wfopen_s erro code return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } namespace tinyexr { // out_data must be allocated initially with the block-header size // of the current image(-part) type static bool EncodePixelData(/* out */ std::vector<unsigned char>& out_data, const unsigned char* const* images, const int* requested_pixel_types, int compression_type, int line_order, int width, // for tiled : tile.width int height, // for tiled : header.tile_size_y int x_stride, // for tiled : header.tile_size_x int line_no, // for tiled : 0 int num_lines, // for tiled : tile.height size_t pixel_data_size, const std::vector<ChannelInfo>& channels, const std::vector<size_t>& channel_offset_list, const void* compression_param = 0) // zfp compression param { size_t buf_size = static_cast<size_t>(width) * static_cast<size_t>(num_lines) * static_cast<size_t>(pixel_data_size); //int last2bit = (buf_size & 3); // buf_size must be multiple of four //if(last2bit) buf_size += 4 - last2bit; std::vector<unsigned char> buf(buf_size); size_t start_y = static_cast<size_t>(line_no); for (size_t c = 0; c < channels.size(); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<const unsigned short * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(&f32.f); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { unsigned short val = reinterpret_cast<const unsigned short * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<const float * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { float val = reinterpret_cast<const float * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { unsigned int val = reinterpret_cast<const unsigned int * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) out_data.insert(out_data.end(), buf.begin(), buf.end()); } else if ((compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = static_cast<unsigned int>(outSize); // truncate out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = static_cast<unsigned int>(outSize); // truncate out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 8192 + static_cast<unsigned int>( 2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, width, num_lines); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = outSize; out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP const ZFPCompressionParam* zfp_compression_param = reinterpret_cast<const ZFPCompressionParam*>(compression_param); std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), width, num_lines, static_cast<int>(channels.size()), *zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = outSize; out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); return false; } return true; } static int EncodeTiledLevel(const EXRImage* level_image, const EXRHeader* exr_header, const std::vector<tinyexr::ChannelInfo>& channels, std::vector<std::vector<unsigned char> >& data_list, size_t start_index, // for data_list int num_x_tiles, int num_y_tiles, const std::vector<size_t>& channel_offset_list, int pixel_data_size, const void* compression_param, // must be set if zfp compression is enabled std::string* err) { int num_tiles = num_x_tiles * num_y_tiles; assert(num_tiles == level_image->num_tiles); if ((exr_header->tile_size_x > level_image->width || exr_header->tile_size_y > level_image->height) && level_image->level_x == 0 && level_image->level_y == 0) { if (err) { (*err) += "Failed to encode tile data.\n"; } return TINYEXR_ERROR_INVALID_DATA; } #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<bool> invalid_data(false); #else bool invalid_data(false); #endif #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> tile_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_tiles)) { num_threads = int(num_tiles); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int i = 0; while ((i = tile_count++) < num_tiles) { #else // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_tiles; i++) { #endif size_t tile_idx = static_cast<size_t>(i); size_t data_idx = tile_idx + start_index; int x_tile = i % num_x_tiles; int y_tile = i / num_x_tiles; EXRTile& tile = level_image->tiles[tile_idx]; const unsigned char* const* images = static_cast<const unsigned char* const*>(tile.images); data_list[data_idx].resize(5*sizeof(int)); size_t data_header_size = data_list[data_idx].size(); bool ret = EncodePixelData(data_list[data_idx], images, exr_header->requested_pixel_types, exr_header->compression_type, 0, // increasing y tile.width, exr_header->tile_size_y, exr_header->tile_size_x, 0, tile.height, pixel_data_size, channels, channel_offset_list, compression_param); if (!ret) { invalid_data = true; continue; } assert(data_list[data_idx].size() > data_header_size); int data_len = static_cast<int>(data_list[data_idx].size() - data_header_size); //tileX, tileY, levelX, levelY // pixel_data_size(int) memcpy(&data_list[data_idx][0], &x_tile, sizeof(int)); memcpy(&data_list[data_idx][4], &y_tile, sizeof(int)); memcpy(&data_list[data_idx][8], &level_image->level_x, sizeof(int)); memcpy(&data_list[data_idx][12], &level_image->level_y, sizeof(int)); memcpy(&data_list[data_idx][16], &data_len, sizeof(int)); swap4(reinterpret_cast<int*>(&data_list[data_idx][0])); swap4(reinterpret_cast<int*>(&data_list[data_idx][4])); swap4(reinterpret_cast<int*>(&data_list[data_idx][8])); swap4(reinterpret_cast<int*>(&data_list[data_idx][12])); swap4(reinterpret_cast<int*>(&data_list[data_idx][16])); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif if (invalid_data) { if (err) { (*err) += "Failed to encode tile data.\n"; } return TINYEXR_ERROR_INVALID_DATA; } return TINYEXR_SUCCESS; } static int NumScanlines(int compression_type) { int num_scanlines = 1; if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } return num_scanlines; } static int EncodeChunk(const EXRImage* exr_image, const EXRHeader* exr_header, const std::vector<ChannelInfo>& channels, int num_blocks, tinyexr_uint64 chunk_offset, // starting offset of current chunk bool is_multipart, OffsetData& offset_data, // output block offsets, must be initialized std::vector<std::vector<unsigned char> >& data_list, // output tinyexr_uint64& total_size, // output: ending offset of current chunk std::string* err) { int num_scanlines = NumScanlines(exr_header->compression_type); data_list.resize(num_blocks); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; { size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } } const void* compression_param = 0; #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { std::string e; bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes, &e); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } compression_param = &zfp_compression_param; } #endif tinyexr_uint64 offset = chunk_offset; tinyexr_uint64 doffset = is_multipart ? 4u : 0u; if (exr_image->tiles) { const EXRImage* level_image = exr_image; size_t block_idx = 0; tinyexr::tinyexr_uint64 block_data_size = 0; int num_levels = (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ? offset_data.num_x_levels : (offset_data.num_x_levels * offset_data.num_y_levels); for (int level_index = 0; level_index < num_levels; ++level_index) { if (!level_image) { if (err) { (*err) += "Invalid number of tiled levels for EncodeChunk\n"; } return TINYEXR_ERROR_INVALID_DATA; } int level_index_from_image = LevelIndex(level_image->level_x, level_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels); if (level_index_from_image != level_index) { if (err) { (*err) += "Incorrect level ordering in tiled image\n"; } return TINYEXR_ERROR_INVALID_DATA; } int num_y_tiles = (int)offset_data.offsets[level_index].size(); assert(num_y_tiles); int num_x_tiles = (int)offset_data.offsets[level_index][0].size(); assert(num_x_tiles); std::string e; int ret = EncodeTiledLevel(level_image, exr_header, channels, data_list, block_idx, num_x_tiles, num_y_tiles, channel_offset_list, pixel_data_size, compression_param, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty() && err) { (*err) += e; } return ret; } for (size_t j = 0; j < static_cast<size_t>(num_y_tiles); ++j) for (size_t i = 0; i < static_cast<size_t>(num_x_tiles); ++i) { offset_data.offsets[level_index][j][i] = offset; swap8(reinterpret_cast<tinyexr_uint64*>(&offset_data.offsets[level_index][j][i])); offset += data_list[block_idx].size() + doffset; block_data_size += data_list[block_idx].size(); ++block_idx; } level_image = level_image->next_level; } assert(block_idx == num_blocks); total_size = offset; } else { // scanlines std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0]; #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<bool> invalid_data(false); std::vector<std::thread> workers; std::atomic<int> block_count(0); int num_threads = std::min(std::max(1, int(std::thread::hardware_concurrency())), num_blocks); for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int i = 0; while ((i = block_count++) < num_blocks) { #else bool invalid_data(false); #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { #endif int start_y = num_scanlines * i; int end_Y = (std::min)(num_scanlines * (i + 1), exr_image->height); int num_lines = end_Y - start_y; const unsigned char* const* images = static_cast<const unsigned char* const*>(exr_image->images); data_list[i].resize(2*sizeof(int)); size_t data_header_size = data_list[i].size(); bool ret = EncodePixelData(data_list[i], images, exr_header->requested_pixel_types, exr_header->compression_type, 0, // increasing y exr_image->width, exr_image->height, exr_image->width, start_y, num_lines, pixel_data_size, channels, channel_offset_list, compression_param); if (!ret) { invalid_data = true; continue; // "break" cannot be used with OpenMP } assert(data_list[i].size() > data_header_size); int data_len = static_cast<int>(data_list[i].size() - data_header_size); memcpy(&data_list[i][0], &start_y, sizeof(int)); memcpy(&data_list[i][4], &data_len, sizeof(int)); swap4(reinterpret_cast<int*>(&data_list[i][0])); swap4(reinterpret_cast<int*>(&data_list[i][4])); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif if (invalid_data) { if (err) { (*err) += "Failed to encode scanline data.\n"; } return TINYEXR_ERROR_INVALID_DATA; } for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size() + doffset; } total_size = static_cast<size_t>(offset); } return TINYEXR_SUCCESS; } // can save a single or multi-part image (no deep* formats) static size_t SaveEXRNPartImageToMemory(const EXRImage* exr_images, const EXRHeader** exr_headers, unsigned int num_parts, unsigned char** memory_out, const char** err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory_out == NULL) { SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory", err); return 0; } { for (unsigned int i = 0; i < num_parts; ++i) { if (exr_headers[i]->compression_type < 0) { SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { SetErrorMessage("ZFP compression is not supported in this build", err); return 0; } #else for (int c = 0; c < exr_header->num_channels; ++c) { if (exr_headers[i]->requested_pixel_types[c] != TINYEXR_PIXELTYPE_FLOAT) { SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); return 0; } } #endif } } std::vector<unsigned char> memory; // Header { const char header[] = { 0x76, 0x2f, 0x31, 0x01 }; memory.insert(memory.end(), header, header + 4); } // Version // using value from the first header int long_name = exr_headers[0]->long_name; { char marker[] = { 2, 0, 0, 0 }; /* @todo if (exr_header->non_image) { marker[1] |= 0x8; } */ // tiled if (num_parts == 1 && exr_images[0].tiles) { marker[1] |= 0x2; } // long_name if (long_name) { marker[1] |= 0x4; } // multipart if (num_parts > 1) { marker[1] |= 0x10; } memory.insert(memory.end(), marker, marker + 4); } int total_chunk_count = 0; std::vector<int> chunk_count(num_parts); std::vector<OffsetData> offset_data(num_parts); for (unsigned int i = 0; i < num_parts; ++i) { if (!exr_images[i].tiles) { int num_scanlines = NumScanlines(exr_headers[i]->compression_type); chunk_count[i] = (exr_images[i].height + num_scanlines - 1) / num_scanlines; InitSingleResolutionOffsets(offset_data[i], chunk_count[i]); total_chunk_count += chunk_count[i]; } else { { std::vector<int> num_x_tiles, num_y_tiles; PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]); chunk_count[i] = InitTileOffsets(offset_data[i], exr_headers[i], num_x_tiles, num_y_tiles); total_chunk_count += chunk_count[i]; } } } // Write attributes to memory buffer. std::vector< std::vector<tinyexr::ChannelInfo> > channels(num_parts); { std::set<std::string> partnames; for (unsigned int i = 0; i < num_parts; ++i) { //channels { std::vector<unsigned char> data; for (int c = 0; c < exr_headers[i]->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_headers[i]->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_headers[i]->channels[c].name); channels[i].push_back(info); } tinyexr::WriteChannelInfo(data, channels[i]); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_headers[i]->compression_type; swap4(&comp); WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char*>(&comp), 1); } { int data[4] = { 0, 0, exr_images[i].width - 1, exr_images[i].height - 1 }; swap4(&data[0]); swap4(&data[1]); swap4(&data[2]); swap4(&data[3]); WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char*>(data), sizeof(int) * 4); int data0[4] = { 0, 0, exr_images[0].width - 1, exr_images[0].height - 1 }; swap4(&data0[0]); swap4(&data0[1]); swap4(&data0[2]); swap4(&data0[3]); // Note: must be the same across parts (currently, using value from the first header) WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char*>(data0), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { // Note: must be the same across parts float aspectRatio = 1.0f; swap4(&aspectRatio); WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char*>(&aspectRatio), sizeof(float)); } { float center[2] = { 0.0f, 0.0f }; swap4(&center[0]); swap4(&center[1]); WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char*>(center), 2 * sizeof(float)); } { float w = 1.0f; swap4(&w); WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char*>(&w), sizeof(float)); } if (exr_images[i].tiles) { unsigned char tile_mode = static_cast<unsigned char>(exr_headers[i]->tile_level_mode & 0x3); if (exr_headers[i]->tile_rounding_mode) tile_mode |= (1u << 4u); //unsigned char data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; unsigned int datai[3] = { 0, 0, 0 }; unsigned char* data = reinterpret_cast<unsigned char*>(&datai[0]); datai[0] = static_cast<unsigned int>(exr_headers[i]->tile_size_x); datai[1] = static_cast<unsigned int>(exr_headers[i]->tile_size_y); data[8] = tile_mode; swap4(reinterpret_cast<unsigned int*>(&data[0])); swap4(reinterpret_cast<unsigned int*>(&data[4])); WriteAttributeToMemory( &memory, "tiles", "tiledesc", reinterpret_cast<const unsigned char*>(data), 9); } // must be present for multi-part files - according to spec. if (num_parts > 1) { // name { size_t len = 0; if ((len = strlen(exr_headers[i]->name)) > 0) { partnames.insert(std::string(exr_headers[i]->name)); if (partnames.size() != i + 1) { SetErrorMessage("'name' attributes must be unique for a multi-part file", err); return 0; } WriteAttributeToMemory( &memory, "name", "string", reinterpret_cast<const unsigned char*>(exr_headers[i]->name), static_cast<int>(len)); } else { SetErrorMessage("Invalid 'name' attribute for a multi-part file", err); return 0; } } // type { const char* type = "scanlineimage"; if (exr_images[i].tiles) type = "tiledimage"; WriteAttributeToMemory( &memory, "type", "string", reinterpret_cast<const unsigned char*>(type), static_cast<int>(strlen(type))); } // chunkCount { WriteAttributeToMemory( &memory, "chunkCount", "int", reinterpret_cast<const unsigned char*>(&chunk_count[i]), 4); } } // Custom attributes if (exr_headers[i]->num_custom_attributes > 0) { for (int j = 0; j < exr_headers[i]->num_custom_attributes; j++) { tinyexr::WriteAttributeToMemory( &memory, exr_headers[i]->custom_attributes[j].name, exr_headers[i]->custom_attributes[j].type, reinterpret_cast<const unsigned char*>( exr_headers[i]->custom_attributes[j].value), exr_headers[i]->custom_attributes[j].size); } } { // end of header memory.push_back(0); } } } if (num_parts > 1) { // end of header list memory.push_back(0); } tinyexr_uint64 chunk_offset = memory.size() + size_t(total_chunk_count) * sizeof(tinyexr_uint64); tinyexr_uint64 total_size = 0; std::vector< std::vector< std::vector<unsigned char> > > data_lists(num_parts); for (unsigned int i = 0; i < num_parts; ++i) { std::string e; int ret = EncodeChunk(&exr_images[i], exr_headers[i], channels[i], chunk_count[i], // starting offset of current chunk after part-number chunk_offset, num_parts > 1, offset_data[i], // output: block offsets, must be initialized data_lists[i], // output total_size, // output &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return 0; } chunk_offset = total_size; } // Allocating required memory if (total_size == 0) { // something went wrong tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char*>(malloc(total_size)); // Writing header memcpy((*memory_out), &memory[0], memory.size()); unsigned char* memory_ptr = *memory_out + memory.size(); size_t sum = memory.size(); // Writing offset data for chunks for (unsigned int i = 0; i < num_parts; ++i) { if (exr_images[i].tiles) { const EXRImage* level_image = &exr_images[i]; int num_levels = (exr_headers[i]->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ? offset_data[i].num_x_levels : (offset_data[i].num_x_levels * offset_data[i].num_y_levels); for (int level_index = 0; level_index < num_levels; ++level_index) { for (size_t j = 0; j < offset_data[i].offsets[level_index].size(); ++j) { size_t num_bytes = sizeof(tinyexr_uint64) * offset_data[i].offsets[level_index][j].size(); sum += num_bytes; assert(sum <= total_size); memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offset_data[i].offsets[level_index][j][0]), num_bytes); memory_ptr += num_bytes; } level_image = level_image->next_level; } } else { size_t num_bytes = sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(chunk_count[i]); sum += num_bytes; assert(sum <= total_size); std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data[i].offsets[0][0]; memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offsets[0]), num_bytes); memory_ptr += num_bytes; } } // Writing chunk data for (unsigned int i = 0; i < num_parts; ++i) { for (size_t j = 0; j < static_cast<size_t>(chunk_count[i]); ++j) { if (num_parts > 1) { sum += 4; assert(sum <= total_size); unsigned int part_number = i; swap4(&part_number); memcpy(memory_ptr, &part_number, 4); memory_ptr += 4; } sum += data_lists[i][j].size(); assert(sum <= total_size); memcpy(memory_ptr, &data_lists[i][j][0], data_lists[i][j].size()); memory_ptr += data_lists[i][j].size(); } } assert(sum == total_size); return total_size; // OK } } // tinyexr size_t SaveEXRImageToMemory(const EXRImage* exr_image, const EXRHeader* exr_header, unsigned char** memory_out, const char** err) { return tinyexr::SaveEXRNPartImageToMemory(exr_image, &exr_header, 1, memory_out, err); } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } #else // Unknown compiler fp = fopen(filename, "wb"); #endif #else fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } size_t SaveEXRMultipartImageToMemory(const EXRImage* exr_images, const EXRHeader** exr_headers, unsigned int num_parts, unsigned char** memory_out, const char** err) { if (exr_images == NULL || exr_headers == NULL || num_parts < 2 || memory_out == NULL) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory", err); return 0; } return tinyexr::SaveEXRNPartImageToMemory(exr_images, exr_headers, num_parts, memory_out, err); } int SaveEXRMultipartImageToFile(const EXRImage* exr_images, const EXRHeader** exr_headers, unsigned int num_parts, const char* filename, const char** err) { if (exr_images == NULL || exr_headers == NULL || num_parts < 2) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRMultipartImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } #else // Unknown compiler fp = fopen(filename, "wb"); #endif #else fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRMultipartImageToMemory(exr_images, exr_headers, num_parts, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { tinyexr::SetErrorMessage("Invalid magic number", err); return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { std::stringstream ss; ss << "Failed to parse attribute\n"; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(&dx); tinyexr::swap4(&dy); tinyexr::swap4(&dw); tinyexr::swap4(&dh); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(&x); tinyexr::swap4(&y); tinyexr::swap4(&w); tinyexr::swap4(&h); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { tinyexr::SetErrorMessage("Unsupported compression format", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(&line_no); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->next_level = NULL; exr_image->level_x = 0; exr_image->level_y = 0; exr_image->num_tiles = 0; } void FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } EXRSetNameAttr(exr_header, NULL); return TINYEXR_SUCCESS; } void EXRSetNameAttr(EXRHeader* exr_header, const char* name) { if (exr_header == NULL) { return; } memset(exr_header->name, 0, 256); if (name != NULL) { size_t len = std::min(strlen(name), (size_t)255); if (len) { memcpy(exr_header->name, name, len); } } } int EXRNumLevels(const EXRImage* exr_image) { if (exr_image == NULL) return 0; if(exr_image->images) return 1; // scanlines int levels = 1; const EXRImage* level_image = exr_image; while((level_image = level_image->next_level)) ++levels; return levels; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_image->next_level) { FreeEXRImage(exr_image->next_level); delete exr_image->next_level; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } free(exr_image->tiles); } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); memset(exr_header, 0, sizeof(EXRHeader)); ConvertHeader(exr_header, infos[i]); exr_header->multipart = exr_version->multipart ? 1 : 0; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t err = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (err != 0) { // TODO(syoyo): return wfopen_s erro code return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<tinyexr::OffsetData> chunk_offset_table_list; chunk_offset_table_list.reserve(num_parts); for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { chunk_offset_table_list.resize(chunk_offset_table_list.size() + 1); tinyexr::OffsetData& offset_data = chunk_offset_table_list.back(); if (!exr_headers[i]->tiled || exr_headers[i]->tile_level_mode == TINYEXR_TILE_ONE_LEVEL) { tinyexr::InitSingleResolutionOffsets(offset_data, exr_headers[i]->chunk_count); std::vector<tinyexr::tinyexr_uint64>& offset_table = offset_data.offsets[0][0]; for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } } else { { std::vector<int> num_x_tiles, num_y_tiles; tinyexr::PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]); int num_blocks = InitTileOffsets(offset_data, exr_headers[i], num_x_tiles, num_y_tiles); if (num_blocks != exr_headers[i]->chunk_count) { tinyexr::SetErrorMessage("Invalid offset table size.", err); return TINYEXR_ERROR_INVALID_DATA; } } for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_data.offsets[l][dy][dx] = offset + 4; // +4 to skip 'part number' marker += sizeof(tinyexr::tinyexr_uint64); // = 8 } } } } } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { tinyexr::OffsetData &offset_data = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { const unsigned char *part_number_addr = memory + offset_data.offsets[l][dy][dx] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_data, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } int ret = SaveEXRImageToFile(&image, &header, outfilename, err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEFINED #endif // TINYEXR_IMPLEMENTATION