void game_loop(int mode) { int y=Y/2,x=X/2; updateB(y, x); updateA(); update_log(); /* il client aspetta */ if (mode) { print_message("Comincia l'avversario, attendi!"); recive_message(); } updateB(y, x); updateA(); update_log(); print_message("Il tuo turno"); update_side_view(1); while (muovi_cursorse(&y, &x)) { updateB(Y,X); updateA(); update_log(); update_side_view(0); while (recive_message()); updateB(y,x); updateA(); update_side_view(1); update_log(); print_message("Il tuo turno"); } }
void* car_park(void* arg) { int fd; info_t info = *(info_t *) arg; message_t message, exitmsg; pthread_t selfThread = pthread_self(); // Makes the thread detached if (pthread_detach(selfThread) != 0){ perror("Failed to make a thread detached.\n"); return NULL; } if ((fd = open(info.carFIFO, O_WRONLY)) == -1 ) { perror(strcat(info.carFIFO, " FIFO opening failed on arrumador")); free(arg); return NULL; } pthread_mutex_lock(&mutexPark ); if (numOccupiedPlaces >= numPlaces){ strcpy(message.msg, FULL); update_log(info, LOG_FULL); pthread_mutex_unlock(&mutexPark); write(fd, &message, sizeof(message)); } else { numOccupiedPlaces++; strcpy(message.msg, ENTRY_PARK); update_log(info, PARKING); write(fd, &message, sizeof(message)); pthread_mutex_unlock(&mutexPark); clock_t start, end; start = clock(); do { end = clock(); } while(end-start <= info.parked_time); // Parking time is over pthread_mutex_lock(&mutexPark); numOccupiedPlaces--; strcpy(exitmsg.msg, EXIT_PARK); update_log(info, EXIT_PARK); pthread_mutex_unlock(&mutexPark); write(fd, &exitmsg, sizeof(exitmsg)); } free(arg); close(fd); return NULL; }
/* Write an AVL tree to a file (the opening book), then clear the tree. Returns 0 if successfull. */ int write_book(const char *filename, AvlNode *tree) { FILE *fp; ASSERT(1, filename != NULL); if (tree == NULL) return -1; if (!book_modified) return 0; if ((fp = fopen(filename, "wb")) == NULL) { my_perror("Can't open file %s", filename); return -1; } write_avl(tree, fp); my_close(fp, filename); update_log("Book file saved: %s", filename); return 0; }
static void draw_window_contents( WindowPtr wp) { GrafPtr old_port; GetPort(&old_port); SetPortWindowPort(wp); /* Any specific updating stuff.... */ #ifdef OP_PLATFORM_MAC_CARBON_FLAG { Rect windowBounds; GetWindowPortBounds(wp, &windowBounds); EraseRect(&windowBounds); } #else EraseRect(&wp->portRect); #endif update_log(wp); SetPort(old_port); return; }
/************************************************* * Function: MX_ReadDataFormFlash * Description: * Author: cxy * Returns: * Parameter: * History: *************************************************/ void MX_ReadDataFormFlash(u8 *pu8Data, u16 u16Len) { uint32_t para_offset = PARA_OFFSET; OSStatus err = kNoErr; err = MicoFlashRead( MICO_PARTITION_PARAMETER_2,¶_offset, pu8Data, u16Len ); require_noerr(err, exit); exit: if(err != kNoErr) update_log("Update exit with err = %d", err); }
static void rcd_transaction_finished (RCDTransaction *transaction, const char *msg) { if (transaction->flags != RCD_TRANSACTION_FLAGS_DRY_RUN) update_log (transaction); rcd_transaction_send_log (transaction, TRUE, msg); rcd_transaction_emit_transaction_finished (transaction); }
/************************************************* * Function: HF_WriteDataToFlash * Description: * Author: cxy * Returns: * Parameter: * History: *************************************************/ void MX_WriteDataToFlash(u8 *pu8Data, u16 u16Len) { mico_logic_partition_t *para_partition_info; OSStatus err = kNoErr; uint32_t para_offset = PARA_OFFSET; para_partition_info = MicoFlashGetInfo(MICO_PARTITION_PARAMETER_2); require_action( para_partition_info->partition_owner != MICO_FLASH_NONE, exit, err = kUnsupportedErr ); err = MicoFlashErase(MICO_PARTITION_PARAMETER_2 ,para_offset, para_partition_info->partition_length-PARA_OFFSET); require_noerr(err, exit); err = MicoFlashWrite( MICO_PARTITION_PARAMETER_2, ¶_offset, pu8Data, u16Len ); require_noerr(err, exit); exit: if(err != kNoErr) update_log("Update exit with err = %d", err); }
void gmrt2fb(FILE *input, FILE *output) /* includefile*/ { double mean,sum,num; short junk,result[256]; unsigned short ur[256]; int c,r,opened; char string[80]; unsigned char uc[256]; r=opened=0; c=256; sum=num=0.0; while (!ferror(input)) { if ( (fread(&junk,2,1,input)) != 1) return; result[c--]= -1*((~junk) & 32767); if (c==0) { r++; if (r>10) { for (c=1;c<=256;c++) { ur[c-1]=result[c]; uc[c-1]=128+((double)result[c]-mean); } ur[0]=ur[1]=ur[254]=ur[255]=uc[0]=uc[1]=uc[254]=uc[255]=0; if (obits==16) fwrite(ur,sizeof(short),256,output); if (obits==8) fwrite(uc,sizeof(char),256,output); } else { /* for some reason, the first 10 samples were not used in the f77 code, so repeat that here but use these samples to calculate a mean */ for (c=1;c<=256;c++) { sum+=result[c]; num+=1.0; } mean=sum/num; } if (r%1024 == 0) { if (!opened) { open_log("filterbank.monitor"); opened=1; } sprintf(string,"time:%.1fs",r*tsamp); update_log(string); } c=256; } } }
/************************************************* * Function: MX_FirmwareUpdate * Description: * Author: cxy * Returns: * Parameter: * History: *************************************************/ u32 MX_FirmwareUpdate(u8 *pu8FileData, u32 u32Offset, u32 u32DataLen) { #if 1 mico_logic_partition_t *para_partition_info; OSStatus err = kNoErr; if (0 == u32Offset) { para_partition_info = MicoFlashGetInfo(MICO_PARTITION_OTA_TEMP); require_action( para_partition_info->partition_owner != MICO_FLASH_NONE, exit, err = kUnsupportedErr ); err = MicoFlashErase(MICO_PARTITION_OTA_TEMP , 0, para_partition_info->partition_length ); require_noerr(err, exit); } err = MicoFlashWrite( MICO_PARTITION_OTA_TEMP, &u32Offset, pu8FileData, u32DataLen ); require_noerr(err, exit); return ZC_RET_OK; exit: if(err != kNoErr) update_log("Update exit with err = %d", err); return ZC_RET_ERROR; #endif }
void create_windows() { /* Creazione finestre varie */ winA = newwin(WIN_GAME_HEIGH, WIN_GAME_WIDTH, WIN_PLAYER_A_START_Y, WIN_PLAYER_A_START_X); winB = newwin(WIN_GAME_HEIGH, WIN_GAME_WIDTH, WIN_PLAYER_B_START_Y, WIN_PLAYER_B_START_X); msg = newwin(WIN_MSG_HEIGH, WIN_MSG_WIDTH, WIN_MSG_START_Y, WIN_MSG_START_X); score = newwin(WIN_SCORE_HEIGH, WIN_SCORE_WIDTH, WIN_SCORE_START_Y, WIN_SCORE_START_X); log_win = newwin(WIN_LOG_HEIGH, WIN_LOG_WIDTH, WIN_LOG_START_Y, WIN_LOG_START_X); wrefresh(winA); wrefresh(winB); wrefresh(msg); wrefresh(score); wrefresh(log_win); winA_outline = newwin(WIN_GAME_OUTLINE_HEIGH, WIN_GAME_OUTLINE_WIDTH, WIN_PLAYER_A_OUTLINE_START_Y, WIN_PLAYER_A_OUTLINE_START_X); winB_outline = newwin(WIN_GAME_OUTLINE_HEIGH, WIN_GAME_OUTLINE_WIDTH, WIN_PLAYER_B_OUTLINE_START_Y, WIN_PLAYER_B_OUTLINE_START_X); msg_outline = newwin(WIN_MSG_OUTLINE_HEIGH, WIN_MSG_OUTLINE_WIDTH, WIN_MSG_OUTLINE_START_Y, WIN_MSG_OUTLINE_START_X); score_outline = newwin(WIN_SCORE_OUTLINE_HEIGH, WIN_SCORE_OUTLINE_WIDTH, WIN_SCORE_OUTLINE_START_Y, WIN_SCORE_OUTLINE_START_X); log_outline = newwin(WIN_LOG_OUTLINE_HEIGH, WIN_LOG_OUTLINE_WIDTH, WIN_LOG_OUTLINE_START_Y, WIN_LOG_OUTLINE_START_X); box(winA_outline,0,0); box(winB_outline,0,0); box(msg_outline,0,0); box(score_outline,0,0); box(log_outline,0,0); mvwprintw(winA_outline, 0, (WIN_GAME_OUTLINE_WIDTH)/2-strlen(player)/2-2, " %s ", player); mvwprintw(winB_outline,0 , (WIN_GAME_OUTLINE_WIDTH)/2-strlen(avversario)/2-1, " %s ", avversario); mvwprintw(score_outline,0 , (WIN_SCORE_OUTLINE_WIDTH)/2-strlen(SCORE_WIN_TITLE)/2-1, " %s ", SCORE_WIN_TITLE); mvwprintw(log_outline,0 , (WIN_LOG_OUTLINE_WIDTH)/2-strlen(LOG_WIN_TITLE)/2-1, " %s ", LOG_WIN_TITLE); mvwprintw(msg_outline,0 , (WIN_MSG_OUTLINE_WIDTH)/2-strlen(MSG_WIN_TITLE)/2-1, " %s ", MSG_WIN_TITLE); wrefresh(winA_outline); wrefresh(winB_outline); wrefresh(msg_outline); wrefresh(score_outline); wrefresh(log_outline); update_log(); updateA(); updateB(Y,X); }
/* * Add the result of the current game to the score list */ void update_topten(int how) { struct toptenentry *toptenlist, newtt; boolean need_rewrite; int fd; if (program_state.panicking) return; end_how = how; /* save how for nh_get_topten */ fill_topten_entry(&newtt, how); update_log(&newtt); update_xlog(&newtt); /* nothing more to do for non-scoring games */ if (wizard || discover) return; fd = open_datafile(RECORD, O_RDWR | O_CREAT, SCOREPREFIX); if (!lock_fd(fd, 30)) { close(fd); return; } toptenlist = read_topten(fd, TTLISTLEN); /* possibly rearrange the score list to include the new entry */ need_rewrite = toptenlist_insert(toptenlist, &newtt); if (need_rewrite) write_topten(fd, toptenlist); unlock_fd(fd); close(fd); free(toptenlist); }
void bpp2fb(FILE *input, FILE *output) /* includefile */ { FILE *fpou; int np,ns,nc,i,c,b,s,nchars,idump,doit,opened,nsblk,i1,i2,*chtab,blocksize; float *tempblock, *datablock,realtime=0.0; unsigned char *charblock,sample; static unsigned char *charcarry; unsigned short *shortblock; char string[80]; int nshift[8] = {28,24,20,16,12,8,4,0}; static int ncarryover; static int first = 1; static int fileidx_start=1,file_count=1; static double end_time; double scantime,sample_start,sample_final; int sample_skip,bytestart; int bytefinal,fileidx_final,sample_diff,byte_diff=0; int bpp_headersize = 32768; int rd_jnq=0; double sample_end,byte_end; np=idump=opened=0; ns=512; blocksize=ns*nchans; nc=nchans; if(first) { charcarry = (unsigned char *) malloc(sizeof(unsigned char)*blocksize); ncarryover = 0; first = 0; scantime = (double)((double)bpp_search.file_size)/((double)(nchans/2))*bpp_search.samp_rate*1.e-6; if(start_time){ fileidx_start = ceil(start_time/scantime); file_count = fileidx_start; sample_skip = floor(start_time/tsamp); sample_start = sample_skip - (double)((fileidx_start-1)*(scantime/(double)tsamp)); bytestart = (sample_start*(double)nchans)/2.; if(bytestart<blocksize/2){ bytestart+=(double)bpp_search.file_size-blocksize/2; fileidx_start-=1; file_count -=1; sample_skip -= ns; sample_start = sample_skip - (double)((fileidx_start-1)*(scantime/(double)tsamp)); } realtime += sample_skip*(double)tsamp - scantime*(fileidx_start-1); if((rd_jnq =fseek(input,bytestart,SEEK_CUR)< 0)) fprintf(stderr,"Error seeking to data byte %d in file\n",bytestart); } if(final_time){ sample_end = ceil(final_time/(double)tsamp); fileidx_final = ceil(final_time/scantime); sample_final = sample_end-(double)((fileidx_final-1)*scantime/tsamp); byte_end = ceil(final_time/(double)tsamp)*(double)nchans/2; bytefinal = (double)sample_final*(double)nchans/2; end_time = (double)(byte_end/((double)nchans/2)*(double)tsamp); fprintf(stderr,"Ending Time: \n"); fprintf(stderr," End File # %2d\n",fileidx_final); fprintf(stderr," End Sample # %12.3f\n",sample_final); fprintf(stderr," End Time (s) %12.5f (w.r.t. File # 1)\n",end_time); if(start_time) { end_time -= (double)((fileidx_start-1)*scantime); fprintf(stderr," End Time (s) %12.5f (w.r.t. File # %d)\n",end_time,fileidx_start); } } if (!final_time) end_time = 1000*scantime; } tempblock = (float *) malloc(sizeof(float)*blocksize); datablock = (float *) malloc(sizeof(float)*blocksize); charblock = (unsigned char *) malloc(sizeof(unsigned char)*blocksize); shortblock = (unsigned short *) malloc(sizeof(unsigned short)*blocksize); if (headerfile) { /* write output ASCII header file */ fpou=open_file("head","w"); fprintf(fpou,"Original BPP file: %s\n",inpfile); fprintf(fpou,"Sample time (us): %f\n",tsamp*1.0e6); fprintf(fpou,"Number of samples/record: %d\n",ns); fprintf(fpou,"Center freq (MHz): %f\n",fch1+(float)nchans*foff/2.0); fprintf(fpou,"Channel band (kHz): %f\n",fabs(foff)*1000.0); fprintf(fpou,"Number of channels/record: %d\n",nc); fprintf(fpou,"Time stamp (MJD): %18.12f\n",tstart); fprintf(fpou,"AZ at start: %f\n",az_start); fprintf(fpou,"ZA at start: %f\n",za_start); fprintf(fpou,"RA (J2000): %f\n",src_raj); fprintf(fpou,"DEC (J2000): %f\n",src_dej); fclose(fpou); } chtab=bpp_chans(bpp_search.bandwidth,bpp_search.mb_start_address, bpp_search.mb_end_address,bpp_search.mb_start_board, bpp_search.mb_end_board,bpp_search.cb_id, bpp_search.aib_los,bpp_search.dfb_sram_freqs, bpp_search.rf_lo); /************************************************/ /* main loop over each record of input data file*/ /************************************************/ while (!feof(input)&& realtime<=end_time) { /* read in a record */ if(!ncarryover) /* No data left from previous file */ nchars=fread(charblock,sizeof(unsigned char),blocksize/2,input); if(ncarryover>0) { /* Add to partial block left from previous file */ nchars=fread(charblock,sizeof(unsigned char),(blocksize/2-ncarryover),input); for(c=0;c<nchars;c++) charblock[c+ncarryover] = charblock[c]; for(c=0;c<ncarryover;c++) charblock[c] = charcarry[c]; ncarryover = 0; nchars = blocksize/2; fprintf(stderr," Starting at beginning of File # %d\n",file_count); } if(!ncarryover && nchars<blocksize/2) { /* Don't process, just keep */ ncarryover = nchars; for(c=0;c<nchars;c++) charcarry[c] = charblock[c]; file_count++; if(final_time) end_time = end_time - (double)tsamp*(int)(scantime/(double)tsamp); fprintf(stderr,"Advancing to file # %d\n",file_count); /* if(final_time) fprintf(stderr," End time = %f (w.r.t. file # %d)\n",end_time,file_count);*/ /* fprintf(stderr," Realtime is %f\n",realtime);*/ } else { /* decide whether to process it */ if ( (doit=process(realtime,sample_skip*(double)tsamp,end_time)) == -1) { fprintf(stderr,"realtime at time of break = %f (s)\n ",realtime); break; } doit = 1; if (doit) { /* about to process this record, update log */ np++; if (np%10 == 0) { if (!opened) { open_log("filterbank.monitor"); opened=1; } sprintf(string,"time:%.1fs",realtime); update_log(string); } /* unscramble the 4-bit data into the float tempblock */ nsblk=0; for (c=0;c<nchars;c++) { char2ints(charblock[c],&i1,&i2); tempblock[nsblk++] = (float) i2; tempblock[nsblk++] = (float) i1; } /* update wallclock time */ realtime+=(float) (nsblk/nchans/nifs) * (float) tsamp; if (sumifs) for (s=0;s<nsblk;s++) datablock[s]=0.0; s=i1=i2=0; /* loop over all samples, summing IFs 1+2 -> total power if neccessary */ while (s<nsblk) { for (i=0;i<nifs;i++) { for (c=0;c<nchans;c++) { if (sumifs) { if (i<2) datablock[i1+c]+=tempblock[i2+chtab[i*nchans+c]]; } else { datablock[i1+i*nchans+c]=tempblock[i2+chtab[i*nchans+c]]; } s++; } } /* update internal counters */ i2+=nifs*nchans; if (sumifs) { i1+=nchans; } else { i1+=nifs*nchans; } } /* divide by 2 to in sumif mode to allow for 4-bit packing */ if (sumifs) { nsblk/=nifs; for (s=0;s<nsblk;s++) datablock[s]/=2.0; } /* decide on how to write out data */ if (obits==32) { /* user has requested floating point numbers in binary file */ if (swapout) for (s=0;s<nsblk;s++) swap_float(&datablock[s]); fwrite(datablock,sizeof(float),nsblk,output); } else if (obits==16) { /* user has requested unsigned shorts in binary file */ float2short(datablock,nsblk,0.0,15.0,shortblock); if (swapout) for (s=0;s<nsblk;s++) swap_short(&shortblock[s]); fwrite(shortblock,sizeof(unsigned short),nsblk,output); } else if (obits==8) { /* user has requested unsigned chars in binary file */ float2char(datablock,nsblk,0.0,15.0,charblock); fwrite(charblock,sizeof(unsigned char),nsblk,output); } else if (obits==4) { /* default is to write data out packed into character format */ float2four(datablock,nsblk,0.0,15.0,charblock); fwrite(charblock,sizeof(unsigned char),nsblk/2,output); } else { error_message("unknown bit format for writing"); } } /* update dumps read/processed */ idump+=ns; } } }
void pspm2fb(FILE *input, FILE *output) /* includefile */ { FILE *fpou; int np=0,ns,nc,c,s,nints,rawdata[PSPM_INT_BLOCK],idump,doit,swap_bytes; int i,opened=0,drift; float datablock[PSPM_REA_BLOCK],datablock2[PSPM_REA_BLOCK],sum,realtime; unsigned char charblock[PSPM_REA_BLOCK],sample; unsigned short shortblock[PSPM_REA_BLOCK]; char string[80]; /* establish whether this is drift-mode data */ if (pspm_search.HEADER_TYPE == 0) { drift=1; } else { drift=0; } idump=0; /* establish whether we need to swap bytes (PSPM is big endian) */ swap_bytes=little_endian(); /* shorthand for number of samples and channels in a datablock */ ns=PSPM_SAM_BLOCK; nc=PSPM_NCH_BLOCK; if (headerfile) { /* write output ASCII header file */ fpou=open_file("head","w"); fprintf(fpou,"Original PSPM file: %s\n",inpfile); fprintf(fpou,"Sample time (us): %f\n",tsamp*1.0e6); fprintf(fpou,"Number of samples/record: %d\n",ns); fprintf(fpou,"Center freq (MHz): %f\n",fch1+(float)nchans*foff/2.0); fprintf(fpou,"Channel band (kHz): %f\n",fabs(foff)*1000.0); fprintf(fpou,"Number of channels/record: %d\n",nc); fprintf(fpou,"Time stamp (MJD): %18.12f\n",tstart); fprintf(fpou,"AZ at start: %f\n",az_start); fprintf(fpou,"ZA at start: %f\n",za_start); fprintf(fpou,"RA (J2000): %f\n",src_raj); fprintf(fpou,"DEC (J2000): %f\n",src_dej); fclose(fpou); } /* main loop over each record of input data file*/ while (!feof(input)) { /* this is the time at that start of the block */ realtime=tsamp*idump; /* read in a record and unscramble the channels */ nints=fread(rawdata,sizeof(int),PSPM_INT_BLOCK,input); if ( (doit=process(realtime,start_time,final_time)) == -1) break; if (doit) { /* about to process this record, update log */ np++; if (np%10 == 0) { if (!opened) { /* open up logfile */ open_log("filterbank.monitor"); opened=1; } sprintf(string,"time:%.1fs",realtime); update_log(string); } if (swap_bytes) for (s=0;s<nints;s++) swap_int(&rawdata[s]); /* unscramble the channels using Ingrid's C routine */ pspm_decode(rawdata,datablock); /* if the -invert option was specified, flip the band */ i=0; if (invert_band) { for(s=0;s<ns;s++) { for (c=nc-1;c>=0;c--) { datablock2[i++]=datablock[s*nc+c]; } } for(i=0;i<ns*nc;i++) datablock[i]=datablock2[i]; } realtime+=(float) ns * (float) tsamp; /* decide on how to write out data */ if (obits==32) { /* user has requested floating point numbers in binary file */ if (swapout) for (s=0;s<ns*nc;s++) swap_float(&datablock[s]); fwrite(datablock,sizeof(float),ns*nc,output); } else if (obits==16) { /* user has requested unsigned shorts in binary file */ float2short(datablock,ns*nc,0.0,15.0,shortblock); if (swapout) for (s=0;s<ns*nc;s++) swap_short(&shortblock[s]); fwrite(shortblock,sizeof(unsigned short),ns*nc,output); } else if (obits==8) { /* user has requested unsigned chars in binary file */ float2char(datablock,ns*nc,0.0,15.0,charblock); fwrite(charblock,sizeof(unsigned char),ns*nc,output); } else if (obits==4) { /* default is to write data out packed into character format */ float2four(datablock,ns*nc,0.0,15.0,charblock); fwrite(charblock,sizeof(unsigned char),ns*nc/2,output); } else if (obits==0) { /* special mode to write out in different order for old ddsp program */ for (c=0;c<nc;c++) { for(s=0;s<ns;s++) { sample=(unsigned char)datablock[s*nc+c]; fwrite(&sample,sizeof(unsigned char),1,output); } } } else { error_message("unknown bit format for writing"); } } /* update dumps read/processed */ idump+=ns; /* break out if this is in drift-mode and we've read 9 beams */ if (drift && (idump == 4718592)) break; } }
main (int argc, char *argv[]) { /* local variables */ double pfactor,newmjd=0.0; float sefd; int i,opened_input=0,opened_output=0,headersize=0; char string[80]; /* set up default globals */ baseline=ascii=multiple=1; npuls=binary=totalpower=accumulate=0; time_offset=acceleration=skip_time=read_time=0.0; asciipol=psrfits=stream=headerless=npulses=0; phase_start=folding_period=dump_time=tsamp_user=0.0; phase_finish=pfactor=1.0; jyfactor=sefd=userbase=0.0; nbins=0; /* this will get set in the folding routine if not set by user */ strcpy(polyco_file,""); /* check the command line parameters */ i=1; while (i<argc) { print_version(argv[0],argv[1]); if (strings_equal(argv[i],"-o")) { /* get and open file for output */ i++; strcpy(outfile,argv[i]); output=fopen(outfile,"wb"); opened_output=1; } else if (strings_equal(argv[i],"-m")) { multiple=atoi(argv[++i]); } else if (strings_equal(argv[i],"-p")) { /* get folding period */ i++; if (file_exists(argv[i])) { strcpy(polyco_file,argv[i]); folding_period=-1.0; } else { folding_period=atof(argv[i]); } } else if (strings_equal(argv[i],"-dt")) { /* add a time offset in seconds to tstart */ time_offset=atof(argv[++i]); } else if (strings_equal(argv[i],"-mjd")) { /* change the start time completely! */ newmjd=atof(argv[++i]); } else if (strings_equal(argv[i],"-sk")) { /* skip the first skip_time seconds before folding */ skip_time=atof(argv[++i]); } else if (strings_equal(argv[i],"-re")) { /* read and fold only read_time seconds of data */ read_time=atof(argv[++i]); } else if (strings_equal(argv[i],"-a")) { /* get acceleration for folding */ acceleration=atof(argv[++i]); } else if (strings_equal(argv[i],"-d")) { /* get dumptime or number of pulses for subintegrations */ i++; if (strcspn(".",argv[i])) { npulses=atoi(argv[i]); } else { dump_time=atof(argv[i]); } } else if (strings_equal(argv[i],"-t")) { /* get user-supplied sampling time */ i++; tsamp_user=atof(argv[i]); } else if (strings_equal(argv[i],"-j")) { /* get user-supplied Jansky calibration factor */ jyfactor=atof(argv[++i]); } else if (strings_equal(argv[i],"-s")) { /* get user-supplied SEFD */ sefd=atof(argv[++i]); } else if (strings_equal(argv[i],"-b")) { /* get user-supplied baseline */ baseline=0; userbase=atof(argv[++i]); } else if (strings_equal(argv[i],"-f")) { /* get period multiplication factor */ i++; pfactor=atof(argv[i]); } else if (strings_equal(argv[i],"-l")) { /* get leading phase of pulse */ i++; phase_start=atof(argv[i]); if ( (phase_start < 0.0) || (phase_start > 1.0) ) error_message("start pulse phase out of range!"); } else if (strings_equal(argv[i],"-r")) { /* get trailing phase of pulse */ i++; phase_finish=atof(argv[i]); if ( (phase_finish < 0.0) || (phase_finish > 1.0) ) error_message("final pulse phase out of range!"); } else if (strings_equal(argv[i],"-n")) { /* get number of bins */ i++; nbins=atoi(argv[i]); } else if (strings_equal(argv[i],"-ascii")) { /* write data as ASCII numbers */ ascii=1; } else if (strings_equal(argv[i],"-totalpower")) { /* sum polarizations 1+2 before writing */ totalpower=1; } else if (strings_equal(argv[i],"-epn")) { /* write data in EPN format */ ascii=0; } else if (strings_equal(argv[i],"-bin")) { /* write data in SIGPROC binary format */ binary=1; } else if (strings_equal(argv[i],"-acc")) { /* write out accumulated pulse profiles in subints */ accumulate=1; } else if (strings_equal(argv[i],"-asciipol")) { /* write data as ASCII numbers for Jim's polarization code */ asciipol=1; } else if (strings_equal(argv[i],"-psrfits")) { /* write data in PSRFITS format */ ascii=0; psrfits=1; #ifndef PSRFITS error_message("-psrfits option not supported in this compilation...\nConsult the SIGPROC manual for further information about PSRFITS."); #endif } else if (strings_equal(argv[i],"-stream")) { /* write data as ASCII streams */ stream=1; } else if (strings_equal(argv[i],"-sub")) { /* shorthand for -nobaseline -stream -d x */ stream=1; baseline=0; i++; if (strcspn(".",argv[i])) { npulses=atoi(argv[i]); } else { dump_time=atof(argv[i]); } } else if (strings_equal(argv[i],"-nobaseline")) { /* processing correlation functions so don't subtract baseline */ baseline=0; } else if (file_exists(argv[i])) { /* get and open file for input */ strcpy(inpfile,argv[i]); input=open_file(inpfile,"rb"); opened_input=1; } else if (help_required(argv[i])) { fold_help(); exit(0); } else { /* unknown argument passed down - stop! */ fold_help(); sprintf(string,"unknown argument (%s) passed to %s",argv[i],argv[0]); error_message(string); } i++; } /* get appropriate calibration factor from SEFD and baseline */ if (sefd != 0.0 && userbase != 0.0) jyfactor=sefd/userbase; /* multiply folding period by user-supplied factor */ if (folding_period != -1.0) folding_period*=pfactor; /* check start and end phase of pulse */ if (phase_start >= phase_finish) error_message("silly pulse phases selected!"); /* check npulses versus dump_time */ if (npulses < 0) error_message("npulses < 0!"); if ((npulses > 0) && (dump_time > 0.0)) error_message("can't have npulses AND dumptime defined!"); /* check for folding period still set to zero - if so, look for polyco.dat */ if (folding_period == 0.0) { strcpy(polyco_file,"polyco.dat"); if (file_exists(polyco_file)) { folding_period=-1.0; } else { error_message("folding period not specified and no polyco.dat found!"); } } if (!opened_input) { /* no input file selected, use standard input */ input=stdin; strcpy(inpfile,"stdin"); } /* read in the header parameters from the input stream */ if (!(headersize=read_header(input))) error_message("could not read header parameters!"); if (acceleration != 0.0) { tobs=tsamp*(double)nsamples(inpfile,headersize,nbits,nifs,nchans); if (tobs <= 0.0) error_message("could not get sensible observation time"); } /* override the header */ if (newmjd!=0.0) tstart=newmjd; if (!opened_output) { /* no output file selected, use standard output */ output=stdout; strcpy(outfile,"stdout"); } /* open the raw data file and establish its origin and header pars */ switch(data_type) { case 1: case 2: case 6: open_log("fold.monitor"); folded_profiles=fold_data(); break; default: error_message("input data is of unknown origin!!!"); } if ((npulses==0.0) && (dump_time==0.0)) write_profiles(folded_profiles,nbins,nchans,nifs,output); if (stream) fprintf(output,"#DONE\n"); /* all done, update and close logfile */ update_log("finished"); close_log(); i=0; #ifdef PSRFITS if (psrfits) fits_close_file(fits,&i); #endif exit(0); }
debug_win::debug_win( m::post_office_ptr p, us::user_service_ptr us, s::conversation_service_ptr ss, const n::udp_stats& udps, QWidget* parent) : QDialog{parent}, _post{p}, _user_service{us}, _conversation_service{ss}, _udp_stats(udps) { REQUIRE(p); REQUIRE(us); REQUIRE(ss); //main layout auto* layout = new QVBoxLayout{this}; setLayout(layout); auto* tabs = new QTabWidget{this}; tabs->setTabPosition(QTabWidget::West); layout->addWidget(tabs); //create log tab auto* log_tab = new QWidget; auto* log_layout = new QGridLayout{log_tab}; _log = new QTextEdit; log_layout->addWidget(_log, 0,0); //udp stats _udp_stat_text = new QLabel; //create mailbox tab auto* mailbox_tab = new QWidget; auto* mailbox_layout = new QGridLayout{mailbox_tab}; _mailboxes = new list; mailbox_layout->addWidget(_udp_stat_text, 0,0); mailbox_layout->addWidget(_mailboxes, 1,0); //add tabs tabs->addTab(log_tab, tr("log")); tabs->addTab(mailbox_tab, tr("mailboxes")); //add outside message queue to mailboxes tab auto outside = new queue_debug{convert(tr("outside")), _post->outside_stats()}; _mailboxes->add(outside); //fill tabs with data update_mailboxes(); update_log(); //setup timers auto *t = new QTimer(this); connect(t, SIGNAL(timeout()), this, SLOT(update_log())); t->start(UPDATE_LOG); auto *t2 = new QTimer(this); connect(t2, SIGNAL(timeout()), this, SLOT(update_mailboxes())); t2->start(UPDATE_MAILBOXES); auto *t3 = new QTimer(this); connect(t3, SIGNAL(timeout()), this, SLOT(update_udp_stats())); t3->start(UPDATE_GRAPH); restore_state(); ENSURE(_log); ENSURE(_post); ENSURE(_user_service); ENSURE(_conversation_service); }
void scamp2fb(FILE *input, FILE *output) /* includefile */ { FILE *fpou; unsigned char *gulp,*spew,*flip,sumof[256]; float realtime; double junk; char string[80],schead[640]; int i,j,k,doit,idump=0,nread,opened=0,s,f, ntotal=0,nclipped=0,ichans,sum,clipmax; //if (scamp_chans != nchans) exit(0); /* allocated space to store incoming and outgoing data blocks */ gulp = (unsigned char *) malloc(scamp_block_size * sizeof(unsigned char)); flip = (unsigned char *) malloc(scamp_block_size * sizeof(unsigned char)); spew = (unsigned char *) malloc(8*scamp_block_size * sizeof(unsigned char)); if (headerfile) { /* write output ASCII header file */ fpou=open_file("head","w"); fprintf(fpou,"Original SCAMP file: %s\n",inpfile); fprintf(fpou,"Sample time (us): %f\n",tsamp*1.0e6); fprintf(fpou,"Center freq (MHz): %f\n",fch1+(float)scamp_chans*foff/2.0); fprintf(fpou,"Channel band (kHz): %f\n",fabs(foff)*1000.0); fprintf(fpou,"Time stamp (MJD): %18.12f\n",tstart); fprintf(fpou,"RA (J2000): %f\n",src_raj); fprintf(fpou,"DEC (J2000): %f\n",src_dej); fclose(fpou); } if (clip_threshold>0.0) { /* clip samples which deviate by more than clip_threshold sigma times the mean. For these data, mean=nchan/2 and sigma = sqrt(nchan) */ clipmax=(float)(scamp_chans)/2.0+clip_threshold*sqrt((float)scamp_chans); for (i=0;i<256;i++) sumof[i]=sumchar(i); /* look-up table of byte sums */ } while (!feof(input)) { /* read ina 48k block of data */ nread=fread(gulp,1,scamp_block_size,input); /* do the band inversion here if necessary DEDISPERSE requires that the first channel is the highest frequency */ if (invert_band) { for (i=0; i<scamp_block_size; i++) flip[i]=flipchar(gulp[i]); for (i=0; i<scamp_block_size/scamp_chans; i++) { s=i*scamp_chans; f=(i+1)*scamp_chans; k=0; for (j=s;j<f;j++) { gulp[j]=flip[f-1-k]; k++; } } } /* now do clipping if necessary */ if (clip_threshold>0.0) { ichans=sum=j=0; for (i=0; i<scamp_block_size; i++) { /* keep track of sum over each byte (8 channels!) */ sum+=sumof[gulp[i]]; ichans+=8; if (ichans==scamp_chans) { /* decide whether to clip this sample */ if (sum>clipmax) { nclipped++; for (k=j; k<=i; k++) gulp[k]=0; } ntotal++; j=i+1; sum=0; ichans=0; } } } if (scamp_rawdata) { /* read off the header from the data and proceed as normal */ fread(schead,sizeof(schead),1,input); } else { /* extra (FORTRAN!) junk that gets written after each block */ fread(&junk,8,1,input); } /* decide whether to write out this block */ realtime=tsamp*idump; if ((doit=process(realtime,start_time,final_time))==-1) break; if (doit) { if (idump%1024 == 0) { if (!opened) { open_log("filterbank.monitor"); opened=1; } sprintf(string,"time:%.1fs",realtime); update_log(string); } /* output as single bit (default) or single byte data */ switch (obits) { case 1: idump+=8*nread/scamp_chans; i=1; /* write out only segments not in scamp.ignore */ for (j=1;j<=nread;j++) { if (!scamp_ignore[i]) fwrite(&gulp[j-1],1,1,output); i++; if (i>scamp_chans/8) i=1; } /*fwrite(gulp,1,nread,output);*/ break; case 8: k=0; for (i=0; i<nread; i++) { for (j=0;j<8;j++) { spew[k]=gulp[i]&1; gulp[i]>>=1; k++; if (!(k%scamp_chans)) idump++; } } fwrite(spew,1,8*scamp_block_size,output); break; } } } /* write out clipping statistics to ASCII file clip.stats */ if (clip_threshold>0) { fpou=open_file("clip.stats","w"); fprintf(fpou,"threshold %.1f sigma (sum = %d)\n", clip_threshold,clipmax); fprintf(fpou,"samples clipped = %d (total = %d)\n", nclipped,ntotal); fclose(fpou); } free(gulp);free(flip);free(spew); }
OSStatus update(void) { boot_table_t updateLog; uint32_t i, j, size; uint32_t updateStartAddress; uint32_t destStartAddress_tmp; uint32_t paraStartAddress; OSStatus err = kNoErr; MicoFlashInitialize( (mico_flash_t)MICO_FLASH_FOR_UPDATE ); memset(data, 0xFF, SizePerRW); memset(newData, 0xFF, SizePerRW); memset(paraSaveInRam, 0xFF, PARA_FLASH_SIZE); updateStartAddress = UPDATE_START_ADDRESS; paraStartAddress = PARA_START_ADDRESS; err = MicoFlashRead(MICO_FLASH_FOR_PARA, ¶StartAddress, (uint8_t *)&updateLog, sizeof(boot_table_t)); require_noerr(err, exit); /*Not a correct record*/ if(updateLogCheck(&updateLog) != Log_NeedUpdate){ size = UPDATE_FLASH_SIZE/SizePerRW; for(i = 0; i <= size; i++){ if( i==size ){ err = MicoFlashRead(MICO_FLASH_FOR_UPDATE, &updateStartAddress, data , UPDATE_FLASH_SIZE%SizePerRW); require_noerr(err, exit); } else{ err = MicoFlashRead(MICO_FLASH_FOR_UPDATE, &updateStartAddress, data , SizePerRW); require_noerr(err, exit); } for(j=0; j<SizePerRW; j++){ if(data[j] != 0xFF){ update_log("Update data need to be erased"); err = MicoFlashInitialize( MICO_FLASH_FOR_UPDATE ); require_noerr(err, exit); err = MicoFlashErase( MICO_FLASH_FOR_UPDATE, UPDATE_START_ADDRESS, UPDATE_END_ADDRESS ); require_noerr(err, exit); err = MicoFlashFinalize( MICO_FLASH_FOR_UPDATE ); require_noerr(err, exit); break; } } } goto exit; } update_log("Write OTA data to destination, type:%d, from 0x%08x to 0x%08x, length 0x%x", destFlashType, destStartAddress, destEndAddress, updateLog.length); destStartAddress_tmp = destStartAddress; updateStartAddress = UPDATE_START_ADDRESS; err = MicoFlashInitialize( destFlashType ); require_noerr(err, exit); err = MicoFlashErase( destFlashType, destStartAddress, destEndAddress ); require_noerr(err, exit); size = (updateLog.length)/SizePerRW; for(i = 0; i <= size; i++){ if( i==size && (updateLog.length)%SizePerRW){ err = MicoFlashRead(MICO_FLASH_FOR_UPDATE, &updateStartAddress, data , (updateLog.length)%SizePerRW); require_noerr(err, exit); err = MicoFlashInitialize( destFlashType ); require_noerr(err, exit); err = MicoFlashWrite(destFlashType, &destStartAddress_tmp, data, (updateLog.length)%SizePerRW); require_noerr(err, exit); destStartAddress_tmp -= (updateLog.length)%SizePerRW; err = MicoFlashRead(destFlashType, &destStartAddress_tmp, newData , (updateLog.length)%SizePerRW); require_noerr(err, exit); err = memcmp(data, newData, (updateLog.length)%SizePerRW); require_noerr_action(err, exit, err = kWriteErr); } else{ err = MicoFlashRead(MICO_FLASH_FOR_UPDATE, &updateStartAddress, data , SizePerRW); require_noerr(err, exit); err = MicoFlashInitialize( destFlashType ); require_noerr(err, exit); err = MicoFlashWrite(destFlashType, &destStartAddress_tmp, data, SizePerRW); require_noerr(err, exit); destStartAddress_tmp -= SizePerRW; err = MicoFlashRead(destFlashType, &destStartAddress_tmp, newData , SizePerRW); require_noerr(err, exit); err = memcmp(data, newData, SizePerRW); require_noerr_action(err, exit, err = kWriteErr); } } update_log("Update start to clear data..."); paraStartAddress = PARA_START_ADDRESS; err = MicoFlashRead(MICO_FLASH_FOR_PARA, ¶StartAddress, paraSaveInRam, PARA_FLASH_SIZE); require_noerr(err, exit); memset(paraSaveInRam, 0xff, sizeof(boot_table_t)); err = MicoFlashErase(MICO_FLASH_FOR_PARA, PARA_START_ADDRESS, PARA_END_ADDRESS); require_noerr(err, exit); paraStartAddress = PARA_START_ADDRESS; err = MicoFlashWrite(MICO_FLASH_FOR_PARA, ¶StartAddress, paraSaveInRam, PARA_FLASH_SIZE); require_noerr(err, exit); err = MicoFlashErase(MICO_FLASH_FOR_UPDATE, UPDATE_START_ADDRESS, UPDATE_END_ADDRESS); require_noerr(err, exit); update_log("Update success"); exit: if(err != kNoErr) update_log("Update exit with err = %d", err); MicoFlashFinalize(MICO_FLASH_FOR_UPDATE); MicoFlashFinalize(destFlashType); return err; }
void decimate_data(FILE *input, FILE *output) /*includefile*/ { char string[80]; float *fblock,min,max,realtime,fsaved[2]; unsigned short *sblock; unsigned char *cblock; int nsaved=0,ns,nsblk,opened=0,nout; nsblk=nchans*nifs*naddt; fblock=(float *) malloc(nsblk*sizeof(float)); sblock=(unsigned short *) malloc(nsblk*sizeof(unsigned short)); cblock=(unsigned char *) malloc(nsblk*sizeof(unsigned short)); realtime=min=0.0; max=(float) pow(2.0,(double)obits) -1.0; /* main decimation loop */ while ((ns=read_block(input,nbits,fblock,nsblk))>0) { add_channels(fblock,ns,naddc); add_samples(fblock,nifs,nchans/naddc,naddt); if (!opened) { /* open up logfile */ open_log("decimate.monitor"); opened=1; } nout=ns/naddt/naddc; switch (obits) { case 32: fwrite(fblock,sizeof(float),nout,output); break; case 16: float2short(fblock,nout,min,max,sblock); fwrite(sblock,sizeof(unsigned short),nout,output); break; case 8: float2char(fblock,nout,min,max,cblock); fwrite(cblock,sizeof(unsigned char),nout,output); break; case 4: if (nout==1) { /* must have at least two samples for four-bit packing save this one */ fsaved[nsaved]=fblock[0]; nsaved++; if (nsaved==2) { /* we have 2 saved! write out */ float2four(fsaved,nsaved,min,max,cblock); fwrite(cblock,sizeof(unsigned char),1,output); nsaved=0; } } else { /* normal case */ float2four(fblock,nout,min,max,cblock); fwrite(cblock,sizeof(unsigned char),nout/2,output); } break; case 2: float2two(fblock,nout,min,max,cblock); fwrite(cblock,sizeof(unsigned char),nout/4,output); break; } realtime+=(float) tsamp * (float) ns/(float) nchans/(float) nifs; sprintf(string,"time:%.1fs",realtime); update_log(string); } update_log("finished"); close_log(); }
void matrix_scan_keymap(void) { update_log(); }
/* Read a PGN file (a collection of one or more games in PGN format) and store the positions and their win/loss ratios in an AVL tree (**tree). The AVL tree can later be written in an opening book file (book.bin). Returns the number of new positions added to the tree, or -1 on error. */ int pgn_to_tree(const char *filename, AvlNode **tree) { PgnResult result; int prev_progress; int npos = 0; long file_len; FILE *fp; Board board; ASSERT(1, filename != NULL); if ((fp = fopen(filename, "r")) == NULL) { my_perror("Can't open PGN file %s", filename); return -1; } if (settings.book_type != BOOK_MEM) { settings.book_type = BOOK_MEM; printf("Changed book mode to \"book in memory\"\n"); } if (*tree == NULL && file_exists(settings.book_file)) { printf("Loading opening book to memory...\n"); book_to_tree(settings.book_file, tree); } else if (*tree == NULL) printf("Creating a new opening book...\n"); /* Find out how big the file is. */ fseek(fp, 0, SEEK_END); file_len = ftell(fp); rewind(fp); printf("Reading PGN file %s...\n", filename); prev_progress = 0; progressbar(50, 0); while ((result = get_pgn_result(fp)) != RESULT_ERROR) { int depth; int progress; int len; char san_move[MAX_BUF]; /* Games with an unknown result are ignored. */ ASSERT(1, result != RESULT_ERROR); if (result == NO_RESULT || result == DRAWN_GAME) continue; depth = 0; fen_to_board(&board, START_FEN); while ((len = read_move(san_move, MAX_BUF, fp)) >= 0) { int points = 0; U32 move; /* break out of the loop when a new game begins */ if (depth > 0 && san_move[0] == '[') break; if (len < 2) continue; move = san_to_move(&board, san_move); if (move == NULLMOVE) { #if DEBUG_LEVEL > 0 update_log("Illegal move in %s: %s, line: %d\n", filename, san_move, get_line_num(fp)); #endif /* DEBUG_LEVEL > 0 */ break; } if ((result == WHITE_WINS && board.color == WHITE) || (result == BLACK_WINS && board.color == BLACK)) points = 2; make_move(&board, move); if (save_book_pos(board.posp->key, points, tree)) npos++; if (++depth >= MAX_BOOK_PLIES) break; } progress = (ftell(fp) * 50) / file_len; if (progress > prev_progress) { progressbar(50, progress); prev_progress = progress; } } progressbar(50, 50); my_close(fp, filename); printf("\n"); return npos; }
/* orders incoming blocks of data into dedispersed sub-bands */ void dedisperse_data(FILE *input, FILE *output) /*includefile*/ { char message[80]; float *buff[2], *dedisp, realtime, nextbaseline, *offset, *tmpblk; int readnext=0,isamp,bnum,nsamp,i,j,s,c,b,indx,ns[2],soffset,ddidx; int ic,ixnb,ixnc,*ishift,maxshift,nsblk,nsmax,cpb,d,spb,x,nsout,nxb; int *ignore; /* calculate table of shift values given the filterbank and DM */ ishift=dmshift(fch1,foff,nchans,nbands,userdm,refrf,tsamp,frequency_table); maxshift=ishift[nchans-1]; /* set the buffer size based on the maximum shift */ nsblk=256*nchans; nsout=32*nchans; /*nsblk=256*nchans; nsout=32768*nchans;*/ nsmax=maxshift*nifs*nchans; if (nsmax>nsblk) nsblk=nsmax; nxb=nifs*nbands; /* define the buffers and initialize counters */ dedisp =(float *) malloc(nxb*nsout*sizeof(float)); offset =(float *) malloc(nxb*sizeof(float)); tmpblk =(float *) malloc(nsout*sizeof(float)); buff[0]=(float *) malloc(nsblk*sizeof(float)); buff[1]=(float *) malloc(nsblk*sizeof(float)); for (i=0;i<nxb;i++) offset[i]=0.0; d=bnum=isamp=0; ic=nchans*nifs; nextbaseline=realtime=0.0; /* zero any channels that are in the ignored list of channels */ if (file_exists(ignfile)) { ignore=ignored_channels(ignfile,nchans); } else { ignore=(int *) malloc(nchans*sizeof(int)); for (i=0;i<nchans;i++) ignore[i]=0; } /* number of channels per band to dedisperse (cpb) must be an integer */ cpb=nchans/nbands; if ((cpb*nbands) != nchans) error_message("silly sub-band selection!"); /* main loop - keep going until no more data comes in */ while (1) { /* read in the buffer to be processed if not done so already */ if (!readnext) { sprintf(message,"time:%.1fs:DM:%.1fpc/cc",realtime,refdm); update_log(message); if ((ns[bnum]=read_block(input,nbits,buff[bnum],nsblk))<=0) { if (isamp)write_dedisp(dedisp,isamp,nifs,nbands,offset,output); return; } } /* number of samples in this buffer */ nsamp=ns[bnum]/ic; /* flag to signify whether next buffer has been read in (1=yes;0=no) */ readnext=0; /* dedispersing loop over all samples in this buffer */ for (s=0; s<nsamp; s++) { soffset=isamp*nxb; /* loop over the IFs */ for (i=0; i<nifs; i++) { /* number of channels to skip within this IF */ ixnc=i*nchans; ixnb=i*nbands; for (b=0; b<nbands; b++) { /* calculate index of this sample */ ddidx=soffset+ixnb+b; /* clear array element for storing dedispersed subband */ dedisp[ddidx]=0.0; /* loop over the channels in this subband */ for (c=b*cpb;c<(b+1)*cpb;c++) { /* proceed only if selected channel # is not in ignore list */ if (!ignore[c]) { /* calculate index of sample to be added */ indx=(s+ishift[c])*ic+ixnc+c; /* required sample will be in either this buffer or the next */ if (indx<ns[bnum]) { dedisp[ddidx]+=buff[bnum][indx]; } else { if (!readnext) { if ((ns[!bnum]=read_block(input,nbits,buff[!bnum],nsblk))<=0) { if (isamp) { write_dedisp(dedisp,isamp,nifs,nbands,offset,output); } return; } sprintf(message,"time:%.1fs:DM:%.1fpc/cc",realtime,refdm); update_log(message); readnext=1; } dedisp[ddidx]+=buff[!bnum][indx-ns[bnum]]; } } } } /* end of loop over subbands */ } /* end of loop over IFs */ /* update number of samples dedispersed and elapsed time */ isamp++; realtime+=tsamp; if (isamp==nsout) { if (baseline) { for (i=0;i<nifs;i++) { ixnb=i*nbands; for (b=0;b<nbands;b++) { for (j=0;j<nsout;j++) tmpblk[j]=dedisp[j*nxb+ixnb+b]; offset[ixnb+b]=nrselect(nsout/2,nsout,tmpblk-1); } } } write_dedisp(dedisp,nsout,nifs,nbands,offset,output); isamp=0; } } /* end of loop over samples */ /* switch to next buffer */ bnum=!bnum; } /* end of main loop */ }
void wapp2fb(FILE *input, FILE *output) /* includefile */ { FILE *bptr, *fpou, *alfa[2]; int pixel[2]; double pra, pdec; double bw, bandwidth, scale, power, hweight, tsamp_us, crate, lmst; double *lag, *sum, *acf, *window, jan1, days, epoch, ras,des,rahr,dede; float zerolag,*block,smin,smax; int doit,i,j,k,two_nlags,nlags,stat,rec_size,idump,swap_bytes,ifnum,opened; int filesize,headersize,beam,utsecs,iymdf[4],rah,ram,ded,dem; unsigned char *cblock, zuc; unsigned short *sblock, zus; unsigned int zul; char message[80], outfile[80]; void *dump; static float realtime=0.0; #ifdef FFTW fftw_plan fftplan; #endif /* establish whether we need to swap bytes (WAPP is little endian) */ swap_bytes=big_endian(); /* initialise correlator parameters used below */ nlags=nchans; two_nlags=2*nlags; bandwidth=foff*nlags; tsamp_us=tsamp*1.0e6; if (bandwidth<0.0) bandwidth *= -1.0; #ifdef FFTW acf = fftw_malloc(sizeof(double) * two_nlags); lag = fftw_malloc(sizeof(double) * two_nlags); /* set up fftw table and acf array when computing power spectra */ fftplan=fftw_plan_r2r_1d(two_nlags,acf,lag,FFTW_R2HC,FFTW_PATIENT); #endif #ifndef FFTW /* set up acf array when computing power spectra */ acf = (double *) malloc(two_nlags * sizeof(double)); lag = (double *) malloc(two_nlags * sizeof(double)); #endif if (compute_spectra) { /* ranges for scaling spectra */ smin=0.0;smax=3.0; } else { /* ranges for scaling correlation functions */ smin=-0.5;smax=1.0; } /* set up the weights for windowing of ACF to monimize FFT leakage */ if (hanning) { /* Hanning window */ hweight=0.50; } else if (hamming) { /* Hamming window */ hweight=0.54; } else { /* no window (default) */ hweight=1.00; } /* define the smoothing window to be applied base on the above weight */ window = (double *) malloc(nlags * sizeof(double)); for (j=0; j<nlags; j++) window[j]=(hweight+(1.0-hweight)*cos(PI*j/nlags)); /* work out number of IFs to loop over */ if (sumifs && (nifs>1)) { smin*=2.0; smax*=2.0; ifnum=2; } else { sumifs=0; ifnum=nifs; } /* calculate required record size for reading - i.e. number of bytes/dump */ rec_size = nifs*nlags*(nbits/8); dump = malloc(rec_size); /* pointer to the correlator dump */ /* correlator data rate */ crate = 1.0/(tsamp_us-WAPP_DEAD_TIME); /* scale factor to normalize correlation functions */ if (bandwidth < 50.0) bw=50.0; /* correct scaling for narrow-band use */ else bw=bandwidth; scale = crate/bw; if (wapp_level==9) scale/=16.0; /* 9-level sampling */ if (wapp_sum) scale/=2.0; /* summed IFs (search mode) */ scale*=pow(2.0,(double)wapp_lagtrunc); /* needed for truncation modes */ /* now define a number of working arrays to store lags and spectra */ block = (float *) malloc(nlags * sizeof(float)); cblock = (unsigned char *) malloc(nlags * sizeof(unsigned char)); sblock = (unsigned short *) malloc(nlags * sizeof(unsigned short)); /* if the file is ALFA data --- do the demultiplexing to two files */ if (wapp_isalfa) { angle_split(src_raj,&rah,&ram,&ras); rahr=(double)rah+(double)ram/60.0+(double)ras/3600.0; angle_split(src_dej,&ded,&dem,&des); if (ded>0) dede=(double)ded+(double)dem/60.0+(double)des/3600.0; else dede=(double)ded-(double)dem/60.0-(double)des/3600.0; /* calculate local sidereal time in hours */ lmst=slaGmst(tstart)*12.0/4.0/atan(1.0)-4.4502051459439667; if (lmst<0.0) lmst+=24.0; slaDjcal(5,tstart,iymdf,&stat); slaCaldj(iymdf[0],1,1,&jan1,&stat); days=tstart-jan1+1.0; epoch=(double)iymdf[0]+days/365.25; utsecs=86400*(tstart-floor(tstart)); pixel[0]=(wapp_number-1)*2; pixel[1]=pixel[0]+1; puts("opening output files for demultiplexed ALFA data..."); for (i=0; i<2; i++) { if (alfa_raj[pixel[i]] == 0.0) { alfa_position(rahr,dede,lmst,epoch,alfa_ang,0.0,0.0,pixel[i],&pra,&pdec); src_raj=h2hms(pra); src_dej=deg2dms(pdec); } else { src_raj=h2hms(alfa_raj[pixel[i]]); src_dej=deg2dms(alfa_dej[pixel[i]]); } sprintf(outfile,"%s_%.0f_%05d_%04d_%s_%d.fil", project,floor(tstart),utsecs, scan_number,source_name,pixel[i]); alfa[i]=open_file(outfile,"wb"); puts(outfile); filterbank_header(alfa[i]); } beam=0; } if (headerfile) { /* write output ASCII header file */ fpou=open_file("head","w"); fprintf(fpou,"Original WAPP file: %s\n",inpfile); fprintf(fpou,"Sample time (us): %f\n",tsamp_us); fprintf(fpou,"Observation time (s): %f\n",wapp_obstime); fprintf(fpou,"Time stamp (MJD): %18.12f\n",tstart); fprintf(fpou,"Number of samples/record: %d\n",512); fprintf(fpou,"Center freq (MHz): %f\n",fch1+(float)nlags*foff/2.0); fprintf(fpou,"Channel band (kHz): %f\n",bandwidth*1000.0/nlags); fprintf(fpou,"Number of channels/record: %d\n",nlags); fprintf(fpou,"Nifs: %d\n",ifnum); fprintf(fpou,"RA (J2000): %f\n",src_raj); fprintf(fpou,"DEC (J2000): %f\n",src_dej); fprintf(fpou,"Gal l: %.4f\n",srcl); fprintf(fpou,"Gal b: %.4f\n",srcb); fprintf(fpou,"Name: %s\n",source_name); fprintf(fpou,"Lagformat: %d\n",wapp_lagformat); fprintf(fpou,"Sum: %d\n",wapp_sum); fprintf(fpou,"Level: %d\n",wapp_level); fprintf(fpou,"AZ at start: %f\n",az_start); fprintf(fpou,"ZA at start: %f\n",za_start); fprintf(fpou,"AST at start: %f\n",ast0); fprintf(fpou,"LST at start: %f\n",lst0); fprintf(fpou,"Project ID: %s\n",project); fprintf(fpou,"Observers: %s\n",culprits); filesize=sizeof_file(inpfile); fprintf(fpou,"File size (bytes): %d\n",filesize); headersize=wapp_header_size+wapp_incfile_length; fprintf(fpou,"Data size (bytes): %d\n",filesize-headersize); fprintf(fpou,"Number of samples: %d\n",nsamples(inpfile,headersize,nbits,nifs,nchans)); fclose(fpou); } /* initialise various counters and flags */ opened=idump=i=j=0; /* main loop reading data from infile until no more left to read */ while( (stat=read(wapp_file,dump,rec_size)) == rec_size) { /* calculate elapsed time and determine whether we process this record */ realtime += (float) tsamp; if ( (doit=process(realtime,start_time,final_time)) == -1) break; if (doit) { /* set ALFA beam output if necessary */ if (wapp_isalfa) { output=alfa[beam]; /* set output file for this loop */ beam=!(beam); /* flip file for next iteration */ } /* clear zerolag and blocksum arrays */ zerolag=0.0; for (j=0; j<nlags; j++) block[j]=0.0; /* loop over the IFs */ for (i=0; i<ifnum; i++) { if (ifstream[i]=='Y') { if (zerolagdump) { /* only interested in the zero lag term for each IF */ switch (nbits) { case 8: zuc = *(((unsigned char *)dump)+i*nlags); zerolag+=zuc; break; case 16: zus = *(((unsigned short *)dump)+i*nlags); if (swap_bytes) swap_short(&zus); zerolag+=zus; break; case 32: zul = *(((unsigned int *)dump)+i*nlags); if (swap_bytes) swap_int(&zul); zerolag+=zul; break; } /* write out the data checking IF number for summed mode */ if ( (sumifs && (i==1)) || (!sumifs) ) { if (obits==32) { if (swapout) swap_float(&zerolag); fwrite(&zerolag,sizeof(float),1,output); } else { sprintf(message,"cannot write %d bits in zerolag mode",obits); error_message(message); } } } else { /* fill lag array with scaled CFs */ for (j=0; j<nlags; j++) { switch (nbits) { case 8: zuc = *(((unsigned char *)dump)+j+i*nlags); lag[j] = scale * (double) zuc - 1.0; break; case 16: zus = *(((unsigned short *)dump)+j+i*nlags); if (swap_bytes) swap_short(&zus); lag[j] = scale * (double) zus - 1.0; break; case 32: zul = *(((unsigned int *)dump)+j+i*nlags); if (swap_bytes) swap_int(&zul); lag[j] = scale * (double) zul - 1.0; break; } } /* calculate power and correct for finite level quantization */ power = inv_cerf(lag[0]); power = 0.1872721836/power/power; if (i<2) { if (do_vanvleck) { if (wapp_level==3) { /* apply standard 3-level van vleck correction */ vanvleck3lev(lag,nlags); } else if (wapp_level==9) { /* apply 9-level van vleck correction */ vanvleck9lev(lag,nlags); } } } if (compute_spectra) { /* form windowed even ACF in array */ for(j=1; j<nlags; j++) { acf[j]=window[j]*lag[j]*power; acf[two_nlags-j]=acf[j]; } acf[nlags]=0.0; acf[0]=lag[0]*power; /* FFT the ACF (which is real and even) -> real and even FFT */ #ifdef FFTW fftw_execute(fftplan); #endif #ifndef FFTW rfft(two_nlags,acf,lag); #endif /* if the band needs to be flipped --- do it here */ if (wapp_flip) { /* use acf as temporary array */ for (j=0;j<nlags;j++) acf[j]=lag[j]; k=nlags-1; for (j=0;j<nlags;j++) { lag[k]=acf[j]; k--; } } /* add lags to block array */ for (j=0; j<nlags; j++) block[j]+=lag[j]; } else { /* just copy correlation functions into block */ for (j=0; j<nlags; j++) block[j]=lag[j]; } /* write out data block checking IF number for summed mode */ if ( (sumifs && (i==1)) || (!sumifs) ) { if (obits==32) { if (swapout) for (j=0; j<nlags; j++) swap_float(&block[j]); fwrite(block,sizeof(float),nlags,output); } else if (obits==16) { float2short(block,nlags,smin,smax,sblock); if (swapout) for (j=0; j<nlags; j++) swap_short(&sblock[j]); fwrite(sblock,sizeof(unsigned short),nlags,output); } else if (obits==8) { float2char(block,nlags,smin,smax,cblock); fwrite(cblock,sizeof(unsigned char),nlags,output); } else if (obits==4) { float2four(block,nlags,smin,smax,cblock); fwrite(cblock,sizeof(unsigned char),nlags/2,output); } else { sprintf(message,"cannot write %d bits in wapp2fb",obits); error_message(message); } } } /* end of zerolagdump if */ if (!sumifs) { /* reset block and zerolag if not summing */ zerolag=0.0; for (j=0; j<nlags; j++) block[j]=0.0; } } /* end of IFstream if */ } /* end of loop over IFs */ } /* end of processing if */ /* increment dump counter and update logfile every 512 dumps */ idump++; if (idump%512 == 0) { if (!opened) { /* open up logfile */ open_log("filterbank.monitor"); opened=1; } sprintf(message,"time:%.1fs",realtime); update_log(message); } } /* end of main read loop*/ /* job done - free up remaining arrays */ free(dump);free(block);free(sblock);free(cblock);free(window); #ifdef FFTW fftw_destroy_plan(fftplan); fftw_free(acf); fftw_free(lag); #endif #ifndef FFTW free(acf); free(lag); #endif }
/* orders incoming blocks of data into dedispersed sub-bands */ void dedisperse_data(FILE *input, FILE *output) /*includefile*/ { char message[80]; float *buff[2], *dedisp, realtime, nextbaseline, *offset, *tmpblk; int readnext=0,isamp,bnum,nsamp,i,j,s,c,b,indx,ns[2],soffset,ddidx; int ic,ixnb,ixnc,*ishift,maxshift,nsblk,nsmax,cpb,d,spb,x,nsout,nxb; int *ignore; unsigned long long totalsamp; totalsamp = 0; /* calculate table of shift values given the filterbank and DM */ ishift=dmshift(fch1,foff,nchans,nbands,userdm,refrf,tsamp,frequency_table); maxshift=ishift[nchans-1]; /* set the buffer size based on the maximum shift */ nsblk=256*nchans; nsout=32*nchans; /*nsblk=256*nchans; nsout=32768*nchans;*/ nsmax=maxshift*nifs*nchans; if (nsmax>nsblk) nsblk=nsmax; nxb=nifs*nbands; /* define the buffers and initialize counters */ dedisp =(float *) malloc(nxb*nsout*sizeof(float)); offset =(float *) malloc(nxb*sizeof(float)); tmpblk =(float *) malloc(nsout*sizeof(float)); buff[0]=(float *) malloc(nsblk*sizeof(float)); buff[1]=(float *) malloc(nsblk*sizeof(float)); for (i=0;i<nxb;i++) offset[i]=0.0; d=bnum=isamp=0; ic=nchans*nifs; nextbaseline=realtime=0.0; /* zero any channels that are in the ignored list of channels */ if (file_exists(ignfile)) { ignore=ignored_channels(ignfile,nchans); } else { ignore=(int *) malloc(nchans*sizeof(int)); for (i=0;i<nchans;i++) ignore[i]=0; } /* number of channels per band to dedisperse (cpb) must be an integer */ cpb=nchans/nbands; if ((cpb*nbands) != nchans) error_message("silly sub-band selection!"); /* main loop - keep going until no more data comes in */ while (1) { /* read in the buffer to be processed if not done so already */ if (!readnext) { sprintf(message,"time:%.1fs:DM:%.1fpc/cc",realtime,refdm); update_log(message); if ((ns[bnum] = read_block (input, nbits, buff[bnum], nsblk)) <= 0){ /* There were no more samples to read */ if (isamp)write_dedisp(dedisp,isamp,nifs,nbands,offset,output); return; } else { /* We managed to read some samples! * There may be some things we want to do to the data as we read it in * These are done here if they need to be done. */ if(ns[bnum]%nchans){ /* If we get here then ns[bnum]/nchans is not integer! * This is really bad, as we assume that we read in an * integer number of samples. */ fprintf(stderr,"ERROR: Could not read an integer number of samples (nread/nchans is not integer).\nPerhaps the file is incomplete or the stream was terminated.\nUnfortunately dedispersion cannot continue.\n"); exit(2); } /* Do we want to clip the input channel data * Note that we must do this BEFORE zerodming */ if(doInputClip){ inputClip(buff[bnum],ns[bnum]/nchans,inputClipLow,inputClipHigh,doInputClip); /* It is important that ns[bnum]/nchans is an integer! */ } /* Do we want to do the 'zero dm' subtraction? */ if(doSubZero){ subzero(buff[bnum],ns[bnum]/nchans); /* It is important that ns[bnum]/nchans is an integer! */ } if(doBaselineFile){ reverseBaselineNormalise(buff[bnum],totalsamp,ns[bnum]/nchans,nchans); } } } /* number of samples in this buffer */ nsamp=ns[bnum]/ic; /* flag to signify whether next buffer has been read in (1=yes;0=no) */ readnext=0; /* dedispersing loop over all samples in this buffer */ for (s=0; s<nsamp; s++) { soffset=isamp*nxb; /* loop over the IFs */ for (i=0; i<nifs; i++) { /* number of channels to skip within this IF */ ixnc=i*nchans; ixnb=i*nbands; for (b=0; b<nbands; b++) { /* calculate index of this sample */ ddidx=soffset+ixnb+b; /* clear array element for storing dedispersed subband */ dedisp[ddidx]=0.0; /* loop over the channels in this subband */ for (c=b*cpb;c<(b+1)*cpb;c++) { /* proceed only if selected channel # is not in ignore list */ if (!ignore[c]) { /* calculate index of sample to be added */ indx=(s+ishift[c])*ic+ixnc+c; /* required sample will be in either this buffer or the next */ if (indx<ns[bnum]) { dedisp[ddidx]+=buff[bnum][indx]; } else { if (!readnext) { if ((ns[!bnum]=read_block(input,nbits,buff[!bnum],nsblk))<=0) { /* There are no more samples to read, nread <= 0 */ if (isamp) { write_dedisp(dedisp,isamp,nifs,nbands,offset,output); } return; } else { /* We read some samples, as nread > 0. * There may be some things we want to do to the data as we read it in * These are done here if they need to be done. */ if(ns[!bnum]%nchans){ /* If we get here then ns[bnum]/nchans is not integer! * This is really bad, as we assume that we read in an * integer number of samples. */ fprintf(stderr,"ERROR: Could not read an integer number of samples (nread/nchans is not integer).\nPerhaps the file is incomplete or the stream was terminated.\nUnfortunately dedispersion cannot continue.\n"); exit(2); } /* Do we want to clip the input channel data */ if(doInputClip){ inputClip(buff[!bnum],ns[!bnum]/nchans,inputClipLow,inputClipHigh,doInputClip); /* It is important that ns[!bnum]/nchans is an integer! */ } /* Do we want to do the 'zero dm' subtraction? */ if(doSubZero){ subzero(buff[!bnum],ns[!bnum]/nchans); /* It is important that ns[!bnum]/nchans is an integer! */ } if(doBaselineFile){ reverseBaselineNormalise(buff[!bnum],totalsamp,ns[!bnum]/nchans,nchans); } } sprintf(message,"time:%.1fs:DM:%.1fpc/cc",realtime,refdm); update_log(message); readnext=1; } dedisp[ddidx]+=buff[!bnum][indx-ns[bnum]]; } } } } /* end of loop over subbands */ } /* end of loop over IFs */ /* update number of samples dedispersed and elapsed time */ isamp++; realtime+=tsamp; totalsamp++; if (isamp==nsout) { if (baseline) { for (i=0;i<nifs;i++) { ixnb=i*nbands; for (b=0;b<nbands;b++) { for (j=0;j<nsout;j++) tmpblk[j]=dedisp[j*nxb+ixnb+b]; offset[ixnb+b]=nrselect(nsout/2,nsout,tmpblk-1); //fprintf(stderr,"%d %f\n",ixnb+b,offset[ixnb+b]); } } } write_dedisp(dedisp,nsout,nifs,nbands,offset,output); isamp=0; } } /* end of loop over samples */ /* switch to next buffer */ bnum=!bnum; } /* end of main loop */ }