void inipotential (int *npar, double par[], char *name) { int n; n = *npar; if (n>0) omega = par[0]; /* standard pattern speed */ if (n>1) iscale = par[1]; /* scaling factor applied to potential */ if (n>2) { /* alternate definition of center pixel */ xcen = par[2]; if (n>3) ycen = par[3]; else ycen = xcen; } if (n>4) { /* alternate definition of pixel size */ dx = par[4]; if (n>5) dy = par[5]; else dy = dx; } if (n>6) warning("inipotential(ccd): npar=%d only 6 parameter accepted",n); /* set some easy to use booleans */ Qcen = n>2; /* if a new center was defined via parameters */ Qdel = n>4; /* if a new pixel size was defined via parameters */ dprintf(1,"INIPOTENTIAL: %s: %s\n",CCD_VERSION,name); dprintf(1," Parameters: Omega=%g iscale=%g xcen,ycen=%g,%g dx,dy=%g,%g\n", omega,iscale,xcen,ycen,dx,dy); potstr = stropen (name, "r"); /* open the image */ read_image (potstr,&iptr); /* read the image */ if (iscale != 1.0) { int i,j; for (j=0; j<Ny(iptr); j++) for (i=0; i<Nx(iptr); i++) MapValue(iptr,i,j) = MapValue(iptr,i,j) * iscale; } nx = Nx(iptr); ny = Ny(iptr); if (!Qdel) { dx = Dx(iptr); dy = Dy(iptr); } idx = 1.0/dx; idy = 1.0/dy; if (!Qcen) { xmin = Xmin(iptr); ymin = Ymin(iptr); } else { xmin = -xcen*dx; ymin = -ycen*dy; } if (idx != idy) { if (idx == -idy && xmin == -ymin) { /* try and patch it */ idx = -idx; xmin = -xmin; warning("Astronomical coordinate convention assumed"); } else warning("Possible bug when using dx != dy"); } if (idx<0) warning("1/Dx=%f",idx); if (idy<0) warning("1/Dy=%f",idy); xmax = xmin + nx * dx; /* pixel centers */ ymax = ymin + ny * dy; dprintf(1,"Offset and scale factors: xmin,ymin,1/dx,1/dy=%f %f %f %f\n", xmin,ymin,idx,idy); dprintf(1,"Formal full pixel X-range: %g %g\n",xmin-0.5*dx,xmax+0.5*dx); dprintf(1,"Formal full pixel Y-range: %g %g\n",ymin-0.5*dy,ymax+0.5*dy); dprintf(1,"Ranges: %g %g %g %g\n",xmin,xmax,ymin,ymax); par[0] = omega; }
void nemo_main() { stream instr, outstr; real tsnap, dr, aux, t0, dt; string times; Body *btab = NULL, *bp, *bq; int i, j, k, n, nbody, bits, nopt, ParticlesBit, ntime; char fmt[20],*pfmt; string *burststring(), *opt; rproc btrtrans(), fopt[MAXOPT]; imageptr iptr = NULL; bool Qfirst = getbparam("first"); ParticlesBit = (MassBit | PhaseSpaceBit | PotentialBit | AccelerationBit | AuxBit | KeyBit | DensBit | EpsBit); instr = stropen(getparam("in"), "r"); outstr = stropen(getparam("out"), "w"); opt = burststring(getparam("options"),", "); nopt = 0; /* count options */ while (opt[nopt]) { /* scan through options */ fopt[nopt] = btrtrans(opt[nopt]); nopt++; if (nopt==MAXOPT) { dprintf(0,"\n\nMaximum number of options = %d exhausted\n",MAXOPT); break; } } times = getparam("times"); ntime = (hasvalue("ntime") ? getiparam("ntime") : 1); for(;;) { /* repeating until first or all times are read */ get_history(instr); if (!get_tag_ok(instr, SnapShotTag)) break; /* done with work */ get_snap(instr, &btab, &nbody, &tsnap, &bits); if (!streq(times,"all") && !within(tsnap,times,0.0001)) continue; /* skip work on this snapshot */ if ( (bits & ParticlesBit) == 0) continue; /* skip work, only diagnostics here */ dprintf(1,"Time=%g\n",tsnap); if (iptr == NULL) { create_cube(&iptr,nbody,nopt,ntime); k=0; t0 = tsnap; if (k==0) dt = 0.0; } if (k==1) dt=tsnap-t0; /* should be good for the whole snapshot */ for (j=0; j<nopt; j++) { for (bp = btab, i=0; bp < btab+nbody; bp++, i++) { CubeValue(iptr,i,j,k) = fopt[j](bp,tsnap,i); } } k++; if (k==ntime) { /* cube is full */ fixheader(iptr,getparam("options"),t0,dt); write_image(outstr,iptr); free_image(iptr); iptr = NULL; k = 0; if (Qfirst) break; } } if (!Qfirst && k) { warning("k=%d something not written yet, possible trailing garbage written",k); fixheader(iptr,getparam("options"),t0,dt); write_image(outstr,iptr); } strclose(instr); strclose(outstr); }
/* * Stream a pipe/FIFO. * The FIFOCONNLD flag is used when CONNLD has been pushed on the stream. * If the flag is set, a new vnode is created by calling fifo_connld(). * Connld logic was moved to fifo_connld() to speed up the open * operation, simplify the connld/fifo interaction, and remove inherent * race conditions between the connld module and fifos. * This routine is single threaded for two reasons. * 1) connld requests are synchronous; that is, they must block * until the server does an I_RECVFD (oh, well). Single threading is * the simplest way to accomplish this. * 2) fifo_close() must not send M_HANGUP or M_ERROR while we are * in stropen. Stropen() has a tendency to reset things and * we would like streams to remember that a hangup occurred. */ int fifo_stropen(vnode_t **vpp, int flag, cred_t *crp, int dotwist, int lockheld) { int error = 0; vnode_t *oldvp = *vpp; fifonode_t *fnp = VTOF(*vpp); dev_t pdev = 0; int firstopen = 0; fifolock_t *fn_lock; fn_lock = fnp->fn_lock; if (!lockheld) mutex_enter(&fn_lock->flk_lock); ASSERT(MUTEX_HELD(&fnp->fn_lock->flk_lock)); /* * FIFO is in the process of opening. Wait for it * to complete before starting another open on it * This prevents races associated with connld open */ while (fnp->fn_flag & FIFOOPEN) { if (!cv_wait_sig(&fnp->fn_wait_cv, &fn_lock->flk_lock)) { fifo_cleanup(oldvp, flag); if (!lockheld) mutex_exit(&fn_lock->flk_lock); return (EINTR); } } /* * The other end of the pipe is almost closed so * reject any other open on this end of the pipe * This only happens with a pipe mounted under namefs */ if ((fnp->fn_flag & (FIFOCLOSE|ISPIPE)) == (FIFOCLOSE|ISPIPE)) { fifo_cleanup(oldvp, flag); cv_broadcast(&fnp->fn_wait_cv); if (!lockheld) mutex_exit(&fn_lock->flk_lock); return (ENXIO); } fnp->fn_flag |= FIFOOPEN; /* * can't allow close to happen while we are * in the middle of stropen(). * M_HANGUP and M_ERROR could leave the stream in a strange state */ while (fn_lock->flk_ocsync) cv_wait(&fn_lock->flk_wait_cv, &fn_lock->flk_lock); fn_lock->flk_ocsync = 1; if (fnp->fn_flag & FIFOCONNLD) { /* * This is a reopen, so we should release the fifo lock * just in case some strange module pushed on connld * has some odd side effect. * Note: this stropen is on the oldvp. It will * have no impact on the connld vp returned and * strclose() will only be called when we release * flk_ocsync */ mutex_exit(&fn_lock->flk_lock); if ((error = stropen(oldvp, &pdev, flag, crp)) != 0) { mutex_enter(&fn_lock->flk_lock); fifo_cleanup(oldvp, flag); fn_lock->flk_ocsync = 0; cv_broadcast(&fn_lock->flk_wait_cv); goto out; } /* * streams open done, allow close on other end if * required. Do this now.. it could * be a very long time before fifo_connld returns. */ mutex_enter(&fn_lock->flk_lock); /* * we need to fake an open here so that if this * end of the pipe closes, we don't loose the * stream head (kind of like single threading * open and close for this end of the pipe) * We'll need to call fifo_close() to do clean * up in case this end of the pipe was closed * down while we were in fifo_connld() */ ASSERT(fnp->fn_open > 0); fnp->fn_open++; fn_lock->flk_ocsync = 0; cv_broadcast(&fn_lock->flk_wait_cv); mutex_exit(&fn_lock->flk_lock); /* * Connld has been pushed onto the pipe * Create new pipe on behalf of connld */ if (error = fifo_connld(vpp, flag, crp)) { (void) fifo_close(oldvp, flag, 1, 0, crp, NULL); mutex_enter(&fn_lock->flk_lock); goto out; } /* * undo fake open. We need to call fifo_close * because some other thread could have done * a close and detach of the named pipe while * we were in fifo_connld(), so * we want to make sure the close completes (yuk) */ (void) fifo_close(oldvp, flag, 1, 0, crp, NULL); /* * fifo_connld has changed the vp, so we * need to re-initialize locals */ fnp = VTOF(*vpp); fn_lock = fnp->fn_lock; mutex_enter(&fn_lock->flk_lock); } else { /* * release lock in case there are modules pushed that * could have some strange side effect */ mutex_exit(&fn_lock->flk_lock); /* * If this is the first open of a fifo (dotwist * will be non-zero) we will need to twist the queues. */ if (oldvp->v_stream == NULL) firstopen = 1; /* * normal open of pipe/fifo */ if ((error = stropen(oldvp, &pdev, flag, crp)) != 0) { mutex_enter(&fn_lock->flk_lock); fifo_cleanup(oldvp, flag); ASSERT(fnp->fn_open != 0 || oldvp->v_stream == NULL); fn_lock->flk_ocsync = 0; cv_broadcast(&fn_lock->flk_wait_cv); goto out; } mutex_enter(&fn_lock->flk_lock); /* * twist the ends of the fifo together */ if (dotwist && firstopen) strmate(*vpp, *vpp); /* * Show that this open has succeeded * and allow closes or other opens to proceed */ fnp->fn_open++; fn_lock->flk_ocsync = 0; cv_broadcast(&fn_lock->flk_wait_cv); } out: fnp->fn_flag &= ~FIFOOPEN; if (error == 0) { fnp->fn_flag |= FIFOISOPEN; /* * If this is a FIFO and has the close flag set * and there are now writers, clear the close flag * Note: close flag only gets set when last writer * on a FIFO goes away. */ if (((fnp->fn_flag & (ISPIPE|FIFOCLOSE)) == FIFOCLOSE) && fnp->fn_wcnt > 0) fnp->fn_flag &= ~FIFOCLOSE; } cv_broadcast(&fnp->fn_wait_cv); if (!lockheld) mutex_exit(&fn_lock->flk_lock); return (error); }
void nemo_main() { string *sp; /* string pointer for output of burststring */ int nsp; /* number of tokens in sp after using burststring */ double magj,magh,magks; /* JHKs magnitudes */ double sigmaj,sigmah,sigmaks; /* JHKs uncertainties in magnitudes */ double sum_jh,sum_jh2; /* Sums for J-H weighted averages */ double sum_hks,sum_hks2; /* Sums for H-Ks weighted averages */ double w_jh,w_hks,w_jhhks; /* sums of weights for J-H,H-Ks, and covariance */ double w_jh2,w_hks2,w_jhhks2; /* sums of square of weights for J-H,H-Ks, and cov. */ double sum_jhhks; /* for covariance matrix */ double sum_jhalt,sum_hksalt; /* for covariance matrix */ double tmp1,tmp2,tmp3; /* temp variables */ double avg_jh,avg_hks; /* average values of J-H,H-Ks */ double std_jh,std_hks; /* Std. deviations of J-H,H-Ks*/ double cov; /* covariance of J-H and H-Ks */ double no_jh,no_hks,no_jhhks; /* unweighted sums */ double no_jh2,no_hks2; /* unweighted sums */ int num; /* number of sources read */ stream fp; /* File pointer */ char line[MAX_LINELEN]; /* Character string for reading from file */ /* Initialize variables */ sum_jh = 0; sum_jh2 = 0; sum_hks = 0; sum_hks2 = 0; sum_jhhks = 0; sum_jhalt = 0; sum_hksalt= 0; w_jh = 0; w_hks = 0; w_jhhks = 0; w_jh2 = 0; w_hks2 = 0; w_jhhks2 = 0; num = 0; no_jh = 0; no_hks = 0; no_jhhks = 0; no_jh2 = 0; no_hks2 = 0; fp = stropen(getparam("in"),"r"); while (fgets(line,MAX_LINELEN,fp)){ if (line[0] != '#'){ /* lines starting with # are comments */ sp = burststring(line," \t\n"); nsp = xstrlen(sp,sizeof(string))-1; if (nsp < 8) warning("Skipping line: %s",line); magj = natof(sp[2]); sigmaj = natof(sp[3]); magh = natof(sp[4]); sigmah = natof(sp[5]); magks = natof(sp[6]); sigmaks = natof(sp[7]); num += 1; tmp1 = 1.0/(sigmaj*sigmaj + sigmah*sigmah); tmp2 = 1.0/(sigmah*sigmah + sigmaks*sigmaks); tmp3 = sqrt(tmp1*tmp2); sum_jh += tmp1*(magj - magh); sum_jh2 += tmp1*(magj - magh)*(magj - magh); sum_hks += tmp2*(magh - magks); sum_hks2 += tmp2*(magh - magks)*(magh - magks); sum_jhhks += tmp3*(magj - magh)*(magh - magks); sum_jhalt += tmp3*(magj - magh); sum_hksalt += tmp3*(magh - magks); no_jh += (magj - magh); no_jh2 += (magj - magh)*(magj - magh); no_hks += (magh - magks); no_hks2 += (magh - magks)*(magh - magks); no_jhhks += (magj - magh)*(magh - magks); w_jh += tmp1; w_hks += tmp2; w_jhhks += tmp3; w_jh2 += tmp1*tmp1; w_hks2 += tmp2*tmp2; w_jhhks2 += tmp3*tmp3; freestrings(sp); } } strclose(fp); avg_jh = sum_jh/w_jh; avg_hks = sum_hks/w_hks; std_jh = sqrt(w_jh/(w_jh*w_jh - w_jh2)*(sum_jh2 - avg_jh*avg_jh*w_jh)); std_hks = sqrt(w_hks/(w_hks*w_hks - w_hks2)*(sum_hks2 - avg_hks*avg_hks*w_hks)); cov = sum_jhhks - avg_hks*sum_jhalt - avg_jh*sum_hksalt + avg_jh*avg_hks*w_jhhks; cov = w_jhhks/(w_jhhks*w_jhhks - w_jhhks2)*cov; fprintf(stdout,"Weighted:\n"); fprintf(stdout,"Average J-H = %5.3e +- %5.3e\n",avg_jh,std_jh); fprintf(stdout,"Average H-Ks = %5.3e +- %5.3e\n",avg_hks,std_hks); fprintf(stdout,"Covariance = %5.3e\n",cov); avg_jh = no_jh/num; avg_hks = no_hks/num; std_jh = sqrt((no_jh2 - avg_jh*avg_jh*num)/(num - 1)); std_hks = sqrt((no_hks2 - avg_hks*avg_hks*num)/(num - 1)); no_jhhks = (no_jhhks- avg_jh*avg_hks*num)/(num - 1); fprintf(stdout,"Unweighted:\n"); fprintf(stdout,"Average J-H = %5.3e +- %5.3e\n",avg_jh,std_jh); fprintf(stdout,"Average H-Ks = %5.3e +- %5.3e\n",avg_hks,std_hks); fprintf(stdout,"Covariance = %5.3e\n",no_jhhks); }
void nemo_main(void) { char fmt1[20], fmt2[20], *cp; double dms[32]; double *x; int *ix; int i,nret, nx, seed; bool Qnl, Qint,Qdms; stream outstr; if (hasvalue("tab")) outstr = stropen(getparam("tab"),"w"); else outstr = stdout; /* is that really ok? */ cp = getparam("format"); /* get format string to print with */ if (strchr(cp,'%')==NULL) warning("%s badly formed printf-conversion specification ???",cp); if (strchr(cp,'d')) { dprintf(1,"Using integer math\n"); Qint = TRUE; } else { dprintf(1,"Using floating point math\n"); Qint = FALSE; } seed = init_xrandom(getparam("seed")); dprintf(1,"init_xrandom: seed=%d\n",seed); Qdms = getbparam("dms"); if (Qdms) { nret = nemoinpx(getparam("expression"),dms,32); if (nret < 0) error("Parsing dms expression"); for (i=0; i<nret; i++) printf("%g\n",dms[i]); return; /* for now */ } strcpy (fmt1,cp); /* store it in 'fmt' */ strcpy (fmt2,cp); /* and here */ cp = getparam("separ"); if (hasvalue("separ")) /* separator between numbers ? */ strcat(fmt2,getparam("separ")); else strcat (fmt2," "); /* else use blank as separator */ Qnl = getbparam("newline"); /* use newlines also ? */ if (hasvalue("atof")) { printf(fmt1,natof(getparam("atof"))); printf("\n"); return; } if (!hasvalue("expression")) { /* extra help if nothing given */ /* this somewhat unusual exit is because aliens often use this program */ /* what really should have been done is make "expression=???" default */ dprintf(0,"Usage: %s <expression>\n",getargv0()); dprintf(0,"\n<expr> can be of form: start[:end][:incr][,start::repeat]...\n"); dprintf(0,"Also try keyword 'help= or help=h'\n"); stop(0); } nx = getiparam("nmax"); if (Qint) { ix = (int *) allocate(nx * sizeof(int)); nret = nemoinpi(getparam("expression"),ix,nx); if (nret == -23) error("Too many items in list, use a bigger nmax=%d",nx); else if (nret < 0) error("nemoinp (%s) parsing error (%d)",cp,nret); for (i=0; i< nret-1; i++) { fprintf(outstr,fmt2,ix[i]); if (Qnl) fprintf(outstr,"\n"); } fprintf (outstr,fmt1,ix[nret-1]); if (Qnl) fprintf (outstr,"\n"); } else { x = (double *) allocate(nx * sizeof(double)); nret = nemoinpd(getparam("expression"),x,nx); if (nret == -23) error("Too many items in list, use a bigger nmax=%d",nx); else if (nret < 0) error("nemoinp (%s) parsing error (%d)",cp,nret); for (i=0; i< nret-1; i++) { fprintf(outstr,fmt2,x[i]); if (Qnl) fprintf(outstr,"\n"); } fprintf (outstr,fmt1,x[nret-1]); if (Qnl) fprintf (outstr,"\n"); } if (!Qnl) fprintf(outstr,"\n"); /* always make sure to add 1 newline */ }
nemo_main() { stream denstr, velstr, outstr, tabstr; real center[2], cospa, sinpa, cosi, sini, cost, costmin, x, y, xt, yt, r, den; real vr, wt, frang, dx, dy, xmin, ymin, rmin, rmax, ave, tmp, rms; real sincosi, cos2i, tga, dmin, dmax, dval, dr, area, fsum1, fsum2; int i, j, k, nx, ny, ir, nring, nundf, nout, nang, nsum; string outmode; int mode = -1; velstr = stropen(getparam("in"),"r"); read_image(velstr,&velptr); nx = Nx(velptr); ny = Ny(velptr); if (hasvalue("out")) { outmode = getparam("mode"); mode = string_index(outmodes, outmode); if (mode < 0) error("Illegal mode=%s [%d], valid:",outmode,mode,outmodes); warning("New out= mode mode=%s [%d]",outmode,mode); Qout = TRUE; outstr = stropen(getparam("out"),"w"); copy_image(velptr,&outptr); } if (hasvalue("den")) { Qden = TRUE; denstr = stropen(getparam("den"),"r"); read_image(denstr,&denptr); } else if (mode==2) error("Need den="); if (hasvalue("tab")) { Qtab = TRUE; tabstr = stropen(getparam("tab"),"w"); } nrad = nemoinpd(getparam("radii"),rad,MAXRING); if (nrad < 2) error("got no rings (%d), use radii=",nrad); nring = nrad-1; if (hasvalue("center")) { if (nemoinpd(getparam("center"),center,2) != 2) error("not enuf values for center=, need 2"); xpos = center[0]; ypos = center[1]; } else { xpos = (Nx(velptr)-1.0)/2.0; ypos = (Ny(velptr)-1.0)/2.0; } pa = getdparam("pa"); inc = getdparam("inc"); vsys = getdparam("vsys"); undf = getdparam("blank"); frang = getdparam("frang"); cospa = cos(pa*PI/180.0); sinpa = sin(pa*PI/180.0); sini = sin(inc*PI/180.0); cosi = cos(inc*PI/180.0); costmin = sin(frang*PI/180.0); sincosi = sini*cosi; cos2i = cosi*cosi; for (i=0; i<nring; i++) pixe[i] = vsum[i] = vsqu[i] = wsum[i] = 0; nundf = nout = nang = 0; ymin = Ymin(velptr); xmin = Xmin(velptr); dx = Dx(velptr); dx = ABS(dx); dx = -dx; dy = Dy(velptr); dy = ABS(dy); rmin = -nx*dx*10.0; rmax = 0.0; dprintf(0,"Map %d x %d pixels, size %g x %g\n", Nx(velptr), Ny(velptr), -dx*Nx(velptr), dy*Ny(velptr)); dprintf(0,"Pixel size: %g x %g\n",-dx, dy); dmin = dmax = vsys; /* loop over the map, accumulating data for fitting process */ for (j=0; j<ny; j++) { y = (j-ypos)*dy; for (i=0; i<nx; i++) { if (MapValue(velptr,i,j) == undf) { nundf++; if (Qout) MapValue(outptr,i,j) = undf; continue; } x = (i-xpos)*dx; yt = x*sinpa + y*cospa; /* major axis now along Y */ xt = x*cospa - y*sinpa; /* minor axis along X */ xt /= cosi; /* deproject to the circle */ r = sqrt(xt*xt+yt*yt); /* radius in the disk */ rmin = MIN(r,rmin); rmax = MAX(r,rmax); ir = ring_index(nrad,rad,r); dprintf(2,"r=%g ir=%d (x,y)=%g,%g (xt,yt)=%g,%g\n", r,ir,x,y,xt,yt); if (ir < 0) { nout++; continue; } cost = yt/r; dval = MapValue(velptr,i,j); if (mode==1) dval /= r; else if (mode==2) dval *= MapValue(denptr,i,j) / r; if (outptr) { if (ABS(cost) > costmin) { MapValue(outptr,i,j) = dval; if (dval > dmax) dmax = dval; if (dval < dmin) dmin = dval; } else { MapValue(outptr,i,j) = undf; } } /* now some ring accumulation, remnant of the velfit fitting */ if (ABS(cost) > costmin) { pixe[ir] += 1; wsum[ir] += 1.0; vsum[ir] += dval; vsqu[ir] += dval*dval; } else nang++; } /* i */ } /* j */ /* write output map(s), if needed */ if (Qout) { dprintf(0,"Data min/max = %g %g\n",dmin,dmax); MapMin(outptr) = dmin; MapMax(outptr) = dmax; write_image(outstr,outptr); } /* report on the rings */ if (Qtab) { fprintf(tabstr,"# r I rms I_sum1 I_sum2 i_ring Npoints\n"); fsum1 = 0.0; /* this will count rings with average values */ fsum2 = 0.0; /* this will count up flux whenever it fell in a ring */ nsum = 0; for (i=0; i<nring; i++) { if (wsum[i] == 0.0) continue; nsum++; r = 0.5*(rad[i] + rad[i+1]); dr = rad[i+1] - rad[i]; area = PI*(sqr(rad[i+1]) - sqr(rad[i])); ave = vsum[i]/wsum[i]; rms = vsqu[i]/wsum[i]-ave*ave; if (rms < 0) rms=0.0; rms = sqrt(rms); fsum1 += ave*area; fsum2 += vsum[i]; fprintf(tabstr,"%g %g %g %g %g %d %d\n", r,ave,rms,fsum1,fsum2,i+1,pixe[i]); } } dprintf(0,"Nundf=%d/%d Nout=%d Nang=%d (sum=%d)\n", nundf,nx*ny,nout,nang,nout+nundf+nang); dprintf(0,"Rmin/max = %g %g\n",rmin,rmax); }
void nemo_main() { stream instr, outstr; int nx, ny, nz, mode; int i,j,k; imageptr iptr1=NULL, iptr2=NULL, optr; /* pointer to images */ real d1, d2, d3, d4, d5, d6, dx, dy, dz; bool Qsym = TRUE; /* symmetric derivates w.r.t. pixel point */ match(getparam("mode"),valid_modes,&mode); if (mode==0) error("Not a valid mode; valid:%s",valid_modes); dprintf(0,"Image sharpening method #%d\n",mode); instr = stropen(getparam("in"), "r"); read_image( instr, &iptr1); nx = Nx(iptr1); ny = Ny(iptr1); nz = Nz(iptr1); dx = Dx(iptr1); dy = Dy(iptr1); dz = Dz(iptr1); if (mode & MODE_DIV || mode & MODE_VORT) { if (read_image(instr,&iptr2) == 0) error("No second image found in %s\n",getparam("in")); if (nx != Nx(iptr2)) error("Second image doesn't match in NX: %d <> %d\n",Nx(iptr2),nx); if (ny != Ny(iptr2)) error("Second image doesn't match in NY: %d <> %d\n",Ny(iptr2),ny); if (nz != Nz(iptr2)) error("Second image doesn't match in NZ: %d <> %d\n",Nz(iptr2),nz); } outstr = stropen(getparam("out"), "w"); create_cube(&optr,nx,ny,nz); Dx(optr) = Dx(iptr1); Dy(optr) = Dy(iptr1); Dz(optr) = Dz(iptr1); Xmin(optr) = Xmin(iptr1); Ymin(optr) = Ymin(iptr1); Zmin(optr) = Zmin(iptr1); if (mode & MODE_LAPLACE) { for (k=1; k<nz-1; k++) { for (j=1; j<ny-1; j++) { for (i=1; i<nx-1; i++) { d1 = CV1(i,j,k) - CV1(i-1,j,k); d2 = CV1(i,j,k) - CV1(i+1,j,k); d3 = CV1(i,j,k) - CV1(i,j-1,k); d4 = CV1(i,j,k) - CV1(i,j+1,k); d5 = CV1(i,j,k) - CV1(i,j,k-1); d6 = CV1(i,j,k) - CV1(i,j,k+1); CVO(i,j,k) = sqrt(d1*d1+d2*d2+d3*d3+d4*d4+d5*d5+d6*d6); } CVO(0,j,k) = 0.0; CVO(nx-1,j,k) = 0.0; } for (i=0; i<nx; i++) CVO(i,0,k) = CVO(i,ny-1,k) = 0.0; } for(j=0; j<ny; j++) for(i=0; i<nx; i++) CVO(i,j,0) = CVO(i,j,nz-1) = 0.0; } else if (mode & MODE_DIV || mode & MODE_VORT) { warning("only 2D implemented"); for (k=0; k<nz; k++) { for (j=0; j<ny-1; j++) { for (i=0; i<nx-1; i++) { if (Qsym) { if (i>0 && j>0) { d1 = 0.5*(CV1(i+1,j,k) - CV1(i-1,j,k)); /* dv_x/dx */ d2 = 0.5*(CV1(i,j+1,k) - CV1(i,j-1,k)); /* dv_x/dy */ d3 = 0.5*(CV2(i+1,j,k) - CV2(i-1,j,k)); /* dv_y/dx */ d4 = 0.5*(CV2(i,j+1,k) - CV2(i,j-1,k)); /* dv_y/dy */ } else d1 = d2 = d3 = d4 = 0.0; } else { d1 = CV1(i+1,j,k) - CV1(i,j,k); /* dv_x/dx */ d2 = CV1(i,j+1,k) - CV1(i,j,k); /* dv_x/dy */ d3 = CV2(i+1,j,k) - CV2(i,j,k); /* dv_y/dx */ d4 = CV2(i,j+1,k) - CV2(i,j,k); /* dv_y/dy */ } if (mode&MODE_DIV) CVO(i,j,k) = d1/dx + d4/dy; else if (mode&MODE_VORT) CVO(i,j,k) = d3/dx - d2/dy; } CVO(nx-1,j,k) = 0.0; } for (i=0; i<nx; i++) { CVO(i,ny-1,k) = 0.0; } } } else if (mode & MODE_AREGAN || mode & MODE_PREGAN) { warning("only 2D implemented"); for (k=0; k<nz; k++) { for (j=0; j<ny-1; j++) { for (i=0; i<nx-1; i++) { d1 = CV1(i,j,k) - CV1(i+1,j,k); d2 = CV1(i,j+1,k) - CV1(i+1,j+1,k); d3 = CV1(i,j,k) - CV1(i,j+1,k); d4 = CV1(i+1,j,k) - CV1(i+1,j+1,k); if (mode&MODE_AREGAN) CVO(i,j,k) = sqrt(sqr(d1+d2)+sqr(d3+d4))/2; else { if (d3+d4==0.0 && d1+d2==0.0) CVO(i,j,k) = 0.0; else CVO(i,j,k) = atan2(d3+d4,d1+d2) * 180 / PI; } } CVO(nx-1,j,k) = 0.0; } for (i=0; i<nx; i++) { CVO(i,ny-1,k) = 0.0; } } } write_image(outstr, optr); }
char * conv_number_str ( const char *number, /* Number to convert */ int flags, /* Number formatting flags */ char dec_point, /* Decimal point: '.' or ',' */ int decimals, /* Number of decimals, or 0 */ int dec_format, /* How are decimals shown? */ int width, /* Output field width, or 0 */ int sign_format /* How are negatives shown? */ ) { static char formatted [FORMAT_MAX + 1], /* Formatted return string */ padded [FORMAT_MAX + 1]; /* Value with leading zeroes */ int sep_stop, /* Where we put next sep_char */ dec_stop, /* Where we put decimal point */ decs_wanted = decimals, /* Number of decimals wanted */ decs_seen, /* Number of decimals output */ sign_pos, /* Where we put sign, if any */ digits; /* Number of digits read so far */ char *dest, /* Store formatted number here */ sign_char, /* Number's sign: ' ', '+', '-' */ sep_char, /* Thousands separator '.' or ',' */ drop_zero, /* We suppress this char */ ch; /* Next character in picture */ Bool have_zero; /* TRUE if whole number is zero */ ASSERT (width <= FORMAT_MAX); ASSERT (dec_point == '.' || dec_point == ','); conv_reason = 0; /* No conversion errors so far */ /* --------------------------------- Prepare to copy digits ---------*/ if (decs_wanted > CONV_MAX_DECS) { conv_reason = CONV_ERR_DECS_OVERFLOW; return (NULL); /* Error - too many decimals */ } /* Pick-up sign character if present */ if (*number == ' ' || *number == '+' || *number == '-') sign_char = *number++; else sign_char = ' '; /* While leading zero is '0' we blank-out zeros in the number */ drop_zero = (char) (flags & FLAG_N_ZERO_FILL? ' ': '0'); /* Prepare for decimals */ if ((flags & FLAG_N_DECIMALS) == 0) decs_wanted = 0; if (strchr (number, '.')) dec_stop = (int) (strchr (number, '.') - (char *) number); else { /* If fraction is provided, fill out to whole + fraction */ if (strlen (number) < (size_t) decs_wanted + 1) { strpad (padded, '0', decs_wanted + 1); strcpy (padded + (decs_wanted - strlen (number) + 1), number); number = padded; } dec_stop = strlen (number) - decs_wanted; } if (dec_stop < 1) { conv_reason = CONV_ERR_DECS_MISSING; return (NULL); /* Error - too few decimals */ } /* Prepare for thousands-separators if FLAG_N_THOUSANDS */ if ((flags & FLAG_N_THOUSANDS) && !(flags & FLAG_N_ZERO_FILL)) { /* Get number of whole digits, allowing for decimals & dec sign */ sep_char = (char) (dec_point == '.'? ',': '.'); sep_stop = (dec_stop - (decs_wanted? decs_wanted + 1: 0)) % 3; if (sep_stop == 0) sep_stop = 3; /* Get into range 1..3 */ } else { sep_char = ' '; sep_stop = 0; /* No thousands separators */ } /* --------------------------------- Copy the digits ----------------*/ digits = 0; /* No digits loaded yet */ decs_seen = 0; /* No decimals output yet */ have_zero = TRUE; /* Assume number is zero */ dest = formatted; /* Format number */ while (*number) /* until we hit the terminator */ { ch = *number++; if (ch == '.') continue; /* Ignore '.' in number */ digits++; if (ch == drop_zero && digits < dec_stop) ch = ' '; else if (isdigit (ch)) { drop_zero = ' '; if (ch > '0') have_zero = FALSE; } if (ch != ' ' || (width > 0 && !(flags & FLAG_N_LEFT))) { *dest++ = ch; /* Output this digit */ if (digits > dec_stop) decs_seen++; /* Count the decimal digit */ else if (digits == dec_stop) /* Handle decimal stop */ { /* with optional point */ if (flags & FLAG_N_DECIMALS) *dest++ = dec_point; sep_stop = 0; /* And kill further thousand seps */ } } /* Output thousands separator unless we are in blank area */ if (digits == sep_stop) { if (ch != ' ') *dest++ = sep_char; sep_stop += 3; } } *dest = 0; /* Terminate the string nicely */ /* --------------------------------- Post-format the result ---------*/ if (decs_wanted > 0) { /* Output trailing decimal zeroes if not supplied */ if (decs_seen == 0) *dest++ = dec_point; while (decs_seen < decs_wanted) { *dest++ = '0'; decs_seen++; } /* Drop all decimals if format is DEC_HIDE_ALL */ if (dec_format == DECS_HIDE_ALL) while (*dest != dec_point) dest--; /* Drop-off trailing zero */ else /* Drop trailing decimal zeroes if format is DEC_DROP_ZEROS */ if (dec_format == DECS_DROP_ZEROS) while (*dest != dec_point) { if (*(dest - 1) > '0') break; else dest--; /* Drop-off trailing zero */ } *dest = 0; /* Terminate the string nicely */ } /* Justify within width if width > 0 */ sign_pos = 0; /* Sign normally comes at start */ digits = strlen (formatted); if (flags & FLAG_N_SIGNED) { digits++; /* Allow for eventual sign */ if (sign_format == SIGN_FINANCIAL) digits++; /* Sign shown like (123) */ } while (digits < width) { if (flags & FLAG_N_LEFT && !(flags & FLAG_N_ZERO_FILL)) strcat (formatted, " "); else { stropen (formatted, FALSE); /* Insert blank at start of string */ if (flags & FLAG_N_ZERO_FILL) formatted [0] = '0'; else sign_pos++; /* Skip leading space */ } digits++; } /* Format sign if FLAG_N_SIGNED */ if (flags & FLAG_N_SIGNED) { if (sign_format == SIGN_NEG_LEAD || sign_format == SIGN_ALL_LEAD || sign_format == SIGN_FINANCIAL) stropen (formatted, FALSE); if (sign_format == SIGN_NEG_TRAIL || sign_format == SIGN_ALL_TRAIL || sign_format == SIGN_FINANCIAL) strcat (formatted, " "); if (!have_zero) /* Zero has no sign */ switch (sign_format) { case SIGN_NEG_LEAD: if (sign_char != '-') break; /* Fall through if negative sign */ case SIGN_ALL_LEAD: formatted [sign_pos] = sign_char; break; case SIGN_NEG_TRAIL: if (sign_char != '-') break; /* Fall through if negative sign */ case SIGN_ALL_TRAIL: strlast (formatted) = sign_char; break; case SIGN_FINANCIAL: if (sign_char == '-') { formatted [0] = '('; strlast (formatted) = ')'; } break; } } /* If all zeroes, return a blank string if FLAG_N_ZERO_BLANK */ if ((flags & FLAG_N_ZERO_BLANK) && have_zero) { memset (formatted, ' ', width); formatted [width] = 0; } if (width > 0 && (strlen (formatted) > (size_t) width)) { conv_reason = CONV_ERR_NUM_OVERFLOW; return (NULL); /* Overflow -- number too large */ } else return (formatted); }
void nemo_main() { int colnr[2]; real *coldat[2], *xdat, *ydat, xmin, xmax, ymin, ymax; real *udat, *vdat, umin, umax, vmin, vmax; real x, y1, y2, dx, xscale, yscale, xQmin, xQmax; real tbb,sum,sum0; stream instr, tabstr; int i, n, ns, nmax; real *sdat, *spdat; string spectrum, filter = filtername(getparam("filter")); bool Qnorm = getbparam("normalize"); bool Qmin = hasvalue("xmin"); bool Qmax = hasvalue("xmax"); bool Qtab = hasvalue("out"); nmax = nemo_file_lines(filter,MAXLINES); xdat = coldat[0] = (real *) allocate(nmax*sizeof(real)); ydat = coldat[1] = (real *) allocate(nmax*sizeof(real)); colnr[0] = 1; /* wavelenght in angstrom */ colnr[1] = 2; /* normalized filter response [0,1] */ instr = stropen(filter,"r"); n = get_atable(instr,2,colnr,coldat,nmax); strclose(instr); if (Qtab) tabstr = stropen(getparam("out"),"w"); for(i=0; i<n; i++) { dprintf(2,"%g %g\n",xdat[i],ydat[i]); if (i==0) { xmin = xmax = xdat[0]; ymin = ymax = ydat[0]; } else { if (xdat[i] <= xdat[i-1]) error("Filter %s must be sorted in wavelength",filter); xmax = MAX(xmax,xdat[i]); ymax = MAX(ymax,ydat[i]); xmin = MIN(xmin,xdat[i]); ymin = MIN(ymin,ydat[i]); } } dprintf(1,"Filter wavelength range: %g : %g\n",xmin,xmax); dprintf(1,"Filter response range: %g : %g\n",ymin,ymax); if (ydat[0] != 0) warning("lower edge filter response not 0: %g",ydat[0]); if (ydat[n-1] != 0) warning("upper edge filter response not 0: %g",ydat[n-1]); dx = getdparam("step"); if ((xmax-xmin)/100 < dx) { warning("Integration step %g in Angstrom too large, resetting to %g", dx, (xmax-xmin)/100); dx = (xmax-xmin)/100; } /* setup a spline interpolation table into the filter */ sdat = (real *) allocate(sizeof(real)*n*3); spline(sdat,xdat,ydat,n); if (Qmin) { /* override any min/max rules ? */ xQmin = getdparam("xmin"); if (xQmin > xmin) warning("xmin=%g greater than minimum in filter (%g)",xQmin,xmin); } if (Qmax) { xQmax = getdparam("xmax"); if (xQmax < xmax) warning("xmax=%g less than maximum in filter (%g)",xQmax,xmax); } if (hasvalue("tbb")) { /* using a Planck curve */ tbb = getdparam("tbb"); if (Qmin) xmin = xQmin; if (Qmax) xmax = xQmax; sum = sum0 = 0; for (x = xmin; x <= xmax; x += dx) { y1 = seval(x,xdat,ydat,sdat,n); /* filter */ y2 = planck(x,tbb); dprintf(3,"%g %g %g\n",x,y1,y2); if (Qtab) fprintf(tabstr,"%g %g\n",x,MAX(DATAMIN,y1*y2)); sum += y1*y2; sum0 += y1; } if (Qnorm) sum /= sum0; else sum *= dx; if (Qtab) dprintf(0,"%g %g %g\n",tbb,sum,-2.5*log10(sum)); else printf("%g %g %g\n",tbb,sum,-2.5*log10(sum)); } else if (hasvalue("spectrum")) { warning("spectrum= is a new feature"); spectrum = getparam("spectrum"); nmax = nemo_file_lines(spectrum,MAXLINES); udat = coldat[0] = (real *) allocate(nmax*sizeof(real)); vdat = coldat[1] = (real *) allocate(nmax*sizeof(real)); colnr[0] = getiparam("xcol"); colnr[1] = getiparam("ycol"); instr = stropen(spectrum,"r"); ns = get_atable(instr,2,colnr,coldat,nmax); strclose(instr); xscale = getdparam("xscale"); yscale = getdparam("yscale"); for(i=0; i<ns; i++) { dprintf(2,"%g %g\n",udat[i],vdat[i]); udat[i] *= xscale; vdat[i] *= yscale; if (i==0) { umin = umax = udat[0]; vmin = vmax = vdat[0]; } else { if (udat[i] <= udat[i-1]) error("Spectrum %s must be sorted in wavelength",spectrum); umax = MAX(umax,udat[i]); vmax = MAX(vmax,vdat[i]); umin = MIN(umin,udat[i]); vmin = MIN(vmin,vdat[i]); } } dprintf(1,"Spectrum wavelength range: %g : %g\n",umin,umax); dprintf(1,"Spectrum response range: %g : %g\n",vmin,vmax); if (umax < xmin || umin >xmax) error("Spectrum and filter do not overlap"); /* setup a spline interpolation table into the spectrum */ spdat = (real *) allocate(sizeof(real)*n*3); spline(spdat,udat,vdat,ns); sum = sum0 = 0; if (Qmin) xmin = xQmin; if (Qmax) xmax = xQmax; for (x = xmin; x <= xmax; x += dx) { y1 = seval(x,xdat,ydat,sdat,n); /* filter */ if (umin < x && x <umax) y2 = seval(x,udat,vdat,spdat,ns); /* spectrum */ else y2 = 0.0; dprintf(3,"%g %g %g\n",x,y1,y2); if (Qtab) fprintf(tabstr,"%g %g\n",x,MAX(DATAMIN,y1*y2)); sum += y1*y2; sum0 += y1; } if (Qnorm) sum /= sum0; else sum *= dx; if (Qtab) dprintf(0,"0 %g %g\n",sum,-2.5*log10(sum)); else printf("0 %g %g\n",sum,-2.5*log10(sum)); } else warning("Either spectrum= or tbb= must be used"); }
void nemo_main() { stream instr, outstr; int i, n, naxis1, naxis2, naxis[2], moment; double edges[2]; struct fits_header fh; struct my_table_header r; char *record, *cp, mesg[80]; string *hitem; FITS *map; /* Setup */ instr = stropen(getparam("in"),"r"); /* open input */ moment = getiparam("moment"); if (moment < 1 || moment > 2) error("moment must be 1 or 2"); band = getiparam("band"); if (band < 1 || band > 10) { band = band_id(getdparam("band")); if (band < 1) error("Invalid DIRBE band"); } naxis[0] = nlon = getiparam("nlong"); naxis[1] = nlat = getiparam("nlat"); grid = (entryptr *) allocate(nlat*nlon*sizeof(entryptr)); for (i=0; i<nlat*nlon; i++) grid[i] = NULL; cp = getparam("coord"); switch (*cp) { case 'g': gal_coord = TRUE; break; case 'e': gal_coord = FALSE; break; default: error("Bad coordinate system choosen; try gal or ecl"); } if (nemoinpd(getparam("long"),edges,2) != 2) error("long= needs 2 values"); if (edges[0] <= edges[1]) error("long= needs left edge to be largest"); lonmin = edges[0]; lonmax = edges[1]; dlon = (lonmax-lonmin)/(float)nlon; if (nemoinpd(getparam("lat"),edges,2) != 2) error("lat= needs 2 values"); if (edges[0] >= edges[1]) error("lat= needs right edge to be largest"); latmin = edges[0]; latmax = edges[1]; dlat = (latmax-latmin)/(float)nlat; dprintf(1,"GridSize: %d * %d Pixels: %g * %g\n",nlon,nlat,dlon,dlat); gc_middle = (lonmax < 0.0 && lonmin > 0.0); /* see if to use SYM_ANGLE */ ncell = getiparam("ncell"); sigma2 = 2*sqr(getdparam("sigma")); /* Open output FITS file, and write a small yet descriptive enough header */ map = fitopen(getparam("out"),"new",2,naxis); fitwrhda(map,"CTYPE1", gal_coord ? "GLON" : "ELON"); fitwrhdr(map,"CRPIX1",(float) 1.0); /* should use center */ fitwrhdr(map,"CRVAL1",(float) (lonmin + 0.5 * dlon)); fitwrhdr(map,"CDELT1",(float) dlon); fitwrhda(map,"CTYPE2", gal_coord ? "GLAT" : "ELAT"); fitwrhdr(map,"CRPIX2",(float) 1.0); /* should use center */ fitwrhdr(map,"CRVAL2",(float) (latmin + 0.5 * dlat)); fitwrhdr(map,"CDELT2",(float) dlat); fitwrhda(map,"TELESCOP","COBE"); fitwrhda(map,"INSTRUME","DIRBE"); fitwrhda(map,"ORIGIN","NEMO processing on CDAC data"); fitwrhda(map,"BUNIT","MJy/sr"); sprintf(mesg,"NEMO: %s VERSION=%s",getargv0(),getparam("VERSION")); fitwra(map,"HISTORY", mesg); hitem = ask_history(); fitwra(map,"HISTORY","NEMO: History in reversed order"); for (i=0, cp=hitem[0]; cp != NULL; i++) { fitwral(map,"HISTORY",cp); cp = hitem[i+1]; /* point to next history item */ } /* Open input file, and process all rows */ fts_zero(&fh); /* clean out header */ n = fts_rhead(&fh,instr); /* read primary header */ if (n<0) error("Error reading primary HDU"); fts_sdata(&fh,instr); /* and skip data .. */ fts_zero(&fh); /* clean out header */ n = fts_rhead(&fh,instr); /* read primary header */ if (n<0) error("Error reading second HDU"); naxis1 = fh.naxisn[0]; /* size of one row */ naxis2 = fh.naxisn[1]; /* number of rows */ record = allocate(naxis1); for (i=0; i<naxis2; i++) { /* loop reading rows */ n = fread(record,1,naxis1,instr); if (n != naxis1) error("Early EOF on record %d",i+1); stuffit(&fh,record,&r); } printf("Used %d/%d points in gridding\n",nused,naxis2); /* map the data on a grid */ mapit(map,moment); /* finish off */ fitclose(map); strclose(instr); }
local void setparams() { input = getparam("in"); ncol = nemoinpi(getparam("xcol"),col,MAXCOL); if (ncol < 0) error("parsing error col=%s",getparam("col")); if (hasvalue("out")) outstr=stropen(getparam("out"),"w"); else outstr = NULL; nsteps = nemoinpd(getparam("bins"),bins,MAXHIST+1) - 1; if (nsteps == 0) { Qbin = FALSE; Qmin = hasvalue("xmin"); Qmax = hasvalue("xmax"); nsteps=getiparam("bins"); if (nsteps > MAXHIST) error("bins=%d too large; MAXHIST=%d",nsteps,MAXHIST); if (Qmin) xrange[0] = getdparam("xmin"); if (Qmax) xrange[1] = getdparam("xmax"); if (Qmin && Qmax && xrange[0] >= xrange[1]) error("Need xmin < xmax"); } else if (nsteps > 0) { Qbin = TRUE; Qmin = TRUE; Qmax = TRUE; xrange[0] = hasvalue("xmin") ? getdparam("xmin") : bins[0]; xrange[1] = hasvalue("xmax") ? getdparam("xmax") : bins[nsteps]; warning("new mode: manual bins=%s",getparam("bins")); } else error("no proper usage for bins=%s",getparam("bins")); Qauto = (!Qmin || !Qmax) ; Qmad = getbparam("mad"); maxcount=getiparam("maxcount"); headline = getparam("headline"); ylog=getbparam("ylog"); xlab=getparam("xlab"); ylab=getparam("ylab"); Qgauss = getbparam("gauss"); Qresid = getbparam("residual"); Qtab = getbparam("tab"); Qcumul = getbparam("cumul"); if (Qcumul) { Qgauss=Qresid=FALSE; ylog=FALSE; } Qmedian = getbparam("median"); Qtorben = getbparam("torben"); if (Qtorben) Qmedian=FALSE; Qrobust = getbparam("robust"); if (ylog && streq(ylab,"N")) ylab = scopy("log(N)"); Qdual = getbparam("dual"); nmax = nemo_file_lines(input,getiparam("nmax")); if (nmax<1) error("Problem reading from %s",input); nxcoord = nemoinpr(getparam("xcoord"),xcoord,MAXCOORD); nsigma = getdparam("nsigma"); mysort = getsort(getparam("sort")); scale = getrparam("scale"); if (scale != 1.0) { int n1=strlen(xlab); string s2 = getparam("scale"); int n2=strlen(s2); xlab2 = (string) allocate(n1+n2+20); sprintf(xlab2,"%s [scale *%s]",xlab,s2); xlab = xlab2; } instr = stropen (input,"r"); }
void nemo_main() { stream instr, outstr; real mscale, pscale, xscale, tsnap, escale, dscale; vector rscale, vscale, ascale; string times; int i, nbody, bits, nrscale, nvscale, nascale, kscale; Body *btab = NULL, *bp; bool Qmass, Qphase, Qacc, Qpot, Qkey, Qaux, Qeps, Qdens; nrscale = nemoinpr(getparam("rscale"),rscale,NDIM); /* RSCALE */ if (nrscale==1) for (i=1; i<NDIM; i++) rscale[i] = rscale[0]; else if (nrscale!=NDIM) error("keyword rscale needs either 1 or %d numbers", NDIM); nvscale = nemoinpr(getparam("vscale"),vscale,NDIM); /* VSCALE */ if (nvscale==1) for (i=1; i<NDIM; i++) vscale[i] = vscale[0]; else if (nvscale!=NDIM) error("keyword vscale needs either 1 or %d numbers", NDIM); nascale = nemoinpr(getparam("ascale"),ascale,NDIM); /* ASCALE */ if (nascale==1) for (i=1; i<NDIM; i++) ascale[i] = ascale[0]; else if (nascale!=NDIM) error("keyword ascale needs either 1 or %d numbers", NDIM); mscale = getdparam("mscale"); pscale = getdparam("pscale"); xscale = getdparam("xscale"); dscale = getdparam("dscale"); escale = getdparam("escale"); kscale = getiparam("kscale"); times = getparam("times"); instr = stropen(getparam("in"), "r"); /* open files */ outstr = stropen(getparam("out"), "w"); get_history(instr); put_history(outstr); for (;;) { get_history(instr); /* skip over stuff we can forget */ if (!get_tag_ok(instr, SnapShotTag)) break; /* done with work in loop */ get_snap(instr, &btab, &nbody, &tsnap, &bits); if ((bits & MassBit) == 0 && (bits & PhaseSpaceBit) == 0) { continue; /* just skip it's probably a diagnostics */ } if ((bits & TimeBit) == 0) tsnap = 0.0; else if (!streq(times,"all") && !within(tsnap, times, TIMEFUZZ)) continue; dprintf (1,"Scaling snapshot at time= %f bits=0x%x\n",tsnap,bits); Qmass = MassBit & bits && !uscalar(mscale); Qphase = PhaseSpaceBit & bits &&(!uvector(rscale) || !uvector(vscale)); Qacc = AccelerationBit & bits&& !uvector(ascale); Qpot = PotentialBit & bits && !uscalar(pscale); Qaux = AuxBit & bits && !uscalar(xscale); Qkey = KeyBit & bits && (kscale!=1); Qdens = DensBit & bits && !uscalar(dscale); Qeps = EpsBit & bits && !uscalar(escale); dprintf(1,"Scaling: "); if (Qmass) dprintf(1," mass"); if (Qphase) dprintf(1," phase"); if (Qacc) dprintf(1," acc"); if (Qpot) dprintf(1," pot"); if (Qaux) dprintf(1," aux"); if (Qkey) dprintf(1," key"); if (Qdens) dprintf(1," dens"); if (Qeps) dprintf(1," eps"); dprintf(1,"\n"); if (Qmass || Qphase || Qacc || Qpot || Qaux || Qkey || Qdens || Qeps) { for (bp = btab; bp < btab+nbody; bp++) { if(Qmass) Mass(bp) *= mscale; if(Qphase) { SMULVV(Pos(bp),rscale); SMULVV(Vel(bp),vscale); } if(Qpot) Phi(bp) *= pscale; if(Qacc) { SMULVV(Acc(bp),ascale); } if(Qaux) Aux(bp) *= xscale; if(Qkey) Key(bp) *= kscale; if(Qdens) Dens(bp) *= dscale; if(Qeps) Eps(bp) *= escale; } } else { warning("No scaling applied to snapshot"); } put_snap(outstr, &btab, &nbody, &tsnap, &bits); } }
void nemo_main() { int i, dir, nrad, npots=0, ltype, ndim = NDIM, nx, ny, ns, ndat, nret; int cols[4], n, idx, idx_max; real pmax, symsize, rr, omk_max = 0.0, omk_rmax; real rad[MAXPT], *vel, *vel1, *vel2, *vel3, *vel4, *curve; real *ome, *kap, *opk, *omk, r0l[MAXPT+2], omega, *f; real inrad[MAXPT], invel[MAXPT], inrade[MAXPT], invele[MAXPT]; double pos[3], acc[3], pot, time = 0.0; /* char *fmt, s[20], pfmt[256]; */ char headline[256], fmt1[80]; string axis, mode, infile, plotlabel; stream instr; bool Qtab, Qplot, Qome, Qvel, Qlv, Qin, QoILR; mode = getparam("mode"); n = getiparam("n"); plotlabel = getparam("headline"); sprintf(fmt1,"%s ",getparam("format")); Qome = (*mode == 'o'); /* options are: velocity|omega|lv */ Qlv = (*mode == 'l'); Qvel = (*mode == 'v'); Qtab = getbparam("tab"); Qplot = getbparam("plot"); infile = getparam("in"); Qin = (*infile != 0); if (Qin) { nret = nemoinpi(getparam("cols"),cols,4); if (nret<0 || nret > 4) error("cols= requires 4 numbers"); for (i=nret; i<4; i++) cols[i] = 0; instr = stropen(infile,"r"); ndat = read_table(instr,MAXPT,inrad,invel,inrade,invele,cols); strclose(instr); } mypot1 = get_potential(getparam("name1"),getparam("pars1"),getparam("file1")); omega = get_pattern(); dprintf(0,"Pattern speed: %f\n",omega); mypot2 = get_potential(getparam("name2"),getparam("pars2"),getparam("file2")); mypot3 = get_potential(getparam("name3"),getparam("pars3"),getparam("file3")); mypot4 = get_potential(getparam("name4"),getparam("pars4"),getparam("file4")); headline[0] = '\0'; /* accumulate headline */ if (mypot1) { strcat(headline,getparam("name1")); strcat(headline,"("); strcat(headline,getparam("pars1")); strcat(headline,")"); npots++; } if (mypot2) { strcat(headline,getparam("name2")); strcat(headline,"("); strcat(headline,getparam("pars2")); strcat(headline,") "); npots++; } if (mypot3) { strcat(headline,getparam("name3")); strcat(headline,"("); strcat(headline,getparam("pars3")); strcat(headline,") "); npots++; } if (mypot4) { strcat(headline,getparam("name4")); strcat(headline,"("); strcat(headline,getparam("pars4")); strcat(headline,")"); npots++; } nrad = nemoinpr(getparam("radii"),rad,MAXPT); /* get radii */ if (nrad <= 0) warning("Using %d radii is not very productive",nrad); vel = (real *) allocate(sizeof(real) * nrad); /* allocate stuff */ vel1 = (real *) allocate(sizeof(real) * nrad); vel2 = (real *) allocate(sizeof(real) * nrad); vel3 = (real *) allocate(sizeof(real) * nrad); vel4 = (real *) allocate(sizeof(real) * nrad); if (Qome) { ome = (real *) allocate(4 * sizeof(real) * nrad); /* plus spline */ kap = (real *) allocate(sizeof(real) * nrad); opk = (real *) allocate(sizeof(real) * nrad); omk = (real *) allocate(sizeof(real) * nrad); } axis = getparam("axis"); dir = 0; if (*axis == 'x') dir=0; if (*axis == 'y') dir=1; if (*axis == 'z') dir=2; if (dir>NDIM) error("Axis %s not supported in NDIM=%d",axis,NDIM); pmax = 0.0; for (i=0; i<nrad; i++) { /* loop to compute */ CLRV(pos); /* clear positions */ pos[dir] = rad[i]; /* set the right axis */ vel[i] = 0.0; if (mypot1) { CLRV(acc); (*mypot1) (&ndim,pos,acc,&pot,&time); vel1[i] = -rad[i] * acc[dir]; vel[i] += vel1[i]; vel1[i] = sqrt(vel1[i]); } if (mypot2) { CLRV(acc); (*mypot2) (&ndim,pos,acc,&pot,&time); vel2[i] = -rad[i] * acc[dir]; vel[i] += vel2[i]; vel2[i] = sqrt(vel2[i]); } if (mypot3) { CLRV(acc); (*mypot3) (&ndim,pos,acc,&pot,&time); vel3[i] = -rad[i] * acc[dir]; vel[i] += vel3[i]; vel3[i] = sqrt(vel3[i]); } if (mypot4) { CLRV(acc); (*mypot4) (&ndim,pos,acc,&pot,&time); vel4[i] = -rad[i] * acc[dir]; vel[i] += vel4[i]; vel4[i] = sqrt(vel4[i]); } vel[i] = sqrt(vel[i]); } if (Qome) { lindblad(nrad,rad,vel,ome,kap,opk,omk,n); if (omega> 0.0) { /* compute resonances */ f = opk; idx = nrad-1; if (omega < f[idx]) { warning("Radii not far enough out for OLR: %g",f[idx]); f = ome; if (omega < f[idx]) { warning("Radii not far enough out for CR: %g",f[idx]); f = omk; } } QoILR = FALSE; for(; idx>0; idx--) { if (omk[idx] > omk_max) { idx_max = idx; omk_max = omk[idx]; } if (f==omk) { if (QoILR) { if (omega < f[idx]) continue; } else { if (omega > f[idx]) continue; } } else { if (omega > f[idx]) continue; } /* found a resonance: */ rr = rad[idx] + (rad[idx+1]-rad[idx])* (omega-f[idx])/(f[idx+1]-f[idx]); if (f == omk) { #if 0 if (QoILR) { dprintf(0,"iILR: %g\n",rr); break; } else { dprintf(0,"oILR: %g\n",rr); QoILR = TRUE; } #endif } else if (f == ome) { dprintf(0,"CR: %g\n",rr); f = omk; } else if (f == opk) { dprintf(0,"OLR: %g\n",rr); f = ome; } else error("impossble resonance"); } peak(nrad,rad,omk,idx_max,1, &omk_rmax, &omk_max); dprintf(0,"OMK_max: %g\n",omk_max); dprintf(0,"OMK_rmax: %g\n",omk_rmax); if (omega < omk_max) { /* search for ILR */ for (idx=idx_max; idx<nrad; idx++) { if (omega > omk[idx]) { rr = rad[idx-1] + (rad[idx]-rad[idx-1])* (omega-f[idx-1])/(f[idx]-f[idx-1]); dprintf(0,"oILR: %g\n",rr); break; } } for (idx=idx_max; idx>0; idx--) { if (omega > omk[idx]) { rr = rad[idx] + (rad[idx+1]-rad[idx])* (omega-f[idx])/(f[idx+1]-f[idx]); dprintf(0,"iILR: %g\n",rr); break; } } } } } for (i=0; i<nrad; i++) { /* loop to print */ if (Qtab) { printf(fmt1,rad[i]); printf(fmt1,vel[i]); } if (Qtab && npots>1 && !Qome) { if (mypot1) printf(fmt1,vel1[i]); if (mypot2) printf(fmt1,vel2[i]); if (mypot3) printf(fmt1,vel3[i]); if (mypot4) printf(fmt1,vel4[i]); } if (Qtab && Qome) { printf(fmt1,ome[i]); printf(fmt1,kap[i]); printf(fmt1,opk[i]); printf(fmt1,omk[i]); } if (Qtab) printf("\n"); if (Qome) pmax = MAX(pmax,opk[i]); else pmax = MAX(pmax,vel[i]); } if (Qin && Qvel) goodness(nrad,rad,vel,ndat,inrad,invel,(cols[3]>0?invele:NULL)); if (Qplot) { plinit("***",0.0,20.0,0.0,20.0); /* open device */ nx = nemoinpr(getparam("xrange"),xplot,2); /* get xrange in plot */ switch(nx) { case 0: xplot[0] = rad[0]; case 1: xplot[1] = rad[nrad-1]; break; case 2: break; default: warning("xrange= only accepts two values"); break; } ny = nemoinpr(getparam("yrange"),yplot,2); /* get yrange in plot */ switch(ny) { case 0: yplot[0] = 0.0; yplot[1] = 1.1 * pmax; /* extra 10% for egde */ break; case 1: yplot[1] = 1.1 * pmax; /* extra 10% for egde */ break; case 2: break; default: warning("yrange= only accepts two values"); break; } xaxis ( 2.0, 2.0, 16.0, xplot, -7, xtrans, "R"); /* plot axes */ xaxis ( 2.0,18.0, 16.0, xplot, -7, xtrans, NULL); if (Qome) yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "[V/R]"); else yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "V"); yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL); if (*plotlabel) pltext(plotlabel,2.0,18.5,0.5,0.0); else pltext(headline,2.0,18.5,0.35,0.0); if (*plotmsg) pltext(plotmsg,8.0,2.5,0.25,0.0); curve = (Qome ? ome : vel); /* assign first curve */ plltype(3,1); /* thick solid line */ plmove(xtrans(rad[0]),ytrans(curve[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(curve[i])); if (Qome) { /* if Lindblad - plot omk, opk */ plltype(1,1); /* all regular solid lines */ plmove(xtrans(rad[0]), ytrans(omk[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(omk[i])); plmove(xtrans(rad[0]), ytrans(opk[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(opk[i])); } else if (npots>1) { /* if velocity and > 1 component */ ltype = 1; if (mypot1) { plltype(1,++ltype); plmove(xtrans(rad[0]),ytrans(vel1[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(vel1[i])); } if (mypot2) { plltype(1,++ltype); plmove(xtrans(rad[0]),ytrans(vel2[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(vel2[i])); } if (mypot3) { plltype(1,++ltype); plmove(xtrans(rad[0]),ytrans(vel2[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(vel3[i])); } if (mypot4) { plltype(1,++ltype); plmove(xtrans(rad[0]),ytrans(vel2[0])); for (i=1; i<nrad; i++) plline(xtrans(rad[i]),ytrans(vel4[i])); } } plltype(1,1); symsize = 0.1; if (Qin && Qvel) { /* if input file with velocities */ for (i=0; i<ndat; i++) plbox(xtrans(inrad[i]),ytrans(invel[i]),symsize); if (cols[3]>0) { /* if error bars in radius */ for (i=0; i<ndat; i++) { plmove(xtrans(inrad[i]-inrade[i]),ytrans(invel[i])); plline(xtrans(inrad[i]+inrade[i]),ytrans(invel[i])); } } if (cols[4]>0) { /* if error bars in velocity */ for (i=0; i<ndat; i++) { plmove(xtrans(inrad[i]),ytrans(invel[i]-invele[i])); plline(xtrans(inrad[i]),ytrans(invel[i]+invele[i])); } } } else if (Qin && Qome) { /* if input file with omega */ for (i=0; i<ndat; i++) plbox(xtrans(inrad[i]),ytrans(invel[i]/inrad[i]),symsize); } plstop(); } /* if plot vel/ome */ if (Qlv) { ns = nemoinpr(getparam("r0l"),r0l,MAXPT+2) - 2; if (ns < 0) error("r0l= needs at least two values: r0 and l"); else if (ns==0) warning("r0l= no lv-radii array supplied"); lv(nrad,rad,vel,r0l[0],r0l[1],ns,&r0l[2]); } }
void nemo_main() { stream instr, outstr; int nx, ny, nz; /* size of scratch map */ int nx1, ny1, nz1, nz2; int ni, i, ix, iy, iz, iz1; real dmin, dmax; imageptr iptr[MAXIM], optr; /* pointer to image */ string flipmode; instr = stropen(getparam("in"), "r"); outstr = stropen(getparam("out"), "w"); for (i=0; i<MAXIM; i++) { /* loop over all to gather data */ iptr[i] = 0; if (read_image( instr, &iptr[i]) == 0) break; nx1 = Nx(iptr[i]); ny1 = Ny(iptr[i]); nz1 = Nz(iptr[i]); dprintf(1,"Image %d: %d x %d x %d\n",i,nx1,ny1,nz1); if (i==0) { nx = nx1; ny = ny1; nz = nz1; dmin = MapMin(iptr[i]); dmax = MapMax(iptr[i]); } else { if (nx != nx1) error("size nx: %d != %d",nx,nx1); if (ny != ny1) error("size ny: %d != %d",ny,ny1); nz += nz1; dmin = MIN(dmin,MapMin(iptr[i])); dmax = MAX(dmax,MapMax(iptr[i])); } } ni = i; dprintf(0,"Final cube: %d x %d x %d\n",nx,ny,nz); dprintf(0,"Data min/max: %g %g\n",dmin,dmax); create_cube(&optr,nx,ny,nz); MapMin(optr) = dmin; MapMax(optr) = dmax; Xmin(optr) = Xmin(iptr[0]); Ymin(optr) = Ymin(iptr[0]); Zmin(optr) = Zmin(iptr[0]); Xref(optr) = Xref(iptr[0]); Yref(optr) = Yref(iptr[0]); Zref(optr) = Zref(iptr[0]); Dx(optr) = Dx(iptr[0]); Dy(optr) = Dy(iptr[0]); Dz(optr) = Dz(iptr[0]); for (i=0, iz=0; i<ni; i++) { /* grab all data in output cube */ nz1 = Nz(iptr[i]); for (iz1=0; iz1< nz1; iz1++, iz++) { for (iy=0; iy<ny; iy++) { for (ix=0; ix<nx; ix++) { CubeValue(optr,ix,iy,iz) = CubeValue(iptr[i],ix,iy,iz1); } } } } write_image(outstr, optr); }
int nemo_main() { int i, n, nbody, bits, ndata, count, ngrid[3]; real scale, dt, dtout, dtlog, tstop, tsnap, mass; string exefile = getparam("exe"); string rundir = getparam("outdir"); string fmt = getparam("format"); stream datstr, instr, outstr; char dname[256]; char command[256]; char fmt6[256]; float *gdata, *gd; Body *bp, *btab = NULL; if (hasvalue("header")) unfsize(getiparam("header")); n = nemoinpi(getparam("grid"),ngrid,3); if (n>0 && n<=3) { for (i=n; i<3; i++) ngrid[i] = ngrid[i-1]; } else error("%d Syntax error: %s (need 1,2 or 3 integers)", n,getparam("grid")); scale = getdparam("scale"); dt = getdparam("dt"); dtout = getdparam("dtout"); dtlog = getdparam("dtlog"); tstop = getdparam("tstop"); sprintf(fmt6,"%s %s %s %s %s %s\n",fmt,fmt,fmt,fmt,fmt,fmt); make_rundir(rundir); /* prepare the parameter file for galaxy */ sprintf(dname,"%s/%s",rundir,"galaxy.dat"); datstr = stropen(dname,"w"); fprintf(datstr,"%d %d %d\n",ngrid[0],ngrid[1],ngrid[2]); fprintf(datstr,"%g\n",scale); fprintf(datstr,"%g\n",dt); fprintf(datstr,"%g\n",dtout); fprintf(datstr,"%g\n",dtlog); fprintf(datstr,"%g\n",tstop); strclose(datstr); /* read snapshot and output it in something galaxy understands */ instr = stropen(getparam("in"),"r"); get_history(instr); if (!get_tag_ok(instr, SnapShotTag)) error("no snapshot"); get_snap(instr, &btab, &nbody, &tsnap, &bits); strclose(instr); if ( (bits & PhaseSpaceBit) == 0) error("no phasespace"); for (bp=btab;bp<btab+nbody; bp++) mass += Mass(bp); sprintf(dname,"%s/%s",rundir,"galaxy.ini"); datstr = stropen(dname,"w"); fprintf(datstr,"%g %g %d\n",tsnap,mass,nbody); for (bp=btab;bp<btab+nbody; bp++) fprintf(datstr,fmt6, Pos(bp)[0],Pos(bp)[1],Pos(bp)[2], Vel(bp)[0],Vel(bp)[1],Vel(bp)[2]); strclose(datstr); /* run the fortran program */ goto_rundir(rundir); if (run_program(exefile)) error("Problem executing %s",exefile); /* Output data from native galaxy (.res) format to snapshot */ sprintf(dname,"%s","galaxy.res"); instr = stropen(dname,"r"); sprintf(dname,"%s","galaxy.snap"); outstr = stropen(dname,"w"); put_history(outstr); ndata = 7*sizeof(float)*nbody; gdata = (float *) allocate(ndata); bits = (TimeBit | PhaseSpaceBit | PotentialBit); while (1) { count = unfread(instr,gdata,ndata); if (count <= 0) break; printf("Time=%g\n",gdata[0]); tsnap = gdata[0]; count = unfread(instr,gdata,ndata); if (count <= 0) error("Problem reading posvelphi from galaxy.res"); for (bp=btab, gd=gdata;bp<btab+nbody; bp++) { Pos(bp)[0] = *gd++; Pos(bp)[1] = *gd++; Pos(bp)[2] = *gd++; Vel(bp)[0] = *gd++; Vel(bp)[1] = *gd++; Vel(bp)[2] = *gd++; Phi(bp) = *gd++; } put_snap(outstr, &btab, &nbody, &tsnap, &bits); } }
void nemo_main(void) { stream instr, outstr, nullstr; string item, *items; string *tags, *sels, *cvt; int i, nsel, select[MAXSEL], cntrd, cntwr; bool all; instr = stropen(getparam("in"), "r"); nullstr = stropen("/dev/null","w+"); /* kludge: force write */ item = getparam("item"); sels = burststring(getparam("select"),", "); nsel = xstrlen(sels, sizeof(string)) - 1; for (i=0; i<nsel; i++) { /* note: array should be sorted */ select[i] = atoi(sels[i]); dprintf(1,"#selected #%d\n",select[i]); if (select[i]<1) error("%d: bad number for select=, must be > 0",select[i]); if (i>0 && (select[i]<select[i-1])) error("%d: bad number for select=, array must be sorted",select[i]); } cvt = burststring(getparam("convert"),", "); if (*item == 0) { all = TRUE; items = (string *) allocate(sizeof(string)); /* PPAP */ items[0] = NULL; } else { all = FALSE; items = burststring(item,", "); if (items==NULL) error("error parsing item=%s\n",item); dprintf(1,"selected: "); for (i=0; items[i]!=NULL; i++) dprintf(1," %s",items[i]); dprintf(1,"\n\n"); } outstr = stropen(getparam("out"), "w"); cntrd = 0; /* keep track of items read */ cntwr = 0; /* and written */ while ((tags = list_tags(instr)) != NULL) { if (check(items, *tags)) { cntrd++; dprintf(1," %d: %s",cntrd,*tags); if (nsel==0 || (nsel>0 && select[cntwr] == cntrd)) { copy_item_cvt(outstr, instr, *tags, cvt); cntwr++; dprintf(1," copied\n"); } else { copy_item(nullstr, instr, *tags); dprintf(1," skipped\n"); } } else { dprintf(1," *: %s",*tags); copy_item(nullstr, instr, *tags); dprintf(1," skipped\n"); } free((char *)*tags); free((char *)tags); if (nsel>0 && cntwr >= nsel) /* early bailout ? */ break; } dprintf(0,"On top-level: %d items read, %d items written\n",cntrd,cntwr); strclose(instr); strclose(outstr); }
image *xyopen(int *handle, string name, string status, int naxis, int *axes) { int i, access; string read_matdef; image *iptr; stream str; if(naxis>MAXNAXIS) error("naxis=%d not supported: MAXNAXIS=%d",naxis, MAXNAXIS); if (first) xy_init(); str = stropen(name,status); /* open file */ switch (*status) { case 'r': /* "r", "old" */ case 'o': access = GET; break; case 'w': /* "w", "new" */ case 'n': access = PUT; break; default: error("xyopen: Unsupported mode %s",status); } iptr = (imageptr )allocate(sizeof(image)); /* new image */ if(access == GET){ get_history(str); get_set (str,ImageTag); get_set (str,ParametersTag); get_data (str,NxTag,IntType, &(Nx(iptr)), 0); get_data (str,NyTag,IntType, &(Ny(iptr)), 0); get_data (str,NzTag,IntType, &(Nz(iptr)), 0); get_data_coerced (str,XminTag,RealType, &(Xmin(iptr)), 0); get_data_coerced (str,YminTag,RealType, &(Ymin(iptr)), 0); get_data_coerced (str,ZminTag,RealType, &(Zmin(iptr)), 0); get_data_coerced (str,DxTag,RealType, &(Dx(iptr)), 0); get_data_coerced (str,DyTag,RealType, &(Dy(iptr)), 0); get_data_coerced (str,DzTag,RealType, &(Dz(iptr)), 0); get_data_coerced (str,MapMinTag, RealType, &(MapMin(iptr)), 0); get_data_coerced (str,MapMaxTag, RealType, &(MapMax(iptr)), 0); get_data (str,BeamTypeTag, IntType, &(BeamType(iptr)), 0); get_data_coerced (str,BeamxTag, RealType, &(Beamx(iptr)), 0); get_data_coerced (str,BeamyTag, RealType, &(Beamy(iptr)), 0); get_data_coerced (str,BeamzTag, RealType, &(Beamz(iptr)), 0); if (get_tag_ok(str,NamexTag)) /* X-axis name */ Namex(iptr) = get_string(str,NamexTag); else Namex(iptr) = NULL; if (get_tag_ok(str,NameyTag)) /* Y-axis name */ Namey(iptr) = get_string(str,NameyTag); else Namey(iptr) = NULL; if (get_tag_ok(str,NamezTag)) /* Z-axis name */ Namez(iptr) = get_string(str,NamezTag); else Namez(iptr) = NULL; if (get_tag_ok(str,UnitTag)) /* units */ Unit(iptr) = get_string(str,UnitTag); else Unit(iptr) = NULL; read_matdef = get_string(str,StorageTag); if (!streq(read_matdef,matdef[idef])) dprintf(0,"read_image: StorageTag = %s, compiled with %s\n", read_matdef, matdef[idef]); get_tes(str,ParametersTag); get_set(str,MapTag); if(Nz(iptr)<=1) get_data_set(str,MapValuesTag,RealType,Nx(iptr),Ny(iptr),0); else get_data_set(str,MapValuesTag,RealType,Nx(iptr),Ny(iptr),Nz(iptr),0); for (i=0; i<naxis; i++) axes[i] = 1; axes[0] = Nx(iptr); axes[1] = Ny(iptr); axes[2] = Nz(iptr); } else { /* PUT */ Nx(iptr) = Ny(iptr) = Nz(iptr) = 1; if (naxis>0) Nx(iptr) = axes[0]; if (naxis>1) Ny(iptr) = axes[1]; if (naxis>2) Nz(iptr) = axes[2]; put_history(str); put_set (str,ImageTag); put_set (str,ParametersTag); put_data (str,NxTag, IntType, &(Nx(iptr)), 0); put_data (str,NyTag, IntType, &(Ny(iptr)), 0); put_data (str,NzTag, IntType, &(Nz(iptr)), 0); put_data (str,XminTag,RealType, &(Xmin(iptr)), 0); put_data (str,YminTag,RealType, &(Ymin(iptr)), 0); put_data (str,ZminTag,RealType, &(Zmin(iptr)), 0); put_data (str,DxTag, RealType, &(Dx(iptr)), 0); put_data (str,DyTag, RealType, &(Dy(iptr)), 0); put_data (str,DzTag, RealType, &(Dz(iptr)), 0); put_data (str,MapMinTag, RealType, &(MapMin(iptr)), 0); put_data (str,MapMaxTag, RealType, &(MapMax(iptr)), 0); put_data (str,BeamTypeTag, IntType, &(BeamType(iptr)), 0); put_data (str,BeamxTag, RealType, &(Beamx(iptr)), 0); put_data (str,BeamyTag, RealType, &(Beamy(iptr)), 0); put_data (str,BeamzTag, RealType, &(Beamz(iptr)), 0); if (Namex(iptr)) put_string (str,NamexTag,Namex(iptr)); if (Namey(iptr)) put_string (str,NameyTag,Namey(iptr)); if (Namez(iptr)) put_string (str,NamezTag,Namez(iptr)); if (Unit(iptr)) put_string (str,UnitTag,Unit(iptr)); put_string(str,StorageTag,matdef[idef]); put_tes(str, ParametersTag); put_set(str, MapTag); if(Nz(iptr)<=1) put_data_set(str,MapValuesTag,RealType,Nx(iptr),Ny(iptr),0); else put_data_set(str,MapValuesTag,RealType,Nx(iptr),Ny(iptr),Nz(iptr),0); } *handle = -1; for(i=0; i<MAXOPEN; i++) { /* look for a new table entry */ if(images[i].str == NULL) *handle = i; } if(*handle < 0) error("xyopen: No more free slots; too many open images"); for (i=0; i<MAXNAXIS; i++) images[*handle].axes[i] = 1; images[*handle].str = str; images[*handle].iptr = iptr; images[*handle].offset = 0; images[*handle].access = access; images[*handle].naxis = (Nz(iptr)<=1 ? 2 : 3); images[*handle].axes[0] = Nx(iptr); images[*handle].axes[1] = Ny(iptr); images[*handle].axes[2] = Nz(iptr); return iptr; }
int main(int argc, string argv[]) { glutInit(&argc, argv); initparam(argv, defv); instr = stropen(getparam("in"), "r"); refscale = getdparam("refscale"); if (! strnull(getparam("colordata"))) { /* color data wanted? */ if (getbparam("dopcolor")) error("%s: colordata precludes dopcolor\n", getargv0()); if (! scanopt(PhiTag "," SmoothTag "," RhoTag "," EntFuncTag "," UinternTag "," UdotIntTag "," UdotRadTag "," UdotVisTag "," TauTag "," BirthTag "," DeathTag "," AuxTag, getparam("colordata"))) error("%s: %s unknown\n", getargv0(), getparam("colordata")); bodytags[1] = getparam("colordata"); /* replace key w/ field... */ butbind[2] = COLORMAP; } else if (getbparam("dopcolor")) { dopcolor = TRUE; bodytags[1] = VelTag; /* replace key w/ velocity */ butbind[2] = COLORMAP; } if (! strnull(getparam("vectordata"))) { if (! scanopt(VelTag "," AccTag "," AuxVecTag, getparam("vectordata"))) error("%s: %s unknown\n", getargv0(), getparam("vectordata")); if (! (streq(getparam("vectordata"), VelTag) && dopcolor)) bodytags[2] = getparam("vectordata"); butbind[2] = VSCALE; } maxfast = getiparam("maxfast"); if (sscanf(getparam("defcolors"), "%x,%x", &pcolor, &bcolor) != 2) error("%s: can't scan defcolor parameter\n", getargv0()); if (sscanf(getparam("viewsize"), "%ix%i", &wscreen, &hscreen) != 2) error("%s: can't scan viewsize parameter\n", getargv0()); layout_body(bodytags, Precision, NDIM); if (! strnull(getparam("colordata"))) { scalaroff = streq(bodytags[1], PhiTag) ? PhiField.offset : streq(bodytags[1], SmoothTag) ? SmoothField.offset : streq(bodytags[1], RhoTag) ? RhoField.offset : streq(bodytags[1], EntFuncTag) ? EntFuncField.offset : streq(bodytags[1], UinternTag) ? UinternField.offset : streq(bodytags[1], UdotIntTag) ? UdotIntField.offset : streq(bodytags[1], UdotRadTag) ? UdotRadField.offset : streq(bodytags[1], UdotVisTag) ? UdotVisField.offset : streq(bodytags[1], TauTag) ? TauField.offset : streq(bodytags[1], BirthTag) ? BirthField.offset : streq(bodytags[1], DeathTag) ? DeathField.offset : streq(bodytags[1], AuxTag) ? AuxField.offset : -1; assert(scalaroff != -1); } if (! strnull(getparam("vectordata"))) { vectoroff = streq(getparam("vectordata"), VelTag) ? VelField.offset : streq(getparam("vectordata"), AccTag) ? AccField.offset : streq(getparam("vectordata"), AuxVecTag) ? AuxVecField.offset : -1; assert(vectoroff != -1); } if (! getdata()) error("%s: no data in input file\n", getargv0()); initgraphics(argv[0]); glutMainLoop(); return (0); }
void nemo_main() { stream instr, outstr; int nx, ny, nz; /* size of scratch map */ int ix, iy, flip; imageptr iptr=NULL; /* pointer to image */ real tmp, zzz; string flipmode; flipmode = getparam("flip"); if (streq(flipmode,"x")) flip = X; else if (streq(flipmode,"y")) flip = Y; else if (streq(flipmode,"xy")) flip = XY; else error("Illegal flip axis"); instr = stropen(getparam("in"), "r"); outstr = stropen(getparam("out"), "w"); read_image( instr, &iptr); nx = Nx(iptr); ny = Ny(iptr); nz = Nz(iptr); if(flip==X) { for (iy=0; iy<ny; iy++) { /* flip in x */ for (ix=0; ix<nx/2; ix++) { tmp = MapValue(iptr,ix,iy); zzz = MapValue(iptr,nx-ix-1,iy); dprintf(1,"%d %d: %f %f\n",ix,iy,tmp,zzz); MapValue(iptr,ix,iy) = MapValue(iptr,nx-ix-1,iy); MapValue(iptr,nx-ix-1,iy) = tmp; } } } else if (flip==Y) { for (iy=0; iy<ny; iy++) { /* flip in y */ for (ix=0; ix<nx/2; ix++) { tmp = MapValue(iptr,iy,ix); zzz = MapValue(iptr,iy,nx-ix-1); dprintf(1,"%d %d: %f %f\n",ix,iy,tmp,zzz); MapValue(iptr,iy,ix) = MapValue(iptr,iy,nx-ix-1); MapValue(iptr,iy,nx-ix-1) = tmp; } } } else if (flip==XY) { for (iy=0; iy<ny; iy++) { /* swap the x and y axes */ for (ix=iy+1; ix<nx; ix++) { tmp = MapValue(iptr,ix,iy); dprintf(1,"%d %d: %f \n",ix,iy,tmp); MapValue(iptr,ix,iy) = MapValue(iptr,iy,ix); MapValue(iptr,iy,ix) = tmp; } } SWAPR(Xmin(iptr), Ymin(iptr)); SWAPR(Dx(iptr), Dy(iptr)); SWAPS(Namex(iptr), Namey(iptr)); } write_image(outstr, iptr); }
nemo_main() { int i, j, k, ki; real x, y, z, xmin, xmax, mean, sigma, skew, kurt, bad, w, *data; real dmin, dmax; real sum, sov, q1, q2, q3; Moment m; bool Qmin, Qmax, Qbad, Qw, Qmedian, Qrobust, Qtorben, Qmmcount = getbparam("mmcount"); bool Qx, Qy, Qz, Qone, Qall, Qign = getbparam("ignore"); bool Qhalf = getbparam("half"); bool Qmaxpos = getbparam("maxpos"); real nu, nppb = getdparam("nppb"); int npar = getiparam("npar"); int ngood; int ndat = 0; int nplanes; int min_count, max_count; int maxmom = getiparam("maxmom"); int maxpos[2]; char slabel[32]; instr = stropen (getparam("in"), "r"); read_image (instr,&iptr); strclose(instr); nx = Nx(iptr); ny = Ny(iptr); nz = Nz(iptr); dprintf(1,"# data order debug: %f %f\n",Frame(iptr)[0], Frame(iptr)[1]); if (hasvalue("tab")) tabstr = stropen(getparam("tab"),"w"); planes = (int *) allocate((nz+1)*sizeof(int)); nplanes = nemoinpi(getparam("planes"),planes,nz+1); Qall = (planes[0]==-1); if (planes[0]==0) { Qone = FALSE; nplanes = nz; for (k=0; k<nz; k++) planes[k] = k; } else if (!Qall) { Qone = (!Qall && nplanes==1); for (k=0; k<nplanes; k++) { if (planes[k]<1 || planes[k]>nz) error("%d is an illegal plane [1..%d]",planes[k],nz); planes[k]--; } } if (hasvalue("win")) { instr = stropen (getparam("win"), "r"); read_image (instr,&wptr); strclose(instr); if (Nx(iptr) != Nx(wptr)) error("X sizes of in=/win= don't match"); if (Ny(iptr) != Ny(wptr)) error("Y sizes of in=/win= don't match"); if (Nz(iptr) != Nz(wptr)) error("Z sizes of in=/win= don't match"); Qw = TRUE; } else Qw = FALSE; Qmin = hasvalue("min"); if (Qmin) xmin = getdparam("min"); Qmax = hasvalue("max"); if (Qmax) xmax = getdparam("max"); Qbad = hasvalue("bad"); if (Qbad) bad = getdparam("bad"); Qmedian = getbparam("median"); Qrobust = getbparam("robust"); Qtorben = getbparam("torben"); if (Qtorben) Qmedian = TRUE; if (Qmedian || Qrobust || Qtorben) { ndat = nx*ny*nz; data = (real *) allocate(ndat*sizeof(real)); } sov = 1.0; /* volume of a pixel/voxel */ Qx = Qign && Nx(iptr)==1; Qy = Qign && Ny(iptr)==1; Qz = Qign && Nz(iptr)==1; sov *= Qx ? 1.0 : Dx(iptr); sov *= Qy ? 1.0 : Dy(iptr); sov *= Qz ? 1.0 : Dz(iptr); strcpy(slabel,"*"); if (!Qx) strcat(slabel,"Dx*"); if (!Qy) strcat(slabel,"Dy*"); if (!Qz) strcat(slabel,"Dz*"); if (maxmom < 0) { warning("No work done, maxmom<0"); stop(0); } if (Qall) { /* treat cube as one data block */ ini_moment(&m,maxmom,ndat); ngood = 0; for (k=0; k<nz; k++) { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { x = CubeValue(iptr,i,j,k); if (Qhalf && x>=0.0) continue; if (Qmin && x<xmin) continue; if (Qmax && x>xmax) continue; if (Qbad && x==bad) continue; w = Qw ? CubeValue(wptr,i,j,k) : 1.0; accum_moment(&m,x,w); if (Qhalf && x<0) accum_moment(&m,-x,w); if (Qmedian) data[ngood++] = x; if (tabstr) fprintf(tabstr,"%g\n",x); } } } if (npar > 0) { nu = n_moment(&m)/nppb - npar; if (nu < 1) error("%g: No degrees of freedom",nu); printf("chi2= %g\n", show_moment(&m,2)/nu/nppb); printf("df= %g\n", nu); } else { nsize = nx * ny * nz; sum = mean = sigma = skew = kurt = 0; if (maxmom > 0) { mean = mean_moment(&m); sum = show_moment(&m,1); } if (maxmom > 1) sigma = sigma_moment(&m); if (maxmom > 2) skew = skewness_moment(&m); if (maxmom > 3) kurt = kurtosis_moment(&m); printf ("Number of points : %d\n",n_moment(&m)); printf ("Min and Max : %f %f\n",min_moment(&m), max_moment(&m)); printf ("Mean and dispersion : %f %f\n",mean,sigma); printf ("Skewness and kurtosis : %f %f\n",skew,kurt); printf ("Sum and Sum*%s : %f %f\n",slabel, sum, sum*sov); if (Qmedian) { if (Qtorben) { printf ("Median Torben : %f (%d)\n",median_torben(ngood,data,min_moment(&m),max_moment(&m)),ngood); } else { printf ("Median : %f\n",get_median(ngood,data)); q2 = median(ngood,data); q1 = median_q1(ngood,data); q3 = median_q3(ngood,data); printf ("Q1,Q2,Q3 : %f %f %f\n",q1,q2,q3); } #if 1 if (ndat>0) printf ("MedianL : %f\n",median_moment(&m)); #endif } if (Qrobust) { compute_robust_moment(&m); printf ("Mean Robust : %f\n",mean_robust_moment(&m)); printf ("Sigma Robust : %f\n",sigma_robust_moment(&m)); printf ("Median Robust : %f\n",median_robust_moment(&m)); } if (Qmmcount) { min_count = max_count = 0; xmin = min_moment(&m); xmax = max_moment(&m); for (i=0; i<nx; i++) { for (j=0; j<ny; j++) { for (k=0; k<nz; k++) { x = CubeValue(iptr,i,j,k); if (x==xmin) min_count++; if (x==xmax) max_count++; } } } /* i */ printf("Min_Max_count : %d %d\n",min_count,max_count); } printf ("%d/%d out-of-range points discarded\n",nsize-n_moment(&m), nsize); } } else { /* treat each plane seperately */ /* tabular output, one line per (selected) plane */ printf("# iz z min max N mean sigma skew kurt sum sumsov "); if (Qmedian) printf(" [med med]"); if (Qrobust) printf(" robust[N mean sig med]"); if (Qmaxpos) printf(" maxposx maxposy"); printf("\n"); ini_moment(&m,maxmom,ndat); for (ki=0; ki<nplanes; ki++) { reset_moment(&m); k = planes[ki]; z = Zmin(iptr) + k*Dz(iptr); ngood = 0; for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { x = CubeValue(iptr,i,j,k); if (Qmin && x<xmin) continue; if (Qmax && x>xmax) continue; if (Qbad && x==bad) continue; if (Qmaxpos) { if (i==0 && j==0) { dmax = x; maxpos[0] = 0; maxpos[1] = 0;} else if (x>dmax) { dmax = x; maxpos[0] = i; maxpos[1] = j;} } w = Qw ? CubeValue(wptr,i,j,k) : 1.0; accum_moment(&m,x,w); if (Qmedian) data[ngood++] = x; } } nsize = nx * ny * nz; sum = mean = sigma = skew = kurt = 0; if (maxmom > 0) { mean = mean_moment(&m); sum = show_moment(&m,1); } if (maxmom > 1) sigma = sigma_moment(&m); if (maxmom > 2) skew = skewness_moment(&m); if (maxmom > 3) kurt = kurtosis_moment(&m); if (n_moment(&m) == 0) { printf("# %d no data\n",k+1); continue; } printf("%d %f %f %f %d %f %f %f %f %f %f", k+1, z, min_moment(&m), max_moment(&m), n_moment(&m), mean,sigma,skew,kurt,sum,sum*sov); if (Qmedian) { printf (" %f",get_median(ngood,data)); if (ndat>0) printf (" %f",median_moment(&m)); } if (Qrobust) { compute_robust_moment(&m); printf (" %d %f %f %f",n_robust_moment(&m), mean_robust_moment(&m), sigma_robust_moment(&m), median_robust_moment(&m)); } if (Qmaxpos) { printf(" %d %d",maxpos[0],maxpos[1]); } #if 0 if (Qmmcount) { min_count = max_count = 0; xmin = min_moment(&m); xmax = max_moment(&m); for (i=0; i<nx; i++) { for (j=0; j<ny; j++) { x = CubeValue(iptr,i,j,k); if (x==xmin) min_count++; if (x==xmax) max_count++; } } /* i,j */ printf(" %d %d",min_count,max_count); } printf ("%d/%d out-of-range points discarded\n",nsize-n_moment(&m), nsize); #endif printf("\n"); } /* ki */ } }
scan_sd(string infile) /* this is the fancy new version */ { float **dump, **coord; int i, j, k, ret, old_size, size, type, nsds, old_rank; char ntype[32]; bool *visib, axis_visib[MAXRANK]; int nselect, select[MAXSDS]; string format, sselect; stream outstr; bool Qdummy = getbparam("dummy"); bool Qout = hasvalue("out"); if (!Qdummy) warning("dummy may not be working so well"); nsds = DFSDndatasets(infile); if (nsds<0) error("%s is probably not an HDF scientific dataset",infile); dprintf(0,"Found %d scientific data set%s in %s\n", nsds,(nsds > 1 ? "s" : ""),infile); visib = (bool *) allocate(sizeof(bool)*nsds); if (hasvalue("out")) { dump = (float **) allocate(nsds*sizeof(float *)); /* all data !! */ format = getparam("format"); outstr = stropen(getparam("out"),"w"); } else outstr = NULL; for (k=0; k<nsds; k++) /* first flag all SDS to be shown */ visib[k] = TRUE; for (k=0; k<MAXRANK; k++) /* first flag all axes to be shown (in case coord=t) */ axis_visib[k] = TRUE; sselect = getparam("select"); if (!streq(sselect,"all")) { nselect = nemoinpi(sselect,select,MAXSDS); if (nselect < 0) error("%d error parsing %s",nselect,sselect); if (nselect > nsds) error("%s: too many specified, nsds=%d",nselect,nsds); for (k=0; k<nsds; k++) visib[k] = FALSE; for (k=0; k<nselect; k++) { if (select[k] < 1 || select[k] > nsds) error("%d: bad SDS selection, nsds=%d",select[k],nsds); visib[select[k]-1] = TRUE; } } for (k=0; k<nsds; k++) dprintf(1,"%d: %s\n", k+1, visib[k] ? "OK" : "hidden"); old_size = -1; for (k=0; k<nsds; k++) { /* loop over all SDS to get the rank, shape, size and info */ ret = DFSDgetdims(infile,&rank, shape, MAXRANK); if (ret < 0) error("Problem getting rank/shape at SDS #%d",k+1); label[0] = unit[0] = fmt[0] = coordsys[0] = 0; ret = DFSDgetdatastrs(label, unit, fmt, coordsys); if (ret < 0) error("Problem getting labels at SDS #%d",k+1); ret = DFSDgetNT(&type); if (ret < 0) error("Problem getting data type at SDS #%d",k+1); if (! visib[k]) continue; /* don't count SDS# that were not selected */ if (old_size < 0) { /* first time around allocate coordinates */ if (getbparam("coord")) { coord = (float **) allocate(rank*sizeof(float *)); } else { coord = NULL; } } dprintf(0,"%d: %s(",k+1,label); for (i=0, size=1; i<rank; i++) { if (i==rank-1) dprintf(0,"%d)",shape[i]); else dprintf(0,"%d,",shape[i]); size *= shape[i]; if (old_size < 0 && coord) { coord[i] = (float *) allocate(shape[i] * sizeof(float)); ret = DFSDgetdimscale(i+1, shape[i],coord[i]); if (ret<0) error("getting shape[%d]",i+1); } } hdf_type_info(type,ntype); dprintf(0," %s ",unit); dprintf(0," -> [%d elements of type: %d (%s)]\n", size, type, ntype); if (outstr) { dump[k] = (float *) allocate(size * sizeof(float)); ret = DFSDgetdata(infile,rank,shape,dump[k]); } if (old_size < 0) { /* first time around */ old_size = size; old_rank = rank; for (i=0; i<rank; i++) old_shape[i] = shape[i]; } else { /* make sure subsequent ones have the same size for display */ if (old_size != size) { if (Qout) warning("bad shape for SDS #%d, removing from selection list",k+1); visib[k] = FALSE; size = old_size; } else if (old_rank != rank) { if (Qout) warning("bad rank for SDS #%d, removing from selection list",k+1); visib[k] = FALSE; rank = old_rank; } } } /* k */ rank = old_rank; /* restore it, in case the last one was a bad one */ for (i=0; i<rank; i++) shape[i] = old_shape[i] ; #if 0 for (k=0; k<nsds; k++) if (!visib[k]) warning("SDS #%d cannot be displayed, it has a different size",k+1); #endif if (outstr) { for (i=0; i<rank; i++) { run[i] = 0; /* reset run (coordinate index) array */ axis_visib[i] = Qdummy ? TRUE : shape[i] > 1; dprintf(1,"axis %d=%d => %d\n",i+1,shape[i],axis_visib[i]); } for (i=0; i<size; i++) { /* loop over all data */ if (coord) { /* print coord system ? */ for (j=rank-1; j>=0; j--) { if (Qdummy || axis_visib[j]) { fprintf(outstr,format,coord[j][run[j]]); fprintf(outstr," "); } } run[rank-1]++; for (j=rank-1; j>=0; j--) { /* check if axis reset needed */ if (run[j] >= shape[j]) { run[j] = 0; if (j>0) run[j-1]++; } else break; } } /* coord */ for (k=0; k<nsds; k++) { /* loop over all columns */ if (visib[k]) { fprintf(outstr,format,dump[k][i]); fprintf(outstr," "); } } fprintf(outstr,"\n"); } } }
int main(int argc,char **argv) { ros::init(argc, argv, "rtk_robot"); ROS_INFO("RTKlib for ROS Robot Edition"); ros::NodeHandle nn; ros::NodeHandle pn("~"); ros::Subscriber ecef_sub; if(pn.getParam("base_position/x", ecef_base_station.position.x) && pn.getParam("base_position/y", ecef_base_station.position.y) && pn.getParam("base_position/z", ecef_base_station.position.z)) { ROS_INFO("RTK -- Loading base station parameters from the parameter server..."); XmlRpc::XmlRpcValue position_covariance; if( pn.getParam("base_position/covariance", position_covariance) ) { ROS_ASSERT(position_covariance.getType() == XmlRpc::XmlRpcValue::TypeArray); if(position_covariance.size() != 9) { ROS_WARN("RTK -- The base station covariances are not complete! Using default values..."); } else { for(int i=0 ; i<position_covariance.size() ; ++i) { ROS_ASSERT(position_covariance[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); ecef_base_station.position_covariance[i] = static_cast<double>(position_covariance[i]); } } } } else { ROS_INFO("RTK -- Subscribing to the base station for online parameters..."); ecef_sub = nn.subscribe("base_station/gps/ecef", 50, ecefCallback); } double rate; pn.param("rate", rate, 2.0); std::string gps_frame_id; pn.param<std::string>("gps_frame_id", gps_frame_id, "gps"); std::string port; pn.param<std::string>("port", port, "ttyACM0"); int baudrate; pn.param("baudrate", baudrate, 115200); ros::Publisher gps_pub = nn.advertise<sensor_msgs::NavSatFix>("gps/fix", 50); ros::Publisher status_pub = nn.advertise<rtk_msgs::Status>("gps/status", 50); ros::Subscriber gps_sub = nn.subscribe("base_station/gps/raw_data", 50, baseStationCallback); int n; //********************* rtklib stuff ********************* rtksvrinit(&server); if(server.state) { ROS_FATAL("RTK -- Failed to initialize rtklib server!"); ROS_BREAK(); } gtime_t time, time0 = {0}; int format[] = {STRFMT_UBX, STRFMT_UBX, STRFMT_RTCM2}; prcopt_t options = prcopt_default; options.mode = 2; options.nf = 1; options.navsys = SYS_GPS | SYS_SBS; options.modear = 3; options.glomodear = 0; options.minfix = 3; options.ionoopt = IONOOPT_BRDC; options.tropopt = TROPOPT_SAAS; options.rb[0] = ecef_base_station.position.x; options.rb[1] = ecef_base_station.position.y; options.rb[2] = ecef_base_station.position.z; strinitcom(); server.cycle = 10; server.nmeacycle = 1000; server.nmeareq = 0; for(int i=0 ; i<3 ; i++) server.nmeapos[i] = 0; server.buffsize = BUFFSIZE; for(int i=0 ; i<3 ; i++) server.format[i] = format[i]; server.navsel = 0; server.nsbs = 0; server.nsol = 0; server.prcout = 0; rtkfree(&server.rtk); rtkinit(&server.rtk, &options); for(int i=0 ; i<3 ; i++) { server.nb[i] = server.npb[i] = 0; if(!(server.buff[i]=(unsigned char *)malloc(BUFFSIZE)) || !(server.pbuf[i]=(unsigned char *)malloc(BUFFSIZE))) { ROS_FATAL("RTK -- Failed to initialize rtklib server - malloc error!"); ROS_BREAK(); } for(int j=0 ; j<10 ; j++) server.nmsg[i][j] = 0; for(int j=0 ; j<MAXOBSBUF ; j++) server.obs[i][j].n = 0; /* initialize receiver raw and rtcm control */ init_raw(server.raw + i); init_rtcm(server.rtcm + i); /* set receiver option */ strcpy(server.raw[i].opt, ""); strcpy(server.rtcm[i].opt, ""); /* connect dgps corrections */ server.rtcm[i].dgps = server.nav.dgps; } /* output peek buffer */ for(int i=0 ; i<2 ; i++) { if (!(server.sbuf[i]=(unsigned char *)malloc(BUFFSIZE))) { ROS_FATAL("RTK -- Failed to initialize rtklib server - malloc error!"); ROS_BREAK(); } } /* set solution options */ solopt_t sol_options[2]; sol_options[0] = solopt_default; sol_options[1] = solopt_default; for(int i=0 ; i<2 ; i++) server.solopt[i] = sol_options[i]; /* set base station position */ for(int i=0 ; i<6 ; i++) server.rtk.rb[i] = i < 3 ? options.rb[i] : 0.0; /* update navigation data */ for(int i=0 ; i<MAXSAT*2 ; i++) server.nav.eph[i].ttr = time0; for(int i=0 ; i<NSATGLO*2 ; i++) server.nav.geph[i].tof = time0; for(int i=0 ; i<NSATSBS*2 ; i++) server.nav.seph[i].tof = time0; updatenav(&server.nav); /* set monitor stream */ server.moni = NULL; /* open input streams */ int stream_type[8] = {STR_SERIAL, 0, 0, 0, 0, 0, 0, 0}; char gps_path[64]; sprintf(gps_path, "%s:%d:8:n:1:off", port.c_str(), baudrate); char * paths[] = {gps_path, "localhost:27015", "", "", "", "", "", ""}; char * cmds[] = {"", "", ""}; int rw; for(int i=0 ; i<8 ; i++) { rw = i < 3 ? STR_MODE_R : STR_MODE_W; if(stream_type[i] != STR_FILE) rw |= STR_MODE_W; if(!stropen(server.stream+i, stream_type[i], rw, paths[i])) { ROS_ERROR("RTK -- Failed to open stream %s", paths[i]); for(i-- ; i>=0 ; i--) strclose(server.stream+i); ROS_FATAL("RTK -- Failed to initialize rtklib server - failed to open all streams!"); ROS_BREAK(); } /* set initial time for rtcm and raw */ if(i<3) { time = utc2gpst(timeget()); server.raw[i].time = stream_type[i] == STR_FILE ? strgettime(server.stream+i) : time; server.rtcm[i].time = stream_type[i] == STR_FILE ? strgettime(server.stream+i) : time; } } /* sync input streams */ strsync(server.stream, server.stream+1); strsync(server.stream, server.stream+2); /* write start commands to input streams */ for(int i=0 ; i<3 ; i++) { if(cmds[i]) strsendcmd(server.stream+i, cmds[i]); } /* write solution header to solution streams */ for(int i=3 ; i<5 ; i++) { unsigned char buff[1024]; int n; n = outsolheads(buff, server.solopt+i-3); strwrite(server.stream+i, buff, n); } //******************************************************** obs_t obs; obsd_t data[MAXOBS*2]; server.state=1; obs.data=data; double tt; unsigned int tick; int fobs[3] = {0}; server.tick = tickget(); ROS_DEBUG("RTK -- Initialization complete."); ros::Rate r(rate); while(ros::ok()) { tick = tickget(); unsigned char *p = server.buff[RTK_ROBOT]+server.nb[RTK_ROBOT]; unsigned char *q = server.buff[RTK_ROBOT]+server.buffsize; ROS_DEBUG("RTK -- Getting data from GPS..."); /* read receiver raw/rtcm data from input stream */ n = strread(server.stream, p, q-p); /* write receiver raw/rtcm data to log stream */ strwrite(server.stream+5, p, n); server.nb[RTK_ROBOT] += n; /* save peek buffer */ rtksvrlock(&server); n = n < server.buffsize - server.npb[RTK_ROBOT] ? n : server.buffsize - server.npb[RTK_ROBOT]; memcpy(server.pbuf[RTK_ROBOT] + server.npb[RTK_ROBOT], p, n); server.npb[RTK_ROBOT] += n; rtksvrunlock(&server); ROS_DEBUG("RTK -- Decoding GPS data..."); /* decode data */ fobs[RTK_ROBOT] = decoderaw(&server, RTK_ROBOT); fobs[RTK_BASE_STATION] = decoderaw(&server, RTK_BASE_STATION); ROS_DEBUG("RTK -- Got %d observations.", fobs[RTK_ROBOT]); /* for each rover observation data */ for(int i=0 ; i<fobs[RTK_ROBOT] ; i++) { obs.n = 0; for(int j=0 ; j<server.obs[RTK_ROBOT][i].n && obs.n<MAXOBS*2 ; j++) { obs.data[obs.n++] = server.obs[RTK_ROBOT][i].data[j]; } for(int j=0 ; j<server.obs[1][0].n && obs.n<MAXOBS*2 ; j++) { obs.data[obs.n++] = server.obs[1][0].data[j]; } ROS_DEBUG("RTK -- Calculating RTK positioning..."); /* rtk positioning */ rtksvrlock(&server); rtkpos(&server.rtk, obs.data, obs.n, &server.nav); rtksvrunlock(&server); sensor_msgs::NavSatFix gps_msg; gps_msg.header.stamp = ros::Time::now(); gps_msg.header.frame_id = gps_frame_id; rtk_msgs::Status status_msg; status_msg.stamp = gps_msg.header.stamp; if(server.rtk.sol.stat != SOLQ_NONE) { /* adjust current time */ tt = (int)(tickget()-tick)/1000.0+DTTOL; timeset(gpst2utc(timeadd(server.rtk.sol.time,tt))); /* write solution */ unsigned char buff[1024]; n = outsols(buff, &server.rtk.sol, server.rtk.rb, server.solopt); if(n==141 && buff[0]>'0' && buff[0]<'9') { int ano,mes,dia,horas,minutos,Q,nsat; double segundos,lat,longi,alt,sde,sdn,sdu,sdne,sdeu,sdun; sscanf((const char *)(buff),"%d/%d/%d %d:%d:%lf %lf %lf %lf %d %d %lf %lf %lf %lf %lf %lf", &ano, &mes, &dia, &horas, &minutos, &segundos, &lat, &longi, &alt, &Q, &nsat, &sdn, &sde, &sdu, &sdne, &sdeu, &sdun); gps_msg.latitude = lat; gps_msg.longitude = longi; gps_msg.altitude = alt; gps_msg.position_covariance_type = sensor_msgs::NavSatFix::COVARIANCE_TYPE_KNOWN; gps_msg.position_covariance[0] = sde + ecef_base_station.position_covariance[0]; gps_msg.position_covariance[1] = sdne + ecef_base_station.position_covariance[1]; gps_msg.position_covariance[2] = sdeu + ecef_base_station.position_covariance[2]; gps_msg.position_covariance[3] = sdne + ecef_base_station.position_covariance[3]; gps_msg.position_covariance[4] = sdn + ecef_base_station.position_covariance[4]; gps_msg.position_covariance[5] = sdun + ecef_base_station.position_covariance[5]; gps_msg.position_covariance[6] = sdeu + ecef_base_station.position_covariance[6]; gps_msg.position_covariance[7] = sdun + ecef_base_station.position_covariance[7]; gps_msg.position_covariance[8] = sdu + ecef_base_station.position_covariance[8]; gps_msg.status.status = Q==5 ? sensor_msgs::NavSatStatus::STATUS_FIX : sensor_msgs::NavSatStatus::STATUS_GBAS_FIX; gps_msg.status.service = sensor_msgs::NavSatStatus::SERVICE_GPS; status_msg.fix_quality = Q; status_msg.number_of_satellites = nsat; } } else { gps_msg.status.status = sensor_msgs::NavSatStatus::STATUS_NO_FIX; gps_msg.status.service = sensor_msgs::NavSatStatus::SERVICE_GPS; } ROS_DEBUG("RTK -- Publishing ROS msg..."); gps_pub.publish(gps_msg); status_pub.publish(status_msg); } ros::spinOnce(); r.sleep(); } return(0); }
void nemo_main() { int i, seed, bits; real mg, mh, tsnap; double vx, vy, vz; double fmax, f0, f1, v2, vmax, vmax2; bool Qcenter = getbparam("zerocm"); bool Qphi = getbparam("addphi"); stream outstr = stropen(getparam("out"),"w"); mu = getdparam("m"); a = getdparam("a"); seed = init_xrandom(getparam("seed")); nobj = getiparam("nbody"); if (nobj%2) warning("Total number of particles reset to %d\n",2*((nobj+1)/2)); nobj = ((nobj+1)/2); if (hasvalue("headline")) set_headline(getparam("headline")); put_history(outstr); b = a - 1; btab = (Body *) allocate(2*nobj*sizeof(Body)); for(i=0, bp=btab; i<2*nobj; i++, bp++) { double eta, radius, cth, sth, phi; double psi0; eta = (double) xrandom(0.0,1.0); radius = rad(eta); if( i >= nobj ) { if( mu == 0.0 ) break; radius *= a; } if( i<nobj ) { galaxy = 1; } else { galaxy = 0; } phi = xrandom(0.0,2*M_PI); cth = xrandom(-1.0,1.0); sth = sqrt(1.0 - cth*cth); Pos(bp)[0] = (real) (radius*sth*cos(phi)); Pos(bp)[1] = (real) (radius*sth*sin(phi)); Pos(bp)[2] = (real) (radius*cth); psi0 = -pot(radius); if (Qphi) Phi(bp) = psi0; vmax2 = 2.0*psi0; vmax = sqrt(vmax2); fmax = f(psi0); f0 = fmax; f1 = 1.1*fmax; /* just some initial values */ while( f1 > f0 ) { /* pick a velocity */ v2 = 2.0*vmax2; while( v2 > vmax2 ) { /* rejection technique */ vx = vmax*xrandom(-1.0,1.0); vy = vmax*xrandom(-1.0,1.0); vz = vmax*xrandom(-1.0,1.0); v2 = vx*vx + vy*vy + vz*vz; } f0 = f((psi0 - 0.5*v2)); f1 = fmax*xrandom(0.0,1.0); } Vel(bp)[0] = vx; Vel(bp)[1] = vy; Vel(bp)[2] = vz; } mg = 1.0/nobj; mh = mu/nobj; for(i=0, bp=btab; i<2*nobj; i++, bp++) { if (i<nobj) Mass(bp) = mg; else Mass(bp) = mh; } if (Qcenter) cofm(); bits = MassBit | PhaseSpaceBit; if (Qphi) bits |= PotentialBit; nobj *= 2; tsnap = 0.0; put_snap(outstr, &btab, &nobj, &tsnap, &bits); strclose(outstr); }
void nemo_main () { string fnames; stream instr; /* input file (optional) */ stream outstr; /* output file */ int size[3],nx, ny, nz; /* size of scratch map */ int ncen; string object; string headline; int seed = init_xrandom(getparam("seed")); object = getparam("object"); npar = nemoinpr(getparam("spar"),spar,MAXPAR); if (npar < 0) error("Syntax error %s",getparam("spar")); Qtotflux = getbparam("totflux"); factor = getdparam("factor"); pa = getdparam("pa"); inc = getdparam("inc"); sinp = sin(pa*PI/180.0); cosp = cos(pa*PI/180.0); sini = sin(inc*PI/180.0); cosi = cos(inc*PI/180.0); dprintf(0,"%s: disk with pa=%g inc=%g\n",object,pa,inc); dprintf(1,"pa(%g %g) inc(%g %g)\n",sinp,cosp,sini,cosi); ncen = nemoinpr(getparam("center"),center,2); if (ncen<0) error("Syntax error %s",getparam("center")); if (ncen==1) center[1] = center[0]; init_xrandom(getparam("seed")); nwcs = nemorinpd(getparam("crval"),crval,MAXNAX,0.0,FALSE); nwcs = nemorinpd(getparam("cdelt"),cdelt,MAXNAX,1.0,FALSE); nwcs = nemorinpd(getparam("crpix"),crpix,MAXNAX,1.0,FALSE); if (hasvalue("in")) { instr = stropen(getparam("in"),"r"); /* open file */ read_image (instr, &iptr); } else { dprintf(0,"Generating a map from scratch\n"); switch (nemoinpi(getparam("size"),size,3)) { case 1: /* nx[,nx,1] */ size[1] = size[0]; size[2] = 1; break; case 2: /* nx,ny[,1] */ size[2] = 1; break; case 3: /* nx,ny,nz */ break; case 0: /* [10,10,1] */ dprintf(0,"Cannot have no size, default 10 assumed\n"); size[0] = size[1] = 10; size[2] = 1; break; default: /* --- some error --- */ error("Syntax error in size keyword\n"); } nx = size[0]; ny = size[1]; nz = size[2]; do_create(nx,ny,nz); #if 0 if (nwcs == 0) { /* last one for crpix */ warning("going to set the center of the map in new NEMO convention"); crpix[0] = (nx-1)/2.0; crpix[1] = (ny-1)/2.0; crpix[2] = (nz-1)/2.0; } #endif } if (ncen==0) { /* fix center if it has not been set yet */ center[0] = (Nx(iptr)-1)/2.0; /* 0 based center= */ center[1] = (Ny(iptr)-1)/2.0; } dprintf(0,"%s: center pixel: %g %g\n",object,center[0],center[1]); surface = Dx(iptr)*Dy(iptr); surface = ABS(surface); if (streq(object,"flat")) object_flat(npar,spar); else if (streq(object,"exp")) object_exp(npar,spar); else if (streq(object,"gauss")) object_gauss(npar,spar); else if (streq(object,"bar")) object_bar(npar,spar); else if (streq(object,"ferrers")) object_ferrers(npar,spar); else if (streq(object,"spiral")) object_spiral(npar,spar); else if (streq(object,"noise")) object_noise(npar,spar); else if (streq(object,"jet")) object_jet(npar,spar); else if (streq(object,"j1x")) object_j1x(npar,spar); else if (streq(object,"isothermal")) object_isothermal(npar,spar); else if (streq(object,"comet")) object_comet(npar,spar); else if (streq(object,"shell")) object_shell(npar,spar); else error("Unknown object %g",object); outstr = stropen (getparam("out"),"w"); /* open output file first ... */ if (hasvalue("headline")) set_headline(getparam("headline")); write_image (outstr,iptr); /* write image to file */ strclose(outstr); }
void nemo_main() { stream instr, outstr; int nx, ny, nz, nx1, ny1, nz1; int axis, mom; int i,j,k, apeak, cnt; imageptr iptr=NULL, iptr1=NULL, iptr2=NULL; /* pointer to images */ real tmp0, tmp1, tmp2, tmp00, newvalue, peakvalue, scale, offset; bool Qpeak; instr = stropen(getparam("in"), "r"); mom = 0; axis = 3; Qpeak = getbparam("peak"); read_image( instr, &iptr); nx1 = nx = Nx(iptr); ny1 = ny = Ny(iptr); nz1 = 1; nz = Nz(iptr); outstr = stropen(getparam("out"), "w"); create_cube(&iptr1,nx1,ny1,nz1); create_cube(&iptr2,nx1,ny1,nz1); scale = Dz(iptr); offset = Zmin(iptr); for(j=0; j<ny; j++) for(i=0; i<nx; i++) { tmp0 = tmp00 = tmp1 = tmp2 = 0.0; cnt = 0; peakvalue = CubeValue(iptr,i,j,0); for(k=0; k<nz; k++) { if (out_of_range(CubeValue(iptr,i,j,k))) continue; cnt++; tmp0 += CubeValue(iptr,i,j,k); tmp00 += sqr(CubeValue(iptr,i,j,k)); if (CubeValue(iptr,i,j,k) > peakvalue) { apeak = k; peakvalue = CubeValue(iptr,i,j,k); } } if (cnt==0 || tmp0==0.0) { newvalue = 0.0; } else { if (Qpeak) newvalue = peakvalue; else newvalue = tmp0; } CubeValue(iptr1,i,j,1) = newvalue; } Xmin(iptr1) = Xmin(iptr); Ymin(iptr1) = Ymin(iptr); Zmin(iptr1) = Zmin(iptr) + 0.5*(nz-1)*Dz(iptr); Dx(iptr1) = Dx(iptr); Dy(iptr1) = Dy(iptr); Dz(iptr1) = nz * Dz(iptr); Namex(iptr1) = Namex(iptr); /* care: we're passing a pointer */ Namey(iptr1) = Namey(iptr); Namez(iptr1) = Namez(iptr); write_image(outstr, iptr1); }
void nemo_main() { stream instr, outstr; int nx, ny, nz; int nstep,nstep1; int i,j,k, n, n1, i1, j1, m; int ix[2], iy[2]; imageptr iptr=NULL, optr; /* pointer to images */ real *vals, fraction; string mode = getparam("mode"); bool Qmedian = (*mode == 'm'); bool Qmean = (*mode == 'a'); nstep = getiparam("nstep"); if (nstep%2 != 1) error("step size %d needs to be odd",nstep); nstep1 = (nstep-1)/2; n = getiparam("n"); if (Qmedian) dprintf(1,"Median filter size %d\n",n); else if (Qmean) dprintf(1,"Mean filter size %d\n",n); else dprintf(1,"Subtraction filter size %d\n",n); if (n%2 != 1) error("filter size %d needs to be odd",n); n1 = (n-1)/2; vals = (real *) allocate (sizeof(real) * (n*n + 1)); instr = stropen(getparam("in"), "r"); read_image( instr, &iptr); nx = Nx(iptr); ny = Ny(iptr); nz = Nz(iptr); if (nz > 1) error("Cannot do 3D cubes properly; use 2D"); if (hasvalue("x") && hasvalue("y")) { get_range("x",ix); get_range("y",iy); } else { ix[0] = 0; ix[1] = nx-1; iy[0] = 0; iy[1] = ny-1; } dprintf(1,"Xrange: %d - %d Yrange: %d - %d\n",ix[0],ix[1],iy[0],iy[1]); outstr = stropen(getparam("out"), "w"); create_cube(&optr,nx,ny,nz); Dx(optr) = Dx(iptr); Dy(optr) = Dy(iptr); Dz(optr) = Dz(iptr); Xmin(optr) = Xmin(iptr); Ymin(optr) = Ymin(iptr); Zmin(optr) = Zmin(iptr); if (nstep > 1) { warning("Cheat mode nstep=%d",nstep); for (j=nstep1; j<ny-nstep1; j+=nstep) { for (i=nstep1; i<nx-nstep1; i+=nstep) { if (j<n1 || j >= ny-n1 || j < iy[0] || j > iy[1]) { CVO(i,j) = CVI(i,j); continue; } if (i<n1 || i >= nx-n1 || i < ix[0] || i > ix[1]) { CVO(i,j) = CVI(i,j); continue; } m = 0; for (j1=j-n1; j1<=j+n1; j1++) for (i1=i-n1; i1<=i+n1; i1++) vals[m++] = CVI(i1,j1); CVO(i,j) = median(m,vals,fraction); for (j1=j-nstep1; j1<=j+nstep1; j1++) for (i1=i-nstep1; i1<=i+nstep1; i1++) CVO(i1,j1) = CVO(i,j); } } } else { for (j=0; j<ny; j++) { for (i=0; i<nx; i++) { if (j<n1 || j >= ny-n1 || j < iy[0] || j > iy[1]) { CVO(i,j) = CVI(i,j); continue; } if (i<n1 || i >= nx-n1 || i < ix[0] || i > ix[1]) { CVO(i,j) = CVI(i,j); continue; } m = 0; for (j1=j-n1; j1<=j+n1; j1++) for (i1=i-n1; i1<=i+n1; i1++) vals[m++] = CVI(i1,j1); if (Qmedian) CVO(i,j) = median(m,vals,fraction); else if (Qmean) CVO(i,j) = mean(m,vals,fraction); else CVO(i,j) = subtract(m,vals,fraction); } } } write_image(outstr, optr); }