LALFrameUFrameH *XLALFrameUFrameHRead_FrameL_(LALFrameUFrFile * stream, int pos) { LALFrameUFrameH *frame; LALFrameUFrameH *copy; /* make sure the TOC is read */ if (stream->handle->toc == NULL) if (FrTOCReadFull(stream->handle) == NULL || stream->handle->error != FR_OK) XLAL_ERROR_NULL(XLAL_EIO, "FrTOCReadFull failed with error code %s.", XLALFrameLErrorMessage(stream->handle->error)); /* go to the right position */ if (FrFileIOSet(stream->handle, stream->handle->toc->positionH[pos]) == -1) XLAL_ERROR_NULL(XLAL_EIO, "FrFileIOSet failed with error code %s.", XLALFrameLErrorMessage(stream->handle->error)); /* get the frame */ frame = FrameRead(stream->handle); if (!frame || stream->handle->error != FR_OK) XLAL_ERROR_NULL(XLAL_EIO, "FrameRead failed with error code %s.", XLALFrameLErrorMessage(stream->handle->error)); copy = FrameHCopy(frame); FrSetIni(stream->handle); stream->handle->curFrame = NULL; FrameFree(frame); return copy; }
int main(int argc, char *argv[]) { char history[] = "Created by " PACKAGE "-" VERSION "."; FILE *devnull; struct options options; int i; struct FrFile *frfileout; options = parse_command_line(argc, argv); /* note the hack to silence libframe if --verbose is not given */ devnull = fopen("/dev/null", "w"); FrLibIni(NULL, options.verbose || !devnull ? stderr : devnull, 0); if(devnull) fclose(devnull); if(options.verbose) fprintf(stderr, "%s: writing to \"%s\"\n", argv[0], options.outfile); frfileout = FrFileONewH(options.outfile, 0, history); if(!frfileout) { fprintf(stderr, "%s: error: could not open output file \"%s\"\n", argv[0], options.outfile); exit(1); } for(i = 0; i < options.n_infiles; i++) { struct FrFile *frfilein; struct FrameH *frame; if(options.verbose) fprintf(stderr, "%s: reading \"%s\"\n", argv[0], options.infiles[i]); frfilein = FrFileINew(options.infiles[i]); if(!frfilein) { FrFileOEnd(frfileout); fprintf(stderr, "%s: error: input file \"%s\" not found\n", argv[0], options.infiles[i]); exit(1); } while((frame = FrameRead(frfilein))) { FrameWrite(frame, frfileout); FrameFree(frame); } FrFileIEnd(frfilein); } FrFileOEnd(frfileout); exit(0); }
void MainCoro() { int _WorldTimer = 0; int _DrawTimer = 0; int _Ticks = 0; while(g_VideoOk != 0) { _Ticks = SDL_GetTicks(); Events(); if(_DrawTimer + 16 <= _Ticks) { Draw(); _DrawTimer = _Ticks; } if(g_GameWorld.IsPaused == 0 && (_WorldTimer + GAME_TICK) <= _Ticks) { World_Tick(); _WorldTimer = _Ticks; FrameFree(); } ++g_TaskPool->Time; } }
static int Integrate(This *t, real *integral, real *error, real *prob) { TYPEDEFREGION; typedef struct pool { struct pool *next; Region region[POOLSIZE]; } Pool; count dim, comp, ncur, ipool, npool; int fail; Totals totals[NCOMP]; Pool *cur = NULL, *pool; Region *region; if( VERBOSE > 1 ) { char s[256]; sprintf(s, "Cuhre input parameters:\n" " ndim " COUNT "\n ncomp " COUNT "\n" " epsrel " REAL "\n epsabs " REAL "\n" " flags %d\n mineval " NUMBER "\n maxeval " NUMBER "\n" " key " COUNT, t->ndim, t->ncomp, t->epsrel, t->epsabs, t->flags, t->mineval, t->maxeval, t->key); Print(s); } if( BadComponent(t) ) return -2; if( BadDimension(t) ) return -1; t->epsabs = Max(t->epsabs, NOTZERO); RuleAlloc(t); t->mineval = IMax(t->mineval, t->rule.n + 1); FrameAlloc(t, ShmRm(t)); ForkCores(t); if( (fail = setjmp(t->abort)) ) goto abort; Alloc(cur, 1); cur->next = NULL; ncur = 1; region = cur->region; region->div = 0; for( dim = 0; dim < t->ndim; ++dim ) { Bounds *b = ®ion->bounds[dim]; b->lower = 0; b->upper = 1; } Sample(t, region); for( comp = 0; comp < t->ncomp; ++comp ) { Totals *tot = &totals[comp]; Result *r = ®ion->result[comp]; tot->avg = tot->lastavg = tot->guess = r->avg; tot->err = tot->lasterr = r->err; tot->weightsum = 1/Max(Sq(r->err), NOTZERO); tot->avgsum = tot->weightsum*r->avg; tot->chisq = tot->chisqsum = tot->chisum = 0; } for( t->nregions = 1; ; ++t->nregions ) { count maxcomp, bisectdim; real maxratio, maxerr; Result result[NCOMP]; Region *regionL, *regionR; Bounds *bL, *bR; if( VERBOSE ) { char s[128 + 128*NCOMP], *p = s; p += sprintf(p, "\n" "Iteration " COUNT ": " NUMBER " integrand evaluations so far", t->nregions, t->neval); for( comp = 0; comp < t->ncomp; ++comp ) { cTotals *tot = &totals[comp]; p += sprintf(p, "\n[" COUNT "] " REAL " +- " REAL " \tchisq " REAL " (" COUNT " df)", comp + 1, tot->avg, tot->err, tot->chisq, t->nregions - 1); } Print(s); } maxratio = -INFTY; maxcomp = 0; for( comp = 0; comp < t->ncomp; ++comp ) { creal ratio = totals[comp].err/MaxErr(totals[comp].avg); if( ratio > maxratio ) { maxratio = ratio; maxcomp = comp; } } if( maxratio <= 1 && t->neval >= t->mineval ) break; if( t->neval >= t->maxeval ) { fail = 1; break; } maxerr = -INFTY; regionL = cur->region; npool = ncur; for( pool = cur; pool; npool = POOLSIZE, pool = pool->next ) for( ipool = 0; ipool < npool; ++ipool ) { Region *region = &pool->region[ipool]; creal err = region->result[maxcomp].err; if( err > maxerr ) { maxerr = err; regionL = region; } } if( ncur == POOLSIZE ) { Pool *prev = cur; Alloc(cur, 1); cur->next = prev; ncur = 0; } regionR = &cur->region[ncur++]; regionR->div = ++regionL->div; FCopy(result, regionL->result); XCopy(regionR->bounds, regionL->bounds); bisectdim = result[maxcomp].bisectdim; bL = ®ionL->bounds[bisectdim]; bR = ®ionR->bounds[bisectdim]; bL->upper = bR->lower = .5*(bL->upper + bL->lower); Sample(t, regionL); Sample(t, regionR); for( comp = 0; comp < t->ncomp; ++comp ) { cResult *r = &result[comp]; Result *rL = ®ionL->result[comp]; Result *rR = ®ionR->result[comp]; Totals *tot = &totals[comp]; real diff, err, w, avg, sigsq; tot->lastavg += diff = rL->avg + rR->avg - r->avg; diff = fabs(.25*diff); err = rL->err + rR->err; if( err > 0 ) { creal c = 1 + 2*diff/err; rL->err *= c; rR->err *= c; } rL->err += diff; rR->err += diff; tot->lasterr += rL->err + rR->err - r->err; tot->weightsum += w = 1/Max(Sq(tot->lasterr), NOTZERO); sigsq = 1/tot->weightsum; tot->avgsum += w*tot->lastavg; avg = sigsq*tot->avgsum; tot->chisum += w *= tot->lastavg - tot->guess; tot->chisqsum += w*tot->lastavg; tot->chisq = tot->chisqsum - avg*tot->chisum; if( LAST ) { tot->avg = tot->lastavg; tot->err = tot->lasterr; } else { tot->avg = avg; tot->err = sqrt(sigsq); } } } for( comp = 0; comp < t->ncomp; ++comp ) { cTotals *tot = &totals[comp]; integral[comp] = tot->avg; error[comp] = tot->err; prob[comp] = ChiSquare(tot->chisq, t->nregions - 1); } #ifdef MLVERSION if( REGIONS ) { MLPutFunction(stdlink, "List", 2); MLPutFunction(stdlink, "List", t->nregions); npool = ncur; for( pool = cur; pool; npool = POOLSIZE, pool = pool->next ) for( ipool = 0; ipool < npool; ++ipool ) { Region const *region = &pool->region[ipool]; real lower[NDIM], upper[NDIM]; for( dim = 0; dim < t->ndim; ++dim ) { cBounds *b = ®ion->bounds[dim]; lower[dim] = b->lower; upper[dim] = b->upper; } MLPutFunction(stdlink, "Cuba`Cuhre`region", 3); MLPutRealList(stdlink, lower, t->ndim); MLPutRealList(stdlink, upper, t->ndim); MLPutFunction(stdlink, "List", t->ncomp); for( comp = 0; comp < t->ncomp; ++comp ) { cResult *r = ®ion->result[comp]; real res[] = {r->avg, r->err}; MLPutRealList(stdlink, res, Elements(res)); } } } #endif abort: while( (pool = cur) ) { cur = cur->next; free(pool); } WaitCores(t); FrameFree(t); RuleFree(t); return fail; }
void XLALFrameUFrameHFree_FrameL_(LALFrameUFrameH * frame) { FrameFree(frame); return; }
static int Integrate(This *t, real *integral, real *error, real *prob) { bin_t *bins; count dim, comp; int fail; struct { count niter; number nsamples, neval; Cumulants cumul[NCOMP]; Grid grid[NDIM]; } state; int statemsg = VERBOSE; struct stat st; if( VERBOSE > 1 ) { char s[512]; sprintf(s, "Vegas input parameters:\n" " ndim " COUNT "\n ncomp " COUNT "\n" " epsrel " REAL "\n epsabs " REAL "\n" " flags %d\n seed %d\n" " mineval " NUMBER "\n maxeval " NUMBER "\n" " nstart " NUMBER "\n nincrease " NUMBER "\n" " nbatch " NUMBER "\n gridno %d\n" " statefile \"%s\"", t->ndim, t->ncomp, t->epsrel, t->epsabs, t->flags, t->seed, t->mineval, t->maxeval, t->nstart, t->nincrease, t->nbatch, t->gridno, t->statefile); Print(s); } if( BadComponent(t) ) return -2; if( BadDimension(t) ) return -1; FrameAlloc(t, ShmRm(t)); ForkCores(t); Alloc(bins, t->nbatch*t->ndim); if( (fail = setjmp(t->abort)) ) goto abort; IniRandom(t); if( t->statefile && *t->statefile == 0 ) t->statefile = NULL; if( t->statefile && stat(t->statefile, &st) == 0 && st.st_size == sizeof state && (st.st_mode & 0400) ) { cint h = open(t->statefile, O_RDONLY); read(h, &state, sizeof state); close(h); t->rng.skiprandom(t, t->neval = state.neval); if( VERBOSE ) { char s[256]; sprintf(s, "\nRestoring state from %s.", t->statefile); Print(s); } } else { state.niter = 0; state.nsamples = t->nstart; Zap(state.cumul); GetGrid(t, state.grid); } /* main iteration loop */ for( ; ; ) { number nsamples = state.nsamples; creal jacobian = 1./nsamples; Grid margsum[NCOMP][NDIM]; Zap(margsum); for( ; nsamples > 0; nsamples -= t->nbatch ) { cnumber n = IMin(t->nbatch, nsamples); real *w = t->frame; real *x = w + n; real *f = x + n*t->ndim; real *lastf = f + n*t->ncomp; bin_t *bin = bins; while( x < f ) { real weight = jacobian; t->rng.getrandom(t, x); for( dim = 0; dim < t->ndim; ++dim ) { creal pos = *x*NBINS; ccount ipos = (count)pos; creal prev = (ipos == 0) ? 0 : state.grid[dim][ipos - 1]; creal diff = state.grid[dim][ipos] - prev; *x++ = prev + (pos - ipos)*diff; *bin++ = ipos; weight *= diff*NBINS; } *w++ = weight; } DoSample(t, n, w, f, t->frame, state.niter + 1); bin = bins; w = t->frame; while( f < lastf ) { creal weight = *w++; for( comp = 0; comp < t->ncomp; ++comp ) { real wfun = weight*(*f++); if( wfun ) { Cumulants *c = &state.cumul[comp]; Grid *m = margsum[comp]; c->sum += wfun; c->sqsum += wfun *= wfun; for( dim = 0; dim < t->ndim; ++dim ) m[dim][bin[dim]] += wfun; } } bin += t->ndim; } } fail = 0; /* compute the integral and error values */ for( comp = 0; comp < t->ncomp; ++comp ) { Cumulants *c = &state.cumul[comp]; real avg, sigsq; real w = Weight(c->sum, c->sqsum, state.nsamples); sigsq = 1/(c->weightsum += w); avg = sigsq*(c->avgsum += w*c->sum); c->avg = LAST ? (sigsq = 1/w, c->sum) : avg; c->err = sqrt(sigsq); fail |= (c->err > MaxErr(c->avg)); if( state.niter == 0 ) c->guess = c->sum; else { c->chisum += w *= c->sum - c->guess; c->chisqsum += w*c->sum; } c->chisq = c->chisqsum - avg*c->chisum; c->sum = c->sqsum = 0; } if( VERBOSE ) { char s[128 + 128*NCOMP], *p = s; p += sprintf(p, "\n" "Iteration " COUNT ": " NUMBER " integrand evaluations so far", state.niter + 1, t->neval); for( comp = 0; comp < t->ncomp; ++comp ) { cCumulants *c = &state.cumul[comp]; p += sprintf(p, "\n[" COUNT "] " REAL " +- " REAL " \tchisq " REAL " (" COUNT " df)", comp + 1, c->avg, c->err, c->chisq, state.niter); } Print(s); } if( fail == 0 && t->neval >= t->mineval ) { if( t->statefile && KEEPFILE == 0 ) unlink(t->statefile); break; } if( t->neval >= t->maxeval && t->statefile == NULL ) break; if( t->ncomp == 1 ) for( dim = 0; dim < t->ndim; ++dim ) RefineGrid(t, state.grid[dim], margsum[0][dim]); else { for( dim = 0; dim < t->ndim; ++dim ) { Grid wmargsum; Zap(wmargsum); for( comp = 0; comp < t->ncomp; ++comp ) { real w = state.cumul[comp].avg; if( w != 0 ) { creal *m = margsum[comp][dim]; count bin; w = 1/Sq(w); for( bin = 0; bin < NBINS; ++bin ) wmargsum[bin] += w*m[bin]; } } RefineGrid(t, state.grid[dim], wmargsum); } } ++state.niter; state.nsamples += t->nincrease; if( t->statefile ) { cint h = creat(t->statefile, 0666); if( h != -1 ) { state.neval = t->neval; write(h, &state, sizeof state); close(h); if( statemsg ) { char s[256]; sprintf(s, "\nSaving state to %s.", t->statefile); Print(s); statemsg = false; } } if( t->neval >= t->maxeval ) break; } } for( comp = 0; comp < t->ncomp; ++comp ) { cCumulants *c = &state.cumul[comp]; integral[comp] = c->avg; error[comp] = c->err; prob[comp] = ChiSquare(c->chisq, state.niter); } abort: PutGrid(t, state.grid); free(bins); WaitCores(t); FrameFree(t); return fail; }
int main(int argc, char *argv[]){ int i,j; #ifdef ONLINE char *cwd; int iarg, status; SIStream sis; char info[MAXLINE]; memset(&sis, '\0', sizeof(SIStream)); #endif parseinput(argc, argv); syserror(0, "Starting up\n"); /* install signal handler to catch SIGCHLD. Note that solaris uses SysV rather than BSD semantics and doesn't automaticall restart system calls like fread and fwrite. So we use sigaction() rather than signal() so that we can set SA_RESTART. */ { struct sigaction sig; memset(&sig, '\0', sizeof(sig)); sig.sa_flags=SA_RESTART; sig.sa_handler=sighandler; if (sigaction(SIGCHLD, &sig, NULL)){ syserror(1, "Unable to install signal handler for messages about troubled children\n"); } if (sigaction(SIGTERM, &sig, NULL)){ syserror(1, "Unable to install signal handler for logging output rate data and terminating\n"); } if (sigaction(SIGUSR1, &sig, NULL)){ syserror(1, "Unable to install signal handler for logging output rate data\n"); } } for (i=0; i<npulsars; i++){ char command[MAXLINE]; char filename[MAXLINE]; FILE *fpc=NULL; int length=0; char *newlineloc=NULL; /* construct file name */ if (snprintf(filename, MAXLINE, "%s/in.%d", directory, i)>MAXLINE-1){ syserror(0, "%s: file name %s/in.%d has more than MAXLINE=%d characters\n", programname, directory, i, MAXLINE); exit(1); } /* open file */ if (!(fpc=fopen(filename, "r"))) { syserror(1, "Can't open file %s for reading\n", filename); exit(1); } /* read command line from file */ if (!(fgets(command, MAXLINE, fpc))){ syserror(1, "Command line file %s was empty!\n", filename); exit(1); } fclose(fpc); /* check that contents are not too large */ length=strlen(command); if (length>=MAXLINE-1) { syserror(0, "Command line file %s has line >= to MAXLINE=%d characters!\n", filename, MAXLINE); exit(1); } /* replace first NEWLINE to null terminate string */ if ((newlineloc=strchr(command, '\n'))) *newlineloc='\0'; /* append additional arguments to command line */ /* GPS starttime */ length=strlen(command); if (snprintf(command+length, MAXLINE-length, " -G %d", gpstime)>MAXLINE-length-1){ command[length]='\0'; syserror(0, "%s: command line has >= MAXLINE=%d characters\n", programname, MAXLINE); exit(1); } /* IFO */ length=strlen(command); if ( snprintf(command+length, MAXLINE-length, " -I %s", ifo_name) > MAXLINE-length-1 ) { command[length]='\0'; syserror(0, "%s: command line has >= MAXLINE=%d characters\n", programname, MAXLINE); exit(1); } /* Actuation-function if given */ if (actuation) { length=strlen(command); if ( snprintf(command+length, MAXLINE-length, " --actuation=%s", actuation) > MAXLINE-length-1 ) { command[length]='\0'; syserror(0, "%s: command line has >= MAXLINE=%d characters\n", programname, MAXLINE); exit(1); } } /* now either show the command or execute it */ if (show) printf("[%02d] %s\n", i, command); else { errno=0; if (!(fp[i]=popen(command, "r")) || errno){ syserror(1, "Unable to popen(3) %s\n", command); exit(1); } } } /* a useful option for debugging -- show the output */ if (show) { if (!npulsars) printf("%s: Warning: n=0 so an infinite-length zero strength signal will be made!\n", argv[0]); exit(0); } #if 0 { pid_t pid; int status; /* wait a couple of seconds, then check that all processes are running happily! */ sleep(2); pid=waitpid(-1, &status, WNOHANG | WUNTRACED); if (pid) { syserror(0,"Subprocess with PID=%d is misbehaving.\n", (int)pid); if (WIFEXITED(status)) syserror(0, "Subprocess or shell did exit(%d)\n", WEXITSTATUS(status)); if (WIFSIGNALED(status)) syserror(0, "Subprocess terminated because it caught signal %d [%s]\n", WTERMSIG(status), strsignal(WTERMSIG(status))); exit(1); } } #endif /* processes opened, read data*/ for (i=0; i<npulsars; i++){ if (fread(&testval, sizeof(float), 1, fp[i]) != 1) { syserror(1, "Could not read first float 1234.5 from %d'th signal source\n", i); exit(1); } else if (testval != 1234.5) { syserror(0, "First value (%f) from %d'th signal source was not 1234.5\n", testval, i); exit(1); } else if (fread(bufflen+i, sizeof(int), 1, fp[i]) != 1) { syserror(1, "Could not read buffer size from %d'th signal source\n", i); exit(1); } else if (bufflen[i]<sampling_rate || bufflen[i]>sampling_rate*60) { syserror(0, "Bad buffer size %d floats from %d'th signal source (expect %d <= size <= %d)\n", bufflen[i], i, sampling_rate, 60*sampling_rate); exit(1); } else if (bufflen[i]% BLOCKSIZE) { syserror(0, "Bad buffer size %d floats from %d'th signal source NOT a multiple of BLOCKSIZE=%d\n", bufflen[i], i, BLOCKSIZE); exit(1); } else if (!(buffs[i]=(float *)calloc(bufflen[i], sizeof(float)))) { syserror(1, "Can't allocate buffer of %d floats for %d'th signal source\n", bufflen[i], i); exit(1); } /* ensure that we read buffers on first pass */ readfrombuff[i]=bufflen[i]; } /* are we calling the excitation engine directly? */ if (channel) { #ifdef ONLINE /* Report some information about this injection client */ cwd = getcwd( NULL, 256 ); if ( cwd ) { sprintf( info, "%s %s", argv[0], cwd ); } else { sprintf( info, "%s unknown_directory", argv[0] ); } free( cwd ); SIStrAppInfo( info ); /* Open the Signal Injection Stream */ status = SIStrOpen( &sis, channel, sampling_rate, (double) gpstime + starttime_offset_eff ); if ( SIStr_debug ) { syserror(0, "SIStrOpen() returned %d\n", status ); } if ( status != SIStr_OK ) { syserror(0, "SIStrOpen() error opening SIStream: %s\n", SIStrErrorMsg(status) ); exit(2); } #endif } else if (do_text) printf("1234.5\n"); else { /* write out 1234.5 */ if (1!=fwrite(&testval, sizeof(float), 1, stdout)){ syserror(1, "Unable to output key value 1234.5\n"); exit(1); } } /* now read data blocks unless a SIGTERM has set shutdown */ while (!shutdown_pulsar_injection) { int num=0; int line; int tdelt=gpstime-tfiducial; /* clear block that will contain totals */ for (j=0; j<BLOCKSIZE; j++) total[j]=0.0; /* if needed, insert calibration line(s) */ for (line=0; line<3; line++){ if (calamp[line] != 0.0) { /* normal int and double variables for integer/fractional time. In this and in the code that follows, _fra refers to the fractional part [0,1) and _int refers to the integer part. */ double dt_fra; /* Avoid long longs in inner loop as they are slow. */ long long t_rem=blocks, t_int=BLOCKSIZE; /* line amplitude and frequency (integer + fractional parts) */ double f_fra = calfreq[line]; int f_int = (int)f_fra; f_fra -= f_int; /* integer and fractional time offsets of first sample */ t_rem *= t_int; t_int = t_rem; t_int /= sampling_rate; t_rem -= t_int*sampling_rate; t_int += tdelt; // unused: int dt_int = t_int; dt_fra = t_rem; dt_fra /= sampling_rate; for (j=0; j<BLOCKSIZE; j++) { double cycles1, cycles2, cycles3; double tlocal_fra = dt_fra+(double)j/((double)sampling_rate); int tlocal_int = (int)tlocal_fra; tlocal_fra -= tlocal_int; tlocal_int += t_int; cycles1 = f_fra*tlocal_int; cycles1 -= (int)cycles1; cycles2 = tlocal_fra*f_int; cycles2 -= (int)cycles2; cycles3 = tlocal_fra*f_fra; cycles3 -= (int)cycles3; total[j]=calamp[line]*sin(2*LAL_PI*(cycles1+cycles2+cycles3)); } } } /* loop over the different pulsars */ for (i=0; i<npulsars; i++) { float *where; if (readfrombuff[i]==bufflen[i]){ /* read data from the i'th signal */ if (bufflen[i]!=(num=fread(buffs[i], sizeof(float), bufflen[i], fp[i]))){ syserror(1, "Only read %d floats (not %d) from %d'th signal source\n", num, bufflen[i], i); exit(1); } #ifdef DEBUGTIMING syserror(0, "just read %d seconds of data from %d'th signal\n", num/sampling_rate, i); #endif readfrombuff[i]=0; } /* location of signal in buffer */ where=buffs[i]+readfrombuff[i]; /* add i'th pulsar to the total signal */ for (j=0; j<BLOCKSIZE; j++) total[j]+=where[j]; readfrombuff[i]+=BLOCKSIZE; } /* now output the total signal to frames */ if (write_frames) { #ifdef HAVE_LIBLALFRAME static int counter = 0; static FrFile *oFile; FrameH *frame; FrSimData *sim; int m, level = 0; long ndata = BLOCKSIZE; char framename[256]; struct stat statbuf; /* This leads to a names like: CW_Injection-921517800-60.gwf */ sprintf(framename, "CW_Injection"); frame = FrameHNew(framename); if (!frame) { syserror(1, "FrameNew failed (%s)", FrErrorGetHistory()); exit(1); } /* set up GPS time, sample interval, copy data */ frame->GTimeS = gpstime + counter; frame->GTimeN = 0; frame->dt = ndata/sampling_rate; char frName[] = "CW_simulated"; sim = FrSimDataNew(frame, frName, sampling_rate, ndata, -32); for (m=0; m < ndata; m++) { sim->data->dataF[m] = total[m]; } /* open framefile, to contain secs_per_framefile of data */ if (!counter) { oFile = FrFileONewM(framename, level, argv[0], secs_per_framefile); if (!oFile) { syserror(1, "Cannot open output file %s\n", framename); exit(1); } /* Turn off the 'framefile boundary alignment'. Without this one gets: CW_Injection-921517807-3.gwf CW_Injection-921517810-10.gwf CW_Injection-921517820-10.gwf ... With this one gets CW_Injection-921517807-10.gwf CW_Injection-921517817-10.gwf ... */ oFile->aligned = FR_NO; } /* write data to framefile */ if (FR_OK != FrameWrite(frame, oFile)) { syserror(1, "Error during frame write\n" " Last errors are:\n%s", FrErrorGetHistory()); exit(1); } /* free memory for frames and for simdata structures */ FrameFree(frame); /* Do we keep a limited set of frames on disk? */ if (write_frames>1) { char listname[256]; int watchtime = gpstime + secs_per_framefile*(counter/secs_per_framefile - write_frames + 1); sprintf(listname, "CW_Injection-%d-%d.gwf", watchtime, secs_per_framefile); /* syserror(0, "Watching for file %s to disappear....\n", listname); */ while (!stat(listname, &statbuf)) { /* if enough files already in place, then sleep 0.1 seconds */ struct timespec rqtp; rqtp.tv_sec = 0; rqtp.tv_nsec = 100000000; nanosleep(&rqtp, NULL); } } /* increment counter for the next second */ counter++; #else syserror(0, "ERROR: write_frames!=0, but binary was built without Frame support\n" ); exit(1); #endif } /* if (write_frames) */ /* now output the total signal... */ else if (channel){ #ifdef ONLINE /* ... to the excitation engine ... */ status = SIStrAppend( &sis, total, BLOCKSIZE, 1.0 ); if ( SIStr_debug >= 2 ) syserror(0, "SIStrAppend() returned %d\n", status ); if ( status != SIStr_OK ) { syserror(0, "SIStrAppend() error adding data to stream: %s\n", SIStrErrorMsg(status) ); break; } #endif } /* ... or as text ... */ else if (do_text){ if (do_axis){ /* ... either as text with both x and y axes ... */ long long x1=gpstime; long long E9=1000000000; x1*=E9; x1 += (long long)(starttime_offset_eff * E9 ); /* account for startime-shift, consistent with CHANNEL injection */ for (j=0; j<BLOCKSIZE; j++){ long long x2=count, x3; x2 *= E9; x2 /= (sampling_rate); x2 += x1; x3 = x2; x3 /= E9; x2 -= x3*E9; printf("%lld.%09lld %g\n", x3, x2, total[j]); count++; } } else { /* ... or as y-axis text only ... */ for (j=0; j<BLOCKSIZE; j++) printf("%g\n", total[j]); } } else { /* ... or in raw binary form. */ if (BLOCKSIZE!=(num=fwrite(total, sizeof(float), BLOCKSIZE, stdout))){ syserror(1, "Only wrote %d values (not %d)\n", num, BLOCKSIZE); exit(1); } #ifdef DEBUGTIMING syserror(0, "Just sent %d seconds of data to system\n", BLOCKSIZE/sampling_rate); sleep(BLOCKSIZE/sampling_rate); #endif } /* increment counter of blocks sent out */ blocks++; } /* We'll be exiting, so clean up */ if (channel) { #ifdef ONLINE /* Close the signal injection stream */ status = SIStrClose( &sis ); if ( SIStr_debug ) syserror(0, "SIStrClose returned %d\n", status ); if ( status != SIStr_OK ) { syserror(0, "Error while closing SIStream: %s\n", SIStrErrorMsg(status) ); exit(2); } #endif } #ifdef _LINUX /* shut down signal handler for SIGCHLD */ { struct sigaction sig; memset(&sig, '\0', sizeof(sig)); sig.sa_flags=SA_RESTART | SA_NOCLDSTOP; sig.sa_handler=SIG_IGN; if (sigaction(SIGCHLD, &sig, NULL)){ syserror(1, "Unable to install signal handler for exiting\n"); } if (sigaction(SIGPIPE, &sig, NULL)){ syserror(1, "Unable to install signal handler for exiting\n"); } } for (i=0; i<npulsars; i++) { int status; __fpurge(fp[i]); status=pclose(fp[i]); if (status!=-1) syserror(0, "The %d'th signal generator did exit(%d)\n", i, (int)WEXITSTATUS(status)); else { syserror(1, "Trouble shutting down the %d'th signal generator\n", i); exit(1); } } #endif /* and exit cleanly */ exit(0); }
int main( int argc, char *argv[] ) { if ( argc == 1 ) { fprintf( stderr, "usage: %s framefiles\n", argv[0] ); return 1; } FrLibIni( NULL, stderr, 0 ); while ( --argc > 0 ) { struct FrFile *frfile; struct FrameH *frame; char *fname = *++argv; if ( ! ( frfile = FrFileINew( fname ) ) ) return fprintf( stderr, "file %s not found!\n", fname ), 1; fprintf( stdout, "\n>>> Info for frame file %s:\n", fname ); while ( ( frame = FrameRead( frfile ) ) ) { fprintf( stdout, "\n>> %s, run %u, frame %u:\n", frame->name, frame->run, frame->frame ); fprintf( stdout, "GPS time (s) = %u.%09u\n", frame->GTimeS, frame->GTimeN ); /* fprintf( stdout, "local time (s) = %d\n", frame->localTime ); */ fprintf( stdout, "leap seconds = %u\n", frame->ULeapS ); fprintf( stdout, "duration (s) = %f\n", frame->dt ); if ( frame->rawData ) { struct FrAdcData *adc = frame->rawData->firstAdc; fprintf( stdout, "adc channels:\n" ); while ( adc ) { fprintf( stdout, "\t%s: (crate %u, channel %u)", adc->name, adc->channelGroup, adc->channelNumber ); if ( adc->data ) fprintf( stdout, ", %ld %s points @ %f Hz", (long)adc->data->nData, typestr( adc->data->type ), adc->sampleRate ); fprintf( stdout, "\n" ); adc = adc->next; } } if ( frame->procData ) { struct FrProcData *proc = frame->procData; while ( proc ) { #if defined FR_VERS && FR_VERS < 5000 fprintf( stdout, "\t%s: srate = %f Hz,", proc->name, proc->sampleRate ); #else fprintf( stdout, "\t%s:", proc->name ); #endif if ( proc->data ) { int dim; fprintf( stdout, " %ld %s points [%s]", (long)proc->data->nData, typestr( proc->data->type ), proc->data->unitY ); for ( dim = 0; dim < (int)proc->data->nDim; ++dim ) fprintf( stdout, ", nx(%d) = %ld dx(%d) = %f %s", dim, (long)proc->data->nx[dim], dim, proc->data->dx[dim], proc->data->unitX[dim] ); } fprintf( stdout, "\n" ); proc = proc->next; } } if ( frame->simData ) { struct FrSimData *sim = frame->simData; while ( sim ) { #if defined FR_VERS && FR_VERS < 5000 fprintf( stdout, "\t%s: srate = %f Hz,", sim->name, sim>sampleRate ); #else fprintf( stdout, "\t%s:", sim->name ); #endif if ( sim->data ) { int dim; fprintf( stdout, " %ld %s points [%s]", (long)sim->data->nData, typestr( sim->data->type ), sim->data->unitY ); for ( dim = 0; dim < (int)sim->data->nDim; ++dim ) fprintf( stdout, ", nx(%d) = %ld dx(%d) = %f %s", dim, (long)sim->data->nx[dim], dim, sim->data->dx[dim], sim->data->unitX[dim] ); } fprintf( stdout, "\n" ); sim = sim->next; } } FrameFree( frame ); } FrFileIEnd( frfile ); } return 0; }
int main( int argc, char *argv[] ) { char history[] = "Created by " PACKAGE "-" VERSION "."; struct FrFile *frfileout; struct FrFile *frfilein; struct FrameH *frameout; struct FrameH *framein; char *fnameout; char *fnamein; char **channels; int nchannels; if ( argc < 4 ) { fprintf( stderr, "usage: %s outfile infile channels\n", argv[0] ); return 1; } fnameout = argv[1]; fnamein = argv[2]; channels = &argv[3]; nchannels = argc - 3; FrLibIni( NULL, stderr, 0 ); if ( ! ( frfilein = FrFileINew( fnamein ) ) ) return fputs( "input file not found!\n", stderr ), 1; if ( ! ( frfileout = FrFileONewH( fnameout, 0, history ) ) ) return fputs( "could not open output file!\n", stderr ), 1; while ( ( framein = FrameRead( frfilein ) ) ) { int chan; if ( ! ( frameout = FrameHNew( framein->name ) ) ) return fputs( "allocation error!\n", stderr ), 1; frameout->run = framein->run; frameout->frame = framein->frame; frameout->dataQuality = framein->dataQuality; frameout->GTimeS = framein->GTimeS; frameout->GTimeN = framein->GTimeN; frameout->ULeapS = framein->ULeapS; /* frameout->localTime = framein->localTime; */ frameout->dt = framein->dt; for ( chan = 0; chan < nchannels; ++chan ) { struct FrAdcData *adc; if ( ! ( adc = FrAdcDataFind( framein, channels[chan] ) ) ) return fprintf( stderr, "channel %s not found!\n", channels[chan] ), 1; if ( ! FrAdcDataCopy( adc, frameout ) ) return fputs( "allocation error!\n", stderr ), 1; } FrameWrite( frameout, frfileout ); FrameFree( frameout ); FrameFree( framein ); } FrFileOEnd( frfileout ); FrFileIEnd( frfilein ); return 0; }
static PyObject *frgetevent(PyObject *self, PyObject *args, PyObject *keywds) { FrFile *iFile=NULL; FrameH *frame=NULL; FrEvent *event=NULL; int verbose=0, status; char *filename=NULL; char msg[MAX_STR_LEN]; PyObject *event_list=NULL, *event_dict=NULL, *verbose_obj=NULL, *output=NULL; static char *kwlist[] = {"filename", "verbose", NULL}; /*--------------- unpack arguments --------------------*/ /* The | in the format string indicates the next arguments are optional. They are simply not assigned anything. */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|O", kwlist, &filename, &verbose_obj)) { Py_RETURN_NONE; } verbose = verbose_obj && PyObject_IsTrue(verbose_obj); FrLibSetLvl(verbose); /*-------------- set up file for reading --------------*/ iFile = FrFileINew(filename); if (iFile == NULL){ snprintf(msg, MAX_STR_LEN, "%s", FrErrorGetHistory()); PyErr_SetString(PyExc_IOError, msg); return NULL; } /* require at least one frame in the file */ frame = FrameRead(iFile); if (frame == NULL) { snprintf(msg, MAX_STR_LEN, "%s", FrErrorGetHistory()); PyErr_SetString(PyExc_IOError, msg); FrFileIEnd(iFile); return NULL; } /*------ iterate, putting each event into output list ------*/ event_list = PyList_New(0); if (!event_list) goto clean_C; do { for (event = frame->event; event != NULL; event = event->next) { event_dict = extract_event_dict(event); if (!event_dict) goto clean_C_and_Python; status = PyList_Append(event_list, event_dict); if (status == -1) { Py_DECREF(event_dict); goto clean_C_and_Python; } } } while ((frame = FrameRead(iFile))); /* error checking */ /* NB: FrameL doesn't distinguish between EOF and an error */ if (PyErr_Occurred()) goto clean_C_and_Python; /* if we've gotten here, we're all done; set the output to return */ output = event_list; /*-------------- clean up and return --------------*/ /* C always needs to be cleaned up, error or no. Python only needs to be cleaned up on a true error condition. */ clean_C: FrameFree(frame); FrFileIEnd(iFile); return output; clean_C_and_Python: Py_XDECREF(event_list); FrameFree(frame); FrFileIEnd(iFile); return NULL; }
static PyObject *frputvect(PyObject *self, PyObject *args, PyObject *keywds) { FrFile *oFile; FrameH *frame; FrProcData *proc; FrAdcData *adc; FrSimData *sim; FrVect *vect; int verbose=0, nData, nBits, type, subType, arrayType; double dx, sampleRate, start; char blank[] = ""; char *filename=NULL, *history=NULL; char channel[MAX_STR_LEN], x_unit[MAX_STR_LEN], y_unit[MAX_STR_LEN], kind[MAX_STR_LEN]; PyObject *temp; char msg[MAX_STR_LEN]; PyObject *channellist, *channellist_iter, *framedict, *array; PyArrayIterObject *arrayIter; PyArray_Descr *temp_descr; static char *kwlist[] = {"filename", "channellist", "history", "verbose", NULL}; /*--------------- unpack arguments --------------------*/ verbose = 0; /* The | in the format string indicates the next arguments are optional. They are simply not assigned anything. */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "sO|si", kwlist, &filename, &channellist, &history, &verbose)) { Py_RETURN_NONE; } FrLibSetLvl(verbose); if (history == NULL) { history = blank; } /*-------- create frames, create vectors, and fill them. ------*/ // Channel-list must be any type of sequence if (!PySequence_Check(channellist)) { PyErr_SetNone(PyExc_TypeError); return NULL; } // Get channel name from first dictionary framedict = PySequence_GetItem(channellist, (Py_ssize_t)0); if (framedict == NULL) { PyErr_SetString(PyExc_ValueError, "channellist is empty!"); return NULL; } PyDict_ExtractString(channel, framedict, "name"); Py_XDECREF(framedict); if (PyErr_Occurred()) {return NULL;} if (verbose > 0) { printf("Creating frame %s...\n", channel); } frame = FrameNew(channel); if (frame == NULL) { snprintf(msg, MAX_STR_LEN, "FrameNew failed (%s)", FrErrorGetHistory()); PyErr_SetString(PyExc_FrError, msg); return NULL; } if (verbose > 0) { printf("Now iterating...\n"); } // Iterators allow one to deal with non-contiguous arrays channellist_iter = PyObject_GetIter(channellist); arrayIter = NULL; while ((framedict = PyIter_Next(channellist_iter))) { if (verbose > 0) { printf("In loop...\n"); } // Extract quantities from dict -- all borrowed references PyDict_ExtractString(channel, framedict, "name"); CHECK_ERROR; start = PyDict_ExtractDouble(framedict, "start"); CHECK_ERROR; dx = PyDict_ExtractDouble(framedict, "dx"); CHECK_ERROR; array = PyDict_GetItemString(framedict, "data"); if (!PyArray_Check(array)) { snprintf(msg, MAX_STR_LEN, "data is not an array"); PyErr_SetString(PyExc_TypeError, msg); } CHECK_ERROR; nData = PyArray_SIZE(array); nBits = PyArray_ITEMSIZE(array)*8; arrayType = PyArray_TYPE(array); // kind, x_unit, y_unit, type, and subType have default values temp = PyDict_GetItemString(framedict, "kind"); if (temp != NULL) {strncpy(kind, PyString_AsString(temp), MAX_STR_LEN);} else {snprintf(kind, MAX_STR_LEN, "PROC");} temp = PyDict_GetItemString(framedict, "x_unit"); if (temp != NULL) {strncpy(x_unit, PyString_AsString(temp), MAX_STR_LEN);} else {strncpy(x_unit, blank, MAX_STR_LEN);} temp = PyDict_GetItemString(framedict, "y_unit"); if (temp != NULL) {strncpy(y_unit, PyString_AsString(temp), MAX_STR_LEN);} else {strncpy(y_unit, blank, MAX_STR_LEN);} temp = PyDict_GetItemString(framedict, "type"); if (temp != NULL) {type = (int)PyInt_AsLong(temp);} else {type = 1;} temp = PyDict_GetItemString(framedict, "subType"); if (temp != NULL) {subType = (int)PyInt_AsLong(temp);} else {subType = 0;} // check for errors CHECK_ERROR; if (dx <= 0 || array == NULL || nData==0) { temp = PyObject_Str(framedict); snprintf(msg, MAX_STR_LEN, "Input dictionary contents: %s", PyString_AsString(temp)); Py_XDECREF(temp); FrameFree(frame); Py_XDECREF(framedict); Py_XDECREF(channellist_iter); PyErr_SetString(PyExc_ValueError, msg); return NULL; } if (verbose > 0) { printf("type = %d, subType = %d, start = %f, dx = %f\n", type, subType, start, dx); } sampleRate = 1./dx; if (verbose > 0) { printf("Now copying data to vector...\n"); } // Create empty vector (-typecode ==> empty) with metadata, // then copy data to vector vect = NULL; arrayIter = (PyArrayIterObject *)PyArray_IterNew(array); if(arrayType == NPY_INT16) { vect = FrVectNew1D(channel,-FR_VECT_2S,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataS[arrayIter->index] = *((npy_int16 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_INT32) { vect = FrVectNew1D(channel,-FR_VECT_4S,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataI[arrayIter->index] = *((npy_int32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_INT64) { vect = FrVectNew1D(channel,-FR_VECT_8S,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataL[arrayIter->index] = *((npy_int64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT8) { vect = FrVectNew1D(channel,-FR_VECT_1U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataU[arrayIter->index] = *((npy_uint8 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT16) { vect = FrVectNew1D(channel,-FR_VECT_2U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataUS[arrayIter->index] = *((npy_uint16 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT32) { vect = FrVectNew1D(channel,-FR_VECT_4U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataUI[arrayIter->index] = *((npy_uint32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT64) { vect = FrVectNew1D(channel,-FR_VECT_8U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataUL[arrayIter->index] = *((npy_uint64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_FLOAT32) { vect = FrVectNew1D(channel,-FR_VECT_4R,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataF[arrayIter->index] = *((npy_float32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_FLOAT64) { vect = FrVectNew1D(channel,-FR_VECT_8R,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataD[arrayIter->index] = *((npy_float64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} /* FrVects don't have complex pointers. Numpy stores complex numbers in the same way, but we have to trick it into giving us a (real) float pointer. */ else if(arrayType == NPY_COMPLEX64) { vect = FrVectNew1D(channel,-FR_VECT_8C,nData,dx,x_unit,y_unit); temp_descr = PyArray_DescrFromType(NPY_FLOAT32); temp = PyArray_View((PyArrayObject *)array, temp_descr, NULL); Py_XDECREF(temp_descr); Py_XDECREF(arrayIter); arrayIter = (PyArrayIterObject *)PyArray_IterNew(temp); while (arrayIter->index < arrayIter->size) { vect->dataF[arrayIter->index] = *((npy_float32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);} Py_XDECREF(temp);} else if(arrayType == NPY_COMPLEX128) { vect = FrVectNew1D(channel,-FR_VECT_16C,nData,dx,x_unit,y_unit); temp_descr = PyArray_DescrFromType(NPY_FLOAT64); temp = PyArray_View((PyArrayObject *)array, temp_descr, NULL); Py_XDECREF(temp_descr); Py_XDECREF(arrayIter); arrayIter = (PyArrayIterObject *)PyArray_IterNew(temp); while (arrayIter->index < arrayIter->size) { vect->dataD[arrayIter->index] = *((npy_float64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);} Py_XDECREF(temp);} else PyErr_SetString(PyExc_TypeError, msg); if (PyErr_Occurred()) { if (vect != NULL) FrVectFree(vect); FrameFree(frame); Py_XDECREF(framedict); Py_XDECREF(channellist_iter); Py_XDECREF(arrayIter); return NULL; } if (verbose > 0) { printf("Done copying...\n"); FrameDump(frame, stdout, 6); } // Add Fr*Data to frame and attach vector to Fr*Data if (strncmp(kind, "PROC", MAX_STR_LEN)==0) { proc = FrProcDataNew(frame, channel, sampleRate, 1, nBits); FrVectFree(proc->data); proc->data = vect; proc->type = type; proc->subType = subType; frame->GTimeS = (npy_uint32)start; frame->GTimeN = (npy_uint32)((start-(frame->GTimeS))*1e9); if (type==1) { // time series proc->tRange = nData*dx; frame->dt = nData*dx; } else if (type==2) { // frequency series proc->fRange = nData*dx; } } else if (strncmp(kind, "ADC", MAX_STR_LEN)==0) { adc = FrAdcDataNew(frame, channel, sampleRate, 1, nBits); FrVectFree(adc->data); adc->data = vect; frame->dt = nData*dx; frame->GTimeS = (npy_uint32)start; frame->GTimeN = (npy_uint32)((start-(frame->GTimeS))*1e9); } else {// Already tested that kind is one of these strings above sim = FrSimDataNew(frame, channel, sampleRate, 1, nBits); FrVectFree(sim->data); sim->data = vect; frame->dt = nData*dx; frame->GTimeS = (npy_uint32)start; frame->GTimeN = (npy_uint32)((start-(frame->GTimeS))*1e9); } if (verbose > 0) { printf("Attached vect to frame.\n"); } // Clean up (all python objects in loop should be borrowed references) Py_XDECREF(framedict); Py_XDECREF(arrayIter); } // end iteration over channellist Py_XDECREF(channellist_iter); // At this point, there should be no Python references left! /*------------- Write file -----------------------------*/ oFile = FrFileONewH(filename, 1, history); // 1 ==> gzip contents if (oFile == NULL) { snprintf(msg, MAX_STR_LEN, "%s\n", FrErrorGetHistory()); PyErr_SetString(PyExc_FrError, msg); FrFileOEnd(oFile); return NULL; } if (FrameWrite(frame, oFile) != FR_OK) { snprintf(msg, MAX_STR_LEN, "%s\n", FrErrorGetHistory()); PyErr_SetString(PyExc_FrError, msg); FrFileOEnd(oFile); return NULL; } /* The FrFile owns data and vector memory. Do not free them separately. */ FrFileOEnd(oFile); FrameFree(frame); Py_RETURN_NONE; };