void Box<DATA>::reset ( ) { for (int r=0;r<lowerBound.rows();++r) { for (int c=0;c<lowerBound.cols();++c) { lowerBound(r,c) = Constants<typename DATA::value_type>().max(); upperBound(r,c) = Constants<typename DATA::value_type>().min(); } } // for r }
SEXP getMZ(SEXP mz, SEXP intensity, SEXP scanindex, SEXP mzrange, SEXP scanrange, SEXP lastscan) { double *pmz, *pintensity,*p_res, mzrangeFrom,mzrangeTo; int i,*pscanindex,scanrangeFrom, scanrangeTo,ilastScan,nmz,ctScan,buflength; SEXP res; pmz = REAL(mz); nmz = GET_LENGTH(mz); pintensity = REAL(intensity); pscanindex = INTEGER(scanindex); int firstScan = 1; // is always 1 ilastScan = INTEGER(lastscan)[0]; mzrangeFrom = REAL(mzrange)[0]; mzrangeTo = REAL(mzrange)[1]; scanrangeFrom = INTEGER(scanrange)[0]; scanrangeTo = INTEGER(scanrange)[1]; if ((scanrangeFrom < firstScan) || (scanrangeFrom > ilastScan) || (scanrangeTo < firstScan) || (scanrangeTo > ilastScan)) error("Error in scanrange \n"); buflength = scanrangeTo - scanrangeFrom +1; PROTECT(res = NEW_NUMERIC(buflength)); p_res = NUMERIC_POINTER(res); i=0; for (ctScan=scanrangeFrom;ctScan<=scanrangeTo;ctScan++) { int idx,idx1,idx2; idx1 = pscanindex[ctScan -1] +1; if (ctScan == ilastScan) idx2 = nmz-1; else idx2 = pscanindex[ctScan]; int idx1b = lowerBound(mzrangeFrom, pmz, idx1-1, idx2-idx1-1); int idx2b = upperBound(mzrangeTo, pmz, idx1b, idx2-idx1b-1); int pc=0; p_res[i]=0; for (idx=idx1b;idx <= idx2b; idx++) { double mzval = pmz[idx]; if ((mzval <= mzrangeTo) && (mzval >= mzrangeFrom)) { if (pc==0) p_res[i] = mzval; else p_res[i] = ((pc * p_res[i]) + mzval) / (pc+1); pc++; } } i++; } UNPROTECT(1); return(res); }
int SymbolInfoJob::execute() { int ret = 1; int idx = -1; if (end.isNull()) { auto symbol = project()->findSymbol(start, &idx); if (!symbol.isNull()) { write(symbol); ret = 0; } } else { assert(start.fileId() == end.fileId()); auto symbols = project()->openSymbols(start.fileId()); if (symbols && symbols->count()) { bool exact = false; uint32_t idx = symbols->lowerBound(start, &exact); if (exact) { write("(list"); write(symbols->valueAt(idx++)); ret = 0; } else { switch (idx) { case 0: break; case std::numeric_limits<uint32_t>::max(): idx = symbols->count() - 1; break; default: --idx; break; } } const uint32_t count = symbols->count(); while (idx < count) { const Location loc = symbols->keyAt(idx); if (loc > end) break; if (loc >= start) { if (ret) write("(list"); write(symbols->valueAt(idx)); ret = 0; } ++idx; } if (!ret) write(")"); } } return ret; }
void addRegion(trace::Call &call, unsigned long long address, void *buffer, unsigned long long size) { if (retrace::verbosity >= 2) { std::cout << "region " << std::hex << "0x" << address << "-0x" << (address + size) << " -> " << "0x" << (uintptr_t)buffer << "-0x" << ((uintptr_t)buffer + size) << std::dec << "\n"; } if (!address) { // Ignore NULL pointer assert(buffer == nullptr); return; } const bool debug = #ifdef NDEBUG false #else true #endif ; if (debug) { RegionMap::iterator start = lowerBound(address); RegionMap::iterator stop = upperBound(address + size - 1); if (0) { // Forget all regions that intersect this new one. regionMap.erase(start, stop); } else { for (RegionMap::iterator it = start; it != stop; ++it) { warning(call) << std::hex << "region 0x" << address << "-0x" << (address + size) << " " "intersects existing region 0x" << it->first << "-0x" << (it->first + it->second.size) << "\n" << std::dec; assert(intersects(it, address, size)); } } } assert(buffer); Region region; region.buffer = buffer; region.size = size; regionMap[address] = region; }
/*! \brief Calculate the filled rectangle of the pipe \param pipeRect Rectangle of the pipe \return Rectangle to be filled ( fill and alarm brush ) \sa pipeRect(), alarmRect() */ QRect QwtThermo::fillRect( const QRect &pipeRect ) const { double origin; if ( d_data->originMode == OriginMinimum ) { origin = qMin( lowerBound(), upperBound() ); } else if ( d_data->originMode == OriginMaximum ) { origin = qMax( lowerBound(), upperBound() ); } else // OriginCustom { origin = d_data->origin; } const QwtScaleMap scaleMap = scaleDraw()->scaleMap(); int from = qRound( scaleMap.transform( d_data->value ) ); int to = qRound( scaleMap.transform( origin ) ); if ( to < from ) qSwap( from, to ); QRect fillRect = pipeRect; if ( d_data->orientation == Qt::Horizontal ) { fillRect.setLeft( from ); fillRect.setRight( to ); } else // Qt::Vertical { fillRect.setTop( from ); fillRect.setBottom( to ); } return fillRect.normalized(); }
double Master::guarantee() const { double lb = lowerBound(); if (fabs(lb) < machineEps()) { if (fabs(upperBound()) < machineEps()) return 0.0; else { Logger::ifout() << "Master::guarantee(): cannot compute guarantee with lower bound 0\n"; OGDF_THROW_PARAM(AlgorithmFailureException, ogdf::AlgorithmFailureCode::IllegalParameter); } } return fabs((upperBound() - lb)/lb * 100.0); }
Buffer* Buffers::createBuffer(QString name) { Buffer *b = new Buffer(new qce::Document(name, this)); b->document->setHighlighter(qce::SyntaxHighlighter::fromFilename(name)); connect(b->document, SIGNAL( cleanChanged(bool) ), this , SLOT ( cleanChanged(bool) )); connect(b->document, SIGNAL( fileNameChanged(QString, QString) ), this , SLOT ( fileNameChanged(QString, QString) )); int idx = lowerBound(m_buffers, name); beginInsertRows(QModelIndex(), idx, idx); m_buffers.insert(idx, b); endInsertRows(); return b; }
void solve(Point p1, Point p2) { if (p1.y == p2.y) return; if (p1.y > p2.y) { Point tmp = p1; p1 = p2; p2 = tmp; } for (int i = upperBound(p1.y); i <= lowerBound(p2.y); i++) if (i > 0 && i < 100) { double v = findX(p1,i,p2); if (maxX[i] < v) maxX[i] = v; if (minX[i] > v) minX[i] = v; } }
bool Box<DATA>::encloses ( const DATA& ar_DataVector ) { bool inside = true; for (int r=0;r<ar_DataVector.rows();++r) { for (int c=0;c<ar_DataVector.cols();++c) { inside &= (lowerBound(r,c) <= ar_DataVector(r,c)); inside &= (upperBound(r,c) >= ar_DataVector(r,c)); } } // for r return inside; }
/*! \brief Determine the value for a new position of the slider handle. \param pos Mouse position \return Value for the mouse position \sa isScrollPosition() */ double QwtSlider::scrolledTo( const QPoint &pos ) const { int p = ( orientation() == Qt::Horizontal ) ? pos.x() : pos.y(); p -= d_data->mouseOffset; int min = transform( lowerBound() ); int max = transform( upperBound() ); if ( min > max ) qSwap( min, max ); p = qBound( min, p, max ); return scaleMap().invTransform( p ); }
void Box<DATA>::enlarge_1_to_1 ( ) { typename DATA::value_type l(0); int r; for (r=0;r<lowerBound.rows();++r) { l = max(l,length(r)); } for (r=0;r<lowerBound.rows();++r) { lowerBound(r) -= (l-length(r))/2.0; upperBound(r) += (l-length(r))/2.0; } }
// ---------------------------------------------------------------------------- xpcc::DynamicPostman::DeliverInfo xpcc::DynamicPostman::deliverPacket(const Header &header, const SmartPointer& payload) { if (this->eventMap != 0) { if (header.destination == 0) { // EVENT EventMap::const_iterator lowerBound(this->eventMap->lower_bound(header.packetIdentifier)); EventMap::const_iterator upperBound(this->eventMap->upper_bound(header.packetIdentifier)); if (lowerBound != upperBound) { do { lowerBound->second.call(header, payload); lowerBound++; } while (lowerBound != upperBound); return OK; } return NO_EVENT; } else { // REQUEST RequestMap::const_iterator iterDestination(this->requenstMap->find(header.destination)); if (iterDestination != this->requenstMap->end()) { CallbackMap::const_iterator iterCallback(iterDestination->second.find(header.packetIdentifier)); if (iterCallback != iterDestination->second.end()) { ResponseHandle response(header); iterCallback->second.call(response, payload); return OK; } else { return NO_ACTION; } } else { return NO_COMPONENT; } } } else { return NO_COMPONENT; } }
sInt sBSpline::FindKnot(sF32 time) const { // range check if(time < Knots[0] || time >= Knots[Knots.Count - 1]) return -1; // binary search for the right knot interval sInt l = lowerBound(&Knots[Degree+1],time,Knots.Count - 2*Degree - 1); // skip over equal knots while possible while(l < Knots.Count - 2 * (Degree + 1) && Knots[Degree+1+l] == time) l++; sVERIFY(l >= 0 && l <= Knots.Count - 2 * (Degree + 1)); return l; }
double getScanEIC(int scan, double from, double to, double *pmz, double *pintensity, int *pscanindex,int nmz, int lastScan) { int idx,idx1,idx2; double sum=0.0; idx1 = pscanindex[scan -1] +1; if (scan == lastScan) idx2 = nmz-1; else idx2 = pscanindex[scan]; int idx1b = lowerBound(from, pmz, idx1-1, idx2-idx1); int idx2b = upperBound(to, pmz, idx1b, idx2-idx1b); for (idx=idx1b;idx <= idx2b; idx++) { double mzval = pmz[idx-1]; if ((mzval <= to) && (mzval >= from)) sum += pintensity[idx-1]; } return(sum); }
int main() { do { scanf("%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,&c.x,&c.y); if (a.x + b.x + c.x + a.y + b.y + c.y == 0) break; for (int i = 1; i < 100; i++) { maxX[i] = -1; minX[i] = 101; } solve(a,b); solve(b,c); solve(a,c); res = 0; for (int i = 1; i < 100; i++) if (maxX[i] > 0) res += min(99,lowerBound(maxX[i])) - max(1,upperBound(minX[i])) + 1; printf("%4d\n",res); } while (1); return 0; }
void thresholdImage( cv_bridge::CvImagePtr cvPtr, bool byColor ) { // blur first cv::GaussianBlur( cvPtr->image, cvPtr->image, cv::Size( 5, 5 ), 0 ); if( byColor == true ) { cv::cvtColor( cvPtr->image, cvPtr->image, CV_BGR2HSV ); cv::Mat destImage; cv::Scalar lowerBound( std::max( hValue_ - hRange_/2, 0 ), 50, 50 ); cv::Scalar upperBound( std::min( hValue_ + hRange_/2, 255 ), 255, 255 ); cv::inRange( cvPtr->image, lowerBound, upperBound, cvPtr->image ); } else { cv::cvtColor( cvPtr->image, cvPtr->image, CV_BGR2GRAY ); cv::Point min_loc; cv::Point max_loc; double min_val; double max_val; cv::minMaxLoc( cvPtr->image, &min_val, &max_val, &min_loc, &max_loc ); cv::threshold( cvPtr->image, cvPtr->image, max_val - 1, //100, 255, CV_THRESH_BINARY ); } cvPtr->encoding = enc::MONO8; thresholdPub_.publish(cvPtr->toImageMsg()); }
/*! Mouse press event handler \param event Mouse event */ void QwtAbstractSlider::mousePressEvent( QMouseEvent *event ) { if ( isReadOnly() ) { event->ignore(); return; } if ( !d_data->isValid || lowerBound() == upperBound() ) return; d_data->isScrolling = isScrollPosition( event->pos() ); if ( d_data->isScrolling ) { d_data->pendingValueChanged = false; Q_EMIT sliderPressed(); } }
void addRegion(unsigned long long address, void *buffer, unsigned long long size) { // Forget all regions that intersect this new one. if (0) { RegionMap::iterator start = lowerBound(address); if (start != regionMap.end()) { RegionMap::iterator stop = upperBound(address + size); regionMap.erase(start, stop); } } assert(buffer); Region region; region.buffer = buffer; region.size = size; regionMap[address] = region; }
void sendStackData(int fd, void** buf, int count, const MapElement* list) { for (int i = 0; i < count; ++i) { ucontext* context = static_cast<ucontext*>(buf[i]); unsigned long start = context->uc_mcontext.arm_sp; const MapElement* found = lowerBound(list, start, mycompare); if (found != NULL) { if (found != list && found->m_start != start) found = found->m_prev; } else { found = list->m_prev; } if ((found->m_start <= start) && (found->m_end >= start) && ((found->m_protect & 7) == (MapElement::READ | MapElement::WRITE))) { SendOnceGeneral once = { reinterpret_cast<void*>(start), found->m_end - start, 0x80000000, DATA_ATTR_USER_CONTENT }; sendTillEnd(fd, reinterpret_cast<const char*>(&once), sizeof(once)); sendTillEnd(fd, reinterpret_cast<const char*>(start), found->m_end - start); } } }
bool NumericRangeTermEnum::next() { // if a current term exists, the actual enum is initialized: try change to next term, if no // such term exists, fall-through if (currentTerm) { BOOST_ASSERT(actualEnum); if (actualEnum->next()) { currentTerm = actualEnum->term(); if (termCompare(currentTerm)) { return true; } } } // if all above fails, we go forward to the next enum, if one is available currentTerm.reset(); while (rangeBounds.size() >= 2) { BOOST_ASSERT(rangeBounds.size() % 2 == 0); // close the current enum and read next bounds if (actualEnum) { actualEnum->close(); actualEnum.reset(); } String lowerBound(rangeBounds.removeFirst()); currentUpperBound = rangeBounds.removeFirst(); // create a new enum actualEnum = reader->terms(termTemplate->createTerm(lowerBound)); currentTerm = actualEnum->term(); if (currentTerm && termCompare(currentTerm)) { return true; } // clear the current term for next iteration currentTerm.reset(); } // no more sub-range enums available BOOST_ASSERT(rangeBounds.empty() && !currentTerm); return false; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void Threshold::execute() { std::stringstream ss; int err = 0; setErrorCondition(err); VoxelDataContainer* m = getVoxelDataContainer(); if(NULL == m) { setErrorCondition(-999); notifyErrorMessage("The DataContainer Object was NULL", getErrorCondition()); return; } setErrorCondition(0); int64_t totalPoints = m->getTotalPoints(); size_t totalFields = m->getNumFieldTuples(); size_t totalEnsembles = m->getNumEnsembleTuples(); dataCheck(false, totalPoints, totalFields, totalEnsembles); if(m_OverwriteArray) { CREATE_NON_PREREQ_DATA(m, DREAM3D, CellData, ProcessedImageData, ss, ImageProcessing::DefaultPixelType, ImageProcessing::DefaultArrayType, 0, totalPoints, 1) } if (getErrorCondition() < 0) { return; } //get dims size_t udims[3] = {0,0,0}; m->getDimensions(udims); #if (CMP_SIZEOF_SIZE_T == 4) typedef int32_t DimType; #else typedef int64_t DimType; #endif DimType dims[3] = { static_cast<DimType>(udims[0]), static_cast<DimType>(udims[1]), static_cast<DimType>(udims[2]), }; //wrap input as itk image ImageProcessing::DefaultImageType::Pointer inputImage=ITKUtilities::Dream3DtoITK(m, m_RawImageData); //define threshold filters typedef itk::BinaryThresholdImageFilter <ImageProcessing::DefaultImageType, ImageProcessing::DefaultImageType> BinaryThresholdImageFilterType; typedef itk::BinaryThresholdImageFilter <ImageProcessing::DefaultSliceType, ImageProcessing::DefaultSliceType> BinaryThresholdImageFilterType2D; if(m_Method>=0 && m_Method<=11) { //define hitogram generator (will make the same kind of histogram for 2 and 3d images typedef itk::Statistics::ImageToHistogramFilter<ImageProcessing::DefaultImageType> HistogramGenerator; //find threshold value w/ histogram itk::HistogramThresholdCalculator< HistogramGenerator::HistogramType, uint8_t >::Pointer calculator; typedef itk::HuangThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > HuangCalculatorType; typedef itk::IntermodesThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > IntermodesCalculatorType; typedef itk::IsoDataThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > IsoDataCalculatorType; typedef itk::KittlerIllingworthThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > KittlerIllingowrthCalculatorType; typedef itk::LiThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > LiCalculatorType; typedef itk::MaximumEntropyThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > MaximumEntropyCalculatorType; typedef itk::MomentsThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > MomentsCalculatorType; typedef itk::OtsuThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > OtsuCalculatorType; typedef itk::RenyiEntropyThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > RenyiEntropyCalculatorType; typedef itk::ShanbhagThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > ShanbhagCalculatorType; typedef itk::TriangleThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > TriangleCalculatorType; typedef itk::YenThresholdCalculator< HistogramGenerator::HistogramType, uint8_t > YenCalculatorType; switch(m_Method) { case 0: { calculator = HuangCalculatorType::New(); } break; case 1: { calculator = IntermodesCalculatorType::New(); } break; case 2: { calculator = IsoDataCalculatorType::New(); } break; case 3: { calculator = KittlerIllingowrthCalculatorType::New(); } break; case 4: { calculator = LiCalculatorType::New(); } break; case 5: { calculator = MaximumEntropyCalculatorType::New(); } break; case 6: { calculator = MomentsCalculatorType::New(); } break; case 7: { calculator = OtsuCalculatorType::New(); } break; case 8: { calculator = RenyiEntropyCalculatorType::New(); } break; case 9: { calculator = ShanbhagCalculatorType::New(); } break; case 10: { calculator = TriangleCalculatorType::New(); } break; case 11: { calculator = YenCalculatorType::New(); } break; } if(m_Slice) { //define 2d histogram generator typedef itk::Statistics::ImageToHistogramFilter<ImageProcessing::DefaultSliceType> HistogramGenerator2D; HistogramGenerator2D::Pointer histogramFilter2D = HistogramGenerator2D::New(); //specify number of bins / bounds typedef HistogramGenerator2D::HistogramSizeType SizeType; SizeType size( 1 ); size[0] = 255; histogramFilter2D->SetHistogramSize( size ); histogramFilter2D->SetMarginalScale( 10.0 ); HistogramGenerator2D::HistogramMeasurementVectorType lowerBound( 1 ); HistogramGenerator2D::HistogramMeasurementVectorType upperBound( 1 ); lowerBound[0] = 0; upperBound[0] = 256; histogramFilter2D->SetHistogramBinMinimum( lowerBound ); histogramFilter2D->SetHistogramBinMaximum( upperBound ); //wrap output buffer as image ImageProcessing::DefaultImageType::Pointer outputImage=ITKUtilities::Dream3DtoITK(m, m_ProcessedImageData); //loop over slices for(int i=0; i<dims[2]; i++) { //get slice ImageProcessing::DefaultSliceType::Pointer slice = ITKUtilities::ExtractSlice<ImageProcessing::DefaultPixelType>(inputImage, ImageProcessing::ZSlice, i); //find histogram histogramFilter2D->SetInput( slice ); histogramFilter2D->Update(); const HistogramGenerator::HistogramType * histogram = histogramFilter2D->GetOutput(); //calculate threshold level calculator->SetInput(histogram); calculator->Update(); const uint8_t thresholdValue = calculator->GetThreshold(); //threshold BinaryThresholdImageFilterType2D::Pointer thresholdFilter = BinaryThresholdImageFilterType2D::New(); thresholdFilter->SetInput(slice); thresholdFilter->SetLowerThreshold(thresholdValue); thresholdFilter->SetUpperThreshold(255); thresholdFilter->SetInsideValue(255); thresholdFilter->SetOutsideValue(0); thresholdFilter->Update(); //copy back into volume ITKUtilities::SetSlice<ImageProcessing::DefaultPixelType>(outputImage, thresholdFilter->GetOutput(), ImageProcessing::ZSlice, i); } } else { //specify number of bins / bounds HistogramGenerator::Pointer histogramFilter = HistogramGenerator::New(); typedef HistogramGenerator::HistogramSizeType SizeType; SizeType size( 1 ); size[0] = 255; histogramFilter->SetHistogramSize( size ); histogramFilter->SetMarginalScale( 10.0 ); HistogramGenerator::HistogramMeasurementVectorType lowerBound( 1 ); HistogramGenerator::HistogramMeasurementVectorType upperBound( 1 ); lowerBound[0] = 0; upperBound[0] = 256; histogramFilter->SetHistogramBinMinimum( lowerBound ); histogramFilter->SetHistogramBinMaximum( upperBound ); //find histogram histogramFilter->SetInput( inputImage ); histogramFilter->Update(); const HistogramGenerator::HistogramType * histogram = histogramFilter->GetOutput(); //calculate threshold level calculator->SetInput(histogram); calculator->Update(); const uint8_t thresholdValue = calculator->GetThreshold(); //threshold BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New(); thresholdFilter->SetInput(inputImage); thresholdFilter->SetLowerThreshold(thresholdValue); thresholdFilter->SetUpperThreshold(255); thresholdFilter->SetInsideValue(255); thresholdFilter->SetOutsideValue(0); thresholdFilter->GetOutput()->GetPixelContainer()->SetImportPointer(m_ProcessedImageData, totalPoints, false); thresholdFilter->Update(); } } else if(m_Method==12)//manual { //threshold BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New(); thresholdFilter->SetInput(inputImage); thresholdFilter->SetLowerThreshold(m_ManualParameter); thresholdFilter->SetUpperThreshold(255); thresholdFilter->SetInsideValue(255); thresholdFilter->SetOutsideValue(0); thresholdFilter->GetOutput()->GetPixelContainer()->SetImportPointer(m_ProcessedImageData, totalPoints, false); thresholdFilter->Update(); } /* else if(m_Method==13)//robust automatic { typedef itk::GradientMagnitudeImageFilter<ImageProcessing::DefaultImageType, ImageProcessing::DefaultImageType> GradientMagnitudeType; typedef itk::GradientMagnitudeImageFilter<ImageProcessing::DefaultSliceType, ImageProcessing::DefaultSliceType> GradientMagnitudeType2D; typedef itk::itkRobustAutomaticThresholdCalculator<ImageProcessing::DefaultImageType,ImageProcessing::DefaultImageType> SelectionType; typedef itk::itkRobustAutomaticThresholdCalculator<ImageProcessing::DefaultSliceType,ImageProcessing::DefaultSliceType> SelectionType2D; if(m_slice) { //wrap output buffer as image ImageProcessing::DefaultImageType::Pointer outputImage=ITKUtilities::Dream3DtoITK(m, m_ProcessedImageData); //loop over slices for(int i=0; i<dims[2]; i++) { //get slice ImageProcessing::DefaultSliceType::Pointer slice = ITKUtilities::ExtractSlice<ImageProcessing::DefaultPixelType>(inputImage, ImageProcessing::ZSlice, i); //find gradient GradientMagnitudeType2D::Pointer gradientFilter = GradientMagnitudeType2D::New(); gradientFilter->setInput(slice); gradientFilter->Update(); //calculate thershold SelectionType2D::Pointer calculatorFilter = SelectionType2D::New(); calculatorFilter->SetInput(slice); calculatorFilter->SetGradientImage(gradientFilter->GetOutput()); calculatorFilter->SetPow(m_ManualParameter); calculatorFilter->Update(); const uint8_t thresholdValue = calculatorFilter->GetOutput(); //threshold BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New(); thresholdFilter->SetInput(inputImage); thresholdFilter->SetLowerThreshold(thresholdValue); thresholdFilter->SetUpperThreshold(255); thresholdFilter->SetInsideValue(255); thresholdFilter->SetOutsideValue(0); thresholdFilter->Update(); //copy back into volume ITKUtilities::SetSlice<ImageProcessing::DefaultPixelType>(outputImage, thresholdFilter->GetOutput(), ImageProcessing::ZSlice, i); } } else { //find gradient GradientMagnitudeType::Pointer gradientFilter = GradientMagnitudeType::New(); gradientFilter->setInput(inputImage); gradientFilter->Update(); //calculate threshold SelectionType::Pointer calculatorFilter = SelectionType::New(); calculatorFilter->SetInput(inputImage); calculatorFilter->SetGradientImage(gradientFilter->GetOutput()); calculatorFilter->SetPow(m_ManualParameter); calculatorFilter->Update(); const uint8_t thresholdValue = calculatorFilter->GetOutput(); //threshold BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New(); thresholdFilter->SetInput(inputImage); thresholdFilter->SetLowerThreshold(thresholdValue); thresholdFilter->SetUpperThreshold(255); thresholdFilter->SetInsideValue(255); thresholdFilter->SetOutsideValue(0); thresholdFilter->GetOutput()->GetPixelContainer()->SetImportPointer(m_ProcessedImageData, totalPoints, false); thresholdFilter->Update(); } } */ //array name changing/cleanup if(m_OverwriteArray) { m->removeCellData(m_SelectedCellArrayName); bool check = m->renameCellData(m_ProcessedImageDataArrayName, m_SelectedCellArrayName); } /* Let the GUI know we are done with this filter */ notifyStatusMessage("Complete"); }
FGSimplexTrim::FGSimplexTrim(FGFDMExec * fdm, TrimMode mode) { std::clock_t time_start=clock(), time_trimDone; // variables FGTrimmer::Constraints constraints; if (fdm->GetDebugLevel() > 0) { std::cout << "\n-----Performing Simplex Based Trim --------------\n" << std::endl; } // defaults std::string aircraftName = fdm->GetAircraft()->GetAircraftName(); FGPropertyNode* node = fdm->GetPropertyManager()->GetNode(); double rtol = node->GetDouble("trim/solver/rtol"); double abstol = node->GetDouble("trim/solver/abstol"); double speed = node->GetDouble("trim/solver/speed"); // must be > 1, 2 typical double random = node->GetDouble("trim/solver/random"); int iterMax = int(node->GetDouble("trim/solver/iterMax")); bool showConvergence = node->GetBool("trim/solver/showConvergence"); bool pause = node->GetBool("trim/solver/pause"); bool showSimplex = node->GetBool("trim/solver/showSimplex"); // flight conditions double phi = fdm->GetIC()->GetPhiRadIC(); double theta = fdm->GetIC()->GetThetaRadIC(); double gd = fdm->GetInertial()->gravity(); constraints.velocity = fdm->GetIC()->GetVtrueFpsIC(); constraints.altitude = fdm->GetIC()->GetAltitudeASLFtIC(); constraints.gamma = fdm->GetIC()->GetFlightPathAngleRadIC(); constraints.rollRate = 0; constraints.pitchRate = 0; constraints.yawRate = tan(phi)*gd*cos(theta)/constraints.velocity; constraints.stabAxisRoll = true; // FIXME, make this an option // initial solver state int n = 6; std::vector<double> initialGuess(n), lowerBound(n), upperBound(n), initialStepSize(n); lowerBound[0] = node->GetDouble("trim/solver/throttleMin"); lowerBound[1] = node->GetDouble("trim/solver/elevatorMin"); lowerBound[2] = node->GetDouble("trim/solver/alphaMin"); lowerBound[3] = node->GetDouble("trim/solver/aileronMin"); lowerBound[4] = node->GetDouble("trim/solver/rudderMin"); lowerBound[5] = node->GetDouble("trim/solver/betaMin"); upperBound[0] = node->GetDouble("trim/solver/throttleMax"); upperBound[1] = node->GetDouble("trim/solver/elevatorMax"); upperBound[2] = node->GetDouble("trim/solver/alphaMax"); upperBound[3] = node->GetDouble("trim/solver/aileronMax"); upperBound[4] = node->GetDouble("trim/solver/rudderMax"); upperBound[5] = node->GetDouble("trim/solver/betaMax"); initialStepSize[0] = node->GetDouble("trim/solver/throttleStep"); initialStepSize[1] = node->GetDouble("trim/solver/elevatorStep"); initialStepSize[2] = node->GetDouble("trim/solver/alphaStep"); initialStepSize[3] = node->GetDouble("trim/solver/aileronStep"); initialStepSize[4] = node->GetDouble("trim/solver/rudderStep"); initialStepSize[5] = node->GetDouble("trim/solver/betaStep"); initialGuess[0] = node->GetDouble("trim/solver/throttleGuess"); initialGuess[1] = node->GetDouble("trim/solver/elevatorGuess"); initialGuess[2] = node->GetDouble("trim/solver/alphaGuess"); initialGuess[3] = node->GetDouble("trim/solver/aileronGuess"); initialGuess[4] = node->GetDouble("trim/solver/rudderGuess"); initialGuess[5] = node->GetDouble("trim/solver/betaGuess"); // solve FGTrimmer * trimmer = new FGTrimmer(fdm, &constraints); Callback callback(aircraftName, trimmer); FGNelderMead * solver = NULL; solver = new FGNelderMead(trimmer,initialGuess, lowerBound, upperBound, initialStepSize,iterMax,rtol, abstol,speed,random,showConvergence,showSimplex,pause,&callback); while(solver->status()==1) solver->update(); time_trimDone = std::clock(); // output if (fdm->GetDebugLevel() > 0) { trimmer->printSolution(std::cout,solver->getSolution()); std::cout << "\nfinal cost: " << std::scientific << std::setw(10) << trimmer->eval(solver->getSolution()) << std::endl; std::cout << "\ntrim computation time: " << (time_trimDone - time_start)/double(CLOCKS_PER_SEC) << "s \n" << std::endl; } delete solver; delete trimmer; }
void OptimalRanking::doCall( const Graph& G, NodeArray<int> &rank, EdgeArray<bool> &reversed, const EdgeArray<int> &length, const EdgeArray<int> &costOrig) { MinCostFlowReinelt<int> mcf; // construct min-cost flow problem GraphCopy GC; GC.createEmpty(G); // compute connected component of G NodeArray<int> component(G); int numCC = connectedComponents(G,component); // intialize the array of lists of nodes contained in a CC Array<List<node> > nodesInCC(numCC); for(node v : G.nodes) nodesInCC[component[v]].pushBack(v); EdgeArray<edge> auxCopy(G); rank.init(G); for(int i = 0; i < numCC; ++i) { GC.initByNodes(nodesInCC[i], auxCopy); makeLoopFree(GC); for(edge e : GC.edges) if(reversed[GC.original(e)]) GC.reverseEdge(e); // special cases: if(GC.numberOfNodes() == 1) { rank[GC.original(GC.firstNode())] = 0; continue; } else if(GC.numberOfEdges() == 1) { edge e = GC.original(GC.firstEdge()); rank[e->source()] = 0; rank[e->target()] = length[e]; continue; } EdgeArray<int> lowerBound(GC,0); EdgeArray<int> upperBound(GC,mcf.infinity()); EdgeArray<int> cost(GC); NodeArray<int> supply(GC); for(edge e : GC.edges) cost[e] = -length[GC.original(e)]; for(node v : GC.nodes) { int s = 0; edge e; forall_adj_edges(e,v) { if(v == e->source()) s += costOrig[GC.original(e)]; else s -= costOrig[GC.original(e)]; } supply[v] = s; } OGDF_ASSERT(isAcyclic(GC) == true); // find min-cost flow EdgeArray<int> flow(GC); NodeArray<int> dual(GC); #ifdef OGDF_DEBUG bool feasible = #endif mcf.call(GC, lowerBound, upperBound, cost, supply, flow, dual); OGDF_ASSERT(feasible); for(node v : GC.nodes) rank[GC.original(v)] = dual[v]; } }
// From Real-time Collision Detection, p179. bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const { float32 tmin = -b2_maxFloat; float32 tmax = b2_maxFloat; b2Vec2 p = input.p1; b2Vec2 d = input.p2 - input.p1; b2Vec2 absD = b2Abs(d); b2Vec2 normal; for (int32 i = 0; i < 2; ++i) { if (absD(i) < b2_epsilon) { // Parallel. if (p(i) < lowerBound(i) || upperBound(i) < p(i)) { return false; } } else { float32 inv_d = 1.0f / d(i); float32 t1 = (lowerBound(i) - p(i)) * inv_d; float32 t2 = (upperBound(i) - p(i)) * inv_d; // Sign of the normal vector. float32 s = -1.0f; if (t1 > t2) { b2Swap(t1, t2); s = 1.0f; } // Push the min up if (t1 > tmin) { normal.SetZero(); normal(i) = s; tmin = t1; } // Pull the max down tmax = b2Min(tmax, t2); if (tmin > tmax) { return false; } } } // Does the ray start inside the box? // Does the ray intersect beyond the max fraction? if (tmin < 0.0f || input.maxFraction < tmin) { return false; } // Intersection. output->fraction = tmin; output->normal = normal; return true; }
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); }
String Symbol::toString(const std::shared_ptr<Project> &project, const Flags<ToStringFlag> cursorInfoFlags, Flags<Location::ToStringFlag> locationToStringFlags, const Set<String> &pieceFilters) const { auto filterPiece = [&pieceFilters](const char *name) { return pieceFilters.isEmpty() || pieceFilters.contains(name); }; auto properties = [this, &filterPiece]() -> String { List<String> ret; if (isDefinition() && filterPiece("definition")) ret << "Definition"; if (isContainer() && filterPiece("container")) ret << "Container"; if ((flags & PureVirtualMethod) == PureVirtualMethod && filterPiece("purevirtual")) ret << "Pure Virtual"; if (flags & VirtualMethod && filterPiece("virtual")) ret << "Virtual"; if (flags & ConstMethod) { if (filterPiece("constmethod")) ret << "ConstMethod"; } else if (flags & StaticMethod && filterPiece("static")) { ret << "Static"; } if (flags & Variadic && filterPiece("variadic")) ret << "Variadic"; if (flags & Auto && filterPiece("auto")) ret << "Auto"; if (flags & MacroExpansion && filterPiece("macroexpansion")) ret << "MacroExpansion"; if (flags & TemplateSpecialization && filterPiece("templatespecialization")) ret << "TemplateSpecialization"; if (flags & TemplateReference && filterPiece("templatereference")) ret << "TemplateReference"; if (ret.isEmpty()) return String(); return String::join(ret, ' ') + '\n'; }; List<String> bases; List<String> args; if (project) { if (filterPiece("baseclasses")) { for (const auto &base : baseClasses) { bool found = false; for (const auto &sym : project->findByUsr(base, location.fileId(), Project::ArgDependsOn)) { bases << sym.symbolName; found = true; break; } if (!found) { bases << base; } } } if (filterPiece("arguments")) { for (const auto &arg : arguments) { const String symName = project->findSymbol(arg.cursor).symbolName; if (!symName.isEmpty()) { args << symName; } else { args << arg.cursor.toString(locationToStringFlags & ~Location::ShowContext); } } } } else if (filterPiece("baseClasses")) { bases = baseClasses; } String ret; auto writePiece = [&ret, &filterPiece](const char *key, const char *filter, const String &piece) { if (piece.isEmpty()) return; if (!filterPiece(filter)) return; if (key && strlen(key)) ret << key << ": "; ret << piece << "\n"; }; writePiece(0, "location", location.toString(locationToStringFlags)); writePiece("SymbolName", "symbolname", symbolName); writePiece("Kind", "kind", kindSpelling()); if (filterPiece("type")) { if (!typeName.isEmpty()) { ret += "Type: " + typeName + "\n"; } else if (type != CXType_Invalid) { ret += "Type: " + RTags::eatString(clang_getTypeKindSpelling(type)) + "\n"; } } writePiece("SymbolLength", "symbollength", std::to_string(symbolLength)); if (startLine != -1) writePiece("Range", "range", String::format<32>("%d:%d-%d:%d", startLine, startColumn, endLine, endColumn)); #if CINDEX_VERSION_MINOR > 1 if (kind == CXCursor_EnumConstantDecl) writePiece("Enum Value", "enumvalue", String::format<32>("%lld/0x%0llx", static_cast<long long>(enumValue), static_cast<long long>(enumValue))); if (isDefinition() && RTags::isFunction(kind)) writePiece("Stack cost", "stackcost", std::to_string(stackCost)); #endif writePiece(0, "linkage", linkageSpelling(linkage)); ret += properties(); writePiece("Usr", "usr", usr); if (size) writePiece("sizeof", "sizeof", std::to_string(size)); if (fieldOffset >= 0) writePiece("Field offset (bits/bytes)", "fieldoffset", String::format<32>("%d/%d", fieldOffset, fieldOffset / 8)); if (alignment >= 0) writePiece("Alignment", "alignment", std::to_string(alignment)); if (!args.isEmpty()) writePiece("Arguments", "arguments", String::join(args, ", ")); if (!bases.isEmpty()) writePiece("Base classes", "baseclasses", String::join(bases, ", ")); writePiece("Brief comment", "briefcomment", briefComment); writePiece("XML comment", "xmlcomment", xmlComment); if ((cursorInfoFlags & IncludeParents && filterPiece("parent")) || (cursorInfoFlags & (IncludeContainingFunction) && filterPiece("cf")) || (cursorInfoFlags & (IncludeContainingFunctionLocation) && filterPiece("cfl"))) { auto syms = project->openSymbols(location.fileId()); uint32_t idx = -1; if (syms) { idx = syms->lowerBound(location); if (idx == std::numeric_limits<uint32_t>::max()) { idx = syms->count() - 1; } } const unsigned int line = location.line(); const unsigned int column = location.column(); while (idx-- > 0) { const Symbol s = syms->valueAt(idx); if (s.isDefinition() && s.isContainer() && comparePosition(line, column, s.startLine, s.startColumn) >= 0 && comparePosition(line, column, s.endLine, s.endColumn) <= 0) { if (cursorInfoFlags & IncludeContainingFunctionLocation) writePiece("Containing function location", "cfl", s.location.toString(locationToStringFlags)); if (cursorInfoFlags & IncludeContainingFunction) writePiece("Containing function", "cf", s.symbolName); if (cursorInfoFlags & IncludeParents) writePiece("Parent", "parent", s.location.toString(locationToStringFlags)); // redundant, this is a mess break; } } } if (cursorInfoFlags & IncludeTargets && project && filterPiece("targets")) { const auto targets = project->findTargets(*this); if (targets.size()) { ret.append("Targets:\n"); auto best = RTags::bestTarget(targets); ret.append(String::format<128>(" %s\n", best.location.toString(locationToStringFlags).constData())); for (const auto &tit : targets) { if (tit.location != best.location) ret.append(String::format<128>(" %s\n", tit.location.toString(locationToStringFlags).constData())); } } } if (cursorInfoFlags & IncludeReferences && project && !isReference() && filterPiece("references")) { const auto references = project->findCallers(*this); if (references.size()) { ret.append("References:\n"); for (const auto &r : references) { ret.append(String::format<128>(" %s\n", r.location.toString(locationToStringFlags).constData())); } } } return ret; }
Value Symbol::toValue(const std::shared_ptr<Project> &project, Flags<ToStringFlag> toStringFlags, Flags<Location::ToStringFlag> locationToStringFlags, const Set<String> &pieceFilters) const { auto filterPiece = [&pieceFilters](const char *name) { return pieceFilters.isEmpty() || pieceFilters.contains(name); }; std::function<Value(const Symbol &, Flags<ToStringFlag>)> toValue = [&](const Symbol &symbol, Flags<ToStringFlag> f) { Value ret; auto formatLocation = [locationToStringFlags,&filterPiece, &ret](Location loc, const char *key, const char *ctxKey, const char *keyFilter = 0, const char *ctxKeyFilter = 0, Value *val = 0) { if (!val) val = &ret; if (filterPiece(keyFilter ? keyFilter : key)) (*val)[key] = loc.toString(locationToStringFlags & ~Location::ShowContext); if (locationToStringFlags & Location::ShowContext && filterPiece(ctxKeyFilter ? ctxKeyFilter : ctxKey)) { (*val)[ctxKey] = loc.context(locationToStringFlags); } }; if (!symbol.location.isNull()) { formatLocation(symbol.location, "location", "context"); } if (!symbol.isNull()) { if (symbol.argumentUsage.index != String::npos) { formatLocation(symbol.argumentUsage.invocation, "invocation", "invocationContext", 0, "invocationcontext"); if (filterPiece("invokedfunction")) ret["invokedFunction"] = symbol.argumentUsage.invokedFunction.toString(locationToStringFlags); formatLocation(symbol.argumentUsage.argument.location, "functionArgumentLocation", "functionArgumentLocationContext", "functionargumentlocation", "functionargumentlocationcontext"); if (filterPiece("functionargumentcursor")) ret["functionArgumentCursor"] = symbol.argumentUsage.argument.cursor.toString(locationToStringFlags); if (filterPiece("functionargumentlength")) ret["functionArgumentLength"] = symbol.argumentUsage.argument.length; if (filterPiece("argumentindex")) ret["argumentIndex"] = symbol.argumentUsage.index; } if (!symbol.symbolName.isEmpty() && filterPiece("symbolname")) ret["symbolName"] = symbol.symbolName; if (!symbol.usr.isEmpty() && filterPiece("usr")) ret["usr"] = symbol.usr; if (filterPiece("type")) { if (!symbol.typeName.isEmpty()) { ret["type"] = symbol.typeName; } else if (symbol.type != CXType_Invalid) { String str; Log(&str) << symbol.type; ret["type"] = str; } } if (!symbol.baseClasses.isEmpty() && filterPiece("baseclasses")) ret["baseClasses"] = symbol.baseClasses; if (!symbol.arguments.isEmpty() && filterPiece("arguments")) { Value args; for (const auto &arg : symbol.arguments) { Value a; formatLocation(arg.location, "location", "context", "arguments", "arguments", &a); formatLocation(arg.location, "cursor", "cursorContext", "arguments", "arguments", &a); a["length"] = arg.length; args.push_back(a); } ret["arguments"] = args; } if (filterPiece("symbollength")) ret["symbolLength"] = symbol.symbolLength; if (filterPiece("kind")) { String str; Log(&str) << symbol.kind; ret["kind"] = str; } if (filterPiece("linkage")) { String str; Log(&str) << symbol.linkage; ret["linkage"] = str; } if (!symbol.briefComment.isEmpty() && filterPiece("briefcomment")) ret["briefComment"] = symbol.briefComment; if (!symbol.xmlComment.isEmpty() && filterPiece("xmlcomment")) ret["xmlComment"] = symbol.xmlComment; if (filterPiece("range")) { ret["startLine"] = symbol.startLine; ret["startColumn"] = symbol.startColumn; ret["endLine"] = symbol.endLine; ret["endColumn"] = symbol.endColumn; } if (symbol.size && filterPiece("sizeof")) ret["sizeof"] = symbol.size; if (symbol.fieldOffset >= 0 && filterPiece("fieldoffset")) ret["fieldOffset"] = symbol.fieldOffset; if (symbol.alignment >= 0 && filterPiece("alignment")) ret["alignment"] = symbol.alignment; if (symbol.kind == CXCursor_EnumConstantDecl && filterPiece("enumvalue")) ret["enumValue"] = symbol.enumValue; if (symbol.isDefinition()) { if (filterPiece("definition")) ret["definition"] = true; if (RTags::isFunction(symbol.kind) && filterPiece("stackcost")) ret["stackCost"] = symbol.stackCost; } else if (symbol.isReference() && filterPiece("reference")) { ret["reference"] = true; } if (symbol.isContainer() && filterPiece("container")) ret["container"] = true; if ((symbol.flags & Symbol::PureVirtualMethod) == Symbol::PureVirtualMethod && filterPiece("purevirtual")) ret["purevirtual"] = true; if (symbol.flags & Symbol::VirtualMethod && filterPiece("virtual")) ret["virtual"] = true; if (symbol.flags & Symbol::ConstMethod && filterPiece("constmethod")) ret["constmethod"] = true; if (symbol.flags & Symbol::StaticMethod && filterPiece("staticmethod")) ret["staticmethod"] = true; if (symbol.flags & Symbol::Variadic && filterPiece("variadic")) ret["variadic"] = true; if (symbol.flags & Symbol::Auto && filterPiece("auto")) ret["auto"] = true; if (symbol.flags & Symbol::MacroExpansion && filterPiece("macroexpansion")) ret["macroexpansion"] = true; if (symbol.flags & Symbol::TemplateSpecialization && filterPiece("templatespecialization")) ret["templatespecialization"] = true; if (symbol.flags & Symbol::TemplateReference && filterPiece("templatereference")) ret["templatereference"] = true; if (f & IncludeTargets) { const auto targets = project->findTargets(symbol); if (!targets.isEmpty() && filterPiece("targets")) { Value t; for (const auto &target : targets) { t.push_back(toValue(target, NullFlags)); } ret["targets"] = t; } } if (f & IncludeReferences) { const auto references = project->findCallers(symbol); if (!references.isEmpty() && filterPiece("references")) { Value r; for (const auto &ref : references) { r.push_back(toValue(ref, NullFlags)); } ret["references"] = r; } } if (f & IncludeBaseClasses && filterPiece("baseclasses")) { List<Value> b; for (const auto &base : symbol.baseClasses) { for (const Symbol &s : project->findByUsr(base, symbol.location.fileId(), Project::ArgDependsOn)) { b.append(toValue(s, NullFlags)); break; } } if (!baseClasses.isEmpty()) { ret["baseClasses"] = b; } } if ((f & IncludeParents && filterPiece("parent")) || (f & (IncludeContainingFunction) && filterPiece("cf")) || (f & (IncludeContainingFunctionLocation) && (filterPiece("cfl") || filterPiece("cflcontext")))) { auto syms = project->openSymbols(symbol.location.fileId()); uint32_t idx = -1; if (syms) { idx = syms->lowerBound(symbol.location); if (idx == std::numeric_limits<uint32_t>::max()) { idx = syms->count() - 1; } } const unsigned int line = symbol.location.line(); const unsigned int column = symbol.location.column(); while (idx-- > 0) { const Symbol s = syms->valueAt(idx); if (s.isDefinition() && s.isContainer() && comparePosition(line, column, s.startLine, s.startColumn) >= 0 && comparePosition(line, column, s.endLine, s.endColumn) <= 0) { if (f & IncludeContainingFunctionLocation) { formatLocation(s.location, "cfl", "cflcontext"); } if (f & IncludeContainingFunction && filterPiece("cf")) ret["cf"] = s.symbolName; if (f & IncludeParents && filterPiece("parent")) ret["parent"] = toValue(s, IncludeParents); break; } } } } return ret; }; return toValue(*this, toStringFlags); }
Value Symbol::toValue(const std::shared_ptr<Project> &project, Flags<ToStringFlag> toStringFlags, Flags<Location::ToStringFlag> locationToStringFlags) const { std::function<Value(const Symbol &, Flags<ToStringFlag>)> toValue = [&](const Symbol &symbol, Flags<ToStringFlag> f) { Value ret; if (!symbol.isNull()) { ret["location"] = symbol.location.toString(locationToStringFlags); if (symbol.argumentUsage.index != String::npos) { ret["invocation"] = symbol.argumentUsage.invocation.toString(locationToStringFlags); ret["invokedFunction"] = symbol.argumentUsage.invokedFunction.toString(locationToStringFlags); ret["functionArgumentLocation"] = symbol.argumentUsage.argument.location.toString(locationToStringFlags); ret["functionArgumentCursor"] = symbol.argumentUsage.argument.cursor.toString(locationToStringFlags); ret["functionArgumentLength"] = symbol.argumentUsage.argument.length; ret["argumentIndex"] = symbol.argumentUsage.index; } if (!symbol.symbolName.isEmpty()) ret["symbolName"] = symbol.symbolName; if (!symbol.usr.isEmpty()) ret["usr"] = symbol.usr; if (!symbol.typeName.isEmpty()) { ret["type"] = symbol.typeName; } else if (symbol.type != CXType_Invalid) { String str; Log(&str) << symbol.type; ret["type"] = str; } if (!symbol.baseClasses.isEmpty()) ret["baseClasses"] = symbol.baseClasses; if (!symbol.arguments.isEmpty()) { Value args; for (const auto &arg : symbol.arguments) { Value a; a["location"] = arg.location.toString(locationToStringFlags); a["cursor"] = arg.cursor.toString(locationToStringFlags); a["length"] = arg.length; args.push_back(a); } ret["arguments"] = args; } ret["symbolLength"] = symbol.symbolLength; { String str; Log(&str) << symbol.kind; ret["kind"] = str; } { String str; Log(&str) << symbol.linkage; ret["linkage"] = str; } if (!symbol.briefComment.isEmpty()) ret["briefComment"] = symbol.briefComment; if (!symbol.xmlComment.isEmpty()) ret["xmlComment"] = symbol.xmlComment; ret["startLine"] = symbol.startLine; ret["startColumn"] = symbol.startColumn; ret["endLine"] = symbol.endLine; ret["endColumn"] = symbol.endColumn; if (symbol.size > 0) ret["sizeof"] = symbol.size; if (symbol.fieldOffset > 0) ret["fieldOffset"] = symbol.fieldOffset; if (symbol.alignment > 0) ret["alignment"] = symbol.alignment; if (symbol.kind == CXCursor_EnumConstantDecl) ret["enumValue"] = symbol.enumValue; if (symbol.isDefinition()) { ret["definition"] = true; if (RTags::isFunction(symbol.kind)) ret["stackCost"] = symbol.stackCost; } else if (symbol.isReference()) { ret["reference"] = true; } if (symbol.isContainer()) ret["container"] = true; if ((symbol.flags & Symbol::PureVirtualMethod) == Symbol::PureVirtualMethod) ret["purevirtual"] = true; if (symbol.flags & Symbol::VirtualMethod) ret["virtual"] = true; if (symbol.flags & Symbol::ConstMethod) ret["constmethod"] = true; if (symbol.flags & Symbol::StaticMethod) ret["staticmethod"] = true; if (symbol.flags & Symbol::Variadic) ret["variadic"] = true; if (symbol.flags & Symbol::Auto) ret["auto"] = true; if (symbol.flags & Symbol::AutoRef) ret["autoref"] = true; if (symbol.flags & Symbol::MacroExpansion) ret["macroexpansion"] = true; if (symbol.flags & Symbol::TemplateSpecialization) ret["templatespecialization"] = true; if (f & IncludeTargets) { const auto targets = project->findTargets(symbol); if (!targets.isEmpty()) { Value t; for (const auto &target : targets) { t.push_back(toValue(target, NullFlags)); } ret["targets"] = t; } } if (f & IncludeReferences) { const auto references = project->findCallers(symbol); if (!references.isEmpty()) { Value r; for (const auto &ref : references) { r.push_back(toValue(ref, NullFlags)); } ret["references"] = r; } } if (f & IncludeBaseClasses) { List<Value> b; for (const auto &base : symbol.baseClasses) { for (const Symbol &s : project->findByUsr(base, symbol.location.fileId(), Project::ArgDependsOn, symbol.location)) { b.append(toValue(s, NullFlags)); break; } } if (!baseClasses.isEmpty()) { ret["baseClasses"] = b; } } if (f & IncludeParents) { auto syms = project->openSymbols(symbol.location.fileId()); uint32_t idx = -1; if (syms) { idx = syms->lowerBound(symbol.location); if (idx == std::numeric_limits<uint32_t>::max()) { idx = syms->count() - 1; } } const unsigned int line = symbol.location.line(); const unsigned int column = symbol.location.column(); while (idx-- > 0) { const Symbol s = syms->valueAt(idx); if (s.isDefinition() && s.isContainer() && comparePosition(line, column, s.startLine, s.startColumn) >= 0 && comparePosition(line, column, s.endLine, s.endColumn) <= 0) { ret["parent"] = toValue(s, IncludeParents); break; } } } } return ret; }; return toValue(*this, toStringFlags); }
void RegistrationFactory3D<TFixedImageType, TMovingImageType>::SetUpOptimizer() { if ( optimizer.REGULARSTEPGRADIENTDESCENT ) { //setting up the regular step gradient descent optimizer... RegularStepGradientDescentOptimizerType::ScalesType optimizerScaleRegularStepGradient( m_NumberOfParameters ); if ( transform.VERSORRIGID or transform.CENTEREDAFFINE or transform.AFFINE or transform.BSPLINEDEFORMABLETRANSFORM or transform.RIGID3D ) { //...for the rigid transform //number of parameters are dependent on the dimension of the images (2D: 4 parameter, 3D: 6 parameters) if ( transform.VERSORRIGID ) { //rotation if ( UserOptions.ROTATIONSCALE == -1 ) { UserOptions.ROTATIONSCALE = 1.0 / 1.0; } optimizerScaleRegularStepGradient[0] = UserOptions.ROTATIONSCALE; optimizerScaleRegularStepGradient[1] = UserOptions.ROTATIONSCALE; optimizerScaleRegularStepGradient[2] = UserOptions.ROTATIONSCALE; //translation if ( UserOptions.TRANSLATIONSCALE == -1 ) { typename FixedImageType::SizeType imageSize = m_FixedImageRegion.GetSize(); UserOptions.TRANSLATIONSCALE = ( sqrt( imageSize[0] * imageSize[0] + imageSize[1] * imageSize[1] + imageSize[2] * imageSize[2] ) ); } optimizerScaleRegularStepGradient[3] = 1.0 / UserOptions.TRANSLATIONSCALE; optimizerScaleRegularStepGradient[4] = 1.0 / UserOptions.TRANSLATIONSCALE; optimizerScaleRegularStepGradient[5] = 1.0 / UserOptions.TRANSLATIONSCALE; } if ( transform.RIGID3D ) { for ( unsigned short i = 0; i < 9; i++ ) { optimizerScaleRegularStepGradient[i] = 1.0; } optimizerScaleRegularStepGradient[9] = 1.0; optimizerScaleRegularStepGradient[10] = 1.0; optimizerScaleRegularStepGradient[11] = 1.0; } if ( transform.BSPLINEDEFORMABLETRANSFORM or transform.AFFINE or transform.CENTEREDAFFINE or transform.TRANSLATION ) { optimizerScaleRegularStepGradient.Fill( 1.0 ); } if ( transform.AFFINE ) { optimizerScaleRegularStepGradient[9] = 1.0 / UserOptions.TRANSLATIONSCALE; optimizerScaleRegularStepGradient[10] = 1.0 / UserOptions.TRANSLATIONSCALE; optimizerScaleRegularStepGradient[11] = 1.0 / UserOptions.TRANSLATIONSCALE; } m_RegularStepGradientDescentOptimizer->SetMaximumStepLength( 0.1 * UserOptions.CoarseFactor ); m_RegularStepGradientDescentOptimizer->SetMinimumStepLength( 0.0001 * UserOptions.CoarseFactor ); m_RegularStepGradientDescentOptimizer->SetScales( optimizerScaleRegularStepGradient ); m_RegularStepGradientDescentOptimizer->SetNumberOfIterations( UserOptions.NumberOfIterations ); m_RegularStepGradientDescentOptimizer->SetRelaxationFactor( 0.9 ); m_RegularStepGradientDescentOptimizer->SetGradientMagnitudeTolerance( 0.00001 ); m_RegularStepGradientDescentOptimizer->SetMinimize( true ); if ( transform.BSPLINEDEFORMABLETRANSFORM ) { m_RegularStepGradientDescentOptimizer->SetMaximumStepLength( 1.0 ); } } if ( metric.MEANSQUARE or metric.MATTESMUTUALINFORMATION or metric.VIOLAWELLSMUTUALINFORMATION or metric.MUTUALINFORMATIONHISTOGRAM ) { m_RegularStepGradientDescentOptimizer->MinimizeOn(); } } if ( optimizer.VERSORRIGID3D ) { VersorRigid3DTransformOptimizerType::ScalesType optimizerScaleVersorRigid3D( m_NumberOfParameters ); if ( transform.VERSORRIGID ) { optimizerScaleVersorRigid3D[0] = 1.0; optimizerScaleVersorRigid3D[1] = 1.0; optimizerScaleVersorRigid3D[2] = 1.0; optimizerScaleVersorRigid3D[3] = 1.0 / 1000.0; optimizerScaleVersorRigid3D[4] = 1.0 / 1000.0; optimizerScaleVersorRigid3D[5] = 1.0 / 1000.0; } m_VersorRigid3DTransformOptimizer->SetMaximumStepLength( 0.1 * UserOptions.CoarseFactor ); m_VersorRigid3DTransformOptimizer->SetMinimumStepLength( 0.0001 * UserOptions.CoarseFactor ); m_VersorRigid3DTransformOptimizer->SetScales( optimizerScaleVersorRigid3D ); m_VersorRigid3DTransformOptimizer->SetNumberOfIterations( UserOptions.NumberOfIterations ); m_VersorRigid3DTransformOptimizer->SetRelaxationFactor( 0.9 ); if ( metric.MEANSQUARE or metric.MATTESMUTUALINFORMATION or metric.VIOLAWELLSMUTUALINFORMATION or metric.MUTUALINFORMATIONHISTOGRAM ) { m_VersorRigid3DTransformOptimizer->MinimizeOn(); } } if ( optimizer.LBFGSBOPTIMIZER ) { LBFGSBOptimizerType::BoundSelectionType boundSelect( m_NumberOfParameters ); LBFGSBOptimizerType::BoundValueType lowerBound( m_NumberOfParameters ); LBFGSBOptimizerType::BoundValueType upperBound( m_NumberOfParameters ); boundSelect.Fill( 2 ); lowerBound.Fill( -UserOptions.BSplineBound ); upperBound.Fill( UserOptions.BSplineBound ); m_LBFGSBOptimizer->SetBoundSelection( boundSelect ); m_LBFGSBOptimizer->SetLowerBound( lowerBound ); m_LBFGSBOptimizer->SetUpperBound( upperBound ); m_LBFGSBOptimizer->SetCostFunctionConvergenceFactor( 1.0 ); m_LBFGSBOptimizer->SetProjectedGradientTolerance( 1e-12 ); m_LBFGSBOptimizer->SetMaximumNumberOfIterations( UserOptions.NumberOfIterations ); m_LBFGSBOptimizer->SetMaximumNumberOfEvaluations( 5000 ); m_LBFGSBOptimizer->SetMaximumNumberOfCorrections( 240 ); if ( metric.MEANSQUARE or metric.MATTESMUTUALINFORMATION or metric.VIOLAWELLSMUTUALINFORMATION or metric.MUTUALINFORMATIONHISTOGRAM ) { m_LBFGSBOptimizer->MinimizeOn(); m_LBFGSBOptimizer->MaximizeOff(); } } if ( optimizer.AMOEBA ) { AmoebaOptimizerType::ParametersType simplexDelta( m_NumberOfParameters ); //simplexDelta.Fill(5.0); m_AmoebaOptimizer->AutomaticInitialSimplexOn(); m_AmoebaOptimizer->SetInitialSimplexDelta( simplexDelta ); m_AmoebaOptimizer->SetMaximumNumberOfIterations( UserOptions.NumberOfIterations ); m_AmoebaOptimizer->SetParametersConvergenceTolerance( 1e-10 ); m_AmoebaOptimizer->SetFunctionConvergenceTolerance( 1e-10 ); if ( metric.MEANSQUARE or metric.MATTESMUTUALINFORMATION or metric.VIOLAWELLSMUTUALINFORMATION or metric.MUTUALINFORMATIONHISTOGRAM ) { m_AmoebaOptimizer->MinimizeOn(); } if ( metric.NORMALIZEDCORRELATION ) { m_AmoebaOptimizer->MaximizeOn(); } } if ( optimizer.POWELL ) { }; }
ConstIterator lower_bound(const FragmentType& match) const { return lowerBound( match ); }