dLine Conv::line_bck(const dLine & l, double acc, int max) const { dLine ret; if (l.size()==0) return ret; dPoint P1 = l[0], P1a =P1; bck(P1a); ret.push_back(P1a); dPoint P2, P2a; for (int i=1; i<l.size(); i++){ P1 = l[i-1]; P2 = l[i]; double d = pdist(P1-P2)/(max+1)*1.5; do { P1a = P1; bck(P1a); P2a = P2; bck(P2a); dPoint C1 = (P1+P2)/2.; dPoint C1a = C1; bck(C1a); if ((pdist(C1a, (P1a+P2a)/2.) < acc) || (pdist(P1-P2) < d)){ ret.push_back(P2a); P1 = P2; P2 = l[i]; } else { P2 = C1; } } while (P1!=P2); } return ret; }
dPoint Conv::units_bck(dPoint p) const{ dPoint p1 = p + dPoint(1,0); dPoint p2 = p + dPoint(0,1); bck(p), bck(p1), bck(p2); return dPoint(pdist(p1-p), pdist(p2-p)); }
static void consolidate (EXTREMUM *plst, int nlst) { float x[3], t, dmin; int i, j, imin, jmin, k; int npair; do { printf ("peak pairs closer than %.4f mm\n", dthresh); dmin = 1.e6; npair = 0; for (i = 0; i < ntop && i < nlst; i++) {if (plst[i].killed) continue; for (j = i + 1; j < ntop && j < nlst; j++) {if (plst[j].killed) continue; t = (float) pdist (plst + i, plst + j); if (t < dthresh) { printf ("%5d%5d%10.4f\n", i + 1, j + 1, t); if (t < dmin) { imin = i; jmin = j; dmin = t; } npair++; } }} printf ("npair = %d\n", npair); if (npair) { for (k = 0; k < 3; k++) { x[k] = plst[imin].weight*plst[imin].x[k] + plst[jmin].weight*plst[jmin].x[k]; } plst[imin].weight += plst[jmin].weight; for (k = 0; k < 3; k++) plst[imin].x[k] = x[k] / plst[imin].weight; plst[jmin].killed++; npair--; } } while (npair); }
double dist(const std::valarray<double>& a, const std::valarray<double>& b) const { #ifdef DEBUG if (a.size()!=b.size()) ERROR("Vector size mismatch in distance."); #endif return pdist(&a[0],&b[0],a.size()); }
void lmoutr(double* v1, double* v2, double* v3, double* r, double *la, double *mu, double *ze) { double a[3], b[3], c[3], d[3]; double a_l=0, b_l=0, c_l=0, d_l=0; double det, det_la, det_mu, det_ze; int k; for (k=0; k<3; k++) { a[k] = r[k]-v1[k]; b[k] = v2[k]-v1[k]; c[k] = v3[k]-v1[k]; a_l += a[k]*a[k]; b_l += b[k]*b[k]; c_l += c[k]*c[k]; } a_l = sqrt(a_l); b_l = sqrt(b_l); c_l = sqrt(c_l); if (a_l==0) { /* point lies exactly on the first vertex */ *la = 0; *mu = 0; *ze = 0; return; } else if (b_l==0 || c_l==0) { /* this is a degenerate triangle, not possible to compute la/mu */ *la = mxGetNaN(); *mu = mxGetNaN(); *ze = mxGetNaN(); return; } else { /* compute vector d orthogonal to the triangle */ cross(b, c, d); d_l = pdist(d); /* normalize vector d */ d[0] = d[0]/d_l; d[1] = d[1]/d_l; d[2] = d[2]/d_l; /* solve the system of equations using Cramer's method (method of determinants) */ /* c = la*a + mu*b + ze*o */ det = determinant(b, c, d); det_la = determinant(a, c, d); det_mu = determinant(b, a, d); det_ze = determinant(b, c, a); *la = det_la/det; *mu = det_mu/det; *ze = det_ze/det; /* since d is an orthonormal vector to the plane, the distance of r */ /* to the plane equals the absolume value of parameter ze */ *ze = ((*ze)<0 ? -(*ze) : +(*ze)); } return; }
void CumulativeDtwRunner::calcBeta() { // After filling the table score_(i, j) (which is also known as alpha(i, j) in the Forward-Backward Algorithm) // , we also need to fill the table beta(i, j), which can be done by reversing the for-loop beta_.Resize(qL_, dL_); beta_.Memfill(float_inf); int q = qL_ - 1, d = dL_ - 1; #ifndef NO_HHTT beta_(qL_ - 1, dL_ -1) = 0; q = qL_ -1; for (d = dL_ - 2; d >= 0; --d) beta_(q, d) = beta_(q, d + 1) + pdist(q, d + 1); #else q = qL_ -1; for (d = 0; d < dL_; ++d) beta_(q, d) = 0; #endif d = dL_ - 1; for (q = qL_ - 2; q >= 0; --q) beta_(q, d) = beta_(q + 1, d) + pdist(q + 1, d); // interior points for (int d = dL_ - 2; d >= 0; --d) { for (int q = qL_ - 2; q >= 0; --q) { #ifndef NO_HHTT #ifdef DTW_SLOPE_CONSTRAINT if ( abs(q - d) > wndSize_ ) continue; #endif #endif double s1 = beta_(q , d+1) + pdist(q , d+1), s2 = beta_(q+1, d ) + pdist(q+1, d ), s3 = beta_(q+1, d+1) + pdist(q+1, d+1); double s = SMIN::eval(s1, s2, s3); beta_(q, d) = s; } } }
dLine Conv::line_frw(const dLine & l, double acc, int max) const { dLine ret; if (l.size()==0) return ret; dPoint P1 = l[0], P1a =P1; frw(P1a); ret.push_back(P1a); // add first point dPoint P2, P2a; for (int i=1; i<l.size(); i++){ P1 = l[i-1]; P2 = l[i]; double d = pdist(P1-P2)/(max+1)*1.5; do { P1a = P1; frw(P1a); P2a = P2; frw(P2a); // C1 - is a center of (P1-P2) // C2-C1 is a perpendicular to (P1-P2) with acc length dPoint C1 = (P1+P2)/2.; dPoint C2 = C1 + acc*pnorm(dPoint(P1.y-P2.y, -P1.x+P2.x)); dPoint C1a = C1; frw(C1a); dPoint C2a = C2; frw(C2a); if ((pdist(C1a, (P1a+P2a)/2.) < pdist(C1a,C2a)) || (pdist(P1-P2) < d)){ // go to the rest of line (P2-l[i]) ret.push_back(P2a); P1 = P2; P2 = l[i]; } else { // go to the first half (P1-C1) of current line P2 = C1; } } while (P1!=P2); } return ret; }
void CumulativeDtwRunner::CalScoreTable() { // q == 0, d == 0 score_(0, 0) = pdist(0, 0); // q == 0 for (int d = 1; d < dL_; ++d) #ifndef NO_HHTT score_(0, d) = score_(0, d - 1) + pdist(0, d); #else score_(0, d) = pdist(0, d); #endif // d == 0 for (int q = 1; q < qL_; ++q) score_(q, 0) = score_(q - 1, 0) + pdist(q, 0); // interior points for (int d = 1; d < dL_; ++d) { for (int q = 1; q < qL_; ++q) { #ifdef DTW_SLOPE_CONSTRAINT if ( abs(q - d) > wndSize_ ) continue; #endif double s1 = score_(q , d-1), s2 = score_(q-1, d ), s3 = score_(q-1, d-1); double s = SMIN::eval(s1, s2, s3) + pdist(q, d); score_(q, d) = s; } } }
// // R_PolysegCompare // // Callback for qsort to sort the segs of a polyobject. Returns such that the // closer one is sorted first. I sure hope this doesn't break anything. -Red // static int R_PolysegCompare(const void *p1, const void *p2) { const seg_t *seg1 = *(const seg_t * const *)p1; const seg_t *seg2 = *(const seg_t * const *)p2; fixed_t dist1v1, dist1v2, dist2v1, dist2v2; // TODO might be a better way to get distance? #define pdist(x, y) (FixedMul(R_PointToDist(x, y), FINECOSINE((R_PointToAngle(x, y)-viewangle)>>ANGLETOFINESHIFT))+0xFFFFFFF) #define vxdist(v) pdist(v->x, v->y) dist1v1 = vxdist(seg1->v1); dist1v2 = vxdist(seg1->v2); dist2v1 = vxdist(seg2->v1); dist2v2 = vxdist(seg2->v2); if (min(dist1v1, dist1v2) != min(dist2v1, dist2v2)) return min(dist1v1, dist1v2) - min(dist2v1, dist2v2); { // That didn't work, so now let's try this....... fixed_t delta1, delta2, x1, y1, x2, y2; vertex_t *near1, *near2, *far1, *far2; // wherever you are~ delta1 = R_PointToDist2(seg1->v1->x, seg1->v1->y, seg1->v2->x, seg1->v2->y); delta2 = R_PointToDist2(seg2->v1->x, seg2->v1->y, seg2->v2->x, seg2->v2->y); delta1 = FixedDiv(128<<FRACBITS, delta1); delta2 = FixedDiv(128<<FRACBITS, delta2); if (dist1v1 < dist1v2) { near1 = seg1->v1; far1 = seg1->v2; } else { near1 = seg1->v2; far1 = seg1->v1; } if (dist2v1 < dist2v2) { near2 = seg2->v1; far2 = seg2->v2; } else { near2 = seg2->v2; far2 = seg2->v1; } x1 = near1->x + FixedMul(far1->x-near1->x, delta1); y1 = near1->y + FixedMul(far1->y-near1->y, delta1); x2 = near2->x + FixedMul(far2->x-near2->x, delta2); y2 = near2->y + FixedMul(far2->y-near2->y, delta2); return pdist(x1, y1)-pdist(x2, y2); } #undef vxdist #undef pdist }
at::real GLineSegment2D::length() const { return pdist(p1, p2); }
at::real pdist(const at::Point& p, int x, int y) { return pdist(p, at::Point(x,y)); }
inline double dist(const double* a, const double* b, unsigned long n) { return pdist(a,b,n); }
int main (int argc, char *argv[]) { FILE *imgfp; /* input file */ FILE *outfp; /* output file */ /*************/ /* image i/o */ /*************/ char *ptr, string[MAXL], program[MAXL], command[MAXL]; char imgroot[MAXL], imgfile[MAXL], ifhfile[MAXL]; char mskroot[MAXL], mskfile[MAXL]; char tmproot[MAXL], tmpfile[MAXL]; char trailer[MAXL] = "", outroot[MAXL], outfile[MAXL], recfile[MAXL]; /***************/ /* computation */ /***************/ float *imgv, *imgr, *imgm; float v, frac, t, del2v, dmin; float fndex[3], x[3], w[3], dvdx[3], d2vdx2[3]; float ctneg = 0.0, ctpos = 0.0; float vtneg = 0.0, vtpos = 0.0; float srad = 0.0, orad = 0; int ix, iy, iz, dim, nx, ny, nz; int c, i, j, k, l, jmin; int isbig, isbigm; char control = '\0'; /**************/ /* peak lists */ /**************/ EXTREMUM *ppos, *pneg, *pall, *pallN, ptmp[1]; int mpos = 0, mneg = 0, npos = 0, nneg = 0, nall, nallN, Nvoxcrit = 1; int npos0, npos1, npos2; int nneg0, nneg1, nneg2; /*********/ /* flags */ /*********/ int mask = 0; int status = 0; int debug = 0; int quiet = 0; int forceblur = 0; printf ("%s\n", rcsid); if (!(ptr = strrchr (argv[0], '/'))) ptr = argv[0]; else ptr++; strcpy (program, ptr); /******************************/ /* get command line arguments */ /******************************/ for (k = 0, i = 1; i < argc; i++) { if (*argv[i] == '-') { strcpy (command, argv[i]); ptr = command; while (c = *ptr++) switch (c) { case 'q': quiet++; break; case 'F': forceblur++; break; case 's': srad = atof (ptr); *ptr = '\0'; break; case 'd': dthresh = atof (ptr); *ptr = '\0'; break; case 'n': ntop = atoi (ptr); *ptr = '\0'; break; case 'N': Nvoxcrit = atoi (ptr); *ptr = '\0'; break; case 'o': orad = atof (ptr); *ptr = '\0'; break; case '@': control = *ptr++; *ptr = '\0'; break; case 'c': getrange (ptr, &ctneg, &ctpos); *ptr = '\0'; break; case 'v': getrange (ptr, &vtneg, &vtpos); *ptr = '\0'; break; case 'm': getroot (ptr, mskroot); mask++; *ptr = '\0'; break; case 'a': strncpy (trailer, ptr, MAXL - 1); *ptr = '\0'; break; } } else switch (k) { case 0: getroot (argv[i], imgroot); k++; break; } } if (k < 1) { printf ("Usage: %s <file_4dfp>\n", program); printf (" e.g., %s grand_average_222[.4dfp.img] -s10\n", program); printf ("\toption\n"); printf ("\t-s<flt>\tpreblur with hard sphere kernel of specified radius\n"); printf ("\t-n<int>\tlimit initial pos and neg peak list lengths (default=%d)\n", NTOP); printf ("\t-c<flt>[to<flt>] specify sign inverted curvature thresholds (default none)\n"); printf ("\t-v<flt>[to<flt>] specify peak value thresholds (default none)\n"); printf ("\t-d<flt>\tconsolidate extremum pairs closer than specified distance\n"); printf ("\t-o<flt>\toutput a fidl compatible 4dfp format ROI file with regions of specified radius\n"); printf ("\t-m<str>\tapply named mask file to output ROIs\n"); printf ("\t-N<int>\tspecify output ROI minimum voxel count (default = 1)\n"); printf ("\t-a<str>\tappend specified string to ROI output filename\n"); printf ("\t-q\tquiet mode (suppress rec file listing)\n"); printf ("\t-F\tforce preblur image creation even if hsphere_4dfp result exists\n"); printf ("\t-@<b|l>\toutput big or little endian (default input endian)\n"); printf ("N.B.:\toperations controlled by options -s, -n, -c, -v, -d, -o, -m, -N are applied serially in listed order\n"); printf ("N.B.:\tall distances are in mm\n"); printf ("N.B.:\toption -s<flt> creates a blurred image by invoking hsphere_4dfp\n"); printf ("N.B.:\toption -F is intended for use in iterative scripts and has no effect absent -s<flt>\n"); exit (1); } /************/ /* read ifh */ /************/ sprintf (imgfile, "%s.4dfp.img", imgroot); if (srad > 0.0) { sprintf (tmproot, "%s_%.0fmm", imgroot, srad); } else { strcpy (tmproot, imgroot); } sprintf (tmpfile, "%s.4dfp.img", tmproot); sprintf (ifhfile, "%s.4dfp.ifh", imgroot); fprintf (stdout, "Reading: %s\n", ifhfile); if (Getifh (ifhfile, &imgifh)) errr (program, ifhfile); isbig = strcmp (imgifh.imagedata_byte_order, "littleendian"); if (!control) control = (isbig) ? 'b' : 'l'; printf ("image dimensions \t%10d%10d%10d%10d\n", imgifh.matrix_size[0], imgifh.matrix_size[1], imgifh.matrix_size[2], imgifh.matrix_size[3]); printf ("image mmppix \t%10.6f%10.6f%10.6f\n", imgifh.mmppix[0], imgifh.mmppix[1], imgifh.mmppix[2]); printf ("image center \t%10.4f%10.4f%10.4f\n", imgifh.center[0], imgifh.center[1], imgifh.center[2]); printf ("image orientation\t%10d\n", imgifh.orientation); /********************************************************************/ /* check that optionally specified mask is dimensionally consistent */ /********************************************************************/ if (mask) { sprintf (mskfile, "%s.4dfp.img", mskroot); sprintf (ifhfile, "%s.4dfp.ifh", mskroot); fprintf (stdout, "Reading: %s\n", ifhfile); if (Getifh (ifhfile, &mskifh)) errr (program, ifhfile); isbigm = strcmp (mskifh.imagedata_byte_order, "littleendian"); status = imgifh.orientation - mskifh.orientation; for (k = 0; k < 3; k++) { status |= imgifh.matrix_size[k] - mskifh.matrix_size[k]; status |= (fabs ((double) (imgifh.mmppix[k] - mskifh.mmppix[k])) > 0.0001); } if (status) { fprintf (stderr, "%s: %s %s dimension mismatch\n", program, imgroot, mskroot); exit (-1); } } dim = 1; for (k = 0; k < 3; k++) dim *= imgifh.matrix_size[k]; if (!(imgv = (float *) malloc (dim * sizeof (float)))) errm (program); if (!(imgr = (float *) malloc (dim * sizeof (float)))) errm (program); if (!(imgm = (float *) malloc (dim * sizeof (float)))) errm (program); nx = imgifh.matrix_size[0]; ny = imgifh.matrix_size[1]; nz = imgifh.matrix_size[2]; /*****************************************/ /* virtual flip instead of x4dfp2ecat () */ /*****************************************/ vrtflip_ (&imgifh.orientation, imgifh.matrix_size, imgifh.center, imgifh.mmppix, centerr, mmppixr); printf ("atlas mmppix \t%10.6f%10.6f%10.6f\n", mmppixr[0], mmppixr[1], mmppixr[2]); printf ("atlas center \t%10.4f%10.4f%10.4f\n", centerr[0], centerr[1], centerr[2]); /****************************************************/ /* read filtered image or create using hpshere_4dfp */ /****************************************************/ if (forceblur || access (tmpfile, R_OK)) { sprintf (command, "hsphere_4dfp %s %.4f", imgfile, srad); printf ("%s\n", command); if (system (command)) errw (program, tmpfile); } printf ("Reading: %s\n", tmpfile); if (!(imgfp = fopen (tmpfile, "rb")) || eread (imgv, dim, isbig, imgfp) || fclose (imgfp)) errr (program, tmpfile); /************************************************************************************************/ /* intial extremum memory allocation (realloc on unassigned pointer => unpredictable core dump) */ /************************************************************************************************/ if (!(ppos = (EXTREMUM *) malloc ((mpos = MSIZE) * sizeof (EXTREMUM)))) errm (program); if (!(pneg = (EXTREMUM *) malloc ((mneg = MSIZE) * sizeof (EXTREMUM)))) errm (program); /*******************/ /* compile extrema */ /*******************/ printf ("peak value thresholds %10.4f to %10.4f\n", vtneg, vtpos); printf ("peak curvature thresholds %10.4f to %10.4f\n", ctneg, ctpos); printf ("compiling extrema slice"); for (iz = 1; iz < imgifh.matrix_size[2] - 1; iz++) {printf (" %d", iz + 1); fflush (stdout); for (iy = 1; iy < imgifh.matrix_size[1] - 1; iy++) { for (ix = 1; ix < imgifh.matrix_size[0] - 1; ix++) { i = ix + nx*(iy + ny*iz); dvdx[0] = 0.5*(-imgv[i - 1] + imgv[i + 1]); dvdx[1] = 0.5*(-imgv[i - nx] + imgv[i + nx]); dvdx[2] = 0.5*(-imgv[i - nx*ny] + imgv[i + nx*ny]); d2vdx2[0] = -2.0*imgv[i] + imgv[i - 1] + imgv[i + 1]; d2vdx2[1] = -2.0*imgv[i] + imgv[i - nx] + imgv[i + nx]; d2vdx2[2] = -2.0*imgv[i] + imgv[i - nx*ny] + imgv[i + nx*ny]; for (k = 0; k < 3; k++) w[k] = -dvdx[k] / d2vdx2[k]; for (del2v = k = 0; k < 3; k++) del2v += d2vdx2[k] / (mmppixr[k] * mmppixr[k]); fndex[0] = (float) (ix + 1) + w[0]; fndex[1] = (float) (iy + 1) + w[1]; fndex[2] = (float) (iz + 1) + w[2]; for (k = 0; k < 3; k++) x[k] = fndex[k] * mmppixr[k] - centerr[k]; if (imgv[i] > 0.0 && del2v <= -ctpos && imgv[i] > imgv[i - 1] && imgv[i] > imgv[i + 1] && imgv[i] > imgv[i - nx] && imgv[i] > imgv[i + nx] && imgv[i] > imgv[i - nx*ny] && imgv[i] > imgv[i + nx*ny]) { imgvalx_ (imgv, &nx, &ny, &nz, centerr, mmppixr, x, &t, &l); if (l < 1) {printf ("undefined imgvalx point\n"); continue;} if (t < vtpos) continue; if (mpos <= npos) { mpos += MSIZE; if (!(ppos = (EXTREMUM *) realloc (ppos, mpos * sizeof (EXTREMUM)))) errm (program); } for (k = 0; k < 3; k++) ppos[npos].x[k] = x[k]; ppos[npos].v = t; ppos[npos].del2v = del2v; ppos[npos].weight = 1.0; ppos[npos].nvox = ppos[npos].killed = 0; npos++; } if (imgv[i] < 0.0 && del2v >= -ctneg && imgv[i] < imgv[i - 1] && imgv[i] < imgv[i + 1] && imgv[i] < imgv[i - nx] && imgv[i] < imgv[i + nx] && imgv[i] < imgv[i - nx*ny] && imgv[i] < imgv[i + nx*ny]) { imgvalx_ (imgv, &nx, &ny, &nz, centerr, mmppixr, x, &t, &l); if (l < 1) {printf ("undefined imgvalx point\n"); continue;} if (t > vtneg) continue; if (mneg <= nneg) { mneg += MSIZE; if (!(pneg = (EXTREMUM *) realloc (pneg, mneg * sizeof (EXTREMUM)))) errm (program); } for (k = 0; k < 3; k++) pneg[nneg].x[k] = x[k]; pneg[nneg].v = t; pneg[nneg].del2v = del2v; pneg[nneg].weight = 1.0; pneg[nneg].nvox = pneg[nneg].killed = 0; nneg++; } }}} printf ("\n"); fflush (stdout); printf ("before sorting npos=%d nneg=%d\n", npos, nneg); npos0 = npos; nneg0 = nneg; qsort ((void *) ppos, npos, sizeof (EXTREMUM), pcompare); qsort ((void *) pneg, nneg, sizeof (EXTREMUM), pcompare); printf ("positive peaks\n"); ntot = 0; peaklist (stdout, ppos, npos, 0); npos1 = ntot; if (dthresh > 0.0) consolidate (ppos, npos); printf ("negative peaks\n"); ntot = 0; peaklist (stdout, pneg, nneg, 0); nneg1 = ntot; if (dthresh > 0.0) consolidate (pneg, nneg); printf ("final peak list\n"); ntot = 0; peaklist (stdout, ppos, npos, 0); peaklist (stdout, pneg, nneg, 0); /********************************************/ /* combine positive and negative peak lists */ /********************************************/ if (!(pall = (EXTREMUM *) malloc (ntot * sizeof (EXTREMUM)))) errm (program); nall = 0; for (npos2 = i = 0; i < ntop && i < npos; i++) if (!ppos[i].killed) {pall[nall++] = ppos[i]; npos2++;} for (nneg2 = i = 0; i < ntop && i < nneg; i++) if (!pneg[i].killed) {pall[nall++] = pneg[i]; nneg2++;} assert (ntot == nall); free (ppos); free (pneg); if (orad == 0.0) goto DONE; /***************************/ /* create output ROI image */ /***************************/ printf ("Reading: %s\n", imgfile); if (!(imgfp = fopen (imgfile, "rb")) || eread (imgv, dim, isbig, imgfp) || fclose (imgfp)) errr (program, imgfile); if (mask) { printf ("Reading: %s\n", mskfile); if (!(imgfp = fopen (mskfile, "rb")) || eread (imgm, dim, isbigm, imgfp) || fclose (imgfp)) errr (program, mskfile); } /****************************/ /* count voxels in each ROI */ /****************************/ for (iz = 0; iz < imgifh.matrix_size[2]; iz++) { for (iy = 0; iy < imgifh.matrix_size[1]; iy++) { for (ix = 0; ix < imgifh.matrix_size[0]; ix++) { i = ix + nx*(iy + ny*iz); fndex[0] = (float) (ix + 1); fndex[1] = (float) (iy + 1); fndex[2] = (float) (iz + 1); for (k = 0; k < 3; k++) ptmp[0].x[k] = fndex[k]*mmppixr[k] - centerr[k]; dmin = 1.e6; for (j = 0; j < nall; j++) { t = (float) pdist (ptmp, pall + j); if (t < dmin) { jmin = j; dmin = t; } } k = !mask || (fabs (imgm[i]) > 1.e-37); if (k && (dmin < orad)) pall[jmin].nvox++; }}} /*******************************/ /* apply voxel count criterion */ /*******************************/ for (i = 0; i < ntot; i++) if (pall[i].nvox < Nvoxcrit) pall[i].killed = 1; if (!(pallN = (EXTREMUM *) malloc (ntot * sizeof (EXTREMUM)))) errm (program); for (nallN = i = 0; i < ntot; i++) if (!pall[i].killed) pallN[nallN++] = pall[i]; free (pall); printf ("creating ROI slice"); for (iz = 0; iz < imgifh.matrix_size[2]; iz++) {printf (" %d", iz + 1); fflush (stdout); for (iy = 0; iy < imgifh.matrix_size[1]; iy++) { for (ix = 0; ix < imgifh.matrix_size[0]; ix++) { i = ix + nx*(iy + ny*iz); imgr[i] = 0.0; fndex[0] = (float) (ix + 1); fndex[1] = (float) (iy + 1); fndex[2] = (float) (iz + 1); for (k = 0; k < 3; k++) ptmp[0].x[k] = fndex[k]*mmppixr[k] - centerr[k]; dmin = 1.e6; for (j = 0; j < nallN; j++) { t = (float) pdist (ptmp, pallN + j); if (t < dmin) { jmin = j; dmin = t; } } k = !mask || (fabs (imgm[i]) > 1.e-37); if (k && (dmin < orad)) imgr[i] = jmin + 2; }}} printf ("\n"); fflush (stdout); if (!(ptr = strrchr (imgroot, '/'))) ptr = imgroot; else ptr++; if (strlen (trailer)) { sprintf (outroot, "%s_ROI_%s", ptr, trailer); } else { sprintf (outroot, "%s_ROI", ptr); } sprintf (outfile, "%s.4dfp.img", outroot); printf ("Writing: %s\n", outfile); if (!(outfp = fopen (outfile, "wb")) || ewrite (imgr, dim, control, outfp) || fclose (outfp)) errw (program, outfile); /********************************************/ /* output ROI ifh and make analyze hdr file */ /********************************************/ if (Writeifh (program, outfile, &imgifh, control)) errw (program, outroot); sprintf (outfile, "%s.4dfp.ifh", outroot); if (!(outfp = fopen (outfile, "a"))) errw (program, outfile); for (i = 0; i < nallN; i++) { fprintf (outfp, "region names\t:= %-5droi_%+03d_%+03d_%+03d%10d\n", i, nint (pallN[i].x[0]), nint (pallN[i].x[1]), nint (pallN[i].x[2]), pallN[i].nvox); } fclose (outfp); /********************/ /* make analyze hdr */ /********************/ sprintf (command, "ifh2hdr %s -r%d", outroot, nallN + 1); printf ("%s\n", command); status |= system (command); /******************/ /* output ROI rec */ /******************/ sprintf (outfile, "%s.4dfp.img", outroot); startrece (outfile, argc, argv, rcsid, control); sprintf (recfile, "%s.rec", outfile); if (!(outfp = fopen (recfile, "a"))) errw (program, recfile); fprintf (outfp, "Peak value thresholds %10.4f to %10.4f\n", vtneg, vtpos); fprintf (outfp, "Peak curvature thresholds %10.4f to %10.4f\n", ctneg, ctpos); fprintf (outfp, "Peak counts before sorting pos=%d neg=%d\n", npos0, nneg0); fprintf (outfp, "Peak counts after sorting pos=%d neg=%d\n", npos1, nneg1); fprintf (outfp, "Peak counts after %.4f mm threshold consolidation pos=%d neg=%d\n", dthresh, npos2, nneg2); ntot = 0; peaklist (outfp, pallN, nallN, 1); free (pallN); fprintf (outfp, "N.B.: indices count from 1 and include orientation specific 4dfptoanalyze flips\n"); fclose (outfp); catrec (tmpfile); if (mask) catrec (mskfile); endrec (); sprintf (command, "brec %s -2", recfile); if (!quiet) system (command); DONE: free (imgv); free (imgr); free (imgm); exit (status); }
int main(int argc, char* argv[]) { // Number of threads unsigned int n_threads = boost::thread::hardware_concurrency(); std::cout << "Number of available threads " << n_threads << std::endl; likelihood l(5, 5, 9); double nexp[5][5] = {{1., 1.6, 0.6, 0.2, 0.0}, {0., 15.4, 2.3, 0.0, 0.0}, {0., 2.5, 4.1, 0.0, 0.0}, {0., 3.3, 0.0, 1.1, 0.0}, {0., 9.5, 10.0, 0.7, 39.2}}; std::cout << "n(regions) = " << l.nr() << ", n(processes) = " << l.np() << ", n(systematics) = " << l.ns() << std::endl; for (unsigned int ir = 0; ir < l.nr(); ir++) for (unsigned int ip = 0; ip < l.np(); ip++) { l.set_nexp(ir, ip, nexp[ir][ip]); for (unsigned int is = 0; is < l.ns(); is++) { double dsyst = 0.; if (is < 2 && ip != 4) // Jet/MET dsyst = (0.1 - 0.05 * is) * (1. + ir * 0.05); else if (is < 7 && (is - 2 == ip)) // Theory dsyst = (ip == 4) ? 1. : 0.5; else if (is == 7 && (ir == 1 || ir == 2)) // b-tagging dsyst = (-1. + (ir - 1) * 2.) * 0.1; else if (is == 8) // Photon id efficiency dsyst = 0.05; l.set_dsyst(ir, ip, is, dsyst); } } // Setup minimizer unsigned int nparams = l.np()+l.ns(); boost::scoped_array<double> p0(new double[nparams]); boost::scoped_array<double> popt(new double[nparams]); for (unsigned int i = 0; i < nparams; i++) p0[i] = (i < l.np()) ? 1. : 0.; boost::function<double (double * const)> feval; feval = boost::bind(&likelihood::eval, &l, _1); optimize::minimizer_nm mle_nm(feval, l.np()+l.ns()); optimize::minimizer_bfgs mle_bfgs(feval, l.np()+l.ns()); // Setup random generation of poisson distributed numbers boost::mt19937 gen; typedef boost::poisson_distribution<unsigned int> t_poisson; typedef boost::scoped_ptr< t_poisson > t_ptr_poisson; typedef boost::variate_generator< boost::mt19937&, t_poisson > t_gen; typedef boost::scoped_ptr< t_gen > t_ptr_gen; boost::scoped_array< t_ptr_poisson > pdist(new t_ptr_poisson[l.nr()]); boost::scoped_array< t_ptr_gen > rndgen(new t_ptr_gen[l.ns()]); for (unsigned int ir = 0; ir < l.nr(); ir++) { std::cout << "region" << ir << " nexp = " << l.nexp(ir, p0.get()) << std::endl; pdist[ir].reset(new t_poisson(l.nexp(ir, p0.get()))); rndgen[ir].reset(new t_gen(gen, *(pdist[ir]))); } boost::timer time_monitor; double dt[3] = {0., 0., 0.}; unsigned int ntoys = 10; for (unsigned int iexp = 0; iexp < ntoys; iexp++) { std::cout << "Starting experiment " << iexp << std::endl; // Generate pseudo-experiment random numbers for (unsigned int ir = 0; ir < l.nr(); ir++) { l.set_nobs(ir, (*(rndgen[ir]))()); std::cout << " region" << ir << " nobs = " << l.nobs(ir) << " nexp = " << l.nexp(ir, p0.get()) << std::endl; } std::cout << " Perform a minimization " << std::endl; // Minimize with Nelder-Mean without mt mle_nm.set_is_mt(false); time_monitor.restart(); mle_nm.minimize(p0.get()); dt[0] = time_monitor.elapsed(); std::cout << " min = ("; for (size_t i = 0; i < nparams; i++) popt[i] = mle_nm.get_opt_var(i).value(); for (size_t i = 0; i < nparams; i++) { if (i < l.nr()) std::cout << l.nexp(i, popt.get()); else std::cout << mle_nm.get_opt_var(i).value(); if (i < nparams - 1) std::cout << ", "; } std::cout << ") fmin = " << mle_nm.get_fmin() << std::endl; // Minimize with Nelder-Mean with mt mle_nm.set_is_mt(true); time_monitor.restart(); mle_nm.minimize(p0.get()); dt[1] = time_monitor.elapsed(); std::cout << " min = ("; for (size_t i = 0; i < nparams; i++) popt[i] = mle_nm.get_opt_var(i).value(); for (size_t i = 0; i < nparams; i++) { if (i < l.nr()) std::cout << l.nexp(i, popt.get()); else std::cout << mle_nm.get_opt_var(i).value(); if (i < nparams - 1) std::cout << ", "; } std::cout << ") fmin = " << mle_nm.get_fmin() << std::endl; // Minimize with BFGS time_monitor.restart(); mle_bfgs.minimize(p0.get()); dt[2] = time_monitor.elapsed(); std::cout << " min = ("; for (size_t i = 0; i < nparams; i++) popt[i] = mle_bfgs.get_opt_var(i).value(); for (size_t i = 0; i < nparams; i++) { if (i < l.nr()) std::cout << l.nexp(i, popt.get()); else std::cout << mle_bfgs.get_opt_var(i).value(); if (i < nparams - 1) std::cout << ", "; } std::cout << ") fmin = " << mle_bfgs.get_fmin() << std::endl; std::cout << " timing " << dt[0] << " " << dt[1] << " " << dt[2] << std::endl; std::cout << " ... done." << std::endl; } return 0; }
void YARPFineOrientation::Apply(YARPImageOf<YarpPixelBGR>& src, YARPImageOf<YarpPixelBGR>& dest, YARPImageOf<YarpPixelFloat>& xdata, YARPImageOf<YarpPixelFloat>& ydata, YARPImageOf<YarpPixelFloat>& mdata) { int view = (dest.GetWidth()>0); YARPImageOf<YarpPixelFloat>& orient = fine_orientation_data.Orient(); static YARPImageOf<YarpPixelMono> mask; static IntegralImageTool ii; if (view) { SatisfySize(src,dest); } for (int i=0;i<SHIFTS;i++) { SatisfySize(src,shifts[i]); } SatisfySize(src,mean); static int shifts_x[SHIFTS], shifts_y[SHIFTS]; int ct = 0; for (int dx=-1; dx<=2; dx++) { for (int dy=-1; dy<=2; dy++) { assert(ct<SHIFTS); ii.Offset(src,shifts[ct],dx,dy,1); shifts_x[ct] = dx; shifts_y[ct] = dy; ct++; } } static YARPImageOf<YarpPixelFloat> mean, var, lx, ly, agree; YARPImageOf<YarpPixelBGR>& mono = src; SatisfySize(mono,mean); SatisfySize(mono,var); SatisfySize(mono,lx); SatisfySize(mono,ly); SatisfySize(mono,agree); SatisfySize(mono,xdata); SatisfySize(mono,ydata); SatisfySize(mono,mdata); int response_ct = 0; IMGFOR(mono,x,y) { float total = 0; float total2 = 0; YarpPixelBGR& pix0 = src(x,y); for (int k=0; k<SHIFTS; k++) { YarpPixelBGR& pix1 = shifts[k](x,y); float v = pdist(pix0,pix1); total += v; #ifdef USE_LUMINANCE_FILTER total2 += v*v; #endif } mean(x,y) = total/SHIFTS; #ifdef USE_LUMINANCE_FILTER var(x,y) = total2/SHIFTS - (total/SHIFTS)*(total/SHIFTS); #endif }