Ejemplo n.º 1
0
void
Selection::removeIndex (const IndexVector &indices)
{
    IndexVector::const_iterator it;
    for(it = indices.begin(); it != indices.end(); ++it)
        removeIndex(*it);
}
Ejemplo n.º 2
0
IndexVector::IndexVector(const IndexVector &rhs){
		_length=rhs.length();
		if(_length>0) {
			_data = new int[_length];
			memcpy(_data,rhs.data(),_length*sizeof(int) );
		}	else{
			_data=0;
		}
}
osg::Vec3f TriangleMeshSmoother::cumulateTriangleNormals(const IndexVector& triangles) const {
    osg::Vec3f normal;
    normal.set(0.f, 0.f, 0.f);
    for(IndexVector::const_iterator triangle = triangles.begin() ; triangle != triangles.end() ; ++ triangle) {
        const Triangle& t = _graph->triangle(*triangle);
        normal += (t._normal * t._area);
    }
    return normal;
}
Ejemplo n.º 4
0
IGL_INLINE void igl::sparse(
  const IndexVector & I,
  const IndexVector & J,
  const ValueVector & V,
  Eigen::SparseMatrix<T>& X)
{
  size_t m = (size_t)I.maxCoeff()+1;
  size_t n = (size_t)J.maxCoeff()+1;
  return igl::sparse(I,J,V,m,n,X);
}
Ejemplo n.º 5
0
	IndexVector buildIndices(const std::string& expr, Iterator begin, Iterator end) const {
		IndexVector indices;

		for (Iterator i = begin; i != end; ++i) {
			if (expr.empty() || i->matches(expr)) {
				indices.push_back(std::distance(begin, i));
			}
		}

		return indices;
	}
Ejemplo n.º 6
0
/*!
 * \brief children Populate a children list for the given contour. No control is made.
 * \param _hierarchy OpenCV contour hierarchy used to find children.
 * \param _parentIndex Index in _hierarchy of the given contour. _parentIndex must exist in _hierarchy.
 * \param _children Output list of the found children.
 * \return number of children.
 */
