Exemplo n.º 1
0
int main ()


{
  
  const int cell_size = 2;
  
  //Initialize A-matrix
  ublas::matrix<double> A (cell_size, cell_size);  
  A (0, 0) = 1;
  A (1, 1) = 2;
  
  A (0, 1) = 0;
  A (1, 0) = 0;

  //Initialize b-vector
  ublas::vector<double> b (cell_size);  
  b (0) = 1;
  b (1) = 1;

  // Solve Ax=b (maybe)
  ublas::permutation_matrix<double> piv (cell_size);
  const bool singular = ublas::lu_factorize(A, piv);
  if (singular)
    std::cout << "singular!" << std::endl;
 
  ublas::lu_substitute (A, piv, b); // b now contains solution 

  std::cout << A << std::endl;
  std::cout << piv << std::endl;  
  std::cout << b << std::endl;
  return 0;
}
Exemplo n.º 2
0
    /// @brief Computes saturation from surface volume
    void computeSaturation(const BlackoilPropertiesInterface& props,
                           BlackoilState& state)
    {

        const int np = props.numPhases();
        const int nc = props.numCells();
        std::vector<double> allA(nc*np*np);
        std::vector<int> allcells(nc);
        for (int c = 0; c < nc; ++c) {
            allcells[c] = c;
        }

        //std::vector<double> res_vol(np);
        const std::vector<double>& z = state.surfacevol();

        props.matrix(nc, &state.pressure()[0], &z[0], &allcells[0], &allA[0], 0);

        // Linear solver.
        MAT_SIZE_T n = np;
        MAT_SIZE_T nrhs = 1;
        MAT_SIZE_T lda = np;
        std::vector<MAT_SIZE_T> piv(np);
        MAT_SIZE_T ldb = np;
        MAT_SIZE_T info = 0;


        //double res_vol;
        double tot_sat;
        const double epsilon = std::sqrt(std::numeric_limits<double>::epsilon());

        for (int c = 0; c < nc; ++c) {
            double* A = &allA[c*np*np];
            const double* z_loc = &z[c*np];
            double* s = &state.saturation()[c*np];

            for (int p = 0; p < np; ++p){
                s[p] = z_loc[p];
                }

            dgesv_(&n, &nrhs, &A[0], &lda, &piv[0], &s[0], &ldb, &info);

            tot_sat = 0;
            for (int p = 0; p < np; ++p){
                if (s[p] < epsilon) // saturation may be less then zero due to round of errors
                    s[p] = 0;

                tot_sat += s[p];
            }

            for (int p = 0; p < np; ++p){
                s[p]  = s[p]/tot_sat;
            }





        }

    }
Exemplo n.º 3
0
lslboost::numeric::ublas::vector<T> solve(
          const lslboost::numeric::ublas::matrix<T>& A_,
          const lslboost::numeric::ublas::vector<T>& b_)
{
   //BOOST_ASSERT(A_.size() == b_.size());

   lslboost::numeric::ublas::matrix<T> A(A_);
   lslboost::numeric::ublas::vector<T> b(b_);
   lslboost::numeric::ublas::permutation_matrix<> piv(b.size());
   lu_factorize(A, piv);
   lu_substitute(A, piv, b);
   //
   // iterate to reduce error:
   //
   lslboost::numeric::ublas::vector<T> delta(b.size());
   for(unsigned i = 0; i < 1; ++i)
   {
      noalias(delta) = prod(A_, b);
      delta -= b_;
      lu_substitute(A, piv, delta);
      b -= delta;

      T max_error = 0;

      for(unsigned i = 0; i < delta.size(); ++i)
      {
         T err = fabs(delta[i] / b[i]);
         if(err > max_error)
            max_error = err;
      }
      //std::cout << "Max change in LU error correction: " << max_error << std::endl;
   }

   return b;
}
Exemplo n.º 4
0
LUDecomposition::Matrix LUDecomposition::solve (const Matrix& B) const {
      BOOST_UBLAS_CHECK((int)B.size1() == m, bad_size("Matrix row dimensions must agree."));
      BOOST_UBLAS_CHECK(isNonsingular(), singular("Matrix is singular."));

      // Copy right hand side with pivoting
      int nx = B.size2();
      Matrix X(m,nx);
      for (int i = 0; i < m; i++) {
          row(X,i) = row(B, piv(i));
      }

      // Solve L*Y = B(piv,:)
      for (int k = 0; k < n; k++) {
         for (int i = k+1; i < n; i++) {
            for (int j = 0; j < nx; j++) {
               X(i,j) -= X(k,j)*LU(i,k);
            }
         }
      }
      // Solve U*X = Y;
      for (int k = n-1; k >= 0; k--) {
         for (int j = 0; j < nx; j++) {
            X(k,j) /= LU(k,k);
         }
         for (int i = 0; i < k; i++) {
            for (int j = 0; j < nx; j++) {
               X(i,j) -= X(k,j)*LU(i,k);
            }
         }
      }
      return X;
   }
