void create_accelobs(accelobs * obs, infodata * idata, Cmdline * cmd, int usemmap) { int ii, rootlen, input_shorts = 0; { int hassuffix = 0; char *suffix; hassuffix = split_root_suffix(cmd->argv[0], &(obs->rootfilenm), &suffix); if (hassuffix) { if (strcmp(suffix, "fft") != 0 && strcmp(suffix, "dat") != 0 && strcmp(suffix, "sdat") != 0) { printf("\nInput file ('%s') must be an '.fft' or '.[s]dat' file!\n\n", cmd->argv[0]); free(suffix); exit(0); } /* If the input file is a time series */ if (strcmp(suffix, "dat") == 0 || strcmp(suffix, "sdat") == 0) { obs->dat_input = 1; obs->mmap_file = 0; if (strcmp(suffix, "sdat") == 0) input_shorts = 1; } else { obs->dat_input = 0; } free(suffix); } else { printf("\nInput file ('%s') must be an '.fft' or '.[s]dat' file!\n\n", cmd->argv[0]); exit(0); } } if (cmd->noharmpolishP) obs->use_harmonic_polishing = 0; else obs->use_harmonic_polishing = 1; // now default /* Read the info file */ readinf(idata, obs->rootfilenm); if (idata->object) { printf("Analyzing %s data from '%s'.\n\n", remove_whitespace(idata->object), cmd->argv[0]); } else { printf("Analyzing data from '%s'.\n\n", cmd->argv[0]); } /* Prepare the input time series if required */ if (obs->dat_input) { FILE *datfile; long long filelen; float *ftmp; printf("Reading and FFTing the time series..."); fflush(NULL); datfile = chkfopen(cmd->argv[0], "rb"); /* Check the length of the file to see if we can handle it */ filelen = chkfilelen(datfile, sizeof(float)); if (input_shorts) filelen *= 2; if (filelen > 67108864) { /* Small since we need memory for the templates */ printf("\nThe input time series is too large. Use 'realfft' first.\n\n"); exit(0); } /* Read the time series into a temporary buffer */ /* Note: The padding allows us to search very short time series */ /* using correlations without having to worry about */ /* accessing data before or after the valid FFT freqs. */ if (input_shorts) { short *stmp = gen_svect(filelen); ftmp = gen_fvect(filelen+2*ACCEL_PADDING); for (ii = 0; ii < ACCEL_PADDING; ii++) { ftmp[ii] = 0.0; ftmp[ii+filelen+ACCEL_PADDING] = 0.0; } chkfread(stmp, sizeof(short), filelen, datfile); for (ii = 0; ii < filelen; ii++) ftmp[ii+ACCEL_PADDING] = (float) stmp[ii]; free(stmp); } else { ftmp = read_float_file(datfile, -ACCEL_PADDING, filelen+2*ACCEL_PADDING); } /* Now, offset the pointer so that we are pointing at the first */ /* bits of valid data. */ ftmp += ACCEL_PADDING; fclose(datfile); /* FFT it */ realfft(ftmp, filelen, -1); obs->fftfile = NULL; obs->fft = (fcomplex *) ftmp; obs->numbins = filelen / 2; printf("done.\n"); /* De-redden it */ printf("Removing red-noise..."); deredden(obs->fft, obs->numbins); printf("done.\n\n"); } /* Determine the output filenames */ rootlen = strlen(obs->rootfilenm) + 25; obs->candnm = (char *) calloc(rootlen, 1); obs->accelnm = (char *) calloc(rootlen, 1); obs->workfilenm = (char *) calloc(rootlen, 1); sprintf(obs->candnm, "%s_ACCEL_%d.cand", obs->rootfilenm, cmd->zmax); sprintf(obs->accelnm, "%s_ACCEL_%d", obs->rootfilenm, cmd->zmax); sprintf(obs->workfilenm, "%s_ACCEL_%d.txtcand", obs->rootfilenm, cmd->zmax); /* Open the FFT file if it exists appropriately */ if (!obs->dat_input) { obs->fftfile = chkfopen(cmd->argv[0], "rb"); obs->numbins = chkfilelen(obs->fftfile, sizeof(fcomplex)); if (usemmap) { fclose(obs->fftfile); obs->fftfile = NULL; printf("Memory mapping the input FFT. This may take a while...\n"); obs->mmap_file = open(cmd->argv[0], O_RDONLY); if (obs->mmap_file == -1) { perror("\nError in open() in accel_utils.c"); printf("\n"); exit(-1); } obs->fft = (fcomplex *) mmap(0, sizeof(fcomplex) * obs->numbins, PROT_READ, MAP_SHARED, obs->mmap_file, 0); if (obs->fft == MAP_FAILED) { perror("\nError in mmap() in accel_utils.c"); printf("Falling back to a non-mmaped approach\n"); obs->fftfile = chkfopen(cmd->argv[0], "rb"); obs->mmap_file = 0; } } else { obs->mmap_file = 0; } } /* Determine the other parameters */ if (cmd->zmax % ACCEL_DZ) cmd->zmax = (cmd->zmax / ACCEL_DZ + 1) * ACCEL_DZ; if (!obs->dat_input) obs->workfile = chkfopen(obs->workfilenm, "w"); obs->N = (long long) idata->N; if (cmd->photonP) { if (obs->mmap_file || obs->dat_input) { obs->nph = obs->fft[0].r; } else { obs->nph = get_numphotons(obs->fftfile); } printf("Normalizing powers using %.0f photons.\n\n", obs->nph); } else { obs->nph = 0.0; /* For short FFTs insure that we don't pick up the DC */ /* or Nyquist component as part of the interpolation */ /* for higher frequencies. */ if (cmd->locpowP) { obs->norm_type = 1; printf("Normalizing powers using local-power determination.\n\n"); } else if (cmd->medianP) { obs->norm_type = 0; printf("Normalizing powers using median-blocks.\n\n"); } else { obs->norm_type = 0; printf("Normalizing powers using median-blocks (default).\n\n"); } if (obs->dat_input) { obs->fft[0].r = 1.0; obs->fft[0].i = 1.0; } } obs->lobin = cmd->lobin; if (obs->lobin > 0) { obs->nph = 0.0; if (cmd->lobin > obs->numbins - 1) { printf("\n'lobin' is greater than the total number of\n"); printf(" frequencies in the data set. Exiting.\n\n"); exit(1); } } if (cmd->numharm != 1 && cmd->numharm != 2 && cmd->numharm != 4 && cmd->numharm != 8 && cmd->numharm != 16) { printf("\n'numharm' = %d must be a power-of-two! Exiting\n\n", cmd->numharm); exit(1); } obs->numharmstages = twon_to_index(cmd->numharm) + 1; obs->dz = ACCEL_DZ; obs->numz = cmd->zmax * 2 + 1; obs->numbetween = ACCEL_NUMBETWEEN; obs->dt = idata->dt; obs->T = idata->dt * idata->N; if (cmd->floP) { obs->rlo = floor(cmd->flo * obs->T); if (obs->rlo < obs->lobin) obs->rlo = obs->lobin; if (obs->rlo > obs->numbins - 1) { printf("\nLow frequency to search 'flo' is greater than\n"); printf(" the highest available frequency. Exiting.\n\n"); exit(1); } } else { if (cmd->rloP) obs->rlo = cmd->rlo; else obs->rlo = 1.0; if (obs->rlo < obs->lobin) obs->rlo = obs->lobin; if (obs->rlo > obs->numbins - 1) { printf("\nLow frequency to search 'rlo' is greater than\n"); printf(" the available number of points. Exiting.\n\n"); exit(1); } } obs->highestbin = obs->numbins - 1; if (cmd->fhiP) { obs->highestbin = ceil(cmd->fhi * obs->T); if (obs->highestbin > obs->numbins - 1) obs->highestbin = obs->numbins - 1; obs->rhi = obs->highestbin; if (obs->highestbin < obs->rlo) { printf("\nHigh frequency to search 'fhi' is less than\n"); printf(" the lowest frequency to search 'flo'. Exiting.\n\n"); exit(1); } } else if (cmd->rhiP) { obs->highestbin = cmd->rhi; if (obs->highestbin > obs->numbins - 1) obs->highestbin = obs->numbins - 1; obs->rhi = obs->highestbin; if (obs->highestbin < obs->rlo) { printf("\nHigh frequency to search 'rhi' is less than\n"); printf(" the lowest frequency to search 'rlo'. Exiting.\n\n"); exit(1); } } obs->dr = ACCEL_DR; obs->zhi = cmd->zmax; obs->zlo = -cmd->zmax; obs->sigma = cmd->sigma; obs->powcut = (float *) malloc(obs->numharmstages * sizeof(float)); obs->numindep = (long long *) malloc(obs->numharmstages * sizeof(long long)); for (ii = 0; ii < obs->numharmstages; ii++) { if (obs->numz == 1) obs->numindep[ii] = (obs->rhi - obs->rlo) / index_to_twon(ii); else /* The numz+1 takes care of the small amount of */ /* search we get above zmax and below zmin. */ obs->numindep[ii] = (obs->rhi - obs->rlo) * (obs->numz + 1) * (obs->dz / 6.95) / index_to_twon(ii); obs->powcut[ii] = power_for_sigma(obs->sigma, index_to_twon(ii), obs->numindep[ii]); } obs->numzap = 0; /* if (zapfile!=NULL) obs->numzap = get_birdies(cmd->zapfile, obs->T, obs->baryv, &(obs->lobins), &(obs->hibins)); else obs->numzap = 0; */ }
int main(int argc, char *argv[]) { FILE *bytemaskfile; float **dataavg = NULL, **datastd = NULL, **datapow = NULL; float *chandata = NULL, powavg, powstd, powmax; float inttime, norm, fracterror = RFI_FRACTERROR; float *rawdata = NULL; unsigned char **bytemask = NULL; short *srawdata = NULL; char *outfilenm, *statsfilenm, *maskfilenm; char *bytemaskfilenm, *rfifilenm; int numchan = 0, numint = 0, newper = 0, oldper = 0, good_padvals = 0; int blocksperint, ptsperint = 0, ptsperblock = 0, padding = 0; int numcands, candnum, numrfi = 0, numrfivect = NUM_RFI_VECT; int ii, jj, kk, slen, numread = 0, insubs = 0; int harmsum = RFI_NUMHARMSUM, lobin = RFI_LOBIN, numbetween = RFI_NUMBETWEEN; double davg, dvar, freq; struct spectra_info s; presto_interptype interptype; rfi *rfivect = NULL; mask oldmask, newmask; fftcand *cands; infodata idata; Cmdline *cmd; /* Call usage() if we have no command line arguments */ if (argc == 1) { Program = argv[0]; printf("\n"); usage(); exit(0); } /* Parse the command line using the excellent program Clig */ cmd = parseCmdline(argc, argv); spectra_info_set_defaults(&s); s.filenames = cmd->argv; s.num_files = cmd->argc; s.clip_sigma = cmd->clip; // -1 causes the data to determine if we use weights, scales, & // offsets for PSRFITS or flip the band for any data type where // we can figure that out with the data s.apply_flipband = (cmd->invertP) ? 1 : -1; s.apply_weight = (cmd->noweightsP) ? 0 : -1; s.apply_scale = (cmd->noscalesP) ? 0 : -1; s.apply_offset = (cmd->nooffsetsP) ? 0 : -1; s.remove_zerodm = (cmd->zerodmP) ? 1 : 0; if (cmd->noclipP) { cmd->clip = 0.0; s.clip_sigma = 0.0; } if (cmd->ifsP) { // 0 = default or summed, 1-4 are possible also s.use_poln = cmd->ifs; } slen = strlen(cmd->outfile) + 20; #ifdef DEBUG showOptionValues(); #endif printf("\n\n"); printf(" Pulsar Data RFI Finder\n"); printf(" by Scott M. Ransom\n\n"); /* The following is the root of all the output files */ outfilenm = (char *) calloc(slen, sizeof(char)); sprintf(outfilenm, "%s_rfifind", cmd->outfile); /* And here are the output file names */ maskfilenm = (char *) calloc(slen, sizeof(char)); sprintf(maskfilenm, "%s.mask", outfilenm); bytemaskfilenm = (char *) calloc(slen, sizeof(char)); sprintf(bytemaskfilenm, "%s.bytemask", outfilenm); rfifilenm = (char *) calloc(slen, sizeof(char)); sprintf(rfifilenm, "%s.rfi", outfilenm); statsfilenm = (char *) calloc(slen, sizeof(char)); sprintf(statsfilenm, "%s.stats", outfilenm); sprintf(idata.name, "%s", outfilenm); if (RAWDATA) { if (cmd->filterbankP) s.datatype = SIGPROCFB; else if (cmd->psrfitsP) s.datatype = PSRFITS; else if (cmd->pkmbP) s.datatype = SCAMP; else if (cmd->bcpmP) s.datatype = BPP; else if (cmd->wappP) s.datatype = WAPP; else if (cmd->spigotP) s.datatype = SPIGOT; } else { // Attempt to auto-identify the data identify_psrdatatype(&s, 1); if (s.datatype==SIGPROCFB) cmd->filterbankP = 1; else if (s.datatype==PSRFITS) cmd->psrfitsP = 1; else if (s.datatype==SCAMP) cmd->pkmbP = 1; else if (s.datatype==BPP) cmd->bcpmP = 1; else if (s.datatype==WAPP) cmd->wappP = 1; else if (s.datatype==SPIGOT) cmd->spigotP = 1; else if (s.datatype==SUBBAND) insubs = 1; else { printf("Error: Unable to identify input data files. Please specify type.\n\n"); exit(1); } } if (!cmd->nocomputeP) { if (RAWDATA || insubs) { char description[40]; psrdatatype_description(description, s.datatype); if (s.num_files > 1) printf("Reading %s data from %d files:\n", description, s.num_files); else printf("Reading %s data from 1 file:\n", description); if (insubs) s.files = (FILE **)malloc(sizeof(FILE *) * s.num_files); for (ii = 0; ii < s.num_files; ii++) { printf(" '%s'\n", cmd->argv[ii]); if (insubs) s.files[ii] = chkfopen(cmd->argv[ii], "rb"); } printf("\n"); } if (RAWDATA) { read_rawdata_files(&s); print_spectra_info_summary(&s); spectra_info_to_inf(&s, &idata); ptsperblock = s.spectra_per_subint; numchan = s.num_channels; idata.dm = 0.0; } if (insubs) { /* Set-up values if we are using subbands */ char *tmpname, *root, *suffix; if (split_root_suffix(s.filenames[0], &root, &suffix) == 0) { printf("Error: The input filename (%s) must have a suffix!\n\n", s.filenames[0]); exit(1); } if (strncmp(suffix, "sub", 3) == 0) { tmpname = calloc(strlen(root) + 6, 1); sprintf(tmpname, "%s.sub", root); readinf(&idata, tmpname); free(tmpname); } else { printf("\nThe input files (%s) must be subbands! (i.e. *.sub##)\n\n", s.filenames[0]); exit(1); } free(root); free(suffix); ptsperblock = 1; /* Compensate for the fact that we have subbands and not channels */ idata.freq = idata.freq - 0.5 * idata.chan_wid + 0.5 * idata.chan_wid * (idata.num_chan / s.num_files); idata.chan_wid = idata.num_chan / s.num_files * idata.chan_wid; idata.num_chan = numchan = s.num_files; idata.dm = 0.0; sprintf(idata.name, "%s", outfilenm); writeinf(&idata); s.padvals = gen_fvect(s.num_files); for (ii = 0 ; ii < s.num_files ; ii++) s.padvals[ii] = 0.0; } /* Read an input mask if wanted */ if (cmd->maskfileP) { read_mask(cmd->maskfile, &oldmask); printf("Read old mask information from '%s'\n\n", cmd->maskfile); good_padvals = determine_padvals(cmd->maskfile, &oldmask, s.padvals); } else { oldmask.numchan = oldmask.numint = 0; } /* The number of data points and blocks to work with at a time */ if (cmd->blocksP) { blocksperint = cmd->blocks; cmd->time = blocksperint * ptsperblock * idata.dt; } else { blocksperint = (int) (cmd->time / (ptsperblock * idata.dt) + 0.5); } ptsperint = blocksperint * ptsperblock; numint = (long long) idata.N / ptsperint; if ((long long) idata.N % ptsperint) numint++; inttime = ptsperint * idata.dt; printf("Analyzing data sections of length %d points (%.6g sec).\n", ptsperint, inttime); { int *factors, numfactors; factors = get_prime_factors(ptsperint, &numfactors); printf(" Prime factors are: "); for (ii = 0; ii < numfactors; ii++) printf("%d ", factors[ii]); printf("\n"); if (factors[numfactors - 1] > 13) { printf(" WARNING: The largest prime factor is pretty big! This will\n" " cause the FFTs to take a long time to compute. I\n" " recommend choosing a different -time value.\n"); } printf("\n"); free(factors); } /* Allocate our workarrays */ if (RAWDATA) rawdata = gen_fvect(idata.num_chan * ptsperblock * blocksperint); else if (insubs) srawdata = gen_svect(idata.num_chan * ptsperblock * blocksperint); dataavg = gen_fmatrix(numint, numchan); datastd = gen_fmatrix(numint, numchan); datapow = gen_fmatrix(numint, numchan); chandata = gen_fvect(ptsperint); bytemask = gen_bmatrix(numint, numchan); for (ii = 0; ii < numint; ii++) for (jj = 0; jj < numchan; jj++) bytemask[ii][jj] = GOODDATA; rfivect = rfi_vector(rfivect, numchan, numint, 0, numrfivect); if (numbetween == 2) interptype = INTERBIN; else interptype = INTERPOLATE; /* Main loop */ printf("Writing mask data to '%s'.\n", maskfilenm); printf("Writing RFI data to '%s'.\n", rfifilenm); printf("Writing statistics to '%s'.\n\n", statsfilenm); printf("Massaging the data ...\n\n"); printf("Amount Complete = %3d%%", oldper); fflush(stdout); for (ii = 0; ii < numint; ii++) { /* Loop over the intervals */ newper = (int) ((float) ii / numint * 100.0 + 0.5); if (newper > oldper) { printf("\rAmount Complete = %3d%%", newper); fflush(stdout); oldper = newper; } /* Read a chunk of data */ if (RAWDATA) numread = read_rawblocks(rawdata, blocksperint, &s, &padding); else if (insubs) numread = read_subband_rawblocks(s.files, s.num_files, srawdata, blocksperint, &padding); if (padding) for (jj = 0; jj < numchan; jj++) bytemask[ii][jj] |= PADDING; for (jj = 0; jj < numchan; jj++) { /* Loop over the channels */ if (RAWDATA) get_channel(chandata, jj, blocksperint, rawdata, &s); else if (insubs) get_subband(jj, chandata, srawdata, blocksperint); /* Calculate the averages and standard deviations */ /* for each point in time. */ if (padding) { dataavg[ii][jj] = 0.0; datastd[ii][jj] = 0.0; datapow[ii][jj] = 1.0; } else { avg_var(chandata, ptsperint, &davg, &dvar); dataavg[ii][jj] = davg; datastd[ii][jj] = sqrt(dvar); realfft(chandata, ptsperint, -1); numcands = 0; norm = datastd[ii][jj] * datastd[ii][jj] * ptsperint; if (norm == 0.0) norm = (chandata[0] == 0.0) ? 1.0 : chandata[0]; cands = search_fft((fcomplex *) chandata, ptsperint / 2, lobin, ptsperint / 2, harmsum, numbetween, interptype, norm, cmd->freqsigma, &numcands, &powavg, &powstd, &powmax); datapow[ii][jj] = powmax; /* Record the birdies */ if (numcands) { for (kk = 0; kk < numcands; kk++) { freq = cands[kk].r / inttime; candnum = find_rfi(rfivect, numrfi, freq, RFI_FRACTERROR); if (candnum >= 0) { update_rfi(rfivect + candnum, freq, cands[kk].sig, jj, ii); } else { update_rfi(rfivect + numrfi, freq, cands[kk].sig, jj, ii); numrfi++; if (numrfi == numrfivect) { numrfivect *= 2; rfivect = rfi_vector(rfivect, numchan, numint, numrfivect / 2, numrfivect); } } } free(cands); } } } } printf("\rAmount Complete = 100%%\n"); /* Write the data to the output files */ write_rfifile(rfifilenm, rfivect, numrfi, numchan, numint, ptsperint, lobin, numbetween, harmsum, fracterror, cmd->freqsigma); write_statsfile(statsfilenm, datapow[0], dataavg[0], datastd[0], numchan, numint, ptsperint, lobin, numbetween); } else { /* If "-nocompute" */ float freqsigma; /* Read the data from the output files */ printf("Reading RFI data from '%s'.\n", rfifilenm); printf("Reading statistics from '%s'.\n", statsfilenm); readinf(&idata, outfilenm); read_rfifile(rfifilenm, &rfivect, &numrfi, &numchan, &numint, &ptsperint, &lobin, &numbetween, &harmsum, &fracterror, &freqsigma); numrfivect = numrfi; read_statsfile(statsfilenm, &datapow, &dataavg, &datastd, &numchan, &numint, &ptsperint, &lobin, &numbetween); bytemask = gen_bmatrix(numint, numchan); printf("Reading bytemask from '%s'.\n\n", bytemaskfilenm); bytemaskfile = chkfopen(bytemaskfilenm, "rb"); chkfread(bytemask[0], numint * numchan, 1, bytemaskfile); fclose(bytemaskfile); for (ii = 0; ii < numint; ii++) for (jj = 0; jj < numchan; jj++) bytemask[ii][jj] &= PADDING; /* Clear all but the PADDING bits */ inttime = ptsperint * idata.dt; } /* Make the plots and set the mask */ { int *zapints, *zapchan; int numzapints = 0, numzapchan = 0; if (cmd->zapintsstrP) { zapints = ranges_to_ivect(cmd->zapintsstr, 0, numint - 1, &numzapints); zapints = (int *) realloc(zapints, (size_t) (sizeof(int) * numint)); } else { zapints = gen_ivect(numint); } if (cmd->zapchanstrP) { zapchan = ranges_to_ivect(cmd->zapchanstr, 0, numchan - 1, &numzapchan); zapchan = (int *) realloc(zapchan, (size_t) (sizeof(int) * numchan)); } else { zapchan = gen_ivect(numchan); } rfifind_plot(numchan, numint, ptsperint, cmd->timesigma, cmd->freqsigma, cmd->inttrigfrac, cmd->chantrigfrac, dataavg, datastd, datapow, zapchan, numzapchan, zapints, numzapints, &idata, bytemask, &oldmask, &newmask, rfivect, numrfi, cmd->rfixwinP, cmd->rfipsP, cmd->xwinP); vect_free(zapints); vect_free(zapchan); } /* Write the new mask and bytemask to the file */ write_mask(maskfilenm, &newmask); bytemaskfile = chkfopen(bytemaskfilenm, "wb"); chkfwrite(bytemask[0], numint * numchan, 1, bytemaskfile); fclose(bytemaskfile); /* Determine the percent of good and bad data */ { int numpad = 0, numbad = 0, numgood = 0; for (ii = 0; ii < numint; ii++) { for (jj = 0; jj < numchan; jj++) { if (bytemask[ii][jj] == GOODDATA) { numgood++; } else { if (bytemask[ii][jj] & PADDING) numpad++; else numbad++; } } } printf("\nTotal number of intervals in the data: %d\n\n", numint * numchan); printf(" Number of padded intervals: %7d (%6.3f%%)\n", numpad, (float) numpad / (float) (numint * numchan) * 100.0); printf(" Number of good intervals: %7d (%6.3f%%)\n", numgood, (float) numgood / (float) (numint * numchan) * 100.0); printf(" Number of bad intervals: %7d (%6.3f%%)\n\n", numbad, (float) numbad / (float) (numint * numchan) * 100.0); qsort(rfivect, numrfi, sizeof(rfi), compare_rfi_sigma); printf(" Ten most significant birdies:\n"); printf("# Sigma Period(ms) Freq(Hz) Number \n"); printf("----------------------------------------------------\n"); for (ii = 0; ii < 10; ii++) { double pperr; char temp1[40], temp2[40]; if (rfivect[ii].freq_var == 0.0) { pperr = 0.0; sprintf(temp1, " %-14g", rfivect[ii].freq_avg); sprintf(temp2, " %-14g", 1000.0 / rfivect[ii].freq_avg); } else { pperr = 1000.0 * sqrt(rfivect[ii].freq_var) / (rfivect[ii].freq_avg * rfivect[ii].freq_avg); nice_output_2(temp1, rfivect[ii].freq_avg, sqrt(rfivect[ii].freq_var), -15); nice_output_2(temp2, 1000.0 / rfivect[ii].freq_avg, pperr, -15); } printf("%-2d %-8.2f %13s %13s %-8d\n", ii + 1, rfivect[ii].sigma_avg, temp2, temp1, rfivect[ii].numobs); } qsort(rfivect, numrfi, sizeof(rfi), compare_rfi_numobs); printf("\n Ten most numerous birdies:\n"); printf("# Number Period(ms) Freq(Hz) Sigma \n"); printf("----------------------------------------------------\n"); for (ii = 0; ii < 10; ii++) { double pperr; char temp1[40], temp2[40]; if (rfivect[ii].freq_var == 0.0) { pperr = 0.0; sprintf(temp1, " %-14g", rfivect[ii].freq_avg); sprintf(temp2, " %-14g", 1000.0 / rfivect[ii].freq_avg); } else { pperr = 1000.0 * sqrt(rfivect[ii].freq_var) / (rfivect[ii].freq_avg * rfivect[ii].freq_avg); nice_output_2(temp1, rfivect[ii].freq_avg, sqrt(rfivect[ii].freq_var), -15); nice_output_2(temp2, 1000.0 / rfivect[ii].freq_avg, pperr, -15); } printf("%-2d %-8d %13s %13s %-8.2f\n", ii + 1, rfivect[ii].numobs, temp2, temp1, rfivect[ii].sigma_avg); } printf("\nDone.\n\n"); } /* Close the files and cleanup */ free_rfi_vector(rfivect, numrfivect); free_mask(newmask); if (cmd->maskfileP) free_mask(oldmask); free(outfilenm); free(statsfilenm); free(bytemaskfilenm); free(maskfilenm); free(rfifilenm); vect_free(dataavg[0]); vect_free(dataavg); vect_free(datastd[0]); vect_free(datastd); vect_free(datapow[0]); vect_free(datapow); vect_free(bytemask[0]); vect_free(bytemask); if (!cmd->nocomputeP) { // Close all the raw files and free their vectors close_rawfiles(&s); vect_free(chandata); if (insubs) vect_free(srawdata); else vect_free(rawdata); } return (0); }
static int get_data(float **outdata, int blocksperread, struct spectra_info *s, mask * obsmask, int *idispdts, int **offsets, int *padding) { static int firsttime = 1, *maskchans = NULL, blocksize; static int worklen, dsworklen; static float *tempzz, *data1, *data2, *dsdata1 = NULL, *dsdata2 = NULL; static float *currentdata, *lastdata, *currentdsdata, *lastdsdata; static float *frawdata; static double blockdt; int totnumread = 0, gotblock = 0, numread = 0; int ii, jj, tmppad = 0, nummasked = 0; if (firsttime) { if (cmd->maskfileP) maskchans = gen_ivect(insubs ? s->num_files : s->num_channels); worklen = s->spectra_per_subint * blocksperread; dsworklen = worklen / cmd->downsamp; blocksize = s->spectra_per_subint * cmd->nsub; blockdt = s->spectra_per_subint * s->dt; if (RAWDATA) { frawdata = gen_fvect(2 * s->num_channels * s->spectra_per_subint); // To initialize the data reading and prep_subbands routines firsttime = 2; } data1 = gen_fvect(cmd->nsub * worklen); data2 = gen_fvect(cmd->nsub * worklen); currentdata = data1; lastdata = data2; if (cmd->downsamp > 1) { dsdata1 = gen_fvect(cmd->nsub * dsworklen); dsdata2 = gen_fvect(cmd->nsub * dsworklen); currentdsdata = dsdata1; lastdsdata = dsdata2; } else { currentdsdata = data1; lastdsdata = data2; } { // Make sure that our working blocks are long enough... int testlen = insubs ? s->num_files : s->num_channels; for (ii = 0; ii < testlen; ii++) { if (idispdts[ii] > worklen) printf("WARNING! (myid = %d): (idispdts[%d] = %d) > (worklen = %d)\n", myid, ii, idispdts[ii], worklen); } for (ii = 0; ii < local_numdms; ii++) { for (jj = 0; jj < cmd->nsub; jj++) { if (offsets[ii][jj] > dsworklen) printf("WARNING! (myid = %d): (offsets[%d][%d] = %d) > (dsworklen = %d)\n", myid, ii, jj, offsets[ii][jj], dsworklen); } } } } while (1) { if (RAWDATA) { for (ii = 0; ii < blocksperread; ii++) { if (myid == 0) { gotblock = s->get_rawblock(frawdata, s, &tmppad); if (gotblock && !firsttime) totnumread += s->spectra_per_subint; } MPI_Bcast(&gotblock, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&tmppad, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(frawdata, s->num_channels * s->spectra_per_subint, MPI_FLOAT, 0, MPI_COMM_WORLD); if (myid > 0) { if (gotblock) { numread = prep_subbands(currentdata + ii * blocksize, frawdata, idispdts, cmd->nsub, s, 0, maskchans, &nummasked, obsmask); if (!firsttime) totnumread += numread; } else { *padding = 1; for (jj = ii * blocksize; jj < (ii + 1) * blocksize; jj++) currentdata[jj] = 0.0; } if (tmppad) *padding = 1; } } } else if (insubs) { short *subsdata = NULL; subsdata = gen_svect(SUBSBLOCKLEN * s->num_files); for (ii = 0; ii < blocksperread; ii++) { if (myid == 0) numread = simple_read_subbands(s->files, s->num_files, subsdata); MPI_Bcast(&numread, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(subsdata, SUBSBLOCKLEN * s->num_files, MPI_SHORT, 0, MPI_COMM_WORLD); convert_subbands(s->num_files, subsdata, currentdata + ii * blocksize, blockdt, maskchans, &nummasked, obsmask, cmd->clip, s->padvals); if (!firsttime) totnumread += numread; } vect_free(subsdata); } /* Downsample the subband data if needed */ if (myid > 0) { if (cmd->downsamp > 1) { int kk, offset, dsoffset, index, dsindex; float ftmp; for (ii = 0; ii < dsworklen; ii++) { dsoffset = ii * cmd->nsub; offset = dsoffset * cmd->downsamp; for (jj = 0; jj < cmd->nsub; jj++) { dsindex = dsoffset + jj; index = offset + jj; currentdsdata[dsindex] = 0.0; for (kk = 0, ftmp = 0.0; kk < cmd->downsamp; kk++) { ftmp += currentdata[index]; index += cmd->nsub; } currentdsdata[dsindex] += ftmp / cmd->downsamp; } } } } if (firsttime) { SWAP(currentdata, lastdata); SWAP(currentdsdata, lastdsdata); firsttime -= 1; } else break; } if (myid > 0) { for (ii = 0; ii < local_numdms; ii++) float_dedisp(currentdsdata, lastdsdata, dsworklen, cmd->nsub, offsets[ii], 0.0, outdata[ii]); } SWAP(currentdata, lastdata); SWAP(currentdsdata, lastdsdata); if (totnumread != worklen) { if (cmd->maskfileP) vect_free(maskchans); vect_free(data1); vect_free(data2); if (RAWDATA) vect_free(frawdata); if (cmd->downsamp > 1) { vect_free(dsdata1); vect_free(dsdata2); } } return totnumread; }
int main(int argc, char *argv[]) { FILE *infile, *outfile; int ii, jj, bufflen = 10000, numread; long long N = 0; float *inbuffer = NULL, *outbuffer = NULL; short useshorts = 0, *sinbuffer = NULL, *soutbuffer = NULL; char *rootfilenm, *outname; infodata idata; Cmdline *cmd; /* Call usage() if we have no command line arguments */ if (argc == 1) { Program = argv[0]; printf("\n"); usage(); exit(1); } /* Parse the command line using the excellent program Clig */ cmd = parseCmdline(argc, argv); #ifdef DEBUG showOptionValues(); #endif printf("\n\n"); printf(" Time Series Downsampling Routine\n"); printf(" Sept, 2002\n\n"); { int hassuffix = 0; char *suffix; hassuffix = split_root_suffix(cmd->argv[0], &rootfilenm, &suffix); if (hassuffix) { if (strcmp(suffix, "sdat") == 0) useshorts = 1; if (strcmp(suffix, "dat") != 0 && strcmp(suffix, "sdat") != 0) { printf ("\nInput file ('%s') must be a time series ('.dat' or '.sdat')!\n\n", cmd->argv[0]); free(suffix); exit(0); } free(suffix); } else { printf("\nInput file ('%s') must be a time series ('.dat' or '.sdat')!\n\n", cmd->argv[0]); exit(0); } if (cmd->outfileP) { outname = cmd->outfile; } else { outname = (char *) calloc(strlen(rootfilenm) + 11, sizeof(char)); if (useshorts) sprintf(outname, "%s_D%d.sdat", rootfilenm, cmd->factor); else sprintf(outname, "%s_D%d.dat", rootfilenm, cmd->factor); } } /* Read the info file */ readinf(&idata, rootfilenm); if (idata.object) { printf("Downsampling %s data from '%s'.\n\n", remove_whitespace(idata.object), cmd->argv[0]); } else { printf("Downsampling data from '%s'.\n\n", cmd->argv[0]); } /* Open files and create arrays */ infile = chkfopen(argv[1], "rb"); outfile = chkfopen(outname, "wb"); /* Read and downsample */ if (useshorts) { sinbuffer = gen_svect(bufflen * cmd->factor); soutbuffer = gen_svect(bufflen); while ((numread = chkfread(sinbuffer, sizeof(short), bufflen * cmd->factor, infile))) { for (ii = 0; ii < numread / cmd->factor; ii++) { soutbuffer[ii] = 0; for (jj = 0; jj < cmd->factor; jj++) soutbuffer[ii] += sinbuffer[cmd->factor * ii + jj]; } chkfwrite(soutbuffer, sizeof(short), numread / cmd->factor, outfile); N += numread / cmd->factor; } vect_free(sinbuffer); vect_free(soutbuffer); } else { inbuffer = gen_fvect(bufflen * cmd->factor); outbuffer = gen_fvect(bufflen); while ((numread = chkfread(inbuffer, sizeof(float), bufflen * cmd->factor, infile))) { for (ii = 0; ii < numread / cmd->factor; ii++) { outbuffer[ii] = 0; for (jj = 0; jj < cmd->factor; jj++) outbuffer[ii] += inbuffer[cmd->factor * ii + jj]; } chkfwrite(outbuffer, sizeof(float), numread / cmd->factor, outfile); N += numread / cmd->factor; } vect_free(inbuffer); vect_free(outbuffer); } printf("Done. Wrote %lld points.\n\n", N); /* Write the new info file */ idata.dt = idata.dt * cmd->factor; idata.numonoff = 0; idata.N = (double) N; strncpy(idata.name, outname, strlen(outname) - 4); if (useshorts) idata.name[strlen(outname) - 5] = '\0'; else idata.name[strlen(outname) - 4] = '\0'; writeinf(&idata); fclose(infile); fclose(outfile); free(rootfilenm); if (!cmd->outfileP) free(outname); exit(0); }
int main(int argc, char *argv[]) { /* Any variable that begins with 't' means topocentric */ /* Any variable that begins with 'b' means barycentric */ FILE *outfile; float *outdata = NULL; double tdf = 0.0, dtmp = 0.0, barydispdt = 0.0, dsdt = 0.0; double *dispdt, *tobsf = NULL, tlotoa = 0.0, blotoa = 0.0; double max = -9.9E30, min = 9.9E30, var = 0.0, avg = 0.0; char obs[3], ephem[10], *datafilenm, *outinfonm; char rastring[50], decstring[50]; int numchan = 1, newper = 0, oldper = 0, nummasked = 0, useshorts = 0; int numadded = 0, numremoved = 0, padding = 0, *maskchans = NULL, offset = 0; long slen, ii, numbarypts = 0, worklen = 65536; long numread = 0, numtowrite = 0, totwrote = 0, datawrote = 0; long padwrote = 0, padtowrite = 0, statnum = 0; int numdiffbins = 0, *diffbins = NULL, *diffbinptr = NULL, good_padvals = 0; int *idispdt; struct spectra_info s; infodata idata; Cmdline *cmd; mask obsmask; /* Call usage() if we have no command line arguments */ if (argc == 1) { Program = argv[0]; printf("\n"); usage(); exit(0); } /* Parse the command line using the excellent program Clig */ cmd = parseCmdline(argc, argv); spectra_info_set_defaults(&s); s.filenames = cmd->argv; s.num_files = cmd->argc; // If we are zeroDMing, make sure that clipping is off. if (cmd->zerodmP) cmd->noclipP = 1; s.clip_sigma = cmd->clip; // -1 causes the data to determine if we use weights, scales, & // offsets for PSRFITS or flip the band for any data type where // we can figure that out with the data s.apply_flipband = (cmd->invertP) ? 1 : -1; s.apply_weight = (cmd->noweightsP) ? 0 : -1; s.apply_scale = (cmd->noscalesP) ? 0 : -1; s.apply_offset = (cmd->nooffsetsP) ? 0 : -1; s.remove_zerodm = (cmd->zerodmP) ? 1 : 0; if (cmd->noclipP) { cmd->clip = 0.0; s.clip_sigma = 0.0; } if (cmd->ifsP) { // 0 = default or summed, 1-4 are possible also s.use_poln = cmd->ifs + 1; } if (cmd->ncpus > 1) { #ifdef _OPENMP int maxcpus = omp_get_num_procs(); int openmp_numthreads = (cmd->ncpus <= maxcpus) ? cmd->ncpus : maxcpus; // Make sure we are not dynamically setting the number of threads omp_set_dynamic(0); omp_set_num_threads(openmp_numthreads); printf("Using %d threads with OpenMP\n\n", openmp_numthreads); #endif } else { #ifdef _OPENMP omp_set_num_threads(1); // Explicitly turn off OpenMP #endif } #ifdef DEBUG showOptionValues(); #endif printf("\n\n"); printf(" Pulsar Data Preparation Routine\n"); printf(" Type conversion, de-dispersion, barycentering.\n"); printf(" by Scott M. Ransom\n\n"); if (RAWDATA) { if (cmd->filterbankP) s.datatype = SIGPROCFB; else if (cmd->psrfitsP) s.datatype = PSRFITS; } else { // Attempt to auto-identify the data identify_psrdatatype(&s, 1); if (s.datatype == SIGPROCFB) cmd->filterbankP = 1; else if (s.datatype == PSRFITS) cmd->psrfitsP = 1; else if (s.datatype == SDAT) useshorts = 1; else if (s.datatype != DAT) { printf ("Error: Unable to identify input data files. Please specify type.\n\n"); exit(1); } } if (!RAWDATA) { char *root, *suffix; /* Split the filename into a rootname and a suffix */ if (split_root_suffix(s.filenames[0], &root, &suffix) == 0) { printf("\nThe input filename (%s) must have a suffix!\n\n", s.filenames[0]); exit(1); } printf("Reading input data from '%s'.\n", s.filenames[0]); printf("Reading information from '%s.inf'.\n\n", root); /* Read the info file if available */ readinf(&idata, root); free(root); free(suffix); s.files = (FILE **) malloc(sizeof(FILE *)); s.files[0] = chkfopen(s.filenames[0], "rb"); } else { char description[40]; psrdatatype_description(description, s.datatype); if (s.num_files > 1) printf("Reading %s data from %d files:\n", description, s.num_files); else printf("Reading %s data from 1 file:\n", description); for (ii = 0; ii < s.num_files; ii++) { printf(" '%s'\n", cmd->argv[ii]); } printf("\n"); } /* Determine the other file names and open the output data file */ slen = strlen(cmd->outfile) + 8; datafilenm = (char *) calloc(slen, 1); sprintf(datafilenm, "%s.dat", cmd->outfile); outfile = chkfopen(datafilenm, "wb"); sprintf(idata.name, "%s", cmd->outfile); outinfonm = (char *) calloc(slen, 1); sprintf(outinfonm, "%s.inf", cmd->outfile); if (RAWDATA) { read_rawdata_files(&s); if (cmd->ignorechanstrP) { s.ignorechans = get_ignorechans(cmd->ignorechanstr, 0, s.num_channels-1, &s.num_ignorechans, &s.ignorechans_str); if (s.ignorechans_str==NULL) { s.ignorechans_str = (char *)malloc(strlen(cmd->ignorechanstr)+1); strcpy(s.ignorechans_str, cmd->ignorechanstr); } } print_spectra_info_summary(&s); spectra_info_to_inf(&s, &idata); /* Finish setting up stuff common to all raw formats */ idata.dm = cmd->dm; worklen = s.spectra_per_subint; /* If we are offsetting into the file, change inf file start time */ if (cmd->start > 0.0 || cmd->offset > 0) { if (cmd->start > 0.0) /* Offset in units of worklen */ cmd->offset = (long) (cmd->start * idata.N / worklen) * worklen; add_to_inf_epoch(&idata, cmd->offset * idata.dt); offset_to_spectra(cmd->offset, &s); printf("Offsetting into the input files by %ld spectra (%.6g sec)\n", cmd->offset, cmd->offset * idata.dt); } if (cmd->maskfileP) maskchans = gen_ivect(idata.num_chan); /* Compare the size of the data to the size of output we request */ if (cmd->numoutP) { dtmp = idata.N; idata.N = cmd->numout; writeinf(&idata); idata.N = dtmp; } else { /* Set the output length to a good number if it wasn't requested */ cmd->numoutP = 1; cmd->numout = choose_good_N((long long)(idata.N/cmd->downsamp)); writeinf(&idata); printf("Setting a 'good' output length of %ld samples\n", cmd->numout); } /* The number of topo to bary time points to generate with TEMPO */ numbarypts = (long) (idata.dt * idata.N * 1.1 / TDT + 5.5) + 1; // Identify the TEMPO observatory code { char *outscope = (char *) calloc(40, sizeof(char)); telescope_to_tempocode(idata.telescope, outscope, obs); free(outscope); } } /* Read an input mask if wanted */ if (cmd->maskfileP) { read_mask(cmd->maskfile, &obsmask); printf("Read mask information from '%s'\n\n", cmd->maskfile); good_padvals = determine_padvals(cmd->maskfile, &obsmask, s.padvals); } else { obsmask.numchan = obsmask.numint = 0; } /* Determine our initialization data if we do _not_ have Parkes, */ /* Green Bank BCPM, or Arecibo WAPP data sets. */ if (!RAWDATA) { /* If we will be barycentering... */ if (!cmd->nobaryP) { /* The number of topo to bary time points to generate with TEMPO */ numbarypts = (long) (idata.dt * idata.N * 1.1 / TDT + 5.5) + 1; // Identify the TEMPO observatory code { char *outscope = (char *) calloc(40, sizeof(char)); telescope_to_tempocode(idata.telescope, outscope, obs); free(outscope); } } /* The number of data points to work with at a time */ if (worklen > idata.N) worklen = idata.N; worklen = (long) (worklen / 1024) * 1024; /* If we are offsetting into the file, change inf file start time */ if (cmd->start > 0.0 || cmd->offset > 0) { if (cmd->start > 0.0) /* Offset in units of worklen */ cmd->offset = (long) (cmd->start * idata.N / worklen) * worklen; add_to_inf_epoch(&idata, cmd->offset * idata.dt); printf("Offsetting into the input files by %ld samples (%.6g sec)\n", cmd->offset, cmd->offset * idata.dt); if (useshorts) { chkfileseek(s.files[0], cmd->offset, sizeof(short), SEEK_SET); } else { chkfileseek(s.files[0], cmd->offset, sizeof(float), SEEK_SET); } } /* Set the output length to a good number if it wasn't requested */ if (!cmd->numoutP) { cmd->numoutP = 1; cmd->numout = choose_good_N((long long)(idata.N/cmd->downsamp)); printf("Setting a 'good' output length of %ld samples\n", cmd->numout); } } /* Check if we are downsampling */ dsdt = idata.dt * cmd->downsamp; if (cmd->downsamp > 1) { printf("Downsampling by a factor of %d\n", cmd->downsamp); printf("New sample dt = %.10g\n\n", dsdt); if (worklen % cmd->downsamp) { printf("Error: The downsample factor (%d) must be a factor of the\n", cmd->downsamp); printf(" worklength (%ld). Exiting.\n\n", worklen); exit(1); } } printf("Writing output data to '%s'.\n", datafilenm); printf("Writing information to '%s'.\n\n", outinfonm); /* The topocentric epoch of the start of the data */ tlotoa = (double) idata.mjd_i + idata.mjd_f; if (!strcmp(idata.band, "Radio") && RAWDATA) { /* The topocentric spacing between channels */ tdf = idata.chan_wid; numchan = idata.num_chan; /* The topocentric observation frequencies */ tobsf = gen_dvect(numchan); tobsf[0] = idata.freq; for (ii = 0; ii < numchan; ii++) tobsf[ii] = tobsf[0] + ii * tdf; /* The dispersion delays (in time bins) */ dispdt = gen_dvect(numchan); // full float bins idispdt = gen_ivect(numchan); // nearest integer bins if (cmd->nobaryP) { /* Determine our dispersion time delays for each channel */ for (ii = 0; ii < numchan; ii++) dispdt[ii] = delay_from_dm(cmd->dm, tobsf[ii]); /* The highest frequency channel gets no delay */ /* All other delays are positive fractions of bin length (dt) */ dtmp = dispdt[numchan - 1]; for (ii = 0; ii < numchan; ii++) { dispdt[ii] = (dispdt[ii] - dtmp) / idata.dt; idispdt[ii] = (int) (dispdt[ii] + 0.5); } worklen *= ((int) (fabs(dispdt[0])) / worklen) + 1; } } else { /* For unknown radio raw data (Why is this here?) */ tobsf = gen_dvect(numchan); dispdt = gen_dvect(numchan); idispdt = gen_ivect(numchan); dispdt[0] = 0.0; idispdt[0] = 0; if (!strcmp(idata.band, "Radio")) { tobsf[0] = idata.freq + (idata.num_chan - 1) * idata.chan_wid; cmd->dm = idata.dm; } else { tobsf[0] = 0.0; cmd->dm = 0.0; } } if (cmd->nobaryP) { /* Main loop if we are not barycentering... */ /* Allocate our data array */ outdata = gen_fvect(worklen); printf("Massaging the data ...\n\n"); printf("Amount Complete = 0%%"); do { if (RAWDATA) numread = read_psrdata(outdata, worklen, &s, idispdt, &padding, maskchans, &nummasked, &obsmask); else if (useshorts) numread = read_shorts(s.files[0], outdata, worklen, numchan); else numread = read_floats(s.files[0], outdata, worklen, numchan); if (numread == 0) break; /* Downsample if requested */ if (cmd->downsamp > 1) numread = downsample(outdata, numread, cmd->downsamp); /* Print percent complete */ newper = (int) ((float) totwrote / cmd->numout * 100.0) + 1; if (newper > oldper) { printf("\rAmount Complete = %3d%%", newper); fflush(stdout); oldper = newper; } /* Write the latest chunk of data, but don't */ /* write more than cmd->numout points. */ numtowrite = numread; if ((totwrote + numtowrite) > cmd->numout) numtowrite = cmd->numout - totwrote; chkfwrite(outdata, sizeof(float), numtowrite, outfile); totwrote += numtowrite; /* Update the statistics */ if (!padding) { for (ii = 0; ii < numtowrite; ii++) update_stats(statnum + ii, outdata[ii], &min, &max, &avg, &var); statnum += numtowrite; } /* Stop if we have written out all the data we need to */ if (totwrote == cmd->numout) break; } while (numread); datawrote = totwrote; } else { /* Main loop if we are barycentering... */ double avgvoverc = 0.0, maxvoverc = -1.0, minvoverc = 1.0, *voverc = NULL; double *bobsf = NULL, *btoa = NULL, *ttoa = NULL; /* What ephemeris will we use? (Default is DE405) */ strcpy(ephem, "DE405"); /* Define the RA and DEC of the observation */ ra_dec_to_string(rastring, idata.ra_h, idata.ra_m, idata.ra_s); ra_dec_to_string(decstring, idata.dec_d, idata.dec_m, idata.dec_s); /* Allocate some arrays */ bobsf = gen_dvect(numchan); btoa = gen_dvect(numbarypts); ttoa = gen_dvect(numbarypts); voverc = gen_dvect(numbarypts); for (ii = 0; ii < numbarypts; ii++) ttoa[ii] = tlotoa + TDT * ii / SECPERDAY; /* Call TEMPO for the barycentering */ printf("Generating barycentric corrections...\n"); barycenter(ttoa, btoa, voverc, numbarypts, rastring, decstring, obs, ephem); for (ii = 0; ii < numbarypts; ii++) { if (voverc[ii] > maxvoverc) maxvoverc = voverc[ii]; if (voverc[ii] < minvoverc) minvoverc = voverc[ii]; avgvoverc += voverc[ii]; } avgvoverc /= numbarypts; vect_free(voverc); blotoa = btoa[0]; printf(" Average topocentric velocity (c) = %.7g\n", avgvoverc); printf(" Maximum topocentric velocity (c) = %.7g\n", maxvoverc); printf(" Minimum topocentric velocity (c) = %.7g\n\n", minvoverc); printf("Collecting and barycentering %s...\n\n", cmd->argv[0]); /* Determine the initial dispersion time delays for each channel */ for (ii = 0; ii < numchan; ii++) { bobsf[ii] = doppler(tobsf[ii], avgvoverc); dispdt[ii] = delay_from_dm(cmd->dm, bobsf[ii]); } /* The highest frequency channel gets no delay */ /* All other delays are positive fractions of bin length (dt) */ barydispdt = dispdt[numchan - 1]; for (ii = 0; ii < numchan; ii++) { dispdt[ii] = (dispdt[ii] - barydispdt) / idata.dt; idispdt[ii] = (int) (dispdt[ii] + 0.5); } if (RAWDATA) worklen *= ((int) (dispdt[0]) / worklen) + 1; /* If the data is de-dispersed radio data... */ if (!strcmp(idata.band, "Radio")) { printf("The DM of %.2f at the barycentric observing freq of %.3f MHz\n", idata.dm, bobsf[numchan - 1]); printf(" causes a delay of %f seconds compared to infinite freq.\n", barydispdt); printf(" This delay is removed from the barycented times.\n\n"); } printf("Topocentric epoch (at data start) is:\n"); printf(" %17.11f\n\n", tlotoa); printf("Barycentric epoch (infinite obs freq at data start) is:\n"); printf(" %17.11f\n\n", blotoa - (barydispdt / SECPERDAY)); /* Convert the bary TOAs to differences from the topo TOAs in */ /* units of bin length (dsdt) rounded to the nearest integer. */ dtmp = (btoa[0] - ttoa[0]); for (ii = 0; ii < numbarypts; ii++) btoa[ii] = ((btoa[ii] - ttoa[ii]) - dtmp) * SECPERDAY / dsdt; { /* Find the points where we need to add or remove bins */ int oldbin = 0, currentbin; double lobin, hibin, calcpt; numdiffbins = abs(NEAREST_LONG(btoa[numbarypts - 1])) + 1; diffbins = gen_ivect(numdiffbins); diffbinptr = diffbins; for (ii = 1; ii < numbarypts; ii++) { currentbin = NEAREST_LONG(btoa[ii]); if (currentbin != oldbin) { if (currentbin > 0) { calcpt = oldbin + 0.5; lobin = (ii - 1) * TDT / dsdt; hibin = ii * TDT / dsdt; } else { calcpt = oldbin - 0.5; lobin = -((ii - 1) * TDT / dsdt); hibin = -(ii * TDT / dsdt); } while (fabs(calcpt) < fabs(btoa[ii])) { /* Negative bin number means remove that bin */ /* Positive bin number means add a bin there */ *diffbinptr = NEAREST_LONG(LININTERP(calcpt, btoa[ii - 1], btoa[ii], lobin, hibin)); diffbinptr++; calcpt = (currentbin > 0) ? calcpt + 1.0 : calcpt - 1.0; } oldbin = currentbin; } } *diffbinptr = cmd->numout; /* Used as a marker */ } diffbinptr = diffbins; /* Now perform the barycentering */ printf("Massaging the data...\n\n"); printf("Amount Complete = 0%%"); /* Allocate our data array */ outdata = gen_fvect(worklen); do { /* Loop to read and write the data */ int numwritten = 0; double block_avg, block_var; if (RAWDATA) numread = read_psrdata(outdata, worklen, &s, idispdt, &padding, maskchans, &nummasked, &obsmask); else if (useshorts) numread = read_shorts(s.files[0], outdata, worklen, numchan); else numread = read_floats(s.files[0], outdata, worklen, numchan); if (numread == 0) break; /* Downsample if requested */ if (cmd->downsamp > 1) numread = downsample(outdata, numread, cmd->downsamp); /* Determine the approximate local average */ avg_var(outdata, numread, &block_avg, &block_var); /* Print percent complete */ newper = (int) ((float) totwrote / cmd->numout * 100.0) + 1; if (newper > oldper) { printf("\rAmount Complete = %3d%%", newper); fflush(stdout); oldper = newper; } /* Simply write the data if we don't have to add or */ /* remove any bins from this batch. */ /* OR write the amount of data up to cmd->numout or */ /* the next bin that will be added or removed. */ numtowrite = abs(*diffbinptr) - datawrote; /* FIXME: numtowrite+totwrote can wrap! */ if ((totwrote + numtowrite) > cmd->numout) numtowrite = cmd->numout - totwrote; if (numtowrite > numread) numtowrite = numread; chkfwrite(outdata, sizeof(float), numtowrite, outfile); datawrote += numtowrite; totwrote += numtowrite; numwritten += numtowrite; /* Update the statistics */ if (!padding) { for (ii = 0; ii < numtowrite; ii++) update_stats(statnum + ii, outdata[ii], &min, &max, &avg, &var); statnum += numtowrite; } if ((datawrote == abs(*diffbinptr)) && (numwritten != numread) && (totwrote < cmd->numout)) { /* Add/remove a bin */ float favg; int skip, nextdiffbin; skip = numtowrite; do { /* Write the rest of the data after adding/removing a bin */ if (*diffbinptr > 0) { /* Add a bin */ favg = (float) block_avg; chkfwrite(&favg, sizeof(float), 1, outfile); numadded++; totwrote++; } else { /* Remove a bin */ numremoved++; datawrote++; numwritten++; skip++; } diffbinptr++; /* Write the part after the diffbin */ numtowrite = numread - numwritten; if ((totwrote + numtowrite) > cmd->numout) numtowrite = cmd->numout - totwrote; nextdiffbin = abs(*diffbinptr) - datawrote; if (numtowrite > nextdiffbin) numtowrite = nextdiffbin; chkfwrite(outdata + skip, sizeof(float), numtowrite, outfile); numwritten += numtowrite; datawrote += numtowrite; totwrote += numtowrite; /* Update the statistics and counters */ if (!padding) { for (ii = 0; ii < numtowrite; ii++) update_stats(statnum + ii, outdata[skip + ii], &min, &max, &avg, &var); statnum += numtowrite; } skip += numtowrite; /* Stop if we have written out all the data we need to */ if (totwrote == cmd->numout) break; } while (numwritten < numread); } /* Stop if we have written out all the data we need to */ if (totwrote == cmd->numout) break; } while (numread); /* Free the arrays used in barycentering */ vect_free(bobsf); vect_free(btoa); vect_free(ttoa); } /* Calculate what the amount of padding we need */ if (cmd->numout > totwrote) padwrote = padtowrite = cmd->numout - totwrote; /* Write the new info file for the output data */ if (!cmd->nobaryP) { idata.bary = 1; idata.mjd_i = (int) floor(blotoa - (barydispdt / SECPERDAY)); idata.mjd_f = blotoa - (barydispdt / SECPERDAY) - idata.mjd_i; } if (cmd->downsamp > 1) idata.dt = dsdt; update_infodata(&idata, totwrote, padtowrite, diffbins, numdiffbins); writeinf(&idata); /* Set the padded points equal to the average data point */ if (idata.numonoff >= 1) { int jj, index, startpad, endpad; for (ii = 0; ii < worklen; ii++) outdata[ii] = avg; fclose(outfile); outfile = chkfopen(datafilenm, "rb+"); for (ii = 0; ii < idata.numonoff; ii++) { index = 2 * ii; startpad = idata.onoff[index + 1]; if (ii == idata.numonoff - 1) endpad = idata.N - 1; else endpad = idata.onoff[index + 2]; chkfseek(outfile, (startpad + 1) * sizeof(float), SEEK_SET); padtowrite = endpad - startpad; for (jj = 0; jj < padtowrite / worklen; jj++) chkfwrite(outdata, sizeof(float), worklen, outfile); chkfwrite(outdata, sizeof(float), padtowrite % worklen, outfile); } } vect_free(outdata); // Close all the raw files and free their vectors close_rawfiles(&s); /* Print simple stats and results */ var /= (datawrote - 1); /* Conver the '.dat' file to '.sdat' if requested */ if (cmd->shortsP) { FILE *infile; int safe_convert = 1, bufflen = 65536; char *sdatafilenm; float *fbuffer; short *sbuffer; offset = (int) (floor(avg)); if ((max - min) > (SHRT_MAX - SHRT_MIN)) { if ((max - min) < 1.5 * (SHRT_MAX - SHRT_MIN)) { printf("Warning: There is more dynamic range in the data\n" " than can be handled perfectly:\n" " max - min = %.2f - %.2f = %.2f\n" " Clipping the low values...\n\n", max, min, max - min); offset = max - SHRT_MAX; } else { printf("Error: There is way too much dynamic range in the data:\n" " max - min = %.2f - %.2f = %.2f\n" " Not converting to shorts.\n\n", max, min, max - min); safe_convert = 0; } } if (safe_convert) { fbuffer = gen_fvect(bufflen); sbuffer = gen_svect(bufflen); sdatafilenm = (char *) calloc(slen, 1); sprintf(sdatafilenm, "%s.sdat", cmd->outfile); printf("\n\nConverting floats in '%s' to shorts in '%s'.", datafilenm, sdatafilenm); fflush(NULL); infile = chkfopen(datafilenm, "rb"); outfile = chkfopen(sdatafilenm, "wb"); while ((numread = chkfread(fbuffer, sizeof(float), bufflen, infile))) { for (ii = 0; ii < numread; ii++) sbuffer[ii] = (short) (fbuffer[ii] + 1e-20 - offset); chkfwrite(sbuffer, sizeof(short), numread, outfile); } fclose(infile); fclose(outfile); remove(datafilenm); vect_free(fbuffer); vect_free(sbuffer); } } printf("\n\nDone.\n\nSimple statistics of the output data:\n"); printf(" Data points written: %ld\n", totwrote); if (padwrote) printf(" Padding points written: %ld\n", padwrote); if (!cmd->nobaryP) { if (numadded) printf(" Bins added for barycentering: %d\n", numadded); if (numremoved) printf(" Bins removed for barycentering: %d\n", numremoved); } printf(" Maximum value of data: %.2f\n", max); printf(" Minimum value of data: %.2f\n", min); printf(" Data average value: %.2f\n", avg); printf(" Data standard deviation: %.2f\n", sqrt(var)); if (cmd->shortsP && offset != 0) printf(" Offset applied to data: %d\n", -offset); printf("\n"); /* Cleanup */ if (cmd->maskfileP) { free_mask(obsmask); vect_free(maskchans); } vect_free(tobsf); vect_free(dispdt); vect_free(idispdt); free(outinfonm); free(datafilenm); if (!cmd->nobaryP) vect_free(diffbins); return (0); }