void ContourManager::children(const Hierarchy & _hierarchy, int _parentIndex, IndexVector & _children)
{
    _children.clear();

    int currentChild = _hierarchy[_parentIndex][HIERARCHY_INDEX_FIRST_CHILD];//First child

    while (currentChild >= 0)
    {
        _children.push_back(currentChild);

        currentChild = _hierarchy[currentChild][HIERARCHY_INDEX_NEXT];
    }//while (currentChild >= 0)
}//children
void TriangleMeshSmoother::replaceVertexIndexInTriangles(const IndexVector& triangles, unsigned int oldIndex, unsigned int newIndex) {
    for(IndexVector::const_iterator tri = triangles.begin() ; tri != triangles.end() ; ++ tri) {
        Triangle& triangle = _graph->triangle(*tri);
        if(triangle.v1() == oldIndex) {
            triangle.v1() = newIndex;
        }
        else if(triangle.v2() == oldIndex) {
            triangle.v2() = newIndex;
        }
        else if(triangle.v3() == oldIndex) {
            triangle.v3() = newIndex;
        }
    }
}
Ejemplo n.º 8
0
  void
  AdjacencyRansac::InvalidateQueryIndices(IndexVector &query_indices)
  {
    if (query_indices.empty())
      return;
    // Figure out the points with those query indices
    std::sort(query_indices.begin(), query_indices.end());
    IndexVector::iterator end = std::unique(query_indices.begin(), query_indices.end());
    query_indices.resize(end - query_indices.begin());

    IndexVector indices_to_remove;
    indices_to_remove.reserve(query_indices_.size());
    IndexVector::const_iterator iter = query_indices.begin();
    BOOST_FOREACH(unsigned int index, valid_indices_){
    unsigned int query_index = query_indices_[index];
    if (query_index < *iter)
    continue;
    // If the match has a keypoint in the inliers, remove the match
    while ((iter != end) && (query_index > *iter))
    ++iter;
    if (query_index == *iter)
    {
      indices_to_remove.push_back(index);
      continue;
    }

    if (iter == end)
    break;
  }
Ejemplo n.º 9
0
void RemoveUnusedStructField::handleOneRecordDecl(const RecordDecl *RD,
                                                  const RecordDecl *BaseRD,
                                                  const FieldDecl *FD,
                                                  unsigned int Idx)
{
  IndexVector *BaseIdxVec = RecordDeclToField[BaseRD];
  if (!BaseIdxVec)
    return;

  IndexVector *NewIdxVec = RecordDeclToField[RD];
  if (!NewIdxVec) {
    NewIdxVec = new IndexVector();
    RecordDeclToField[RD] = NewIdxVec;
  }
  NewIdxVec->push_back(Idx);
  FieldToIdxVector[FD] = BaseIdxVec;
}
Ejemplo n.º 10
0
    void testInterleavedSortingWithPops()
    {
        DPQ dpq;

        IndexVector idVector;

        const Index MAXI( 101 );
        for( int n( MAXI-1 ); n != 0  ; n-=2 )
        {
            const Index id( dpq.push( n ) );

            if( n == 12 || n == 46 )
            {
                idVector.push_back( id );
            }
        }

        dpq.pop( idVector.back() );
        idVector.pop_back();

        BOOST_CHECK_EQUAL( MAXI/2 -1, dpq.getSize() );

        BOOST_CHECK( dpq.checkConsistency() );

        for( int n( MAXI ); n != -1  ; n-=2 )
        {
            const Index id( dpq.push( n ) );

            if( n == 17 || n == 81 )
            {
                idVector.push_back( id );
            }
        }

        for( typename IndexVector::const_iterator i( idVector.begin() );
             i != idVector.end(); ++i )
        {
            dpq.pop( *i );
        }

        BOOST_CHECK( dpq.checkConsistency() );
        BOOST_CHECK_EQUAL( MAXI-4, dpq.getSize() );

        int n( 0 );
        while( ! dpq.isEmpty() )
        {
            ++n;
            if( n == 12 || n == 46 || n == 17 || n == 81 )
            {
                continue;
            }
            BOOST_CHECK_EQUAL( n, dpq.getTop() );
            dpq.popTop();
        }

        BOOST_CHECK_EQUAL( MAXI, Index( n ) );

        BOOST_CHECK( dpq.isEmpty() );
        BOOST_CHECK( dpq.checkConsistency() );
    }
Ejemplo n.º 11
0
    void testSimpleSortingWithPops()
    {
        DPQ dpq;

        IndexVector idVector;

        const Index MAXI( 100 );
        for( int n( MAXI ); n != 0  ; --n )
        {
            Index id( dpq.push( n ) );
            if( n == 11 || n == 45 )
            {
                idVector.push_back( id );
            }
        }

        BOOST_CHECK( dpq.checkConsistency() );

        BOOST_CHECK_EQUAL( MAXI, dpq.getSize() );

        for( typename IndexVector::const_iterator i( idVector.begin() );
             i != idVector.end(); ++i )
        {
            dpq.pop( *i );
        }

        BOOST_CHECK_EQUAL( MAXI - 2, dpq.getSize() );

        int n( 0 );
        while( ! dpq.isEmpty() )
        {
            ++n;
            if( n == 11 || n == 45 )
            {
                continue; // skip
            }
            BOOST_CHECK_EQUAL( int( n ), dpq.getTop() );
            dpq.popTop();
        }

        BOOST_CHECK_EQUAL( MAXI, Index( n ) );

        BOOST_CHECK( dpq.isEmpty() );
        BOOST_CHECK( dpq.checkConsistency() );
    }
Ejemplo n.º 12
0
void
AdjacencyList::node_neighbors(const int& local_index,
                              IndexVector& global_neighbor_indexes) const
{
  BOOST_ASSERT(local_index < p_adjacency.size());
  global_neighbor_indexes.clear();
  std::copy(p_adjacency[local_index].begin(), p_adjacency[local_index].end(),
            std::back_inserter(global_neighbor_indexes));

}
Ejemplo n.º 13
0
void
Select2DTool::end (int x, int y, BitMask modifiers, BitMask)
{
  if (!cloud_ptr_)
    return;
  final_x_ = x;
  final_y_ = y;
  display_box_ = false;
  // don't select anything if we don't have a selection box.
  if ((final_x_ == origin_x_) || (final_y_ == origin_y_))
    return;

  GLint viewport[4];
  glGetIntegerv(GL_VIEWPORT,viewport);
  IndexVector indices;
  GLfloat project[16];
  glGetFloatv(GL_PROJECTION_MATRIX, project);

  Point3DVector ptsvec;
  cloud_ptr_->getDisplaySpacePoints(ptsvec);
  for(size_t i = 0; i < ptsvec.size(); ++i)
  {
    Point3D pt = ptsvec[i];
    if (isInSelectBox(pt, project, viewport))
      indices.push_back(i);
  }

  if (modifiers & SHFT)
  {
    selection_ptr_->addIndex(indices);
  }
  else if (modifiers & CTRL)
  {
    selection_ptr_->removeIndex(indices);
  }
  else
  {
    selection_ptr_->clear();
    selection_ptr_->addIndex(indices);
  }
  cloud_ptr_->setSelection(selection_ptr_);
}
Ejemplo n.º 14
0
postTable::postTable (OpenTypeFile &aFont, MemoryBlockPtr memory) : Table (aFont)
{
	MemoryPen pen (memory);
	version = pen.readFixed();
	if (version != 0x00020000 && version != 0x00030000)
		throw Exception ("Unsupported table version: " + String (version, 16));
	italicAngle = pen.readFixed();
	underlinePosition = pen.readFWord();
	underlineThickness = pen.readFWord();
	isFixedPitch = pen.readULong();
	minMemType42 = pen.readULong();
	maxMemType42 = pen.readULong();
	minMemType1 = pen.readULong();
	maxMemType1 = pen.readULong();

	if (version == 0x00020000) {
		// Read glyph names
		UShort glyphNum = pen.readUShort();
		typedef vector<UShort> IndexVector;
		IndexVector glyphNameIndices;
		glyphNameIndices.reserve (glyphNum);
		UShort i;
		for (i = 0; i < glyphNum; i++)
			glyphNameIndices.push_back (pen.readUShort());

		vector<String> extraNames;
		IndexVector::iterator index;
		for (index = glyphNameIndices.begin(); index != glyphNameIndices.end(); index ++) {
			if (*index < MACINTOSH_SET_SIZE)
				postNames.push_back (macGlyphs [*index]);
			else {
				UShort extraIndex = *index - MACINTOSH_SET_SIZE;
				while (extraNames.size() <= extraIndex) {
					Byte nameLength = pen.readByte();
					extraNames.push_back (pen.readString (nameLength));
				}
				postNames.push_back (extraNames [extraIndex]);
			}
		}
	}
}
Ejemplo n.º 15
0
void RemoveUnusedStructField::setBaseLine(const RecordDecl *RD, 
                                          const FieldDecl *FD)
{
  TheRecordDecl = RD;
  TheFieldDecl = FD;
    
  IndexVector *IdxVec = new IndexVector();
  unsigned int Idx = FD->getFieldIndex();
  IdxVec->push_back(Idx);
  RecordDeclToField[RD] = IdxVec;
  FieldToIdxVector[FD] = IdxVec;

  // IsLastField = (FD->getNextDeclInContext() == NULL);
  RecordDecl::field_iterator I = RD->field_begin();
  IsFirstField = (FD == (*I));
  RecordDecl::field_iterator E = RD->field_end();

  for (; I != E; ++I) {
    NumFields++;
  }
}
Ejemplo n.º 16
0
void
TopologyGraph::dumpBoundary(const IndexVector& boundary, const std::string& filename)
{
    if (boundary.empty())
        return;
    
    osg::Vec3Array* v = new osg::Vec3Array();

    for (IndexVector::const_iterator i = boundary.begin(); i != boundary.end(); ++i)
    {
        const Index& index = *i;
        v->push_back(osg::Vec3(index->x(), index->y(), 0));
    }

    osg::ref_ptr<osg::Geometry> g = new osg::Geometry();
    g->setVertexArray(v);
    g->addPrimitiveSet(new osg::DrawArrays(GL_LINE_LOOP, 0, v->size()));
    g->addPrimitiveSet(new osg::DrawArrays(GL_POINTS, 0, v->size()));
    g->getOrCreateStateSet()->setAttributeAndModes(new osg::Point(3));
    osgDB::writeNodeFile(*(g.get()), filename);
}
Ejemplo n.º 17
0
// Sort elements and return sort index mapping.
bool NgramVector::Sort(const VocabVector &vocabMap,
                       const IndexVector &boNgramMap,
                       IndexVector &ngramMap) {
    // Update word and hist indices.
    for (size_t i = 0; i < size(); ++i) {
        _words[i] = vocabMap[_words[i]];
        _hists[i] = boNgramMap[_hists[i]];
    }

    // Sort indices.
    NgramIndexCompare compare(*this);
    IndexVector       sortIndices = Range(0, size());
    if (!sortIndices.sort(compare)) {
        ngramMap = Range(size());
        return false;
    }

    // Apply ordered indices to values.
    // Build sort mapping that maps old to new indices.
    VocabVector newWords(_words.length());
    IndexVector newHists(_hists.length());
    ngramMap.reset(size());
    for (NgramIndex i = 0; i < (NgramIndex)size(); i++) {
        newWords[i] = _words[sortIndices[i]];
        newHists[i] = _hists[sortIndices[i]];
        ngramMap[sortIndices[i]] = i;
    }
    _words.swap(newWords);
    _hists.swap(newHists);

    // Rebuild index map.
    _Reindex(_indices.length());

    // Build truncated view into words and hists.
    Range r(_length);
    _wordsView.attach(_words[r]);
    _histsView.attach(_hists[r]);

    return true;
}
Ejemplo n.º 18
0
  bool AlignmentAlgorithmSE2::operator()(AlignmentAlgorithmSE2::TransformType& transform, const CorrespondenceVector& correspondences, const IndexVector& indices){
    if ((int)indices.size()<minimalSetSize())
      return false;

    SE2 x0;
    SE2 ix0;
    double deltaRSum=0.;
    Vector2d mean1(0.,0.);
    Vector2d mean2(0.,0.);
    for (size_t i=0; i<indices.size(); i++){
      const Correspondence& c = correspondences[indices[i]];
      const EdgeSE2* edge = static_cast<const g2o::EdgeSE2*>(c.edge());
      const VertexSE2* v1 = static_cast<const g2o::VertexSE2*>(edge->vertex(0));
      const VertexSE2* v2 = static_cast<const g2o::VertexSE2*>(edge->vertex(1));
      SE2 xi = v2->estimate()*v1->estimate().inverse();
      mean1 += v1->estimate().translation();
      mean2 += v2->estimate().translation();
      if (i==0){
	x0 = xi;
	ix0 = x0.inverse();
      } else {
	SE2 delta=ix0*xi;
	deltaRSum += delta.rotation().angle();
      }
    }
    int count  = indices.size();
    double icount = 1./double(count);
    deltaRSum*=icount;
    mean1*=icount;
    mean2*=icount;
    Rotation2Dd R = x0.rotation()*Rotation2Dd(deltaRSum);
    transform.setRotation(R);
    transform.setTranslation(mean2 - R*mean1);
    transform = transform.inverse();
    return true;
  }
Ejemplo n.º 19
0
    void _computeReverseMap() {

        _genesToTranscripts.resize( _geneNames.size(), {});

        Index geneID;
        Index transcriptID = 0;
        size_t maxNumTrans = 0;
        Index maxGene;
        for ( size_t transcriptID = 0; transcriptID < _transcriptsToGenes.size(); ++transcriptID ) {
            _genesToTranscripts[ _transcriptsToGenes[transcriptID] ].push_back( transcriptID );
            if ( maxNumTrans < _genesToTranscripts[ _transcriptsToGenes[transcriptID] ].size() ) {
                maxNumTrans = _genesToTranscripts[ _transcriptsToGenes[transcriptID] ].size();
                maxGene = _transcriptsToGenes[transcriptID];
            }
        }
        std::cerr << "max # of transcripts in a gene was " << maxNumTrans << " in gene " << _geneNames[maxGene] << "\n";
    }
  bool IdCorrespondenceValidator::operator()(const CorrespondenceVector& correspondences, const IndexVector& indices, int k){
    if (k>minimalSetSize())
      return true;
    
    assert(indices.size()>=k && "VALIDATION_INDEX_OUT_OF_BOUND");
    assert(correspondences.size()>=indices[k] && "VALIDATION_CORRESPONDENCE_INDEX_OUT_OF_BOUND");
    const g2o::OptimizableGraph::Edge* edgek = correspondences[indices[k]].edge();
    int idk1=edgek->vertex(0)->id();
    int idk2=edgek->vertex(1)->id();
    
    for (int i=0; i<k-1; i++){
      const g2o::OptimizableGraph::Edge* edge = correspondences[indices[i]].edge();
      int id1=edge->vertex(0)->id();
      int id2=edge->vertex(1)->id();
      if (idk1==id1)
	return false;
      if (idk2==id2)
	return false;
    }
    return true;
  }
Ejemplo n.º 21
0
void
Selection::addIndex (const IndexVector &indices)
{
    selected_indices_.insert(indices.begin(), indices.end());
}
Ejemplo n.º 22
0
CRSIndexMatrix::CRSIndexMatrix(IndexVector &row, IndexVector &col, IndexVector &values){

		int idx, rowidx, datalen, rowdiff, offset, length=row.length();
		/* *** determine number of rows and cols */
		int nRow=0,nCol=0;
		for(int k=0;k<length;k++){
			if(row(k)>nRow) nRow=row(k);
			if(col(k)>nCol) nCol=col(k);
		}
		nRow+=1;
		nCol+=1; /* row and col index start with 0... */

		/* *** initialize temporary variables */
		int* data = new int[length];
		int* colindex = new int[length];
		int* rowptr = new int[nRow+1];
		int* rowoff = new int[nRow];
		memset(rowptr,0,(nRow+1)*sizeof(int));

		/* *** create rowptr */
		for(int k=0 ; k<length ; k++){
			rowptr[row(k)+1]++;
		}

		for(int k=1 ; k<nRow ; k++){
			rowptr[k+1] = rowptr[k+1]+rowptr[k];
		}
		memcpy(rowoff,rowptr,nRow*sizeof(int));
		/* *** copy column index and values */
		for(int k=0;k<length;k++){
			idx = rowoff[ row(k) ];
			rowoff[row(k) ]++;
			data[idx] = values(k);
			colindex[idx] = col(k);
		}
		/* *** sort values of each row */
		for(int k=0;k<nRow;k++){
			if(rowptr[k+1]>rowptr[k] ){
				insort(colindex+rowptr[k],data+rowptr[k],rowptr[k+1]-rowptr[k]);
			}
		}

		/* *** sum up entries with same indices and compress the data structures */
		idx=0; rowidx=0; rowdiff=0;
		for(int k=0;k<length;){
			while(rowptr[rowidx+1]==k){
				rowidx++;
				rowptr[rowidx]-=rowdiff;
			}
			/* *** sum upp values with similar row and column indices  */
			offset=1;
			while(k+offset < rowptr[rowidx+1] && colindex[k] == colindex[k+offset]){
				data[k] += data[k+offset];
				offset+=1;
			}
			if(data[k] != 0){
				data[idx] = data[k] ;
				colindex[idx] = colindex[k];
				idx++;
				rowdiff+=(offset-1);
			}else{
				/* *** ignore values that are 0 */
				rowdiff+=offset;
			}
			k+=offset;
		}
		datalen=idx;
		for(int k=rowidx+1;k<nRow+1;k++)
			rowptr[k]= datalen;

		/* *** set private variables */	
		_data = new int[datalen];
		memcpy(_data, data, datalen*sizeof(int) );
		_colindex = new int[datalen];
		memcpy(_colindex, colindex, datalen*sizeof(int) );
		_rowptr    = rowptr;
		_cols      = nCol;
		_rows      = nRow;
		_nonZeros  = datalen;

		delete []data;
		delete []colindex; 

	}
Ejemplo n.º 23
0
// returns the number of race conditions detected (0 or 1 as of now)
int Specialization::verifyUpdateSequenceRaceConditions(LoopInfoSet& loopInfoSet, ArrayUpdatesSequence& arrayUpdates, VariableIdMapping* variableIdMapping) {
  int cnt=0;
  stringstream ss;
  cout<<"STATUS: checking race conditions."<<endl;
  cout<<"INFO: number of parallel loops: "<<numParLoops(loopInfoSet,variableIdMapping)<<endl;

  VariableIdSet allIterVars;
  for(LoopInfoSet::iterator lis=loopInfoSet.begin();lis!=loopInfoSet.end();++lis) {
    allIterVars.insert((*lis).iterationVarId);
  }
  for(LoopInfoSet::iterator lis=loopInfoSet.begin();lis!=loopInfoSet.end();++lis) {
    if((*lis).iterationVarType==ITERVAR_PAR) {
      VariableId parVariable;
      parVariable=(*lis).iterationVarId;
      cout<<"INFO: checking parallel loop: "<<variableIdMapping->variableName(parVariable)<<endl;

      // race check
      // intersect w-set_i = empty
      // w-set_i intersect r-set_j = empty, i!=j.

      IndexToReadWriteDataMap indexToReadWriteDataMap;
      for(ArrayUpdatesSequence::iterator i=arrayUpdates.begin();i!=arrayUpdates.end();++i) {
        const EState* estate=(*i).first;
        const PState* pstate=estate->pstate();
        SgExpression* exp=(*i).second;
        IndexVector index;
        // use all vars for indexing or only outer+par loop variables
#ifdef USE_ALL_ITER_VARS
        for(VariableIdSet::iterator ol=allIterVars.begin();ol!=allIterVars.end();++ol) {
          VariableId otherVarId=*ol;
          ROSE_ASSERT(otherVarId.isValid());
          if(!pstate->varValue(otherVarId).isTop()) {
            int otherIntVal=pstate->varValue(otherVarId).getIntValue();
            index.push_back(otherIntVal);
          }
        }
#else
        for(VariableIdSet::iterator ol=(*lis).outerLoopsVarIds.begin();ol!=(*lis).outerLoopsVarIds.end();++ol) {
          VariableId otherVarId=*ol;
          ROSE_ASSERT(otherVarId.isValid());
          if(!pstate->varValue(otherVarId).isTop()&&pstate->varValue(otherVarId).isConstInt()) {
            int otherIntVal=pstate->varValue(otherVarId).getIntValue();
            index.push_back(otherIntVal);
          }
        }
        if(!pstate->varValue(parVariable).isTop()&&pstate->varValue(parVariable).isConstInt()) {
          int parIntVal=pstate->varValue(parVariable).getIntValue();
          index.push_back(parIntVal);
        }
#endif
        if((*lis).isInAssociatedLoop(estate)) {
          SgExpression* lhs=isSgExpression(SgNodeHelper::getLhs(exp));
          SgExpression* rhs=isSgExpression(SgNodeHelper::getRhs(exp));
          ROSE_ASSERT(isSgPntrArrRefExp(lhs)||SgNodeHelper::isFloatingPointAssignment(exp));
        
          //cout<<"EXP: "<<exp->unparseToString()<<", lhs:"<<lhs->unparseToString()<<" :: "<<endl;
          // read-set
          RoseAst rhsast(rhs);
          for(RoseAst::iterator j=rhsast.begin();j!=rhsast.end();++j) {
            if(SgPntrArrRefExp* useRef=isSgPntrArrRefExp(*j)) {
              j.skipChildrenOnForward();
              ArrayElementAccessData access(useRef,variableIdMapping);
              indexToReadWriteDataMap[index].readArrayAccessSet.insert(access);
            } else if(SgVarRefExp* useRef=isSgVarRefExp(*j)) {
              ROSE_ASSERT(useRef);
              j.skipChildrenOnForward();
              VariableId varId=variableIdMapping->variableId(useRef);
              indexToReadWriteDataMap[index].readVarIdSet.insert(varId);
            } else {
              //cout<<"INFO: UpdateExtraction: ignored expression on rhs:"<<(*j)->unparseToString()<<endl;
            }
          }
          if(SgPntrArrRefExp* arr=isSgPntrArrRefExp(lhs)) {
            ArrayElementAccessData access(arr,variableIdMapping);
            indexToReadWriteDataMap[index].writeArrayAccessSet.insert(access);
          } else if(SgVarRefExp* var=isSgVarRefExp(lhs)) {
            VariableId varId=variableIdMapping->variableId(var);
            indexToReadWriteDataMap[index].writeVarIdSet.insert(varId);
          } else {
            cerr<<"Error: SSA Numbering: unknown LHS."<<endl;
            exit(1);
          }
        
          ss<<"UPD"<<cnt<<":"<<pstate->toString(variableIdMapping)<<" : "<<exp->unparseToString()<<endl;
          ++cnt;
        }
      } // array sequence iter

      // to be utilized later for more detailed output
#if 0
      for(IndexToReadWriteDataMap::iterator imap=indexToReadWriteDataMap.begin();
          imap!=indexToReadWriteDataMap.end();
          ++imap) {
        //        cout<<"DEBUG: INDEX: "<<(*imap).first<<" R-SET: ";
        IndexVector index=(*imap).first;

        cout<<"DEBUG: INDEX: ";
        for(IndexVector::iterator iv=index.begin();iv!=index.end();++iv) {
          if(iv!=index.begin())
            cout<<",";
          cout<<*iv;
        }
        cout<<" R-SET: ";
        for(ArrayElementAccessDataSet::const_iterator i=indexToReadWriteDataMap[index].readArrayAccessSet.begin();i!=indexToReadWriteDataMap[index].readArrayAccessSet.end();++i) {
          cout<<(*i).toString(variableIdMapping)<<" ";
        }
        cout<<endl;
        cout<<"DEBUG: INDEX: ";
        for(IndexVector::iterator iv=index.begin();iv!=index.end();++iv) {
          if(iv!=index.begin())
            cout<<",";
          cout<<*iv;
        }
        cout<<" W-SET: ";
        for(ArrayElementAccessDataSet::const_iterator i=indexToReadWriteDataMap[index].writeArrayAccessSet.begin();i!=indexToReadWriteDataMap[index].writeArrayAccessSet.end();++i) {
          cout<<(*i).toString(variableIdMapping)<<" ";
        }
        cout<<endl;
        cout<<"DEBUG: read-array-access:"<<indexToReadWriteDataMap[index].readArrayAccessSet.size()<<" read-var-access:"<<indexToReadWriteDataMap[index].readVarIdSet.size()<<endl;
        cout<<"DEBUG: write-array-access:"<<indexToReadWriteDataMap[index].writeArrayAccessSet.size()<<" write-var-access:"<<indexToReadWriteDataMap[index].writeVarIdSet.size()<<endl;
      } // imap
#endif

      // perform the check now
      // 1) compute vector if index-vectors for each outer-var-vector
      // 2) check each index-vector. For each iteration of each par-loop iteration then.
      
      //typedef set<int> ParVariableValueSet;
      //ParVariableValueSet parVariableValueSet;
      // MAP: par-variable-val -> vector of IndexVectors with this par-variable-val
      typedef vector<IndexVector> ThreadVector;
      typedef map<IndexVector,ThreadVector > CheckMapType;
      CheckMapType checkMap;
      for(IndexToReadWriteDataMap::iterator imap=indexToReadWriteDataMap.begin();
          imap!=indexToReadWriteDataMap.end();
          ++imap) {
        IndexVector index=(*imap).first;
        IndexVector outVarIndex;
        // if index.size()==0, it will analyze the loop independet of outer loops
        if(index.size()>0) {
          ROSE_ASSERT(index.size()>0);
          for(size_t iv1=0;iv1<index.size()-1;iv1++) {
            outVarIndex.push_back(index[iv1]);
          }
          ROSE_ASSERT(outVarIndex.size()<index.size());
        } else {
          // nothing to check
          continue;
        }
        // last index of index of par-variable
        //int parVariableValue=index[index.size()-1];
        checkMap[outVarIndex].push_back(index);
      }
      //cout<<"INFO: race condition check-map size: "<<checkMap.size()<<endl;
      // perform the check now

      for(CheckMapType::iterator miter=checkMap.begin();miter!=checkMap.end();++miter) {
        IndexVector outerVarIndexVector=(*miter).first;
        ThreadVector threadVectorToCheck=(*miter).second;
        //cout<<"DEBUG: to check: "<<threadVectorToCheck.size()<<endl;
        for(ThreadVector::iterator tv1=threadVectorToCheck.begin();tv1!=threadVectorToCheck.end();++tv1) {
          ArrayElementAccessDataSet wset=indexToReadWriteDataMap[*tv1].writeArrayAccessSet;
          for(ThreadVector::iterator tv2=tv1;tv2!=threadVectorToCheck.end();++tv2) {
            ThreadVector::iterator tv2b=tv2;
            ++tv2b;
            if(tv2b!=threadVectorToCheck.end()) {
              ArrayElementAccessDataSet rset2=indexToReadWriteDataMap[*tv2b].readArrayAccessSet;
              ArrayElementAccessDataSet wset2=indexToReadWriteDataMap[*tv2b].writeArrayAccessSet;
              // check intersect(rset,wset)
              if(accessSetIntersect(wset,rset2)) {
                // verification failed
                cout<<"INFO: race condition detected (wset1,rset2)."<<endl;
                return 1;
              } 
              if(accessSetIntersect(wset,wset2)) {
                // verification failed
                cout<<"INFO: race condition detected (wset1,wset2)."<<endl;
                return 1;
              }
            }
          }
        }
      }
    } // if parallel loop
  } // foreach loop
  return 0;
}
Ejemplo n.º 24
0
IGL_INLINE void igl::sparse(
  const IndexVector & I,
  const IndexVector & J,
  const ValueVector & V,
  const size_t m,
  const size_t n,
  Eigen::SparseMatrix<T>& X)
{
  using namespace std;
  using namespace Eigen;
  assert((int)I.maxCoeff() < (int)m);
  assert((int)I.minCoeff() >= 0);
  assert((int)J.maxCoeff() < (int)n);
  assert((int)J.minCoeff() >= 0);
  assert(I.size() == J.size());
  assert(J.size() == V.size());
  // Really we just need .size() to be the same, but this is safer
  assert(I.rows() == J.rows());
  assert(J.rows() == V.rows());
  assert(I.cols() == J.cols());
  assert(J.cols() == V.cols());

  vector<Triplet<T> > IJV;
  IJV.reserve(I.size());
  for(int x = 0;x<I.size();x++)
  {
    IJV.push_back(Triplet<T >(I(x),J(x),V(x)));
  }
  X.resize(m,n);
  X.setFromTriplets(IJV.begin(),IJV.end());
}
Ejemplo n.º 25
0
IGL_INLINE void igl::sparse(
  const IndexVector & I,
  const IndexVector & J,
  const ValueVector & V,
  const size_t m,
  const size_t n,
  Eigen::SparseMatrix<T>& X)
{
  using namespace std;
  using namespace Eigen;
  assert((int)I.maxCoeff() < (int)m);
  assert((int)I.minCoeff() >= 0);
  assert((int)J.maxCoeff() < (int)n);
  assert((int)J.minCoeff() >= 0);
  assert(I.size() == J.size());
  assert(J.size() == V.size());
  // Really we just need .size() to be the same, but this is safer
  assert(I.rows() == J.rows());
  assert(J.rows() == V.rows());
  assert(I.cols() == J.cols());
  assert(J.cols() == V.cols());
  //// number of values
  //int nv = V.size();

  //Eigen::DynamicSparseMatrix<T, Eigen::RowMajor> dyn_X(m,n);
  //// over estimate the number of entries
  //dyn_X.reserve(I.size());
  //for(int i = 0;i < nv;i++)
  //{
  //  dyn_X.coeffRef((int)I(i),(int)J(i)) += (T)V(i);
  //}
  //X = Eigen::SparseMatrix<T>(dyn_X);
  vector<Triplet<T> > IJV;
  IJV.reserve(I.size());
  for(int x = 0;x<I.size();x++)
  {
    IJV.push_back(Triplet<T >(I(x),J(x),V(x)));
  }
  X.resize(m,n);
  X.setFromTriplets(IJV.begin(),IJV.end());
}
Ejemplo n.º 26
0
/* *** math operations  *******************************************/
int IndexVector::dot(IndexVector &x){
	assert(_length==x.length());
	int tmp=0;
	for(int k=0;k<_length;k++) tmp+= _data[k]*x(k);
	return tmp;
}
Ejemplo n.º 27
0
void IndexVector::add(IndexVector &x, int alpha){
	assert(_length==x.length());
	for(int k=0;k<_length;k++) _data[k]+=alpha*x(k);
}
bool AlignmentAlgorithmPlaneLinear::operator()(AlignmentAlgorithmPlaneLinear::TransformType& transform, const CorrespondenceVector& correspondences, const IndexVector& indices)
{
    double err=0;
    //If my correspondaces indices are less then a minimum threshold, stop it please
    if ((int)indices.size()<minimalSetSize()) return false;

    //My initial guess for the transformation it's the identity matrix
    //maybe in the future i could have a less rough guess
    transform = Isometry3d::Identity();
    //Unroll the matrix to a vector
    Vector12d x=homogeneous2vector(transform.matrix());
    Matrix9x1d rx=x.block<9,1>(0,0);

    //Initialization of variables, melting fat, i've so much space
    Matrix9d H;
    H.setZero();
    Vector9d b;
    b.setZero();
    Matrix3x9d A;
    //iteration for each correspondace
    for (size_t i=0; i<indices.size(); i++)
    {

        A.setZero();
        const Correspondence& c = correspondences[indices[i]];
        const EdgePlane* edge = static_cast<const EdgePlane*>(c.edge());

        //estraggo i vertici dagli edge
        const VertexPlane* v1 = static_cast<const VertexPlane*>(edge->vertex(0));
        const VertexPlane* v2 = static_cast<const VertexPlane*>(edge->vertex(1));

        //recupero i dati dei piani
        const AlignmentAlgorithmPlaneLinear::PointEstimateType& pi= v1->estimate();
        const AlignmentAlgorithmPlaneLinear::PointEstimateType& pj= v2->estimate();

        //recupeo le normali, mi servono per condizionare la parte rotazionale
        Vector3d ni;
        Vector3d nj;
        Vector4d coeffs_i=pi.toVector();
        Vector4d coeffs_j=pj.toVector();

        ni=coeffs_i.head(3);
        nj=coeffs_j.head(3);

        //inizializzo lo jacobiano, solo la parte rotazionale (per ora)
        A.block<1,3>(0,0)=nj.transpose();
        A.block<1,3>(1,3)=nj.transpose();
        A.block<1,3>(2,6)=nj.transpose();

        if(DEBUG) {
            cerr << "[DEBUG] PI"<<endl;
            cerr << coeffs_i<<endl;
            cerr << "[DEBUG] PJ "<<endl;
            cerr << coeffs_j<<endl;
            cerr << "[ROTATION JACOBIAN][PLANE "<<i<<"]"<<endl;
            cerr << A<<endl;
        }
        //errore
        //inizializzo errore
        Vector3d ek;
        ek.setZero();
        ek=A*x.block<9,1>(0,0)-coeffs_i.head(3);
        H+=A.transpose()*A;

        b+=A.transpose()*ek;

        err+=abs(ek.dot(ek));

        if(DEBUG)
            cerr << "[ROTATIONAL Hessian for plane "<<i<<"]"<<endl<<H<<endl;
        if(DEBUG)
            cerr << "[ROTATIONAL B for plane "<<i<<"]"<<endl<<b<<endl;
    }
    LDLT<Matrix9d> ldlt(H);
    if (ldlt.isNegative()) return false;
    rx=ldlt.solve(-b); // using a LDLT factorizationldlt;

    x.block<3,1>(0,0)+=rx.block<3,1>(0,0);
    x.block<3,1>(3,0)+=rx.block<3,1>(3,0);
    x.block<3,1>(6,0)+=rx.block<3,1>(6,0);
    if(DEBUG) {
        cerr << "Solving the linear system"<<endl;
        cerr << "------------>H"<<endl;
        cerr << H<<endl;
        cerr << "------------>b"<<endl;
        cerr << b<<endl;
        cerr << "------------>rx"<<endl;
        cerr << rx<<endl;
        cerr << "------------>xTEMP"<<endl;
        cerr << vector2homogeneous(x)<<endl<<endl;

        cerr << "łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł"<<endl;
        cerr << "łłłłłłłłłłł Ringraziamo Cthulhu la parte rotazionale è finitałłłłłłłłłłł"<<endl;
        cerr << "łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł łłłłłłłłłłł"<<endl;
    }
    Matrix4d Xtemp=vector2homogeneous(x);

    //now the problem si solved but i could have (and probably i have!)
    //a not orthogonal rotation matrix, so i've to recondition it

    Matrix3x3d R=Xtemp.block<3,3>(0,0);
    // recondition the rotation
    JacobiSVD<Matrix3x3d> svd(R, Eigen::ComputeThinU | Eigen::ComputeThinV);
    if (svd.singularValues()(0)<.5) return false;
    R=svd.matrixU()*svd.matrixV().transpose();
    Isometry3d X = Isometry3d::Identity();
    X.linear()=R;
    X.translation()= x.block<3,1>(0,3);
    if(DEBUG)
        cerr << "X dopo il ricondizionamento appare come:"<<endl;
    if(DEBUG)
        cerr << X.matrix()<<endl;


    Matrix3d H2=Matrix3d::Zero();
    Vector3d b2=Vector3d::Zero();
    Vector3d A2=Vector3d::Zero();

    //at this point rotation is cured, now it's time to work on the translation

    for (size_t i=0; i<indices.size(); i++)
    {
        if(DEBUG)
            cerr << "[TRANSLATION JACOBIAN START][PLANE "<<i<<"]"<<endl;

        const Correspondence& c = correspondences[indices[i]];
        const EdgePlane* edge = static_cast<const EdgePlane*>(c.edge());

        //estraggo i vertici dagli edge
        const VertexPlane* v1 = static_cast<const VertexPlane*>(edge->vertex(0));
        const VertexPlane* v2 = static_cast<const VertexPlane*>(edge->vertex(1));

        //recupero i dati dei piani
        const AlignmentAlgorithmPlaneLinear::PointEstimateType& pi= v1->estimate();
        const AlignmentAlgorithmPlaneLinear::PointEstimateType& pj= v2->estimate();

        //recupeo le normali, mi servono per condizionare la parte rotazionale
        Vector3d ni;
        Vector3d nj;
        Vector4d coeffs_i=pi.toVector();
        Vector4d coeffs_j=pj.toVector();
        double di;
        double dj;

        ni=coeffs_i.head(3);
        nj=coeffs_j.head(3);

        di=coeffs_i(3);
        dj=coeffs_j(3);
        if(DEBUG)
            cerr << "[TRANSLATION JACOBIAN][ JACOBIAN IS: ]"<<endl;
        A2=(-nj.transpose()*R.transpose());
        if(DEBUG)
            cerr << A2<<endl;

        double ek;
        ek=dj+A2.transpose()*X.translation()-di;
        H2+=A2*A2.transpose();
        b2+= (A2.transpose()*ek);
        err += abs(ek*ek);

        if(DEBUG)
            cerr << "[TRANSLATIONAL Hessian for plane "<<i<<"]"<<endl<<H2<<endl;
        if(DEBUG)
            cerr << "[TRANSLATIONAL B for plane "<<i<<"]"<<endl<<b2<<endl;
    }
    if(DEBUG)
        cerr << "[FINAL][TRANSLATIONAL Hessian]"<<endl<<H2<<endl;
    if(DEBUG)
        cerr << "[FINAL][TRANSLATIONAL B]"<<endl<<b2<<endl;

    //solving the system
    Vector3d dt;
    LDLT<Matrix3d> ldlt2(H2);
    dt=ldlt2.solve(-b2); // using a LDLT factorizationldlt;
    if(DEBUG)
        cerr << "[FINAL][TRANSLATIONAL DT]"<<endl<<dt<<endl;


    X.translation()+=dt;
    transform = X;
    if(DEBUG)
    {
        cerr << "TRANSFORM found: " << endl<< endl<< endl;
        cerr << g2o::internal::toVectorMQT(X) << endl;;
        cerr << transform.matrix()<< endl;;
    }
    return true;
}
Ejemplo n.º 29
0
static void expandLabels(Bundle& bundle, size_t beamSize)
{
    auto& outputActivationsVector = bundle["outputActivations"].get<MatrixVector>();

    auto& outputActivations = outputActivationsVector.back();

    auto& labels = bundle["referenceLabels"].get<LabelVector>();
    auto& inputTimesteps = bundle["inputTimesteps"].get<IndexVector>();

    size_t characters    = outputActivations.size().front();
    size_t miniBatchSize = outputActivations.size()[outputActivations.size().size() - 2];
    size_t maxTimesteps  = outputActivations.size()[outputActivations.size().size() - 1];

    size_t originalMiniBatchSize = miniBatchSize / beamSize;

    LabelVector expandedLabels;
    IndexVector expandedTimesteps;

    for(size_t miniBatch = 0; miniBatch < originalMiniBatchSize; ++miniBatch)
    {
        for(size_t beam = 0; beam < beamSize; ++beam)
        {
            expandedLabels.push_back(labels[miniBatch]);
            expandedTimesteps.push_back(inputTimesteps[miniBatch]);
        }
    }

    labels = std::move(expandedLabels);
    inputTimesteps = std::move(expandedTimesteps);

    auto referenceActivations = matrix::zeros({characters, miniBatchSize, maxTimesteps},
        outputActivations.precision());

    for(size_t miniBatch = 0; miniBatch < miniBatchSize; ++miniBatch)
    {
        for(size_t timestep = 0; timestep < maxTimesteps; ++timestep)
        {
            if(timestep < labels[miniBatch].size())
            {
                size_t character = labels[miniBatch][timestep];

                assert(character < characters);

                referenceActivations(character, miniBatch, timestep) = 1.0;
            }
            else
            {
                referenceActivations(characters - 1, miniBatch, timestep) = 1.0;
            }
        }
    }

    if(util::isLogEnabled("CTCDecoderLayer::Detail"))
    {
        util::log("CTCDecoderLayer::Detail") << "  reference labels: \n";
        for(auto& label : labels)
        {
            util::log("CTCDecoderLayer::Detail") << "   reference label: "
                << util::toString(label) << "\n";

        }
        util::log("CTCDecoderLayer::Detail") << "  reference activations: "
            << referenceActivations.debugString();
    }
    else
    {
        util::log("CTCDecoderLayer::Detail") << "  reference labels size: "
            << labels.size() << "\n";
        util::log("CTCDecoderLayer") << "  reference activations size: "
            << outputActivations.shapeString() << "\n";
    }

    bundle["referenceActivations"] = MatrixVector({referenceActivations});
}