int jiveL_thread_time(lua_State *L) { lua_pushinteger(L, (int)(clock() * 1000 / CLOCKS_PER_SEC)); return 1; }
void osc_gen(int argc, char *argv[]) { //This function serves as an Osccilator bank (an arrary of oscillators) for additive synthesis //It produces more natural sounding waves confined in the spectrum of the availabke ranges of the sampling rate at or above the Nyquist limit //Structurally, this program is very similar to sig_gen, except that we will only be calling upon sine_wave_node and implement additive synthesis //to achieve the other waveforms. If osc_gen_num_oscs == 1 (meaning only 1 oscillator) a normal sine wave will be produced. //This function makes use of wave_generator.c/.h objects and functions /***************USAGE*************** oscgen outfile dur srate num_chans, amp, freq, wavetype, num_oscs **********************************/ if(argc < OSC_GEN_NARGS) { fprintf(stderr, "insufficient arguments.\n" "usage: oscgen outfile dur srate num_chans amp freq wavetype num_oscs\n" "where wavetype =:\n" " 0 = square\n" " 1 = triangle\n" " 2 = sawtooth up\n" " 3 = sawtooth down\n" " 4 = pulse\n" "dur = duration of outfile (seconds)\n" "srate = required sample rate of outfile\n" "amp = amplitude value or breakpoint file (0 < amp <= 1.0)\n" "freq = frequency value (freq > 0) or breakpoint file.\n" "num_oscs = number of oscillators (where 1 is normal sine wave)\n" ); exit(1); } /********* initialize all dynamic resources to default states **********/ PSF_PROPS outprops; int ofd = -1; int error = 0; PSF_CHPEAK* peaks = NULL; psf_format outformat = PSF_FMT_UNKNOWN; long nframes = NFRAMES; float* outframe = NULL; double amp,freq,dur; long outframes,nbufs = 0,num_oscs,i; //num_oscs holds number of oscillators for additive synthesis long remainder; int samptype = PSF_SAMP_16; OSCIL** oscs = NULL; //an array of oscil pointers (because additive synthesis requires more than one oscillators) double* oscamps = NULL; //for oscillator bank amplitudes and frequencies double* oscfreqs = NULL; double phase = 0.0; double ampfac,freqfac,ampadjust; //Because we cannot know the number of oscillators before hand, we need to calculate it cumulatively //Recall that adding sine waves amplitude is as simple as numerically adding the amplitude values. So 1 + 3 + 5 + 7 will yield an amp //value of 16. However, we want amp to be between -1 and 1 --> therefore total amp is 1/(1^2) + 1/(3^2) + 1/(5^2) + 1/(7^2) = 1 + 1/9 + 1/25 + 1/49 = 1.172 //General Rule : totalamp = Sum (from n = 0 to N) 1/(2n-1)^2 where N = number of oscillators FILE* fpfreq = NULL; BRKSTREAM *freqstream = NULL, *ampstream = NULL; unsigned long brkfreqSize = 0; double minval = 0.0,maxval= 0.0; FILE* fpamp = NULL; unsigned long brkampSize = 0; double amp_minval = 0.0,amp_maxval= 0.0; clock_t starttime, endtime; int wavetype; oscs = NULL; /********** error checking on wave type **********/ wavetype = atoi(argv[OSC_GEN_WAVETYPE]); if(wavetype < OSC_GEN_SQUARE || wavetype > OSC_GEN_PULSE) { fprintf(stderr, "Error: wavetype not defined\n"); goto exit; } /********** error checking on number of oscillators **********/ num_oscs = atoi(argv[OSC_GEN_NUM_OSCS]); if(num_oscs <= 0) { fprintf(stderr, "Error: number of oscillators must be positive\n"); goto exit; } /********** define outfile format (with embedded error checking) **********/ outprops.srate = atoi(argv[OSC_GEN_SRATE]); if(outprops.srate <= 0) { fprintf(stderr, "Error: srate must be positive\n"); goto exit; } outprops.chans = atoi(argv[OSC_GEN_NUM_CHANS]); if(outprops.chans <= 0) { fprintf(stderr, "Error: number of channels must be positive\n"); goto exit; } outprops.samptype = (psf_stype) samptype; outprops.chformat = STDWAVE; dur = atof(argv[OSC_GEN_DUR]); if(dur <= 0.0) { fprintf(stderr, "Error: duration must be positive (>=0)\n"); goto exit; } outframes = (unsigned long) (dur * outprops.srate + 0.5); nbufs = outframes / nframes; remainder = outframes - nbufs * nframes; if(remainder > 0) nbufs++; /********** open breakpoint files, or set constants if no breakpoint file is defined **********/ /***** amp (amplitude) breakpoints file *****/ fpamp = fopen(argv[OSC_GEN_AMP], "r"); //try opening specified argument if(fpamp == NULL) { //meaning that either argument OSC_GEN_AMP is not a breakpoint file or error opening amp = atof(argv[OSC_GEN_AMP]); if(amp <= 0.0 || amp > 1) { fprintf(stderr, "Error: amplitude must be between 0 and 1 (0 <= amp <= 1)\n"); goto exit; } } else { //meaning that argument OSC_GEN_AMP is indeed a breakpoint file ampstream = bps_newstream(fpamp,outprops.srate,&brkampSize); if(ampstream == NULL) { fprintf(stderr, "Error reading amplitude breakpoint file: %s\n", argv[OSC_GEN_AMP]); goto exit; } if(bps_getminmax(ampstream, &minval, &maxval)) { //meaning we called upon said function that will put into minval and maxval appropriate values //if said function returns 1 --> we have error fprintf(stderr, "Error reading range breakpoint file: %s\n", argv[OSC_GEN_AMP]); goto exit; } if(minval < 0.0 || minval > 1.0 || maxval < 0.0 || maxval > 1.0) { fprintf(stderr, "Error: amplitude values out of range in breakpoint file\n"); goto exit; } } /***** freq (frequency) breakpoints file *****/ fpfreq = fopen(argv[OSC_GEN_FREQ], "r"); if(fpfreq == NULL) { //meaning that either argument OSC_GEN_FREQ is not a breakpoint file or error opening freq = atof(argv[OSC_GEN_FREQ]); if(freq <= 0.0) { fprintf(stderr, "Error: frequency must be positive\n"); goto exit; } } else { //meaning that argument OSC_GEN_FREQ is indeed a breakpoint file freqstream = bps_newstream(fpfreq, outprops.srate, &brkfreqSize); if(freqstream == NULL) { fprintf(stderr, "Error reading frequncy from breakpoint file: %s\n", argv[OSC_GEN_FREQ]); goto exit; } if(bps_getminmax(freqstream, &minval, &maxval)) { fprintf(stderr, "Error reading range from breakpoint file: %s\n", argv[OSC_GEN_FREQ]); goto exit; } if(minval <= 0.0) { fprintf(stderr, "Error in breakpoing file; Frequency values must be positive\n"); goto exit; } } /********** Initialize portsf **********/ if(psf_init()) { fprintf(stderr, "Error: Unable to initialize portsf\n"); goto exit; } /********** Sample Frame Buffer Memory Aloocation **********/ outframe = (float*)malloc(nframes * outprops.chans * sizeof(float)); if(outframe == NULL) { fprintf(stderr, "Error: No memory for outframe buffer\n"); goto exit; } /********** Check for correct output extension **********/ outformat = psf_getFormatExt(argv[OSC_GEN_OUTFILE]); if(outformat == PSF_FMT_UNKNOWN) { fprintf(stderr, "Error: invalid extension\n" "Possible extensions:\t *.wav\t *.aiff\t *.aif\t *.afc\t *.aifc\n"); goto exit; } //reach here meaning outformat is viable extension outprops.format = outformat; /********** create oscillator amp and oscillator freq arrays **********/ oscamps = (double*)malloc(num_oscs * sizeof(double)); oscfreqs = (double*)malloc(num_oscs * sizeof(double)); if(!oscamps || !oscfreqs) { fprintf(stderr, "Error: Failed memory allocation for oscillator amp/freq arrays\n"); goto exit; } /********** create amp/freq data for requested waveshape, normalized to 1 **********/ ampfac = 1.0; freqfac = 1.0; ampadjust = 0.0; switch(wavetype) { case(OSC_GEN_SQUARE): for(i=0; i<num_oscs; i++) { oscamps[i] = ampfac; oscfreqs[i] = freqfac; freqfac += 2.0; ampadjust += ampfac; ampfac = 1.0 / freqfac; } //normalize for(i=0; i<num_oscs; i++) oscamps[i] /= ampadjust; break; case(OSC_GEN_TRIANGLE): for(i=0; i<num_oscs; i++) { oscamps[i] = ampfac; oscfreqs[i] = freqfac; freqfac += 2.0; ampadjust += ampfac; ampfac = 1.0 / (freqfac * freqfac); } //normalize for(i=0; i<num_oscs; i++) oscamps[i] /= ampadjust; phase = 0.25; break; case(OSC_GEN_SAW_UP): case(OSC_GEN_SAW_DOWN): for(i=0; i<num_oscs; i++) { oscamps[i] = ampfac; oscfreqs[i] = freqfac; freqfac += 1.0; ampadjust += ampfac; ampfac = 1.0 / freqfac; } if(wavetype == OSC_GEN_SAW_UP) ampadjust = -ampadjust; //normalize for(i=0; i<num_oscs; i++) oscamps[i] /= ampadjust; break; case(OSC_GEN_PULSE): freqfac = 1.0; ampfac = 1.0 / num_oscs; ampadjust = 0.0; for(i=0; i<num_oscs; i++) { oscamps[i] = ampfac; oscfreqs[i] = freqfac; freqfac += 1.0; } break; } /********** Create Oscillator Bank **********/ oscs = (OSCIL**)malloc(num_oscs * sizeof(OSCIL*)); if(!oscs) { fprintf(stderr, "Error: Failed memory allocation on creation of oscillator bank\n"); goto exit; } for(i=0; i< num_oscs; i++) { oscs[i] = new_oscil_with_phase(outprops.srate, phase); if(!oscs[i]) { fprintf(stderr, "Error: Failed memory allocation on creation of oscillator object\n"); goto exit; } } /********** Initialize Peak nfo **********/ peaks = (PSF_CHPEAK*)malloc(outprops.chans * sizeof(PSF_CHPEAK)); if(peaks == NULL) { fprintf(stderr, "Error: No memory for peaks\n"); goto exit; } /********** Create and Handle outfile **********/ ofd = psf_sndCreate(argv[OSC_GEN_OUTFILE],&outprops, 0, 0, PSF_CREATE_RDWR); //refer to sf2float for documentation if(ofd < 0) { fprintf(stderr, "Error: Unable to create outfile\n"); goto exit; } /********** Audio Processing **********/ printf("Reached here\t\t numbufs: %lu; numframes: %lu\n", nbufs, nframes); starttime = clock(); for(i=0; i<nbufs; i++) { long j,k,l; double val; if(i == nbufs -1) nframes = remainder; for(j=0; j< nframes; j++) { if(freqstream) freq = bps_tick(freqstream); if(ampstream) amp = bps_tick(freqstream); val = 0.0; for(l=0; l<num_oscs; l++) { val += oscamps[l] * sine_wave_node(oscs[l], freq * oscfreqs[l]); } for(k=0; k<outprops.chans; k++) { outframe[j*outprops.chans +k] = (float)(val * amp); } } //end j for-loop if(psf_sndWriteFloatFrames(ofd, outframe, nframes) != nframes) { fprintf(stderr, "Error writing to outfile"); break; } }//end i for-loop endtime = clock(); exit: fprintf(stdout, "Task Finished \nElapsed Time: %f seconds\n", (endtime - starttime)/(double)CLOCKS_PER_SEC); /***** Report PEAK values to user *****/ if(psf_sndReadPeaks(ofd,peaks,NULL) > 0){ long i; double peaktime; printf("PEAK information:\n"); for(i=0;i < outprops.chans;i++){ peaktime = (double) peaks[i].pos / (double) outprops.srate; printf("CH %d:\t%.4f at %.4f secs\n", (int)(i+1), peaks[i].val, peaktime); } } if(ofd >= 0) psf_sndClose(ofd); if(outframe) free(outframe); if(peaks) free(peaks); if(oscs){ for(i=0;i < num_oscs;i++){ free(oscs[i]); } free(oscs); } if(oscamps) free(oscamps); if(oscfreqs) free(oscfreqs); psf_finish(); exit(1); }
void okim6295_device::device_clock_changed() { int divisor = m_pin7_state ? 132 : 165; m_stream->set_sample_rate(clock() / divisor); }
void ym2203_device::device_clock_changed() { calculate_rates(); ym2203_clock_changed(m_chip, clock(), clock() / 72); }
void rectangle::begin() { m_start = clock(); }
int main(int ac, char *argv[]) { if (ac<2) { printf("\n This demo will show how a Sparse Distributed Memory\n"); printf(" works. The implementation uses the advanced implementation \n"); printf(" with different distributions.\n"); printf(" The distributions are relativ and absolute, with linear\n"); printf(" and gaussian functions (argument's are (1) linear,\n"); printf(" (2) gaussian and (3) with NAND ditance masurement. After the\n"); printf(" initialization phase rarely used entries are deleted.\n"); printf("\n syntax:"); printf("\n %s <df> <a/r> <al> <dl> <mems> <inits> <tests> <thrs> <rem>", argv[0]); printf("\n"); printf("\n <df> specifies the distribution function:"); printf("\n 0=linear with Hamming distance,"); printf("\n 1=gaussian with Hamming distance,"); printf("\n 2=with NAND distance masurement."); printf("\n <a/r> absolute(0) or relativ(1) distance masurement."); printf("\n <al> stands for the adress length."); printf("\n <dl> stands for the data length."); printf("\n <mems> specifies the number of address data vector tupels."); printf("\n <inits> indicates the number of initialization vectors"); printf("\n <tests> indicates the number of vectors stored in the memory"); printf("\n <thres> specifies the threshold value indicates the percentage"); printf("\n that the influence goes down with each distance step."); printf("\n <rem> indicates the minimum influence the initialization phase"); printf("\n must have had on each memory vector, so it doesn't gets deleted.\n"); printf("\n try for instance '%s 0 0 40 50 5000 500 6000 0.085 0.0',", argv[0]); printf("\n or try '%s 1 0 40 50 2000 400 2400 0.075 0.0',", argv[0]); printf("\n or try '%s 1 1 40 50 2000 500 2400 0.075 0.0',", argv[0]); printf("\n or try '%s 2 1 40 50 2000 500 2400 0.07 0.0',", argv[0]); printf("\n or try '%s 2 0 40 50 2000 500 2400 0.08 0.0'.", argv[0]); printf("\n\n"); exit(0); } vei_t ADDR_LEN=atoi(argv[3]); vei_t DATA_LEN=atoi(argv[4]); vei_t MEM_SIZE=atoi(argv[5]); vei_t INIT_SIZE=atoi(argv[6]); vei_t TEST_SIZE=atoi(argv[7]); oas_t THRS=atof(argv[8]); oas_t REM=atof(argv[9]); ve_t AbsRel=atoi(argv[2]); ve_t fct=atoi(argv[1]); SDMAfct sdma(MEM_SIZE, ADDR_LEN, DATA_LEN); sdma.create(MEM_SIZE, ADDR_LEN, DATA_LEN, THRS); BinVector v1, v2, b1, b2; KVector hd(MEM_SIZE); // keep all values in the vector vei_t d=0; v1.create(ADDR_LEN); v2.create(ADDR_LEN); b1.create(DATA_LEN); b2.create(DATA_LEN); for (vei_t i=0;i<ADDR_LEN;i++) { v1.set_comp(0,i); v2.set_comp(0,i); } for (vei_t i=0;i<DATA_LEN;i++) { b1.set_comp(0,i); b2.set_comp(0,i); } v1.set_comp(1,2); v1.set_comp(1,11); v1.set_comp(1,12); v1.tgl_comp(13); v1.tgl_comp(23); v1.tgl_comp(27); b1.set_comp(1,2); b1.set_comp(1,12); b1.set_comp(1,22); b1.set_comp(1,17); printf(" Creating %i random vectors as the address space.\n\r", MEM_SIZE); sdma.random_init(); printf(" Adding %i (random) vectors i for initialization tempsum = new BVector<oas_t>;n random places.\n\r", INIT_SIZE); int tm; tm = clock(); for (vei_t k=0; k<INIT_SIZE; k++) { for (vei_t i=0;i<ADDR_LEN;i++) v2.set_comp(floor(2.0*rand()/(RAND_MAX+1.0)),i); switch (fct) { case 0: d = sdma.store(v2, b2, AbsRel); break; case 1: d = sdma.store_gauss(v2, b2, AbsRel, DENS_INIT); break; case 2: d = sdma.store_nand(v2, b2, AbsRel); break; } if (k<10) { printf(" %i: ",d); for (vei_t i=0;i<v2.get_dim();i++) printf("%i",v2.get_comp(i)); printf(" "); printv(&b2); } else printf("."); } tm = clock() - tm; printf("time during calculation: %i", tm); printf("\n\r"); printf("remove all empty addresses, address space is now %i entries large.", sdma.remove(REM)); printf("\n\r"); printf(" Storing v1's data vector, which is:\n\r"); printv(&b1); //sdma.store(v1, b1, AbsRel); switch (fct) { case 0: sdma.store(v1, b1, AbsRel); d = sdma.store(v1, b1, AbsRel); break; case 1: sdma.store_gauss(v1, b1, AbsRel, DENS_INIT); d = sdma.store_gauss(v1, b1, AbsRel, DENS); break; case 2: sdma.store_nand(v1, b1, AbsRel); d = sdma.store_nand(v1, b1, AbsRel); break; } printf(" in %i locations on address:\n\r",d); printv(&v1); printf(" Adding %i other (random) vectors i tempsum = new BVector<oas_t>;n random places.\n\r", TEST_SIZE); tm = clock(); for (vei_t k=0; k<TEST_SIZE; k++) { for (vei_t i=0;i<ADDR_LEN;i++) v2.set_comp(floor(2.0*rand()/(RAND_MAX+1.0)),i); for (vei_t i=0;i<DATA_LEN;i++) b2.set_comp(floor(2.0*rand()/(RAND_MAX+1.0)),i); switch (fct) { case 0: d = sdma.store(v2, b2, AbsRel); break; case 1: d = sdma.store_gauss(v2, b2, AbsRel, DENS); break; case 2: d = sdma.store_nand(v2, b2, AbsRel); break; } if (k<10) { printf(" %i: ",d); for (vei_t i=0;i<v2.get_dim();i++) printf("%i",v2.get_comp(i)); printf(" "); printv(&b2); } else printf("."); } tm = clock() - tm; printf("time during calculation: %i", tm); printf("\n\r"); printf(" Adding the winner's counters from retrieval of address.\n\r"); BVector<s_16b> tsum2(b1.get_dim()); BVector<oas_t> tsum3(b1.get_dim()); BinVector sum; sum.create(DATA_LEN); switch (fct) { case 0: d = sdma.retrieve(v1,sum,tsum3,AbsRel); break; case 1: d = sdma.retrieve_gauss(v1,sum,tsum3,AbsRel,DENS); break; case 2: d = sdma.retrieve_nand(v1,sum,tsum3,AbsRel); break; } //sdm.retrieve(v1, tsum2, c); //printf("Which sums up to:\n\r"); //printv2(&tsum2); printf("\n\r"); printf("Which sums up to:\n\r"); printv3(&tsum3); printf("\n\r"); printf("And results in:\n\r"); printv(&sum); printf("Which should match:\n\r"); printv(&b1); printf("\n\rDone.\n\r"); return 0; }
//////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { int num_clusters; // For profiling clock_t seed_start, seed_end, seed_total = 0; clock_t regroup_start, regroup_end, regroup_total = 0; int regroup_iterations = 0; clock_t params_start, params_end, params_total = 0; int params_iterations = 0; clock_t constants_start, constants_end, constants_total = 0; int constants_iterations = 0; clock_t total_timer = clock(); double total_time = 0; clock_t io_timer; double io_time = 0; clock_t cpu_timer; double cpu_time = 0; io_timer = clock(); // Validate the command-line arguments, parse # of clusters, etc if(validateArguments(argc,argv,&num_clusters)) { return 1; //Bard args } int num_dimensions; int num_events; // Read FCS data PRINT("Parsing input file..."); // This stores the data in a 1-D array with consecutive values being the dimensions from a single event // (num_events by num_dimensions matrix) float* fcs_data_by_event = readData(argv[2],&num_dimensions,&num_events); if(!fcs_data_by_event) { printf("Error parsing input file. This could be due to an empty file "); printf("or an inconsistent number of dimensions. Aborting.\n"); return 1; } // Transpose the event data (allows coalesced access pattern in E-step kernel) // This has consecutive values being from the same dimension of the data // (num_dimensions by num_events matrix) float* fcs_data_by_dimension = (float*) malloc(sizeof(float)*num_events*num_dimensions); for(int e=0; e<num_events; e++) { for(int d=0; d<num_dimensions; d++) { fcs_data_by_dimension[d*num_events+e] = fcs_data_by_event[e*num_dimensions+d]; } } io_time += (double)(clock() - io_timer); PRINT("Number of events: %d\n",num_events); PRINT("Number of dimensions: %d\n",num_dimensions); PRINT("Number of target clusters: %d\n\n",num_clusters); cpu_timer = clock(); // Setup the cluster data structures on host clusters_t clusters; clusters.N = (float*) malloc(sizeof(float)*num_clusters); clusters.pi = (float*) malloc(sizeof(float)*num_clusters); clusters.constant = (float*) malloc(sizeof(float)*num_clusters); clusters.avgvar = (float*) malloc(sizeof(float)*num_clusters); clusters.means = (float*) malloc(sizeof(float)*num_dimensions*num_clusters); clusters.R = (float*) malloc(sizeof(float)*num_dimensions*num_dimensions*num_clusters); clusters.Rinv = (float*) malloc(sizeof(float)*num_dimensions*num_dimensions*num_clusters); clusters.memberships = (float*) malloc(sizeof(float)*num_events*num_clusters); if(!clusters.means || !clusters.R || !clusters.Rinv || !clusters.memberships) { printf("ERROR: Could not allocate memory for clusters.\n"); return 1; } DEBUG("Finished allocating memory on host for clusters.\n"); float rissanen; //////////////// Initialization done, starting kernels //////////////// DEBUG("Invoking seed_clusters kernel.\n"); fflush(stdout); // seed_clusters sets initial pi values, // finds the means / covariances and copies it to all the clusters // TODO: Does it make any sense to use multiple blocks for this? seed_start = clock(); seed_clusters(fcs_data_by_event, &clusters, num_dimensions, num_clusters, num_events); DEBUG("Invoking constants kernel.\n"); // Computes the R matrix inverses, and the gaussian constant //constants_kernel<<<num_clusters, num_threads>>>(d_clusters,num_clusters,num_dimensions); constants(&clusters,num_clusters,num_dimensions); constants_iterations++; seed_end = clock(); seed_total = seed_end - seed_start; // Calculate an epsilon value //int ndata_points = num_events*num_dimensions; float epsilon = (1+num_dimensions+0.5*(num_dimensions+1)*num_dimensions)*log((float)num_events*num_dimensions)*0.01; float likelihood, old_likelihood; int iters; epsilon = 1e-6; PRINT("Gaussian.cu: epsilon = %f\n",epsilon); /*************** EM ALGORITHM *****************************/ // do initial regrouping // Regrouping means calculate a cluster membership probability // for each event and each cluster. Each event is independent, // so the events are distributed to different blocks // (and hence different multiprocessors) DEBUG("Invoking regroup (E-step) kernel with %d blocks.\n",NUM_BLOCKS); regroup_start = clock(); estep1(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events,&likelihood); estep2(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events,&likelihood); //estep2b(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events,&likelihood); regroup_end = clock(); regroup_total += regroup_end - regroup_start; regroup_iterations++; DEBUG("Regroup Kernel Iteration Time: %f\n\n",((double)(regroup_end-regroup_start))/CLOCKS_PER_SEC); DEBUG("Likelihood: %e\n",likelihood); float change = epsilon*2; PRINT("Performing EM algorithm on %d clusters.\n",num_clusters); iters = 0; // This is the iterative loop for the EM algorithm. // It re-estimates parameters, re-computes constants, and then regroups the events // These steps keep repeating until the change in likelihood is less than some epsilon while(iters < MIN_ITERS || (fabs(change) > epsilon && iters < MAX_ITERS)) { old_likelihood = likelihood; DEBUG("Invoking reestimate_parameters (M-step) kernel.\n"); params_start = clock(); // This kernel computes a new N, pi isn't updated until compute_constants though mstep_n(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events); mstep_mean(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events); mstep_covar(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events); params_end = clock(); params_total += params_end - params_start; params_iterations++; DEBUG("Model M-Step Iteration Time: %f\n\n",((double)(params_end-params_start))/CLOCKS_PER_SEC); //return 0; // RETURN FOR FASTER PROFILING DEBUG("Invoking constants kernel.\n"); // Inverts the R matrices, computes the constant, normalizes cluster probabilities constants_start = clock(); constants(&clusters,num_clusters,num_dimensions); constants_end = clock(); constants_total += constants_end - constants_start; constants_iterations++; DEBUG("Constants Kernel Iteration Time: %f\n\n",((double)(constants_end-constants_start))/CLOCKS_PER_SEC); DEBUG("Invoking regroup (E-step) kernel with %d blocks.\n",NUM_BLOCKS); regroup_start = clock(); // Compute new cluster membership probabilities for all the events estep1(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events,&likelihood); estep2(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events,&likelihood); //estep2b(fcs_data_by_dimension,&clusters,num_dimensions,num_clusters,num_events,&likelihood); regroup_end = clock(); regroup_total += regroup_end - regroup_start; regroup_iterations++; DEBUG("E-step Iteration Time: %f\n\n",((double)(regroup_end-regroup_start))/CLOCKS_PER_SEC); change = likelihood - old_likelihood; DEBUG("likelihood = %f\n",likelihood); DEBUG("Change in likelihood: %f\n",change); iters++; } // Calculate Rissanen Score rissanen = -likelihood + 0.5*(num_clusters*(1+num_dimensions+0.5*(num_dimensions+1)*num_dimensions)-1)*logf((float)num_events*num_dimensions); PRINT("\nFinal rissanen Score was: %f, with %d clusters.\n",rissanen,num_clusters); char* result_suffix = ".results"; char* summary_suffix = ".summary"; int filenamesize1 = strlen(argv[3]) + strlen(result_suffix) + 1; int filenamesize2 = strlen(argv[3]) + strlen(summary_suffix) + 1; char* result_filename = (char*) malloc(filenamesize1); char* summary_filename = (char*) malloc(filenamesize2); strcpy(result_filename,argv[3]); strcpy(summary_filename,argv[3]); strcat(result_filename,result_suffix); strcat(summary_filename,summary_suffix); PRINT("Summary filename: %s\n",summary_filename); PRINT("Results filename: %s\n",result_filename); cpu_time += (double)(clock() - cpu_timer); io_timer = clock(); // Open up the output file for cluster summary FILE* outf = fopen(summary_filename,"w"); if(!outf) { printf("ERROR: Unable to open file '%s' for writing.\n",argv[3]); } // Print the clusters with the lowest rissanen score to the console and output file for(int c=0; c<num_clusters; c++) { //if(saved_clusters.N[c] == 0.0) { // continue; //} if(ENABLE_PRINT) { // Output the final cluster stats to the console PRINT("Cluster #%d\n",c); printCluster(clusters,c,num_dimensions); PRINT("\n\n"); } if(ENABLE_OUTPUT) { // Output the final cluster stats to the output file fprintf(outf,"Cluster #%d\n",c); writeCluster(outf,clusters,c,num_dimensions); fprintf(outf,"\n\n"); } } // Print profiling information printf("Program Component\tTotal\tIters\tTime Per Iteration\n"); printf(" Seed Kernel:\t%7.4f\t%d\t%7.4f\n",seed_total/(double)CLOCKS_PER_SEC,1, (double) seed_total / (double) CLOCKS_PER_SEC); printf(" E-step Kernel:\t%7.4f\t%d\t%7.4f\n",regroup_total/(double)CLOCKS_PER_SEC,regroup_iterations, (double) regroup_total / (double) CLOCKS_PER_SEC / (double) regroup_iterations); printf(" M-step Kernel:\t%7.4f\t%d\t%7.4f\n",params_total/(double)CLOCKS_PER_SEC,params_iterations, (double) params_total / (double) CLOCKS_PER_SEC / (double) params_iterations); printf(" Constants Kernel:\t%7.4f\t%d\t%7.4f\n",constants_total/(double)CLOCKS_PER_SEC,constants_iterations, (double) constants_total / (double) CLOCKS_PER_SEC / (double) constants_iterations); // Write profiling info to summary file fprintf(outf,"Program Component\tTotal\tIters\tTime Per Iteration\n"); fprintf(outf," Seed Kernel:\t%7.4f\t%d\t%7.4f\n",seed_total/(double)CLOCKS_PER_SEC,1, (double) seed_total / (double) CLOCKS_PER_SEC); fprintf(outf," E-step Kernel:\t%7.4f\t%d\t%7.4f\n",regroup_total/(double)CLOCKS_PER_SEC,regroup_iterations, (double) regroup_total / (double) CLOCKS_PER_SEC / (double) regroup_iterations); fprintf(outf," M-step Kernel:\t%7.4f\t%d\t%7.4f\n",params_total/(double)CLOCKS_PER_SEC,params_iterations, (double) params_total / (double) CLOCKS_PER_SEC / (double) params_iterations); fprintf(outf," Constants Kernel:\t%7.4f\t%d\t%7.4f\n",constants_total/(double)CLOCKS_PER_SEC,constants_iterations, (double) constants_total / (double) CLOCKS_PER_SEC / (double) constants_iterations); fclose(outf); // Open another output file for the event level clustering results FILE* fresults = fopen(result_filename,"w"); if(ENABLE_OUTPUT) { for(int i=0; i<num_events; i++) { for(int d=0; d<num_dimensions-1; d++) { fprintf(fresults,"%f,",fcs_data_by_event[i*num_dimensions+d]); } fprintf(fresults,"%f",fcs_data_by_event[i*num_dimensions+num_dimensions-1]); fprintf(fresults,"\t"); for(int c=0; c<num_clusters-1; c++) { fprintf(fresults,"%f,",clusters.memberships[c*num_events+i]); } fprintf(fresults,"%f",clusters.memberships[(num_clusters-1)*num_events+i]); fprintf(fresults,"\n"); } } fclose(fresults); io_time += (double)(clock() - io_timer); printf("\n"); printf( "I/O time: %f (ms)\n", 1000.0*io_time/CLOCKS_PER_SEC); printf( "CPU processing time: %f (ms)\n", 1000.0*cpu_time/CLOCKS_PER_SEC); total_time += (double)(clock() - total_timer); printf( "Total time: %f (ms)\n", 1000.0*total_time/CLOCKS_PER_SEC); // cleanup host memory free(fcs_data_by_event); free(fcs_data_by_dimension); free(clusters.N); free(clusters.pi); free(clusters.constant); free(clusters.avgvar); free(clusters.means); free(clusters.R); free(clusters.Rinv); free(clusters.memberships); return 0; }
int main(int argc, char *argv[]) { ps_decoder_t *ps; cmd_ln_t *config; acmod_t *acmod; ps_search_t *ngs, *pls; clock_t c; int32 score; int i; TEST_ASSERT(config = cmd_ln_init(NULL, ps_args(), TRUE, "-hmm", MODELDIR "/en-us/en-us", "-lm", MODELDIR "/en-us/en-us.lm.dmp", "-dict", MODELDIR "/en-us/cmudict-en-us.dict", "-fwdtree", "yes", "-fwdflat", "no", "-bestpath", "no", "-pl_window", "6", "-input_endian", "little", "-samprate", "16000", NULL)); TEST_ASSERT(ps = ps_init(config)); ngs = ps->search; pls = ps->phone_loop; acmod = ps->acmod; setbuf(stdout, NULL); c = clock(); for (i = 0; i < 5; ++i) { FILE *rawfh; int16 buf[2048]; size_t nread; int16 const *bptr; int nfr, n_searchfr; TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb")); TEST_EQUAL(0, acmod_start_utt(acmod)); ps_search_start(ngs); ps_search_start(pls); n_searchfr = 0; while (!feof(rawfh)) { nread = fread(buf, sizeof(*buf), 2048, rawfh); bptr = buf; while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) { while (acmod->n_feat_frame > 0) { ps_search_step(pls, n_searchfr); if (n_searchfr >= 6) ps_search_step(ngs, n_searchfr - 6); acmod_advance(acmod); ++n_searchfr; } } } for (nfr = n_searchfr - 6; nfr < n_searchfr; ++nfr) { ps_search_step(ngs, nfr); } ps_search_finish(pls); ps_search_finish(ngs); printf("%s\n", ps_search_hyp(ngs, &score, NULL)); TEST_ASSERT(acmod_end_utt(acmod) >= 0); fclose(rawfh); } printf("%s\n", ps_search_hyp(ngs, &score, NULL)); TEST_EQUAL(0, strcmp("go forward ten meters", ps_search_hyp(ngs, &score, NULL))); c = clock() - c; printf("5 * fwdtree search in %.2f sec\n", (double)c / CLOCKS_PER_SEC); ps_free(ps); cmd_ln_free_r(config); return 0; }
/**Function************************************************************* Synopsis [Performs rewriting for one node.] Description [This procedure considers all the cuts computed for the node and tries to rewrite each of them using the "forest" of different AIG structures precomputed and stored in the RWR manager. Determines the best rewriting and computes the gain in the number of AIG nodes in the final network. In the end, p->vFanins contains information about the best cut that can be used for rewriting, while p->pGraph gives the decomposition dag (represented using decomposition graph data structure). Returns gain in the number of nodes or -1 if node cannot be rewritten.] SideEffects [] SeeAlso [] ***********************************************************************/ int Rwr_NodeRewrite( Rwr_Man_t * p, Cut_Man_t * pManCut, Abc_Obj_t * pNode, int fUpdateLevel, int fUseZeros, int fPlaceEnable ) { int fVeryVerbose = 0; Dec_Graph_t * pGraph; Cut_Cut_t * pCut;//, * pTemp; Abc_Obj_t * pFanin; unsigned uPhase; unsigned uTruthBest = 0; // Suppress "might be used uninitialized" unsigned uTruth; char * pPerm; int Required, nNodesSaved; int nNodesSaveCur = -1; // Suppress "might be used uninitialized" int i, GainCur, GainBest = -1; int clk, clk2;//, Counter; p->nNodesConsidered++; // get the required times Required = fUpdateLevel? Abc_ObjRequiredLevel(pNode) : ABC_INFINITY; // get the node's cuts clk = clock(); pCut = (Cut_Cut_t *)Abc_NodeGetCutsRecursive( pManCut, pNode, 0, 0 ); assert( pCut != NULL ); p->timeCut += clock() - clk; //printf( " %d", Rwr_CutCountNumNodes(pNode, pCut) ); /* Counter = 0; for ( pTemp = pCut->pNext; pTemp; pTemp = pTemp->pNext ) Counter++; printf( "%d ", Counter ); */ // go through the cuts clk = clock(); for ( pCut = pCut->pNext; pCut; pCut = pCut->pNext ) { // consider only 4-input cuts if ( pCut->nLeaves < 4 ) continue; // Cut_CutPrint( pCut, 0 ), printf( "\n" ); // get the fanin permutation uTruth = 0xFFFF & *Cut_CutReadTruth(pCut); pPerm = p->pPerms4[ (int)p->pPerms[uTruth] ]; uPhase = p->pPhases[uTruth]; // collect fanins with the corresponding permutation/phase Vec_PtrClear( p->vFaninsCur ); Vec_PtrFill( p->vFaninsCur, (int)pCut->nLeaves, 0 ); for ( i = 0; i < (int)pCut->nLeaves; i++ ) { pFanin = Abc_NtkObj( pNode->pNtk, pCut->pLeaves[(int)pPerm[i]] ); if ( pFanin == NULL ) break; pFanin = Abc_ObjNotCond(pFanin, ((uPhase & (1<<i)) > 0) ); Vec_PtrWriteEntry( p->vFaninsCur, i, pFanin ); } if ( i != (int)pCut->nLeaves ) { p->nCutsBad++; continue; } p->nCutsGood++; { int Counter = 0; Vec_PtrForEachEntry( Abc_Obj_t *, p->vFaninsCur, pFanin, i ) if ( Abc_ObjFanoutNum(Abc_ObjRegular(pFanin)) == 1 ) Counter++; if ( Counter > 2 ) continue; } clk2 = clock(); /* printf( "Considering: (" ); Vec_PtrForEachEntry( Abc_Obj_t *, p->vFaninsCur, pFanin, i ) printf( "%d ", Abc_ObjFanoutNum(Abc_ObjRegular(pFanin)) ); printf( ")\n" ); */ // mark the fanin boundary Vec_PtrForEachEntry( Abc_Obj_t *, p->vFaninsCur, pFanin, i ) Abc_ObjRegular(pFanin)->vFanouts.nSize++; // label MFFC with current ID Abc_NtkIncrementTravId( pNode->pNtk ); nNodesSaved = Abc_NodeMffcLabelAig( pNode ); // unmark the fanin boundary Vec_PtrForEachEntry( Abc_Obj_t *, p->vFaninsCur, pFanin, i ) Abc_ObjRegular(pFanin)->vFanouts.nSize--; p->timeMffc += clock() - clk2; // evaluate the cut clk2 = clock(); pGraph = Rwr_CutEvaluate( p, pNode, pCut, p->vFaninsCur, nNodesSaved, Required, &GainCur, fPlaceEnable ); p->timeEval += clock() - clk2; // check if the cut is better than the current best one if ( pGraph != NULL && GainBest < GainCur ) { // save this form nNodesSaveCur = nNodesSaved; GainBest = GainCur; p->pGraph = pGraph; p->fCompl = ((uPhase & (1<<4)) > 0); uTruthBest = 0xFFFF & *Cut_CutReadTruth(pCut); // collect fanins in the Vec_PtrClear( p->vFanins ); Vec_PtrForEachEntry( Abc_Obj_t *, p->vFaninsCur, pFanin, i ) Vec_PtrPush( p->vFanins, pFanin ); } }
bool CSyntaxHolder::GetSentencesFromSynAn(string str, bool bFile) { clock_t t1,t2; int CountOfWords; try { m_Synan.ClearSentences(); ClearVector(m_PlmLines.m_Items); if (!GetMorphology(str, bFile, CountOfWords)) return false;; #ifdef _DEBUG m_PlmLines.SaveToFile("before.lem"); #endif // ============ Postmorphology ======================= CPlmLineCollection MapostPlmLines; if (m_bTimeStatis) t1= clock(); if (!m_pPostMorph->ProcessData(&m_PlmLines, MapostPlmLines)) { fprintf (stderr, " Cannot process Mapost\n"); return false; };; if (m_bTimeStatis) { t2 = clock(); double speed = ((double)CountOfWords)/((t2-t1)/((double)CLOCKS_PER_SEC)); fprintf(stderr,"Mapost: Ticks = %i Speed = %6.0f\n", t2-t1, speed ); }; #ifdef _DEBUG MapostPlmLines.SaveToFile("after.lem"); #endif // ============ Syntax ======================= if (m_bTimeStatis) t1= clock(); if (!m_Synan.ProcessData(&MapostPlmLines)) { fprintf (stderr, " Synan has crushed!\n"); return false; }; if (m_bTimeStatis) { t2 = clock(); double speed = ((double)CountOfWords)/((t2-t1)/((double)CLOCKS_PER_SEC)); fprintf(stderr,"Synan: Ticks = %i Speed = %6.0f\n", t2-t1, speed ); }; return true; } catch (...) { return false; }; }
void RotatePointList (g3sPoint *dest, vmsVector *src, g3sNormal *norms, int n, int o) { fVector *pfv = gameData.models.fPolyModelVerts + o; float fScale; #if PROFILING time_t t = clock (); #endif dest += o; if (norms) norms += o; while (n--) { dest->p3_key = (short) o; #if 1 if (norms) { if (norms->nFaces > 1) { norms->vNormal.p.x /= norms->nFaces; norms->vNormal.p.y /= norms->nFaces; norms->vNormal.p.z /= norms->nFaces; norms->nFaces = 1; VmVecNormalizef (&norms->vNormal, &norms->vNormal); } dest->p3_normal = *norms++; } else #endif dest->p3_normal.nFaces = 0; fScale = (gameData.models.nScale ? f2fl (gameData.models.nScale) : 1) / 65536.0f; if (gameStates.ogl.bUseTransform) { pfv->p.x = src->p.x * fScale; pfv->p.y = src->p.y * fScale; pfv->p.z = src->p.z * fScale; } else { if (gameData.models.nScale) { vmsVector v = *src; VmVecScale (&v, gameData.models.nScale); #if 1 G3TransformPoint (&dest->p3_vec, &v, 0); #else G3TransformAndEncodePoint (dest, &v); #endif } else { #if 1 G3TransformPoint (&dest->p3_vec, src, 0); #else G3TransformAndEncodePoint (dest, src); #endif } pfv->p.x = (float) dest->p3_vec.p.x / 65536.0f; pfv->p.y = (float) dest->p3_vec.p.y / 65536.0f; pfv->p.z = (float) dest->p3_vec.p.z / 65536.0f; } dest->p3_index = o++; dest->p3_src = *src++; dest++; pfv++; } #if PROFILING tTransform += clock () - t; #endif }
void main() { clrscr(); int time; int i,j,k; clock_t tic=clock(); cout<<"::MineSweeper::"<<endl; cout<<"\n Press ENTER to start the game."; for(i=0;i<10;i++) for(j=0;j<10;j++) a[i][j]='.'; getch(); clock_t toc=clock(); time=((toc-tic)*4)+3; // cout<<"\n Time= "<<time<<endl; place_mine(time); time=((toc-tic)*4)+3; // cout<<"\n Time= "<<time<<endl; place_1(time); time=((toc-tic)*7)+1; // cout<<"\n Time= "<<time<<endl; place_2(time); // for(i=0;i<10;i++) // { // if(i==0) // cout<<" "; // cout<<" "<<i; // } cout<<endl; for(i=0;i<10;i++) { for(j=0;j<10;j++) { // if(j==0) // cout<<i; cout<<" "<<a[i][j]; } cout<<endl; } for(i=0;i<10;i++) { cout<<bomb[i][0]<<" "<<bomb[i][1]<<"||"; } getch(); player(); clrscr(); cout<<"::MineSweeper::"<<endl; cout<<endl; for(i=0;i<10;i++) { if(i==0) cout<<" "; cout<<" "<<i; } cout<<endl; for(i=0;i<10;i++) { for(j=0;j<10;j++) { if(j==0) cout<<i; cout<<" "<<user[i][j]; } cout<<endl; } cout<<"\n You took "<<f_count<<" chances"; getch(); }
int get_random(int low, int high) { srand(clock()); return low + (rand() % (high - low + 1)); }
void *cal_thread(void *p) { /* int *ips = (int *)p; sscanf(p->id, "%d", ip); */ int ic; int jc; int kc; int ip; int ii; int im; unsigned int WriteLen; unsigned long looptmp; unsigned long loop; unsigned long maxi; int counter=0; THREADS_STRUCT *pt = (THREADS_STRUCT *)p; double sum=0.0; double Totalrealsec=0.0; double Totaliorealsec=0.0; double Totalsec=0.0; double Totalmemsize=0.0; double *b; struct timeval startTime, endTime, ioTime; clock_t startClock, endClock, ioClock; ip = pt->id; looptmp = pt->loop; maxi = pt->maxi; #ifdef DEBUG printf(" looptmp = %ld , ip = %d \n",looptmp,ip); printf(" maxi = %ld , ip = %d \n",maxi,ip); printf(" maxi pt = %ld , ip = %d \n",pt->maxi,ip); #endif Totalrealsec = 0.0; Totaliorealsec = 0.0; Totalsec = 0.0; Totalmemsize = 0.0; if(looptmp == 0){ loop = 10000000; } else { loop = looptmp; } for(ii = 0 ;ii < loop ; ii++){ #ifdef DEBUG printf(" ii = %d ,ip = %d \n",ii,ip); printf(" loop = %ld ,ip = %d \n",loop,ip); printf(" maxi = %ld ,ip = %d \n",maxi,ip); #endif sum = 0.0; gettimeofday(&startTime, NULL); startClock = clock(); if(maxi < 3){ maxi = 4; } for(im = (maxi-1);im<maxi;im++){ b = (double *)malloc((sizeof(double))*im*im*im); if( b == NULL) { err(EXIT_FAILURE, "can not create thread 2" ); } for(ic=0;ic<im;ic++){ for(jc=0;jc<im;jc++){ for(kc=0;kc<im;kc++){ b[ic*jc*kc] = 0.0; } } } for(ic=0;ic<im;ic++){ b[ic] = 1.0; } for(ic=1;ic<(im-1);ic++){ for(jc=1;jc<(im-1);jc++){ for(kc=1;kc<(im-1);kc++){ sum = sum + (b[ic*jc*kc] + b[(ic-1)*jc*kc] + b[(ic+1)*jc*kc] + b[ic*(jc-1)*kc] + b[ic*(jc+1)*kc] + b[ic*jc*(kc-1)] + b[ic*jc*(kc+1)] )/7.0; } } } for(ic=0;ic<im;ic++){ b[ic] = sum; } gettimeofday(&ioTime, NULL); ioClock = clock(); if(pt->arg1 == 1){ WriteLen = (int)((im*im*im)-1); fwrite((char *)b,sizeof(char),WriteLen,pt->fp); fseek(pt->fp, 0L, SEEK_SET); } free(b); } gettimeofday(&endTime, NULL); endClock = clock(); time_t diffsec = difftime(endTime.tv_sec, startTime.tv_sec); suseconds_t diffsub = endTime.tv_usec - startTime.tv_usec; if (diffsub < 0) { diffsec -= 1; diffsub = 1000000 + diffsub; } double realsec = diffsec+diffsub*1e-6; double cpusec = (endClock - startClock)/(double)CLOCKS_PER_SEC; double percent = 100.0*cpusec/realsec; time_t iodiffsec = difftime(endTime.tv_sec, ioTime.tv_sec); suseconds_t iodiffsub = endTime.tv_usec - ioTime.tv_usec; if (iodiffsub < 0) { iodiffsec -= 1; iodiffsub = 1000000 + iodiffsub; } double iorealsec = iodiffsec+iodiffsub*1e-6; double iocpusec = (endClock - ioClock)/(double)CLOCKS_PER_SEC; double iopercent = 100.0*iocpusec/iorealsec; Totalrealsec += realsec; Totaliorealsec += iorealsec; Totalsec += realsec+ iorealsec; Totalmemsize += im; counter++; } printf("******************************** \n"); printf("**** Real Time %f s\n", Totalrealsec); printf("**** I/O Time %f byte/s\n", Totalmemsize*Totalmemsize*Totalmemsize/Totaliorealsec); printf("**** Ave. %f s\n", Totalrealsec/counter); printf("******************************** \n"); #ifdef DEBUG printf(" write start WriteLen = %d ,ip = %d \n",pt->WriteLen,ip); #endif return 0; }
int run_test_case(int casenum__) { switch (casenum__) { case 0: { int blockHeights[] = {4,7}; int expected__ = 11; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 1: { int blockHeights[] = {7,4}; int expected__ = 7; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 2: { int blockHeights[] = {7}; int expected__ = 7; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 3: { int blockHeights[] = {4}; int expected__ = 4; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 4: { int blockHeights[] = {48,1,50,1,50,1,48}; int expected__ = 196; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 5: { int blockHeights[] = {49,2,49,2,49}; int expected__ = 147; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 6: { int blockHeights[] = {44,3,44,3,44,47,2,47,2,47,2}; int expected__ = 273; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } // custom cases case 7: { int blockHeights[] = {2, 1, 1, 33, 40}; int expected__ = 42; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 8: { int blockHeights[] = {11, 6, 6, 6}; int expected__ = 18; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } /* case 9: { int blockHeights[] = ; int expected__ = ; clock_t start__ = clock(); int received__ = BlockTower().getTallest(vector <int>(blockHeights, blockHeights + (sizeof blockHeights / sizeof blockHeights[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); }*/ default: return -1; } }
nTupleVolume * inpaint_image( nTupleVolume *imgVolIn, nTupleVolume *occVolIn, patchMatchParameterStruct *patchMatchParams, inpaintingParameterStruct *inpaintingParams) { // ******************************************************************** // // **** AUTOMATICALLY DETERMINE NUMBER OF LEVELS, IF NOT SPECIFIED **** // // ******************************************************************** // if (inpaintingParams->nLevels == -1) { inpaintingParams->nLevels = determine_multiscale_level_number(occVolIn,imgVolIn->patchSizeX,imgVolIn->patchSizeY); } display_inpainting_parameters(inpaintingParams); display_patch_match_parameters(patchMatchParams); nTupleVolume *imgVolOut; // ************************** // // **** CREATE PYRDAMIDS **** // // ************************** // nTupleVolumePyramid imgVolPyramid = create_nTupleVolume_pyramid(imgVolIn, inpaintingParams->nLevels); nTupleVolumePyramid occVolPyramid = create_nTupleVolume_pyramid_binary(occVolIn, inpaintingParams->nLevels); featurePyramid featuresVolPyramid; if (inpaintingParams->useFeatures == true) { double t1 = clock(); featuresVolPyramid = create_feature_pyramid(imgVolIn, occVolIn, inpaintingParams->nLevels); MY_PRINTF("\n\nFeatures calculation time: %f\n",((double)(clock()-t1)) / CLOCKS_PER_SEC); } else { featuresVolPyramid.normGradX = NULL; featuresVolPyramid.normGradY = NULL; featuresVolPyramid.nLevels = -1; } //create structuring element nTupleVolume *structElDilate = create_structuring_element("rectangle", imgVolIn->patchSizeX, imgVolIn->patchSizeY); //show_patch_match_parameters(patchMatchParams); // ****************************************** // // ************* START INPAINTING *********** // // ****************************************** // nTupleVolume *imgVol,*normGradXvol,*normGradYvol; nTupleVolume *shiftVol=NULL; for (int level=( (inpaintingParams->nLevels)-1); level>=0; level--) { printf("Current pyramid level : %d\n",level); nTupleVolume *imgVolPrevious,*occVol,*occVolDilate; if (patchMatchParams->maxShiftDistance != -1) patchMatchParams->maxShiftDistance = (float)( (patchMatchParams->maxShiftDistance)/( pow((float)SUBSAMPLE_FACTOR,(float)level) )); imgVol = copy_image_nTuple(imgVolPyramid[level]); occVol = copy_image_nTuple(occVolPyramid[level]); //create dilated occlusion occVolDilate = imdilate(occVol, structElDilate); if (featuresVolPyramid.nLevels >= 0) { normGradXvol = copy_image_nTuple((featuresVolPyramid.normGradX)[level]); normGradYvol = copy_image_nTuple((featuresVolPyramid.normGradY)[level]); //attach features to patchMatch parameters patchMatchParams->normGradX = normGradXvol; patchMatchParams->normGradY = normGradYvol; } //initialise solution if (level == ((inpaintingParams->nLevels)-1)) { shiftVol = new nTupleVolume(4,imgVol->xSize,imgVol->ySize,imgVol->patchSizeX,imgVol->patchSizeY,IMAGE_INDEXING); shiftVol->set_all_image_values(0); printf("\nInitialisation started\n\n\n"); initialise_inpainting(imgVol,occVol,featuresVolPyramid,shiftVol,patchMatchParams); patchMatchParams->partialComparison = 0; printf("\nInitialisation finished\n\n\n"); if (featuresVolPyramid.nLevels >= 0) //retrieve features from the pointers in the patchMatch parameters { normGradXvol = patchMatchParams->normGradX; normGradYvol = patchMatchParams->normGradY; } } else //reconstruct current solution { if (featuresVolPyramid.nLevels >= 0) { reconstruct_image_and_features(imgVol, occVol, normGradXvol, normGradYvol, shiftVol, SIGMA_COLOUR); } else { reconstruct_image(imgVol,occVol,shiftVol,SIGMA_COLOUR); //write_shift_map(shiftVol,fileOut); } } calclulate_patch_distances(imgVol,imgVol,shiftVol,occVolDilate,patchMatchParams); //iterate ANN search and reconstruction int iterationNb = 0; imageDataType residual = FLT_MAX; while( (residual > (inpaintingParams->residualThreshold) ) && (iterationNb < (inpaintingParams->maxIterations) ) ) { //copy current imgVol imgVolPrevious = copy_image_nTuple(imgVol); patch_match_ANN(imgVol,imgVol,shiftVol,occVolDilate,occVolDilate,patchMatchParams); if (featuresVolPyramid.nLevels >= 0) { reconstruct_image_and_features(imgVol, occVol, normGradXvol, normGradYvol, shiftVol, SIGMA_COLOUR); } else reconstruct_image(imgVol,occVol,shiftVol,SIGMA_COLOUR); residual = calculate_residual(imgVol,imgVolPrevious,occVol); if (patchMatchParams->verboseMode == true) printf("Iteration number %d, residual = %f\n",iterationNb,residual); iterationNb++; } //upsample shift volume, if we are not on the finest level if (level >0) { nTupleVolume * shiftVolTemp = up_sample_image(shiftVol, SUBSAMPLE_FACTOR,imgVolPyramid[level-1]); delete(shiftVol); shiftVol = copy_image_nTuple(shiftVolTemp); shiftVol->multiply((imageDataType)SUBSAMPLE_FACTOR); delete(shiftVolTemp); } else { reconstruct_image(imgVol,occVol,shiftVol,SIGMA_COLOUR,3); imgVolOut = new nTupleVolume(imgVol); } //destroy structures delete(imgVol); delete(imgVolPrevious); delete(occVol); delete(occVolDilate); if (featuresVolPyramid.nLevels >= 0) { delete normGradXvol; delete normGradYvol; } } // ************************** // // **** DELETE STRUCTURES *** // // ************************** // for (int i=0; i< (inpaintingParams->nLevels); i++) { delete(imgVolPyramid[i]); delete(occVolPyramid[i]); } delete(imgVolPyramid); delete(occVolPyramid); delete(shiftVol); delete_feature_pyramid(featuresVolPyramid); delete(patchMatchParams); printf("Inpainting finished !\n"); return(imgVolOut); }
void run_epd_testsuite(void) { FILE *testsuite; char readbuff[2000]; char testname[FILENAME_MAX]; char tempbuff[2000]; float elapsed; int nps; long thinktime; move_s comp_move; int tested, found; clock_t cpu_start, cpu_end; tested = 0; found = 0; printf("\nName of EPD testsuite: "); rinput(testname, STR_BUFF, stdin); printf("\nTime per move (s): "); rinput(readbuff, STR_BUFF, stdin); thinktime = atol(readbuff); printf("\n"); thinktime *= 100; testsuite = fopen(testname, "r"); while (fgets(readbuff, 2000, testsuite) != NULL) { tested++; setup_epd_line(readbuff); root_to_move = ToMove; clear_tt(); initialize_hash(); display_board(stdout, 1); forcedwin = FALSE; // pn_time = thinktime; // cpu_start = clock(); // proofnumbersearch(); // cpu_end = clock(); // rdelay(2); elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC; printf("Time: %f\n", elapsed); if (interrupt()) rinput(tempbuff, STR_BUFF, stdin); fixed_time = thinktime; cpu_start = clock(); comp_move = think(); cpu_end = clock(); printf ("\nNodes: %ld (%0.2f%% qnodes)\n", nodes, (float) ((float) qnodes / (float) nodes * 100.0)); elapsed = (cpu_end-cpu_start)/(float) CLOCKS_PER_SEC; nps = (int)((float) nodes/(float) elapsed); if (!elapsed) printf ("NPS: N/A\n"); else printf ("NPS: %ld\n", (long int) nps); printf("ECacheProbes : %ld ECacheHits : %ld HitRate : %f%%\n", ECacheProbes, ECacheHits, ((float)ECacheHits/((float)ECacheProbes+1)) * 100); printf("TTStores : %ld TTProbes : %ld TTHits : %ld HitRate : %f%%\n", TTStores, TTProbes, TTHits, ((float)TTHits/((float)TTProbes+1)) * 100); printf("NTries : %d NCuts : %d CutRate : %f%% TExt: %d\n", NTries, NCuts, (((float)NCuts*100)/((float)NTries+1)), TExt); printf("Check extensions: %ld Razor drops : %ld Razor Material : %ld\n", ext_check, razor_drop, razor_material); printf("EGTB Hits: %d EGTB Probes: %d Efficiency: %3.1f%%\n", EGTBHits, EGTBProbes, (((float)EGTBHits*100)/(float)(EGTBProbes+1))); printf("Move ordering : %f%%\n", (((float)FHF*100)/(float)FH+1)); printf("Material score: %d Eval : %ld\n", Material, eval()); printf("\n"); if (!forcedwin) { if(check_solution(readbuff, comp_move)) { found++; printf("Solution found.\n"); } else { printf("Solution not found.\n"); } } else { found++; } printf("Solved: %d/%d\n", found, tested); }; printf("\n"); };
/* Corpo de leitura do arquivo adaptado do arquivo filtro_windows.c no repositório. */ int main(int argc, char *argv[]) { clock_t start, end; double cpu_time_used; char filetype[256], *ptri, *ptro, *img; char rnds[SIMD_SIZE]; char limit[SIMD_SIZE]; int width, height, depth, pixels, i, j, k, n, resto, siz, rnd; char mult[24] = { 1, 1, 3, 1, 1, 3, 1, 1, 3, 1, 1, 3, 1, 1, 3, 1, 1, 3, 1, 1, 3, 1, 1, 3 }; // vetor com as 3 sequencias de multiplicadores usadas (apos a 3a sequencia, a 4a iguala-se a primeira, entao reiniciamos) char *m = mult; char clear[] = { 1, 1, 1, 1, 1, 1, 1, 1 }; // bytes auxiliares char xorFix[] = { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }; // bytes 128 para corrigir a comparacao FILE *fp; FILE *fo; if (argc < 3) { printf("Usage: %s input output", argv[0]); exit(1); } fp = fopen(argv[1], "rb"); if (!fp) { printf("File %s not found!", argv[1]); exit(1); } fo = fopen(argv[2], "wb"); if (!fo) { printf("Unable to create file %s!", argv[2]); exit(1); } srand((unsigned)time(NULL)); // para valores randomicos fscanf(fp, "%s\n", filetype); fprintf(fo, "%s%c", filetype, 10); fscanf(fp, "%d %d\n%d\n", &width, &height, &depth); fprintf(fo, "%d %d\n%d%c", width, height, depth, 10); pixels = width * height; siz = (pixels * 3) + (SIMD_SIZE - ((3 * pixels) % SIMD_SIZE)); // fazemos o tamanho do malloc ser divisivel por SIMD_SIZE, adicionando o que falta ao resto ptri = ptro = img = (char *)malloc(siz); fread(img, 3, pixels, fp); start = clock(); for (j = 0; j < SIMD_SIZE; j++) limit[j] = RND_LIMIT; // preenchemos o vetor que limita a subtracao do ruido com 50 for (i = 0; i < (siz / SIMD_SIZE); i++) // precisamos de menos iteracoes agora que varios bytes serao tratados por vez { k = 0; for (j = 0; j < (SIMD_SIZE/3) + 1; j++) { rnd = rand() % 40; for (n = 0; n < 3 && k < SIMD_SIZE; n++) // gera um vetor de numeros aleatorios, sempre repetido r1, r1, r1, r2, r2, r2, r3, r3, embora o ideal tambem seja deslocar esses valores rnds[k++] = rnd; } resto = i % 3; __asm { emms mov esi, ptri mov edi, ptro cmp i, 0 // para evitar acessos a memoria, carregamos esses valores nos registradores apenas na primeira iteracao e o reutilizamos depois jne skip movq mm2, limit // limitante para o ruido movq mm5, xorFix // fator de correcao para a comparacao do ruido movq mm7, clear // vetor composto por 1 para concatenar os resultados da multiplicacao azul mov eax, m // aqui carregamos os valores dos 3 estagios de multiplicacao movlpd xmm5, [eax] movlpd xmm6, [eax + 8] movlpd xmm7, [eax + 16] // fazemos xor entre o limite do ruido e o fator de correcao, pois a comparacao e sempre com sinal e valores elevados serao tratados como negativos // entao, subtraimos 128 destes para que a comparacao seja adequada pxor mm2, mm5 skip : cmp resto, 2 // verifica o estagio e escolhe os fatores do 3o estagio jne skip2 movdq2q mm6, xmm7 jmp read skip2: cmp resto, 1 // escolhe o 2o estagio jne skip3 movdq2q mm6, xmm6 jmp read skip3: movdq2q mm6, xmm5 // escolhe o estagio inicial read: movq mm0, [esi] // lemos os 8 bytes para mm0 movq mm1, rnds // lemos os valores random para mm1 movq mm3, mm0 // copia mm0 em mm3 pxor mm3, mm5 // fazemos o xor em mm3 para subtrair 128 pcmpgtb mm3, mm2 // comparamos com sinal os valores com o limitante pand mm3, mm1 // os positivos recebem FF, então fazemos um and com os valores randomicos psubb mm0, mm3 // e subtraimos dos bytes originais, assim, aqueles que nao satisfazem o limite sao subtraidos de 0 e continuam iguais movq2dq mm0, xmm0 // agora movemos mm0 para xmm0 e o expandimos para words punpcklbw xmm0, xmm4 movq2dq xmm2, mm6 // movemos o vetor de multiplicacao escolhido para xmm2 e o expandimos em words punpcklbw xmm2, xmm4 pmullw xmm0, xmm2 // multiplicamos os bytes pelo fator de multiplicacao, resultando apenas nos azuis *3 e os demais *1 movdqa xmm1, xmm0 // copiamos xmm0 em xmm1 psrlw xmm1, 2 // e fazemos a divisao das words de xmm1 por 4 (shift right 2) movq2dq xmm3, mm7 // move o vetor clear (composto por 1s para xmm3) e o expandimos em words punpcklbw xmm3, xmm4 pcmpgtw xmm2, xmm3 // marca em xmm2 quais as words cujo multiplicador é maior que 1 (quais são as posições azuis) pcmpgtw xmm3, xmm4 // faz xmm3 todo igual a FF pxor xmm3, xmm2 // faz as words de xmm3 que tem posição do azul serem 0 e as demais continuam FFFF pand xmm2, xmm1 // copia os 2 ou 3 bytes azuis para xmm2 pand xmm3, xmm0 // copia os demais bytes para xmm3, deixando os bytes azuis como 0 por xmm3, xmm2 // junta os bytes em xmm3, resultando em todos os bytes sem shift, exceto por aqueles marcados nas posições azuis // assim, temos os bytes azuis * 0.75 e os compactamos de words para bytes em xmm3 packuswb xmm3, xmm4 movlpd [edi], xmm3 // gravamos a parte baixa (com os bytes) na memoria } ptri += SIMD_SIZE; ptro += SIMD_SIZE; } end = clock(); fwrite(img, 3, pixels, fo); // aqui ignoramos os ultimos pixels que foram usados para deixar a divisao por SIMD_SIZE exata e salvamos apenas os que fazem parte da imagem fclose(fp); fclose(fo); free(img); cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC; fprintf(stderr, "tempo = %f segundos\n", cpu_time_used); return 0; }
int main() { int key,age; char name[MAXSTR],operacao; FILE *fIndex,*fTerminal; Register reg,*cons; float start,end,timeElapsed; fIndex = checkFileIndex(); fTerminal = checkFileTerminal(); do { fseek(fIndex,0,SEEK_SET); fseek(fTerminal,0,SEEK_SET); scanf("%c%*c",&operacao); operacao = tolower(operacao); switch(operacao) { //Sair do Programa case 'e': { fclose(fIndex); fclose(fTerminal); exit(1); break; } //Insere Registro case 'i': { scanf("%d%*c",&key); getstr(name,MAXSTR); scanf("%d%*c",&age); if(fIndex && fTerminal) { reg.key = key; strcpy(reg.name,name); reg.age = age; if(!insereRegistro(fIndex,fTerminal,®)) { printf("chave ja existente: %d\n",key); } } break; } //Consulta Regisro case 'c': { scanf("%d%*c",&key); start = (float)clock()/CLOCKS_PER_SEC; cons = consultaRegistro(fIndex,fTerminal,key); end = (float)clock()/CLOCKS_PER_SEC; timeElapsed = end - start; if(cons) printf("chave: %d\n%s\n%d\n",key,cons->name,cons->age); else printf("chave nao encontrada\n"); printf("query rapida: %f segundos\n",timeElapsed); start = (float)clock()/CLOCKS_PER_SEC; cons = slowQuery(fTerminal,key); end = (float)clock()/CLOCKS_PER_SEC; timeElapsed = end - start; printf("query lenta: %f segundos\n",timeElapsed); break; } //Remove Registro case 'r': { scanf("%d%*c",&key); if(!removeRegistro(fIndex,fTerminal,key)) { printf("chave nao encontrada\n"); } break; } //Imprime Árvore case 'p': { imprimeArvore(fIndex,fTerminal); break; } //Imprime nós Terminais case 'f': { imprimeNosTerminais(fTerminal); break; } } }while(operacao != 'e'); return 0; }
static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
int main(void) { double y[EQ_N][2]; double (*func[EQ_N])(); double parameter[PARTICLE_N][PARA_N], parameter_memory[PARA_N], resampled_parameter[PARTICLE_N][PARA_N]; double time_point[TIME_POINT_N]; double ref_time_point[TIME_POINT_N]; int i, j, k, l, m; int mcmc_num, pa_num, integral_num, particle_num, rk_num, timepoint_num, parameter_num, equation_num; int x_flag = 0; double X, dt; double probability_before, probability_after, probability_ratio; int move_count = 0; double weight[PARTICLE_N], weight_tmp[PARTICLE_N]; double total_weight = 0, power_total_weight, partial_total_weight, upper_weight, lower_weight; double log_weight[PARTICLE_N], log_weight_tmp[PARTICLE_N]; double total_likelihood[PARTICLE_N], total_likelihood_previous[PARTICLE_N]; double log_likelihood[PARTICLE_N], total_log_likelihood; double epsilon[POPULATION_N] = {10, 5, 2.5, 2, 1.5}; double ess; int sampling_num; int resampling_count = 0; int weighten_particle_num[POPULATION_N] = {0, 0, 0, 0, 0}, last_weighten_particle_num = 0; int resampling_flag[POPULATION_N] = {0, 0, 0, 0, 0}; double effective_particle_num = 0, total_effective_particle_num = 0; double weighten_particle_multiplier = 1; int mcmc_step; double unit_r, chosen_num; FILE *fp1, *fp2, *fp3, *fp4, *fp5, *fp6, *fp7, *fin; clock_t start, end; dt = 0.01; X = 1.0; function_set(func); /*** 計算開始 **********************************************************************************************************************************/ /* 時間を計る */ start = clock(); /* 乱数の初期化 */ init_genrand(8); /* ファイル設定 */ fp1 = fopen("information8.data","w"); /* 実験データの読み込み */ fin = fopen("ref_time_point.data","r"); for(timepoint_num=0;timepoint_num<TIME_POINT_N;timepoint_num++){ fscanf(fin, "%lf", &ref_time_point[timepoint_num]); } fclose(fin); /* 実験データの読み込み終了 */ /* サンプル番号初期化 */ sampling_num = 0; printf("0 th population\n"); /* ランダムサンプリングによる 粒子数個のパラメータセットの発生 **************************************************************************************/ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ /* パラメータ、合計濃度、変動係数を発生させる */ parameter_set(parameter[particle_num]); parameter_generation(parameter[particle_num]); } /* 重みを初期化 正規化 */ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ weight[particle_num] = 1.0/PARTICLE_N; } /* ランダムサンプリングによる初期パラメータ発生 終了 ************************************************************************************************/ /* Population annealing 開始 *****************************************************************************************************************/ for(pa_num=0;pa_num<POPULATION_N;pa_num++){ printf("%d th population\n", pa_num+1); /* 各粒子ごとに尤度の計算 */ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ total_likelihood[particle_num] = 0; /* 初期化 */ total_likelihood_previous[particle_num] = 0; /* 初期化 */ } /* 中間分布の計算 */ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ /* time point データの発生 */ y[0][0] = 0.0; y[1][0] = 0.0; rk_search(X, dt, func, y, parameter[particle_num], time_point); /* 尤度の計算 */ total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]); if(pa_num==0){ total_likelihood_previous[particle_num] = 1; } else{ total_likelihood_previous[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num-1]); } } /* 中間分布の計算終了 */ /* 重みの計算 */ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ weight[particle_num] = weight[particle_num] * total_likelihood[particle_num]/total_likelihood_previous[particle_num]; if(total_likelihood[particle_num]==0 || total_likelihood_previous[particle_num]==0) weight[particle_num] = 0.0; } total_weight = 0.0; for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ total_weight = total_weight + weight[particle_num]; } for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ weight[particle_num] = weight[particle_num]/total_weight; } /* 重みを持つ粒子数の計算 */ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ if(weight[particle_num]!=0) weighten_particle_num[pa_num]++; } fprintf(fp1, "weighten particle num = %d\n", weighten_particle_num[pa_num]); /* 各粒子ごとに */ for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ /* 重みが0なら飛ばす */ if(weight[particle_num]==0) continue; /* フラグの初期化 */ x_flag = 0; /* MCMC 計算 */ for(mcmc_num=0;mcmc_num<MCMC_MAX_STEP;mcmc_num++){ /* 許容されなければ、元のままのパラメータ */ if(x_flag == 1){ for(parameter_num=0;parameter_num<PARA_N;parameter_num++){ parameter[particle_num][parameter_num] = parameter_memory[parameter_num]; } } /* 確率の初期化 */ probability_before = 1.0; probability_after = 1.0; /* フラグの初期化 */ x_flag = 0; /* 新候補の計算前の値を記憶 */ for(parameter_num=0;parameter_num<PARA_N;parameter_num++){ parameter_memory[parameter_num] = parameter[particle_num][parameter_num]; } /* 移動前の確率を計算 */ probability_before = probability_before*pdf_uniform_parameter(parameter[particle_num]); /* 事前分布を乗じる */ total_likelihood[particle_num] = 0.0; /* 初期化 */ /* time point データの発生 */ y[0][0] = 0.0; y[1][0] = 0.0; rk_search(X, dt, func, y, parameter[particle_num], time_point); /* 尤度の計算 */ total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]); probability_before = probability_before * total_likelihood[particle_num]; /* 移動前の確率 */ /* 新候補を計算 パラメータの中から1つだけ動かす */ unit_r = genrand_real2(); chosen_num = PERTURB_PARA_N*unit_r; parameter_sampler(parameter[particle_num]); /* 移動後の確率を計算 : 一様事前分布を乗じる */ probability_after = probability_after*pdf_uniform_parameter(parameter[particle_num]); /* 事前分布を乗じる */ if(probability_after == 0.0){ x_flag = 1; for(parameter_num=0;parameter_num<PARA_N;parameter_num++){ parameter[particle_num][parameter_num] = parameter_memory[parameter_num]; } continue; } /* 移動後の確率を計算 */ total_likelihood[particle_num] = 0.0; /* 初期化 */ /* time point データの発生 */ y[0][0] = 0.0; y[1][0] = 0.0; rk_search(X, dt, func, y, parameter[particle_num], time_point); /* 尤度の計算 */ total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]); probability_after = probability_after * total_likelihood[particle_num]; /* 移動後の確率 */ if(probability_after == 0.0){ x_flag = 1; for(parameter_num=0;parameter_num<PARA_N;parameter_num++){ parameter[particle_num][parameter_num] = parameter_memory[parameter_num]; } continue; } /* 移動前と移動後の確率の比の計算 */ probability_ratio = probability_after/probability_before; /* [0,1) 単位乱数の発生 */ unit_r = genrand_real2(); /* 移動の判定 */ if(probability_ratio > unit_r){ move_count++; } else{ x_flag = 1; for(parameter_num=0;parameter_num<PARA_N;parameter_num++){ parameter[particle_num][parameter_num] = parameter_memory[parameter_num]; } continue; } } /* particle_num 番目の粒子の MCMC 終了 */ } /* 全粒子の MCMC 終了 */ /* リサンプリング ********************************************************/ power_total_weight = 0.0; ess = 0.0; for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ power_total_weight = power_total_weight + pow(weight[particle_num], 2); } /* Effective Sample Size の計算 */ ess = 1.0/power_total_weight; //if(pa_num==4) ess = 0.0; fprintf(fp1, "%d th population", pa_num); fprintf(fp1, "ESS = %f\t particle_num/2 = %f\n\n", ess, PARTICLE_N/2.0); /* リサンプリングの判定と実行 */ if(ess < PARTICLE_N/2){ fprintf(fp1, "resampling\n"); resampling_count++; resampling_flag[pa_num] = 1; fprintf(fp1, "resampling flag = %d\n", resampling_flag[pa_num]); /* 粒子数個リサンプリングする 重複可 */ for(m=0;m<PARTICLE_N;m++){ /* [0,1) 乱数発生 */ unit_r = genrand_real2(); partial_total_weight = 0.0; /* l 番目の粒子が選ばれる */ for(l=0;l<PARTICLE_N;l++){ partial_total_weight = partial_total_weight + weight[l]; upper_weight = partial_total_weight; lower_weight = partial_total_weight - weight[l]; if((unit_r >= lower_weight) && (unit_r < upper_weight)){ for(i=0;i<PARA_N;i++){ resampled_parameter[m][i] = parameter[l][i]; } break; } } } /* 粒子数個リサンプリング終了 */ /* リサンプル後のパラメータと活性化時間の再設定 */ for(l=0;l<PARTICLE_N;l++){ for(i=0;i<PARA_N;i++){ parameter[l][i] = resampled_parameter[l][i]; } } /* リサンプル後の重みを初期化 正規化 */ for(l=0;l<PARTICLE_N;l++){ weight[l] = 1.0/PARTICLE_N; } } /* リサンプリングの判定と実行 終了 */ /* リサンプリング終了 ****************************************************/ } /* Population annealing 終了 *****************************************************************************************************************/ for(pa_num=0;pa_num<POPULATION_N;pa_num++){ if(resampling_flag[pa_num]==1){ weighten_particle_multiplier = weighten_particle_multiplier * weighten_particle_num[pa_num]/PARTICLE_N; } } /* 重みを持つ粒子数の計算 */ last_weighten_particle_num = 0; for(particle_num=0;particle_num<PARTICLE_N;particle_num++){ if(weight[particle_num]!=0) last_weighten_particle_num++; } effective_particle_num = last_weighten_particle_num*weighten_particle_multiplier; fprintf(fp1, "effective particle number = %f\n", effective_particle_num); /* 移動回数、 リサンプリング回数、 モデル数を出力 */ fprintf(fp1, "%d times move\n", move_count); fprintf(fp1, "%d times resampling\n", resampling_count); end = clock(); /* 計算時間の出力 */ fprintf(fp1, "%f min\n", (double)(end - start)/CLOCKS_PER_SEC/60.0); fclose(fp1); return 0; }
void PCHPerformReloc( pch_reloc_index ri ) /****************************************/ { long start_position; long stop_position; unsigned reloc_size; char *volatile pch_fname; // must be preserved by setjmp() int status; jmp_buf restore_state; #ifndef NDEBUG clock_t start; clock_t stop; start = clock(); #endif if( ErrCount != 0 ) { return; } start_position = relocInfo[ ri ].start; if( start_position == 0 ) { return; } stop_position = relocInfo[ ri ].stop; pch_fname = PCHFileName(); pchFile = sopen3( pch_fname, O_RDWR | O_BINARY | O_EXCL, SH_DENYRW ); if( pchFile == -1 ) { CErr2p( ERR_PCH_OPEN_ERROR, pch_fname ); return; } DbgAssert( ( stop_position - start_position ) < UINT_MAX ); reloc_size = stop_position - start_position; ioBuffer = CMemAlloc( reloc_size ); abortData = &restore_state; status = setjmp( restore_state ); if( status == 0 ) { if( lseek( pchFile, start_position, SEEK_SET ) != start_position ) { fail(); } if( read( pchFile, ioBuffer, reloc_size ) != reloc_size ) { fail(); } if( relocFunctions[ri]( ioBuffer, reloc_size ) == PCHCB_ERROR ) { fail(); } if( lseek( pchFile, -(long)reloc_size, SEEK_CUR ) != start_position ) { fail(); } if( write( pchFile, ioBuffer, reloc_size ) != reloc_size ) { fail(); } // keep this PCH file pch_fname = NULL; } else { CErr1( ERR_PCH_WRITE_ERROR ); } abortData = NULL; CMemFreePtr( &ioBuffer ); close( pchFile ); if( pch_fname != NULL ) { // write error occurred; delete PCH file remove( pch_fname ); } #ifndef NDEBUG stop = clock(); printf( "%u ticks to relocate pre-compiled header (%u section)\n", (unsigned)( stop - start ), ri ); #endif }
void display(void) { if(dipMode==1) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); }else{ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } curF++; // put your OpenGL display commands here glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // reset OpenGL transformation matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // reset transformation matrix to identity // setup look at transformation so that // eye is at : (0,0,3) // look at center is at : (0,0,0) // up direction is +y axis gluLookAt(0.f,0.f,3.f,0.f,0.f,0.f,0.f,1.f,0.f); glRotatef(fRotateAngle,.3f,1.f,.3f); //rand() * 2 - 1; // Test drawing a solid teapot /* else{ glLineWidth(2.5); //glColor3f(1. , 0. , 0.); } */ glColor3f(changecolor + 1., changecolor + .5, changecolor);// set current color to orange //glutSolidTeapot(1.f); // call glut utility to draw a solid teapot glBegin(GL_TRIANGLE_FAN); glVertex2f(-.6 + sin(change - 10) / 20, 1. + cos(change - 10) / 20); glVertex2f(-.6 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); glVertex2f(-.2 + cos(change - 10) / 20, .6 + cos(change - 10) / 20); // v3 glVertex2f(.2 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); // v10 glVertex2f(.6 + sin(change - 10) / 20, .6 + sin(change - 10) / 20); glVertex2f(.6 + cos(change - 10) / 20, 1. + sin(change - 10) / 20); glEnd(); glBegin(GL_TRIANGLE_FAN); /* if (colorflag) { glColor3f(changecolor + 1., changecolor + .5, changecolor);// set current color to orange } else { glColor3f(changecolor + 1., changecolor + .5, changecolor); }*/ glVertex2f(0. + sin(change - 10) / 20, -1. + sin(change - 10) / 20); glVertex2f(-.6 + sin(change - 10) / 20, -1. + sin(change - 10) / 20); glVertex2f(-.6 + cos(change - 10) / 20, -.6 + cos(change - 10) / 20); glVertex2f(-.2 + cos(change - 10) / 20, -.6 + sin(change - 10) / 20); glVertex2f(-.2 + cos(change - 10) / 20, .6 + cos(change - 10) / 20); // v3 glVertex2f(.2 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); // v10 glVertex2f(.2 + sin(change - 10) / 20, -.6 + cos(change - 10) / 20); glVertex2f(.6 + cos(change - 10) / 20, -.6 + sin(change - 10) / 20); glVertex2f(.6 + sin(change - 10) / 20, -1. + cos(change - 10) / 20); glEnd(); //glFlush(); glutSwapBuffers(); // swap front/back framebuffer to avoid flickering curClock=clock(); float elapsed=(curClock-startClock)/(float)CLOCKS_PER_SEC; if(elapsed>1.0f){ float fps=(float)(curF-prevF)/elapsed; printf("fps:%f\n",fps); prevF=curF; startClock=curClock; } }
void PCHActivate( void ) { start_parse = clock(); }
/////////////////////////////////////////////////////// // Panel::CalibrateCamera() Description /////////////////////////////////////////////////////// void Panel::CalibrateCamera(string sFilePath) { help(); //! [file_read] Settings s; const string inputSettingsFile = sFilePath; FileStorage fs(inputSettingsFile, FileStorage::READ); // Read the settings if (!fs.isOpened()) { cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << endl; // return -1; } fs["Settings"] >> s; fs.release(); // close Settings file //! [file_read] //FileStorage fout("settings.yml", FileStorage::WRITE); // write config as YAML //fout << "Settings" << s; if (!s.goodInput) { cout << "Invalid input detected. Application stopping. " << endl; // return -1; } vector<vector<Point2f> > imagePoints; Mat cameraMatrix, distCoeffs; Size imageSize; int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION; clock_t prevTimestamp = 0; const Scalar RED(0, 0, 255), GREEN(0, 255, 0); const char ESC_KEY = 27; int counter = 1; //! [get_input] for (;;) { Mat view; bool blinkOutput = false; view = s.nextImage(); //----- If no more image, or got enough, then stop calibration and show result ------------- if (mode == CAPTURING && imagePoints.size() >= (size_t)s.nrFrames) { if (runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints)) mode = CALIBRATED; else mode = DETECTION; } if (view.empty()) // If there are no more images stop the loop { // if calibration threshold was not reached yet, calibrate now if (mode != CALIBRATED && !imagePoints.empty()) runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints); break; } //! [get_input] imageSize = view.size(); // Format input image. if (s.flipVertical) flip(view, view, 0); //! [find_pattern] vector<Point2f> pointBuf; bool found; switch (s.calibrationPattern) // Find feature points on the input format { case Settings::CHESSBOARD: found = findChessboardCorners(view, s.boardSize, pointBuf, CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE); break; case Settings::CIRCLES_GRID: found = findCirclesGrid(view, s.boardSize, pointBuf); break; case Settings::ASYMMETRIC_CIRCLES_GRID: found = findCirclesGrid(view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID); break; default: found = false; break; } //! [find_pattern] //! [pattern_found] if (found) // If done with success, { // improve the found corners' coordinate accuracy for chessboard if (s.calibrationPattern == Settings::CHESSBOARD) { Mat viewGray; cvtColor(view, viewGray, COLOR_BGR2GRAY); cornerSubPix(viewGray, pointBuf, Size(11, 11), Size(-1, -1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1)); } if (mode == CAPTURING && // For camera only take new samples after delay time (!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay*1e-3*CLOCKS_PER_SEC)) { imagePoints.push_back(pointBuf); prevTimestamp = clock(); blinkOutput = s.inputCapture.isOpened(); } // Draw the corners. drawChessboardCorners(view, s.boardSize, Mat(pointBuf), found); } //! [pattern_found] //----------------------------- Output Text ------------------------------------------------ //! [output_text] string msg = (mode == CAPTURING) ? "100/100" : mode == CALIBRATED ? "Calibrated" : "Press 'g' to start"; int baseLine = 0; Size textSize = getTextSize(msg, 1, 1, 1, &baseLine); Point textOrigin(view.cols - 2 * textSize.width - 10, view.rows - 2 * baseLine - 10); if (mode == CAPTURING) { if (s.showUndistorsed) msg = format("%d/%d Undist", (int)imagePoints.size(), s.nrFrames); else msg = format("%d/%d", (int)imagePoints.size(), s.nrFrames); } putText(view, msg, textOrigin, 1, 1, mode == CALIBRATED ? GREEN : RED); if (blinkOutput) bitwise_not(view, view); //! [output_text] //------------------------- Video capture output undistorted ------------------------------ //! [output_undistorted] if (mode == CALIBRATED && s.showUndistorsed) { Mat temp = view.clone(); undistort(temp, view, cameraMatrix, distCoeffs); } //! [output_undistorted] //------------------------------ Show image and check for input commands ------------------- //! [await_input] namedWindow("Image View" + to_string(counter), WINDOW_NORMAL); resizeWindow("Image View" + to_string(counter), 640, 480); imshow("Image View" + to_string(counter), view); char key = (char)waitKey(s.inputCapture.isOpened() ? 50 : s.delay); cout << "Image " << to_string(counter) << " Completed" << endl; counter++; if (key == ESC_KEY) break; if (key == 'u' && mode == CALIBRATED) s.showUndistorsed = !s.showUndistorsed; if (s.inputCapture.isOpened() && key == 'g') { mode = CAPTURING; imagePoints.clear(); } //! [await_input] } // -----------------------Show the undistorted image for the image list ------------------------ //! [show_results] if (s.inputType == Settings::IMAGE_LIST && s.showUndistorsed) { Mat view, rview, map1, map2; initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2); m_mainMap1 = map1; m_mainMap2 = map2; for (size_t i = 0; i < s.imageList.size(); i++) { view = imread(s.imageList[i], 1); if (view.empty()) continue; remap(view, rview, map1, map2, INTER_LINEAR); imshow("Image View", rview); char c = (char)waitKey(); if (c == ESC_KEY || c == 'q' || c == 'Q') break; } } //! [show_results] // return 0; }
void PCHeaderCreate( char *include_file ) /***************************************/ { char * volatile pch_fname; // must be preserved by setjmp() int status; auto jmp_buf restore_state; #ifndef NDEBUG clock_t start; clock_t stop; start = clock(); #endif if( ErrCount != 0 ) { return; } if( CompFlags.fhr_switch_used ) { // treat any .PCH as read-only (do not create one) return; } pch_fname = PCHFileName(); pchFile = sopen4( pch_fname, O_RDWR | O_BINARY | O_CREAT | O_TRUNC, SH_DENYRW, PMODE_RW ); if( pchFile == -1 ) { CErr2p( ERR_PCH_CREATE_ERROR, pch_fname ); return; } bufferPosition = 0; ioBuffer = CMemAlloc( IO_BUFFER_SIZE ); bufferCursor = ioBuffer; amountLeft = IO_BUFFER_SIZE; abortData = &restore_state; status = setjmp( restore_state ); if( status == 0 ) { unsigned long brinf_posn; if( CompFlags.pch_debug_info_opt ) { pchDebugInfoName = CppPCHDebugInfoName( include_file ); } dumpHeader(); dumpCheckData( include_file ); execInitFunctions( TRUE ); execControlFunctions( TRUE, writeFunctions ); execFiniFunctions( TRUE ); brinf_posn = BrinfPch( pchFile ); PCHFlushBuffer(); // keep this PCH file pch_fname = NULL; setOKHeader( brinf_posn ); } else { CErr1( ERR_PCH_WRITE_ERROR ); } abortData = NULL; CMemFreePtr( &ioBuffer ); close( pchFile ); if( pch_fname != NULL ) { // write error occurred; delete PCH file remove( pch_fname ); } else { if( CompFlags.pch_debug_info_opt ) { CompFlags.pch_debug_info_write = TRUE; CompFlags.all_debug_type_names = TRUE; } } #ifndef NDEBUG stop = clock(); printf( "%u ticks to parse header\n", (unsigned)( start - start_parse ) ); printf( "%u ticks to save pre-compiled header\n", (unsigned)( stop - start ) ); #endif }
int main(int argc, const char *argv[]) { FILE *fp; sauchar_t *T; saidx_t *SA; saidx_t n; clock_t start, finish; #if HAVE_SYS_STAT_H struct stat s; #endif /* Check argument. */ if((argc != 2) || (strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0)) { fprintf(stderr, "suftest, a suffixsort tester, version %s.\n" , divsufsort_version()); fprintf(stderr, "usage: %s FILE\n\n" , argv[0]); exit(EXIT_FAILURE); } /* Get a file's status information. */ #if HAVE_SYS_STAT_H if(stat(argv[1], &s) != 0) { fprintf(stderr, "%s: Cannot stat file `%s': ", argv[0], argv[1]); perror(NULL); exit(EXIT_FAILURE); } n = s.st_size; #endif /* Open a file for reading. */ if((fp = fopen(argv[1], "rb")) == NULL) { fprintf(stderr, "%s: Cannot open file `%s': ", argv[0], argv[1]); perror(NULL); exit(EXIT_FAILURE); } #if !HAVE_SYS_STAT_H fseek(fp, 0, SEEK_END); n = ftell(fp); rewind(fp); #endif /* Allocate n+4(n+1) bytes of memory. */ if(((T = malloc(n * sizeof(sauchar_t))) == NULL) || ((SA = malloc((n + 1) * sizeof(saidx_t))) == NULL)) { fprintf(stderr, "%s: Cannot allocate memory.\n", argv[0]); exit(EXIT_FAILURE); } /* Read n bytes of data. */ if(fread(T, sizeof(sauchar_t), n, fp) != n) { fprintf(stderr, "%s: %s `%s': ", argv[0], (ferror(fp) || !feof(fp)) ? "Cannot read from" : "Unexpected EOF in", argv[1]); perror(NULL); exit(EXIT_FAILURE); } fclose(fp); /* Construct the suffix array. */ fprintf(stderr, "%s: %d bytes ... ", argv[1], (int)n); start = clock(); divsufsort(T, SA, n); finish = clock(); fprintf(stderr, "%.4f sec\n", (double)(finish - start) / (double)CLOCKS_PER_SEC); /* Check the suffix array. */ if(sufcheck(T, SA, n, 3) != 0) { exit(EXIT_FAILURE); } /* Deallocate memory. */ free(SA); free(T); return 0; }
pch_absorb PCHeaderAbsorb( char *include_file ) /*********************************************/ { pch_absorb ret; int status; auto jmp_buf restore_state; #ifndef NDEBUG clock_t start; clock_t stop; start = clock(); #endif if( ErrCount != 0 ) { return( PCHA_ERRORS_PRESENT ); } if( CompFlags.fhw_switch_used ) { return( PCHA_IGNORE ); } pchFile = sopen3( PCHFileName(), O_RDONLY | O_BINARY, SH_DENYWR ); if( pchFile == -1 ) { return( PCHA_NOT_PRESENT ); } ioBuffer = CMemAlloc( IO_BUFFER_SIZE ); pch_buff_eob = ioBuffer + IO_BUFFER_SIZE; pch_buff_cur = pch_buff_eob; ret = PCHA_OK; abortData = &restore_state; status = setjmp( restore_state ); if( status == 0 ) { if( initialRead() == 0 ) { ret = PCHA_NOT_PRESENT; } else { auto precompiled_header_header header; #ifdef OPT_BR unsigned long br_posn; #endif PCHReadVar( header ); #ifdef OPT_BR br_posn = header.browse_info; #endif if( headerIsOK( &header ) ) { if( ! stalePCH( include_file ) ) { execInitFunctions( FALSE ); execControlFunctions( FALSE, readFunctions ); execFiniFunctions( FALSE ); #ifdef OPT_BR if( 0 != br_posn ) { BrinfPchRead(); } #endif } else { ret = PCHA_STALE; } } else { pchWarn( WARN_PCH_CONTENTS_HEADER_ERROR ); ret = PCHA_HEADER; } } } else { CErr1( ERR_PCH_READ_ERROR ); } abortData = NULL; CMemFreePtr( &ioBuffer ); close( pchFile ); if( CompFlags.pch_debug_info_opt && ret == PCHA_OK ) { CompFlags.pch_debug_info_read = TRUE; } #ifndef NDEBUG stop = clock(); printf( "%u ticks to load pre-compiled header\n", (unsigned)( stop - start ) ); #endif return( ret ); }
void Lines::draw() { //Draw, calls update when required Geometry::draw(); if (drawcount == 0) return; // Undo any scaling factor for arrow drawing... glPushMatrix(); if (view->scale[0] != 1.0 || view->scale[1] != 1.0 || view->scale[2] != 1.0) glScalef(1.0/view->scale[0], 1.0/view->scale[1], 1.0/view->scale[2]); //Draw any 3d rendered tubes tris->draw(); // Re-Apply scaling factors glPopMatrix(); // Draw using vertex buffer object glPushAttrib(GL_ENABLE_BIT); clock_t t0 = clock(); double time; int stride = 3 * sizeof(float) + sizeof(Colour); //3+3+2 vertices, normals, texCoord + 32-bit colour int offset = 0; if (geom.size() > 0 && elements > 0 && glIsBuffer(vbo)) { glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexPointer(3, GL_FLOAT, stride, (GLvoid*)0); // Load vertex x,y,z only glColorPointer(4, GL_UNSIGNED_BYTE, stride, (GLvoid*)(3*sizeof(float))); // Load rgba, offset 3 float glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); //Disable depth test on 2d models if (view->is3d) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); for (unsigned int i=0; i<geom.size(); i++) { Properties& props = geom[i]->draw->properties; if (drawable(i) && props.getBool("flat", true) && !props["tubes"]) { //Set draw state setState(i, drawstate.prog[lucLineType]); //Lines specific state float scaling = props["scalelines"]; //Don't apply object scaling to internal lines objects if (!internal) scaling *= (float)props["scaling"]; float lineWidth = (float)props["linewidth"] * scaling * view->scale2d; //Include 2d scale factor if (lineWidth <= 0) lineWidth = scaling; glLineWidth(lineWidth); if (props["link"]) glDrawArrays(GL_LINE_STRIP, offset, counts[i]); else glDrawArrays(GL_LINES, offset, counts[i]); } offset += counts[i]; } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } glBindBuffer(GL_ARRAY_BUFFER, 0); GL_Error_Check; //Restore state glPopAttrib(); glBindTexture(GL_TEXTURE_2D, 0); time = ((clock()-t0)/(double)CLOCKS_PER_SEC); if (time > 0.05) debug_print(" %.4lf seconds to draw %d lines\n", time, offset); GL_Error_Check; }
int jiveL_dispatch_event(lua_State *L) { Uint32 r = 0; Uint32 t0 = 0, t1 = 0; clock_t c0 = 0, c1 = 0; /* stack is: * 1: framework * 2: widget * 3: event */ if (perfwarn.event) { t0 = jive_jiffies(); c0 = clock(); } lua_pushcfunction(L, jive_traceback); /* push traceback function */ // call global event listeners if (jive_getmethod(L, 1, "_event")) { lua_pushvalue(L, 1); // framework lua_pushvalue(L, 3); // event lua_pushboolean(L, 1); // global listeners if (lua_pcall(L, 3, 1, 4) != 0) { LOG_WARN(log_ui_draw, "error in event function:\n\t%s\n", lua_tostring(L, -1)); return 0; } r |= lua_tointeger(L, -1); lua_pop(L, 1); } /* by default send the event to the top window. fetch that top * window here in case the global event handler has modified * the window stack. */ if (lua_isnil(L, 2)) { lua_getfield(L, 1, "windowStack"); if (lua_objlen(L, -1) == 0) { lua_pop(L, 1); return 0; } lua_rawgeti(L, -1, 1); lua_replace(L, 2); } // call widget event handler, unless the event is consumed if (!(r & JIVE_EVENT_CONSUME) && jive_getmethod(L, 2, "_event")) { lua_pushvalue(L, 2); // widget lua_pushvalue(L, 3); // event if (lua_pcall(L, 2, 1, 4) != 0) { LOG_WARN(log_ui_draw, "error in event function:\n\t%s\n", lua_tostring(L, -1)); return 0; } r |= lua_tointeger(L, -1); lua_pop(L, 1); } // call unused event listeners, unless the event is consumed if (!(r & JIVE_EVENT_CONSUME) && jive_getmethod(L, 1, "_event")) { lua_pushvalue(L, 1); // framework lua_pushvalue(L, 3); // event lua_pushboolean(L, 0); // unused listeners if (lua_pcall(L, 3, 1, 4) != 0) { LOG_WARN(log_ui_draw, "error in event function:\n\t%s\n", lua_tostring(L, -1)); return 0; } r |= lua_tointeger(L, -1); lua_pop(L, 1); } if (perfwarn.event) { t1 = jive_jiffies(); c1 = clock(); if (t1-t0 > perfwarn.event) { printf("process_event > %dms: %4dms (%dms) ", perfwarn.event, t1-t0, (int)((c1-c0) * 1000 / CLOCKS_PER_SEC)); lua_getglobal(L, "tostring"); lua_pushvalue(L, 2); lua_call(L, 1, 1); lua_pushcfunction(L, jiveL_event_tostring); lua_pushvalue(L, 3); lua_call(L, 1, 1); printf("[widget:%s event:%s]\n", lua_tostring(L, -2), lua_tostring(L, -1)); lua_pop(L, 2); } } lua_pushinteger(L, r); return 1; }