Esempio n. 1
0
void test_empty()
{
	IntVec v;
	CYBOZU_TEST_EQUAL((int)v.size(), 0);
	CYBOZU_TEST_ASSERT(v.empty());
	for (typename IntVec::const_iterator i = v.begin(); i != v.end(); ++i) {
		printf("%d\n", i->val());
	}
	v.push_back(3, 1);
	CYBOZU_TEST_EQUAL((int)v.size(), 1);
	CYBOZU_TEST_ASSERT(!v.empty());
	for (typename IntVec::const_iterator i = v.begin(); i != v.end(); ++i) {
		CYBOZU_TEST_EQUAL(i->pos(), (size_t)3);
		CYBOZU_TEST_EQUAL(i->val(), 1);
	}
	v.push_back(4, 2);
	CYBOZU_TEST_EQUAL((int)v.size(), 2);
	int j = 0;
	for (typename IntVec::const_iterator i = v.begin(); i != v.end(); ++i) {
		CYBOZU_TEST_EQUAL(i->pos(), size_t(j + 3));
		CYBOZU_TEST_EQUAL(i->val(), j + 1);
		j++;
	}
	v.clear();
	CYBOZU_TEST_EQUAL((int)v.size(), 0);
	CYBOZU_TEST_ASSERT(v.empty());
	IntVec v1, v2;
	for (int i = 0; i < 3; i++) {
		v1.push_back(i, i);
		v2.push_back(i, i);
	}
	CYBOZU_TEST_ASSERT(v1 == v2);
	v2.push_back(10, 10);
	CYBOZU_TEST_ASSERT(v1 != v2);
}
int solve(const IntVec& A, const IntVec& B, int k)
{
    IntVec q(k);
    int n = 0;
    int NA = A.size() >= k ? k : A.size();
    int NB = B.size() >= k ? k : B.size();

    for (int i = 0; i < NA; ++i) {
        for (int j = 0; j < NB; ++j) {
            int s = A[i] + B[i];
            if (n == k) {
                if (s < q[0]) {
                    pop_heap(q.begin(), q.end());
                    q[n - 1] = A[i] + B[j];
                    push_heap(q.begin(), q.begin() + n);
                }
            } else {
                q[n++] = A[i] + B[j];
                push_heap(q.begin(), q.begin() + n);
            }
            //			cout << n << "," << q << endl;
        }
    }
    //	cout << q << endl;
    return q[0];
}
Esempio n. 3
0
  static int findRotatedIndex(IntVec const& vec) {
    if (vec.size() < 1) return 0;
    int prev_val = vec[0];
    for (int i=1; i<vec.size(); ++i) {
      int curr_val = vec[i];
      if (prev_val > curr_val) return i;
      prev_val = curr_val;
    }

    return 0;
  }
Esempio n. 4
0
bool SparseMatrix::assemble (const Matrix& eM, const SAM& sam,
                             SystemVector& B, const IntVec& meen)
{
  StdVector* Bptr = dynamic_cast<StdVector*>(&B);
  if (!Bptr) return false;

  if (eM.rows() < meen.size() || eM.cols() < meen.size())
    return false;

  assemSparse(eM,*this,*Bptr,meen,sam.meqn,sam.mpmceq,sam.mmceq,sam.ttcc);
  return true;
}
Esempio n. 5
0
//
// Initialise with domain data
//
bool DataVar::initFromMeshData(const_DomainChunk_ptr dom, const IntVec& data,
        int fsCode, Centering c, NodeData_ptr nodes, const IntVec& id)
{
    cleanup();
    
    domain = dom;
    rank = 0;
    ptsPerSample = 1;
    centering = c;
    sampleID = id;
    meshName = nodes->getName();
    siloMeshName = nodes->getFullSiloName();
    numSamples = data.size();

    if (numSamples > 0) {
        float* c = new float[numSamples];
        dataArray.push_back(c);
        IntVec::const_iterator it;
        for (it=data.begin(); it != data.end(); it++)
            *c++ = static_cast<float>(*it);
    }
    initialized = true;

    return initialized;
}
Esempio n. 6
0
void CEditableObject::GetBoneWorldTransform(u32 bone_idx, float t, CSMotion* motion, Fmatrix& matrix)
{
	VERIFY(bone_idx<m_Bones.size());
    int idx	= bone_idx;
    matrix.identity();
    IntVec lst;
    do{ lst.push_back(idx); }while((idx=m_Bones[idx]->Parent()?m_Bones[idx]->Parent()->SelfID:-1)>-1);
    for (int i=lst.size()-1; i>=0; i--){
    	idx = lst[i];
	    Flags8 flags	= motion->GetMotionFlags(idx);
    	Fvector T,R;
        Fmatrix rot, mat;
        motion->_Evaluate(idx,t,T,R);
        if (flags.is(st_BoneMotion::flWorldOrient)){
            rot.setXYZi(R.x,R.y,R.z);
            mat.identity();
            mat.c.set(T);
            mat.mulA_43(matrix);
            mat.i.set(rot.i);
            mat.j.set(rot.j);
            mat.k.set(rot.k);
        }else{
            mat.setXYZi(R.x,R.y,R.z);
            mat.c.set(T);
            mat.mulA_43(matrix);
        }
        matrix.set(mat);
    }
}
Esempio n. 7
0
	void term()
	{
		const double logN = log(double(tf_.size()));
		idf_.resize(df_.size());
		for (size_t i = 0, n = df_.size(); i < n; i++) {
			idf_[i] = logN - log(double(df_[i]));
		}
		for (size_t i = 0, n = df_.size(); i < n; i++) {
			const Int2Int& iv = tf_[i];
			DoubleSvec v;
			for (Int2Int::const_iterator j = iv.begin(), je = iv.end(); j != je; ++j) {
				v.push_back(j->first, j->second * idf_[j->first]);
			}
			sv_.push_back(v);
		}
	}
