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);
}
Esempio n. 2
0
	double maxExpectation(int M, vector <int> day, vector <int> win, vector <int> gain) {
		Max = M;
		IIVec Days;
		int i;
		for (i = 0; i < (int)day.size(); ++i) {
			if (win[i] > 0 && gain[i] > 0) {
				Days.push_back(II(day[i], i));
			}
		}
		sort(Days.begin(), Days.end());

		_day.clear();
		_win.clear();
		_gain.clear();
		memset(memo, 0, sizeof(memo));
		for (i = 0; i < (int)Days.size(); ++i) {
			_day.push_back(Days[i].first);
			_win.push_back(win[Days[i].second] * 0.01);
			_gain.push_back(gain[Days[i].second]);
		}

		if (Days.size() <= 0 || M <= _day[0]) {
			return M;
		}
		return rec(0, M - _day[0]);
	}
IntVec PrimeSwing::GetMultiplies( int _number, PrimeSieve& _sieve )
{
    IntVec multiplies;
    int sqrtN = static_cast<int>( sqrt( static_cast<double>(_number) ) );

    int maxIdx = _sieve.GetPrimeIndex( sqrtN, 2, _sieve.GetNumberOfPrimes() );
    for ( int i = 1; i < maxIdx; ++i )
    {
        int prime = _sieve.GetPrime(i);

        int q = _number, p = 1;

        while ((q /= prime) > 0)
            if ((q & 1) == 1)
                p *= prime;

        if (p > 1)
            multiplies.push_back(p);
    }

    int minIdx = maxIdx;
    maxIdx = _sieve.GetPrimeIndex( _number / 3, minIdx, _sieve.GetNumberOfPrimes() );

    for (int i = minIdx; i < maxIdx; ++i)
    {
        int prime = _sieve.GetPrime(i);

        if (((_number / prime) & 1) == 1)
            multiplies.push_back(prime);
    }

    return multiplies;
}
Esempio n. 4
0
File: ASMs1D.C Progetto: OPM/IFEM
void ASMs1D::getBoundaryNodes (int lIndex, IntVec& glbNodes, int) const
{
  if (!curv) return; // silently ignore empty patches

  size_t iel = lIndex == 1 ? 0 : nel-1;
  if (MLGE[iel] > 0)
  {
    if (lIndex == 1)
      glbNodes.push_back(MLGN[MNPC[iel].front()]);
    else if (lIndex == 2)
      glbNodes.push_back(MLGN[MNPC[iel][curv->order()-1]]);
  }
}
Esempio n. 5
0
bool SIMoutput::writeGlvV (const Vector& vec, const char* fieldName,
                           int iStep, int& nBlock, int idBlock) const
{
  if (vec.empty())
    return true;
  else if (!myVtf)
    return false;

  Matrix field;
  Vector lovec;
  IntVec vID;

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

    if (msgLevel > 1)
      IFEM::cout <<"Writing vector field for patch "<< i+1 << std::endl;

    myModel[i]->extractNodeVec(vec,lovec);
    if (!myModel[i]->evalSolution(field,lovec,opt.nViz))
      return false;

    if (!myVtf->writeVres(field,++nBlock,++geomID,this->getNoSpaceDim()))
      return false;
    else
      vID.push_back(nBlock);
  }

  return myVtf->writeVblk(vID,fieldName,idBlock,iStep);
}
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
bool SIMoutput::writeGlvE (const Vector& vec, int iStep, int& nBlock,
                           const char* name)
{
  if (!myVtf)
    return false;

  Matrix infield(1,vec.size());
  infield.fillRow(1,vec.ptr());
  Matrix field;

  int geomID = myGeomID;
  IntVec sID;
  for (size_t i = 0; i < myModel.size(); i++)
  {
    if (myModel[i]->empty()) continue; // skip empty patches

    if (msgLevel > 1)
      IFEM::cout <<"Writing element field "<< name
                 <<" for patch "<< i+1 << std::endl;

    myModel[i]->extractElmRes(infield,field);

    if (!myVtf->writeEres(field.getRow(1),++nBlock,++geomID))
      return false;

    sID.push_back(nBlock);
  }

  int idBlock = 300;
  if (!myVtf->writeSblk(sID,name,++idBlock,iStep,true))
    return false;

  return true;
}
Esempio n. 8
0
File: ASMs3DLag.C Progetto: OPM/IFEM
void ASMs3DLag::generateThreadGroups (char lIndex, bool)
{
  if (threadGroupsFace.find(lIndex) != threadGroupsFace.end()) return;

  const int p1 = svol->order(0);
  const int p2 = svol->order(1);
  const int p3 = svol->order(2);
  const int n1 = (nx-1)/(p1-1);
  const int n2 = (ny-1)/(p2-1);
  const int n3 = (nz-1)/(p3-1);

  // Find elements that are on the boundary face 'lIndex'
  IntVec map; map.reserve(this->getNoBoundaryElms(lIndex,2));
  int d1, d2, iel = 0;
  for (int i3 = 1; i3 <= n3; i3++)
    for (int i2 = 1; i2 <= n2; i2++)
      for (int i1 = 1; i1 <= n1; i1++, iel++)
	switch (lIndex)
          {
	  case 1: if (i1 ==  1) map.push_back(iel); break;
	  case 2: if (i1 == n1) map.push_back(iel); break;
	  case 3: if (i2 ==  1) map.push_back(iel); break;
	  case 4: if (i2 == n2) map.push_back(iel); break;
	  case 5: if (i3 ==  1) map.push_back(iel); break;
	  case 6: if (i3 == n3) map.push_back(iel); break;
          }

  switch (lIndex)
    {
    case 1:
    case 2:
      d1 = n2;
      d2 = n3;
      break;
    case 3:
    case 4:
      d1 = n1;
      d2 = n3;
      break;
    default:
      d1 = n1;
      d2 = n2;
    }

  threadGroupsFace[lIndex].calcGroups(d1,d2,1);
  threadGroupsFace[lIndex].applyMap(map);
}
Esempio n. 9
0
	void add_train( string item, int label, MatVec & images, IntVec & labels )
	{
		Mat img = load(item);
		if ( img.empty() ) return ;

		images.push_back(img);
        labels.push_back(label);
	}