Exemplo n.º 5
0
  void solve (Matrix& A, const Vector& b, Vector& x) const // Solve Ax=b
  {
    namespace ublas = boost::numeric::ublas;

    const size_t size = b.size ();
    ublas::permutation_matrix<double> piv (size);
    const bool singular = ublas::lu_factorize(A, piv);
    daisy_assert (!singular);
    x = b; 			// x should contain b as a start.
    ublas::lu_substitute (A, piv, x);
  }
Exemplo n.º 6
0
    //==========================================================================
    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- symmetric shape
    BOOST_FORCEINLINE
    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<2> const
              , nt2::symmetric_ const&) const
    {
      type_t rcond;
      nt2::container::table<nt2_la_int> piv(nt2::of_size(a0.leading_size(),1));
      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));
      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);
      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);
      nt2_la_int iter = nt2::sysvx( boost::proto::value(a),boost::proto::value(piv)
                                 , boost::proto::value(b)
                                 , boost::proto::value(boost::proto::child_c<0>(a2))
                                 , rcond);

      boost::ignore_unused(iter);
      boost::proto::child_c<1>(a2) = rcond;
    }
Exemplo n.º 7
0
    boost boost::solve_x(const boost& B) const {
        if(this->num_rows() != this->num_cols())
            throw std::invalid_argument("A must be square in Ax = B");
        if(this->num_cols() != B.num_rows())
            throw std::invalid_argument("B.rows must equal A.cols in Ax = B");
        if(B.num_cols() != 1)
            throw std::invalid_argument("B must be n x 1 vector in Ax = B");

        bnu::matrix<float> A(this->data());
        bnu::matrix<float> y = bnu::trans(B.data());

        bnu::vector<float> b(B.num_rows());
        std::copy(y.begin1(), y.end1(), b.begin());

        bnu::permutation_matrix<> piv(b.size());
        bnu::lu_factorize(A, piv);
        bnu::lu_substitute(A, piv, b);

        bnu::matrix<float> x(this->num_rows(), 1);
        std::copy(b.begin(), b.end(), x.begin1());
        return std::move(boost(x));
    }