Esempio n. 8
0
	long long minCost(vector <string> road, vector <int> altitude) {
		int sz = (int)road.size();

		// generate alt table
		IntVec alt = altitude;
		sort(alt.begin(), alt.end());
		unique(alt.begin(), alt.end());

		LL mincost[64][64];
		memset(mincost, 0x3f, sizeof(mincost));

		LIIQueue q;
		int i, j;
		for (i = 0; i < (int)alt.size(); ++i) {
			LL cost = abs(alt[i] - altitude[0]);
			mincost[0][i] = cost;
			q.push(LII(-cost, II(0, alt[i])));
		}

		// dijkstra
		while (q.size() > 0) {
			LII current = q.top();
			q.pop();
			int from = current.second.first;
			if (from == (sz-1)) {
				return -current.first;
			}
			for (i = 0; i < (int)alt.size(); ++i) {
				if (alt[i] > current.second.second) {
					break;
				}
				for (j = 0; j < sz; ++j) {
					if (road[from][j] == 'Y') {
						LL cost = -current.first + abs(alt[i] - altitude[j]);
						if (cost < mincost[j][i]) {
							mincost[j][i] = cost;
							q.push(LII(-cost, II(j, alt[i])));
						}
					}
				}
			}
		}

		return -1;
	}
Esempio n. 9
0
	void put(int maxNum = 0x7fffffff) const
	{
		printf("docNum=%d, wordNum=%d\n", (int)tf_.size(), (int)df_.size());
		for (int i = 0, n = std::min(maxNum, (int)sv_.size()); i < n; i++) {
			const DoubleSvec& v = sv_[i];
			for (DoubleSvec::const_iterator j = v.begin(), je = v.end(); j != je; ++j) {
				printf("%d:%f ", (int)j->pos(), j->val());
			}
			printf("\n");
		}
	}
Esempio n. 10
0
	bool can(LL n) {
		int i = 0;
		LLVec t(g.size());
		ILLMap::const_iterator it;
		for (it = e.begin(); it != e.end(); ++it) {
			LL r = it->second;
			while (r > 0) {
				LL c = min(r, n - t[i]);
				if (g[i] < it->first || c <= 0) {
					++i;
					if (i >= (int)g.size()) {
						return false;
					}
					continue;
				}
				r -= c;
				t[i] += c;
			}
		}
		return true;
	}
Esempio n. 11
0
	// sort freq order
	void term(int lowerLimit = 3, double upperRateLimit = 0.98)
	{
		fprintf(stderr, "#doc=%d, #word=%d\n", docNum_, (int)df_.size());
		for (size_t i = 0, n = id2word_.size(); i < n; i++) {
			const int freq = df_[i];
			if (freq <= lowerLimit) continue;
			pv_.push_back(Pair(i, freq));
		}
		int pvNum = (int)(pv_.size() * upperRateLimit);
		fprintf(stderr, "shrink %d -> %d\n", (int)pv_.size(), pvNum);
		std::partial_sort(pv_.begin(), pv_.begin() + pvNum, pv_.end());
		pv_.resize(pvNum);
	}
Esempio n. 12
0
int main ()
{
  typedef vector <int> IntVec;
  IntVec v (10);
  for (int i = 0; i < v.size (); i++)
    v[i] = (i + 1) * (i + 1);
  IntVec::iterator iter;
  iter = find_if (v.begin (), v.end (), div_3);
  if (iter != v.end ())
    cout
      << "Value "
      << *iter
      << " at offset "
      << (iter - v.begin ())
      << " is divisible by 3"
      << endl;
  return 0;
}
Esempio n. 13
0
static void assemSparse (const RealArray& V, SparseMatrix& SM, size_t col,
                         const IntVec& mnen, const int* meqn,
                         const int* mpmceq, const int* mmceq, const Real* ttcc)
{
  for (size_t d = 0; d < mnen.size(); d++, col++)
  {
    Real vd = d < V.size() ? V[d] : V.back();
    int ieq = mnen[d];
    int ceq = -ieq;
    if (ieq > 0)
      SM(ieq,col) += vd;
    else if (ceq > 0)
      for (int ip = mpmceq[ceq-1]; ip < mpmceq[ceq]-1; ip++)
      {
        ieq = meqn[mmceq[ip]-1];
        SM(ieq,col) += vd;
      }
  }
}
Esempio n. 14
0
void SpeckleyElements::reorderArray(IntVec& v, const IntVec& idx,
                               int elementsPerIndex)
{
    IntVec newArray(v.size());
    IntVec::iterator arrIt = newArray.begin();
    IntVec::const_iterator idxIt;
    if (elementsPerIndex == 1) {
        for (idxIt=idx.begin(); idxIt!=idx.end(); idxIt++) {
            *arrIt++ = v[*idxIt];
        }
    } else {
        for (idxIt=idx.begin(); idxIt!=idx.end(); idxIt++) {
            int i = *idxIt;
            copy(&v[i*elementsPerIndex], &v[(i+1)*elementsPerIndex], arrIt);
            arrIt += elementsPerIndex;
        }
    }
    v.swap(newArray);
}
Esempio n. 15
0
	bool loadKeywordFile(const std::string& keyFile)
	{
		std::ifstream ifs(keyFile.c_str(), std::ios::binary);
		if (!ifs) return false;
		std::string word;
		while (std::getline(ifs, word)) {
			size_t pos = word.find('\t');
			if (pos == std::string::npos) break;
			word.resize(pos);
			std::pair<Str2Int::iterator, bool> ret = word2id_.insert(Str2Int::value_type(word, (int)id2word_.size()));
			if (ret.second) {
				id2word_.push_back(word);
			} else {
				fprintf(stderr, "ERR already set %s\n", word.c_str());
			}
		}
		df_.resize(id2word_.size());
		fprintf(stderr, "#word = %d\n", (int)df_.size());
		return true;
	}
