Out operator()(In begin, In end, Out out, MassComp massComp, AbundanceComp abundanceComp) { // get a copy std::vector<typename In::value_type> v(begin, end); TopX topX(x_); while (!v.empty()) { // sort by abundance std::sort(v.begin(), v.end(), abundanceComp); double maxAbundanceMass = v[v.size()-1].first; // sort by mass std::sort(v.begin(), v.end(), massComp); // define window #ifdef DEBUG std::cerr << '#' << maxAbundanceMass - z_ << '-' << maxAbundanceMass + z_ << std::endl; #endif In regionBegin = lower_bound(v.begin(), v.end(), maxAbundanceMass - z_, massComp); In regionEnd = upper_bound(regionBegin, v.end(), maxAbundanceMass + z_, massComp); // get TopX out = topX(regionBegin, regionEnd, out, abundanceComp); // erase entries in window v.erase(regionBegin, regionEnd); } return out; }
/********************************** * Longest Increasing Subsequence * ********************************** * Computes the longest increasing subsequence for a number * of problem instances, each given as a sequence of non-negative * integers, terminated by a -1. The whole input is terminated * by a -1. * * readn( int *n ) reads the next integer in the sequence. * * #include <vector> * #include <algorithm> * REQUIRES: readn (suggested) * COMPLEXITY: O(nlogn) **/ int lis() { int n, prob = 0; vector< int > table; while( true ) { table.clear(); while( true ) { readn( &n ); // "cin >> n;" might be too slow if( n < 0 ) break; vector< int >::iterator i = upper_bound( table.begin(), table.end(), n ); if( i == table.end() ) table.push_back( n ); else *i = n; } if( table.empty() ) break; printf( "Test #%d:\n maximum possible interceptions: %d\n\n", ++prob, table.size() ); } return 0; }
int smallestDistancePair(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); int n = nums.size(), total = n * (n - 1) / 2; int l = 0, r = nums.back() - nums[0]; while(true) { int m = (l + r) / 2; int cnt = 0; int equalCnt = 0; for(int i = 0; i < n - 1; ++i) { auto lowerIter = lower_bound(nums.begin() + i + 1, nums.end(), nums[i] + m); auto upperIter = upper_bound(nums.begin() + i + 1, nums.end(), nums[i] + m); if(lowerIter == nums.end()) break; int t = nums.end() - lowerIter; cnt += t; if(*lowerIter == nums[i] + m) equalCnt += upperIter - lowerIter; } if(cnt > total - k && equalCnt != 0 && total - cnt + equalCnt >= k) return m; if(cnt > total - k) l = m + 1; else r = m; } }
/// Constructor MiscibilityLiveOil::MiscibilityLiveOil(const table_t& pvto) { // OIL, PVTO const int region_number = 0; if (pvto.size() != 1) { THROW("More than one PVD-region"); } saturated_oil_table_.resize(4); const int sz = pvto[region_number].size(); for (int k=0; k<4; ++k) { saturated_oil_table_[k].resize(sz); } for (int i=0; i<sz; ++i) { saturated_oil_table_[0][i] = pvto[region_number][i][1]; // p saturated_oil_table_[1][i] = 1.0/pvto[region_number][i][2]; // 1/Bo saturated_oil_table_[2][i] = pvto[region_number][i][3]; // mu_o saturated_oil_table_[3][i] = pvto[region_number][i][0]; // Rs } undersat_oil_tables_.resize(sz); for (int i=0; i<sz; ++i) { undersat_oil_tables_[i].resize(3); int tsize = (pvto[region_number][i].size() - 1)/3; undersat_oil_tables_[i][0].resize(tsize); undersat_oil_tables_[i][1].resize(tsize); undersat_oil_tables_[i][2].resize(tsize); for (int j=0, k=0; j<tsize; ++j) { undersat_oil_tables_[i][0][j] = pvto[region_number][i][++k]; // p undersat_oil_tables_[i][1][j] = 1.0/pvto[region_number][i][++k]; // 1/Bo undersat_oil_tables_[i][2][j] = pvto[region_number][i][++k]; // mu_o } } // Fill in additional entries in undersaturated tables by interpolating/extrapolating 1/Bo and mu_o ... int iPrev = -1; int iNext = 1; while (undersat_oil_tables_[iNext][0].size() < 2) { ++iNext; } assert(iNext < sz); for (int i=0; i<sz; ++i) { if (undersat_oil_tables_[i][0].size() > 1) { iPrev = i; continue; } bool flagPrev = (iPrev >= 0); bool flagNext = true; if (iNext < i) { iPrev = iNext; flagPrev = true; iNext = i+1; while (undersat_oil_tables_[iNext][0].size() < 2) { ++iNext; } } double slopePrevBinv = 0.0; double slopePrevVisc = 0.0; double slopeNextBinv = 0.0; double slopeNextVisc = 0.0; while (flagPrev || flagNext) { double pressure0 = undersat_oil_tables_[i][0].back(); double pressure = 1.0e47; if (flagPrev) { std::vector<double>::iterator itPrev = upper_bound(undersat_oil_tables_[iPrev][0].begin(), undersat_oil_tables_[iPrev][0].end(),pressure0+1.); if (itPrev == undersat_oil_tables_[iPrev][0].end()) { --itPrev; // Extrapolation ... } else if (itPrev == undersat_oil_tables_[iPrev][0].begin()) { ++itPrev; } if (itPrev == undersat_oil_tables_[iPrev][0].end()-1) { flagPrev = false; // Last data set for "prev" ... } double dPPrev = *itPrev - *(itPrev-1); pressure = *itPrev; int index = int(itPrev - undersat_oil_tables_[iPrev][0].begin()); slopePrevBinv = (undersat_oil_tables_[iPrev][1][index] - undersat_oil_tables_[iPrev][1][index-1])/dPPrev; slopePrevVisc = (undersat_oil_tables_[iPrev][2][index] - undersat_oil_tables_[iPrev][2][index-1])/dPPrev; } if (flagNext) { std::vector<double>::iterator itNext = upper_bound(undersat_oil_tables_[iNext][0].begin(), undersat_oil_tables_[iNext][0].end(),pressure0+1.); if (itNext == undersat_oil_tables_[iNext][0].end()) { --itNext; // Extrapolation ... } else if (itNext == undersat_oil_tables_[iNext][0].begin()) { ++itNext; } if (itNext == undersat_oil_tables_[iNext][0].end()-1) { flagNext = false; // Last data set for "next" ... } double dPNext = *itNext - *(itNext-1); if (flagPrev) { pressure = std::min(pressure,*itNext); } else { pressure = *itNext; } int index = int(itNext - undersat_oil_tables_[iNext][0].begin()); slopeNextBinv = (undersat_oil_tables_[iNext][1][index] - undersat_oil_tables_[iNext][1][index-1])/dPNext; slopeNextVisc = (undersat_oil_tables_[iNext][2][index] - undersat_oil_tables_[iNext][2][index-1])/dPNext; } double dP = pressure - pressure0; if (iPrev >= 0) { double w = (saturated_oil_table_[3][i] - saturated_oil_table_[3][iPrev]) / (saturated_oil_table_[3][iNext] - saturated_oil_table_[3][iPrev]); undersat_oil_tables_[i][0].push_back(pressure0+dP); undersat_oil_tables_[i][1].push_back(undersat_oil_tables_[i][1].back() + dP*(slopePrevBinv+w*(slopeNextBinv-slopePrevBinv))); undersat_oil_tables_[i][2].push_back(undersat_oil_tables_[i][2].back() + dP*(slopePrevVisc+w*(slopeNextVisc-slopePrevVisc))); } else { undersat_oil_tables_[i][0].push_back(pressure0+dP); undersat_oil_tables_[i][1].push_back(undersat_oil_tables_[i][1].back()+dP*slopeNextBinv); undersat_oil_tables_[i][2].push_back(undersat_oil_tables_[i][2].back()+dP*slopeNextVisc); } } } }
struct mzROIStruct * insertpeak(const double fMass, const double fInten, struct scanBuf * scanbuf, const int scan, const int LastScan, struct mzROIStruct *mzval, struct mzLengthStruct *mzLength, struct pickOptionsStruct *pickOptions) { int i,wasfound=FALSE; double ddev = (pickOptions->dev * fMass); int lpos = lower_bound( fMass - ddev,mzval,0,mzLength->mzval); int hpos = upper_bound( fMass + ddev,mzval,lpos,mzLength->mzval - lpos); if (lpos > mzLength->mzval-1) lpos = mzLength->mzval -1; if (hpos > mzLength->mzval-1) hpos = mzLength->mzval -1 ; for (i=lpos; i <= hpos; i++) { double ddiff = fabs(mzval[i].mz - fMass); if (ddiff <= ddev) { // match -> extend this ROI if ( (i > hpos) || (i<lpos) ) error("! scan: %d \n",scan); wasfound = TRUE; //recursive m/z mean update mzval[i].mz = ((mzval[i].length * mzval[i].mz) + fMass) / (mzval[i].length + 1); if (fMass < mzval[i].mzmin) mzval[i].mzmin = fMass; if (fMass > mzval[i].mzmax) mzval[i].mzmax = fMass; mzval[i].scmax = scan; mzval[i].length++; mzval[i].intensity+=fInten; if (fInten >= pickOptions->minimumInt) mzval[i].kI++; } } // for // if not found if (wasfound == FALSE) { // no, create new ROI for mz lpos=-1;hpos=-1; int doInsert=FALSE; if ((scan < LastScan) && (scanbuf->nextScanLength > 0)) {// check next scan int lpos = lowerBound( fMass - ddev,scanbuf->nextScan,0,scanbuf->nextScanLength); int hpos = upperBound( fMass + ddev,scanbuf->nextScan,lpos,scanbuf->nextScanLength - lpos); if (lpos < scanbuf->nextScanLength) { for (i=lpos; i <= hpos; i++) // { ddev = (pickOptions->dev * scanbuf->nextScan[i]); double ddiff = fabs(fMass - scanbuf->nextScan[i]); if (ddiff <= ddev) { doInsert=TRUE; break; } } } } else doInsert=TRUE; if (doInsert == TRUE) { // get pos. for insert int i = lower_bound(fMass,mzval,0,mzLength->mzval); // check buffer size mzval=checkmzvalBufSize(mzval, mzLength->mzval + 1, mzLength); // elements to move int n = mzLength->mzval - i; // insert element if (n>0) memmove(mzval + i +1, mzval + i, n*sizeof(struct mzROIStruct)); mzval[i].mz = fMass; mzval[i].mzmin = fMass; mzval[i].mzmax = fMass; mzval[i].intensity = fInten; mzval[i].scmin = scan; mzval[i].scmax = scan; mzval[i].length = 1; if (fInten >= pickOptions->minimumInt) mzval[i].kI = 1; else mzval[i].kI = 0; mzval[i].deleteMe = FALSE; mzLength->mzval++; } } return(mzval); }
uint32_t Route::GetTotalTimeSec() const { return m_times.empty() ? 0 : m_times.back().second; } uint32_t Route::GetCurrentTimeToEndSec() const { size_t const polySz = m_poly.GetPolyline().GetSize(); if (m_times.empty() || polySz == 0) { ASSERT(!m_times.empty(), ()); ASSERT(polySz != 0, ()); return 0; } TTimes::const_iterator it = upper_bound(m_times.begin(), m_times.end(), m_poly.GetCurrentIter().m_ind, [](size_t v, Route::TTimeItem const & item) { return v < item.first; }); if (it == m_times.end()) return 0; size_t idx = distance(m_times.begin(), it); double time = (*it).second; if (idx > 0) time -= m_times[idx - 1].second; auto distFn = [&](size_t start, size_t end) { return m_poly.GetDistanceM(m_poly.GetIterToIndex(start), m_poly.GetIterToIndex(end)); }; ASSERT_LESS(m_times[idx].first, polySz, ());
PosList IndexScan::_scan_chunk(const ChunkID chunk_id) { const auto to_row_id = [chunk_id](ChunkOffset chunk_offset) { return RowID{chunk_id, chunk_offset}; }; auto range_begin = BaseIndex::Iterator{}; auto range_end = BaseIndex::Iterator{}; const auto chunk = _in_table->get_chunk(chunk_id); auto matches_out = PosList{}; const auto index = chunk->get_index(_index_type, _left_column_ids); Assert(index, "Index of specified type not found for segment (vector)."); switch (_predicate_condition) { case PredicateCondition::Equals: { range_begin = index->lower_bound(_right_values); range_end = index->upper_bound(_right_values); break; } case PredicateCondition::NotEquals: { // first, get all values less than the search value range_begin = index->cbegin(); range_end = index->lower_bound(_right_values); matches_out.reserve(std::distance(range_begin, range_end)); std::transform(range_begin, range_end, std::back_inserter(matches_out), to_row_id); // set range for second half to all values greater than the search value range_begin = index->upper_bound(_right_values); range_end = index->cend(); break; } case PredicateCondition::LessThan: { range_begin = index->cbegin(); range_end = index->lower_bound(_right_values); break; } case PredicateCondition::LessThanEquals: { range_begin = index->cbegin(); range_end = index->upper_bound(_right_values); break; } case PredicateCondition::GreaterThan: { range_begin = index->upper_bound(_right_values); range_end = index->cend(); break; } case PredicateCondition::GreaterThanEquals: { range_begin = index->lower_bound(_right_values); range_end = index->cend(); break; } case PredicateCondition::BetweenInclusive: { range_begin = index->lower_bound(_right_values); range_end = index->upper_bound(_right_values2); break; } case PredicateCondition::BetweenLowerExclusive: { range_begin = index->upper_bound(_right_values); range_end = index->upper_bound(_right_values2); break; } case PredicateCondition::BetweenUpperExclusive: { range_begin = index->lower_bound(_right_values); range_end = index->lower_bound(_right_values2); break; } case PredicateCondition::BetweenExclusive: { range_begin = index->upper_bound(_right_values); range_end = index->lower_bound(_right_values2); break; } default: Fail("Unsupported comparison type encountered"); } matches_out.reserve(matches_out.size() + std::distance(range_begin, range_end)); std::transform(range_begin, range_end, std::back_inserter(matches_out), to_row_id); return matches_out; }
static int upper_level(vector<double> const &levels,double x,double tol=0.){ return(upper_bound(levels.begin(),levels.end(),x-tol)-levels.begin()); }
void UserQueue::addBundle(BundlePtr& aBundle, const UserPtr& aUser) noexcept{ auto& s = userBundleQueue[aUser]; s.insert(upper_bound(s.begin(), s.end(), aBundle, Bundle::SortOrder()), aBundle); }
static void test4() { typedef LIBCXX_NAMESPACE::mcguffinmultimap <int, LIBCXX_NAMESPACE::ref<valueObj>> map_t; test34_common<map_t>("test4: "); auto m=map_t::create(); m->lower_bound(0); m->upper_bound(0); { std::vector<LIBCXX_NAMESPACE::ref<valueObj>> v; v.push_back(LIBCXX_NAMESPACE::ref<valueObj>::create()); auto mcguffin=m->insert(std::make_pair(0, v.front())); std::cout << "test4: this should be 0: " << m->insert(std::make_pair(0, v.front())).null() << std::endl; std::cout << "test4: this should be 0: " << m->insert(std::make_pair(1, v.front())).null() << std::endl; v.clear(); for (const auto &v:*m) { std::cout << "test4: remaining key " << v.first << std::flush << " value: " << v.second.getptr()->v_proof << std::endl; } } std::vector<LIBCXX_NAMESPACE::ptr<LIBCXX_NAMESPACE::obj>> save_mcguffin; { auto v=LIBCXX_NAMESPACE::ref<valueObj>::create(); auto mcguffin1=m->find_or_create(0, [&v] { return v; }); auto mcguffin2=m->find_or_create(0, [&v] { return v; }); for (const auto &v:*m) { std::cout << "test4: after find_or_create: " << v.first << std::flush << " value: " << v.second.getptr()->v_proof << std::endl; auto p=v.second.mcguffin(); std::cout << "test4: mcguffin.null() should be 0: " << p.null() << std::endl; save_mcguffin.push_back(p); } } for (const auto &v:*m) { std::cout << "test4: mcguffin should exist: " << v.first << std::flush << " value: " << v.second.getptr()->v_proof << std::endl; save_mcguffin.clear(); std::cout << "test4: mcguffin should work: " << v.first << std::flush << " null: " << v.second.getptr().null() << std::endl; } }
double CtrlList::value(int frame, bool cur_val_only, int* nextFrame) const { if(cur_val_only || empty()) { if(nextFrame) *nextFrame = -1; return _curVal; } double rv; int nframe; ciCtrl i = upper_bound(frame); // get the index after current frame if (i == end()) { // if we are past all items just return the last value --i; if(nextFrame) *nextFrame = -1; return i->second.val; } else if(_mode == DISCRETE) { if(i == begin()) { nframe = i->second.frame; rv = i->second.val; } else { nframe = i->second.frame; --i; rv = i->second.val; } } else { // INTERPOLATE if (i == begin()) { nframe = i->second.frame; rv = i->second.val; } else { int frame2 = i->second.frame; double val2 = i->second.val; --i; int frame1 = i->second.frame; double val1 = i->second.val; if(val2 != val1) nframe = 0; // Zero signifies the next frame should be determined by caller. else nframe = frame2; if (_valueType == VAL_LOG) { val1 = 20.0*fast_log10(val1); if (val1 < MusEGlobal::config.minSlider) val1=MusEGlobal::config.minSlider; val2 = 20.0*fast_log10(val2); if (val2 < MusEGlobal::config.minSlider) val2=MusEGlobal::config.minSlider; } val2 -= val1; val1 += (double(frame - frame1) * val2)/double(frame2 - frame1); if (_valueType == VAL_LOG) { val1 = exp10(val1/20.0); } rv = val1; } } if(nextFrame) *nextFrame = nframe; return rv; }
/* BIN * --- * Input parameters: * dataCol - the column with the channel data * numChans - number of channels in groupCol and qualCol * binLow - array of lower group boundaries * binHigh - array of higher group boundaries * numBins - number of binLow-binHigh group pairs * groupCol - the GROUPING column * qualCol - the QUALITY column * tabStops - array giving channels with tabs or stops */ int grp_do_bin(double *dataCol, long numChans, double *binLow, double *binHigh, long numBins, short *groupCol, short *qualCol, short *tabStops, dsErrList *errList, short partialBin, int isColReal){ long ii, jj, binLength, counter, tempLow, tempHigh, chanHigh; short isComplete; double maxVal, dataHigh; int tmpVar = 0; int isAscending = 0; /* Check for obviously bad inputs */ if(!dataCol || (numChans <= 0) || !binLow || !binHigh || (numBins < 0) || !groupCol || !qualCol || !tabStops){ if(errList) dsErrAdd(errList, dsDMGROUPBADPARAMERR, Accumulation, Generic); else err_msg("ERROR: At least one input parameter has an " "invalid value.\n"); return(GRP_ERROR); } /* Check for monotonically increasing or decreasing data */ if (check_increasing(dataCol, numChans) == 0) { isAscending = 1; } else { if ( check_decreasing(dataCol, numChans) != 0 ) { if(errList) dsErrAdd(errList, dsDMGROUPBADDATAORDERERR, Accumulation, Generic); else err_msg("ERROR: Data column is not increasing/decreasing.\n"); return(GRP_ERROR); } } if (isAscending) { dataHigh = dataCol[numChans - 1]; maxVal = binHigh[numBins - 1]; } else { dataHigh = dataCol[0]; maxVal = binLow[0]; } chanHigh = upper_bound(maxVal, dataCol, numChans, isAscending, isColReal, errList); /* Check if any bins overlap */ if(check_overlap(binLow, binHigh, numBins)){ if(errList) dsErrAdd(errList, dsDMGROUPOVERLAPBINSPECERR, Accumulation, Generic); else err_msg("ERROR: At least two bins in binspec overlap.\n"); return(GRP_ERROR); } /* Go through all binLow-binHigh pairs */ for(ii = 0; ii < numBins; ii++){ tempLow = lower_bound(binLow[ii], dataCol, numChans, isAscending, errList); tempHigh = upper_bound(binHigh[ii], dataCol, numChans, isAscending, isColReal, errList); if (!isAscending) { tmpVar = tempLow; tempLow = tempHigh; tempHigh = tmpVar; } if((tempLow == GRP_ERROR) || (tempHigh == GRP_ERROR)) continue; /* return(GRP_ERROR); */ /* If there are no data within the pair, skip to next pair */ if((tempHigh - tempLow) < 0) continue; binLength = tempHigh - tempLow; if(binLow[ii] > dataHigh){ if(errList) dsErrAdd(errList, dsDMGROUPINVALIDBINERR, Accumulation, Generic); else err_msg("ERROR: A bin boundary is invalid.\nMake " "sure the binspec fits within the bounds " "of the data.\n"); return(GRP_ERROR); } isComplete = GRP_TRUE; /* Check for a complete group */ for(jj = tempLow; jj <= tempHigh; jj++){ if ( (jj > chanHigh) || tabStops[jj] ) { isComplete = GRP_FALSE; break; } } /* If it's the last group, and partialBin is TRUE, then it's not complete. */ if( (partialBin && (ii == (numBins - 1))) || ((!isAscending) && (binLength < (numBins-1))) ) isComplete = GRP_FALSE; counter = 0; /* Create group - good or bad */ for(jj = tempLow; jj <= tempHigh; jj++){ /* Are we in a tab or stop? */ if(tabStops[jj]){ counter = 0; } /* Are we at the end of the table? */ else if(jj == (numChans - 1)){ /* Is this a single-element group? */ if(counter == 0){ if(isComplete){ groupCol[jj] = GRP_BEGIN; qualCol[jj] = GRP_GOOD; break; } else{ groupCol[jj] = GRP_BEGIN; qualCol[jj] = GRP_POOR; break; } } /* Does this complete the group? */ if(isComplete){ groupCol[jj] = GRP_MIDDLE; qualCol[jj] = GRP_GOOD; break; } else{ groupCol[jj] = GRP_MIDDLE; qualCol[jj] = GRP_POOR; break; } } /* Are we at the beginning of a group? */ else if(counter == 0){ if(isComplete){ groupCol[jj] = GRP_BEGIN; qualCol[jj] = GRP_GOOD; counter++; } else{ groupCol[jj] = GRP_BEGIN; qualCol[jj] = GRP_POOR; counter++; } } /* We must be in the middle of a group */ else{ if(isComplete){ groupCol[jj] = GRP_MIDDLE; qualCol[jj] = GRP_GOOD; counter++; } else{ groupCol[jj] = GRP_MIDDLE; qualCol[jj] = GRP_POOR; counter++; } } } /* end for(jj) */ } /* end for(ii) */ return(GRP_SUCCESS); }
vector<int> searchRange(vector<int>& nums, int target) { vector<int> ret; ret.push_back(lower_bound(nums, target)); ret.push_back(upper_bound(nums, target)); return ret; }
/* Create tabstops, given tab and stop boundaries */ int create_tabstops(long numChans, double *stopCol, double *tabCol, int isStopColReal, int isTabColReal, double *tBinLow, double *tBinHigh, long tNumBins, double *sBinLow, double *sBinHigh, long sNumBins, short *tabStops, int isAscending, dsErrList *errList){ long ii, jj, tempLow, tempHigh, tmpVar; /* Initialize tabStops */ for(ii = 0; ii < numChans; ii++) tabStops[ii] = GRP_FALSE; /* Go through stops */ for(ii = 0; ii < sNumBins; ii++){ tempLow = lower_bound(sBinLow[ii], stopCol, numChans, isAscending, errList); tempHigh = upper_bound(sBinHigh[ii], stopCol, numChans, isAscending, isStopColReal, errList); if (!isAscending) { tmpVar = tempLow; tempLow = tempHigh; tempHigh = tmpVar; } if((tempLow == GRP_ERROR) || (tempHigh == GRP_ERROR)) return(GRP_ERROR); for(jj = tempLow; jj <= tempHigh; jj++){ if(jj >= numChans) continue; else tabStops[jj] = GRP_TRUE; } } /* Go through tabs */ for(ii = 0; ii < tNumBins; ii++){ tempLow = lower_bound(tBinLow[ii], tabCol, numChans, isAscending, errList); tempHigh = upper_bound(tBinHigh[ii], tabCol, numChans, isAscending, isTabColReal, errList); if (!isAscending) { tmpVar = tempLow; tempLow = tempHigh; tempHigh = tmpVar; } if((tempLow == GRP_ERROR) || (tempHigh == GRP_ERROR)) return(GRP_ERROR); for(jj = tempLow; jj <= tempHigh; jj++){ if(jj >= numChans) continue; else tabStops[jj] = GRP_TRUE; } } return(GRP_SUCCESS); }
void operator()(I begin, I middle, I end, iterator_difference_t<I> len1, iterator_difference_t<I> len2, iterator_value_t<I> *buf, std::ptrdiff_t buf_size, C pred_ = C{}, P proj_ = P{}) const { using D = iterator_difference_t<I>; auto &&pred = invokable(pred_); auto &&proj = invokable(proj_); while(true) { // if middle == end, we're done if(len2 == 0) return; // shrink [begin, middle) as much as possible (with no moves), returning if it shrinks to 0 for(; true; ++begin, --len1) { if(len1 == 0) return; if(pred(proj(*middle), proj(*begin))) break; } if(len1 <= buf_size || len2 <= buf_size) { merge_adaptive_fn::impl(std::move(begin), std::move(middle), std::move(end), len1, len2, buf, pred, proj); return; } // begin < middle < end // *begin > *middle // partition [begin, m1) [m1, middle) [middle, m2) [m2, end) such that // all elements in: // [begin, m1) <= [middle, m2) // [middle, m2) < [m1, middle) // [m1, middle) <= [m2, end) // and m1 or m2 is in the middle of its range I m1; // "median" of [begin, middle) I m2; // "median" of [middle, end) D len11; // distance(begin, m1) D len21; // distance(middle, m2) // binary search smaller range if(len1 < len2) { // len >= 1, len2 >= 2 len21 = len2 / 2; m2 = next(middle, len21); m1 = upper_bound(begin, middle, proj(*m2), std::ref(pred), std::ref(proj)); len11 = distance(begin, m1); } else { if(len1 == 1) { // len1 >= len2 && len2 > 0, therefore len2 == 1 // It is known *begin > *middle ranges::iter_swap(begin, middle); return; } // len1 >= 2, len2 >= 1 len11 = len1 / 2; m1 = next(begin, len11); m2 = lower_bound(middle, end, proj(*m1), std::ref(pred), std::ref(proj)); len21 = distance(middle, m2); } D len12 = len1 - len11; // distance(m1, middle) D len22 = len2 - len21; // distance(m2, end) // [begin, m1) [m1, middle) [middle, m2) [m2, end) // swap middle two partitions middle = rotate(m1, std::move(middle), m2).begin(); // len12 and len21 now have swapped meanings // merge smaller range with recursive call and larger with tail recursion elimination if(len11 + len21 < len12 + len22) { (*this)(std::move(begin), std::move(m1), middle, len11, len21, buf, buf_size, std::ref(pred), std::ref(proj)); begin = std::move(middle); middle = std::move(m2); len1 = len12; len2 = len22; } else { (*this)(middle, std::move(m2), std::move(end), len12, len22, buf, buf_size, std::ref(pred), std::ref(proj)); end = std::move(middle); middle = std::move(m1); len1 = len11; len2 = len21; } } }
BCP_branching_decision MCF1_lp:: select_branching_candidates(const BCP_lp_result& lpres, const BCP_vec<BCP_var*>& vars, const BCP_vec<BCP_cut*>& cuts, const BCP_lp_var_pool& local_var_pool, const BCP_lp_cut_pool& local_cut_pool, BCP_vec<BCP_lp_branching_object*>& cands, bool force_branch) { if (generated_vars > 0) { return BCP_DoNotBranch; } if (lpres.objval() > upper_bound() - 1e-6) { return BCP_DoNotBranch_Fathomed; } int i, j; const int dummyStart = par.entry(MCF1_par::AddDummySourceSinkArcs) ? data.numarcs - data.numcommodities : data.numarcs; // find a few fractional original variables and do strong branching on them for (i = data.numcommodities-1; i >= 0; --i) { std::map<int,double>& f = flows[i]; int most_frac_ind = -1; double most_frac_val = 0.5-1e-6; double frac_val = 0.0; for (std::map<int,double>::iterator fi=f.begin(); fi != f.end(); ++fi){ if (fi->first >= dummyStart) continue; const double frac = fabs(fi->second - floor(fi->second) - 0.5); if (frac < most_frac_val) { most_frac_ind = fi->first; most_frac_val = frac; frac_val = fi->second; } } if (most_frac_ind >= 0) { BCP_vec<BCP_var*> new_vars; BCP_vec<int> fvp; BCP_vec<double> fvb; int lb = data.arcs[most_frac_ind].lb; int ub = data.arcs[most_frac_ind].ub; for (j = branch_history[i].size() - 1; j >= 0; --j) { // To correctly set lb/ub we need to check whether we have // already branched on this arc const MCF1_branch_decision& h = branch_history[i][j]; if (h.arc_index == most_frac_ind) { lb = CoinMax(lb, h.lb); ub = CoinMin(ub, h.ub); } } const int mid = static_cast<int>(floor(frac_val)); new_vars.push_back(new MCF1_branching_var(i, most_frac_ind, lb, mid, mid+1, ub)); // Look at the consequences of of this branch BCP_vec<int> child0_pos, child1_pos; BCP_vec<double> child0_bd, child1_bd; MCF1_branch_decision child0(most_frac_ind, lb, mid); MCF1_adjust_bounds(vars, i, child0, child0_pos, child0_bd); MCF1_branch_decision child1(most_frac_ind, mid+1, ub); MCF1_adjust_bounds(vars, i, child1, child1_pos, child1_bd); // Now put together the changes fvp.push_back(-1); fvp.append(child0_pos); fvp.append(child1_pos); fvb.push_back(0.0); fvb.push_back(0.0); fvb.append(child0_bd); for (j = child1_pos.size() - 1; j >= 0; --j) { fvb.push_back(0.0); fvb.push_back(1.0); } fvb.push_back(1.0); fvb.push_back(1.0); for (j = child0_pos.size() - 1; j >= 0; --j) { fvb.push_back(0.0); fvb.push_back(1.0); } fvb.append(child1_bd); cands.push_back(new BCP_lp_branching_object(2, // num of children &new_vars, NULL, // no new cuts &fvp,NULL,&fvb,NULL, NULL,NULL,NULL,NULL)); } } return BCP_DoBranch; }
// Return the line in which the offset appears. inline Line const& Line_map::line(int n) const { return (--upper_bound(n))->second; }
void exit_handler_intel_x64::unittest_100A_containers_map() const { auto mymap = std::map<int, int>(); auto mymap2 = std::map<int, int>(); mymap2[0] = 0; mymap2[1] = 1; mymap2[2] = 2; mymap2[3] = 3; mymap = mymap2; auto total = 0; for (auto iter = mymap.begin(); iter != mymap.end(); iter++) total += iter->second; auto rtotal = 0; for (auto iter = mymap.rbegin(); iter != mymap.rend(); iter++) rtotal += iter->second; auto ctotal = 0; for (auto iter = mymap.cbegin(); iter != mymap.cend(); iter++) ctotal += iter->second; auto crtotal = 0; for (auto iter = mymap.crbegin(); iter != mymap.crend(); iter++) crtotal += iter->second; expect_true(total == 6); expect_true(rtotal == 6); expect_true(ctotal == 6); expect_true(crtotal == 6); expect_true(mymap.size() == 4); expect_true(mymap.max_size() >= 4); expect_false(mymap.empty()); expect_true(mymap.at(0) == 0); expect_true(mymap.at(3) == 3); mymap.insert(std::pair<int, int>(4, 4)); mymap.erase(4); mymap = mymap2; mymap.swap(mymap2); mymap.swap(mymap2); mymap.emplace(); mymap.emplace_hint(mymap.begin(), std::pair<int, int>(4, 4)); mymap = mymap2; mymap.key_comp(); mymap.value_comp(); expect_true(mymap.find(0) != mymap.end()); expect_true(mymap.count(0) == 1); expect_true(mymap.lower_bound(0) != mymap.end()); expect_true(mymap.upper_bound(0) != mymap.end()); mymap.equal_range(0); mymap.get_allocator(); mymap.clear(); }
std::pair<line::const_iterator, line::const_iterator> line::range(double min, double max) const { return std::make_pair<line::const_iterator, line::const_iterator>( lower_bound(min), upper_bound(max) ); }
static typename util::detail::algorithm_result<ExPolicy, bool>::type parallel(ExPolicy policy, FwdIter1 first1, FwdIter1 last1, FwdIter2 first2, FwdIter2 last2, F && f) { if (first1 == last1) { return util::detail::algorithm_result<ExPolicy, bool>::get( false); } if (first2 == last2) { return util::detail::algorithm_result<ExPolicy, bool>::get( true); } util::cancellation_token<> tok; return util::partitioner<ExPolicy, bool>::call(policy, first2, std::distance(first2, last2), [first1, last1, first2, last2, f, tok]( FwdIter2 part_begin, std::size_t part_count ) mutable -> bool { FwdIter2 part_end = detail::next(part_begin, part_count); if (first2 != part_begin) { part_begin = upper_bound(part_begin, part_end, *part_begin, f, tok); if (tok.was_cancelled()) return false; if (part_begin == part_end) return true; } FwdIter1 low = lower_bound(first1, last1, *part_begin, f, tok); if (tok.was_cancelled()) return false; if (low == last1 || f(*part_begin, *low)) { tok.cancel(); return false; } FwdIter1 high = last1; if (part_end != last2) { high = upper_bound(low, last1, *part_end, f, tok); part_end = upper_bound(part_end, last2, *part_end, f, tok); if (tok.was_cancelled()) return false; } if (!sequential_includes(low, high, part_begin, part_end, f, tok)) { tok.cancel(); } return !tok.was_cancelled(); }, [](std::vector<hpx::future<bool> > && results) { return std::all_of( boost::begin(results), boost::end(results), [](hpx::future<bool>& val) { return val.get(); }); }); }
void prune() { auto old = upper_bound(hits.begin(), hits.end(), make_pair(now() - 1 * hour, -1)); if (old != hits.end()) { hits.erase(hits.begin(), old); } }
int SigList::ticksBeat(unsigned tick) const { ciSigEvent i = upper_bound(tick); assert(i != end()); return ticks_beat(i->second->n); }
double StepFunc::operator()(double input) { return values[upper_bound(thresholds.begin(), thresholds.end(), input)-thresholds.begin()]; }
iterator erase(iterator const& i) { erase(*i); // Note that the following would be undefined behaviour if I didn't know // implementation details of the iterator return upper_bound(*i); }
bool runMIRA(const std::vector<TaggerImpl* > &x, EncoderFeatureIndex *feature_index, double *alpha, size_t maxitr, float C, double eta, unsigned short shrinking_size, unsigned short thread_num) { std::vector<unsigned char> shrink(x.size()); std::vector<float> upper_bound(x.size()); std::vector<double> expected(feature_index->size()); std::fill(upper_bound.begin(), upper_bound.end(), 0.0); std::fill(shrink.begin(), shrink.end(), 0); int converge = 0; int all = 0; for (size_t i = 0; i < x.size(); ++i) all += (int)x[i]->size(); for (size_t itr = 0; itr < maxitr; ++itr) { int zeroone = 0; int err = 0; int active_set = 0; int upper_active_set = 0; double max_kkt_violation = 0.0; feature_index->clear(); for (size_t i = 0; i < x.size(); ++i) { if (shrink[i] >= shrinking_size) continue; ++active_set; std::fill(expected.begin(), expected.end(), 0.0); double cost_diff = x[i]->collins(&expected[0]); int error_num = x[i]->eval(); err += error_num; if (error_num) ++zeroone; if (error_num == 0) { ++shrink[i]; } else { shrink[i] = 0; double s = 0.0; for (size_t k = 0; k < expected.size(); ++k) s += expected[k] * expected[k]; double mu = _max(0.0, (error_num - cost_diff) / s); if (upper_bound[i] + mu > C) { mu = C - upper_bound[i]; ++upper_active_set; } else { max_kkt_violation = _max(error_num - cost_diff, max_kkt_violation); } if (mu > 1e-10) { upper_bound[i] += mu; upper_bound[i] = _min(C, upper_bound[i]); for (size_t k = 0; k < expected.size(); ++k) alpha[k] += mu * expected[k]; } } } double obj = 0.0; for (size_t i = 0; i < feature_index->size(); ++i) obj += alpha[i] * alpha[i]; std::cout << "iter=" << itr << " terr=" << 1.0 * err / all << " serr=" << 1.0 * zeroone / x.size() << " act=" << active_set << " uact=" << upper_active_set << " obj=" << obj << " kkt=" << max_kkt_violation << std::endl; if (max_kkt_violation <= 0.0) { std::fill(shrink.begin(), shrink.end(), 0); converge++; } else { converge = 0; } if (itr > maxitr || converge == 2) break; // 2 is ad-hoc } return true; }
void Guard::FindMinTerm (Guard *guard,Variable *targetVar, list<minTerm> &minTab) { list<minTerm>::iterator it; /* debug */ // cerr << "minTab : [" << endl ; // for (it = minTab.begin() ; it != minTab.end() ; it ++) { // cerr << "{ pred:" << it->pred ; // if (it->pred) cerr << "->" << *it->pred ; // cerr << ", pereET : " << it->pereET << ", minT: "<< it->minT << "}" << endl; // } // cerr << "]" << endl ; if (guard == NULL) return; if (!isMentioned(guard,targetVar)) { /* this minterm has no pred on targetVar */ minTerm minT = minTerm (NULL,NULL,guard); it = upper_bound(minTab.begin(),minTab.end(),minT); minTab.insert(it,minT); return; } // cerr << "\nin FindMinTerm" << *guard <<endl; if (guard->op == '+') { FindMinTerm (guard->fg,targetVar,minTab); FindMinTerm (guard->fd,targetVar,minTab); } else if (guard->op == '.') { if (guard->fg->var == targetVar) { minTerm minT = minTerm (guard->fg,guard,guard->fd); it = upper_bound(minTab.begin(),minTab.end(),minT); minTab.insert(it,minT); } else if (guard->fd->var == targetVar) { minTerm minT = minTerm (guard->fd,guard,guard->fg); it = upper_bound(minTab.begin(),minTab.end(),minT); minTab.insert(it,minT); } else { /* this minterm has no pred on targetVar */ minTerm minT = minTerm (NULL,NULL,guard); it = upper_bound(minTab.begin(),minTab.end(),minT); minTab.insert(it,minT); } } else { if (guard->var == targetVar) { minTerm minT = minTerm (guard,NULL,NULL); it = upper_bound(minTab.begin(),minTab.end(),minT); minTab.insert(it,minT); } else if (guard->op == 'h') { FindMinTerm (guard->fg,targetVar,minTab); } else { /* this minterm has no pred on targetVar */ minTerm minT = minTerm (NULL,NULL,guard); it = upper_bound(minTab.begin(),minTab.end(),minT); minTab.insert(it,minT); } } /* debug */ // cerr << "minTab : [" << endl ; // for (it = minTab.begin() ; it != minTab.end() ; it ++) { // cerr << "{ pred:" << it->pred ; // if (it->pred) cerr << "->" << *it->pred ; // cerr << ", pereET : " << it->pereET << ", minT: "<< it->minT << "}" << endl; // } // cerr << "]" << endl ; }
void SpParHelper::GlobalSelect(IT gl_rank, pair<KEY,VAL> * & low, pair<KEY,VAL> * & upp, pair<KEY,VAL> * array, IT length, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); IT begin = 0; IT end = length; // initially everyone is active pair<KEY, double> * wmminput = new pair<KEY,double>[nprocs]; // (median, #{actives}) MPI_Datatype MPI_sortType; MPI_Type_contiguous (sizeof(pair<KEY,double>), MPI_CHAR, &MPI_sortType); MPI_Type_commit (&MPI_sortType); KEY wmm; // our median pick IT gl_low, gl_upp; IT active = end-begin; // size of the active range IT nacts = 0; bool found = 0; int iters = 0; /* changes by shan : to add begin0 and end0 for exit condition */ IT begin0, end0; do { iters++; begin0 = begin; end0 = end; KEY median = array[(begin + end)/2].first; // median of the active range wmminput[myrank].first = median; wmminput[myrank].second = static_cast<double>(active); MPI_Allgather(MPI_IN_PLACE, 0, MPI_sortType, wmminput, 1, MPI_sortType, comm); double totact = 0; // total number of active elements for(int i=0; i<nprocs; ++i) totact += wmminput[i].second; // input to weighted median of medians is a set of (object, weight) pairs // the algorithm computes the first set of elements (according to total // order of "object"s), whose sum is still less than or equal to 1/2 for(int i=0; i<nprocs; ++i) wmminput[i].second /= totact ; // normalize the weights sort(wmminput, wmminput+nprocs); // sort w.r.t. medians double totweight = 0; int wmmloc=0; while( wmmloc<nprocs && totweight < 0.5 ) { totweight += wmminput[wmmloc++].second; } wmm = wmminput[wmmloc-1].first; // weighted median of medians pair<KEY,VAL> wmmpair = make_pair(wmm, VAL()); low =lower_bound (array+begin, array+end, wmmpair); upp =upper_bound (array+begin, array+end, wmmpair); IT loc_low = low-array; // #{elements smaller than wmm} IT loc_upp = upp-array; // #{elements smaller or equal to wmm} MPI_Allreduce( &loc_low, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); MPI_Allreduce( &loc_upp, &gl_upp, 1, MPIType<IT>(), MPI_SUM, comm); if(gl_upp < gl_rank) { // our pick was too small; only recurse to the right begin = (low - array); } else if(gl_rank < gl_low) { // our pick was too big; only recurse to the left end = (upp - array); } else { found = true; } active = end-begin; MPI_Allreduce(&active, &nacts, 1, MPIType<IT>(), MPI_SUM, comm); if (begin0 == begin && end0 == end) break; // ABAB: Active range did not shrink, so we break (is this kosher?) } while((nacts > 2*nprocs) && (!found)); delete [] wmminput; MPI_Datatype MPI_pairType; MPI_Type_contiguous (sizeof(pair<KEY,VAL>), MPI_CHAR, &MPI_pairType); MPI_Type_commit (&MPI_pairType); int * nactives = new int[nprocs]; nactives[myrank] = static_cast<int>(active); // At this point, actives are small enough MPI_Allgather(MPI_IN_PLACE, 0, MPI_INT, nactives, 1, MPI_INT, comm); int * dpls = new int[nprocs](); // displacements (zero initialized pid) partial_sum(nactives, nactives+nprocs-1, dpls+1); pair<KEY,VAL> * recvbuf = new pair<KEY,VAL>[nacts]; low = array + begin; // update low to the beginning of the active range MPI_Allgatherv(low, active, MPI_pairType, recvbuf, nactives, dpls, MPI_pairType, comm); pair<KEY,int> * allactives = new pair<KEY,int>[nacts]; int k = 0; for(int i=0; i<nprocs; ++i) { for(int j=0; j<nactives[i]; ++j) { allactives[k] = make_pair(recvbuf[k].first, i); k++; } } DeleteAll(recvbuf, dpls, nactives); sort(allactives, allactives+nacts); MPI_Allreduce(&begin, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); // update int diff = gl_rank - gl_low; for(int k=0; k < diff; ++k) { if(allactives[k].second == myrank) ++low; // increment the local pointer } delete [] allactives; begin = low-array; MPI_Allreduce(&begin, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); // update }
void k_additive_objectif(int *n, int *k, int *subset, int *Integral, double *X, int *nX, double *R, double *xl, double *xu) { int i,j,l,m,p,q; int sb = (int)sum_binom(*n,*k); double min_x, min_xplus, min_xminus; p = 0; q = 0; /* On parcourt les "lignes" de X */ for (m=0;m<*nX;m++) { if (*Integral==1) { /* Choquet */ for (i=1;i<sb;i++) { for (j=0;j<*n;j++) if (subset[i] & 1<<j) { min_x = X[j+p]; break; } for (l=j+1;l<*n;l++) if (subset[i] & 1<<l) min_x = INF(min_x, X[l+p]); R[i - 1 + q] = min_x; } } else { /* Sipos */ for (i=1;i<sb;i++) { for (j=0;j<*n;j++) if (subset[i] & 1<<j) { min_xplus = SUP(X[j+p],0); min_xminus = SUP(-X[j+p],0); break; } for (l=j+1;l<*n;l++) if (subset[i] & 1<<l) { min_xplus = INF(min_xplus, SUP(X[l+p],0)); min_xminus = INF(min_xminus, SUP(-X[l+p],0)); } R[i - 1 + q] = min_xplus - min_xminus; } } p += *n; q += sb - 1; } /* Initialise la borne inf. et sup. de la representation de Möbius */ for (i=0;i<sb-1;i++) { xl[i]=(double)lower_bound(i+1, *n); xu[i]=(double)upper_bound(i+1, *n); } }
void MessageSwitch::AddRoute(unsigned int begin, unsigned int end, BufferedTransformation &destination, const std::string &channel) { RangeRoute route(begin, end, Route(&destination, channel)); RouteList::iterator it = upper_bound(m_routes.begin(), m_routes.end(), route); m_routes.insert(it, route); }
bool R2CellUnion::contains(const GeoHash cellId) const { // Since all cells are ordered, if an ancestor of id exists, it must be the previous one. vector<GeoHash>::const_iterator it; it = upper_bound(_cellIds.begin(), _cellIds.end(), cellId); // it > cellId return it != _cellIds.begin() && (--it)->contains(cellId); // --it <= cellId }