Esempio n. 10
0
IntVec SpeckleyElements::prepareGhostIndices(int ownIndex)
{
    IntVec indexArray;
    numGhostElements = 0;
    for (int i=0; i<numElements; i++) {
        indexArray.push_back(i);
    }
    return indexArray;
}
Esempio n. 11
0
	void read_test(const string & fn, int label, IntVec & labels, StrVec & items, int maxiter)
	{
		ifstream pos(fn.c_str());
		int i = 0;
		while ( ! pos.eof() )
		{
			string item;
			pos >> item;
			if ( item.empty() ) 	break;

			i++;
			if ( i % 2 == 0 )		
				continue;
			if ( i / 2 > maxiter )		
				break;

			labels.push_back(label);
			items.push_back(item);
		}
	}
Esempio n. 12
0
bool SIMoutput::writeGlvM (const Mode& mode, bool freq, int& nBlock)
{
  if (mode.eigVec.empty())
    return true;
  else if (!myVtf)
    return false;

  if (msgLevel > 1)
    IFEM::cout <<"Writing eigenvector for Mode "<< mode.eigNo << std::endl;

  Vector displ;
  Matrix field;
  IntVec vID;

  int geomID = myGeomID;
  for (size_t i = 0; i < myModel.size(); i++)
  {
    if (myModel[i]->empty()) continue; // skip empty patches
    if (myModel.size() > 1 && msgLevel > 1)
      IFEM::cout <<"."<< std::flush;

    geomID++;
    myModel[i]->extractNodeVec(mode.eigVec,displ);
    if (!myModel[i]->evalSolution(field,displ,opt.nViz))
      return false;

    if (!myVtf->writeVres(field,++nBlock,geomID))
      return false;
    else
      vID.push_back(nBlock);
  }
  if (myModel.size() > 1 && msgLevel > 1)
    IFEM::cout << std::endl;

  int idBlock = 10;
  if (!myVtf->writeDblk(vID,"Mode Shape",idBlock,mode.eigNo))
    return false;

  return myVtf->writeState(mode.eigNo, freq ? "Frequency %g" : "Eigenvalue %g",
                           mode.eigVal, 1);
}
Esempio n. 13
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. 14
0
bool SIMoutput::writeGlvF (const RealFunc& f, const char* fname,
                           int iStep, int& nBlock, int idBlock, double time)
{
  if (!myVtf) return false;

  IntVec sID;

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

    if (msgLevel > 1)
      IFEM::cout <<"Writing function "<< fname
                 <<" for patch "<< i+1 << std::endl;

    if (!myVtf->writeNfunc(f,time,++nBlock,++geomID))
      return false;
    else
      sID.push_back(nBlock);
  }

  return myVtf->writeSblk(sID,fname,idBlock,iStep);
}
Esempio n. 15
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. 16
0
void test_intersect()
{
	DoubleVec dv;
	IntVec iv;

	const struct {
		unsigned int pos;
		double val;
	} dTbl[] = {
		{ 5, 3.14 }, { 10, 2 }, { 12, 1.4 }, { 100, 2.3 }, { 1000, 4 },
	};

	const struct {
		unsigned int pos;
		int val;
	} iTbl[] = {
		{ 2, 4 }, { 5, 2 }, { 100, 4 }, { 101, 3}, { 999, 4 }, { 1000, 1 }, { 2000, 3 },
	};

	const struct {
		unsigned int pos;
		double d;
		int i;
	} interTbl[] = {
		 { 5, 3.14, 2 }, { 100, 2.3, 4 }, { 1000, 4, 1 }
	};

	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(dTbl); i++) {
		dv.push_back(dTbl[i].pos, dTbl[i].val);
	}
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(iTbl); i++) {
		iv.push_back(iTbl[i].pos, iTbl[i].val);
	}

	int j = 0;
	for (typename DoubleVec::const_iterator i = dv.begin(), ie = dv.end(); i != ie; ++i) {
		CYBOZU_TEST_EQUAL(i->pos(), dTbl[j].pos);
		CYBOZU_TEST_EQUAL(i->val(), dTbl[j].val);
		j++;
	}

	j = 0;
	for (typename IntVec::const_iterator i = iv.begin(), ie = iv.end(); i != ie; ++i) {
		CYBOZU_TEST_EQUAL(i->pos(), iTbl[j].pos);
		CYBOZU_TEST_EQUAL(i->val(), iTbl[j].val);
		j++;
	}

	int sum = 0;
	for (typename IntVec::const_iterator i = iv.begin(), ie = iv.end(); i != ie; ++i) {
		sum += i->val() * i->val();
	}
	CYBOZU_TEST_EQUAL(sum, 71);

	typedef cybozu::nlp::Intersection<DoubleVec, IntVec> InterSection;
	InterSection inter(dv, iv);

	j = 0;
	for (typename InterSection::const_iterator i = inter.begin(), ie = inter.end(); i != ie; ++i) {
		CYBOZU_TEST_EQUAL(i->pos(), interTbl[j].pos);
		CYBOZU_TEST_EQUAL(i->val1(), interTbl[j].d);
		CYBOZU_TEST_EQUAL(i->val2(), interTbl[j].i);
		j++;
	}
}
Esempio n. 17
0
bool ASMu3Dmx::assembleL2matrices (SparseMatrix& A, StdVector& B,
                                   const IntegrandBase& integrand,
                                   bool continuous) const
{
  const int p1 = projBasis->order(0);
  const int p2 = projBasis->order(1);
  const int p3 = projBasis->order(2);

  // Get Gaussian quadrature points
  const int ng1 = continuous ? nGauss : p1 - 1;
  const int ng2 = continuous ? nGauss : p2 - 1;
  const int ng3 = continuous ? nGauss : p3 - 1;
  const double* xg = GaussQuadrature::getCoord(ng1);
  const double* yg = GaussQuadrature::getCoord(ng2);
  const double* zg = GaussQuadrature::getCoord(ng3);
  const double* wg = continuous ? GaussQuadrature::getWeight(nGauss) : nullptr;
  if (!xg || !yg || !zg) return false;
  if (continuous && !wg) return false;

  size_t nnod = this->getNoProjectionNodes();
  double dV = 0.0;
  Vectors phi(2);
  Matrices dNdu(2);
  Matrix sField, Xnod, Jac;
  std::vector<Go::BasisDerivs> spl1(2);
  std::vector<Go::BasisPts> spl0(2);


  // === Assembly loop over all elements in the patch ==========================
  LR::LRSplineVolume* geoVol;
  if (m_basis[geoBasis-1]->nBasisFunctions() == projBasis->nBasisFunctions())
    geoVol = m_basis[geoBasis-1].get();
  else
    geoVol = projBasis.get();

  for (const LR::Element* el1 : geoVol->getAllElements())
  {
    double uh = (el1->umin()+el1->umax())/2.0;
    double vh = (el1->vmin()+el1->vmax())/2.0;
    double wh = (el1->wmin()+el1->wmax())/2.0;
    std::vector<size_t> els;
    els.push_back(projBasis->getElementContaining(uh, vh, wh) + 1);
    els.push_back(m_basis[geoBasis-1]->getElementContaining(uh, vh, wh) + 1);

    if (continuous)
    {
      // Set up control point (nodal) coordinates for current element
      if (!this->getElementCoordinates(Xnod,els[1]))
        return false;
      else if ((dV = 0.25*this->getParametricVolume(els[1])) < 0.0)
        return false; // topology error (probably logic error)
    }

    // Compute parameter values of the Gauss points over this element
    RealArray gpar[3], unstrGpar[3];
    this->getGaussPointParameters(gpar[0],0,ng1,els[1],xg);
    this->getGaussPointParameters(gpar[1],1,ng2,els[1],yg);
    this->getGaussPointParameters(gpar[2],2,ng3,els[1],zg);

    // convert to unstructred mesh representation
    expandTensorGrid(gpar, unstrGpar);

    // Evaluate the secondary solution at all integration points
    if (!this->evalSolution(sField,integrand,unstrGpar))
      return false;

    // set up basis function size (for extractBasis subroutine)
    const LR::Element* elm = projBasis->getElement(els[0]-1);
    phi[0].resize(elm->nBasisFunctions());
    phi[1].resize(el1->nBasisFunctions());
    IntVec lmnpc;
    if (projBasis != m_basis[0]) {
      lmnpc.reserve(phi[0].size());
      for (const LR::Basisfunction* f : elm->support())
        lmnpc.push_back(f->getId());
    }
    const IntVec& mnpc = projBasis == m_basis[0] ? MNPC[els[1]-1] : lmnpc;

    // --- Integration loop over all Gauss points in each direction ----------
    Matrix eA(phi[0].size(), phi[0].size());
    Vectors eB(sField.rows(), Vector(phi[0].size()));
    int ip = 0;
    for (int k = 0; k < ng3; k++)
      for (int j = 0; j < ng2; j++)
        for (int i = 0; i < ng1; i++, ip++)
        {
          if (continuous)
          {
            projBasis->computeBasis(gpar[0][i], gpar[1][j], gpar[2][k],
                                    spl1[0], els[0]-1);
            SplineUtils::extractBasis(spl1[0],phi[0],dNdu[0]);
            m_basis[geoBasis-1]->computeBasis(gpar[0][i], gpar[1][j], gpar[2][k],
                                              spl1[1], els[1]-1);
            SplineUtils::extractBasis(spl1[1], phi[1], dNdu[1]);
          }
          else
          {
            projBasis->computeBasis(gpar[0][i], gpar[1][j], gpar[2][k],
                                    spl0[0], els[0]-1);
            phi[0] = spl0[0].basisValues;
          }

          // Compute the Jacobian inverse and derivatives
          double dJw = 1.0;
          if (continuous)
          {
            dJw = dV*wg[i]*wg[j]*wg[k]*utl::Jacobian(Jac,dNdu[1],Xnod,dNdu[1],false);
            if (dJw == 0.0) continue; // skip singular points
          }

          // Integrate the mass matrix
          eA.outer_product(phi[0], phi[0], true, dJw);

          // Integrate the rhs vector B
          for (size_t r = 1; r <= sField.rows(); r++)
            eB[r-1].add(phi[0],sField(r,ip+1)*dJw);
        }

    for (size_t i = 0; i < eA.rows(); ++i) {
      for (size_t j = 0; j < eA.cols(); ++j)
        A(mnpc[i]+1, mnpc[j]+1) += eA(i+1,j+1);

      int jp = mnpc[i]+1;
      for (size_t r = 0; r < sField.rows(); r++, jp += nnod)
        B(jp) += eB[r](1+i);
    }
  }

  return true;
}
Esempio n. 18
0
bool ASMs3Dmx::assembleL2matrices (SparseMatrix& A, StdVector& B,
                                   const IntegrandBase& integrand,
                                   bool continuous) const
{
  const size_t nnod = projBasis->numCoefs(0) *
                      projBasis->numCoefs(1) *
                      projBasis->numCoefs(2);

  const int p1 = svol->order(0);
  const int p2 = svol->order(1);
  const int p3 = svol->order(2);
  const int p11 = projBasis->order(0);
  const int p21 = projBasis->order(1);
  const int p31 = projBasis->order(2);
  const int n1 = svol->numCoefs(0);
  const int n2 = svol->numCoefs(1);
  const int n3 = svol->numCoefs(2);
  const int nel1 = n1 - p1 + 1;
  const int nel2 = n2 - p2 + 1;
  const int nel3 = n3 - p3 + 1;

  // Get Gaussian quadrature point coordinates (and weights if continuous)
  const int ng1 = continuous ? nGauss : p1 - 1;
  const int ng2 = continuous ? nGauss : p2 - 1;
  const int ng3 = continuous ? nGauss : p3 - 1;
  const double* xg = GaussQuadrature::getCoord(ng1);
  const double* yg = GaussQuadrature::getCoord(ng2);
  const double* zg = GaussQuadrature::getCoord(ng3);
  const double* wg = continuous ? GaussQuadrature::getWeight(nGauss) : 0;
  if (!xg || !yg || !zg) return false;
  if (continuous && !wg) return false;

  // Compute parameter values of the Gauss points over the whole patch
  Matrix gp;
  std::array<RealArray,3> gpar;
  gpar[0] = this->getGaussPointParameters(gp,0,ng1,xg);
  gpar[1] = this->getGaussPointParameters(gp,1,ng2,yg);
  gpar[2] = this->getGaussPointParameters(gp,2,ng3,zg);

  // Evaluate basis functions at all integration points
  std::vector<Go::BasisPts>    spl0;
  std::array<std::vector<Go::BasisDerivs>,2> spl1;
  if (continuous) {
    projBasis->computeBasisGrid(gpar[0],gpar[1],gpar[2],spl1[0]);
    svol->computeBasisGrid(gpar[0],gpar[1],gpar[2],spl1[1]);
  } else
    projBasis->computeBasisGrid(gpar[0],gpar[1],gpar[2],spl0);

  // Evaluate the secondary solution at all integration points
  Matrix sField;
  if (!this->evalSolution(sField,integrand,gpar.data()))
  {
    std::cerr <<" *** ASMs3D::assembleL2matrices: Failed for patch "<< idx+1
      <<" nPoints="<< gpar[0].size()*gpar[1].size()*gpar[2].size()
      << std::endl;
    return false;
  }

  double dV = 1.0;
  std::array<Vector,2> phi;
  phi[0].resize(p11*p21*p31);
  phi[1].resize(p1*p2*p3);
  std::array<Matrix,2> dNdu;
  Matrix Xnod, J;


  // === Assembly loop over all elements in the patch ==========================

  int iel = 0;
  for (int i3 = 0; i3 < nel3; i3++)
    for (int i2 = 0; i2 < nel2; i2++)
      for (int i1 = 0; i1 < nel1; i1++, iel++)
      {
        if (MLGE[iel] < 1) continue; // zero-volume element

        if (continuous)
        {
          // Set up control point (nodal) coordinates for current element
          if (!this->getElementCoordinates(Xnod,1+iel))
            return false;
          else if ((dV = 0.125*this->getParametricVolume(1+iel)) < 0.0)
            return false; // topology error (probably logic error)
        }

        int ip = ((i3*ng2*nel2 + i2)*ng1*nel1 + i1)*ng3;
        IntVec lmnpc;
        if (projBasis != m_basis[0]) {
          lmnpc.reserve(phi[0].size());
          int nuv = projBasis->numCoefs(0)*projBasis->numCoefs(1);
          int widx = (spl1[0][ip].left_idx[2]-p31+1)*nuv;
          for (int k = 0; k < p31; ++k, widx += nuv) {
            int vidx = (spl1[0][ip].left_idx[1]-p21+1)*projBasis->numCoefs(0);
            for (int j = 0; j < p21; ++j, vidx += projBasis->numCoefs(0))
              for (int i = 0; i < p11; ++i)
                if (continuous)
                  lmnpc.push_back(spl1[0][ip].left_idx[0]-p11+1+i+vidx+widx);
                else
                  lmnpc.push_back(spl0[ip].left_idx[0]-p11+1+i+vidx+widx);
          }
        }
        const IntVec& mnpc = projBasis == m_basis[0] ? MNPC[iel] : lmnpc;

        // --- Integration loop over all Gauss points in each direction --------

        Matrix eA(p11*p21*p31, p11*p21*p31);
        Vectors eB(sField.rows(), Vector(p11*p21*p31));
        for (int k = 0; k < ng3; k++, ip += ng2*(nel2-1)*ng1*nel1)
          for (int j = 0; j < ng2; j++, ip += ng1*(nel1-1))
            for (int i = 0; i < ng1; i++, ip++)
            {
              if (continuous) {
                SplineUtils::extractBasis(spl1[0][ip],phi[0],dNdu[0]);
                SplineUtils::extractBasis(spl1[1][ip],phi[1],dNdu[1]);
              } else
                phi[0] = spl0[ip].basisValues;

              // Compute the Jacobian inverse and derivatives
              double dJw = dV;
              if (continuous)
              {
                dJw *= wg[i]*wg[j]*wg[k]*utl::Jacobian(J,dNdu[1],Xnod,dNdu[1],false);
                if (dJw == 0.0) continue; // skip singular points
              }

              // Integrate the mass matrix
              eA.outer_product(phi[0], phi[0], true, dJw);

              // Integrate the rhs vector B
              for (size_t r = 1; r <= sField.rows(); r++)
                eB[r-1].add(phi[0],sField(r,ip+1)*dJw);
            }

        for (int i = 0; i < p11*p21*p31; ++i) {
          for (int j = 0; j < p11*p21*p31; ++j)
            A(mnpc[i]+1, mnpc[j]+1) += eA(i+1, j+1);

          int jp = mnpc[i]+1;
          for (size_t r = 0; r < sField.rows(); r++, jp += nnod)
            B(jp) += eB[r](1+i);
        }
      }

  return true;
}
void* RegisterInitControl::createIntVec(unsigned long long val)
{
    IntVec* vec = new IntVec;
    vec->push_back(val);
    return vec;
}
Esempio n. 20
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;
}
////////////////////////////////////////////////////////////////////////////////////////
// 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. 22
0
void ConvexDecomp(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr& cloud, const Eigen::MatrixXf& dirs, float thresh,
                  /*optional outputs: */ std::vector<IntVec>* indices, std::vector< IntVec >* hull_indices)
{

  int k_neighbs = 5;
  pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr tree(new pcl::KdTreeFLANN<pcl::PointXYZ>(true));
  tree->setEpsilon(0);
  tree->setInputCloud(cloud);
  int n_pts = cloud->size();
  int n_dirs = dirs.rows();
  
  
  
  
  DEBUG_PRINT("npts, ndirs %i %i\n", n_pts, n_dirs);
  
  MatrixXf dirs4(n_dirs, 4);
  dirs4.leftCols(3) = dirs;
  dirs4.col(3).setZero();
  MatrixXf pt2supports = Map< const Matrix<float, Dynamic, Dynamic, RowMajor > >(reinterpret_cast<const float*>(cloud->points.data()), n_pts, 4) * dirs4.transpose();
  
  
  const int UNLABELED = -1;
  IntVec pt2label(n_pts, UNLABELED);
  
  IntSet alldirs;
  for(int i = 0; i < n_dirs; ++i) alldirs.insert(i);
  
  int i_seed = 0;
  int i_label = 0;
  
  // each loop cycle, add a new cluster
  while(true)
  {
  
  
  
  
    // find first unlabeled point
    while(true)
    {
      if(i_seed == n_pts) return;
      if(pt2label[i_seed] == UNLABELED) break;
      ++i_seed;
    }
    
    pt2label[i_seed] = i_label;
    map<int, IntSet> pt2dirs;
    pt2dirs[i_seed] = alldirs;
    vector<SupInfo> dir2supinfo(n_dirs);
    for(int i_dir = 0; i_dir < n_dirs; ++i_dir)
    {
      float seedsup = pt2supports(i_seed, i_dir);
      dir2supinfo[i_dir].inds.push_back(i_seed);
      dir2supinfo[i_dir].sups.push_back(seedsup);
      dir2supinfo[i_dir].best = seedsup;
      
    }
    
    
    DEBUG_PRINT("seed: %i\n", i_seed);
    
    IntSet exclude_frontier;
    exclude_frontier.insert(i_seed);
    queue<int> frontier;
    
    BOOST_FOREACH(const int & i_nb,  getNeighbors(*tree, i_seed, k_neighbs, 2 * thresh))
    {
      if(pt2label[i_nb] == UNLABELED && exclude_frontier.find(i_nb) == exclude_frontier.end())
      {
        DEBUG_PRINT("adding %i to frontier\n", i_nb);
        frontier.push(i_nb);
        exclude_frontier.insert(i_nb);
      }
    }
    
    
    
    
    
    while(!frontier.empty())
    {
    
#if 0 // for serious debugging
      vector<int> clu;
      BOOST_FOREACH(Int2IntSet::value_type & pt_dir, pt2dirs)
      {
        clu.push_back(pt_dir.first);
      }
      MatrixXd sup_pd(clu.size(), n_dirs);
      for(int i = 0; i < clu.size(); ++i)
      {
        for(int i_dir = 0; i_dir < n_dirs; ++i_dir)
        {
          sup_pd(i, i_dir) = pt2supports(clu[i], i_dir);
        }
      }
      for(int i_dir = 0; i_dir < n_dirs; ++i_dir)
      {
        IntSet nearext;
        for(int i = 0; i < clu.size(); ++i)
        {
          if(sup_pd.col(i_dir).maxCoeff() - sup_pd(i, i_dir) < thresh)
          {
            nearext.insert(clu[i]);
          }
        }
        assert(toSet(dir2supinfo[i_dir].inds) == nearext);
      }
      printf("ok!\n");
#endif
      
      
      
      
      int i_cur = frontier.front();
      frontier.pop();
//      printf("cur: %i\n", i_cur);
      DEBUG_PRINT("pt2dirs %s", Str(pt2dirs).c_str());
      
      bool reject = false;
      
      Int2Int pt2decrement;
      for(int i_dir = 0; i_dir < n_dirs; ++i_dir)
      {
        float cursup = pt2supports(i_cur, i_dir);
        SupInfo& si = dir2supinfo[i_dir];
        if(cursup > si.best)
        {
          for(int i = 0; i < si.inds.size(); ++i)
          {
            float sup = si.sups[i];
            int i_pt = si.inds[i];
            if(cursup - sup > thresh)
            {
              pt2decrement[i_pt] = pt2decrement[i_pt] + 1;
              DEBUG_PRINT("decrementing %i (dir %i)\n", i_pt, i_dir);
            }
          }
        }
      }
      
      DEBUG_PRINT("pt2dec: %s", Str(pt2decrement).c_str());
      
      BOOST_FOREACH(const Int2Int::value_type & pt_dec, pt2decrement)
      {
        if(pt_dec.second == pt2dirs[pt_dec.first].size())
        {
          reject = true;
          break;
        }
      }
      
      DEBUG_PRINT("reject? %i\n", reject);
      if(!reject)
      {
        pt2label[i_cur] = i_label;
        pt2dirs[i_cur] = IntSet();
        for(int i_dir = 0; i_dir < n_dirs; ++i_dir)
        {
          float cursup = pt2supports(i_cur, i_dir);
          if(cursup > dir2supinfo[i_dir].best - thresh) pt2dirs[i_cur].insert(i_dir);
        }
        
        
        for(int i_dir = 0; i_dir < n_dirs; ++i_dir)
        {
          float cursup = pt2supports(i_cur, i_dir);
          SupInfo& si = dir2supinfo[i_dir];
          if(cursup > si.best)
          {
          
            IntVec filtinds;
            FloatVec filtsups;
            for(int i = 0; i < si.inds.size(); ++i)
            {
              float sup = si.sups[i];
              int i_pt = si.inds[i];
              if(cursup - sup > thresh)
              {
                pt2dirs[i_pt].erase(i_dir);
              }
              else
              {
                filtinds.push_back(i_pt);
                filtsups.push_back(sup);
              }
            }
            si.inds = filtinds;
            si.sups = filtsups;
            si.inds.push_back(i_cur);
            si.sups.push_back(cursup);
            si.best = cursup;
          }
          else if(cursup > si.best - thresh)
          {
            si.inds.push_back(i_cur);
            si.sups.push_back(cursup);
          }
        }
        BOOST_FOREACH(const int & i_nb,  getNeighbors(*tree, i_cur, k_neighbs, 2 * thresh))
        {
          if(pt2label[i_nb] == UNLABELED && exclude_frontier.find(i_nb) == exclude_frontier.end())
          {
            DEBUG_PRINT("adding %i to frontier\n", i_nb);
            frontier.push(i_nb);
            exclude_frontier.insert(i_nb);
          }
        }
        
      } // if !reject
      else
      {
      }
      
    } // while frontier nonempty
    
    if(indices != NULL)