Esempio n. 16
0
	LLPair eval(const IntVec &program, size_t pos) {
		int sz = (int)program.size();
		size_t i;
		LLPairQueue q;
		for (i = 0; i <= sz*2; ++i) {
			q.push_front(LLPair(0, 0));
		}
		for (i = 0; i < sz; ++i) {
			LLPair c(program[i], i == pos);
			if (program[i] == 0) {
				LLPair a = q.front();
				q.pop_front();
				LLPair b = q.front();
				q.pop_front();
				c.first = a.first + b.first;
				c.second = a.second + b.second;
			}
			q.push_front(c);
		}
		return q.front();
	}
Esempio n. 17
0
	double rec(int i, int M) {
		if (memo[i][M] > 0) {
			return memo[i][M];
		}
		double &res = memo[i][M];
		int G = min(Max, M+_gain[i]);
		int d = G+1;
		if ((i+1) < (int)_day.size()) {
			d = _day[i+1] - _day[i];
		}
		if (M > d) {
			res = rec(i+1, M-d);
		} else {
			res = _day[i]+M;
		}
		if (G > d) {
			res = max(res, (1.0-_win[i])*_day[i] + _win[i]*rec(i+1, G-d));
		} else {
			res = max(res, (1.0-_win[i])*_day[i] + _win[i]*(_day[i]+G));
		}
		return res;
	}
Esempio n. 18
0
//prime factors, less than or equal to num. 
//check each prime number to square root
void factor(i64 num, I64PairVec& ifac, const IntVec& prime)
{
    //special case, not prime factor for 1
    ifac.clear();
    if(num==1){
        ifac.push_back(IntPair(1,1));
        return;
    }
    i64 n1 = num;
    int ubound = sqrt((double) num);
    for(unsigned int i = 0; i < prime.size(); ++i) {
        int nth = 0;
        if( n1 % prime[i] == 0){
            while(n1% prime[i] ==0) {
                n1/=prime[i];
                ++nth;
            }
            ifac.push_back(IntPair(prime[i], nth));
        }
        if(n1 == 1 || prime[i] > ubound)break;
    }
    if(n1 > 1) ifac.push_back(I64Pair(n1, 1));
}
Esempio n. 19
0
bool ASMstruct::addXNodes (unsigned short int dim, size_t nXn, IntVec& nodes)
{
  if (dim != ndim-1)
  {
    std::cerr <<" *** ASMstruct::addXNodes: Invalid boundary dimension "<< dim
              <<", only "<< (int)ndim-1 <<" is allowed."<< std::endl;
    return false;
  }
  else if (!geo || shareFE == 'F')
    return false; // logic error

  else if (MNPC.size() == nel && MLGE.size() == nel)
  {
    // Extend the element number and element topology arrays to double size,
    // to account for extra-ordinary elements associated with contact surfaces
    myMLGE.resize(2*nel,0);
    myMNPC.resize(2*nel);
  }
  else if (MLGE.size() != 2*nel || MNPC.size() != 2*nel)
  {
    // Already added interface elements, currently not allowed
    std::cerr <<" *** ASMstruct::addXNodes: Already have interface elements."
              << std::endl;
    return false;
  }

  // Add nXn extra-ordinary nodes to the list of global node numbers
  for (size_t i = 0; i < nXn; i++)
  {
    if (nodes.size() == i)
      nodes.push_back(++gNod);
    myMLGN.push_back(nodes[i]);
  }

  return true;
}
Esempio n. 20
0
bool SIMoutput::dumpVector (const Vector& vsol, const char* fname,
                            utl::LogStream& os, std::streamsize precision) const
{
  if (vsol.empty() || myPoints.empty())
    return true;

  size_t i, j, k;
  Matrix sol1;
  Vector lsol;

  for (i = 0; i < myModel.size(); i++)
  {
    if (myModel[i]->empty()) continue; // skip empty patches

    std::vector<ResPtPair>::const_iterator pit;
    ResPointVec::const_iterator p;
    std::array<RealArray,3> params;
    IntVec points;

    // Find all evaluation points within this patch, if any
    for (j = 0, pit = myPoints.begin(); pit != myPoints.end(); ++pit)
      for (p = pit->second.begin(); p != pit->second.end(); j++, ++p)
        if (this->getLocalPatchIndex(p->patch) == (int)(i+1))
          if (opt.discretization >= ASM::Spline)
          {
            points.push_back(p->inod > 0 ? p->inod : -(j+1));
            for (k = 0; k < myModel[i]->getNoParamDim(); k++)
              params[k].push_back(p->u[k]);
          }
          else if (p->inod > 0)
            points.push_back(p->inod);

    if (points.empty()) continue; // no points in this patch

    // Evaluate/extracto nodal solution variables
    myModel[i]->extractNodeVec(vsol,lsol);
    if (opt.discretization >= ASM::Spline)
    {
      if (!myModel[i]->evalSolution(sol1,lsol,params.data(),false))
        return false;
    }
    else
    {
      if (!myModel[i]->getSolution(sol1,lsol,points))
        return false;
    }

    // Formatted output, use scientific notation with fixed field width
    std::streamsize flWidth = 8 + precision;
    std::streamsize oldPrec = os.precision(precision);
    std::ios::fmtflags oldF = os.flags(std::ios::scientific | std::ios::right);
    for (j = 0; j < points.size(); j++)
    {
      if (points[j] < 0)
        os <<"  Point #"<< -points[j];
      else
      {
        points[j] = myModel[i]->getNodeID(points[j]);
        os <<"  Node #"<< points[j];
      }

      os <<":\t"<< fname <<" =";
      for (k = 1; k <= sol1.rows(); k++)
        os << std::setw(flWidth) << utl::trunc(sol1(k,j+1));

      os << std::endl;
    }
    os.precision(oldPrec);
    os.flags(oldF);
  }

  return true;
}
Esempio n. 21
0
 RotatedIndex(IntVec const& vec) {
   size = vec.size();
   shift = findRotatedIndex(vec);
 }
