static QList<double> _calcJenksBreaks( QList<double> values, int classes, double minimum, double maximum, int maximumSize = 1000 ) { // Jenks Optimal (Natural Breaks) algorithm // Based on the Jenks algorithm from the 'classInt' package available for // the R statistical prgramming language, and from Python code from here: // http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/ // and is based on a JAVA and Fortran code available here: // https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html // Returns class breaks such that classes are internally homogeneous while // assuring heterogeneity among classes. if ( classes <= 1 ) { return QList<double>() << maximum; } if ( classes >= values.size() ) { return values; } QVector<double> sample; // if we have lots of values, we need to take a random sample if ( values.size() > maximumSize ) { // for now, sample at least maximumSize values or a 10% sample, whichever // is larger. This will produce a more representative sample for very large // layers, but could end up being computationally intensive... qsrand( time( 0 ) ); sample.resize( qMax( maximumSize, values.size() / 10 ) ); QgsDebugMsg( QString( "natural breaks (jenks) sample size: %1" ).arg( sample.size() ) ); QgsDebugMsg( QString( "values:%1" ).arg( values.size() ) ); sample[ 0 ] = minimum; sample[ 1 ] = maximum;; for ( int i = 2; i < sample.size(); i++ ) { // pick a random integer from 0 to n double r = qrand(); int j = floor( r / RAND_MAX * ( values.size() - 1 ) ); sample[ i ] = values[ j ]; } } else { sample = values.toVector(); } int n = sample.size(); // sort the sample values qSort( sample ); QVector< QVector<int> > matrixOne( n + 1 ); QVector< QVector<double> > matrixTwo( n + 1 ); for ( int i = 0; i <= n; i++ ) { matrixOne[i].resize( classes + 1 ); matrixTwo[i].resize( classes + 1 ); } for ( int i = 1; i <= classes; i++ ) { matrixOne[0][i] = 1; matrixOne[1][i] = 1; matrixTwo[0][i] = 0.0; for ( int j = 2; j <= n; j++ ) { matrixTwo[j][i] = std::numeric_limits<double>::max(); } } for ( int l = 2; l <= n; l++ ) { double s1 = 0.0; double s2 = 0.0; int w = 0; double v = 0.0; for ( int m = 1; m <= l; m++ ) { int i3 = l - m + 1; double val = sample[ i3 - 1 ]; s2 += val * val; s1 += val; w++; v = s2 - ( s1 * s1 ) / ( double ) w; int i4 = i3 - 1; if ( i4 != 0 ) { for ( int j = 2; j <= classes; j++ ) { if ( matrixTwo[l][j] >= v + matrixTwo[i4][j - 1] ) { matrixOne[l][j] = i4; matrixTwo[l][j] = v + matrixTwo[i4][j - 1]; } } } } matrixOne[l][1] = 1; matrixTwo[l][1] = v; } QVector<double> breaks( classes ); breaks[classes-1] = sample[n-1]; for ( int j = classes, k = n; j >= 2; j-- ) { int id = matrixOne[k][j] - 1; breaks[j - 2] = sample[id]; k = matrixOne[k][j] - 1; } return breaks.toList(); } //_calcJenksBreaks
int CGridManager::GetGridHeight() { return (int) floor(GridDimensions.z); }
bool IPLCanny::processInputData(IPLImage* image , int, bool useOpenCV) { // delete previous result delete _result; _result = NULL; delete _binaryImage; _binaryImage = NULL; int width = image->width(); int height = image->height(); _result = new IPLImage( image->type(), width, height ); _binaryImage = new IPLImage( IPLData::IMAGE_BW, width, height ); // get properties int window = getProcessPropertyInt("window"); double sigma = getProcessPropertyDouble("sigma"); double lowThreshold = getProcessPropertyDouble("lowThreshold"); double highThreshold = getProcessPropertyDouble("highThreshold"); std::stringstream s; s << "Window: "; s << window; addInformation(s.str()); //! @todo currently only the opencv implementation works if(useOpenCV || true) { notifyProgressEventHandler(-1); cv::Mat input; cv::Mat output; cvtColor(image->toCvMat(), input, CV_BGR2GRAY); cv::Canny(input, output, lowThreshold*255, highThreshold*255, window); delete _result; _result = new IPLImage(output); return true; } return false; // Create a Gaussian 1D filter int N = ceil( sigma * sqrt( 2.0*log( 1.0/0.015 ) ) + 1.0 ); double ssq = sigma*sigma; double* gau = new double [window]; double* dgau = new double [window]; for( int k = -N; k <= N; ++k ) { gau[k+N] = gauss ( (double)k, ssq ); dgau[k+N] = dGauss ( (double)k, 0, ssq ); } // Create a directional derivative of 2D Gaussian (along X-axis) // Since the result is symmetric along X, we can get the derivative along // Y-axis simply by transposing the result for X direction. // DoubleImage* dgau = new DoubleImage( window, window ); // for( int y = -N; y <= N; ++y ) // for( int x = -N; x <= N; ++x ) // dgau->f(x+N, y+N) = dGauss( x, y, ssq ); int progress = 0; int maxProgress = width * image->getNumberOfPlanes(); int nrOfPlanes = image->getNumberOfPlanes(); //#pragma omp parallel for for( int planeNr=0; planeNr < nrOfPlanes; planeNr++ ) { IPLImagePlane* plane = image->plane( planeNr ); IPLImagePlane* newplane = _result->plane( planeNr ); // ******** Gaussian filtering of input image IPLImagePlane* gI = new IPLImagePlane( width, height ); // horizontal run (normalizing original image) IPLImagePlane* tmpI = new IPLImagePlane( width, height ); for(int x=0; x<width; x++) { // progress notifyProgressEventHandler(100*progress++/maxProgress); for(int y=0; y<height; y++) { double sum = 0; int i = 0; for( int kx=-N; kx<=N; kx++ ) { double img = (double) plane->bp(x+kx, y); sum += (img * gau[i++]); } tmpI->p(x,y) = (double) (sum); } } // vertiacl run for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { double sum = 0; int i = 0; for( int ky=-N; ky<=N; ky++ ) { double img = tmpI->bp(x, y+ky); sum += (img * gau[i++]); } gI->p(x,y) = sum; } } //delete tmpI; // ******** Apply directional derivatives ... // ... in x-direction IPLImagePlane* dx = new IPLImagePlane( width, height ); for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { dx->p(x,y) = 0.0; for( int k=1; k<N; k++ ) { dx->p(x,y) += ( gI->bp(x-k,y) - gI->bp(x+k,y) ) * dgau[k]; } } } // double maxVal = 0.0; // for(int x=0; x<width; x++) // for(int y=0; y<height; y++) // if( dx->f(x,y) > maxVal ) maxVal = dx->f(x,y); // ... in y-direction IPLImagePlane* dy = new IPLImagePlane( width, height ); for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { dy->p(x,y) = 0.0; for( int k=1; k<N; k++ ) { dy->p(x,y) += ( gI->bp(x,y-k) - gI->bp(x,y+k) ) * dgau[k]; } } } // ******** Compute magnitude and binarization thresholds IPLImagePlane* mag = new IPLImagePlane( width, height ); double magMax = 0.0; double magMin = 999999999.0; for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { double val = sqrt( dx->p(x,y)*dx->p(x,y) + dy->p(x,y)*dy->p(x,y) ); mag->p(x,y) = val; if( val > magMax ) magMax = val; if( val < magMin ) magMin = val; } } //// ******** Non-maxima suppression - edge pixels should be a local maximum _orientedImage = new IPLOrientedImage( width, height ); for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { double ix = dx->p(x,y); double iy = dy->p(x,y); double g = mag->p(x,y); // determine 4-neighbor direction of gradient int dir4 = 0; if( (iy<=0.0 && ix>-iy) || (iy>=0.0 && ix<-iy) ) dir4 = 1; else if( (ix>0.0 && -iy>=ix) || (ix<0.0 && -iy<=ix) ) dir4 = 2; else if( (ix<=0.0 && ix>iy) || (ix>=0.0 && ix<iy) ) dir4 = 3; else if( (iy<0.0 && ix<=iy) || (iy>0.0 && ix>=iy) ) dir4 = 4; else continue; double gradmag1, gradmag2, d; switch(dir4) { case 1: d = std::fabs(iy/ix); gradmag1 = mag->bp(x+1,y)*(1-d) + mag->bp(x+1,y-1)*d; gradmag2 = mag->bp(x-1,y)*(1-d) + mag->bp(x-1,y+1)*d; break; case 2: d = std::fabs(ix/iy); gradmag1 = mag->bp(x,y-1)*(1-d) + mag->bp(x+1,y-1)*d; gradmag2 = mag->bp(x,y+1)*(1-d) + mag->bp(x-1,y+1)*d; break; case 3: d = std::fabs(ix/iy); gradmag1 = mag->bp(x,y-1)*(1-d) + mag->bp(x-1,y-1)*d; gradmag2 = mag->bp(x,y+1)*(1-d) + mag->bp(x+1,y+1)*d; break; case 4: d = std::fabs(iy/ix); gradmag1 = mag->bp(x-1,y)*(1-d) + mag->bp(x-1,y-1)*d; gradmag2 = mag->bp(x+1,y)*(1-d) + mag->bp(x+1,y+1)*d; break; } if( g > gradmag1 && g > gradmag2 ) { _orientedImage->magnitude(x,y) = g; _orientedImage->phase(x,y) = atan2(iy,ix); } } } for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { _orientedImage->magnitude(x,y) /= magMax; double val = _orientedImage->magnitude(x,y)*255.0; // double val = mag->f(x,y)/magMax*255.0; if (val > 255.0 ) val = 255.0; if (val < 0.0 ) val = 0.0; newplane->p(x,y) = (unsigned char ) val; } } // ******** Binarize with hysteresis threshold double hist[ 256 ]; for( int i=0; i<256; ++i ) hist[i] = 0; int pixCount = 0; for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { if( _orientedImage->magnitude(x,y) > 0.0 ) { int index = floor( _orientedImage->magnitude(x,y)*256.0+0.5 ); ++hist[ index ]; ++pixCount; } } } double PercentOfPixelsNotEdges = 0.7*pixCount; double highThresh = 0.0; double cumsum = 0.0; for( int i=0; i<256; ++i ) { cumsum += hist[i]; if( cumsum > PercentOfPixelsNotEdges ) { highThresh = (double)i / 256.0; break; } } double lowThresh = 0.4 * highThresh; IPLImagePlane* binPlane = _binaryImage->plane( 0 ); for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { if(_orientedImage->magnitude(x,y) >= highThresh) trace(x, y, lowThresh, _orientedImage, binPlane); } } //delete dx; //delete dy; //delete gI; thinning(_orientedImage, binPlane, newplane ); } //delete [] gau; //delete [] dgau; return true; }
KFR_SINTRIN f32sse fract(f32sse x) { return x - floor(x); }
inT32 row_words( //compute space size TO_BLOCK *block, //block it came from TO_ROW *row, //row to operate on inT32 maxwidth, //max expected space size FCOORD rotation, //for drawing BOOL8 testing_on //for debug ) { BOOL8 testing_row; //contains testpt BOOL8 prev_valid; //if decent size BOOL8 this_valid; //current blob big enough inT32 prev_x; //end of prev blob inT32 min_gap; //min interesting gap inT32 cluster_count; //no of clusters inT32 gap_index; //which cluster inT32 smooth_factor; //for smoothing stats BLOBNBOX *blob; //current blob float lower, upper; //clustering parameters float gaps[3]; //gap clusers ICOORD testpt; TBOX blob_box; //bounding box //iterator BLOBNBOX_IT blob_it = row->blob_list (); STATS gap_stats (0, maxwidth); STATS cluster_stats[4]; //clusters testpt = ICOORD (textord_test_x, textord_test_y); smooth_factor = (inT32) (block->xheight * textord_wordstats_smooth_factor + 1.5); // if (testing_on) // tprintf("Row smooth factor=%d\n",smooth_factor); prev_valid = FALSE; prev_x = -MAX_INT32; testing_row = FALSE; for (blob_it.mark_cycle_pt (); !blob_it.cycled_list (); blob_it.forward ()) { blob = blob_it.data (); blob_box = blob->bounding_box (); if (blob_box.contains (testpt)) testing_row = TRUE; gap_stats.add (blob_box.width (), 1); } min_gap = (inT32) floor (gap_stats.ile (textord_words_width_ile)); gap_stats.clear (); for (blob_it.mark_cycle_pt (); !blob_it.cycled_list (); blob_it.forward ()) { blob = blob_it.data (); if (!blob->joined_to_prev ()) { blob_box = blob->bounding_box (); // this_valid=blob_box.width()>=min_gap; this_valid = TRUE; if (this_valid && prev_valid && blob_box.left () - prev_x < maxwidth) { gap_stats.add (blob_box.left () - prev_x, 1); } prev_x = blob_box.right (); prev_valid = this_valid; } } if (gap_stats.get_total () == 0) { row->min_space = 0; //no evidence row->max_nonspace = 0; return 0; } gap_stats.smooth (smooth_factor); lower = row->xheight * textord_words_initial_lower; upper = row->xheight * textord_words_initial_upper; cluster_count = gap_stats.cluster (lower, upper, textord_spacesize_ratioprop, 3, cluster_stats); while (cluster_count < 2 && ceil (lower) < floor (upper)) { //shrink gap upper = (upper * 3 + lower) / 4; lower = (lower * 3 + upper) / 4; cluster_count = gap_stats.cluster (lower, upper, textord_spacesize_ratioprop, 3, cluster_stats); } if (cluster_count < 2) { row->min_space = 0; //no evidence row->max_nonspace = 0; return 0; } for (gap_index = 0; gap_index < cluster_count; gap_index++) gaps[gap_index] = cluster_stats[gap_index + 1].ile (0.5); //get medians if (cluster_count > 2) { if (testing_on && textord_show_initial_words) { tprintf ("Row at %g has 3 sizes of gap:%g,%g,%g\n", row->intercept (), cluster_stats[1].ile (0.5), cluster_stats[2].ile (0.5), cluster_stats[3].ile (0.5)); } lower = gaps[0]; if (gaps[1] > lower) { upper = gaps[1]; //prefer most frequent if (upper < block->xheight * textord_words_min_minspace && gaps[2] > gaps[1]) { upper = gaps[2]; } } else if (gaps[2] > lower && gaps[2] >= block->xheight * textord_words_min_minspace) upper = gaps[2]; else if (lower >= block->xheight * textord_words_min_minspace) { upper = lower; //not nice lower = gaps[1]; if (testing_on && textord_show_initial_words) { tprintf ("Had to switch most common from lower to upper!!\n"); gap_stats.print(); } } else { row->min_space = 0; //no evidence row->max_nonspace = 0; return 0; } } else { if (gaps[1] < gaps[0]) { if (testing_on && textord_show_initial_words) { tprintf ("Had to switch most common from lower to upper!!\n"); gap_stats.print(); } lower = gaps[1]; upper = gaps[0]; } else { upper = gaps[1]; lower = gaps[0]; } } if (upper < block->xheight * textord_words_min_minspace) { row->min_space = 0; //no evidence row->max_nonspace = 0; return 0; } if (upper * 3 < block->min_space * 2 + block->max_nonspace || lower * 3 > block->min_space * 2 + block->max_nonspace) { if (testing_on && textord_show_initial_words) { tprintf ("Disagreement between block and row at %g!!\n", row->intercept ()); tprintf ("Lower=%g, upper=%g, Stats:\n", lower, upper); gap_stats.print(); } } row->min_space = (inT32) ceil (upper - (upper - lower) * textord_words_definite_spread); row->max_nonspace = (inT32) floor (lower + (upper - lower) * textord_words_definite_spread); row->space_threshold = (row->max_nonspace + row->min_space) / 2; row->space_size = upper; row->kern_size = lower; if (testing_on && textord_show_initial_words) { if (testing_row) { tprintf ("GAP STATS\n"); gap_stats.print(); tprintf ("SPACE stats\n"); cluster_stats[2].print_summary(); tprintf ("NONSPACE stats\n"); cluster_stats[1].print_summary(); } tprintf ("Row at %g has minspace=%d(%g), max_non=%d(%g)\n", row->intercept (), row->min_space, upper, row->max_nonspace, lower); } return cluster_stats[2].get_total (); }
wxString mmReportSummaryStocks::getHTMLText() { RefreshData(); mmHTMLBuilder hb; hb.init(); hb.addDivContainer(); hb.addHeader(2, m_title); hb.addDateNow(); hb.addLineBreak(); hb.addDivRow(); hb.addDivCol17_67(); for (const auto& acct : m_stocks) { const Model_Account::Data* account = Model_Account::instance().get(acct.id); const Model_Currency::Data* currency = Model_Account::currency(account); hb.addHeader(3, acct.name); hb.startTable(); display_header(hb); hb.startTbody(); for (const auto& entry : acct.data) { hb.startTableRow(); hb.addTableCell(entry.name); hb.addTableCell(entry.symbol); hb.addTableCellDate(entry.date); hb.addTableCell(Model_Account::toString(entry.qty, account, floor(entry.qty) ? 0 : 4), true); hb.addCurrencyCell(entry.purchase, currency, 4); hb.addCurrencyCell(entry.current, currency, 4); hb.addCurrencyCell(entry.commission, currency, 4); hb.addCurrencyCell(entry.gainloss, currency); hb.addCurrencyCell(entry.value, currency); hb.endTableRow(); } hb.endTbody(); hb.startTfoot(); hb.startTotalTableRow(); hb.addTableCell(_("Total:")); hb.addEmptyTableCell(6); hb.addCurrencyCell(acct.gainloss, currency); hb.addCurrencyCell(acct.total, currency); hb.endTableRow(); hb.endTfoot(); hb.endTable(); } hb.addDivCol17_67(); hb.addHeader(3, _("Grand Total:")); hb.startTable(); hb.startThead(); hb.startTableRow(); hb.addTableHeaderCell(_("Gain/Loss"), true); hb.addTableHeaderCell(_("Current Value"), true); hb.endTableRow(); hb.endThead(); hb.startTfoot(); hb.startTotalTableRow(); hb.addCurrencyCell(m_gain_loss_sum_total); hb.addCurrencyCell(m_stock_balance); hb.endTableRow(); hb.endTfoot(); hb.endTable(); hb.endDiv(); hb.endDiv(); hb.endDiv(); hb.endDiv(); hb.end(); return hb.getHTMLText(); }
//move within divisons and return true, if at the end bool Camera::nextPixel() { Coord temp = this->getVPos(); short tWidth = this->getVWidth(); short tHeight = this->getVHeight(); short tDivSize = this->getDivSize(); if (this->vDivSize == 1) { //normal method, moving from pixel to pixel //increment coordinates if ((temp.x + 1) == this->getVWidth()) { //cout << "Finished line " << temp.y << endl; temp.y = (temp.y + 1) % (this->getVHeight()); //next y-pixel } temp.x = (temp.x + 1) % (this->getVWidth()); //next x-pixel } else { //using divisions, moving within divisions //move to next pixel normally temp.x++; //if not within the same division, move back divSize pixel and up 1 pixel if (temp.x % tDivSize == 0) { temp.x -= tDivSize; if ((temp.y + 1) % tDivSize == 0) { //next divison this->nextDiv(); //calculate bottom left of new division temp.x = this->getDivNo() % ((unsigned int) ceil(tWidth/tDivSize)) * tDivSize; temp.y = floor(this->getDivNo() / ceil(tWidth/tDivSize)) * tDivSize; } else temp.y++; } //if at the end of the line, move back width % divSize pixel and up 1 pixel else if (temp.x == tWidth) { temp.x -= tWidth % tDivSize; if ((temp.y + 1) % tDivSize == 0) { //next divison this->nextDiv(); //calculate bottom left of new division temp.x = this->getDivNo() % ((unsigned int) ceil(tWidth/tDivSize)) * tDivSize; temp.y = floor(this->getDivNo() / ceil(tWidth/tDivSize)) * tDivSize; } else if ((temp.y == tHeight)) { //arrived at top right temp = nullCoord; } else temp.y++; } //make sure it does not get out of vPos temp.x = temp.x % tWidth; temp.y = temp.y % tHeight; } //apply this->setVPos(temp); if (temp == nullCoord) return true; //is at (0,0) again else return false; //is not at the end yet }
int ReportPulseEvent(float PulsePower,float MeanPower, float period, int time_bin,int freq_bin, float snr, float thresh, float *folded_pot, int scale, int write_pulse) { PULSE_INFO pi; pulse pulse; int retval=0, i, len_prof=static_cast<int>(floor(period)); float step,norm,index,MinPower=PulsePower*MeanPower*scale; // debug possible heap corruption -- jeffc #ifdef _WIN32 BOINCASSERT(_CrtCheckMemory()); #endif // pulse info pi.score=snr/thresh; pi.p.peak_power=PulsePower-1; pi.p.mean_power=MeanPower; pi.p.fft_len=ChirpFftPairs[analysis_state.icfft].FftLen; pi.p.chirp_rate=ChirpFftPairs[analysis_state.icfft].ChirpRate; pi.p.period=static_cast<float>(period*static_cast<double>(pi.p.fft_len)/swi.subband_sample_rate); pi.p.snr = snr; pi.p.thresh = thresh; pi.p.len_prof = len_prof; pi.freq_bin=freq_bin; pi.time_bin=time_bin; pi.p.freq=cnvt_bin_hz(freq_bin, pi.p.fft_len); double t_offset=(static_cast<double>(time_bin)+0.5) *static_cast<double>(pi.p.fft_len)/ swi.subband_sample_rate; pi.p.detection_freq=calc_detection_freq(pi.p.freq,pi.p.chirp_rate,t_offset); pi.p.time=swi.time_recorded+t_offset/86400.0; time_to_ra_dec(pi.p.time, &pi.p.ra, &pi.p.decl); for (i=0;i<len_prof;i++) { if (folded_pot[i]<MinPower) MinPower=folded_pot[i]; } norm=255.0f/((PulsePower*MeanPower*scale-MinPower)); // Populate the min and max PoT arrays. These are only used // for graphics. #ifdef BOINC_APP_GRAPHICS if (!nographics()) { step=static_cast<float>(len_prof)/swi.analysis_cfg.pulse_pot_length; index=0; for (i=0;i<swi.analysis_cfg.pulse_pot_length;i++) { pi.pot_min[i]=255; pi.pot_max[i]=0; int j; for (j=0; j<step; j++) { unsigned int pot = static_cast<unsigned int>((folded_pot[static_cast<int>(floor(index))+j]-MinPower)*norm); if (pot<pi.pot_min[i]) { pi.pot_min[i]=pot; } if (pi.pot_min[i] >= 256) pi.pot_min[i] = 255; // kludge until we fix the assert failures BOINCASSERT(pi.pot_min[i] < 256); if (pot>pi.pot_max[i]) pi.pot_max[i]=pot; if (pi.pot_max[i] >= 256) pi.pot_max[i] = 255; // kludge until we fix the assert failures BOINCASSERT(pi.pot_max[i] < 256); } index+=step; } } #endif // Populate the result PoT if the folded PoT will fit. if (pi.p.len_prof < swi.analysis_cfg.pulse_pot_length) { pi.p.pot.resize(len_prof); for (i=0;i<len_prof;i++) { pi.p.pot[i] = (char)((folded_pot[i]-MinPower)*norm); } } else { pi.p.pot.clear(); } // Update gdata pulse info regardless of whether it is the // best thus far. If a pulse has made it this far, display it. #ifdef BOINC_APP_GRAPHICS if (!nographics()) sah_graphics->pi.copy(&pi); #endif // best thus far ? if (pi.score>best_pulse->score) { *best_pulse=pi; } if (write_pulse) { if (signal_count > swi.analysis_cfg.max_signals) { SETIERROR(RESULT_OVERFLOW,"in ReportPulseEvent"); } //for (i=0;i<len_prof;i++) { // sprintf(&pi.p.pot[i], "%02x",(int)((folded_pot[i]-MinPower)*norm)); // } retval = outfile.printf("%s", pi.p.print_xml(0,0,1).c_str()); if (retval >= 0) { outfile.printf("\n"); } if (retval < 0) { SETIERROR(WRITE_FAILED,"in ReportPulseEvent"); } else { signal_count++; pulse_count++; } } // debug possible heap corruption -- jeffc #ifdef _WIN32 BOINCASSERT(_CrtCheckMemory()); #endif return(retval); }
float RayTracer::fract(float val){ return (val - floor(val)); }
template <typename PointInT, typename PointOutT> void pcl::ESFEstimation<PointInT, PointOutT>::computeESF ( PointCloudIn &pc, std::vector<float> &hist) { const int binsize = 64; unsigned int sample_size = 20000; srand (static_cast<unsigned int> (time (0))); int maxindex = static_cast<int> (pc.points.size ()); int index1, index2, index3; std::vector<float> d2v, d1v, d3v, wt_d3; std::vector<int> wt_d2; d1v.reserve (sample_size); d2v.reserve (sample_size * 3); d3v.reserve (sample_size); wt_d2.reserve (sample_size * 3); wt_d3.reserve (sample_size); float h_in[binsize] = {0}; float h_out[binsize] = {0}; float h_mix[binsize] = {0}; float h_mix_ratio[binsize] = {0}; float h_a3_in[binsize] = {0}; float h_a3_out[binsize] = {0}; float h_a3_mix[binsize] = {0}; float h_d1[binsize] = {0}; float h_d3_in[binsize] = {0}; float h_d3_out[binsize] = {0}; float h_d3_mix[binsize] = {0}; float ratio=0.0; float pih = static_cast<float>(M_PI) / 2.0f; float a,b,c,s; int th1,th2,th3; int vxlcnt = 0; int pcnt1,pcnt2,pcnt3; for (size_t nn_idx = 0; nn_idx < sample_size; ++nn_idx) { // get a new random point index1 = rand()%maxindex; index2 = rand()%maxindex; index3 = rand()%maxindex; if (index1==index2 || index1 == index3 || index2 == index3) { nn_idx--; continue; } Eigen::Vector4f p1 = pc.points[index1].getVector4fMap (); Eigen::Vector4f p2 = pc.points[index2].getVector4fMap (); Eigen::Vector4f p3 = pc.points[index3].getVector4fMap (); // A3 Eigen::Vector4f v21 (p2 - p1); Eigen::Vector4f v31 (p3 - p1); Eigen::Vector4f v23 (p2 - p3); a = v21.norm (); b = v31.norm (); c = v23.norm (); s = (a+b+c) * 0.5f; if (s * (s-a) * (s-b) * (s-c) <= 0.001f) continue; v21.normalize (); v31.normalize (); v23.normalize (); //TODO: .dot gives nan's th1 = static_cast<int> (pcl_round (acos (fabs (v21.dot (v31))) / pih * (binsize-1))); th2 = static_cast<int> (pcl_round (acos (fabs (v23.dot (v31))) / pih * (binsize-1))); th3 = static_cast<int> (pcl_round (acos (fabs (v23.dot (v21))) / pih * (binsize-1))); if (th1 < 0 || th1 >= binsize) { nn_idx--; continue; } if (th2 < 0 || th2 >= binsize) { nn_idx--; continue; } if (th3 < 0 || th3 >= binsize) { nn_idx--; continue; } //pcl::PointXYZ cog(((rand()%100)-50.0f) / 100.0f,((rand()%100)-50.0f) / 100.0f,((rand()%100)-50.0f) / 100.0f); // D1 // d1v.push_back( pcl::euclideanDistance(cog, pc.points[index1]) ); // D2 d2v.push_back (pcl::euclideanDistance (pc.points[index1], pc.points[index2])); d2v.push_back (pcl::euclideanDistance (pc.points[index1], pc.points[index3])); d2v.push_back (pcl::euclideanDistance (pc.points[index2], pc.points[index3])); int vxlcnt_sum = 0; int p_cnt = 0; // IN, OUT, MIXED, Ratio line tracing, index1->index2 { const int xs = p1[0] < 0.0? static_cast<int>(floor(p1[0])+GRIDSIZE_H): static_cast<int>(ceil(p1[0])+GRIDSIZE_H-1); const int ys = p1[1] < 0.0? static_cast<int>(floor(p1[1])+GRIDSIZE_H): static_cast<int>(ceil(p1[1])+GRIDSIZE_H-1); const int zs = p1[2] < 0.0? static_cast<int>(floor(p1[2])+GRIDSIZE_H): static_cast<int>(ceil(p1[2])+GRIDSIZE_H-1); const int xt = p2[0] < 0.0? static_cast<int>(floor(p2[0])+GRIDSIZE_H): static_cast<int>(ceil(p2[0])+GRIDSIZE_H-1); const int yt = p2[1] < 0.0? static_cast<int>(floor(p2[1])+GRIDSIZE_H): static_cast<int>(ceil(p2[1])+GRIDSIZE_H-1); const int zt = p2[2] < 0.0? static_cast<int>(floor(p2[2])+GRIDSIZE_H): static_cast<int>(ceil(p2[2])+GRIDSIZE_H-1); wt_d2.push_back (this->lci (xs, ys, zs, xt, yt, zt, ratio, vxlcnt, pcnt1)); if (wt_d2.back () == 2) h_mix_ratio[static_cast<int> (pcl_round (ratio * (binsize-1)))]++; vxlcnt_sum += vxlcnt; p_cnt += pcnt1; } // IN, OUT, MIXED, Ratio line tracing, index1->index3 { const int xs = p1[0] < 0.0? static_cast<int>(floor(p1[0])+GRIDSIZE_H): static_cast<int>(ceil(p1[0])+GRIDSIZE_H-1); const int ys = p1[1] < 0.0? static_cast<int>(floor(p1[1])+GRIDSIZE_H): static_cast<int>(ceil(p1[1])+GRIDSIZE_H-1); const int zs = p1[2] < 0.0? static_cast<int>(floor(p1[2])+GRIDSIZE_H): static_cast<int>(ceil(p1[2])+GRIDSIZE_H-1); const int xt = p3[0] < 0.0? static_cast<int>(floor(p3[0])+GRIDSIZE_H): static_cast<int>(ceil(p3[0])+GRIDSIZE_H-1); const int yt = p3[1] < 0.0? static_cast<int>(floor(p3[1])+GRIDSIZE_H): static_cast<int>(ceil(p3[1])+GRIDSIZE_H-1); const int zt = p3[2] < 0.0? static_cast<int>(floor(p3[2])+GRIDSIZE_H): static_cast<int>(ceil(p3[2])+GRIDSIZE_H-1); wt_d2.push_back (this->lci (xs, ys, zs, xt, yt, zt, ratio, vxlcnt, pcnt2)); if (wt_d2.back () == 2) h_mix_ratio[static_cast<int>(pcl_round (ratio * (binsize-1)))]++; vxlcnt_sum += vxlcnt; p_cnt += pcnt2; } // IN, OUT, MIXED, Ratio line tracing, index2->index3 { const int xs = p2[0] < 0.0? static_cast<int>(floor(p2[0])+GRIDSIZE_H): static_cast<int>(ceil(p2[0])+GRIDSIZE_H-1); const int ys = p2[1] < 0.0? static_cast<int>(floor(p2[1])+GRIDSIZE_H): static_cast<int>(ceil(p2[1])+GRIDSIZE_H-1); const int zs = p2[2] < 0.0? static_cast<int>(floor(p2[2])+GRIDSIZE_H): static_cast<int>(ceil(p2[2])+GRIDSIZE_H-1); const int xt = p3[0] < 0.0? static_cast<int>(floor(p3[0])+GRIDSIZE_H): static_cast<int>(ceil(p3[0])+GRIDSIZE_H-1); const int yt = p3[1] < 0.0? static_cast<int>(floor(p3[1])+GRIDSIZE_H): static_cast<int>(ceil(p3[1])+GRIDSIZE_H-1); const int zt = p3[2] < 0.0? static_cast<int>(floor(p3[2])+GRIDSIZE_H): static_cast<int>(ceil(p3[2])+GRIDSIZE_H-1); wt_d2.push_back (this->lci (xs,ys,zs,xt,yt,zt,ratio,vxlcnt,pcnt3)); if (wt_d2.back () == 2) h_mix_ratio[static_cast<int>(pcl_round(ratio * (binsize-1)))]++; vxlcnt_sum += vxlcnt; p_cnt += pcnt3; } // D3 ( herons formula ) d3v.push_back (sqrtf (sqrtf (s * (s-a) * (s-b) * (s-c)))); if (vxlcnt_sum <= 21) { wt_d3.push_back (0); h_a3_out[th1] += static_cast<float> (pcnt3) / 32.0f; h_a3_out[th2] += static_cast<float> (pcnt1) / 32.0f; h_a3_out[th3] += static_cast<float> (pcnt2) / 32.0f; } else if (p_cnt - vxlcnt_sum < 4) { h_a3_in[th1] += static_cast<float> (pcnt3) / 32.0f; h_a3_in[th2] += static_cast<float> (pcnt1) / 32.0f; h_a3_in[th3] += static_cast<float> (pcnt2) / 32.0f; wt_d3.push_back (1); } else { h_a3_mix[th1] += static_cast<float> (pcnt3) / 32.0f; h_a3_mix[th2] += static_cast<float> (pcnt1) / 32.0f; h_a3_mix[th3] += static_cast<float> (pcnt2) / 32.0f; wt_d3.push_back (static_cast<float> (vxlcnt_sum) / static_cast<float> (p_cnt)); } } // Normalizing, get max float maxd1 = 0; float maxd2 = 0; float maxd3 = 0; for (size_t nn_idx = 0; nn_idx < sample_size; ++nn_idx) { // get max of Dx if (d1v[nn_idx] > maxd1) maxd1 = d1v[nn_idx]; if (d2v[nn_idx] > maxd2) maxd2 = d2v[nn_idx]; if (d2v[sample_size + nn_idx] > maxd2) maxd2 = d2v[sample_size + nn_idx]; if (d2v[sample_size*2 +nn_idx] > maxd2) maxd2 = d2v[sample_size*2 +nn_idx]; if (d3v[nn_idx] > maxd3) maxd3 = d3v[nn_idx]; } // Normalize and create histogram int index; for (size_t nn_idx = 0; nn_idx < sample_size; ++nn_idx) { h_d1[static_cast<int>(pcl_round (d1v[nn_idx] / maxd1 * (binsize-1)))]++ ; if (wt_d3[nn_idx] >= 0.999) // IN { index = static_cast<int>(pcl_round (d3v[nn_idx] / maxd3 * (binsize-1))); if (index >= 0 && index < binsize) h_d3_in[index]++; } else { if (wt_d3[nn_idx] <= 0.001) // OUT { index = static_cast<int>(pcl_round (d3v[nn_idx] / maxd3 * (binsize-1))); if (index >= 0 && index < binsize) h_d3_out[index]++ ; } else { index = static_cast<int>(pcl_round (d3v[nn_idx] / maxd3 * (binsize-1))); if (index >= 0 && index < binsize) h_d3_mix[index]++; } } } //normalize and create histogram for (size_t nn_idx = 0; nn_idx < d2v.size(); ++nn_idx ) { if (wt_d2[nn_idx] == 0) h_in[static_cast<int>(pcl_round (d2v[nn_idx] / maxd2 * (binsize-1)))]++ ; if (wt_d2[nn_idx] == 1) h_out[static_cast<int>(pcl_round (d2v[nn_idx] / maxd2 * (binsize-1)))]++; if (wt_d2[nn_idx] == 2) h_mix[static_cast<int>(pcl_round (d2v[nn_idx] / maxd2 * (binsize-1)))]++ ; } //float weights[10] = {1, 1, 1, 1, 1, 1, 1, 1 , 1 , 1}; float weights[10] = {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f}; hist.reserve (binsize * 10); for (int i = 0; i < binsize; i++) hist.push_back (h_a3_in[i] * weights[0]); for (int i = 0; i < binsize; i++) hist.push_back (h_a3_out[i] * weights[1]); for (int i = 0; i < binsize; i++) hist.push_back (h_a3_mix[i] * weights[2]); for (int i = 0; i < binsize; i++) hist.push_back (h_d3_in[i] * weights[3]); for (int i = 0; i < binsize; i++) hist.push_back (h_d3_out[i] * weights[4]); for (int i = 0; i < binsize; i++) hist.push_back (h_d3_mix[i] * weights[5]); for (int i = 0; i < binsize; i++) hist.push_back (h_in[i]*0.5f * weights[6]); for (int i = 0; i < binsize; i++) hist.push_back (h_out[i] * weights[7]); for (int i = 0; i < binsize; i++) hist.push_back (h_mix[i] * weights[8]); for (int i = 0; i < binsize; i++) hist.push_back (h_mix_ratio[i]*0.5f * weights[9]); float sm = 0; for (size_t i = 0; i < hist.size (); i++) sm += hist[i]; for (size_t i = 0; i < hist.size (); i++) hist[i] /= sm; }
int ReportTripletEvent( float Power, float MeanPower, float period, float mid_time_bin, int start_time_bin, int freq_bin, int pot_len,const float *PoT, int write_triplet ) { TRIPLET_INFO ti; triplet triplet; int retval=0, i, j; double step,norm,index; double max_power=0; static int * inv; // debug possible heap corruption -- jeffc #ifdef _WIN32 BOINCASSERT(_CrtCheckMemory()); #endif if (!inv) inv = (int*)calloc_a(swi.analysis_cfg.triplet_pot_length, sizeof(int), MEM_ALIGN); // triplet info ti.score=Power; ti.t.peak_power=Power; ti.t.mean_power=MeanPower; ti.freq_bin=freq_bin; ti.time_bin=mid_time_bin+start_time_bin+0.5f; ti.t.chirp_rate=ChirpFftPairs[analysis_state.icfft].ChirpRate; ti.t.fft_len=ChirpFftPairs[analysis_state.icfft].FftLen; ti.bperiod=period; ti.t.period=static_cast<float>(period*static_cast<double>(ti.t.fft_len)/swi.subband_sample_rate); ti.t.freq=cnvt_bin_hz(freq_bin, ti.t.fft_len); double t_offset=(static_cast<double>(mid_time_bin)+start_time_bin+0.5) *static_cast<double>(ti.t.fft_len)/ swi.subband_sample_rate; ti.t.detection_freq=calc_detection_freq(ti.t.freq,ti.t.chirp_rate,t_offset); ti.t.time=swi.time_recorded+t_offset/86400.0; time_to_ra_dec(ti.t.time, &ti.t.ra, &ti.t.decl); // Populate the min and max PoT arrays. These are only used // for graphics. memset(ti.pot_min,0xff,swi.analysis_cfg.triplet_pot_length*sizeof(int)); memset(ti.pot_max,0,swi.analysis_cfg.triplet_pot_length*sizeof(int)); step=static_cast<double>(pot_len)/swi.analysis_cfg.triplet_pot_length; ti.scale=static_cast<float>(1.0/step); index=0; for (i=0;i<pot_len;i++) { if (PoT[i]>max_power) max_power=PoT[i]; } norm=255.0/max_power; float mtb = mid_time_bin; if (pot_len > swi.analysis_cfg.triplet_pot_length) { ti.tpotind0_0 = ti.tpotind0_1 = static_cast<int>(((mtb-period)*swi.analysis_cfg.triplet_pot_length)/pot_len); ti.tpotind1_0 = ti.tpotind1_1 = static_cast<int>(((mtb)*swi.analysis_cfg.triplet_pot_length)/pot_len); ti.tpotind2_0 = ti.tpotind2_1 = static_cast<int>(((mtb+period)*swi.analysis_cfg.triplet_pot_length)/pot_len); for (j=0; j<pot_len; j++) { i = (j*swi.analysis_cfg.triplet_pot_length)/pot_len; if ((PoT[j]*norm)<ti.pot_min[i]) { ti.pot_min[i]=static_cast<unsigned int>(floor(PoT[j]*norm)); } if ((PoT[j]*norm)>ti.pot_max[i]) { ti.pot_max[i]=static_cast<unsigned int>(floor(PoT[j]*norm)); } } } else { memset(inv, -1, sizeof(inv)); for (i=0;i<swi.analysis_cfg.triplet_pot_length;i++) { j = (i*pot_len)/swi.analysis_cfg.triplet_pot_length; if (inv[j] < 0) inv[j] = i; if ((PoT[j]*norm)<ti.pot_min[i]) { ti.pot_min[i]=static_cast<unsigned int>(floor(PoT[j]*norm)); } if ((PoT[j]*norm)>ti.pot_max[i]) { ti.pot_max[i]=static_cast<unsigned int>(floor(PoT[j]*norm)); } } ti.tpotind0_0 = inv[static_cast<int>(mtb-period)]; ti.tpotind0_1 = inv[static_cast<int>(mtb-period+1)]; ti.tpotind1_0 = (inv[static_cast<int>(mtb)]+inv[static_cast<int>(mtb+1)])/2; ti.tpotind1_1 = (inv[static_cast<int>(mtb+1)]+inv[static_cast<int>(mtb+2)])/2; ti.tpotind2_0 = inv[static_cast<int>(mtb+period)]; if (mtb+period+1 >= pot_len) ti.tpotind2_1 = swi.analysis_cfg.triplet_pot_length-1; else ti.tpotind2_1 = inv[static_cast<int>(mtb+period+1)]; } // Update sah_graphics triplet info regardless of whether it is the // best thus far. If a triplet has made it this far, display it. #ifdef BOINC_APP_GRAPHICS if (!nographics()) sah_graphics->ti.copy(&ti); #endif // best thus far ? if (ti.score>best_triplet->score) { *best_triplet=ti; } if (write_triplet) { if (signal_count > swi.analysis_cfg.max_signals) { SETIERROR(RESULT_OVERFLOW,"in ReportTripletEvent"); } retval = outfile.printf("%s", ti.t.print_xml(0,0,1).c_str()); if (retval < 0) { SETIERROR(WRITE_FAILED,"in ReportTripletEvent"); } else { signal_count++; triplet_count++; } } // debug possible heap corruption -- jeffc #ifdef _WIN32 BOINCASSERT(_CrtCheckMemory()); #endif return(retval); }
void set_timeval_from_double( struct timeval *tv, double d ) { tv->tv_usec = (long) ( fmod(d, 1.0) * 1000000.0 ); tv->tv_sec = (long) floor(d); }
static double roundDouble(double r) { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); }
int two_means(int nb_dimensions,groupe_t *groupe,groupe_t *groupe1,groupe_t *groupe2, int type_donnees) { /*declaration des variables*/ int i,j,point1,point2,*groupes_des_individus,succes_affectation; int compteur_iterations,nb_iterations_two_means,compteur_while; double *centre,*centre1,*centre2,inertie_inter_classe_precedente; double inertie_inter_classe_courante,meilleure_inertie_inter_classe; /*fin declaration des variables*/ nb_iterations_two_means=10; meilleure_inertie_inter_classe=NOT_DEFINED; /*allocation memoire*/ centre1=(double *)malloc(sizeof(double)*nb_dimensions); centre2=(double *)malloc(sizeof(double)*nb_dimensions); centre=(double *)malloc(sizeof(double)*nb_dimensions); groupes_des_individus=(int *)malloc(sizeof(int)*groupe->nb_individus); /*fin allocation memoire*/ if((type_donnees==SIMILARITES)||(type_donnees==ALIGNEMENT)) { for(i=0;i<groupe->nb_individus;i++) { centre[i]=0; for(j=0;j<groupe->nb_individus;j++) { centre[i]+=groupe->individus[j]->valeurs_traitees[groupe->individus[i]->id]; } centre[i]/=(double)groupe->nb_individus; } } else { for(i=0;i<nb_dimensions;i++) { centre[i]=0; for(j=0;j<groupe->nb_individus;j++) { centre[i]+=groupe->individus[j]->valeurs_traitees[i]; } centre[i]/=(double)groupe->nb_individus; } } for(compteur_iterations=0;compteur_iterations<nb_iterations_two_means;compteur_iterations++) { point1=(int)floor((double)groupe->nb_individus-1.0)*((double)rand()/(double)RAND_MAX); compteur_while=0; while(compteur_while<50) { point2=(int)floor((double)groupe->nb_individus-1.0)*((double)rand()/(double)RAND_MAX); if(calcul_distance(nb_dimensions,groupe->individus[point1]->valeurs_traitees, groupe->individus[point2]->valeurs_traitees)>ZERO_LIMIT) { break; } compteur_while++; } if(compteur_while==50) { return NON; } /*initialisation*/ if((type_donnees==SIMILARITES)||(type_donnees==ALIGNEMENT)) { for(i=0;i<groupe->nb_individus;i++) { centre1[i]= groupe->individus[point1]->valeurs_traitees[groupe->individus[i]->id]; centre2[i]= groupe->individus[point2]->valeurs_traitees[groupe->individus[i]->id]; } } else { for(i=0;i<nb_dimensions;i++) { centre1[i]=groupe->individus[point1]->valeurs_traitees[i]; centre2[i]=groupe->individus[point2]->valeurs_traitees[i]; } } /*premiere affectation des individus aux deux groupes*/ succes_affectation= affectation_individus2means(nb_dimensions,groupe->nb_individus,groupe->individus, centre1,centre2,groupes_des_individus, &inertie_inter_classe_precedente,type_donnees,centre); if(succes_affectation==NON) { return NON; } /*fin initialisation*/ compteur_while=0; while(compteur_while<10) { succes_affectation= affectation_individus2means(nb_dimensions,groupe->nb_individus,groupe->individus, centre1,centre2,groupes_des_individus, &inertie_inter_classe_courante,type_donnees,centre); if(succes_affectation==NON) { return NON; } if((inertie_inter_classe_courante-inertie_inter_classe_precedente<ZERO_LIMIT)&& (-inertie_inter_classe_courante+inertie_inter_classe_precedente<ZERO_LIMIT)) { break; } else { inertie_inter_classe_precedente=inertie_inter_classe_courante; } compteur_while++; } if((meilleure_inertie_inter_classe==NOT_DEFINED)|| (inertie_inter_classe_courante>meilleure_inertie_inter_classe)) { groupe1->nb_individus=0; groupe2->nb_individus=0; for(i=0;i<groupe->nb_individus;i++) { if(groupes_des_individus[i]==GROUPE1) { groupe1->individus[groupe1->nb_individus]=groupe->individus[i]; (groupe1->nb_individus)++; } else { groupe2->individus[groupe2->nb_individus]=groupe->individus[i]; (groupe2->nb_individus)++; } } meilleure_inertie_inter_classe=inertie_inter_classe_courante; } } /*desallocation memoire*/ free(centre1); free(centre2); free(centre); free(groupes_des_individus); /*fin desallocation memoire*/ return OUI; }
bool GLSprite::DrawShaped( const math::Vector2 &v2Pos, const math::Vector2 &v2Size, const Color& color0, const Color& color1, const Color& color2, const Color& color3, const float angle) { if (v2Size == math::Vector2(0,0)) { return true; } // compute flip parameters that will be sent to the VS math::Vector2 flipMul, flipAdd; GetFlipShaderParameters(flipAdd, flipMul); // centralizes the sprite according to the origin math::Vector2 v2Center = m_normalizedOrigin * v2Size; GLVideo* video = m_video.lock().get(); ShaderPtr pCurrentVS = video->GetVertexShader(); math::Matrix4x4 mRot; if (angle != 0.0f) mRot = math::RotateZ(math::DegreeToRadian(angle)); pCurrentVS->SetMatrixConstant("rotationMatrix", mRot); // rounds up the final position to avoid alpha distortion math::Vector2 v2FinalPos; if (video->IsRoundingUpPosition()) { v2FinalPos.x = floor(v2Pos.x); v2FinalPos.y = floor(v2Pos.y); } else { v2FinalPos = v2Pos; } pCurrentVS->SetConstant("size", v2Size); pCurrentVS->SetConstant("entityPos", v2FinalPos); pCurrentVS->SetConstant("center", v2Center); pCurrentVS->SetConstant("flipMul", flipMul); pCurrentVS->SetConstant("flipAdd", flipAdd); pCurrentVS->SetConstant("bitmapSize", GetBitmapSizeF()); pCurrentVS->SetConstant("scroll", GetScroll()); pCurrentVS->SetConstant("multiply", GetMultiply()); const bool setCameraPos = pCurrentVS->ConstantExist("cameraPos"); if (setCameraPos) pCurrentVS->SetConstant("cameraPos", video->GetCameraPos()); if (m_rect.size.x == 0 || m_rect.size.y == 0) { pCurrentVS->SetConstant("rectSize", GetBitmapSizeF()); pCurrentVS->SetConstant("rectPos", 0, 0); } else { pCurrentVS->SetConstant("rectSize", m_rect.size); pCurrentVS->SetConstant("rectPos", m_rect.pos); } pCurrentVS->SetConstant("color0", color0); pCurrentVS->SetConstant("color1", color1); pCurrentVS->SetConstant("color2", color2); pCurrentVS->SetConstant("color3", color3); if (pCurrentVS->ConstantExist("depth")) pCurrentVS->SetConstant("depth", video->GetSpriteDepth()); // apply textures according to the rendering mode (pixel shaded or not) ShaderPtr pCurrentPS = video->GetPixelShader(); SetDiffuseTexture(pCurrentPS); pCurrentVS->SetShader(); // draw the one-pixel-quad applying the vertex shader video->GetRectRenderer().Draw(m_rectMode); return true; }
int RayTracer::min(float val){ val = fabs(val); // multiply the color component by white light and clamp it to 255 return ( val*255 > 255 ? 255 : floor(val*255)); }
int sock_sim(double prior_r,double prior_p,double alpha,double beta,double obs_paired,double obs_odd,double *BigVector,int iter){ int nthreads; //variables, gsl rng initiation int i,j,match_count,n_picked; unsigned int n_socks; double prop_pairs,n_pairs,n_odd,prior_n; double obs_total = obs_paired + obs_odd; prior_n = prior_r - 1; match_count = 0; double temp_paired,temp_odd,temp_pairs; //setup gsl random seed const gsl_rng_type * T; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); #pragma omp parallel for for(i=0;i<iter;i++){ //sample, get n_pairs and n_odd n_socks = gsl_ran_negative_binomial(r,prior_p,prior_n); prop_pairs = gsl_ran_beta(r,alpha,beta); n_pairs = round(floor(.5*n_socks)*prop_pairs); n_odd = n_socks - 2*n_pairs; //make generated population double *gen_pop = (double *)malloc(sizeof(double)*n_socks); for(j=0;j<n_pairs;j++){ gen_pop[2*j] = (double) j; gen_pop[(2*j)+1] = (double) j; } for(j=2*n_pairs;j<n_socks;j++){ gen_pop[j]= (double) j; } //get generated sample size if(obs_total <= n_socks){ n_picked = (int) obs_total; }else{ n_picked = n_socks; } //get sample vector double *gen_samp = (double *)malloc(sizeof(double)*n_picked); //count pairs //sample from generated population gsl_ran_choose(r,gen_samp,n_picked,gen_pop,n_socks,sizeof(double)); //sort sample gsl_sort(gen_samp,1,n_picked); //count the number of pairs/odd in sample temp_pairs = 0.; temp_odd = 1.; for(j=1;j<n_picked;j++){ if(gen_samp[j] == gen_samp[j-1]){ temp_pairs = temp_pairs + 1; temp_odd = temp_odd - 1; continue; }else{ temp_odd = temp_odd + 1; } } temp_paired = 2*temp_pairs; //allocate big vector BigVector[5*i] = (double) n_socks; BigVector[(5*i) + 1] = n_pairs; BigVector[(5*i) + 2] = n_odd; BigVector[(5*i) + 3] = prop_pairs; //counter if(temp_odd==obs_odd && temp_paired==obs_paired){ match_count = match_count + 1; BigVector[(5*i) + 4] = 1.; continue; } else{ BigVector[(5*i) + 4] = 0.; continue; } //free the temp allocated things free(gen_pop); free(gen_samp); } gsl_rng_free(r); return(match_count); }
void IOserver::initialize(int proc_size0,int proc_size1, int IOserver_size, int IO_node_size) { int rang[3]; int totalMPIsize; int itemp; MPI_Group groupTemp1,groupTemp2; MPI_Comm_group(MPI_COMM_WORLD,&world_group_); MPI_Group_size(world_group_,&totalMPIsize); if((proc_size0*proc_size1) % IOserver_size!=0 || IOserver_size % IO_node_size!=0) { //cout<<"IOserver wrong number of process"<<endl; exit(-44); } rang[0]=0; rang[1]=proc_size0*proc_size1-1; rang[2]=1; MPI_Group_range_incl(world_group_,1,&rang,&computeGroup_); MPI_Comm_create(MPI_COMM_WORLD,computeGroup_ , &computeComm_); MPI_Group_rank(computeGroup_, &computeRank_); rang[0]=proc_size0*proc_size1; rang[1]=proc_size0*proc_size1 + IOserver_size - 1 ; rang[2]=1; MPI_Group_range_incl(world_group_,1,&rang,&IO_Group_); MPI_Comm_create(MPI_COMM_WORLD,IO_Group_ , &IO_Comm_); MPI_Group_rank(IO_Group_, &IO_Rank_); rang[0]=proc_size0*proc_size1; rang[1]=0; MPI_Group_incl(world_group_,2,&rang[0],&syncLineGroup_); MPI_Comm_create(MPI_COMM_WORLD,syncLineGroup_ , &syncLineComm_); MPI_Group_rank(syncLineGroup_, &syncLineRank_); IO_ClientSize_=proc_size0*proc_size1/IOserver_size; IO_NodeSize_=IO_node_size; if(computeRank_!=MPI_UNDEFINED)itemp = floor((float)computeRank_/(float)IO_ClientSize_) * IO_ClientSize_; else itemp = IO_Rank_ * IO_ClientSize_; //if(computeRank_!=MPI_UNDEFINED)cout<< "compute core: "<< computeRank_ <<" , "<< itemp<<endl; //if(IO_Rank_!=MPI_UNDEFINED)cout<< "IO core: "<< IO_Rank_ <<" , "<< itemp<<endl; rang[0] = itemp; rang[1] = itemp + IO_ClientSize_ -1; rang[2]=1; MPI_Group_range_incl(world_group_,1,&rang,&groupTemp2); if(computeRank_!=MPI_UNDEFINED)itemp = proc_size0*proc_size1 + floor((float)computeRank_/(float)IO_ClientSize_); else itemp = proc_size0*proc_size1 + IO_Rank_; //if(computeRank_!=MPI_UNDEFINED)cout<< "compute core: "<< computeRank_ <<" , "<< itemp<<endl; //if(IO_Rank_!=MPI_UNDEFINED)cout<< "IO core: "<< IO_Rank_ <<" , "<< itemp<<endl; MPI_Group_incl(world_group_,1,&itemp,&groupTemp1); MPI_Group_union(groupTemp1,groupTemp2,&masterClientGroup_); MPI_Comm_create(MPI_COMM_WORLD,masterClientGroup_ , &masterClientComm_); //if(computeRank_!=MPI_UNDEFINED)cout<< "compute core: "<< computeRank_ <<" , "<< itemp<<endl; //if(IO_Rank_!=MPI_UNDEFINED)cout<< "IO core: "<< IO_Rank_ <<" , "<< itemp<<endl; if(IO_Rank_!=MPI_UNDEFINED) { itemp= floor((float)IO_Rank_/ (float)IO_node_size) * IO_node_size; rang[0] = itemp; rang[1] = itemp + IO_node_size -1; rang[2]=1; MPI_Group_range_incl(IO_Group_,1,&rang,&IO_NodeGroup_); MPI_Comm_create(IO_Comm_,IO_NodeGroup_ , &IO_NodeComm_); MPI_Group_rank(IO_NodeGroup_, &IO_NodeRank_); files = new file_struct[MAX_FILE_NUMBER]; dataBuffer = (char*)malloc(IO_BUFFERS_TOTAL_SIZE); IO_Node_=floor((float)IO_Rank_/ (float)IO_node_size) ; } sendRequest = MPI_REQUEST_NULL; }
static int Psor_UpOut(double s,NumFunc_1 *p,double l,double rebate,double t,double r,double divid,double sigma,int N,int M,double theta,double omega,double epsilon,double *ptprice,double *ptdelta) { int Index,PriceIndex,TimeIndex; int j,loops; double k,vv,loc,h,z,alpha,beta,gamma,y,alpha1,beta1,gamma1,up,upwind_alphacoef; double error,norm,x; double *P,*Obst,*Rhs; /*Memory Allocation*/ P= malloc((N+2)*sizeof(double)); if (P==NULL) return MEMORY_ALLOCATION_FAILURE; Obst= malloc((N+2)*sizeof(double)); if (Obst==NULL) return MEMORY_ALLOCATION_FAILURE; Rhs= malloc((N+2)*sizeof(double)); if (Rhs==NULL) return MEMORY_ALLOCATION_FAILURE; /*Time Step*/ k=t/(double)M; /*Space Localisation*/ vv=0.5*sigma*sigma; z=(r-divid)-vv; loc=sigma*sqrt(t)*sqrt(log(1.0/PRECISION))+fabs(z)*t; /*Space Step*/ x=log(s); up=log(l); h=(up-(x-loc))/(double)(N+1); /*Coefficient of diffusion augmented*/ if ((h*fabs(z))<=vv) upwind_alphacoef=0.5; else { if (z>0.) upwind_alphacoef=0.0; else upwind_alphacoef=1.0; } vv-=z*h*(upwind_alphacoef-0.5); /*Lhs factor of theta-schema*/ alpha=theta*k*(-vv/(h*h)+z/(2.0*h)); beta=1.0+k*theta*(r+2.*vv/(h*h)); gamma=k*theta*(-vv/(h*h)-z/(2.0*h)); /*Rhs factor of theta-schema*/ alpha1=k*(1.0-theta)*(vv/(h*h)-z/(2.0*h)); beta1=1.0-k*(1.0-theta)*(r+2.*vv/(h*h)); gamma1=k*(1.0-theta)*(vv/(h*h)+z/(2.0*h)); /*Terminal Values*/ for(PriceIndex=0;PriceIndex<=N;PriceIndex++) { Obst[PriceIndex]=(p->Compute)(p->Par,exp(x-loc+(double)PriceIndex*h)); P[PriceIndex]= Obst[PriceIndex]; } P[N+1]=rebate; /*Finite Difference Cycle*/ for(TimeIndex=1;TimeIndex<=M;TimeIndex++) { /*Init Rhs*/ for(j=1;j<=N;j++) Rhs[j]=P[j]*beta1+alpha1*P[j-1]+gamma1*P[j+1]; /*Psor Cycle*/ loops=0; do { error=0.; norm=0.; for(j=1;j<=N;j++) { y=(Rhs[j]-alpha*P[j-1]-gamma*P[j+1])/beta; y=MAX(Obst[j],P[j]+omega*(y-P[j])); error+=(double)(j+1)*fabs(y-P[j]); norm+=fabs(y); P[j]=y; } if (norm<1.0) norm=1.0; error=error/norm; loops++; } while ((error>epsilon) && (loops<MAXLOOPS)); } Index=(int)floor(loc/h); *ptprice=P[Index]+(P[Index+1]-P[Index])*(exp(x)-exp(x-loc+Index*h))/(exp(x-loc+(Index+1)*h)-exp(x-loc+Index*h)); /*Delta*/ if(x==up) *ptdelta=(P[Index]-P[Index-1])/(s*h); else *ptdelta=(P[Index+1]-P[Index-1])/(2*s*h); /*Memory Desallocation*/ free(P); free(Obst); free(Rhs); return OK; }
static void Z_TagDebug_f(void) { TagBlockLabels_t AllTagBlockLabels_Local; qboolean bSnapShotTestActive = qfalse; memtag_t eTag = TAG_ALL; const char *psTAGName = Cmd_Argv(1); if (psTAGName[0]) { // check optional arg... // if (!Q_stricmp(psTAGName,"#snap")) { bSnapShotTestActive = qtrue; AllTagBlockLabels_Local = AllTagBlockLabels; // horrible great STL copy psTAGName = Cmd_Argv(2); } if (psTAGName[0]) { // skip over "tag_" if user supplied it... // if (!Q_stricmpn(psTAGName,"TAG_",4)) { psTAGName += 4; } // see if the user specified a valid tag... // for (int i=0; i<TAG_COUNT; i++) { if (!Q_stricmp(psTAGName,psTagStrings[i])) { eTag = (memtag_t) i; break; } } } } else { Com_Printf("Usage: 'zone_tagdebug [#snap] <tag>', e.g. TAG_GHOUL2, TAG_ALL (careful!)\n"); return; } Com_Printf("Dumping debug data for tag \"%s\"...%s\n\n",psTagStrings[eTag], bSnapShotTestActive?"( since snapshot only )":""); Com_Printf("%8s"," "); // to compensate for code further down: Com_Printf("(%5d) ",iBlocksListed); if (eTag == TAG_ALL) { Com_Printf("%20s ","Zone Tag"); } Com_Printf("%9s\n","Bytes"); Com_Printf("%8s"," "); if (eTag == TAG_ALL) { Com_Printf("%20s ","--------"); } Com_Printf("%9s\n","-----"); if (bSnapShotTestActive) { // dec ref counts in last snapshot for all current blocks (which will make new stuff go negative) // zoneHeader_t *pMemory = TheZone.Header.pNext; while (pMemory) { if (pMemory->eTag == eTag || eTag == TAG_ALL) { AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel]--; } pMemory = pMemory->pNext; } } // now dump them out... // int iBlocksListed = 0; int iTotalSize = 0; zoneHeader_t *pMemory = TheZone.Header.pNext; while (pMemory) { if ( (pMemory->eTag == eTag || eTag == TAG_ALL) && (!bSnapShotTestActive || (pMemory->iSnapshotNumber == giZoneSnaphotNum && AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel] <0) ) ) { float fSize = (float)(pMemory->iSize) / 1024.0f / 1024.0f; int iSize = fSize; int iRemainder = 100.0f * (fSize - floor(fSize)); Com_Printf("(%5d) ",iBlocksListed); if (eTag == TAG_ALL) { Com_Printf("%20s",psTagStrings[pMemory->eTag]); } Com_Printf(" %9d (%2d.%02dMB) File: \"%s\", Line: %d\n", pMemory->iSize, iSize,iRemainder, pMemory->sSrcFileBaseName, pMemory->iSrcFileLineNum ); if (pMemory->sOptionalLabel[0]) { Com_Printf("( Label: \"%s\" )\n",pMemory->sOptionalLabel); } iBlocksListed++; iTotalSize += pMemory->iSize; if (bSnapShotTestActive) { // bump ref count so we only 1 warning per new string, not for every one sharing that label... // AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel]++; } } pMemory = pMemory->pNext; } Com_Printf("( %d blocks listed, %d bytes (%.2fMB) total )\n",iBlocksListed, iTotalSize, (float)iTotalSize / 1024.0f / 1024.0f); }
static gfxFloat ComputeMaxAscent(const gfxFont::Metrics& aMetrics) { return floor(aMetrics.maxAscent + 0.5); }
void WorldSession::SendTrainerList(uint64 guid, const std::string& strTitle) { TC_LOG_DEBUG("network", "WORLD: SendTrainerList"); Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); if (!unit) { TC_LOG_DEBUG("network", "WORLD: SendTrainerList - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); CreatureTemplate const* ci = unit->GetCreatureTemplate(); if (!ci) { TC_LOG_DEBUG("network", "WORLD: SendTrainerList - (GUID: %u) NO CREATUREINFO!", GUID_LOPART(guid)); return; } TrainerSpellData const* trainer_spells = unit->GetTrainerSpells(); if (!trainer_spells) { TC_LOG_DEBUG("network", "WORLD: SendTrainerList - Training spells not found for creature (GUID: %u Entry: %u)", GUID_LOPART(guid), unit->GetEntry()); return; } WorldPacket data(SMSG_TRAINER_LIST, 8+4+4+trainer_spells->spellList.size()*38 + strTitle.size()+1); data << guid; data << uint32(trainer_spells->trainerType); size_t count_pos = data.wpos(); data << uint32(trainer_spells->spellList.size()); // reputation discount float fDiscountMod = _player->GetReputationPriceDiscount(unit); bool can_learn_primary_prof = GetPlayer()->GetFreePrimaryProfessionPoints() > 0; uint32 count = 0; for (TrainerSpellMap::const_iterator itr = trainer_spells->spellList.begin(); itr != trainer_spells->spellList.end(); ++itr) { TrainerSpell const* tSpell = &itr->second; bool valid = true; bool primary_prof_first_rank = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!tSpell->learnedSpell[i]) continue; if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell[i])) { valid = false; break; } SpellInfo const* learnedSpellInfo = sSpellMgr->GetSpellInfo(tSpell->learnedSpell[i]); if (learnedSpellInfo && learnedSpellInfo->IsPrimaryProfessionFirstRank()) primary_prof_first_rank = true; } if (!valid) continue; TrainerSpellState state = _player->GetTrainerSpellState(tSpell); data << uint32(tSpell->spell); // learned spell (or cast-spell in profession case) data << uint8(state == TRAINER_SPELL_GREEN_DISABLED ? TRAINER_SPELL_GREEN : state); data << uint32(floor(tSpell->spellCost * fDiscountMod)); data << uint32(primary_prof_first_rank && can_learn_primary_prof ? 1 : 0); // primary prof. learn confirmation dialog data << uint32(primary_prof_first_rank ? 1 : 0); // must be equal prev. field to have learn button in enabled state data << uint8(tSpell->reqLevel); data << uint32(tSpell->reqSkill); data << uint32(tSpell->reqSkillValue); //prev + req or req + 0 uint8 maxReq = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!tSpell->learnedSpell[i]) continue; if (uint32 prevSpellId = sSpellMgr->GetPrevSpellInChain(tSpell->learnedSpell[i])) { data << uint32(prevSpellId); ++maxReq; } if (maxReq == 3) break; SpellsRequiringSpellMapBounds spellsRequired = sSpellMgr->GetSpellsRequiredForSpellBounds(tSpell->learnedSpell[i]); for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequired.first; itr2 != spellsRequired.second && maxReq < 3; ++itr2) { data << uint32(itr2->second); ++maxReq; } if (maxReq == 3) break; } while (maxReq < 3) { data << uint32(0); ++maxReq; } ++count; } data << strTitle; data.put<uint32>(count_pos, count); SendPacket(&data); }
KFR_SINTRIN f64sse fract(f64sse x) { return x - floor(x); }
/* HBB 20010121: added code that attempts to fix rounding-induced * off-by-one errors in 10^%T and similar output formats */ static void mant_exp( double log10_base, double x, TBOOLEAN scientific, /* round to power of 3 */ double *m, /* results */ int *p, const char *format) /* format string for fixup */ { int sign = 1; double l10; int power; double mantissa; /*{{{ check 0 */ if (x == 0) { if (m) *m = 0; if (p) *p = 0; return; } /*}}} */ /*{{{ check -ve */ if (x < 0) { sign = (-1); x = (-x); } /*}}} */ l10 = log10(x) / log10_base; power = floor(l10); mantissa = pow(10.0, log10_base * (l10 - power)); /* round power to an integer multiple of 3, to get what's * sometimes called 'scientific' or 'engineering' notation. Also * useful for handling metric unit prefixes like 'kilo' or 'micro' * */ if (scientific) { /* Scientific mode makes no sense whatsoever if the base of * the logarithmic axis is anything but 10.0 */ assert(log10_base == 1.0); /* HBB FIXED 20040701: negative modulo positive may yield * negative result. But we always want an effectively * positive modulus --> adjust input by one step */ switch (power % 3) { case -1: power -= 3; case 2: mantissa *= 100; break; case -2: power -= 3; case 1: mantissa *= 10; break; case 0: break; default: int_error (NO_CARET, "Internal error in scientific number formatting"); } power -= (power % 3); } /* HBB 20010121: new code for decimal mantissa fixups. Looks at * format string to see how many decimals will be put there. Iff * the number is so close to an exact power of 10 that it will be * rounded up to 10.0e??? by an sprintf() with that many digits of * precision, increase the power by 1 to get a mantissa in the * region of 1.0. If this handling is not wanted, pass NULL as * the format string */ /* HBB 20040521: extended to also work for bases other than 10.0 */ if (format) { double actual_base = (scientific ? 1000 : pow(10.0, log10_base)); int precision = 0; double tolerance; format = strchr (format, '.'); if (format != NULL) /* a decimal point was found in the format, so use that * precision. */ precision = strtol(format + 1, NULL, 10); /* See if mantissa would be right on the border. The * condition to watch out for is that the mantissa is within * one printing precision of the next power of the logarithm * base. So add the 0.5*10^-precision to the mantissa, and * see if it's now larger than the base of the scale */ tolerance = pow(10.0, -precision) / 2; if (mantissa + tolerance >= actual_base) { mantissa /= actual_base; power += (scientific ? 3 : 1); } } if (m) *m = sign * mantissa; if (p) *p = power; }
inT32 row_words2( //compute space size TO_BLOCK *block, //block it came from TO_ROW *row, //row to operate on inT32 maxwidth, //max expected space size FCOORD rotation, //for drawing BOOL8 testing_on //for debug ) { BOOL8 testing_row; //contains testpt BOOL8 prev_valid; //if decent size BOOL8 this_valid; //current blob big enough inT32 prev_x; //end of prev blob inT32 min_width; //min interesting width inT32 valid_count; //good gaps inT32 total_count; //total gaps inT32 cluster_count; //no of clusters inT32 prev_count; //previous cluster_count inT32 gap_index; //which cluster inT32 smooth_factor; //for smoothing stats BLOBNBOX *blob; //current blob float lower, upper; //clustering parameters ICOORD testpt; TBOX blob_box; //bounding box //iterator BLOBNBOX_IT blob_it = row->blob_list (); STATS gap_stats (0, maxwidth); //gap sizes float gaps[BLOCK_STATS_CLUSTERS]; STATS cluster_stats[BLOCK_STATS_CLUSTERS + 1]; //clusters testpt = ICOORD (textord_test_x, textord_test_y); smooth_factor = (inT32) (block->xheight * textord_wordstats_smooth_factor + 1.5); // if (testing_on) // tprintf("Row smooth factor=%d\n",smooth_factor); prev_valid = FALSE; prev_x = -MAX_INT16; testing_row = FALSE; //min blob size min_width = (inT32) block->pr_space; total_count = 0; for (blob_it.mark_cycle_pt (); !blob_it.cycled_list (); blob_it.forward ()) { blob = blob_it.data (); if (!blob->joined_to_prev ()) { blob_box = blob->bounding_box (); this_valid = blob_box.width () >= min_width; if (this_valid && prev_valid && blob_box.left () - prev_x < maxwidth) { gap_stats.add (blob_box.left () - prev_x, 1); } total_count++; //count possibles prev_x = blob_box.right (); prev_valid = this_valid; } } valid_count = gap_stats.get_total (); if (valid_count < total_count * textord_words_minlarge) { gap_stats.clear (); prev_x = -MAX_INT16; for (blob_it.mark_cycle_pt (); !blob_it.cycled_list (); blob_it.forward ()) { blob = blob_it.data (); if (!blob->joined_to_prev ()) { blob_box = blob->bounding_box (); if (blob_box.left () - prev_x < maxwidth) { gap_stats.add (blob_box.left () - prev_x, 1); } prev_x = blob_box.right (); } } } if (gap_stats.get_total () == 0) { row->min_space = 0; //no evidence row->max_nonspace = 0; return 0; } cluster_count = 0; lower = block->xheight * words_initial_lower; upper = block->xheight * words_initial_upper; gap_stats.smooth (smooth_factor); do { prev_count = cluster_count; cluster_count = gap_stats.cluster (lower, upper, textord_spacesize_ratioprop, BLOCK_STATS_CLUSTERS, cluster_stats); } while (cluster_count > prev_count && cluster_count < BLOCK_STATS_CLUSTERS); if (cluster_count < 1) { row->min_space = 0; row->max_nonspace = 0; return 0; } for (gap_index = 0; gap_index < cluster_count; gap_index++) gaps[gap_index] = cluster_stats[gap_index + 1].ile (0.5); //get medians if (testing_on) { tprintf ("cluster_count=%d:", cluster_count); for (gap_index = 0; gap_index < cluster_count; gap_index++) tprintf (" %g(%d)", gaps[gap_index], cluster_stats[gap_index + 1].get_total ()); tprintf ("\n"); } //Try to find proportional non-space and space for row. for (gap_index = 0; gap_index < cluster_count && gaps[gap_index] > block->max_nonspace; gap_index++); if (gap_index < cluster_count) lower = gaps[gap_index]; //most frequent below else { if (testing_on) tprintf ("No cluster below block threshold!, using default=%g\n", block->pr_nonsp); lower = block->pr_nonsp; } for (gap_index = 0; gap_index < cluster_count && gaps[gap_index] <= block->max_nonspace; gap_index++); if (gap_index < cluster_count) upper = gaps[gap_index]; //most frequent above else { if (testing_on) tprintf ("No cluster above block threshold!, using default=%g\n", block->pr_space); upper = block->pr_space; } row->min_space = (inT32) ceil (upper - (upper - lower) * textord_words_definite_spread); row->max_nonspace = (inT32) floor (lower + (upper - lower) * textord_words_definite_spread); row->space_threshold = (row->max_nonspace + row->min_space) / 2; row->space_size = upper; row->kern_size = lower; if (testing_on) { if (testing_row) { tprintf ("GAP STATS\n"); gap_stats.print(); tprintf ("SPACE stats\n"); cluster_stats[2].print_summary(); tprintf ("NONSPACE stats\n"); cluster_stats[1].print_summary(); } tprintf ("Row at %g has minspace=%d(%g), max_non=%d(%g)\n", row->intercept (), row->min_space, upper, row->max_nonspace, lower); } return 1; }
// http://jeanne.wankuma.com/tips/math/rounddown.html double roundDown(double val, size_t digits) { double factor = pow(10.0, (double)digits); double ret = (val > 0) ? (floor(val*factor) / factor) : (ceil(val*factor) / factor); return ret; }
int CGridManager::GetGridWidth() { return (int) floor(GridDimensions.x); }
void DIA_properties( void ) { char text[80]; uint16_t hh, mm, ss, ms; GtkWidget *dialog; uint8_t gmc, qpel,vop; uint32_t info=0; const char *yesno[2]={QT_TR_NOOP("No"),QT_TR_NOOP("Yes")}; uint32_t war,har; if (playing) return; text[0] = 0; if (!avifileinfo) return; // Fetch info info=video_body->getSpecificMpeg4Info(); vop=!!(info & ADM_VOP_ON); qpel=!!(info & ADM_QPEL_ON); gmc=!!(info & ADM_GMC_ON); dialog = create_dialog1(); gtk_register_dialog(dialog); sprintf(text, QT_TR_NOOP("%lu x %lu"), avifileinfo->width,avifileinfo->height); FILL_ENTRY(label_size); sprintf(text, QT_TR_NOOP("%2.3f fps"), (float) avifileinfo->fps1000 / 1000.F); FILL_ENTRY(label_fps); sprintf(text, QT_TR_NOOP("%ld frames"), avifileinfo->nb_frames); FILL_ENTRY(label_number); sprintf(text, "%s", fourCC::tostring(avifileinfo->fcc)); FILL_ENTRY(label_videofourcc); if (avifileinfo->nb_frames) { frame2time(avifileinfo->nb_frames, avifileinfo->fps1000, &hh, &mm, &ss, &ms); sprintf(text, QT_TR_NOOP("%02d:%02d:%02d.%03d"), hh, mm, ss, ms); FILL_ENTRY(label_duration); } // Fill in vop, gmc & qpel SET_YES(labelPacked,vop); SET_YES(labelGMC,gmc); SET_YES(labelQP,qpel); // Aspect ratio const char *s; war=video_body->getPARWidth(); har=video_body->getPARHeight(); getAspectRatioFromAR(war,har, &s); sprintf(text, QT_TR_NOOP("%s (%u:%u)"), s,war,har); FILL_ENTRY(labelAspectRatio); // Now audio WAVHeader *wavinfo=NULL; if (currentaudiostream) wavinfo=currentaudiostream->getInfo(); if(wavinfo) { switch (wavinfo->channels) { case 1: sprintf(text, QT_TR_NOOP("Mono")); break; case 2: sprintf(text, QT_TR_NOOP("Stereo")); break; default: sprintf(text, "%d",wavinfo->channels); break; } FILL_ENTRY(label1_audiomode); sprintf(text, QT_TR_NOOP("%lu Hz"), wavinfo->frequency); FILL_ENTRY(label_fq); sprintf(text, QT_TR_NOOP("%lu Bps / %lu kbps"), wavinfo->byterate, wavinfo->byterate * 8 / 1000); FILL_ENTRY(label_bitrate); sprintf(text, "%s", getStrFromAudioCodec(wavinfo->encoding)); FILL_ENTRY(label1_audiofourcc); // Duration in seconds too if(currentaudiostream && wavinfo->byterate>1) { uint32_t l=currentaudiostream->getLength(); double du; du=l; du*=1000; du/=wavinfo->byterate; ms2time((uint32_t)floor(du), &hh, &mm, &ss, &ms); sprintf(text, QT_TR_NOOP("%02d:%02d:%02d.%03d"), hh, mm, ss, ms); FILL_ENTRY(label_audioduration); sprintf(text, QT_TR_NOOP("%.2f MB"), l / 1048576.F); FILL_ENTRY(labelFileSize); } SET_YES(labelVbr, currentaudiostream->isVBR()); } else { DISABLE_WIDGET(frame2); } gtk_dialog_run(GTK_DIALOG(dialog)); gtk_unregister_dialog(dialog); gtk_widget_destroy(dialog); }
void LuminanceRangeWidget::paintEvent( QPaintEvent *pe ) { { QPainter p( this ); QRect fRect = getPaintRect(); if( fRect.width() < 50 ) // Does not make sense to paint anything return; // Paint range window { int x1, x2; x1 = getWindowX( draggedMin() ); x2 = getWindowX( draggedMax() ); QColor selectionColor = mouseDragStart == DRAGNOTSTARTED ? QColor( 0, 100, 255 ) : QColor( 0, 150, 255 ); p.fillRect( x1, fRect.top(), x2-x1, fRect.height(), QBrush( selectionColor ) ); } // Paint histogram if( histogramImage != NULL ) { if( histogram == NULL || histogram->getBins() != fRect.width() ) { delete histogram; // Build histogram from at least 5000 pixels int accuracy = histogramImage->getRows()*histogramImage->getCols()/5000; if( accuracy < 1 ) accuracy = 1; histogram = new Histogram( fRect.width(), accuracy ); histogram->computeLog( histogramImage, minValue, maxValue ); } float maxP = histogram->getMaxP(); int i = 0; p.setPen( Qt::green ); for( int x = fRect.left(); i < histogram->getBins(); x++, i++ ) { if( histogram->getP(i) > 0 ) { int barSize = (int)((float)fRect.height() * histogram->getP(i)/maxP); p.drawLine( x, fRect.bottom(), x, fRect.bottom() - barSize ); } } } // Paint scale QFont labelFont( "SansSerif", 8 ); p.setFont( labelFont ); p.setPen( Qt::black ); QRect textBounding = p.boundingRect( fRect, Qt::AlignHCenter|Qt::AlignBottom, "-8" ); for( float x = ceil( minValue ); x <= floor( maxValue ); x++ ) { int rx = getWindowX(x); p.drawLine( rx, fRect.top(), rx, textBounding.top() ); char str[10]; sprintf( str, "%g", x ); p.drawText( rx-20, textBounding.top(), 40, textBounding.height(), Qt::AlignHCenter|Qt::AlignBottom, str ); } // Paint value pointer if( showVP ) { int x = getWindowX( valuePointer ); if( fRect.contains( x, fRect.y() ) ) { p.setPen( Qt::yellow ); p.drawLine( x, fRect.top(), x, fRect.bottom() ); } } } QFrame::paintEvent(pe); }
static QList<double> _calcPrettyBreaks( double minimum, double maximum, int classes ) { // C++ implementation of R's pretty algorithm // Based on code for determining optimal tick placement for statistical graphics // from the R statistical programming language. // Code ported from R implementation from 'labeling' R package // // Computes a sequence of about 'classes' equally spaced round values // which cover the range of values from 'minimum' to 'maximum'. // The values are chosen so that they are 1, 2 or 5 times a power of 10. QList<double> breaks; if ( classes < 1 ) { breaks.append( maximum ); return breaks; } int minimumCount = ( int ) classes / 3; double shrink = 0.75; double highBias = 1.5; double adjustBias = 0.5 + 1.5 * highBias; int divisions = classes; double h = highBias; double cell; int U; bool small = false; double dx = maximum - minimum; if ( dx == 0 && maximum == 0 ) { cell = 1.0; small = true; U = 1; } else { cell = qMax( qAbs( minimum ), qAbs( maximum ) ); if ( adjustBias >= 1.5 * h + 0.5 ) { U = 1 + ( 1.0 / ( 1 + h ) ); } else { U = 1 + ( 1.5 / ( 1 + adjustBias ) ); } small = dx < ( cell * U * qMax( 1, divisions ) * 1e-07 * 3.0 ); } if ( small ) { if ( cell > 10 ) { cell = 9 + cell / 10; cell = cell * shrink; } if ( minimumCount > 1 ) { cell = cell / minimumCount; } } else { cell = dx; if ( divisions > 1 ) { cell = cell / divisions; } } if ( cell < 20 * 1e-07 ) { cell = 20 * 1e-07; } double base = pow( 10.0, floor( log10( cell ) ) ); double unit = base; if (( 2 * base ) - cell < h *( cell - unit ) ) { unit = 2.0 * base; if (( 5 * base ) - cell < adjustBias *( cell - unit ) ) { unit = 5.0 * base; if (( 10.0 * base ) - cell < h *( cell - unit ) ) { unit = 10.0 * base; } } } // Maybe used to correct for the epsilon here?? int start = floor( minimum / unit + 1e-07 ); int end = ceil( maximum / unit - 1e-07 ); // Extend the range out beyond the data. Does this ever happen?? while ( start * unit > minimum + ( 1e-07 * unit ) ) { start = start - 1; } while ( end * unit < maximum - ( 1e-07 * unit ) ) { end = end + 1; } QgsDebugMsg( QString( "pretty classes: %1" ).arg( end ) ); // If we don't have quite enough labels, extend the range out // to make more (these labels are beyond the data :( ) int k = floor( 0.5 + end - start ); if ( k < minimumCount ) { k = minimumCount - k; if ( start >= 0 ) { end = end + k / 2; start = start - k / 2 + k % 2; } else { start = start - k / 2; end = end + k / 2 + k % 2; } divisions = minimumCount; } else { divisions = k; } double minimumBreak = start * unit; //double maximumBreak = end * unit; int count = end - start; for ( int i = 1; i < count + 1; i++ ) { breaks.append( minimumBreak + i * unit ); } if ( breaks.isEmpty() ) return breaks; if ( breaks.first() < minimum ) { breaks[0] = minimum; } if ( breaks.last() > maximum ) { breaks[breaks.count()-1] = maximum; } return breaks; } // _calcPrettyBreaks