ordinal_type
Stokhos::MonomialGramSchmidtPCEBasis<ordinal_type, value_type>::
buildReducedBasis(
  ordinal_type max_p, 
  value_type threshold, 
  const Teuchos::SerialDenseMatrix<ordinal_type,value_type>& A, 
  const Teuchos::SerialDenseMatrix<ordinal_type,value_type>& F,
  const Teuchos::Array<value_type>& weights, 
  Teuchos::Array< Stokhos::MultiIndex<ordinal_type> >& terms_,
  Teuchos::Array<ordinal_type>& num_terms_,
  Teuchos::SerialDenseMatrix<ordinal_type,value_type>& Qp_, 
  Teuchos::SerialDenseMatrix<ordinal_type,value_type>& Q_)
{
  // Compute basis terms -- 2-D array giving powers for each linear index
  ordinal_type max_sz;
  CPBUtils::compute_terms(max_p, this->d, max_sz, terms_, num_terms_);

  // Compute B matrix -- monomials in F
  // for i=0,...,nqp-1
  //   for j=0,...,sz-1
  //      B(i,j) = F(i,1)^terms_[j][1] * ... * F(i,d)^terms_[j][d]
  // where sz is the total size of a basis up to order p and terms_[j] 
  // is an array of powers for each term in the total-order basis
  ordinal_type nqp = weights.size();
  SDM B(nqp, max_sz);
  for (ordinal_type i=0; i<nqp; i++) {
    for (ordinal_type j=0; j<max_sz; j++) {
      B(i,j) = 1.0;
      for (ordinal_type k=0; k<this->d; k++)
	B(i,j) *= std::pow(F(i,k), terms_[j][k]);
    }
  }

  // Rescale columns of B to have unit norm
  for (ordinal_type j=0; j<max_sz; j++) {
    value_type nrm = 0.0;
    for (ordinal_type i=0; i<nqp; i++)
      nrm += B(i,j)*B(i,j)*weights[i];
    nrm = std::sqrt(nrm);
    for (ordinal_type i=0; i<nqp; i++)
      B(i,j) /= nrm;
  }

  // Compute our new basis -- each column of Q is the new basis evaluated
  // at the original quadrature points.  Constraint pivoting so first d+1
  // columns and included in Q.
  SDM R;
  Teuchos::Array<ordinal_type> piv(max_sz);
  for (int i=0; i<this->d+1; i++)
    piv[i] = 1;
  typedef Stokhos::OrthogonalizationFactory<ordinal_type,value_type> SOF;
   ordinal_type sz_ = SOF::createOrthogonalBasis(
    this->orthogonalization_method, threshold, this->verbose, B, weights, 
    Q_, R, piv);

  // Compute Qp = A^T*W*Q
  SDM tmp(nqp, sz_);
  Qp_.reshape(this->pce_sz, sz_);
  for (ordinal_type i=0; i<nqp; i++)
    for (ordinal_type j=0; j<sz_; j++)
      tmp(i,j) = Q_(i,j)*weights[i];
  ordinal_type ret = 
    Qp_.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0, A, tmp, 0.0);
  TEUCHOS_ASSERT(ret == 0);

  // It isn't clear that Qp is orthogonal, but if you derive the projection
  // matrix from the original space to the reduced, you end up with 
  // Q^T*W*A = Qp^T

  return sz_;
}
Stokhos::ProductLanczosGramSchmidtPCEBasis<ordinal_type, value_type>::
ProductLanczosGramSchmidtPCEBasis(
  ordinal_type max_p,
  const Teuchos::Array< Stokhos::OrthogPolyApprox<ordinal_type, value_type> >& pce,
  const Teuchos::RCP<const Stokhos::Quadrature<ordinal_type, value_type> >& quad,
  const Teuchos::RCP< const Stokhos::Sparse3Tensor<ordinal_type, value_type> >& Cijk,
  const Teuchos::ParameterList& params_) :
  name("Product Lanczos Gram-Schmidt PCE Basis"),
  params(params_),
  p(max_p)
{
  Teuchos::RCP<const Stokhos::OrthogPolyBasis<ordinal_type,value_type> > pce_basis = pce[0].basis();
  pce_sz = pce_basis->size();

  // Check if basis is a product basis
  Teuchos::RCP<const Stokhos::ProductBasis<ordinal_type,value_type> > prod_basis = Teuchos::rcp_dynamic_cast<const Stokhos::ProductBasis<ordinal_type,value_type> >(pce_basis);
  Teuchos::Array< Teuchos::RCP<const OneDOrthogPolyBasis<ordinal_type,value_type> > > coord_bases;
  if (prod_basis != Teuchos::null)
    coord_bases = prod_basis->getCoordinateBases();

  // Build Lanczos basis for each pce
  bool project = params.get("Project", true);
  bool normalize = params.get("Normalize", true);
  bool limit_integration_order = params.get("Limit Integration Order", false);
  bool use_stieltjes = params.get("Use Old Stieltjes Method", false);
  Teuchos::Array< Teuchos::RCP<const Stokhos::OneDOrthogPolyBasis<int,double > > > coordinate_bases;
  Teuchos::Array<int> is_invariant(pce.size(),-2);
  for (ordinal_type i=0; i<pce.size(); i++) {

    // Check for pce's lying in invariant subspaces, which are pce's that
    // depend on only a single dimension.  In this case use the corresponding
    // original coordinate basis.  Convention is:  -2 -- not invariant, -1 --
    // constant, i >= 0 pce depends only on dimension i
    if (prod_basis != Teuchos::null)
      is_invariant[i] = isInvariant(pce[i]);
    if (is_invariant[i] >= 0) {
      coordinate_bases.push_back(coord_bases[is_invariant[i]]);
    }

    // Exclude constant pce's from the basis since they don't represent
    // stochastic dimensions
    else if (is_invariant[i] != -1) {
      if (use_stieltjes) {
	coordinate_bases.push_back(
	  Teuchos::rcp(
	    new Stokhos::StieltjesPCEBasis<ordinal_type,value_type>(
	      p, Teuchos::rcp(&(pce[i]),false), quad, false,
	      normalize, project, Cijk)));
      }
      else {
	if (project) 
	  coordinate_bases.push_back(
	    Teuchos::rcp(
	      new Stokhos::LanczosProjPCEBasis<ordinal_type,value_type>(
		p, Teuchos::rcp(&(pce[i]),false), Cijk,
		normalize, limit_integration_order)));
	else
	  coordinate_bases.push_back(
	    Teuchos::rcp(
	      new Stokhos::LanczosPCEBasis<ordinal_type,value_type>(
		p, Teuchos::rcp(&(pce[i]),false), quad,
		normalize, limit_integration_order)));
      }
    }
  }
  d = coordinate_bases.size();

  // Build tensor product basis
  tensor_lanczos_basis = 
    Teuchos::rcp(
      new Stokhos::CompletePolynomialBasis<ordinal_type,value_type>(
	coordinate_bases,
	params.get("Cijk Drop Tolerance", 1.0e-15),
	params.get("Use Old Cijk Algorithm", false)));

  // Build Psi matrix -- Psi_ij = Psi_i(x^j)*w_j/<Psi_i^2>
  const Teuchos::Array<value_type>& weights = quad->getQuadWeights();
  const Teuchos::Array< Teuchos::Array<value_type> >& points = 
    quad->getQuadPoints(); 
  const Teuchos::Array< Teuchos::Array<value_type> >& basis_vals = 
    quad->getBasisAtQuadPoints();
  ordinal_type nqp = weights.size();
  SDM Psi(pce_sz, nqp);
  for (ordinal_type i=0; i<pce_sz; i++)
    for (ordinal_type k=0; k<nqp; k++)
      Psi(i,k) = basis_vals[k][i]*weights[k]/pce_basis->norm_squared(i);

  // Build Phi matrix -- Phi_ij = Phi_i(y(x^j))
  sz = tensor_lanczos_basis->size();
  Teuchos::Array<value_type> red_basis_vals(sz);
  Teuchos::Array<value_type> pce_vals(d);
  SDM Phi(sz, nqp);
  SDM F(nqp, d);
  for (int k=0; k<nqp; k++) {
    ordinal_type jdx = 0;
    for (int j=0; j<pce.size(); j++) {

      // Exclude constant pce's
      if (is_invariant[j] != -1) {

	// Use the identity mapping for invariant subspaces
	if (is_invariant[j] >= 0)
	  pce_vals[jdx] = points[k][is_invariant[j]];
	else
	  pce_vals[jdx] = pce[j].evaluate(points[k], basis_vals[k]);
	F(k,jdx) = pce_vals[jdx];
	jdx++;

      }

    }
    tensor_lanczos_basis->evaluateBases(pce_vals, red_basis_vals);
    for (int i=0; i<sz; i++)
      Phi(i,k) = red_basis_vals[i];
  }

  bool verbose = params.get("Verbose", false);
 
  // Compute matrix A mapping reduced space to original
  SDM A(pce_sz, sz);
  ordinal_type ret = 
    A.multiply(Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, Psi, Phi, 0.0);
  TEUCHOS_ASSERT(ret == 0);

  // Rescale columns of A to have unit norm
  const Teuchos::Array<value_type>& basis_norms = pce_basis->norm_squared();
  for (ordinal_type j=0; j<sz; j++) {
    value_type nrm = 0.0;
    for (ordinal_type i=0; i<pce_sz; i++)
      nrm += A(i,j)*A(i,j)*basis_norms[i];
    nrm = std::sqrt(nrm);
    for (ordinal_type i=0; i<pce_sz; i++)
      A(i,j) /= nrm;
  }

  // Compute our new basis -- each column of Qp is the coefficients of the
  // new basis in the original basis. Constraint pivoting so first d+1
  // columns and included in Qp.
  value_type rank_threshold = params.get("Rank Threshold", 1.0e-12);
  std::string  orthogonalization_method = 
    params.get("Orthogonalization Method", "Householder");
  Teuchos::Array<value_type> w(pce_sz, 1.0);
  SDM R;
  Teuchos::Array<ordinal_type> piv(sz);
  for (int i=0; i<d+1; i++)
    piv[i] = 1;
  typedef Stokhos::OrthogonalizationFactory<ordinal_type,value_type> SOF;
  sz = SOF::createOrthogonalBasis(
    orthogonalization_method, rank_threshold, verbose, A, w, Qp, R, piv);

  // Original basis at quadrature points -- needed to transform expansions
  // in this basis back to original
  SDM B(nqp, pce_sz);
  for (ordinal_type i=0; i<nqp; i++)
    for (ordinal_type j=0; j<pce_sz; j++)
      B(i,j) = basis_vals[i][j];

  // Evaluate new basis at original quadrature points
  Q.reshape(nqp, sz);
  ret = Q.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1.0, B, Qp, 0.0);
  TEUCHOS_ASSERT(ret == 0);

  // Compute reduced quadrature rule
  Stokhos::ReducedQuadratureFactory<ordinal_type,value_type> quad_factory(
    params.sublist("Reduced Quadrature"));
  Teuchos::SerialDenseMatrix<ordinal_type, value_type> Q2;
  reduced_quad = quad_factory.createReducedQuadrature(Q, Q2, F, weights);

  // Basis is orthonormal by construction
  norms.resize(sz, 1.0);
}
Exemplo n.º 10
0
LUDecomposition::LUDecomposition (const Matrix& A) {

   // Use a "left-looking", dot-product, Crout/Doolittle algorithm.

      LU = A;
      m = A.size1();
      n = A.size2();
      piv = PivotVector(m);
      for (int i = 0; i < m; i++) {
         piv(i) = i;
      }
      pivsign = 1;
      Vector LUcolj(m);

      // Outer loop.

      for (int j = 0; j < n; j++) {

         // Make a copy of the j-th column to localize references.

         for (int i = 0; i < m; i++) {
            LUcolj(i) = LU(i,j);
         }

         // Apply previous transformations.

         for (int i = 0; i < m; i++) {
             matrix_row<Matrix> LUrowi(LU,i);

            // Most of the time is spent in the following dot product.

            int kmax = std::min(i,j);
            double s = 0.0;
            for (int k = 0; k < kmax; k++) {
               s += LUrowi(k)*LUcolj(k);
            }

            LUrowi(j) = LUcolj(i) -= s;
         }
   
         // Find pivot and exchange if necessary.

         int p = j;
         for (int i = j+1; i < m; i++) {
            if (std::abs(LUcolj(i)) > std::abs(LUcolj(p))) {
               p = i;
            }
         }

         if (p != j) {
            for (int k = 0; k < n; k++) {
               double t = LU(p,k); LU(p,k) = LU(j,k); LU(j,k) = t;
            }
            int k = piv(p); piv(p) = piv(j); piv(j) = k;
            pivsign = -pivsign;
         }
         // Compute multipliers.
        
         if (j < m && LU(j,j) != 0.0) {
            for (int i = j+1; i < m; i++) {
               LU(i,j) /= LU(j,j);
            }
         }
      }
   }