Esempio n. 22
0
////////////////////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
bool GenerateStrips(const unsigned short* in_indices, const unsigned int in_numIndices,
					PrimitiveGroup** primGroups, unsigned short* numGroups, bool validateEnabled)
{
	int i = 0;
	
	//put data in format that the stripifier likes
	WordVec tempIndices;
	tempIndices.resize(in_numIndices);
	unsigned short maxIndex = 0;
	unsigned short minIndex = 0xFFFF;
	for(i = 0; i < in_numIndices; i++)
	{
		tempIndices[i] = in_indices[i];
		if (in_indices[i] > maxIndex)
			maxIndex = in_indices[i];
		if (in_indices[i] < minIndex)
			minIndex = in_indices[i];
	}
	NvStripInfoVec tempStrips;
	NvFaceInfoVec tempFaces;

	NvStripifier stripifier;
	
	//do actual stripification
	stripifier.Stripify(tempIndices, cacheSize, minStripSize, maxIndex, tempStrips, tempFaces);

	//stitch strips together
	IntVec stripIndices;
	unsigned int numSeparateStrips = 0;

	if(bListsOnly)
	{
		//if we're outputting only lists, we're done
		*numGroups = 1;
		(*primGroups) = new PrimitiveGroup[*numGroups];
		PrimitiveGroup* primGroupArray = *primGroups;

		//count the total number of indices
		unsigned int numIndices = 0;
		for(i = 0; i < tempStrips.size(); i++)
		{
			numIndices += tempStrips[i]->m_faces.size() * 3;
		}

		//add in the list
		numIndices += tempFaces.size() * 3;

		primGroupArray[0].type       = PT_LIST;
		primGroupArray[0].numIndices = numIndices;
		primGroupArray[0].indices    = new unsigned short[numIndices];

		//do strips
		unsigned int indexCtr = 0;
		for(i = 0; i < tempStrips.size(); i++)
		{
			for(int j = 0; j < tempStrips[i]->m_faces.size(); j++)
			{
				//degenerates are of no use with lists
				if(!NvStripifier::IsDegenerate(tempStrips[i]->m_faces[j]))
				{
					primGroupArray[0].indices[indexCtr++] = tempStrips[i]->m_faces[j]->m_v0;
					primGroupArray[0].indices[indexCtr++] = tempStrips[i]->m_faces[j]->m_v1;
					primGroupArray[0].indices[indexCtr++] = tempStrips[i]->m_faces[j]->m_v2;
				}
				else
				{
					//we've removed a tri, reduce the number of indices
					primGroupArray[0].numIndices -= 3;
				}
			}
		}

		//do lists
		for(i = 0; i < tempFaces.size(); i++)
		{			
			primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v0;
			primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v1;
			primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v2;
		}
	}
	else
	{
		stripifier.CreateStrips(tempStrips, stripIndices, bStitchStrips, numSeparateStrips, bRestart, restartVal);

		//if we're stitching strips together, we better get back only one strip from CreateStrips()
		assert( (bStitchStrips && (numSeparateStrips == 1)) || !bStitchStrips);
		
		//convert to output format
		*numGroups = numSeparateStrips; //for the strips
		if(tempFaces.size() != 0)
			(*numGroups)++;  //we've got a list as well, increment
		(*primGroups) = new PrimitiveGroup[*numGroups];
		
		PrimitiveGroup* primGroupArray = *primGroups;
		
		//first, the strips
		int startingLoc = 0;
		for(int stripCtr = 0; stripCtr < numSeparateStrips; stripCtr++)
		{
			int stripLength = 0;

			if(!bStitchStrips)
			{
				int i;
				//if we've got multiple strips, we need to figure out the correct length
				for(i = startingLoc; i < stripIndices.size(); i++)
				{
					if(stripIndices[i] == -1)
						break;
				}
				
				stripLength = i - startingLoc;
			}
			else
				stripLength = stripIndices.size();
			
			primGroupArray[stripCtr].type       = PT_STRIP;
			primGroupArray[stripCtr].indices    = new unsigned short[stripLength];
			primGroupArray[stripCtr].numIndices = stripLength;
			
			int indexCtr = 0;
			for(int i = startingLoc; i < stripLength + startingLoc; i++)
				primGroupArray[stripCtr].indices[indexCtr++] = stripIndices[i];

			//we add 1 to account for the -1 separating strips
			//this doesn't break the stitched case since we'll exit the loop
			startingLoc += stripLength + 1; 
		}
		
		//next, the list
		if(tempFaces.size() != 0)
		{
			int faceGroupLoc = (*numGroups) - 1;    //the face group is the last one
			primGroupArray[faceGroupLoc].type       = PT_LIST;
			primGroupArray[faceGroupLoc].indices    = new unsigned short[tempFaces.size() * 3];
			primGroupArray[faceGroupLoc].numIndices = tempFaces.size() * 3;
			int indexCtr = 0;
			for(int i = 0; i < tempFaces.size(); i++)
			{
				primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v0;
				primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v1;
				primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v2;
			}
		}
	}

	//validate generated data against input
	if (validateEnabled)
	{
		const int NUMBINS = 100;

		std::vector<NvFaceInfo> in_bins[NUMBINS];
		
		//hash input indices on first index
		for (i = 0; i < in_numIndices; i += 3)
		{
			NvFaceInfo faceInfo(in_indices[i], in_indices[i + 1], in_indices[i + 2]);
			in_bins[in_indices[i] % NUMBINS].push_back(faceInfo);
		}
		
		for (i = 0; i < *numGroups; ++i)
		{
			switch ((*primGroups)[i].type)
			{
				case PT_LIST:
				{
					for (int j = 0; j < (*primGroups)[i].numIndices; j += 3)
					{
						unsigned short v0 = (*primGroups)[i].indices[j];
						unsigned short v1 = (*primGroups)[i].indices[j + 1];
						unsigned short v2 = (*primGroups)[i].indices[j + 2];
						
						//ignore degenerates
						if (NvStripifier::IsDegenerate(v0, v1, v2))
							continue;

						if (!TestTriangle(v0, v1, v2, in_bins, NUMBINS))
						{
							Cleanup(tempStrips, tempFaces);
							return false;
						}
					}
					break;
				}

				case PT_STRIP:
				{
					//int brokenCtr = 0;
					bool flip = false;
					for (int j = 2; j < (*primGroups)[i].numIndices; ++j)
					{
						unsigned short v0 = (*primGroups)[i].indices[j - 2];
						unsigned short v1 = (*primGroups)[i].indices[j - 1];
						unsigned short v2 = (*primGroups)[i].indices[j];
						
						if (flip)
						{
							//swap v1 and v2
							unsigned short swap = v1;
							v1 = v2;
							v2 = swap;
						}

						//ignore degenerates
						if (NvStripifier::IsDegenerate(v0, v1, v2))
						{
							flip = !flip;
							continue;
						}

						if (!TestTriangle(v0, v1, v2, in_bins, NUMBINS))
						{
							Cleanup(tempStrips, tempFaces);
							return false;
						}

						flip = !flip;
					}
					break;
				}

				case PT_FAN:
				default:
					break;
			}
		}

	}

	//clean up everything
	Cleanup(tempStrips, tempFaces);

	return true;
}
////////////////////////////////////////////////////////////////////////////////////////
// CreateStrips()
//
// Generates actual strips from the list-in-strip-order.
//
void NvStripifier::CreateStrips(const NvStripInfoVec& allStrips, IntVec& stripIndices, 
								const bool bStitchStrips, unsigned int& numSeparateStrips, 
								const bool bRestart, const unsigned int restartVal)
{
	assert(numSeparateStrips == 0);

	NvFaceInfo tLastFace(0, 0, 0);
	NvFaceInfo tPrevStripLastFace(0, 0, 0);
	size_t nStripCount = allStrips.size();

	//we infer the cw/ccw ordering depending on the number of indices
	//this is screwed up by the fact that we insert -1s to denote changing strips
	//this is to account for that
	int accountForNegatives = 0;

	for (size_t i = 0; i < nStripCount; i++)
	{
		NvStripInfo *strip = allStrips[i];
		int nStripFaceCount = strip->m_faces.size();
		assert(nStripFaceCount > 0);

		// Handle the first face in the strip
		{
			NvFaceInfo tFirstFace(strip->m_faces[0]->m_v0, strip->m_faces[0]->m_v1, strip->m_faces[0]->m_v2);

			// If there is a second face, reorder vertices such that the
			// unique vertex is first
			if (nStripFaceCount > 1)
			{
				int nUnique = NvStripifier::GetUniqueVertexInB(strip->m_faces[1], &tFirstFace);
				if (nUnique == tFirstFace.m_v1)
				{
					SWAP(tFirstFace.m_v0, tFirstFace.m_v1);
				}
				else if (nUnique == tFirstFace.m_v2)
				{
					SWAP(tFirstFace.m_v0, tFirstFace.m_v2);
				}

				// If there is a third face, reorder vertices such that the
				// shared vertex is last
				if (nStripFaceCount > 2)
				{
					if(IsDegenerate(strip->m_faces[1]))
					{
						int pivot = strip->m_faces[1]->m_v1;
						if(tFirstFace.m_v1 == pivot)
						{
							SWAP(tFirstFace.m_v1, tFirstFace.m_v2);
						}
					}
					else
					{
						int nShared0, nShared1;
						GetSharedVertices(strip->m_faces[2], &tFirstFace, &nShared0, &nShared1);
						if ( (nShared0 == tFirstFace.m_v1) && (nShared1 == -1) )
						{
							SWAP(tFirstFace.m_v1, tFirstFace.m_v2);
						}
					}
				}
			}

			if( (i == 0) || !bStitchStrips || bRestart)
			{
				if(!IsCW(strip->m_faces[0], tFirstFace.m_v0, tFirstFace.m_v1))
					stripIndices.push_back(tFirstFace.m_v0);
			}
			else
			{
				// Double tap the first in the new strip
				stripIndices.push_back(tFirstFace.m_v0);
	
				// Check CW/CCW ordering
				if (NextIsCW(stripIndices.size() - accountForNegatives) != IsCW(strip->m_faces[0], tFirstFace.m_v0, tFirstFace.m_v1))
				{
					stripIndices.push_back(tFirstFace.m_v0);
				}
			}

			stripIndices.push_back(tFirstFace.m_v0);
			stripIndices.push_back(tFirstFace.m_v1);
			stripIndices.push_back(tFirstFace.m_v2);

			// Update last face info
			tLastFace = tFirstFace;
		}

		for (int j = 1; j < nStripFaceCount; j++)
		{
			int nUnique = GetUniqueVertexInB(&tLastFace, strip->m_faces[j]);
			if (nUnique != -1)
			{
				stripIndices.push_back(nUnique);

				// Update last face info
				tLastFace.m_v0 = tLastFace.m_v1;
				tLastFace.m_v1 = tLastFace.m_v2;
				tLastFace.m_v2 = nUnique;
			}
			else
			{
				//we've hit a degenerate
				stripIndices.push_back(strip->m_faces[j]->m_v2);
				tLastFace.m_v0 = strip->m_faces[j]->m_v0;//tLastFace.m_v1;
				tLastFace.m_v1 = strip->m_faces[j]->m_v1;//tLastFace.m_v2;
				tLastFace.m_v2 = strip->m_faces[j]->m_v2;//tLastFace.m_v1;

			}
		}

		// Double tap between strips.
		if (bStitchStrips && !bRestart) 
		{
			if (i != nStripCount - 1)
				stripIndices.push_back(tLastFace.m_v2);
		} 
		else if (bRestart) 
		{
			stripIndices.push_back(restartVal);
		} 
		else 
		{
			//-1 index indicates next strip
			stripIndices.push_back(-1);
			accountForNegatives++;
			numSeparateStrips++;
		}

		// Update last face info
		tLastFace.m_v0 = tLastFace.m_v1;
		tLastFace.m_v1 = tLastFace.m_v2;
		tLastFace.m_v2 = tLastFace.m_v2;
	}
	
	if(bStitchStrips || bRestart)
		numSeparateStrips = 1;
}
Esempio n. 24
0
static void assemSparse (const Matrix& eM, SparseMatrix& SM, Vector& SV,
                         const IntVec& meen, const int* meqn,
                         const int* mpmceq, const int* mmceq, const Real* ttcc)
{
  // Add elements corresponding to free dofs in eM into SM
  int i, j, ip, nedof = meen.size();
  for (j = 1; j <= nedof; j++)
  {
    int jeq = meen[j-1];
    if (jeq < 1) continue;

    SM(jeq,jeq) += eM(j,j);

    for (i = 1; i < j; i++)
    {
      int ieq = meen[i-1];
      if (ieq < 1) continue;

      SM(ieq,jeq) += eM(i,j);
      SM(jeq,ieq) += eM(j,i);
    }
  }

  // Add (appropriately weighted) elements corresponding to constrained
  // (dependent and prescribed) dofs in eM into SM and/or SV
  for (j = 1; j <= nedof; j++)
  {
    int jceq = -meen[j-1];
    if (jceq < 1) continue;

    int jp = mpmceq[jceq-1];
    Real c0 = ttcc[jp-1];

    // Add contributions to SV (right-hand-side)
    if (!SV.empty())
      for (i = 1; i <= nedof; i++)
      {
        int ieq = meen[i-1];
        int iceq = -ieq;
        if (ieq > 0)
          SV(ieq) -= c0*eM(i,j);
        else if (iceq > 0)
          for (ip = mpmceq[iceq-1]; ip < mpmceq[iceq]-1; ip++)
            if (mmceq[ip] > 0)
            {
              ieq = meqn[mmceq[ip]-1];
              SV(ieq) -= c0*ttcc[ip]*eM(i,j);
            }
      }

    // Add contributions to SM
    for (jp = mpmceq[jceq-1]; jp < mpmceq[jceq]-1; jp++)
      if (mmceq[jp] > 0)
      {
        int jeq = meqn[mmceq[jp]-1];
        for (i = 1; i <= nedof; i++)
        {
          int ieq = meen[i-1];
          int iceq = -ieq;
          if (ieq > 0)
          {
            SM(ieq,jeq) += ttcc[jp]*eM(i,j);
            SM(jeq,ieq) += ttcc[jp]*eM(j,i);
          }
          else if (iceq > 0)
            for (ip = mpmceq[iceq-1]; ip < mpmceq[iceq]-1; ip++)
              if (mmceq[ip] > 0)
              {
                ieq = meqn[mmceq[ip]-1];
                SM(ieq,jeq) += ttcc[ip]*ttcc[jp]*eM(i,j);
              }
        }
      }
  }
}
Esempio n. 25
0
bool findNum(IntVec const& vec, int target) {
  RotatedIndex rotation(vec);
  cout << "Rotation shift: " << rotation.shift << endl;

  return binarySearch(vec, 0, vec.size()-1, target, rotation);
}
Esempio n. 26
0
bool SIMoutput::dumpResults (const Vector& psol, double time,
                             utl::LogStream& os, const ResPointVec& gPoints,
                             bool formatted, std::streamsize precision) const
{
  if (gPoints.empty())
    return true;

  size_t i, j, k;
  Matrix sol1, sol2;
  Vector reactionFS;
  const Vector* reactionForces = myEqSys->getReactions();

  for (i = 0; i < myModel.size(); i++)
  {
    if (myModel[i]->empty()) continue; // skip empty patches

    ResPointVec::const_iterator p;
    std::array<RealArray,3> params;
    IntVec points;

    // Find all evaluation points within this patch, if any
    for (j = 0, p = gPoints.begin(); p != gPoints.end(); j++, p++)
      if (this->getLocalPatchIndex(p->patch) == (int)(i+1))
        if (opt.discretization >= ASM::Spline)
        {
          points.push_back(p->inod > 0 ? p->inod : -(j+1));
          for (k = 0; k < myModel[i]->getNoParamDim(); k++)
            params[k].push_back(p->u[k]);
        }
        else if (p->inod > 0)
          points.push_back(p->inod);

    if (points.empty()) continue; // no points in this patch

    myModel[i]->extractNodeVec(psol,myProblem->getSolution());
    if (opt.discretization >= ASM::Spline)
    {
      // Evaluate the primary solution variables
      if (!myModel[i]->evalSolution(sol1,myProblem->getSolution(),
                                    params.data(),false))
        return false;

      // Evaluate the secondary solution variables
      LocalSystem::patch = i;
      if (myProblem->getNoFields(2) > 0)
      {
        const_cast<SIMoutput*>(this)->setPatchMaterial(i+1);
        if (!myModel[i]->evalSolution(sol2,*myProblem,params.data(),false))
          return false;
      }
    }
    else
      // Extract nodal primary solution variables
      if (!myModel[i]->getSolution(sol1,myProblem->getSolution(),points))
        return false;

    // Formatted output, use scientific notation with fixed field width
    std::streamsize flWidth = 8 + precision;
    std::streamsize oldPrec = os.precision(precision);
    std::ios::fmtflags oldF = os.flags(std::ios::scientific | std::ios::right);
    for (j = 0; j < points.size(); j++)
    {
      if (!formatted)
        os << time <<" ";
      else if (points[j] < 0)
        os <<"  Point #"<< -points[j] <<":\tsol1 =";
      else
      {
        points[j] = myModel[i]->getNodeID(points[j]);
        os <<"  Node #"<< points[j] <<":\tsol1 =";
      }

      for (k = 1; k <= sol1.rows(); k++)
        os << std::setw(flWidth) << utl::trunc(sol1(k,j+1));

      if (opt.discretization >= ASM::Spline)
      {
        if (formatted && sol2.rows() > 0)
          os <<"\n\t\tsol2 =";
        for (k = 1; k <= sol2.rows(); k++)
          os << std::setw(flWidth) << utl::trunc(sol2(k,j+1));
      }

      if (reactionForces && points[j] > 0)
        // Print nodal reaction forces for nodes with prescribed DOFs
        if (mySam->getNodalReactions(points[j],*reactionForces,reactionFS))
        {
          if (formatted)
            os <<"\n\t\treac =";
          for (k = 0; k < reactionFS.size(); k++)
            os << std::setw(flWidth) << utl::trunc(reactionFS[k]);
        }

      os << std::endl;
    }
    os.precision(oldPrec);
    os.flags(oldF);
  }

  return true;
}
Esempio n. 27
0
// makes a new paving from a vtk file
// expects 3d, structured point data in file
SPMinimalnode* SPMinimalnode::vtkPaving(const std::string filename)
{
	SPMinimalnode* newTree = NULL;
	
	try {

		size_t expectedDims = 3;

		IntVec Xs;
		IntVec Ys;
		IntVec Zs;

		// get the spacing and fill in the coordinates vectors using
		// getCoordinatesFromVtk.
		// getCoordinatesFromVtk expects 10 header lines with spacings on 4th
		IntVec spacing = getCoordinatesFromVtk(Xs, Ys, Zs, filename);
		bool success = ((spacing.size() == expectedDims) && (spacing[0] > 0)
								&& (spacing[0] == spacing[1])
								&& (spacing[0] == spacing[2]));

		if (success) {

			ivector rootbox(expectedDims);

			double maxXYZ = spacing[0] * 1.0;

			ImageList boxes;

			double totalListVol = 0;

			IntVecItr xIt = Xs.begin();
			IntVecItr yIt = Ys.begin();
			IntVecItr zIt = Zs.begin();

			for (xIt = Xs.begin(); xIt < Xs.end(); xIt++, yIt++, zIt++) {
				ivector box(expectedDims);
				// make the box so that its boundaries are on the inner edges
				// of the voxel
				interval xdim(Sup(_interval(*xIt/maxXYZ)),
							Inf(_interval(*xIt + 1.0)/maxXYZ));
				interval ydim(Sup(_interval(*yIt/maxXYZ)),
							Inf(_interval(*yIt + 1.0)/maxXYZ));
				interval zdim(Sup(_interval(*zIt/maxXYZ)),
							Inf(_interval(*zIt + 1.0)/maxXYZ));
				box[1] = xdim;
				box[2] = ydim;
				box[3] = zdim;
				boxes.push_back(box);
				totalListVol += Volume(box);

			}

			rootbox[1] = interval(0.0, 1.0);
			rootbox[2] = interval(0.0, 1.0);
			rootbox[3] = interval(0.0, 1.0);


			newTree = makeTreeFromVoxels(rootbox, boxes,
										maxXYZ, expectedDims);
		}

		if (newTree != NULL) {
			newTree->setNodeName("X");
			newTree->recursiveRename();
		}
	
		return newTree;
	}
	catch(std::exception const& e) {
		delete newTree;
		newTree = NULL;
		throw;
	}
	
}
Esempio n. 28
0
////////////////////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
void GenerateStrips(const U16* in_indices, const U32 in_numIndices,
					PrimitiveGroup** primGroups, U16* numGroups)
{
	//put data in format that the stripifier likes
	WordVec tempIndices;
	tempIndices.resize(in_numIndices);
	U16 maxIndex = 0;
   U32 i;
	for(i = 0; i < in_numIndices; i++)
	{
		tempIndices[i] = in_indices[i];
		if(in_indices[i] > maxIndex)
			maxIndex = in_indices[i];
	}
	NvStripInfoVec tempStrips;
	NvFaceInfoVec tempFaces;

	NvStripifier stripifier;
	
	//do actual stripification
	stripifier.Stripify(tempIndices, cacheSize, minStripSize, maxIndex, tempStrips, tempFaces);

	//stitch strips together
	IntVec stripIndices;
	U32 numSeparateStrips = 0;

	if(bListsOnly)
	{
		//if we're outputting only lists, we're done
		*numGroups = 1;
		(*primGroups) = new PrimitiveGroup[*numGroups];
		PrimitiveGroup* primGroupArray = *primGroups;

		//count the total number of indices
		U32 numIndices = 0;
      U32 i;
		for(i = 0; i < tempStrips.size(); i++)
		{
			numIndices += tempStrips[i]->m_faces.size() * 3;
		}

		//add in the list
		numIndices += tempFaces.size() * 3;

		primGroupArray[0].type       = PT_LIST;
		primGroupArray[0].numIndices = numIndices;
		primGroupArray[0].indices    = new U16[numIndices];

		//do strips
		U32 indexCtr = 0;
		for(U32 k = 0; k < tempStrips.size(); k++)
		{
			for(U32 j = 0; j < tempStrips[i]->m_faces.size(); j++)
			{
				//degenerates are of no use with lists
				if(!NvStripifier::IsDegenerate(tempStrips[i]->m_faces[j]))
				{
					primGroupArray[0].indices[indexCtr++] = tempStrips[k]->m_faces[j]->m_v0;
					primGroupArray[0].indices[indexCtr++] = tempStrips[k]->m_faces[j]->m_v1;
					primGroupArray[0].indices[indexCtr++] = tempStrips[k]->m_faces[j]->m_v2;
				}
				else
				{
					//we've removed a tri, reduce the number of indices
					primGroupArray[0].numIndices -= 3;
				}
			}
		}

		//do lists
		for(i = 0; i < tempFaces.size(); i++)
		{
			primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v0;
			primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v1;
			primGroupArray[0].indices[indexCtr++] = tempFaces[i]->m_v2;
		}
	}
	else
	{
		stripifier.CreateStrips(tempStrips, stripIndices, bStitchStrips, numSeparateStrips);

		//if we're stitching strips together, we better get back only one strip from CreateStrips()
		assert( (bStitchStrips && (numSeparateStrips == 1)) || !bStitchStrips);
		
		//convert to output format
		*numGroups = numSeparateStrips; //for the strips
		if(tempFaces.size() != 0)
			(*numGroups)++;  //we've got a list as well, increment
		(*primGroups) = new PrimitiveGroup[*numGroups];
		
		PrimitiveGroup* primGroupArray = *primGroups;
		
		//first, the strips
		S32 startingLoc = 0;
		for(U32 stripCtr = 0; stripCtr < numSeparateStrips; stripCtr++)
		{
			S32 stripLength = 0;

			if(!bStitchStrips)
			{
				//if we've got multiple strips, we need to figure out the correct length
            U32 i;
				for(i = startingLoc; i < stripIndices.size(); i++)
				{
					if(stripIndices[i] == -1)
						break;
				}
				
				stripLength = i - startingLoc;
			}
			else
				stripLength = stripIndices.size();
			
			primGroupArray[stripCtr].type       = PT_STRIP;
			primGroupArray[stripCtr].indices    = new U16[stripLength];
			primGroupArray[stripCtr].numIndices = stripLength;
			
			S32 indexCtr = 0;
			for(S32 i = startingLoc; i < stripLength + startingLoc; i++)
				primGroupArray[stripCtr].indices[indexCtr++] = stripIndices[i];

			//we add 1 to account for the -1 separating strips
			//this doesn't break the stitched case since we'll exit the loop
			startingLoc += stripLength + 1; 
		}
		
		//next, the list
		if(tempFaces.size() != 0)
		{
			S32 faceGroupLoc = (*numGroups) - 1;    //the face group is the last one
			primGroupArray[faceGroupLoc].type       = PT_LIST;
			primGroupArray[faceGroupLoc].indices    = new U16[tempFaces.size() * 3];
			primGroupArray[faceGroupLoc].numIndices = tempFaces.size() * 3;
			S32 indexCtr = 0;
			for(U32 i = 0; i < tempFaces.size(); i++)
			{
				primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v0;
				primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v1;
				primGroupArray[faceGroupLoc].indices[indexCtr++] = tempFaces[i]->m_v2;
			}
		}
	}

	//clean up everything

	//delete strips
	for(i = 0; i < tempStrips.size(); i++)
	{
		for(U32 j = 0; j < tempStrips[i]->m_faces.size(); j++)
		{
			delete tempStrips[i]->m_faces[j];
			tempStrips[i]->m_faces[j] = NULL;
		}
		delete tempStrips[i];
		tempStrips[i] = NULL;
	}

	//delete faces
	for(i = 0; i < tempFaces.size(); i++)
	{
		delete tempFaces[i];
		tempFaces[i] = NULL;
	}
}
Esempio n. 29
0
py::list toPyList(const IntVec& x) {
  py::list out;
  for (int i=0; i < x.size(); ++i) out.append(x[i]);
  return out;
}