double minimumOnObjectVolume(const BallType &b, const BoxType &r) { ++calls; return SQR(std::max(0., r.exteriorDistance(b.center) - b.radius)); }
void radiosity_set(Real e, int iter, int vis) { if (iter < 0 || e < 0) error("(radiosity) invalid parameters"); dm_eps = SQR(3*e); max_iter = iter; vis_flag = vis; }
static GCA_SAMPLE * find_control_points(GCA *gca, GCA_SAMPLE *gcas_total, int total_samples, int *pnorm_samples, int nregions, int label, MRI *mri_in, TRANSFORM *transform, double min_prior, double ctl_point_pct) { int i, j, *ordered_indices, nsamples, xmin, ymin, zmin, xmax, ymax, zmax, xv,yv,zv, x, y, z, xi, yi, zi, region_samples, used_in_region, prior_wsize=5, image_wsize=3, histo_peak, n, nbins ; GCA_SAMPLE *gcas, *gcas_region, *gcas_norm ; double means[MAX_GCA_INPUTS], vars[MAX_GCA_INPUTS], val, nsigma ; HISTOGRAM *histo, *hsmooth ; GC1D *gc ; float fmin, fmax ; MRI *mri_T1 = NULL ; if (label == Gdiag_no) DiagBreak() ; MRIvalRange(mri_in, &fmin, &fmax) ; nbins = (int)(fmax-fmin+1); histo = HISTOalloc(nbins) ; hsmooth = HISTOalloc(nbins) ; for (nsamples = i = 0 ; i < total_samples ; i++) { if (gcas_total[i].label != label) continue ; nsamples++ ; } *pnorm_samples = 0 ; printf("found %d control points for structure...\n", nsamples) ; if (nsamples == 0) { DiagBreak() ; return(NO_ERROR) ; } gcas = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ; gcas_region = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ; gcas_norm = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ; if (!gcas || !gcas_region || !gcas_norm) ErrorExit (ERROR_NOMEMORY, "find_control_points: could not allocate %d samples\n",nsamples); for (j = i = 0 ; i < total_samples ; i++) { if (gcas_total[i].label != label) continue ; memmove(&gcas[j], &gcas_total[i], sizeof(GCA_SAMPLE)) ; j++ ; } ordered_indices = (int *)calloc(nsamples, sizeof(int)) ; gcas_bounding_box(gcas, nsamples, &xmin, &ymin, &zmin, &xmax, &ymax, &zmax, label) ; printf("bounding box (%d, %d, %d) --> (%d, %d, %d)\n", xmin, ymin, zmin, xmax, ymax, zmax) ; for (x = 0 ; x < nregions ; x++) { for (y = 0 ; y < nregions ; y++) { for (z = 0 ; z < nregions ; z++) { /* only process samples in this region */ nsigma = 1.0 ; do { for (region_samples = i = 0 ; i < nsamples ; i++) { xi = (int)(nregions*(gcas[i].x - xmin) / (xmax-xmin+1)) ; yi = (int)(nregions*(gcas[i].y - ymin) / (ymax-ymin+1)) ; zi = (int)(nregions*(gcas[i].z - zmin) / (zmax-zmin+1)) ; if ((xi < 0 || xi >= nregions) || (yi < 0 || yi >= nregions) || (zi < 0 || zi >= nregions)) DiagBreak() ; xv = gcas[i].x ; yv = gcas[i].y ; zv = gcas[i].z ; if (xi != x || yi != y || zi != z || gcas[i].prior < min_prior) continue ; if (xv == Gx && yv == Gy && zv == Gz) DiagBreak() ; if (sqrt(SQR(xv-Gx)+SQR(yv-Gy)+SQR(zv-Gz)) < 2) DiagBreak() ; if (min_region_prior(gca, gcas[i].xp, gcas[i].yp, gcas[i].zp,prior_wsize, label) < min_prior) continue ; if (uniform_region(gca, mri_in, transform, xv, yv, zv, image_wsize, &gcas[i], nsigma) == 0) continue ; memmove(&gcas_region[region_samples], &gcas[i], sizeof(GCA_SAMPLE)) ; region_samples++ ; if (gcas[i].x == Gx && gcas[i].y == Gy && gcas[i].z == Gz) DiagBreak() ; } nsigma *= 1.1 ; } while (region_samples < 8 && nsigma < 3) ; if (region_samples < 8)/* can't reliably estimate statistics */ continue ; if (DIAG_VERBOSE_ON) printf("\t%d total samples found in region (%d, %d, %d)\n", region_samples,x, y,z) ; /* compute mean and variance of label within this region */ for (n = 0 ; n < mri_in->nframes ; n++) { HISTOclear(histo, histo) ; histo->bin_size = 1 ; for (means[n] = vars[n] = 0.0, i = 0 ; i < region_samples ; i++) { MRIsampleVolumeFrame (mri_in, gcas_region[i].x,gcas_region[i].y,gcas_region[i].z, n, &val) ; if (FZERO(val)) { if (i < (region_samples-1)) memmove(&gcas_region[i], &gcas_region[i+1], (region_samples-(i+1))*sizeof(GCA_SAMPLE)); i-- ; region_samples-- ; continue ; } histo->counts[(int)val]++ ; means[n] += val ; vars[n] += (val*val) ; } HISTOsmooth(histo, hsmooth, 2) ; histo_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins) ; if (histo_peak < 0) /* couldn't find a valid peak? */ break ; for (means[n] = vars[n] = 0.0, i = 0 ; i < region_samples ; i++) { if (gcas_region[i].label < 0) continue ; MRIsampleVolumeFrame (mri_in, gcas_region[i].x, gcas_region[i].y, gcas_region[i].z, n, &val) ; means[n] += val ; vars[n] += (val*val) ; } means[n] /= (double)region_samples ; vars[n] = vars[n] / (double)region_samples - means[n]*means[n] ; means[n] = histo_peak ; if (DIAG_VERBOSE_ON) printf("\tlabel %s[%d]: %2.1f +- %2.1f\n", cma_label_to_name(label), n, means[n], sqrt(vars[n])) ; } /* ignore GCA mean and variance - use image instead (otherwise bias field will mess us up) */ for (i = 0 ; i < region_samples ; i++) { int r ; for (r = 0 ; r < gca->ninputs ; r++) gcas_region[i].means[r] = means[r] ; /* gcas_region[i].var = var ;*/ } GCAcomputeLogSampleProbability (gca, gcas_region, mri_in, transform, region_samples) ; GCArankSamples (gca, gcas_region, region_samples, ordered_indices) ; GCAremoveOutlyingSamples (gca, gcas_region, mri_in, transform, region_samples, 2.0) ; for (used_in_region = i = 0 ; i < region_samples ; i++) { j = ordered_indices[i] ; if (gcas_region[j].label != label) /* it was an outlier */ continue ; memmove (&gcas_norm[*pnorm_samples], &gcas_region[j], sizeof(GCA_SAMPLE)) ; (*pnorm_samples)++ ; used_in_region++ ; } if ((used_in_region <= 0) && region_samples>0) { j = ordered_indices[0] ; /* gcas_region[j].label = label ;*/ printf("forcing use of sample %d @ (%d, %d, %d)\n", j, gcas_region[j].x, gcas_region[j].y, gcas_region[j].z) ; memmove(&gcas_norm[*pnorm_samples], &gcas_region[j], sizeof(GCA_SAMPLE)) ; (*pnorm_samples)++ ; used_in_region++ ; } if (DIAG_VERBOSE_ON) printf("\t%d samples used in region\n", used_in_region) ; } } } /* put gca means back into samples */ for (i = 0 ; i < *pnorm_samples ; i++) { gc = GCAfindPriorGC(gca, gcas_norm[i].xp, gcas_norm[i].yp, gcas_norm[i].zp, gcas_norm[i].label) ; if (gc) { int r, c, v ; for (v = r = 0 ; r < gca->ninputs ; r++) { for (c = r ; c < gca->ninputs ; c++, v++) { gcas_norm[i].means[v] = gc->means[v] ; gcas_norm[i].covars[v] = gc->covars[v] ; } } } } HISTOfree(&histo) ; HISTOfree(&hsmooth) ; free(gcas_region) ; free(gcas) ; if (mri_T1) MRIfree(&mri_T1) ; return(gcas_norm) ; }
/* Do modular exponentiation using integer multiply code. */ mp_err mp_exptmod_safe_i(const mp_int *montBase, const mp_int *exponent, const mp_int *modulus, mp_int *result, mp_mont_modulus *mmm, int nLen, mp_size bits_in_exponent, mp_size window_bits, mp_size num_powers) { mp_int *pa1, *pa2, *ptmp; mp_size i; mp_size first_window; mp_err res; int expOff; mp_int accum1, accum2, accum[WEAVE_WORD_SIZE]; mp_int tmp; mp_digit *powersArray = NULL; mp_digit *powers = NULL; MP_DIGITS(&accum1) = 0; MP_DIGITS(&accum2) = 0; MP_DIGITS(&accum[0]) = 0; MP_DIGITS(&accum[1]) = 0; MP_DIGITS(&accum[2]) = 0; MP_DIGITS(&accum[3]) = 0; MP_DIGITS(&tmp) = 0; /* grab the first window value. This allows us to preload accumulator1 * and save a conversion, some squares and a multiple*/ MP_CHECKOK(mpl_get_bits(exponent, bits_in_exponent - window_bits, window_bits)); first_window = (mp_size)res; MP_CHECKOK(mp_init_size(&accum1, 3 * nLen + 2)); MP_CHECKOK(mp_init_size(&accum2, 3 * nLen + 2)); /* build the first WEAVE_WORD powers inline */ /* if WEAVE_WORD_SIZE is not 4, this code will have to change */ if (num_powers > 2) { MP_CHECKOK(mp_init_size(&accum[0], 3 * nLen + 2)); MP_CHECKOK(mp_init_size(&accum[1], 3 * nLen + 2)); MP_CHECKOK(mp_init_size(&accum[2], 3 * nLen + 2)); MP_CHECKOK(mp_init_size(&accum[3], 3 * nLen + 2)); mp_set(&accum[0], 1); MP_CHECKOK(s_mp_to_mont(&accum[0], mmm, &accum[0])); MP_CHECKOK(mp_copy(montBase, &accum[1])); SQR(montBase, &accum[2]); MUL_NOWEAVE(montBase, &accum[2], &accum[3]); powersArray = (mp_digit *)malloc(num_powers * (nLen * sizeof(mp_digit) + 1)); if (!powersArray) { res = MP_MEM; goto CLEANUP; } /* powers[i] = base ** (i); */ powers = (mp_digit *)MP_ALIGN(powersArray, num_powers); MP_CHECKOK(mpi_to_weave(accum, powers, nLen, num_powers)); if (first_window < 4) { MP_CHECKOK(mp_copy(&accum[first_window], &accum1)); first_window = num_powers; } } else { if (first_window == 0) { mp_set(&accum1, 1); MP_CHECKOK(s_mp_to_mont(&accum1, mmm, &accum1)); } else { /* assert first_window == 1? */ MP_CHECKOK(mp_copy(montBase, &accum1)); } } /* * calculate all the powers in the powers array. * this adds 2**(k-1)-2 square operations over just calculating the * odd powers where k is the window size in the two other mp_modexpt * implementations in this file. We will get some of that * back by not needing the first 'k' squares and one multiply for the * first window. * Given the value of 4 for WEAVE_WORD_SIZE, this loop will only execute if * num_powers > 2, in which case powers will have been allocated. */ for (i = WEAVE_WORD_SIZE; i < num_powers; i++) { int acc_index = i & (WEAVE_WORD_SIZE - 1); /* i % WEAVE_WORD_SIZE */ if (i & 1) { MUL_NOWEAVE(montBase, &accum[acc_index - 1], &accum[acc_index]); /* we've filled the array do our 'per array' processing */ if (acc_index == (WEAVE_WORD_SIZE - 1)) { MP_CHECKOK(mpi_to_weave(accum, powers + i - (WEAVE_WORD_SIZE - 1), nLen, num_powers)); if (first_window <= i) { MP_CHECKOK(mp_copy(&accum[first_window & (WEAVE_WORD_SIZE - 1)], &accum1)); first_window = num_powers; } } } else { /* up to 8 we can find 2^i-1 in the accum array, but at 8 we our source * and target are the same so we need to copy.. After that, the * value is overwritten, so we need to fetch it from the stored * weave array */ if (i > 2 * WEAVE_WORD_SIZE) { MP_CHECKOK(weave_to_mpi(&accum2, powers, i / 2, nLen, num_powers)); SQR(&accum2, &accum[acc_index]); } else { int half_power_index = (i / 2) & (WEAVE_WORD_SIZE - 1); if (half_power_index == acc_index) { /* copy is cheaper than weave_to_mpi */ MP_CHECKOK(mp_copy(&accum[half_power_index], &accum2)); SQR(&accum2, &accum[acc_index]); } else { SQR(&accum[half_power_index], &accum[acc_index]); } } } } /* if the accum1 isn't set, Then there is something wrong with our logic * above and is an internal programming error. */ #if MP_ARGCHK == 2 assert(MP_USED(&accum1) != 0); #endif /* set accumulator to montgomery residue of 1 */ pa1 = &accum1; pa2 = &accum2; /* tmp is not used if window_bits == 1. */ if (window_bits != 1) { MP_CHECKOK(mp_init_size(&tmp, 3 * nLen + 2)); } for (expOff = bits_in_exponent - window_bits * 2; expOff >= 0; expOff -= window_bits) { mp_size smallExp; MP_CHECKOK(mpl_get_bits(exponent, expOff, window_bits)); smallExp = (mp_size)res; /* handle unroll the loops */ switch (window_bits) { case 1: if (!smallExp) { SQR(pa1, pa2); SWAPPA; } else if (smallExp & 1) { SQR(pa1, pa2); MUL_NOWEAVE(montBase, pa2, pa1); } else { abort(); } break; case 6: SQR(pa1, pa2); SQR(pa2, pa1); /* fall through */ case 4: SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp, pa1, pa2); SWAPPA; break; case 5: SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); MUL(smallExp, pa2, pa1); break; default: abort(); /* could do a loop? */ } } res = s_mp_redc(pa1, mmm); mp_exch(pa1, result); CLEANUP: mp_clear(&accum1); mp_clear(&accum2); mp_clear(&accum[0]); mp_clear(&accum[1]); mp_clear(&accum[2]); mp_clear(&accum[3]); mp_clear(&tmp); /* PORT_Memset(powers,0,num_powers*nLen*sizeof(mp_digit)); */ free(powersArray); return res; }
void DrImage::LennardJones(){ //---------------------alloc---------------------- int NStill = 50; int NStep = (int)(25.*60.*.2) - NStill; int NRow = 20; int NCol = 20; double NPRow = 1.;//(double)NRow; double NPCol = 1.;//(double)NCol; double NStepPRow = NRow/(double)NStep; double NStepPCol = NCol/(double)NStep; double Eps = 0.1; double Sigma = 3.0; double Dt = 2.;//.1; double InvNStep = 1./(double)NStep; double InvWid = 1./(double)NWidth; double InvHei = 1./(double)NHeight; double InvRow = 1./(double)NRow; double InvCol = 1./(double)NCol; //int HeiSize = (int)(NHeight*InvRow); //int WidSize = (int)(NWidth*InvCol); double **data2 = (double **)calloc(3,sizeof(double)); for(int l=0;l<3;l++){ data2[l] = (double *)calloc(NHeight*NWidth,sizeof(double)); } double *PPos = (double *)calloc(2*NRow*NCol,sizeof(double)); int *PBound = (int *)calloc(4*NRow*NCol,sizeof(int)); double *PVel = (double *)calloc(2*NRow*NCol,sizeof(double)); double *PFor = (double *)calloc(2*NRow*NCol,sizeof(double)); double Edge[2] = {NWidth,NHeight}; double InvEdge[2] = {1./(double)NWidth,1./(double)NHeight}; Matematica *Mate = new Matematica(); PERMUTE *Perm = (PERMUTE *)calloc(NRow*NCol,sizeof(PERMUTE)); //-------------------------initializing----------------------- for(int l=0;l<3;l++){ for(int h=0;h<NHeight;h++){ for(int w=0;w<NWidth;w++){ data2[l][h*NWidth+w] = data[l][h*NWidth+w]; } } } for(int r=0;r<NRow;r++){ for(int c=0;c<NCol;c++){ double x = (c)*InvCol*NWidth; double y = (r)*InvRow*NHeight; int p1 = (r*NCol+c)*2; PPos[p1 ] = x; PPos[p1+1] = y; PVel[p1 ] = (2.*Mate->Casuale()-1.); PVel[p1+1] = (2.*Mate->Casuale()-1.); PBound[(r*NCol+c)*4 ] = (int)(c*InvCol*NWidth); PBound[(r*NCol+c)*4+1] = (int)((c+1)*InvCol*NWidth); PBound[(r*NCol+c)*4+2] = (int)(r*InvRow*NHeight); PBound[(r*NCol+c)*4+3] = (int)((r+1)*InvRow*NHeight); Perm[r*NCol+c].n = r*NCol+c; Perm[r*NCol+c].m = r*NCol+c; } } //squares of different sizes if(1==1){ for(int c=0;c<NCol-1;c++){ int NBorder = (int)((2.*Mate->Casuale()-1.)*10.); for(int r=0;r<NRow;r++){ int p1 = (r*NCol+c)*4; int p2 = (r*NCol+(c+1))*4; PBound[p1+1] += NBorder; PBound[p2 ] += NBorder; } } for(int r=0;r<NRow-1;r++){ int NBorder = (int)((2.*Mate->Casuale()-1.)*10.); for(int c=0;c<NCol;c++){ int p1 = (r*NCol+c)*4; int p2 = ((r+1)*NCol+c)*4; PBound[p1+3] += NBorder; PBound[p2+2] += NBorder; } } for(int r=0;r<NRow;r++){ for(int c=0;c<NCol;c++){ int p1 = (r*NCol+c)*4; double x = PBound[p1 ]; double y = PBound[p1+2]; int p2 = (r*NCol+c)*2; PPos[p2 ] = x; PPos[p2+1] = y; PPos[p2 ] -= floor(PPos[p2 ]*InvEdge[0])*Edge[0]; PPos[p2+1] -= floor(PPos[p2+1]*InvEdge[1])*Edge[1]; } } } // for(int c=0;c<NCol;c++){ // int p1 = (0*NCol+c)*4; // printf("x %d) %d %d %d\n",c,PBound[p1],PBound[p1+1],PBound[p1+1]-PBound[p1],NWidth); // } // for(int r=0;r<NRow;r++){ // int p1 = (r*NCol+0)*4; // printf("y %d) %d %d %d\n",r,PBound[p1+2],PBound[p1+3],PBound[p1+3]-PBound[p1+2],NHeight); // } Mate->PermuteRandomAll(Perm,NRow*NCol); //------------------------loop---------------------------- for(int s=NStill+NStep;s>=NStep;s--){ char cImage[160]; sprintf(cImage,"Image%05u.png",s); pngwriter ImageOut(NWidth,NHeight,1.0,cImage); for(int h=0;h<NHeight;h++){ for(int w=0;w<NWidth;w++){ ImageOut.plot(w,h,data[0][h*NWidth+w],data[1][h*NWidth+w],data[2][h*NWidth+w]); } } ImageOut.close(); } for(int s=NStep;s>=0;s--){ NPCol += NStepPCol; if(NPCol > NCol) NPCol = NCol; NPRow += NStepPRow; if(NPRow > NRow) NPRow = NRow; fprintf(stderr,"Elaborating %lf %%\r",s*InvNStep*100.); for(int r=0;r<NRow;r++){ for(int c=0;c<NCol;c++){ int p1 = (r*NCol+c)*2; PFor[p1 ] = 0.; PFor[p1+1] = 0.; } } for(int r=0;r<NRow;r++){ for(int c=0;c<NCol;c++){ if(c > (int)NPCol) continue; if(r > (int)NPRow) continue; int p1 = Perm[r*NCol+c].m*2; if(p1 < 0 || p1 >= NRow*NCol*2){ continue; } for(int r1=r+1;r1<NRow;r1++){ for(int c1=c+1;c1<NCol;c1++){ //int p2 = (r1*NCol+c1)*2; int p2 = Perm[r1*NCol+c1].m*2; if(p2 < 0 || p2 >= NRow*NCol) continue; double Dist[3]; for(int d=0;d<2;d++){ Dist[d] = PPos[p1+d] - PPos[p2+d]; Dist[d] -= floor(Dist[d]/Edge[d] + .5)*Edge[d]; } double Dist2 = SQR(Dist[0]) + SQR(Dist[1]); if(Dist2 > SQR(3.*Sigma))continue; Dist[2] = sqrt(Dist2); double a = (Sigma/sqrt(Dist2)); //double Force = Eps*12.*pow(a,13.) - Eps*6.*pow(a,7.); // if(Force > 20.) Force = 20.; double Force = -Eps/Dist2; for(int d=0;d<2;d++){ PFor[p1+d] -= Force*Dist[d]/Dist[2]; PFor[p2+d] += Force*Dist[d]/Dist[2]; } } } } } //-------------integration-------------- for(int r=0;r<NRow;r++){ for(int c=0;c<NCol;c++){ if(c > (int)NPCol) continue; if(r > (int)NPRow) continue; int p1 = Perm[r*NCol+c].m*2; if(p1 < 0 || p1 >= NRow*NCol*2){ continue; } for(int d=0;d<2;d++){ PVel[p1+d] += PFor[p1+d]*Dt; PPos[p1+d] += PVel[p1+d]*Dt; PPos[p1+d] -= floor(PPos[p1+d]*InvEdge[d])*Edge[d]; } // printf("%d %lf %lf\n",r*NCol+c,PPos[p1],PPos[p1+1]); } } for(int l=0;l<3;l++){ for(int h=0;h<NHeight;h++){ for(int w=0;w<NWidth;w++){ data[l][h*NWidth+w] = 0.; } } } //---------------updating position------------- for(int r=0;r<NRow;r++){ for(int c=0;c<NCol;c++){ int p1 = (r*NCol+c)*2; int xn = (int)(PPos[p1 ]); int yn = (int)(PPos[p1+1]); int xo = PBound[(r*NCol+c)*4 ]; int yo = PBound[(r*NCol+c)*4+2]; int WidSize = PBound[(r*NCol+c)*4+1]-PBound[(r*NCol+c)*4 ]; int HeiSize = PBound[(r*NCol+c)*4+3]-PBound[(r*NCol+c)*4+2]; //printf("%d %d) %d %d -> %d %d |%d %d| %f %f\n",s,r*NCol+c,xo,yo,xn,yn,WidSize,HeiSize,PPos[p1],PPos[p1+1]); for(int l=0;l<3;l++){ for(int ws=0;ws<WidSize;ws++){ int wo = xo+ws; int wn = xn+ws; if(wo >= NWidth){ printf("x out of bound %d > %d | %d\n",wo,NWidth,WidSize); continue; } if(wn >= NWidth) wn -= NWidth; for(int hs=0;hs<HeiSize;hs++){ int ho = yo+hs; int hn = yn+hs; if(ho >= NHeight){ printf("y out of bound %d+%d = %d > %d |%d\n",yo,hs,ho,NHeight,HeiSize); continue; } if(hn > NHeight) hn -= NHeight; //printf("%d= %d %d) %d->%d (%d %d) %d->%d (%d %d)\n",p1,r,c,xo,xn,WidSize,NWidth,yo,yn,HeiSize,NHeight); if(hn*NWidth+wn < 0 || hn*NWidth+wn >= NWidth*NHeight){ printf("input out of border hn %d wn %d > %d %d\n",hn,wn,yn,xn,hn*NWidth+wn,NWidth,NHeight); continue; } if(ho*NWidth+wo < 0 || ho*NWidth+wo >= NWidth*NHeight){ printf("output out of border %d %d %d > %d %d\n",hn,wn,hn*NWidth+wn,NWidth,NHeight); continue; } data[l][hn*NWidth+wn] = data2[l][ho*NWidth+wo]; } } } } } //-------------saving images char cImage[160]; sprintf(cImage,"Image%05u.png",s); pngwriter ImageOut(NWidth,NHeight,1.0,cImage); for(int h=0;h<NHeight;h++){ for(int w=0;w<NWidth;w++){ ImageOut.plot(w,h,data[0][h*NWidth+w],data[1][h*NWidth+w],data[2][h*NWidth+w]); } } ImageOut.close(); } printf("\n"); for(int l=0;l<3;l++){ free(data2[l]); } free(data2); free(PPos); free(PFor); free(PVel); free(PBound); }
void build_verlet_lists() { int c, np1, n, np2, i ,j, j_start; Cell *cell; IA_Neighbor *neighbor; Particle *p1, *p2; PairList *pl; double dist2; #ifdef VERLET_DEBUG double max_range_nonbonded2 = SQR(max_cut_nonbonded + skin); int estimate, sum=0; fprintf(stderr,"%d: build_verlet_list_and_force_calc:\n",this_node); /* estimate number of interactions: (0.5*n_part*ia_volume*density)/n_nodes */ estimate = 0.5*n_part*(4.0/3.0*PI*pow(max_range_nonbonded2,1.5))*(n_part/(box_l[0]*box_l[1]*box_l[2]))/n_nodes; if (!dd.use_vList) { fprintf(stderr, "%d: build_verlet_lists, but use_vList == 0\n", this_node); errexit(); } #endif /* Loop local cells */ for (c = 0; c < local_cells.n; c++) { VERLET_TRACE(fprintf(stderr,"%d: cell %d with %d neighbors\n",this_node,c, dd.cell_inter[c].n_neighbors)); cell = local_cells.cell[c]; p1 = cell->part; np1 = cell->n; /* Loop cell neighbors */ for (n = 0; n < dd.cell_inter[c].n_neighbors; n++) { neighbor = &dd.cell_inter[c].nList[n]; p2 = neighbor->pList->part; np2 = neighbor->pList->n; /* init pair list */ pl = &neighbor->vList; pl->n = 0; /* no interaction set, Verlet list stays empty */ if (max_cut_nonbonded == 0.0) continue; /* Loop cell particles */ for(i=0; i < np1; i++) { j_start = 0; /* Tasks within cell: store old position, avoid double counting */ if(n == 0) { memcpy(p1[i].l.p_old, p1[i].r.p, 3*sizeof(double)); j_start = i+1; } /* Loop neighbor cell particles */ for(j = j_start; j < np2; j++) { #ifdef EXCLUSIONS if(do_nonbonded(&p1[i], &p2[j])) #endif { dist2 = distance2(p1[i].r.p, p2[j].r.p); if(dist2 <= SQR(get_ia_param(p1[i].p.type, p2[j].p.type)->max_cut + skin)) add_pair(pl, &p1[i], &p2[j]); } } } resize_verlet_list(pl); VERLET_TRACE(fprintf(stderr,"%d: neighbor %d has %d particles\n",this_node,n,pl->n)); VERLET_TRACE(sum += pl->n); } } rebuild_verletlist = 0; VERLET_TRACE(fprintf(stderr,"%d: total number of interaction pairs: %d (should be around %d)\n",this_node,sum,estimate)); }
/** calculate dihedral force between particles p1, p2 p3 and p4 Written by Arijit Maitra, adapted to new force interface by Hanjo, more general new dihedral form by Ana. */ inline int calc_dihedral_force(Particle *p2, Particle *p1, Particle *p3, Particle *p4, Bonded_ia_parameters *iaparams, double force2[3], double force1[2], double force3[2]) { int i; /* vectors for dihedral angle calculation */ double v12[3], v23[3], v34[3], v12Xv23[3], v23Xv34[3], l_v12Xv23, l_v23Xv34; double v23Xf1[3], v23Xf4[3], v34Xf4[3], v12Xf1[3]; /* dihedral angle, cosine of the dihedral angle */ double phi, cosphi, sinmphi_sinphi; /* force factors */ double fac, f1[3], f4[3]; /* dihedral angle */ calc_dihedral_angle(p1, p2, p3, p4, v12, v23, v34, v12Xv23, &l_v12Xv23, v23Xv34, &l_v23Xv34, &cosphi, &phi); /* dihedral angle not defined - force zero */ if ( phi == -1.0 ) { for(i=0;i<3;i++) { force1[i] = 0.0; force2[i] = 0.0; force3[i] = 0.0; } return 0; } /* calculate force components (directions) */ for(i=0;i<3;i++) { f1[i] = (v23Xv34[i] - cosphi*v12Xv23[i])/l_v12Xv23;; f4[i] = (v12Xv23[i] - cosphi*v23Xv34[i])/l_v23Xv34; } vector_product(v23, f1, v23Xf1); vector_product(v23, f4, v23Xf4); vector_product(v34, f4, v34Xf4); vector_product(v12, f1, v12Xf1); /* calculate force magnitude */ #ifdef OLD_DIHEDRAL fac = iaparams->p.dihedral.bend * iaparams->p.dihedral.phase * iaparams->p.dihedral.mult; #else fac = -iaparams->p.dihedral.bend * iaparams->p.dihedral.mult; #endif if(fabs(sin(phi)) < TINY_SIN_VALUE) { #ifdef OLD_DIHEDRAL sinmphi_sinphi = iaparams->p.dihedral.mult * cos(2.0*PI - iaparams->p.dihedral.mult*phi)/cos(phi); #else /*(comes from taking the first term of the MacLaurin expansion of sin(n*phi - phi0) and sin(phi) and then making the division). The original code had a 2PI term in the cosine (cos(2PI - nPhi)) but I removed it because it wasn't doing anything. AnaVV*/ sinmphi_sinphi = iaparams->p.dihedral.mult* cos(iaparams->p.dihedral.mult*phi - iaparams->p.dihedral.phase)/cosphi; #endif } else { #ifdef OLD_DIHEDRAL sinmphi_sinphi = sin(iaparams->p.dihedral.mult*phi)/sin(phi); #else sinmphi_sinphi = sin(iaparams->p.dihedral.mult*phi - iaparams->p.dihedral.phase)/sin(phi); #ifdef CONFIGTEMP extern double configtemp[2]; double a[3], b[3], c[3], aXb[3], bXc[3]; get_mi_vector(a, p2->r.p, p1->r.p); get_mi_vector(b, p3->r.p, p2->r.p); get_mi_vector(c, p4->r.p, p3->r.p); vector_product(a, b, aXb); vector_product(b, c, bXc); if (p1->p.configtemp) { configtemp[0] += SQR(fac*sinmphi_sinphi*sin(phi))*sqrlen(b)/sqrlen(aXb); configtemp[1] -= iaparams->p.dihedral.bend * (SQR(iaparams->p.dihedral.mult) * cos(iaparams->p.dihedral.mult*phi - iaparams->p.dihedral.phase) - iaparams->p.dihedral.mult * sinmphi_sinphi*cosphi)*sqrlen(b)/sqrlen(aXb); } if (p4->p.configtemp) { configtemp[0] += SQR(fac*sinmphi_sinphi*sin(phi))*sqrlen(b)/sqrlen(bXc); configtemp[1] -= iaparams->p.dihedral.bend * (SQR(iaparams->p.dihedral.mult) * cos(iaparams->p.dihedral.mult*phi - iaparams->p.dihedral.phase) - iaparams->p.dihedral.mult * sinmphi_sinphi*cosphi)*sqrlen(b)/sqrlen(bXc); } #endif #endif } fac *= sinmphi_sinphi; /* store dihedral forces */ for(i=0;i<3;i++) { force1[i] = fac*v23Xf1[i]; force2[i] = fac*(v34Xf4[i] - v12Xf1[i] - v23Xf1[i]); force3[i] = fac*(v12Xf1[i] - v23Xf4[i] - v34Xf4[i]); } return 0; }
void dpos_vel_linear(int vort) { double x,y,r2; double U,V,Ux,Uy,Vx,Vy; double Uxx,Uyy,Uxy,Vxx,Vyy,Vxy; double Uxxx,Uxyy,Uxxy,Uyyy,Vxxx,Vxyy,Vxxy,Vyyy; double Uxxxx,Uxxxy,Uxxyy,Uxyyy,Uyyyy; double Vxxxx,Vxxxy,Vxxyy,Vxyyy,Vyyyy; double termA,termB,termC; double correction1=1.0,correction2=1.0,correction3=0.0; double xi=0.1; x = mblob[vort].blob0.x; y = mblob[vort].blob0.y; r2 = SQR(mblob[vort].blob0.x) + SQR(mblob[vort].blob0.y); termA = (tmpparms[vort].cos2*blobguts[vort].a2+ tmpparms[vort].sin2/blobguts[vort].a2); termB = (tmpparms[vort].sin2*blobguts[vort].a2+ tmpparms[vort].cos2/blobguts[vort].a2); termC = tmpparms[vort].sincos*(blobguts[vort].a2-1.0/blobguts[vort].a2); U = -(M_PI/2 + xi*(4*r2-3))*y; V = (M_PI/2 + xi*(4*r2-3))*x; Ux = -8*xi*x*y; Uy = -(M_PI/2 + xi*(4*r2-3)) - 8*xi*y*y; Vx = (M_PI/2 + xi*(4*r2-3)) + 8*xi*x*x; Vy = -Ux; Uxx = -8*xi*y; Uxy = -8*xi*x; Uyy = -24*xi*y; Vxx = 24*xi*x; Vxy = -Uxx; Vyy = -Uxy; Uxxx = 0; Uxxy = -8*xi; Uxyy = 0; Uyyy = -24*xi; Vxxx = 24*xi; Vxxy = -Uxxx; Vxyy = -Uxxy; Vyyy = -Uxyy; Uxxxx = 0; Uxxxy = 0; Uxxyy = 0; Uxyyy = 0; Uyyyy = 0; Vxxxx = 0; Vxxxy = -Uxxxx; Vxxyy = -Uxxxy; Vxyyy = -Uxxyy; Vyyyy = -Uxyyy; mblob[vort].blob0.dx = U + correction1*blobguts[vort].s2* (Uxx*termA + Uyy*termB + 2.0*Uxy*termC)- correction3*1.5*SQR(blobguts[vort].s2)* (Uxxxx*SQR(termA)+ 4*Uxxxy*termA*termC+ 2*Uxxyy*(termA*termB+2*SQR(termC))+ 4*Uxyyy*termB*termC+ Uyyyy*SQR(termB)); mblob[vort].blob0.dy = V + correction1*blobguts[vort].s2* (Vxx*termA + Vyy*termB + 2.0*Vxy*termC)- correction3*1.5*SQR(blobguts[vort].s2)* (Vxxxx*SQR(termA)+ 4*Vxxxy*termA*termC+ 2*Vxxyy*(termA*termB+2*SQR(termC))+ 4*Vxyyy*termB*termC+ Vyyyy*SQR(termB)); tmpparms[vort].du11 = Ux - correction2*blobguts[vort].s2* (Uxxx*termA + Uxyy*termB + 2.0*Uxxy*termC); tmpparms[vort].du12 = Uy - correction2*blobguts[vort].s2* (Uxxy*termA + Uyyy*termB + 2.0*Uxyy*termC); tmpparms[vort].du21 = Vx - correction2*blobguts[vort].s2* (Vxxx*termA + Vxyy*termB + 2.0*Vxxy*termC); }
/* ================ Bot_ScriptInitBot ================ */ qboolean Bot_ScriptInitBot(int entnum) { gentity_t *ent, *trav; bot_state_t *bs; char userinfo[MAX_INFO_STRING]; bot_script_global_data_t *bsgd; char *token, *p, *pBackup; int i, val = 0; int weapons[2]; gitem_t *item = NULL; char *name; // bs = &botstates[entnum]; if (!bs->inuse) { return qfalse; } if (bs->script.data) { return qtrue; } // set starting defaults bs->script.status.eventIndex = -1; bs->script.data = NULL; // ent = BotGetEntity(bs->entitynum); trap_GetUserinfo(bs->entitynum, userinfo, sizeof(userinfo)); name = Info_ValueForKey(userinfo, "scriptName"); if (!name || !name[0]) { return qfalse; } // find the script data for this bot bsgd = botCharacterScriptData; for (i = 0; i < numScriptCharacters; i++, bsgd++) { if (Q_stricmp(name, bsgd->name) != 0) { continue; } // check params p = bsgd->params; // // eliminate them with each condition not met while (qtrue) { token = COM_ParseExt(&p, qfalse); if (!token || !token[0]) { // we're done, we found a match break; } // if (token[0] != '/') { G_Error("BotScript, line %i: condition identifier expected, '%s' found\n", bsgd->lineNum, token); } // if (!Q_stricmp(token, "/team")) { token = COM_ParseExt(&p, qfalse); if (!token || !token[0] || token[0] == '/') { G_Error("BotScript, line %i: unexpected end of /team parameter", bsgd->lineNum); } // if (!Q_stricmp(token, "axis")) { val = TEAM_AXIS; } else if (!Q_stricmp(token, "allies")) { val = TEAM_ALLIES; } else { G_Error("BotScript, line %i: unknown team \"%s\"", bsgd->lineNum, token); } // eliminate player if (bs->mpTeam != val) { break; } } else // if (!Q_stricmp(token, "/class")) { token = COM_ParseExt(&p, qfalse); if (!token || !token[0] || token[0] == '/') { G_Error("BotScript, line %i: unexpected end of /class parameter", bsgd->lineNum); } // val = Team_ClassForString(token); if (val < 0) { G_Error("BotScript, line %i: unknown class \"%s\"", bsgd->lineNum, token); } if (bs->mpClass != val) { break; } } else // if (!Q_stricmp(token, "/weapon")) { memset(weapons, 0, sizeof(weapons)); // for each weapon while (qtrue) { // read the weapon token = COM_ParseExt(&p, qfalse); if (!token || !token[0] || token[0] == '/') { G_Error("BotScript, line %i: unexpected end of /weapon parameter", bsgd->lineNum); } // if ((item = BG_FindItem(token))) { if (!item->giTag) { G_Error("BotScript, line %i: unknown weapon \"%s\"", bsgd->lineNum, token); } COM_BitSet(weapons, item->giTag); } else { G_Error("BotScript, line %i: unknown weapon \"%s\"", bsgd->lineNum, token); } // pBackup = p; token = COM_ParseExt(&p, qfalse); if (Q_stricmp(token, "or") != 0) { // not OR, so drop out of here p = pBackup; break; } } if (!(ent->client->ps.weapons[0] & weapons[0]) && !(ent->client->ps.weapons[1] & weapons[1])) { break; } } else // if (!Q_stricmp(token, "/within_range")) { // targetname token = COM_ParseExt(&p, qfalse); if (!token || !token[0] || token[0] == '/') { G_Error("BotScript, line %i: unexpected end of /within_range parameter", bsgd->lineNum); } trav = G_FindByTargetname(NULL, token); if (!trav) { G_Error("BotScript, line %i: unknown spawn point \"%s\"", bsgd->lineNum, token); } // range token = COM_ParseExt(&p, qfalse); if (!token || !token[0] || token[0] == '/') { G_Error("BotScript, line %i: range expected, not found", bsgd->lineNum); } // // eliminate players if (VectorDistanceSquared(ent->r.currentOrigin, trav->s.origin) > SQR(atof(token))) { break; } } } // // if there is a NOT a valid token waiting, then we passed all checks if (!token[0]) { break; } } // if (i < numScriptCharacters) { // we found a script for this character bs->script.data = bsgd->data; return qtrue; } // return qfalse; }
bool intersectObjectVolume(const BallType &b, const BoxType &r) { ++calls; return r.squaredExteriorDistance(b.center) < SQR(b.radius); }
/** * gimp_motion_buffer_motion_event: * @buffer: * @coords: * @time: * @event_fill: * * This function evaluates the event to decide if the change is big * enough to need handling and returns FALSE, if change is less than * set filter level taking a whole lot of load off any draw tools that * have no use for these events anyway. If the event is seen fit at * first look, it is evaluated for speed and smoothed. Due to lousy * time resolution of events pretty strong smoothing is applied to * timestamps for sensible speed result. This function is also ideal * for other event adjustment like pressure curve or calculating other * derived dynamics factors like angular velocity calculation from * tilt values, to allow for even more dynamic brushes. Calculated * distance to last event is stored in GimpCoords because its a * sideproduct of velocity calculation and is currently calculated in * each tool. If they were to use this distance, more resouces on * recalculating the same value would be saved. * * Return value: %TRUE if the motion was significant enough to be * processed, %FALSE otherwise. **/ gboolean gimp_motion_buffer_motion_event (GimpMotionBuffer *buffer, GimpCoords *coords, guint32 time, gboolean event_fill) { gdouble delta_time = 0.001; gdouble delta_x = 0.0; gdouble delta_y = 0.0; gdouble distance = 1.0; gdouble scale_x = coords->xscale; gdouble scale_y = coords->yscale; g_return_val_if_fail (GIMP_IS_MOTION_BUFFER (buffer), FALSE); g_return_val_if_fail (coords != NULL, FALSE); /* the last_read_motion_time most be set unconditionally, so set * it early */ buffer->last_read_motion_time = time; delta_time = (buffer->last_motion_delta_time * (1 - SMOOTH_FACTOR) + (time - buffer->last_motion_time) * SMOOTH_FACTOR); if (buffer->last_motion_time == 0) { /* First pair is invalid to do any velocity calculation, so we * apply a constant value. */ coords->velocity = 1.0; } else { GimpCoords last_dir_event = buffer->last_coords; gdouble filter; gdouble dist; gdouble delta_dir; gdouble dir_delta_x = 0.0; gdouble dir_delta_y = 0.0; delta_x = last_dir_event.x - coords->x; delta_y = last_dir_event.y - coords->y; /* Events with distances less than the screen resolution are * not worth handling. */ filter = MIN (1.0 / scale_x, 1.0 / scale_y) / 2.0; if (fabs (delta_x) < filter && fabs (delta_y) < filter) { return FALSE; } distance = dist = sqrt (SQR (delta_x) + SQR (delta_y)); /* If even smoothed time resolution does not allow to guess for * speed, use last velocity. */ if (delta_time == 0) { coords->velocity = buffer->last_coords.velocity; } else { /* We need to calculate the velocity in screen coordinates * for human interaction */ gdouble screen_distance = (distance * MIN (scale_x, scale_y)); /* Calculate raw valocity */ coords->velocity = ((screen_distance / delta_time) / VELOCITY_UNIT); /* Adding velocity dependent smoothing, feels better in tools. */ coords->velocity = (buffer->last_coords.velocity * (1 - MIN (SMOOTH_FACTOR, coords->velocity)) + coords->velocity * MIN (SMOOTH_FACTOR, coords->velocity)); /* Speed needs upper limit */ coords->velocity = MIN (coords->velocity, 1.0); } if (((fabs (delta_x) > DIRECTION_RADIUS) && (fabs (delta_y) > DIRECTION_RADIUS)) || (buffer->event_history->len < 4)) { dir_delta_x = delta_x; dir_delta_y = delta_y; } else { gint x = CLAMP ((buffer->event_history->len - 1), 3, 15); while (((fabs (dir_delta_x) < DIRECTION_RADIUS) || (fabs (dir_delta_y) < DIRECTION_RADIUS)) && (x >= 0)) { last_dir_event = g_array_index (buffer->event_history, GimpCoords, x); dir_delta_x = last_dir_event.x - coords->x; dir_delta_y = last_dir_event.y - coords->y; x--; } } if ((fabs (dir_delta_x) < DIRECTION_RADIUS) || (fabs (dir_delta_y) < DIRECTION_RADIUS)) { coords->direction = buffer->last_coords.direction; } else { coords->direction = gimp_coords_direction (&last_dir_event, coords); } coords->direction = coords->direction - floor (coords->direction); delta_dir = coords->direction - buffer->last_coords.direction; if (delta_dir < -0.5) { coords->direction = (0.5 * coords->direction + 0.5 * (buffer->last_coords.direction - 1.0)); } else if (delta_dir > 0.5) { coords->direction = (0.5 * coords->direction + 0.5 * (buffer->last_coords.direction + 1.0)); } else { coords->direction = (0.5 * coords->direction + 0.5 * buffer->last_coords.direction); } coords->direction = coords->direction - floor (coords->direction); /* do event fill for devices that do not provide enough events */ if (distance >= EVENT_FILL_PRECISION && event_fill && buffer->event_history->len >= 2) { if (buffer->event_delay) { gimp_motion_buffer_interpolate_stroke (buffer, coords); } else { buffer->event_delay = TRUE; gimp_motion_buffer_push_event_history (buffer, coords); } } else { if (buffer->event_delay) buffer->event_delay = FALSE; gimp_motion_buffer_push_event_history (buffer, coords); } #ifdef EVENT_VERBOSE g_printerr ("DIST: %f, DT:%f, Vel:%f, Press:%f,smooth_dd:%f, POS: (%f, %f)\n", distance, delta_time, buffer->last_coords.velocity, coords->pressure, distance - dist, coords->x, coords->y); #endif } g_array_append_val (buffer->event_queue, *coords); buffer->last_coords = *coords; buffer->last_motion_time = time; buffer->last_motion_delta_time = delta_time; buffer->last_motion_delta_x = delta_x; buffer->last_motion_delta_y = delta_y; buffer->last_motion_distance = distance; return TRUE; }
bool intersectObject(const BallType &b) { ++calls; if((b.center - p).squaredNorm() < SQR(b.radius)) ++count; return false; //continue }
double minimumOnObjectObject(const BallType &b, const VectorType &v) { ++calls; return SQR(std::max(0., (b.center - v).norm() - b.radius)); }
double minimumOnObjectObject(const BallType &b1, const BallType &b2) { ++calls; return SQR(std::max(0., (b1.center - b2.center).norm() - b1.radius - b2.radius)); }
int trim_distances(double **dep, double **xp, double **yp, double **gammap, double min, double max, int np) { int j; int nn = np; /* , step = 1; */ double dist; double *de, *x, *y, *gamma; double *de_new, *x_new, *y_new, *gamma_new; struct node *pp, *p = NULL, *first = NULL; double vort1, vort2, vort3, weight; de = *dep; x = *xp; y = *yp; gamma = *gammap; /* printf("\n\nTotal in: %f\n", integral(gamma,de,nn)); */ for(j = 0; j < np; j++) { pp = malloc(sizeof(struct node)); pp->de = de[j]; pp->x = x[j]; pp->y = y[j]; pp->gamma = gamma[j]; if(j == np-1) { dist = SQR(x[0] - x[j] + 1.0); dist += SQR(y[0] - y[j]); } else { dist = SQR(x[j+1] - x[j]); dist += SQR(y[j+1] - y[j]); } pp->dist = dist; pp->prev = p; if(first == NULL) first = pp; else p->next = pp; p = pp; } p->next = first; first->prev = p; p = first; do { /* printf("\n\nStep %i: ", step); */ if(p->dist < min) { /* printf("kill\n"); */ vort1 = p->gamma*(p->prev->de + p->de); vort2 = p->next->gamma*(p->de + p->next->de); pp = p->next->next; vort3 = pp->gamma*(pp->prev->de + pp->de); weight = 1.0/(1.0 + p->next->de / p->de); p->de += p->next->de; free(p->next); if(first == p->next) first = pp; nn--; p->next = pp; pp->prev = p; vort1 += weight*vort2; vort3 += (1.0-weight)*vort2; p->gamma = vort1/(p->prev->de + p->de); pp->gamma = vort3/(pp->prev->de + pp->de); p = pp; } else if(p->dist > max) { /* printf("add\n"); */ vort1 = p->gamma*(p->prev->de + .5*p->de); vort2 = .5*p->de*(p->gamma + p->next->gamma); vort3 = p->next->gamma*(.5*p->de + p->next->de); pp = malloc(sizeof(struct node)); nn++; pp->de = .5*p->de; p->de = pp->de; pp->x = .5*(p->x + p->next->x); if(first == p->next) pp->x += .5; pp->y = .5*(p->y + p->next->y); pp->next = p->next; pp->prev = p; pp->next->prev = pp; p->next = pp; p->gamma = vort1/(p->prev->de + p->de); pp->gamma = vort2/(p->de + pp->de); pp->next->gamma = vort3/(pp->de + pp->next->de); p = pp->next; } else { /* printf("noop\n"); */ p = p->next; } /* debdump(first); */ /* getchar(); */ } while(p != first); de_new = vector(nn); x_new = vector(nn); y_new = vector(nn); gamma_new = vector(nn); p = first; j = 0; do { de_new[j] = p->de; x_new[j] = p->x; y_new[j] = p->y; gamma_new[j] = p->gamma; j++; pp = p; p = p->next; free(pp); } while(p != first); swap(&de_new, dep); swap(&x_new, xp); swap(&y_new, yp); swap(&gamma_new, gammap); free(de_new); free(x_new); free(y_new); free(gamma_new); return nn; }
/* satellite position by precise ephemeris -----------------------------------*/ static int pephpos(gtime_t time, int sat, const nav_t *nav, double *rs, double *dts, double *vare, double *varc) { double t[NMAX+1],p[3][NMAX+1],c[2],*pos,std=0.0,s[3],sinl,cosl; int i,j,k,index; trace(4,"pephpos : time=%s sat=%2d\n",time_str(time,3),sat); rs[0]=rs[1]=rs[2]=dts[0]=0.0; if (nav->ne<NMAX+1|| timediff(time,nav->peph[0].time)<-MAXDTE|| timediff(time,nav->peph[nav->ne-1].time)>MAXDTE) { trace(2,"no prec ephem %s sat=%2d\n",time_str(time,0),sat); return 0; } /* binary search */ for (i=0,j=nav->ne-1;i<j;) { k=(i+j)/2; if (timediff(nav->peph[k].time,time)<0.0) i=k+1; else j=k; } index=i<=0?0:i-1; /* polynomial interpolation for orbit */ i=index-(NMAX+1)/2; if (i<0) i=0; else if (i+NMAX>=nav->ne) i=nav->ne-NMAX-1; for (j=0;j<=NMAX;j++) { t[j]=timediff(nav->peph[i+j].time,time); if (norm(nav->peph[i+j].pos[sat-1],3)<=0.0) { trace(2,"prec ephem outage %s sat=%2d\n",time_str(time,0),sat); return 0; } } for (j=0;j<=NMAX;j++) { pos=nav->peph[i+j].pos[sat-1]; #if 0 p[0][j]=pos[0]; p[1][j]=pos[1]; #else /* correciton for earh rotation ver.2.4.0 */ sinl=sin(OMGE*t[j]); cosl=cos(OMGE*t[j]); p[0][j]=cosl*pos[0]-sinl*pos[1]; p[1][j]=sinl*pos[0]+cosl*pos[1]; #endif p[2][j]=pos[2]; } for (i=0;i<3;i++) { rs[i]=interppol(t,p[i],NMAX+1); } if (vare) { for (i=0;i<3;i++) s[i]=nav->peph[index].std[sat-1][i]; std=norm(s,3); /* extrapolation error for orbit */ if (t[0 ]>0.0) std+=EXTERR_EPH*SQR(t[0 ])/2.0; else if (t[NMAX]<0.0) std+=EXTERR_EPH*SQR(t[NMAX])/2.0; *vare=SQR(std); } /* linear interpolation for clock */ t[0]=timediff(time,nav->peph[index ].time); t[1]=timediff(time,nav->peph[index+1].time); c[0]=nav->peph[index ].pos[sat-1][3]; c[1]=nav->peph[index+1].pos[sat-1][3]; if (t[0]<=0.0) { if ((dts[0]=c[0])!=0.0) { std=nav->peph[index].std[sat-1][3]*CLIGHT-EXTERR_CLK*t[0]; } } else if (t[1]>=0.0) { if ((dts[0]=c[1])!=0.0) { std=nav->peph[index+1].std[sat-1][3]*CLIGHT+EXTERR_CLK*t[1]; } } else if (c[0]!=0.0&&c[1]!=0.0) { dts[0]=(c[1]*t[0]-c[0]*t[1])/(t[0]-t[1]); i=t[0]<-t[1]?0:1; std=nav->peph[index+i].std[sat-1][3]+EXTERR_CLK*fabs(t[i]); } else { dts[0]=0.0; } if (varc) *varc=SQR(std); return 1; }
void build_verlet_lists_and_calc_verlet_ia() { int c, np1, n, np2, i ,j, j_start; Cell *cell; IA_Neighbor *neighbor; Particle *p1, *p2; PairList *pl; double dist2, vec21[3]; #ifdef VERLET_DEBUG int estimate, sum=0; double max_range_nonbonded2 = SQR(max_cut_nonbonded + skin); fprintf(stderr,"%d: build_verlet_list_and_calc_verlet_ia:\n",this_node); /* estimate number of interactions: (0.5*n_part*ia_volume*density)/n_nodes */ estimate = 0.5*n_part*(4.0/3.0*PI*pow(max_range_nonbonded2,1.5))*(n_part/(box_l[0]*box_l[1]*box_l[2]))/n_nodes; if (!dd.use_vList) { fprintf(stderr, "%d: build_verlet_lists, but use_vList == 0\n", this_node); errexit(); } #endif /* Loop local cells */ for (c = 0; c < local_cells.n; c++) { VERLET_TRACE(fprintf(stderr,"%d: cell %d with %d neighbors\n",this_node,c, dd.cell_inter[c].n_neighbors)); cell = local_cells.cell[c]; p1 = cell->part; np1 = cell->n; /* Loop cell neighbors */ for (n = 0; n < dd.cell_inter[c].n_neighbors; n++) { neighbor = &dd.cell_inter[c].nList[n]; p2 = neighbor->pList->part; np2 = neighbor->pList->n; VERLET_TRACE(fprintf(stderr,"%d: neighbor %d contains %d parts\n",this_node,n,np2)); /* init pair list */ pl = &neighbor->vList; pl->n = 0; /* Loop cell particles */ for(i=0; i < np1; i++) { j_start = 0; /* Tasks within cell: bonded forces, store old position, avoid double counting */ if(n == 0) { add_bonded_force(&p1[i]); #ifdef CONSTRAINTS add_constraints_forces(&p1[i]); #endif add_external_potential_forces(&p1[i]); memcpy(p1[i].l.p_old, p1[i].r.p, 3*sizeof(double)); j_start = i+1; } /* no interaction set, no need for particle pairs */ if (max_cut_nonbonded == 0.0) continue; /* Loop neighbor cell particles */ for(j = j_start; j < np2; j++) { #ifdef EXCLUSIONS if(do_nonbonded(&p1[i], &p2[j])) #endif { dist2 = distance2vec(p1[i].r.p, p2[j].r.p, vec21); VERLET_TRACE(fprintf(stderr,"%d: pair %d %d has distance %f\n",this_node,p1[i].p.identity,p2[j].p.identity,sqrt(dist2))); if(dist2 <= SQR(get_ia_param(p1[i].p.type, p2[j].p.type)->max_cut + skin)) { ONEPART_TRACE(if(p1[i].p.identity==check_id) fprintf(stderr,"%d: OPT: Verlet Pair %d %d (Cells %d,%d %d,%d dist %f)\n",this_node,p1[i].p.identity,p2[j].p.identity,c,i,n,j,sqrt(dist2))); ONEPART_TRACE(if(p2[j].p.identity==check_id) fprintf(stderr,"%d: OPT: Verlet Pair %d %d (Cells %d %d dist %f)\n",this_node,p1[i].p.identity,p2[j].p.identity,c,n,sqrt(dist2))); add_pair(pl, &p1[i], &p2[j]); /* calc non bonded interactions */ add_non_bonded_pair_force(&(p1[i]), &(p2[j]), vec21, sqrt(dist2), dist2); } } } } resize_verlet_list(pl); VERLET_TRACE(fprintf(stderr,"%d: neighbor %d has %d pairs\n",this_node,n,pl->n)); VERLET_TRACE(sum += pl->n); }
/* The main entry to LSH package. Depending on the command line parameters, the function computes the R-NN data structure optimal parameters and/or construct the R-NN data structure and runs the queries on the data structure. */ int main(int nargs, char **args){ if(nargs < 9){ usage(args[0]); exit(1); } //initializeLSHGlobal(); // Parse part of the command-line parameters. nPoints = atoi(args[1]); IntT nQueries = atoi(args[2]); pointsDimension = atoi(args[3]); successProbability = atof(args[4]); char* endPtr[1]; RealT thresholdR = strtod(args[5], endPtr); if (thresholdR == 0 || endPtr[1] == args[5]){ // The value for R is not specified, instead there is a file // specifying multiple R's. thresholdR = 0; // Read in the file FILE *radiiFile = fopen(args[5], "rt"); FAILIF(radiiFile == NULL); fscanf(radiiFile, "%d\n", &nRadii); ASSERT(nRadii > 0); FAILIF(NULL == (listOfRadii = (RealT*)MALLOC(nRadii * sizeof(RealT)))); FAILIF(NULL == (memRatiosForNNStructs = (RealT*)MALLOC(nRadii * sizeof(RealT)))); for(IntT i = 0; i < nRadii; i++){ FSCANF_REAL(radiiFile, &listOfRadii[i]); ASSERT(listOfRadii[i] > 0); FSCANF_REAL(radiiFile, &memRatiosForNNStructs[i]); ASSERT(memRatiosForNNStructs[i] > 0); } }else{ nRadii = 1; FAILIF(NULL == (listOfRadii = (RealT*)MALLOC(nRadii * sizeof(RealT)))); FAILIF(NULL == (memRatiosForNNStructs = (RealT*)MALLOC(nRadii * sizeof(RealT)))); listOfRadii[0] = thresholdR; memRatiosForNNStructs[0] = 1; } DPRINTF("No. radii: %d\n", nRadii); //thresholdR = atof(args[5]); availableTotalMemory = atoll(args[8]); if (nPoints > MAX_N_POINTS) { printf("Error: the structure supports at most %d points (%d were specified).\n", MAX_N_POINTS, nPoints); fprintf(ERROR_OUTPUT, "Error: the structure supports at most %d points (%d were specified).\n", MAX_N_POINTS, nPoints); exit(1); } readDataSetFromFile(args[6]); DPRINTF("Allocated memory (after reading data set): %lld\n", totalAllocatedMemory); Int32T nSampleQueries = N_SAMPLE_QUERY_POINTS; PPointT sampleQueries[nSampleQueries]; Int32T sampleQBoundaryIndeces[nSampleQueries]; if ((nargs < 9) || (strcmp("-c", args[9]) == 0)){ // In this cases, we need to generate a sample query set for // computing the optimal parameters. // Generate a sample query set. FILE *queryFile = fopen(args[7], "rt"); if (strcmp(args[7], ".") == 0 || queryFile == NULL || nQueries <= 0){ // Choose several data set points for the sample query points. for(IntT i = 0; i < nSampleQueries; i++){ sampleQueries[i] = dataSetPoints[genRandomInt(0, nPoints - 1)]; } }else{ // Choose several actual query points for the sample query points. nSampleQueries = MIN(nSampleQueries, nQueries); Int32T sampleIndeces[nSampleQueries]; for(IntT i = 0; i < nSampleQueries; i++){ sampleIndeces[i] = genRandomInt(0, nQueries - 1); } qsort(sampleIndeces, nSampleQueries, sizeof(*sampleIndeces), compareInt32T); //printIntVector("sampleIndeces: ", nSampleQueries, sampleIndeces); Int32T j = 0; for(Int32T i = 0; i < nQueries; i++){ if (i == sampleIndeces[j]){ sampleQueries[j] = readPoint(queryFile); j++; while (i == sampleIndeces[j]){ sampleQueries[j] = sampleQueries[j - 1]; j++; } }else{ fscanf(queryFile, "%[^\n]", sBuffer); fscanf(queryFile, "\n"); } } nSampleQueries = j; fclose(queryFile); } // Compute the array sampleQBoundaryIndeces that specifies how to // segregate the sample query points according to their distance // to NN. sortQueryPointsByRadii(pointsDimension, nSampleQueries, sampleQueries, nPoints, dataSetPoints, nRadii, listOfRadii, sampleQBoundaryIndeces); } RNNParametersT *algParameters = NULL; PRNearNeighborStructT *nnStructs = NULL; if (nargs > 9) { // Additional command-line parameter is specified. if (strcmp("-c", args[9]) == 0) { // Only compute the R-NN DS parameters and output them to stdout. printf("%d\n", nRadii); transformMemRatios(); for(IntT i = 0; i < nRadii; i++){ // which sample queries to use Int32T segregatedQStart = (i == 0) ? 0 : sampleQBoundaryIndeces[i - 1]; Int32T segregatedQNumber = nSampleQueries - segregatedQStart; if (segregatedQNumber == 0) { // XXX: not the right answer segregatedQNumber = nSampleQueries; segregatedQStart = 0; } ASSERT(segregatedQStart < nSampleQueries); ASSERT(segregatedQStart >= 0); ASSERT(segregatedQStart + segregatedQNumber <= nSampleQueries); ASSERT(segregatedQNumber >= 0); RNNParametersT optParameters = computeOptimalParameters(listOfRadii[i], successProbability, nPoints, pointsDimension, dataSetPoints, segregatedQNumber, sampleQueries + segregatedQStart, (MemVarT)((availableTotalMemory - totalAllocatedMemory) * memRatiosForNNStructs[i])); printRNNParameters(stdout, optParameters); } exit(0); } else if (strcmp("-p", args[9]) == 0) { // Read the R-NN DS parameters from the given file and run the // queries on the constructed data structure. if (nargs < 10){ usage(args[0]); exit(1); } FILE *pFile = fopen(args[10], "rt"); FAILIFWR(pFile == NULL, "Could not open the params file."); fscanf(pFile, "%d\n", &nRadii); DPRINTF1("Using the following R-NN DS parameters:\n"); DPRINTF("N radii = %d\n", nRadii); FAILIF(NULL == (nnStructs = (PRNearNeighborStructT*)MALLOC(nRadii * sizeof(PRNearNeighborStructT)))); FAILIF(NULL == (algParameters = (RNNParametersT*)MALLOC(nRadii * sizeof(RNNParametersT)))); for(IntT i = 0; i < nRadii; i++){ algParameters[i] = readRNNParameters(pFile); printRNNParameters(stderr, algParameters[i]); nnStructs[i] = initLSH_WithDataSet(algParameters[i], nPoints, dataSetPoints); } pointsDimension = algParameters[0].dimension; FREE(listOfRadii); FAILIF(NULL == (listOfRadii = (RealT*)MALLOC(nRadii * sizeof(RealT)))); for(IntT i = 0; i < nRadii; i++){ listOfRadii[i] = algParameters[i].parameterR; } } else{ // Wrong option. usage(args[0]); exit(1); } } else { FAILIF(NULL == (nnStructs = (PRNearNeighborStructT*)MALLOC(nRadii * sizeof(PRNearNeighborStructT)))); // Determine the R-NN DS parameters, construct the DS and run the queries. transformMemRatios(); for(IntT i = 0; i < nRadii; i++){ // XXX: segregate the sample queries... nnStructs[i] = initSelfTunedRNearNeighborWithDataSet(listOfRadii[i], successProbability, nPoints, pointsDimension, dataSetPoints, nSampleQueries, sampleQueries, (MemVarT)((availableTotalMemory - totalAllocatedMemory) * memRatiosForNNStructs[i])); } } DPRINTF1("X\n"); IntT resultSize = nPoints; PPointT *result = (PPointT*)MALLOC(resultSize * sizeof(*result)); PPointT queryPoint; FAILIF(NULL == (queryPoint = (PPointT)MALLOC(sizeof(PointT)))); FAILIF(NULL == (queryPoint->coordinates = (RealT*)MALLOC(pointsDimension * sizeof(RealT)))); FILE *queryFile = fopen(args[7], "rt"); FAILIF(queryFile == NULL); TimeVarT meanQueryTime = 0; PPointAndRealTStructT *distToNN = NULL; MyInspectionCounterTotal = 0; for(IntT i = 0; i < nQueries; i++){ RealT sqrLength = 0; // read in the query point. for(IntT d = 0; d < pointsDimension; d++){ FSCANF_REAL(queryFile, &(queryPoint->coordinates[d])); sqrLength += SQR(queryPoint->coordinates[d]); } queryPoint->sqrLength = sqrLength; //printRealVector("Query: ", pointsDimension, queryPoint->coordinates); // get the near neighbors. IntT nNNs = 0; for(IntT r = 0; r < nRadii; r++){ nNNs = getRNearNeighbors(nnStructs[r], queryPoint, result, resultSize); printf("Total time for R-NN query at radius %0.6lf (radius no. %d):\t%0.6lf\n", (double)(listOfRadii[r]), r, timeRNNQuery); meanQueryTime += timeRNNQuery; if (nNNs > 0){ printf("Query point %d: found %d NNs at distance %0.6lf (%dth radius). First %d NNs are:\n", i, nNNs, (double)(listOfRadii[r]), r, MIN(nNNs, MAX_REPORTED_POINTS)); // compute the distances to the found NN, and sort according to the distance FAILIF(NULL == (distToNN = (PPointAndRealTStructT*)REALLOC(distToNN, nNNs * sizeof(*distToNN)))); for(IntT p = 0; p < nNNs; p++){ distToNN[p].ppoint = result[p]; distToNN[p].real = distance(pointsDimension, queryPoint, result[p]); } qsort(distToNN, nNNs, sizeof(*distToNN), comparePPointAndRealTStructT); // Print the points for(IntT j = 0; j < MIN(nNNs, MAX_REPORTED_POINTS); j++){ ASSERT(distToNN[j].ppoint != NULL); printf("%09d\tDistance:%0.6lf\n", distToNN[j].ppoint->index, distToNN[j].real); CR_ASSERT(distToNN[j].real <= listOfRadii[r]); //DPRINTF("Distance: %lf\n", distance(pointsDimension, queryPoint, result[j])); //printRealVector("NN: ", pointsDimension, result[j]->coordinates); } break; } } MyInspectionCounterTotal += MyInspectionCounter; printf("Inspections - %d \n",MyInspectionCounter); if (nNNs == 0){ printf("Query point %d: no NNs found.\n", i); } } FILE *fp = fopen("LSH_RESULTS.txt","a"); fprintf(fp,"%d %d %lf \n",(nPoints+200),pointsDimension,float(MyInspectionCounterTotal)/float(100)); fclose(fp); if (nQueries > 0){ meanQueryTime = meanQueryTime / nQueries; printf("Mean query time: %0.6lf\n", (double)meanQueryTime); } for(IntT i = 0; i < nRadii; i++){ freePRNearNeighborStruct(nnStructs[i]); } // XXX: should ideally free the other stuff as well. return 0; }
/* ----------------------------------------------------------------- */ static int FixedAsian_Glassermann(double s, double K, double time_spent, NumFunc_2 *p, double t, double r, double divid, double sigma, long nb, int M, int generator, double confidence, double *ptprice,double *ptdelta, double *pterror_price, double *pterror_delta, double *inf_price, double *sup_price, double *inf_delta, double *sup_delta) { long i,ipath; double price_sample , delta_sample, mean_price, mean_delta, var_price, var_delta; int init_mc; int simulation_dim; double alpha, z_alpha,dot1,dot2; /* inc=0.001;*/ double integral, S_t, g1; double h = t /(double)M; double sqrt_h = sqrt(h); double trend= (r -divid)- 0.5 * SQR(sigma); int step_number=M; /* Value to construct the confidence interval */ alpha= (1.- confidence)/2.; z_alpha= pnl_inv_cdfnor(1.- alpha); /*Initialisation*/ mean_price= 0.0; mean_delta= 0.0; var_price= 0.0; var_delta= 0.0; /* Size of the random vector we need in the simulation */ simulation_dim= M; /* MC sampling */ init_mc= pnl_rand_init(generator, simulation_dim,nb); /* Test after initialization for the generator */ if(init_mc == OK) { /* Price */ (void)Drift_Computation(generator, M, t, s,r, divid, sigma, p, K); dot2=0; for(i=0;i<step_number;i++) dot2+=mu[i]*mu[i]; for(ipath= 1;ipath<= nb;ipath++) { /* Begin of the N iterations */ g1= pnl_rand_gauss(step_number, CREATE, 0, generator); integral=0.0; S_t=s;dot1=0.; for(i=0 ; i< step_number ; i++) { g1= pnl_rand_gauss(step_number, RETRIEVE, i, generator); S_t *=exp(trend *h +sigma*sqrt_h*(g1+mu[i])); integral+=S_t; dot1+=mu[i]*g1; } price_sample=(p->Compute)(p->Par, s,integral/(double)step_number)*exp(-dot1-0.5*dot2); /* Delta */ if(price_sample >0.0) delta_sample=(1-time_spent)*(integral/(s*(double)step_number))*exp(-dot1-0.5*dot2); else delta_sample=0.; /* Sum */ mean_price+= price_sample; mean_delta+= delta_sample; /* Sum of squares */ var_price+= SQR(price_sample); var_delta+= SQR(delta_sample); } /* End of the N iterations */ /* Price estimator */ *ptprice=(mean_price/(double)nb); *pterror_price= exp(-r*t)*sqrt(var_price/(double)nb-SQR(*ptprice))/sqrt((double)nb-1); *ptprice= exp(-r*t)*(*ptprice); /* Price Confidence Interval */ *inf_price= *ptprice - z_alpha*(*pterror_price); *sup_price= *ptprice + z_alpha*(*pterror_price); /* Delta estimator */ *ptdelta=exp(-r*t)*(mean_delta/(double)nb); if((p->Compute) == &Put_OverSpot2) *ptdelta *= (-1); *pterror_delta= sqrt(exp(-2.0*r*t)*(var_delta/(double)nb-SQR(*ptdelta)))/sqrt((double)nb-1); /* Delta Confidence Interval */ *inf_delta= *ptdelta - z_alpha*(*pterror_delta); *sup_delta= *ptdelta + z_alpha*(*pterror_delta); } return init_mc; }
inline float vec3_squared_length(const t_vec3 *v) { return (SQR(v->x) + SQR(v->y) + SQR(v->z)); }
/* Do modular exponentiation using integer multiply code. */ mp_err mp_exptmod_i(const mp_int *montBase, const mp_int *exponent, const mp_int *modulus, mp_int *result, mp_mont_modulus *mmm, int nLen, mp_size bits_in_exponent, mp_size window_bits, mp_size odd_ints) { mp_int *pa1, *pa2, *ptmp; mp_size i; mp_err res; int expOff; mp_int accum1, accum2, power2, oddPowers[MAX_ODD_INTS]; /* power2 = base ** 2; oddPowers[i] = base ** (2*i + 1); */ /* oddPowers[i] = base ** (2*i + 1); */ MP_DIGITS(&accum1) = 0; MP_DIGITS(&accum2) = 0; MP_DIGITS(&power2) = 0; for (i = 0; i < MAX_ODD_INTS; ++i) { MP_DIGITS(oddPowers + i) = 0; } MP_CHECKOK(mp_init_size(&accum1, 3 * nLen + 2)); MP_CHECKOK(mp_init_size(&accum2, 3 * nLen + 2)); MP_CHECKOK(mp_init_copy(&oddPowers[0], montBase)); MP_CHECKOK(mp_init_size(&power2, nLen + 2 * MP_USED(montBase) + 2)); MP_CHECKOK(mp_sqr(montBase, &power2)); /* power2 = montBase ** 2 */ MP_CHECKOK(s_mp_redc(&power2, mmm)); for (i = 1; i < odd_ints; ++i) { MP_CHECKOK(mp_init_size(oddPowers + i, nLen + 2 * MP_USED(&power2) + 2)); MP_CHECKOK(mp_mul(oddPowers + (i - 1), &power2, oddPowers + i)); MP_CHECKOK(s_mp_redc(oddPowers + i, mmm)); } /* set accumulator to montgomery residue of 1 */ mp_set(&accum1, 1); MP_CHECKOK(s_mp_to_mont(&accum1, mmm, &accum1)); pa1 = &accum1; pa2 = &accum2; for (expOff = bits_in_exponent - window_bits; expOff >= 0; expOff -= window_bits) { mp_size smallExp; MP_CHECKOK(mpl_get_bits(exponent, expOff, window_bits)); smallExp = (mp_size)res; if (window_bits == 1) { if (!smallExp) { SQR(pa1, pa2); SWAPPA; } else if (smallExp & 1) { SQR(pa1, pa2); MUL(0, pa2, pa1); } else { abort(); } } else if (window_bits == 4) { if (!smallExp) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); } else if (smallExp & 1) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 2, pa1, pa2); SWAPPA; } else if (smallExp & 2) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); MUL(smallExp / 4, pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 4) { SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 8, pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 8) { SQR(pa1, pa2); MUL(smallExp / 16, pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else { abort(); } } else if (window_bits == 5) { if (!smallExp) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 1) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); MUL(smallExp / 2, pa2, pa1); } else if (smallExp & 2) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 4, pa1, pa2); SQR(pa2, pa1); } else if (smallExp & 4) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); MUL(smallExp / 8, pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); } else if (smallExp & 8) { SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 16, pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); } else if (smallExp & 0x10) { SQR(pa1, pa2); MUL(smallExp / 32, pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); } else { abort(); } } else if (window_bits == 6) { if (!smallExp) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); } else if (smallExp & 1) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 2, pa1, pa2); SWAPPA; } else if (smallExp & 2) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); MUL(smallExp / 4, pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 4) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 8, pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 8) { SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); MUL(smallExp / 16, pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 0x10) { SQR(pa1, pa2); SQR(pa2, pa1); MUL(smallExp / 32, pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else if (smallExp & 0x20) { SQR(pa1, pa2); MUL(smallExp / 64, pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SQR(pa2, pa1); SQR(pa1, pa2); SWAPPA; } else { abort(); } } else { abort(); } } res = s_mp_redc(pa1, mmm); mp_exch(pa1, result); CLEANUP: mp_clear(&accum1); mp_clear(&accum2); mp_clear(&power2); for (i = 0; i < odd_ints; ++i) { mp_clear(oddPowers + i); } return res; }
void ReadSubFunc () { double _i, _j, _k; double _rho, _df_drho, _grad; double _sub, _wa; double _rho_temp, _wa_temp, _sub_temp; char str [120]; FILE *snap, *Wfields, *Wsub; sprintf(name,"snapshot_final.dat"); MAKE_FILENAME(fullname_snap,name); snap=fopen(fullname_snap,"r"); // skip first 10 words (header of tecplot) for (int i=0; i<10; i++) { fscanf (snap, "%s", str); } for(int i = 1; i < grid.x+1; i++){ for(int j = 1; j < grid.y+1; j++){ for(int k = 1; k < grid.z+1; k++){ /* read in the field and the substrate potential */ fscanf(snap,"%lf %lf %lf %lf %lf %lf %lf %lf \n", &_i, &_j, &_k, &_rho_temp, &df_drho[i][j][k], &grad[i][j][k], &_sub_temp, &_wa_temp); } } } fclose(snap); printf("finished snapshot reading\n"); // read filename of the fields for restart sprintf(name,"Wfields_final.dat"); MAKE_FILENAME(fullname_Wfields,name); Wfields=fopen(fullname_Wfields,"r"); for(int i = 1; i < grid.x+1; i++){ for(int j = 1; j < grid.y+1; j++){ for(int k = 1; k < grid.z+1; k++){ fscanf(Wfields,"%lf \n",&_wa); wa[i][j][k] = _wa; // the following is only valid for grand canonical ensemble: rho[i][j][k] = rho_liq * exp(V11*rho_liq + W111*SQR(rho_liq) - wa[i][j][k]); } } } fclose(Wfields); printf("finished Wfields reading\n"); // read substrate potential for restart MAKE_FILENAME(fullname_Wsub,"substrate.dat"); Wsub = fopen(fullname_Wsub,"r"); for(int i = 1; i < grid.x+1; i++){ for(int j = 1; j < grid.y+1; j++){ for(int k = 1; k < grid.z+1; k++){ fscanf(Wsub,"%lf \n",&_sub); sub[i][j][k] = _sub; } } } fclose(Wsub); printf("finished substrate reading\n"); // fill in array borders through periodic boundaries // // x-direction for(int k = 1; k < grid.z+1; k++){ for(int j = 1; j < grid.y+1; j++){ rho[0][j][k] = rho[grid.x][j][k]; rho[grid.x+1][j][k] = rho[1][j][k]; } } // y-direction for(int i = 1; i < grid.x+1; i++){ for(int k = 1; k < grid.z+1; k++){ rho[i][0][k] = rho[i][grid.y][k]; rho[i][grid.y+1][k] = rho[i][1][k]; } } // z-direction for(int i = 1; i < grid.x+1; i++){ for(int j = 1; j < grid.y+1; j++){ rho[i][j][0] = 0.; rho[i][j][grid.z+1] = rho[i][j][grid.z-1]; } } }
bool LinearRegression::train(LabelledRegressionData trainingData){ const unsigned int M = trainingData.getNumSamples(); const unsigned int N = trainingData.getNumInputDimensions(); const unsigned int K = trainingData.getNumTargetDimensions(); trained = false; trainingResults.clear(); if( M == 0 ){ errorLog << "train(LabelledRegressionData trainingData) - Training data has zero samples!" << endl; return false; } if( K == 0 ){ errorLog << "train(LabelledRegressionData trainingData) - The number of target dimensions is not 1!" << endl; return false; } numFeatures = N; numOutputDimensions = 1; //Logistic Regression will have 1 output inputVectorRanges.clear(); targetVectorRanges.clear(); //Scale the training and validation data, if needed if( useScaling ){ //Find the ranges for the input data inputVectorRanges = trainingData.getInputRanges(); //Find the ranges for the target data targetVectorRanges = trainingData.getTargetRanges(); //Scale the training data trainingData.scale(inputVectorRanges,targetVectorRanges,0.0,1.0); } //Reset the weights Random rand; w0 = rand.getRandomNumberUniform(-0.1,0.1); w.resize(N); for(UINT j=0; j<N; j++){ w[j] = rand.getRandomNumberUniform(-0.1,0.1); } double error = 0; double lastError = 0; double delta = 0; UINT iter = 0; bool keepTraining = true; vector< UINT > randomTrainingOrder(M); TrainingResult result; trainingResults.reserve(M); //In most cases, the training data is grouped into classes (100 samples for class 1, followed by 100 samples for class 2, etc.) //This can cause a problem for stochastic gradient descent algorithm. To avoid this issue, we randomly shuffle the order of the //training samples. This random order is then used at each epoch. for(UINT i=0; i<M; i++){ randomTrainingOrder[i] = i; } std::random_shuffle(randomTrainingOrder.begin(), randomTrainingOrder.end()); //Run the main stochastic gradient descent training algorithm while( keepTraining ){ //Run one epoch of training using stochastic gradient descent totalSquaredTrainingError = 0; for(UINT m=0; m<M; m++){ //Select the random sample UINT i = randomTrainingOrder[m]; //Compute the error, given the current weights VectorDouble x = trainingData[i].getInputVector(); VectorDouble y = trainingData[i].getTargetVector(); double h = w0; for(UINT j=0; j<N; j++){ h += x[j] * w[j]; } error = y[0] - h; totalSquaredTrainingError += SQR( error ); //Update the weights for(UINT j=0; j<N; j++){ w[j] += learningRate * error * x[j]; } w0 += learningRate * error; } //Compute the error delta = fabs( totalSquaredTrainingError-lastError ); lastError = totalSquaredTrainingError; //Check to see if we should stop if( delta <= minChange ){ keepTraining = false; } if( isinf( totalSquaredTrainingError ) || isnan( totalSquaredTrainingError ) ){ errorLog << "train(LabelledRegressionData &trainingData) - Training failed! Total squared training error is NAN. If scaling is not enabled then you should try to scale your data and see if this solves the issue." << endl; return false; } if( ++iter >= maxNumIterations ){ keepTraining = false; } //Store the training results rootMeanSquaredTrainingError = sqrt( totalSquaredTrainingError / double(M) ); result.setRegressionResult(iter,totalSquaredTrainingError,rootMeanSquaredTrainingError); trainingResults.push_back( result ); //Notify any observers of the new training data trainingResultsObserverManager.notifyObservers( result ); trainingLog << "Epoch: " << iter << " SSE: " << totalSquaredTrainingError << " Delta: " << delta << endl; } //Flag that the algorithm has been trained regressionData.resize(1,0); trained = true; return trained; }
void CalcDivSigma () { double invDX = 1. / (12. * dx); double invDY = 1. / (12. * dy); double invDZ = 1. / (12. * dz); // double derSigmaXZ, derSigmaYZ, derSigmaZZ; double derRhoX, derRhoY, derRhoZ; double derRho2XZ, derRho2YZ, derRho2ZZ; for(int i = 2*offset; i < grid.x+1 - 2*offset; i++){ for(int j = 2*offset; j < grid.y+1 - 2*offset; j++){ for(int k = 2*offset; k < grid.z+1 - 2*offset; k++){ derSigmaXZ[i][j][k] = (-sigmaXZ[i+2][j][k] + 8.*sigmaXZ[i+1][j][k] - 8.*sigmaXZ[i-1][j][k] + sigmaXZ[i-2][j][k]) * invDX; derSigmaYZ[i][j][k] = (-sigmaYZ[i][j+2][k] + 8.*sigmaYZ[i][j+1][k] - 8.*sigmaYZ[i][j-1][k] + sigmaYZ[i][j-2][k]) * invDY; derSigmaZZ[i][j][k] = (-sigmaZZ[i][j][k+2] + 8.*sigmaZZ[i][j][k+1] - 8.*sigmaZZ[i][j][k-1] + sigmaZZ[i][j][k-2]) * invDZ; derRhoX = (-rho[i+2][j][k] + 8.*rho[i+1][j][k] - 8.*rho[i-1][j][k] + rho[i-2][j][k]) * invDX; derRhoY = (-rho[i][j+2][k] + 8.*rho[i][j+1][k] - 8.*rho[i][j-1][k] + rho[i][j-2][k]) * invDY; derRhoZ = (-rho[i][j][k+2] + 8.*rho[i][j][k+1] - 8.*rho[i][j][k-1] + rho[i][j][k-2]) * invDZ; derSigmaZZ[i][j][k] += derRhoZ * (wa[i][j][k] - sub[i][j][k] - V11 * rho[i][j][k] - W111 * SQR(rho[i][j][k]))+fZ[i][j][k]; divSigma[i][j][k] = derSigmaXZ[i][j][k] + derSigmaYZ[i][j][k] + derSigmaZZ[i][j][k]; } } } printf("calculated divergence of sigma\n"); }
/** initialize the forces for a real particle */ MDINLINE void init_local_particle_force(Particle *part) { #ifdef ADRESS double new_weight; if (ifParticleIsVirtual(part)) { new_weight = adress_wf_vector(part->r.p); #ifdef ADRESS_INIT double old_weight = part->p.adress_weight; if(new_weight>0 && old_weight==0){ double rand_cm_pos[3], rand_cm_vel[3], rand_weight, new_pos, old_pos; int it, dim, this_mol_id=part->p.mol_id, rand_mol_id, rand_type; int n_ats_this_mol=topology[this_mol_id].part.n, n_ats_rand_mol; //look for a random explicit particle rand_type=-1; rand_weight=-1; rand_mol_id=-1; n_ats_rand_mol=-1; while(rand_type != part->p.type || rand_weight != 1 || n_ats_rand_mol != n_ats_this_mol){ rand_mol_id = i_random(n_molecules); rand_type = local_particles[(topology[rand_mol_id].part.e[0])]->p.type; rand_weight = local_particles[(topology[rand_mol_id].part.e[0])]->p.adress_weight; n_ats_rand_mol = topology[rand_mol_id].part.n; if(!ifParticleIsVirtual(local_particles[(topology[rand_mol_id].part.e[0])])) fprintf(stderr,"No virtual site found on molecule %d, with %d total molecules.\n",rand_mol_id, n_molecules); } //store CM position and velocity for(dim=0;dim<3;dim++){ rand_cm_pos[dim]=local_particles[(topology[rand_mol_id].part.e[0])]->r.p[dim]; rand_cm_vel[dim]=local_particles[(topology[rand_mol_id].part.e[0])]->m.v[dim]; } //assign new positions and velocities to the atoms for(it=0;it<n_ats_this_mol;it++){ if (!ifParticleIsVirtual(local_particles[topology[rand_mol_id].part.e[it]])) { for(dim=0;dim<3;dim++){ old_pos = local_particles[topology[this_mol_id].part.e[it]]->r.p[dim]; new_pos = local_particles[topology[rand_mol_id].part.e[it]]->r.p[dim]-rand_cm_pos[dim]+part->r.p[dim]; //MAKE SURE THEY ARE IN THE SAME BOX while(new_pos-old_pos>box_l[dim]*0.5) new_pos=new_pos-box_l[dim]; while(new_pos-old_pos<-box_l[dim]*0.5) new_pos=new_pos+box_l[dim]; local_particles[(topology[this_mol_id].part.e[it])]->r.p[dim] = new_pos; local_particles[(topology[this_mol_id].part.e[it])]->m.v[dim] = local_particles[(topology[rand_mol_id].part.e[it])]->m.v[dim]-rand_cm_vel[dim]+part->m.v[dim]; } } } } #endif part->p.adress_weight=new_weight; } #endif if ( thermo_switch & THERMO_LANGEVIN ) friction_thermo_langevin(part); else { part->f.f[0] = 0; part->f.f[1] = 0; part->f.f[2] = 0; } #ifdef EXTERNAL_FORCES if(part->l.ext_flag & PARTICLE_EXT_FORCE) { part->f.f[0] += part->l.ext_force[0]; part->f.f[1] += part->l.ext_force[1]; part->f.f[2] += part->l.ext_force[2]; } #endif #ifdef ROTATION { double scale; /* set torque to zero */ part->f.torque[0] = 0; part->f.torque[1] = 0; part->f.torque[2] = 0; /* and rescale quaternion, so it is exactly of unit length */ scale = sqrt( SQR(part->r.quat[0]) + SQR(part->r.quat[1]) + SQR(part->r.quat[2]) + SQR(part->r.quat[3])); part->r.quat[0]/= scale; part->r.quat[1]/= scale; part->r.quat[2]/= scale; part->r.quat[3]/= scale; } #endif #ifdef ADRESS /** #ifdef THERMODYNAMIC_FORCE */ if(ifParticleIsVirtual(part)) if(part->p.adress_weight > 0 && part->p.adress_weight < 1) add_thermodynamic_force(part); /** #endif */ #endif }
void funcv(int n,float x[],float f[]) { f[1]=SQR(x[1])+SQR(x[2])-2.0; f[2]=exp(x[1]-1.0)+x[2]*SQR(x[2])-2.0; }
short CSpehere::isIntersect(CRay ray,double &distance) { Vec3d v = ray.origin - center; double A = ray.direction | ray.direction; double B = 2 * ( ray.direction | v ); double C = (v | v) - sqrRadius; int retval = INTERSECTION_MISS; double det = SQR(B) - 4 * A * C; //double det = SQR(B) - C; if (det > 0 ) { det = sqrtf(det); double t1 = (-B - det)/2*A; double t2 = (-B + det)/2*A; /*if (t2 > 0) { if (t1 < 0) { if (t2 < distance) { distance = t2; retval = INTERSECTION_INSIDE; } } else { if (t1 < distance) { distance = t1; retval = INTERSECTION_HIT; } } }*/ if (t1>0 && t1<distance) { distance = t1; retval = INTERSECTION_HIT; } else if (t2> 0 && t2<distance) { distance = t2; retval = INTERSECTION_INSIDE; } } distance -= 0.1; return retval; /*Vec3d v = ray.origin - center; double b = -( v | ray.direction ); double det = (b * b) - ( v | v ) + sqrRadius; int retval = INTERSECTION_MISS; if (det > 0) { det = sqrtf( det ); double i1 = b - det; double i2 = b + det; if (i2 > 0) { if (i1 < 0) { if (i2 < distance) { distance = i2; retval = INTERSECTION_INSIDE; } } else { if (i1 < distance) { distance = i1; retval = INTERSECTION_HIT; } } } } return retval;*/ }
static PyObject* func(PyObject *self, PyObject *pyargs) { NRpyArgs args(pyargs); // unpack args Doub x = NRpyDoub(args[0]); Doub y = (x != 0. ? SQR(sin(x)/x) : 1.); return NRpyObject(y); // return a single value }
double FindCut() { int i, imin = 0; double d, xmin, xmax; /* first find the margins of our binary search -> compute xmin and xmax of the polygon */ xmin = P[0].x; xmax = P[0].x; for (i = 1; i < N; i++) { if (P[i].x < xmin) { xmin = P[i].x; imin = i; } if (P[i].x > xmax) xmax = P[i].x; } /* binary search between xmin and xmax and compute the area of the part that contains the imin (left part area). * It should be equal to TotalArea/2 * Move the sweeping line towards the point with the greater area */ Point p1, p2; double l, r, x; l = xmin; r = xmax; /* a parallel line between [xmin, xmax] which splits the polygon in two * parts with same area should always exists, that's why while(true) because we break when we have ar1 == ar2 */ while (true) { x = (l + r) / 2; /* compute the equation of the line || Oy. We take two random points such as (x, 1) and (x, -1) */ double a = 2; double b = 0; double c = -2 * x; double area; ComputeCutAreas(a, b, c, area, p1, p2, imin); if (fabs(2 * area - TotalArea) < EPS) { break; } else if (2 * area > TotalArea) { r = x; } else { l = x; } } /* wow, we found a solution! */ d = sqrtl(SQR(p2.x - p1.x) + SQR(p2.y - p1.y)); return d; }
double minimumOnObject(const BallType &b) { ++calls; return std::max(0., (b.center - p).squaredNorm() - SQR(b.radius)); }