Exemplo n.º 11
0
void MainWindow::renderBoardCompleteGame(std::vector<MoveHistoryEntry> history, QString outDir, bool renderOpenTiles, bool renderFrames, bool renderPlayers, bool renderNextTile, int playerCount)
{
	//TODO correct backgrounds

	QDir(outDir).mkpath(".");

	jcz::TileFactory tileFactory(false);
	TileImageFactory imgFactory(&tileFactory);

	QImage image;
	QPainter * painter = 0;

	RandomNextTileProvider rntp;
	HistoryProvider hp(&rntp, history, 0);
	Game g(&hp, false);

	for (int i = 0; i < playerCount; ++i)
		g.addPlayer(&RandomPlayer::instance);

	BoardGraphicsScene bgs(&tileFactory, &imgFactory);
	bgs.setRenderOpenTiles(renderOpenTiles);
	bgs.setRenderFrames(renderFrames);
	bgs.setGame(&g);
	g.addWatchingPlayer(&bgs);

	g.newGame(Tile::BaseGame, &tileFactory, history, true);

	bgs.clearSelection();
	QRectF sceneRect = bgs.itemsBoundingRect();

	int const spacing = 50;
	int constexpr pivScale = 4;
	QSize sceneSize = sceneRect.size().toSize();
	QSize size = sceneSize;
	if (renderPlayers)
	{
		QLabel remainingLabel(QString("%1 tiles left").arg(g.getTileCount() - 1));
		remainingLabel.updateGeometry();
		int nextTileType = g.getTile(hp.nextTile(&g))->tileType;

		QSize pivSize;
		{
			PlayerInfoView piv(0, &g, &imgFactory);
			piv.updateView();
			if (renderNextTile)
				piv.displayTile(g.getNextPlayer(), nextTileType);
			piv.updateGeometry();

			pivSize = piv.size() * pivScale;
			pivSize.rheight() *= g.getPlayerCount();

			QSize remSize = remainingLabel.sizeHint() * pivScale;

			size.rwidth() += pivSize.width() + spacing;
			size.rheight() = qMax(size.height(), pivSize.height() + spacing + remSize.height());
		}
	}



	std::vector<MoveHistoryEntry> applyHistory;
	for (int i = -1; i < (int)history.size(); ++i)
	{
		// oh well, this is ugly. If only there was a Game::step(MoveHistoryEntry)...
		if (i >= 0)
			applyHistory.push_back(history[i]);
		g.newGame(Tile::BaseGame, &tileFactory, applyHistory, true);

		delete painter;
		image = QImage(size, QImage::Format_ARGB32);
		image.fill(Qt::transparent);
		painter = new QPainter(&image);
		painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);

		QPoint offset(0, 0);
		if (renderPlayers)
		{
			QLabel remainingLabel(QString("%1 tiles left").arg(g.getTileCount() - 1));
			remainingLabel.updateGeometry();
			int nextTileType = g.getTile(hp.nextTile(&g))->tileType;

			QSize pivSize;
			painter->scale(pivScale, pivScale);
			for (uint p = 0; p < g.getPlayerCount(); ++p)
			{
				PlayerInfoView piv(p, &g, &imgFactory);
				piv.updateView();
				if (renderNextTile)
					piv.displayTile(g.getNextPlayer(), nextTileType);
				piv.updateGeometry();

				piv.render(painter, offset);

				offset.ry() += piv.size().height();
			}
			offset.setX(0);
			offset.setY((pivSize.height() + spacing) / pivScale);

			remainingLabel.render(painter, offset);

			offset.setX(pivSize.width() + spacing);
			offset.setY(0);
			painter->resetTransform();
		}

		bgs.setSceneRect(sceneRect);
		bgs.render(painter, QRectF(offset, size));

		image.save(QString("%1/%2.png").arg(outDir).arg(i+1, 3, 10, QLatin1Char('0')));
	}

	delete painter;
}
Exemplo n.º 12
0
void MainWindow::renderBoard(std::vector<MoveHistoryEntry> history, QString outFile, int removeLast, bool renderOpenTiles, bool renderFrames, bool renderPlayers, bool renderNextTile)
{
	//TODO correct backgrounds

	jcz::TileFactory tileFactory(false);
	TileImageFactory imgFactory(&tileFactory);

	QImage image;
	QPainter * painter = 0;

	RandomNextTileProvider rntp;
	HistoryProvider hp(&rntp, history, history.size() - removeLast);
	Game g(&hp, false);
	g.addPlayer(&RandomPlayer::instance);
	g.addPlayer(&RandomPlayer::instance);

	BoardGraphicsScene bgs(&tileFactory, &imgFactory);
	bgs.setRenderOpenTiles(renderOpenTiles);
	bgs.setRenderFrames(renderFrames);
	bgs.setGame(&g);
	g.addWatchingPlayer(&bgs);

	history.erase(history.end() - removeLast, history.end());
	g.newGame(Tile::BaseGame, &tileFactory, history, true);

	bgs.clearSelection();
	bgs.setSceneRect(bgs.itemsBoundingRect());

	int const spacing = 50;
	int constexpr pivScale = 4;
	QSize sceneSize = bgs.sceneRect().size().toSize();
	QSize size = sceneSize;
	QPoint offset(0, 0);
	if (renderPlayers)
	{
		QLabel remainingLabel(QString("%1 tiles left").arg(g.getTileCount() - 1));
		remainingLabel.updateGeometry();
		int nextTileType = g.getTile(hp.nextTile(&g))->tileType;

		QSize pivSize;
		for (uint p = 0; p < g.getPlayerCount(); ++p)
		{
			PlayerInfoView piv(p, &g, &imgFactory);
			piv.updateView();
			if (renderNextTile)
				piv.displayTile(g.getNextPlayer(), nextTileType);
			piv.updateGeometry();

			if (p == 0)
			{
				pivSize = piv.size() * pivScale;
				pivSize.rheight() *= g.getPlayerCount();

				QSize remSize = remainingLabel.sizeHint() * pivScale;

				size.rwidth() += pivSize.width() + spacing;
				size.rheight() = qMax(size.height(), pivSize.height() + spacing + remSize.height());

				image = QImage(size, QImage::Format_ARGB32);
				image.fill(Qt::transparent);
				painter = new QPainter(&image);
				painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);

				painter->scale(pivScale, pivScale);
			}

			piv.render(painter, offset);

			offset.ry() += piv.size().height();
		}
		offset.setX(0);
		offset.setY((pivSize.height() + spacing) / pivScale);

		remainingLabel.render(painter, offset);

		offset.setX(pivSize.width() + spacing);
		offset.setY(0);
		painter->resetTransform();
	}
	else
	{
		image = QImage(size, QImage::Format_ARGB32);
		image.fill(Qt::transparent);
		painter = new QPainter(&image);
		painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
	}

	bgs.render(painter, QRectF(offset, size));

	image.save(outFile);

	delete painter;
}
Exemplo n.º 13
0
short RangePartitioningFunction::codeGen(Generator *generator,
					 Lng32 partInputDataLength)
{
  ExpGenerator         * exp_gen = generator->getExpGenerator();
  Lng32                 myOwnPartInputDataLength;

  const Int32            pivMoveAtp = 0; // only one atp is used for this expr
  const Int32            pivMoveAtpIndex = 2; // 0: consts, 1: temps, 2: result
  const ExpTupleDesc::TupleDataFormat pivFormat = // format of PIVs
                          ExpTupleDesc::SQLARK_EXPLODED_FORMAT;
  ex_cri_desc          *partInputCriDesc = new(generator->getSpace())
                           ex_cri_desc(pivMoveAtpIndex+1,
				       generator->getSpace());
  ExpTupleDesc         *partInputTupleDesc;
  ExRangePartInputData *generatedObject = NULL;

  // get the list of partition input variables
  ValueIdList          piv(getPartitionInputValuesLayout());

  CollIndex numPartInputs = piv.entries();
  CollIndex numPartKeyCols = (numPartInputs - 1) / 2;
  // the number of partition input variables must be odd
  GenAssert(2*numPartKeyCols+1 == numPartInputs,
	    "NOT 2*numPartKeyCols+1 == numPartInputs");

  Attributes **begEndAttrs;
  Int32 alignedPartKeyLen;

  // make a layout of the partition input data record
  generatePivLayout(
       generator,
       myOwnPartInputDataLength,
       pivMoveAtp,
       pivMoveAtpIndex,
       &begEndAttrs);
  
  // the aligned part key length is where the end key values start
  alignedPartKeyLen = (Int32) begEndAttrs[numPartKeyCols]->getOffset();

  if (begEndAttrs[numPartKeyCols]->getNullIndicatorLength() > 0)
    alignedPartKeyLen = MINOF(
	 alignedPartKeyLen,
	 (Int32)begEndAttrs[numPartKeyCols]->getNullIndOffset());
    
  if (begEndAttrs[numPartKeyCols]->getVCIndicatorLength() > 0)
    alignedPartKeyLen = MINOF(
	 alignedPartKeyLen,
	 begEndAttrs[numPartKeyCols]->getVCLenIndOffset());
    
  // generate a tuple desc for the whole PIV record and a cri desc
  partInputTupleDesc = new(generator->getSpace()) ExpTupleDesc(
       numPartInputs,
       begEndAttrs,
       myOwnPartInputDataLength,
       pivFormat,
       ExpTupleDesc::LONG_FORMAT,
       generator->getSpace());
  partInputCriDesc->setTupleDescriptor(pivMoveAtpIndex,partInputTupleDesc);

  // make sure we fulfill the assertions we made

  // optimizer and generator should agree on the part input data length
  GenAssert(partInputDataLength == (Lng32) myOwnPartInputDataLength,
	    "NOT partInputDataLength == myOwnPartInputDataLength");
  // the length of the begin key and the end key must be the same
  // (compare offsets of their last fields)
// Commented out because this check does not work. The check needs
// to compute the LENGTH of each key field, by subtracting the current
// offset from the next offset, taking into account varchar length
// and null indicator fields (which are not part of the length but
// increase the offset).
//GenAssert(begEndAttrs[numPartKeyCols-1]->getOffset() + alignedPartKeyLen ==
//  begEndAttrs[2*numPartKeyCols-1]->getOffset(),
//    "begin/end piv keys have different layouts");

#pragma nowarn(1506)   // warning elimination 
  generatedObject = new(generator->getSpace()) ExRangePartInputData(
       partInputCriDesc,
       partInputDataLength,
       alignedPartKeyLen, //len of one part key + filler
       begEndAttrs[numPartInputs-1]->getOffset(),//offset of last field
       getCountOfPartitions(),
       generator->getSpace(),
       TRUE); // uses expressions to calculate ranges in the executor
  generatedObject->setPartitionExprAtp(pivMoveAtp);
  generatedObject->setPartitionExprAtpIndex(pivMoveAtpIndex);
#pragma warn(1506)  // warning elimination 

  // now fill in the individual partition boundaries
  // (NOTE: there is one more than there are partitions)
  ULng32 boundaryDataLength = 0;
  for (Lng32 i = 0; i <= getCountOfPartitions(); i++)
    {
      const ItemExprList *iel = partitionBoundaries_->getBoundaryValues(i);
      ex_expr * generatedExpr = NULL;

      ValueIdList boundaryColValues;
      ULng32 checkedBoundaryLength;

      // convert the ItemExpressionList iel into a ValueIdList
      for (CollIndex kc = 0; kc < iel->entries(); kc++)
	{
	  ItemExpr *boundaryVal = (*iel)[kc];

	  // create a cast node to convert the boundary value to the
	  // data type of the column
	  ItemExpr *castBoundaryVal =
	    new(generator->wHeap()) Cast(boundaryVal,&piv[kc].getType());

	  castBoundaryVal->bindNode(generator->getBindWA());

	  boundaryColValues.insert(castBoundaryVal->getValueId());
	}

      // Now generate a contiguous move expression. Only for the first time
      // generate a tuple desc, since all tuples should be the same.
      exp_gen->generateContiguousMoveExpr(
	   boundaryColValues,
	   0, // cast nodes created above will do the move, no conv nodes
	   pivMoveAtp,
	   pivMoveAtpIndex,
	   pivFormat,
	   checkedBoundaryLength,
	   &generatedExpr);

      if (i == 0)
	{
	  // first time set the actual part key data length
	  boundaryDataLength = checkedBoundaryLength;
	}
      else
	{
	  // all boundary values (piv tuples) must have the same layout
	  // and therefore the same length
	  GenAssert(boundaryDataLength == checkedBoundaryLength,
		    "Partition boundary tuple layout mismatch");
	}

      generatedObject->setPartitionStartExpr(i,generatedExpr);
    }

  NADELETEBASIC(begEndAttrs, generator->wHeap());
  generator->setGenObj(NULL, (ComTdb*)generatedObject);
  return 0;
}
Exemplo n.º 14
0
ordinal_type
Stokhos::MonomialProjGramSchmidtPCEBasis<ordinal_type, value_type>::
buildReducedBasis(
  ordinal_type max_p, 
  value_type threshold,
  const Teuchos::SerialDenseMatrix<ordinal_type,value_type>& A, 
  const Teuchos::SerialDenseMatrix<ordinal_type,value_type>& F,
  const Teuchos::Array<value_type>& weights, 
  Teuchos::Array< Stokhos::MultiIndex<ordinal_type> >& terms_,
  Teuchos::Array<ordinal_type>& num_terms_,
  Teuchos::SerialDenseMatrix<ordinal_type,value_type>& Qp_, 
  Teuchos::SerialDenseMatrix<ordinal_type,value_type>& Q_)
{
  // Compute basis terms -- 2-D array giving powers for each linear index
  ordinal_type max_sz;
  CPBUtils::compute_terms(max_p, this->d, max_sz, terms_, num_terms_);

  // Compute B matrix -- monomials in F
  // for i=0,...,nqp-1
  //   for j=0,...,sz-1
  //      B(i,j) = F(i,1)^terms_[j][1] * ... * F(i,d)^terms_[j][d]
  // where sz is the total size of a basis up to order p and terms_[j] 
  // is an array of powers for each term in the total-order basis
  ordinal_type nqp = weights.size();
  SDM B(nqp, max_sz);
  for (ordinal_type i=0; i<nqp; i++) {
    for (ordinal_type j=0; j<max_sz; j++) {
      B(i,j) = 1.0;
      for (ordinal_type k=0; k<this->d; k++)
	B(i,j) *= std::pow(F(i,k), terms_[j][k]);
    }
  }

  // Project B into original basis -- should use SPAM for this
  SDM Bp(this->pce_sz, max_sz);
  const Teuchos::Array<value_type>& basis_norms = 
    this->pce_basis->norm_squared();
  for (ordinal_type i=0; i<this->pce_sz; i++) {
    for (ordinal_type j=0; j<max_sz; j++) {
      Bp(i,j) = 0.0;
      for (ordinal_type k=0; k<nqp; k++)
	Bp(i,j) += weights[k]*B(k,j)*A(k,i);
      Bp(i,j) /= basis_norms[i];
    }
  }

  // Rescale columns of Bp to have unit norm
  for (ordinal_type j=0; j<max_sz; j++) {
    value_type nrm = 0.0;
    for (ordinal_type i=0; i<this->pce_sz; i++)
      nrm += Bp(i,j)*Bp(i,j)*basis_norms[i];
    nrm = std::sqrt(nrm);
    for (ordinal_type i=0; i<this->pce_sz; i++)
      Bp(i,j) /= nrm;
  }

  // Compute our new basis -- each column of Qp is the coefficients of the
  // new basis in the original basis.  Constraint pivoting so first d+1
  // columns and included in Qp.
  Teuchos::Array<value_type> w(this->pce_sz, 1.0);
  SDM R;
  Teuchos::Array<ordinal_type> piv(max_sz);
  for (int i=0; i<this->d+1; i++)
    piv[i] = 1;
  typedef Stokhos::OrthogonalizationFactory<ordinal_type,value_type> SOF;
  ordinal_type sz_ = SOF::createOrthogonalBasis(
    this->orthogonalization_method, threshold, this->verbose, Bp, w, 
    Qp_, R, piv);

  // Evaluate new basis at original quadrature points
  Q_.reshape(nqp, sz_);
  ordinal_type ret = 
    Q_.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1.0, A, Qp_, 0.0);
  TEUCHOS_ASSERT(ret == 0);

  return sz_;
}
Exemplo n.º 15
0
void ResetXForm::ResetNodes(const INodeTab& nodesToReset)
{
	Interface *ip = GetCOREInterface();
	for (int i = 0; i < nodesToReset.Count(); i++) {
		INode *node = nodesToReset[i];
		if (!node || node->IsGroupMember() || node->IsGroupHead()) 
			continue;
		if (SelectedAncestor(node)) 
			continue;

		Matrix3 ntm, ptm, rtm(1), piv(1), tm;
		
		// Get Parent and Node TMs
		ntm = node->GetNodeTM(ip->GetTime());
		ptm = node->GetParentTM(ip->GetTime());
		
		// Compute the relative TM
		ntm = ntm * Inverse(ptm);
		
		// The reset TM only inherits position
		rtm.SetTrans(ntm.GetTrans());
		
		// Set the node TM to the reset TM		
		tm = rtm*ptm;
		node->SetNodeTM(ip->GetTime(), tm);

		// Compute the pivot TM
		piv.SetTrans(node->GetObjOffsetPos());
		PreRotateMatrix(piv,node->GetObjOffsetRot());
		ApplyScaling(piv,node->GetObjOffsetScale());
		
		// Reset the offset to 0
		node->SetObjOffsetPos(Point3(0,0,0));
		node->SetObjOffsetRot(IdentQuat());
		node->SetObjOffsetScale(ScaleValue(Point3(1,1,1)));

		// Take the position out of the matrix since we don't reset position
		ntm.NoTrans();

		// Apply the offset to the TM
		ntm = piv * ntm;

		// Apply a derived object to the node's object
		Object *obj = node->GetObjectRef();
		IDerivedObject *dobj = CreateDerivedObject(obj);
		
		// Create an XForm mod
		SimpleMod *mod = (SimpleMod*)ip->CreateInstance(
			OSM_CLASS_ID,
			Class_ID(CLUSTOSM_CLASS_ID,0));

		// Apply the transformation to the mod.
		SetXFormPacket pckt(ntm);
		mod->tmControl->SetValue(ip->GetTime(),&pckt);

		// Add the modifier to the derived object.
		dobj->SetAFlag(A_LOCK_TARGET); // RB 3/11/99: When the macro recorder is on the derived object will get deleted unless it is locked.
		dobj->AddModifier(mod);
		dobj->ClearAFlag(A_LOCK_TARGET);

		// Replace the node's object
		node->SetObjectRef(dobj);
	}
	
//	Why on earth were we clearing the undo stack?
//	GetSystemSetting(SYSSET_CLEAR_UNDO);
	ip->RedrawViews(ip->GetTime());
	SetSaveRequiredFlag(TRUE);
}