Exemplo n.º 1
0
		std::string makeFormattedString(
		const char* aFormat,
		const A1& a1 = A1(),
		const A2& a2 = A2(),
		const A3& a3 = A3(),
		const A4& a4 = A4(),
		const A5& a5 = A5(),
		const A6& a6 = A6(),
		const A7& a7 = A7(),
		const A8& a8 = A8(),
		const A9& a9 = A9(),
		const A10& a10 = A10(),
		const A11& a11 = A11(),
		const A12& a12 = A12(),
		const A13& a13 = A13(),
		const A14& a14 = A14(),
		const A15& a15 = A15(),
		const A16& a16 = A16(),
		const A17& a17 = A17(),
		const A18& a18 = A18(),
		const A19& a19 = A19(),
		const A20& a20 = A20()
		)
		{
			return makeStringByPrintf(aFormat,
				a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
				a11, a12, a13, a14, a15, a16, a17, a18, a19, a20
				);
		}
Exemplo n.º 2
0
  void testQLDSolver()
  {
    BaseVariable xy("xy",2);
    BaseVariable z("z",1);
    CompositeVariable T("T", xy, z);

    MatrixXd A1(1,1); A1 << 1;
    VectorXd b1(1); b1 << -3;
    LinearFunction lf1(z, A1, b1);
    LinearConstraint c1(&lf1, true);

    MatrixXd A2(1,2); A2 << 3,1 ;
    VectorXd b2(1); b2 << 0;
    LinearFunction lf2(xy, A2, b2);
    LinearConstraint c2(&lf2, true);

    MatrixXd A3(2,2); A3 << 2,1,-0.5,1 ;
    VectorXd b3(2); b3 << 0, 1;
    LinearFunction lf3(xy, A3, b3);
    LinearConstraint c3(&lf3, false);

    QuadraticFunction objFunc(T, Matrix3d::Identity(), Vector3d::Zero(), 0);
    QuadraticObjective obj(&objFunc);
    
    QLDSolver solver;
    solver.addConstraint(c1);
    solver.addConstraint(c2);
    solver.addConstraint(c3);
    solver.addObjective(obj);

    std::cout << "sol = " << std::endl << solver.solve().solution << std::endl << std::endl;
    ocra_assert(solver.getLastResult().info == 0);


    solver.removeConstraint(c1);
    IdentityFunction id(z);
    VectorXd lz(1); lz << 1;
    VectorXd uz(1); uz << 2;
    IdentityConstraint bnd1(&id, lz, uz);
    solver.addBounds(bnd1);
    std::cout << "sol = " << std::endl << solver.solve().solution << std::endl << std::endl;
    ocra_assert(solver.getLastResult().info == 0);

    BaseVariable t("t", 2);
    VectorXd ut(2); ut << -4,-1;
    BoundFunction bf(t, ut, BOUND_TYPE_SUPERIOR);
    BoundConstraint bnd2(&bf, false);
    solver.addBounds(bnd2);

    QuadraticFunction objFunc2(t, Matrix2d::Identity(), Vector2d::Constant(2.71828),0);
    QuadraticObjective obj2(&objFunc2);
    solver.addObjective(obj2);
    std::cout << "sol = " << std::endl << solver.solve().solution << std::endl << std::endl;
    ocra_assert(solver.getLastResult().info == 0);

    Vector2d c3l(-1,-1);
    c3.setL(c3l);
    std::cout << "sol = " << std::endl << solver.solve().solution << std::endl << std::endl;
    ocra_assert(solver.getLastResult().info == 0);
  }
Exemplo n.º 3
0
/*! \fn Real vecpot2b1i(Real (*A2)(Real,Real,Real), Real (*A3)(Real,Real,Real),
 *                const GridS *pG, const int i, const int j, const int k)
 *  \brief Compute B-field components from a vector potential.
 *
 * THESE FUNCTIONS COMPUTE MAGNETIC FIELD COMPONENTS FROM COMPONENTS OF A
 * SPECIFIED VECTOR POTENTIAL USING STOKES' THEOREM AND SIMPSON'S QUADRATURE.
 * NOTE:  THIS IS ONLY GUARANTEED TO WORK IF THE POTENTIAL IS OF CLASS C^1.
 * WRITTEN BY AARON SKINNER.
 */
Real vecpot2b1i(Real (*A2)(Real,Real,Real), Real (*A3)(Real,Real,Real),
                const GridS *pG, const int i, const int j, const int k)
{
  Real x1,x2,x3,b1i=0.0,lsf=1.0,rsf=1.0,dx2=pG->dx2;
  Real f2(Real y);
  Real f3(Real z);

  a2func = A2;
  a3func = A3;
  cc_pos(pG,i,j,k,&x1,&x2,&x3);
  xmin = x1 - 0.5*pG->dx1;  xmax = x1 + 0.5*pG->dx1;
  ymin = x2 - 0.5*pG->dx2;  ymax = x2 + 0.5*pG->dx2;
  zmin = x3 - 0.5*pG->dx3;  zmax = x3 + 0.5*pG->dx3;

  xsav = xmin;
#ifdef CYLINDRICAL
  lsf = xmin;  rsf = xmin;
  dx2 = xmin*pG->dx2;
#endif

  if (A2 != NULL) {
    if (ymin == ymax)
      b1i += rsf*A2(xmin,ymin,zmin) - lsf*A2(xmin,ymin,zmax);
    else {
      zsav = zmin;
      b1i += rsf*qsimp(f2,ymin,ymax);
      zsav = zmax;
      b1i -= lsf*qsimp(f2,ymin,ymax);
    }
  }
  if (A3 != NULL) {
    if (zmin == zmax)
      b1i += A3(xmin,ymax,zmin) - A3(xmin,ymin,zmin);
    else {
      ysav = ymax;
      b1i += qsimp(f3,zmin,zmax);
      ysav = ymin;
      b1i -= qsimp(f3,zmin,zmax);
    }
  }

  if (pG->dx2 > 0.0) b1i /= dx2;
  if (pG->dx3 > 0.0) b1i /= pG->dx3;

  return b1i;
}
Exemplo n.º 4
0
Tensor::Tensor()
  : A1(3,3), A2(3,3), A3(3,3) {
  int i, j;
  for (i=1; i<=3; i++)
    for (j=1; j<=3; j++) {
      A1(i, j) = 0.0;
      A2(i, j) = 0.0;
      A3(i, j) = 0.0;
    }
}
Exemplo n.º 5
0
/*! \fn Real vecpot2b2i(Real (*A1)(Real,Real,Real), Real (*A3)(Real,Real,Real),
 *                const GridS *pG, const int i, const int j, const int k)
 *  \brief Compute B-field components from a vector potential.
 *
 * THESE FUNCTIONS COMPUTE MAGNETIC FIELD COMPONENTS FROM COMPONENTS OF A
 * SPECIFIED VECTOR POTENTIAL USING STOKES' THEOREM AND SIMPSON'S QUADRATURE.
 * NOTE:  THIS IS ONLY GUARANTEED TO WORK IF THE POTENTIAL IS OF CLASS C^1.
 * WRITTEN BY AARON SKINNER.
 */
Real vecpot2b2i(Real (*A1)(Real,Real,Real), Real (*A3)(Real,Real,Real),
                const GridS *pG, const int i, const int j, const int k)
{
  Real x1,x2,x3,b2i=0.0;
  Real f1(Real x);
  Real f3(Real z);

  a1func = A1;
  a3func = A3;
  cc_pos(pG,i,j,k,&x1,&x2,&x3);
  xmin = x1 - 0.5*pG->dx1;  xmax = x1 + 0.5*pG->dx1;
  ymin = x2 - 0.5*pG->dx2;  ymax = x2 + 0.5*pG->dx2;
  zmin = x3 - 0.5*pG->dx3;  zmax = x3 + 0.5*pG->dx3;

  ysav = ymin;

  if (A1 != NULL) {
    if (xmin == xmax)
      b2i += A1(xmin,ymin,zmax) - A1(xmin,ymin,zmin);
    else {
      zsav = zmax;
      b2i += qsimp(f1,xmin,xmax);
      zsav = zmin;
      b2i -= qsimp(f1,xmin,xmax);
    }
  }
  if (A3 != NULL) {
    if (zmin == zmax)
      b2i += A3(xmin,ymin,zmin) - A3(xmax,ymin,zmin);
    else {
      xsav = xmin;
      b2i += qsimp(f3,zmin,zmax);
      xsav = xmax;
      b2i -= qsimp(f3,zmin,zmax);
    }
  }

  if (pG->dx1 > 0.0) b2i /= pG->dx1;
  if (pG->dx3 > 0.0) b2i /= pG->dx3;

  return b2i;
}
Exemplo n.º 6
0
 int main(void){
 Marray<double,3> A3(3,3,3);
 Marray<double,1> B1(3);
 Marray<double,2> C2Test(3,3);
 Marray<double,2> C2(3,3);
 A3.sucesion(0,1);
 B1.sucesion(0,1);
 Index<'i'> iG;
 Index<'j'> jG;
 Index<'k'> kG;
 for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C2(i,j)+=A3(i,j,k)*B1(k);
          }
     }
 }

C2Test(iG,jG)=A3(iG,jG,kG)*B1(kG);
assert(C2==C2Test);


C2=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C2(i,j)+=A3(i,k,j)*B1(k);
          }
     }
 }

C2Test(iG,jG)=A3(iG,kG,jG)*B1(kG);
assert(C2==C2Test);


C2=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C2(i,j)+=A3(k,i,j)*B1(k);
          }
     }
 }

C2Test(iG,jG)=A3(kG,iG,jG)*B1(kG);
assert(C2==C2Test);


C2=0;


}
int hpx_main(boost::program_options::variables_map& vm)
{
    {
        orthotope<double>
            A0({3, 3})
          , A1({3, 3})
          , A2({3, 3})  
          , A3({3, 3})
          , A4({3, 3})
          , A5({4, 4})
            ;
    
        // QR {{1, 3, 6}, {3, 5, 7}, {6, 7, 4}}
        A0.row(0,  1,    3,    6   );
        A0.row(1,  3,    5,    7   );
        A0.row(2,  6,    7,    4   );
    
        // QR {{12, -51, 4}, {6, 167, -68}, {-4, 24, -41}}
        A1.row(0,  12,  -51,   4   );
        A1.row(1,  6,    167, -68  );
        A1.row(2, -4,    24,  -41  );
 
        // QR {{2, -2, 18}, {2, 1, 0}, {1, 2, 0}}
        A2.row(0,  2,   -2,    18  );
        A2.row(1,  2,    1,    0   );
        A2.row(2,  1,    2,    0   );
   
        // QR {{0, 1, 1}, {1, 1, 2}, {0, 0, 3}}
        A3.row(0,  0,    1,    1   );
        A3.row(1,  1,    1,    2   );
        A3.row(2,  0,    0,    3   );

        // QR {{1, 1, -1}, {1, 2, 1}, {1, 2, -1}}
        A4.row(0,  1,    1,   -1   );
        A4.row(1,  1,    2,    1   );
        A4.row(2,  1,    2,   -1   );
    
        // QR {{4, -2, 2, 8}, {-2, 6, 2, 4}, {2, 2, 10, -6}, {8, 4, -6, 12}}
        A5.row(0,  4,   -2,    2,    8   );
        A5.row(1, -2,    6,    2,    4   );
        A5.row(2,  2,    2,    10,  -6   );
        A5.row(3,  8,    4,   -6,    12  );
    
        householders(A0);
        householders(A1);
        householders(A2);
        householders(A3);
        householders(A4);
        householders(A5);
    }

    return hpx::finalize(); 
}
Exemplo n.º 8
0
void Tensor::set(int i, int j, int k, double f) {
  switch(i) {
  case 1: A1(j, k) = f; break;
  case 2: A2(j, k) = f; break;
  case 3: A3(j, k) = f; break;
  default:  
    ostringstream ii;
    ii << "Tensor index out of range: " << i << "\n";
    throw ii.str();
    break;
  }
}
Exemplo n.º 9
0
double & Tensor::operator() (int i, int j, int k) {
  switch(i) {
  case 1: return A1(j, k); break;
  case 2: return A2(j, k); break;
  case 3: return A3(j, k); break;
  default: 
    ostringstream ii;
    ii << "Trying to access " << i << j << k << "th element of tensor";
    ii << *this;
    throw ii.str();
    break;
  }
}
Exemplo n.º 10
0
int main()
{
	int n = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0, num = 0;
	int count_a1 = 0, count_a2 = 0, count_a3 = 0, count_a4 = 0, count_a5 = 0;
	int flag_A2 = 1;

	scanf("%d", &n);
	for (; n > 0; n--) {
		scanf("%d", &num);
		A1(num, &a1, &count_a1);
		A2(num, &a2, &count_a2, &flag_A2);
		A3(num, &a3, &count_a3);
		A4(num, &a4, &count_a4);
		A5(num, &a5, &count_a5);
	}
	if (count_a1 > 0)
		printf("%d ", a1);
	else
		printf("N ");

	if (count_a2 > 0)
		printf("%d ", a2);
	else
		printf("N ");

	if (count_a3 > 0)
		printf("%d ", a3);
	else
		printf("N ");

	if (count_a4 > 0)
		printf("%.1lf ", (double)a4 / count_a4);
	else
		printf("N ");

	if (count_a5 > 0)
		printf("%d", a5);
	else
		printf("N");

	return 0;
}
Exemplo n.º 11
0
static Float A3inv(Float y, Float guess) {
	Float x = guess;
	int it = 1;

	while (true) {
		Float residual = A3(x)-y,
			  deriv = dA3(x);
		x -= residual/deriv;

		if (++it > 20) {
			SLog(EWarn, "VanMisesFisherDistr::convolve(): Newton's method "
				" did not converge!");
			return guess;
		}

		if (std::abs(residual) < 1e-5f)
			break;
	}
	return x;
}
Exemplo n.º 12
0
TYPED_TEST(Intesection_TEST, intersection_ray_triangle)
{
	using Scalar = typename cgogn::geometry::vector_traits<TypeParam>::Scalar;
	TypeParam p0(Scalar(1), Scalar(1), Scalar(96.1));
	TypeParam p1(Scalar(5), Scalar(1), Scalar(92.3));
	TypeParam p2(Scalar(3), Scalar(5), Scalar(94.2));

	TypeParam A0(Scalar(3), Scalar(3), Scalar(0));
	TypeParam D0(Scalar(0.001), Scalar(0.001), Scalar(1.0));

	TypeParam A1(Scalar(3), Scalar(1), Scalar(0));
	TypeParam D1(Scalar(0), Scalar(0), Scalar(1.0));
	TypeParam A2(Scalar(5), Scalar(1), Scalar(0));
	TypeParam A3(Scalar(9), Scalar(5), Scalar(0));

	EXPECT_TRUE(cgogn::geometry::intersection_ray_triangle(A0,D0,p0,p1,p2));
	EXPECT_TRUE(cgogn::geometry::intersection_ray_triangle(A1,D1,p0,p1,p2));
	EXPECT_TRUE(cgogn::geometry::intersection_ray_triangle(A2,D1,p0,p1,p2));
	EXPECT_FALSE(cgogn::geometry::intersection_ray_triangle(A3,D0,p0,p1,p2));

}
Exemplo n.º 13
0
MxQuadric::MxQuadric(const MxQuadric3& Q3, unsigned int N)
    : A(N), b(N)
{
    unsigned int i, j;

    clear();

    Mat3 A3 = Q3.tensor();
    Vec3 b3 = Q3.vector();

    for(i=0; i<3; i++)
    {
	for(j=0; j<3; j++)
	    A(i,j) = A3(i,j);

	b[i] = b3[i];
    }

    c = Q3.offset();
    r = Q3.area();
}
Exemplo n.º 14
0
void PDESolver::CrankNicolson(vec *v){
        double a,a2,a3; vec A1 = zeros<vec>(Nx), A2 = zeros<vec>(Nx), A3 = zeros<vec>(Nx), vtilde, vnew;
        a = dt / dx / dx; a2 = 2 - 2*a; a3 = 2 + 2*a; ofstream myfile;
        myfile.open("CrankNicolson_movie.txt");

        // Setting the diagonals on of the LHS-matrix.
        for (int i=0; i<Nx; i++){
            A1(i) = -a; A2(i) = a3; A3(i) = -a;
        }

        vnew = *v; vtilde = vnew;
        for (int j=1; j<Nt; j++){
            // Chaning the RHS vector v_old into vtilde.
            for (int i=1; i<Nx-1; i++){
                vtilde(i) = a*vnew(i-1) + a2*vnew(i) + a*vnew(i+1);
            }
            vnew = PDESolver::tridiagonal(A1,A2,A3,vtilde);
            for (int i=0; i<Nx; i++){myfile << vnew(i) + 1 - i*dx << " ";}; myfile << endl;
        }
        myfile.close();
        for (int i=0; i<Nx; i++){vnew(i) += 1 - i*dx;}
        *v = vnew;
}
Exemplo n.º 15
0
Float VonMisesFisherDistr::convolve(Float kappa1, Float kappa2) {
	return A3inv(A3(kappa1) * A3(kappa2), std::min(kappa1, kappa2));
}
Exemplo n.º 16
0
    KJG_GENO_UNPACK(p + 3)
#define U2(p) U1(p), U1(p +  4), U1(p +  8), U1(p + 12)
#define U3(p) U2(p), U2(p + 16), U2(p + 32), U2(p + 48)
const uint8_t KJG_GENO_UNPACK_LOOKUP[256][4] =
  { U3(0), U3(64), U3(128),
U3(192) };

#define A1(p) \
    KJG_GENO_SUM_ALT(p), \
    KJG_GENO_SUM_ALT(p + 1), \
    KJG_GENO_SUM_ALT(p + 2), \
    KJG_GENO_SUM_ALT(p + 3)
#define A2(p) A1(p), A1(p +  4), A1(p +  8), A1(p + 12)
#define A3(p) A2(p), A2(p + 16), A2(p + 32), A2(p + 48)
const uint8_t KJG_GENO_SUM_ALT_LOOKUP[256] =
  { A3(0), A3(64), A3(128), A3(192) };

#define C1(p) \
    KJG_GENO_COUNT(p), \
    KJG_GENO_COUNT(p + 1), \
    KJG_GENO_COUNT(p + 2), \
    KJG_GENO_COUNT(p + 3)
#define C2(p) C1(p), C1(p +  4), C1(p +  8), C1(p + 12)
#define C3(p) C2(p), C2(p + 16), C2(p + 32), C2(p + 48)
const uint8_t KJG_GENO_COUNT_LOOKUP[256] =
  { C3(0), C3(64), C3(128), C3(192) };

// Functional interface

void
kjg_geno_pack (const size_t n, const uint8_t* u, uint8_t* p)
Exemplo n.º 17
0
            blit(muertebmp,enemigom,0,0,0,0,33,33);//carga la imagen sobre el buffer pacman
            draw_sprite(buffer,enemigom,_x,_y);
            blit(buffer, screen ,0,0,0,0,1280,600);
            rest(80);

        _x = 0;
        _y = 0;
        vidaenemigo--;
    }
}

int main()
{

    allegro_init();
    install_keyboard();

    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED,1280, 600 , 0, 0);

    //inicializa la musica en allegro
    if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0)
        {
            allegro_message("Error: inicializando sistema de sonido\n%s\n", allegro_error);
            return 1;
        }
    // ajuste de volumen
    set_volume(70, 70);//cuanto se oye a la izquierdsa y a la derecha

    intro = load_wav("music/start.wav");
    sirenafantasma = load_wav("music/sirene.wav");
    muertes = load_wav("music/muerte.wav");

    buffer = create_bitmap(1280,600); //870 570
    pacman = create_bitmap(33,33);
    complemento = create_bitmap(400,600);
    vid =create_bitmap(33,33);
    ataqueb = create_bitmap(33,33);

    atabmp = load_bitmap("images/ataque.bmp",NULL);
    roca = load_bitmap("images/tile2.bmp",NULL);
    pacbmp =load_bitmap("images/tank2.bmp", NULL);
    comida = load_bitmap("images/Comida.bmp",NULL);
    muertebmp = load_bitmap("images/muerte1.bmp",NULL);
    combmp =load_bitmap("images/complemento.bmp",NULL);
    vidas = load_bitmap("images/vidas.bmp",NULL);

    mapa1 mapa;
    enemigo A1(30*1,30*18) ;
    enemigo A2(30*27,30*1) ;
    enemigo A3(30*14,30*11) ;
    enemigo A4(30*27,30*18) ;
    enemigo A5(30*27,30*18);
    personaje1 personaje;
    personaje2 personaje3;



    play_sample(intro,200,150,1000,0); // volumen,sonido,,velocidad a la que se reproduce,distribucion 1000 es punto medio,para que no se repita
    rest(4000);

    play_sample(sirenafantasma,150,150,1000,1);

    while (!key[KEY_ESC] && mapa.game_over())
    {
        if(A1.getvida()==0 && A2.getvida()==0 && A3.getvida()==0 && A4.getvida()==0) return false;

        personaje.mover_personaje();
        mapa.dibujar_mapa();
        personaje.dibujar_personaje();
        personaje.ataque();
        personaje.ataque1();
        personaje3.dibujar_personaje();
        personaje3.mover_personaje();
        A1.mover_enemigo();
        A2.mover_enemigo();
        A4.mover_enemigo();
        A3.mover_enemigo();
        personaje3.ataque();
        personaje3.ataque1();
        A1.ataque2();
        A1.ataque_enemigo();
        A2.ataque2();
        A2.ataque_enemigo();
        A4.ataque2();
        A4.ataque_enemigo();
        A3.ataque2();
        A3.ataque_enemigo();
        A1.muerte_enemigo();
        A2.muerte_enemigo();
Exemplo n.º 18
0
//TODO Must make sure we always use 32F or 64F.
void PCAMerge::computeAdd()
{
	// Add checks for errors, Exceptions
	// TODO : Add checks against model, number of observations. Create eigenVals and eigenVecs accordingly. Refer Matlab code for possible checks to be implemented
	//
	// From here, going forward assuming no other errors possible
	//
	
	float eps = 1e-3;
	// New number of Observations
	nObs = N + M;
	// TODO add check for nObs being zero
	
	// New model's mean.
	mean = ( (N * m1.mean) + (M * m2.mean) ) / nObs;

	// Vector joining the centres
	cv::Mat dorg = m1.mean - m2.mean;

	// Note:
	// dorg            : n x 1
	// m1.eigenvectors : n x p
	// m2.eigenvectors : n x q
	// G			   : p x q
	// H			   : n x q
	// g 			   : p x 1
	// h               : n x 1
	
	//Note Eigenvectors from cv::PCA are stored as rows. We need to transpose them.
	//Note We should probably put the transposed vectors in other matrices, in order to leave the original models untouched (Luca)

	m1.eigenvectors = m1.eigenvectors.t();
	m2.eigenvectors = m2.eigenvectors.t();

	//New Basis
	cv::Mat G = m1.eigenvectors.t() * m2.eigenvectors; 
	cv::Mat H = m2.eigenvectors - ( m1.eigenvectors * G );// H is orthogonal to m1.eigenvectors
	
	cv::Mat g = m1.eigenvectors.t() * dorg;
	cv::Mat h = dorg - (m1.eigenvectors * g); // h is orthogonal to dorg

	//Some vectors in H can be zero vectors. Must be removed
	cv::Mat sumH = cv::Mat::zeros( 1, H.cols, CV_64FC1 );
	cv::reduce( H.mul(H), sumH, 0, cv::REDUCE_SUM );
	// Even h can be a zero vector. Must not be used if so
	double sumh = 0;
	sumh = h.dot(h);
	//
	// Get indices of sumH > eps. use it to construct vector nu
	cv::Mat newH;
	for( int i=0; i < sumH.cols; i++ )
	{
		if( sumH.at<double>(i) > eps )
			newH.push_back( H.col(i).t() );
	}

	if (sumh > eps)
		newH.push_back( h.t() );

	newH = newH.t();
	// Dimension of newH must be n x t
	std::cout << newH.size() << std::endl;
	
	//TODO : Implement Gram Schmidt Orthonormalization. DONE
	cv::Mat nu = orth( newH );

	//TODO : Forgetting about residues at the moment.
	//Residues are the eigenvalues which were not used in the model m1 / m2.
	//The following was used in matlab for including residues
	//resn1 = size( m1.vct, 1) - size(m1.vct,2 );
	/* if resn1 > 0
  		rpern1 = m1.residue / resn1;
	   else
 		rpern1 = 0;
	   end

		resn2 = size( m2.vct, 1) - size(m2.vct,2 );
		if resn2 > 0
  			rpern2 = m2.residue / resn2;
		else
  			rpern2 = 0;
		end
	*/

	//First part of the matrix in equation (20) in paper - Correlation of m1
	//
	int n,p,t,q;

	n = m1.eigenvectors.rows; // = m2.eigenvectors.rows
	t = nu.cols; //
	p = m1.eigenvalues.rows;
	q = m2.eigenvalues.rows;

	cv::Mat tempeval = cv::Mat::zeros( (p + t) , 1, m1.eigenvalues.type() );
	m1.eigenvalues.copyTo( tempeval.rowRange(0,m1.eigenvalues.rows) );

	cv::Mat A1 = ( N / nObs ) * cv::Mat::diag(tempeval);

	// Correlation of m2
	cv::Mat Gamma = nu.t() * m2.eigenvectors;
	cv::Mat D     = G * cv::Mat::diag( m2.eigenvalues );
	cv::Mat E     = Gamma * cv::Mat::diag( m2.eigenvalues);

	cv::Mat A2 = cv::Mat::zeros( A1.size(), A1.type() );

	A2( cv::Range(0,p), cv::Range(0, p) ) = D * G.t();
	A2( cv::Range(0,p), cv::Range(p, A1.cols) ) = D * Gamma.t();
	A2( cv::Range(p, A1.rows), cv::Range(0,p) ) = E * G.t();
	A2( cv::Range(p, A1.rows), cv::Range(p, A1.cols) ) = E * Gamma.t();

	A2 = A2 * ( M / nObs );

	//Third Part : term for diff between means
	cv::Mat gamma = nu.t() * dorg;
	cv::Mat A3 = cv::Mat( A1.size(), A1.type() );
	
	A3( cv::Range(0,p), cv::Range(0,p) ) = g * g.t();
	A3( cv::Range(0,p), cv::Range(p, A1.cols) ) = g * gamma.t(); 
	A3( cv::Range(p, A1.rows), cv::Range(0,p) ) = gamma * g.t(); 
	A3( cv::Range(p, A1.rows), cv::Range(p, A1.cols) ) = gamma * gamma.t();

	A3 = ( N * M / (nObs*nObs) ) * A3;

	// Guard against rounding errors
	cv::Mat A = A1 + A2 + A3;
	A = ( A + A.t() ) / 2.0;

	/*	(Luca)
		Is this step right? Because PCA expects A to have samples inside, not correlation matrices. We should probably call
		cv::eigen instead

		[m3.vct m3.val] = eig( A ); % the eigen-solution
		m3.vct = [m1.vct nu]* m3.vct; % rotate the basis set into place - can fail for v.high dim data
		m3.val = diag(m3.val);             % keep only the diagonal
	*/
	m3 = cv::PCA( A, cv::noArray(), cv::PCA::DATA_AS_ROW );

	eigenVals = m3.eigenvalues;
	m3.eigenvectors = m3.eigenvectors.t();

	cv::Mat m3Temp = cv::Mat::zeros( n, A.cols, A.type() );

	m3Temp( cv::Range::all(), cv::Range(0,p)) = m1.eigenvectors;
	m3Temp( cv::Range::all(), cv::Range(p, A.cols)) = nu;

	eigenVecs = m3Temp * m3.eigenvectors;

	//Look at how many eigenvalues must be returned. Call that function as required.
	//Calling the function like the matlab code.
	//I'd try not to transpose the eigenvectors in order to be more OpenCV friendly.
	int nValsToKeep = keepVals(KEEP_T,eigenVals,eps);

	eigenVals = eigenVals(cv::Range(0,nValsToKeep),cv::Range::all()).clone();
	eigenVecs = eigenVecs(cv::Range::all(),cv::Range(0,nValsToKeep)).clone();

}
Exemplo n.º 19
0
USING_NAMESPACE_ACADO

int main( ){
	
	// Define variables, functions and constants:
	// ----------------------------------------------------------
    DifferentialState   dT1;
    DifferentialState   dT2;
    DifferentialState   dT3;
    DifferentialState   dT4;
    
    DifferentialState   T1;
    DifferentialState   T2;
    DifferentialState   T3;
    DifferentialState   T4;
    
    DifferentialState   W1;
    DifferentialState   W2;
    DifferentialState   W3;
    DifferentialState   W4;
    
    DifferentialState   q1;
    DifferentialState   q2;
    DifferentialState   q3;
    DifferentialState   q4;
    
    DifferentialState   Omega1;
    DifferentialState   Omega2;
    DifferentialState   Omega3;
    
    DifferentialState   V1;
    DifferentialState   V2;
    DifferentialState   V3;
    
    DifferentialState   P1;		// x
    DifferentialState   P2;		// y
    DifferentialState   P3;		// z
    
    DifferentialState   IP1;
    DifferentialState   IP2;
    DifferentialState   IP3;

    Control             U1;
    Control             U2;
    Control             U3;
    Control             U4;

    DifferentialEquation   f1, f2;   
	
    const double rho = 1.23;
    const double A = 0.1;
    const double Cl = 0.25;
    const double Cd = 0.3*Cl;
    const double m = 10;
    const double g = 9.81;
    const double L  = 0.5;
    const double Jp = 1e-2;
    const double xi = 1e-2;
    const double J1 = 0.25;
    const double J2 = 0.25;
    const double J3 = 1;
    const double gain = 1e-4;

    const double alpha = 0.0;


	// Define the quadcopter ODE model in fully nonlinear form:
	// ----------------------------------------------------------
	f1 << U1*gain; 
	f1 << U2*gain; 
	f1 << U3*gain; 
	f1 << U4*gain; 
	f1 << dT1; 
	f1 << dT2; 
	f1 << dT3; 
	f1 << dT4; 
	f1 << (T1 - W1*xi)/Jp; 
	f1 << (T2 - W2*xi)/Jp; 
	f1 << (T3 - W3*xi)/Jp; 
	f1 << (T4 - W4*xi)/Jp; 
	f1 << - (Omega1*q2)/2 - (Omega2*q3)/2 - (Omega3*q4)/2 - (alpha*q1*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f1 << (Omega1*q1)/2 - (Omega3*q3)/2 + (Omega2*q4)/2 - (alpha*q2*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f1 << (Omega2*q1)/2 + (Omega3*q2)/2 - (Omega1*q4)/2 - (alpha*q3*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f1 << (Omega3*q1)/2 - (Omega2*q2)/2 + (Omega1*q3)/2 - (alpha*q4*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f1 << (J3*Omega2*Omega3 - J2*Omega2*Omega3 + (A*Cl*L*rho*(W2*W2 - W4*W4))/2)/J1; 
	f1 << -(J3*Omega1*Omega3 - J1*Omega1*Omega3 + (A*Cl*L*rho*(W1*W1 - W3*W3))/2)/J2; 
	f1 << (J2*Omega1*Omega2 - J1*Omega1*Omega2 + (A*Cd*rho*(W1*W1 - W2*W2 + W3*W3 - W4*W4))/2)/J3; 
	f1 << (A*Cl*rho*(2*q1*q3 + 2*q2*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); 
	f1 << -(A*Cl*rho*(2*q1*q2 - 2*q3*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); 
	f1 << (A*Cl*rho*(W1*W1 + W2*W2 + W3*W3 + W4*W4)*(q1*q1 - q2*q2 - q3*q3 + q4*q4))/(2*m) - g; 
	f1 << V1; 
	f1 << V2; 
	f1 << V3; 
	f1 << P1; 
	f1 << P2; 
	f1 << P3; 


	// Define the quadcopter ODE model in 3-stage format:
	// ----------------------------------------------------------
	
	// LINEAR INPUT SYSTEM (STAGE 1):
	Matrix M1, A1, B1;
	M1 = eye(12);
	A1 = zeros(12,12);
	B1 = zeros(12,4);
	
	A1(4,0) = 1.0;
	A1(5,1) = 1.0;
	A1(6,2) = 1.0;
	A1(7,3) = 1.0;
	A1(8,4) = 1.0/Jp;	A1(8,8) = -xi/Jp;
	A1(9,5) = 1.0/Jp;	A1(9,9) = -xi/Jp;
	A1(10,6) = 1.0/Jp;	A1(10,10) = -xi/Jp;
	A1(11,7) = 1.0/Jp;	A1(11,11) = -xi/Jp;
	
	B1(0,0) = gain;
	B1(1,1) = gain;
	B1(2,2) = gain;
	B1(3,3) = gain;
	
	// NONLINEAR SYSTEM (STAGE 2):
	f2 << - (Omega1*q2)/2 - (Omega2*q3)/2 - (Omega3*q4)/2 - (alpha*q1*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f2 << (Omega1*q1)/2 - (Omega3*q3)/2 + (Omega2*q4)/2 - (alpha*q2*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f2 << (Omega2*q1)/2 + (Omega3*q2)/2 - (Omega1*q4)/2 - (alpha*q3*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f2 << (Omega3*q1)/2 - (Omega2*q2)/2 + (Omega1*q3)/2 - (alpha*q4*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); 
	f2 << (J3*Omega2*Omega3 - J2*Omega2*Omega3 + (A*Cl*L*rho*(W2*W2 - W4*W4))/2)/J1; 
	f2 << -(J3*Omega1*Omega3 - J1*Omega1*Omega3 + (A*Cl*L*rho*(W1*W1 - W3*W3))/2)/J2; 
	f2 << (J2*Omega1*Omega2 - J1*Omega1*Omega2 + (A*Cd*rho*(W1*W1 - W2*W2 + W3*W3 - W4*W4))/2)/J3; 
	f2 << (A*Cl*rho*(2*q1*q3 + 2*q2*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); 
	f2 << -(A*Cl*rho*(2*q1*q2 - 2*q3*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); 
	f2 << (A*Cl*rho*(W1*W1 + W2*W2 + W3*W3 + W4*W4)*(q1*q1 - q2*q2 - q3*q3 + q4*q4))/(2*m) - g; 
	
	// LINEAR OUTPUT SYSTEM (STAGE 3):
	Matrix M3, A3;
	M3 = eye(6);
	A3 = zeros(6,6);
	
	A3(3,0) = 1.0;
	A3(4,1) = 1.0;
	A3(5,2) = 1.0;
    
    OutputFcn f3;
	
	f3 << V1;
	f3 << V2;
	f3 << V3;
	f3 << 0.0;
	f3 << 0.0;
	f3 << 0.0;


	// ----------------------------------------------------------
	// ----------------------------------------------------------
	SIMexport sim1( 10, 1.0 );
	
	sim1.setModel( f1 );
	sim1.set( INTEGRATOR_TYPE, INT_IRK_GL4 );
	
	sim1.set( NUM_INTEGRATOR_STEPS, 50 );
	sim1.setTimingSteps( 10000 );
	
	acadoPrintf( "-----------------------------------------------------------\n  Using a QuadCopter ODE model in fully nonlinear form:\n-----------------------------------------------------------\n" );
	sim1.exportAndRun( "quadcopter_export", "init_quadcopter.txt", "controls_quadcopter.txt" );


	// ----------------------------------------------------------
	// ----------------------------------------------------------
	SIMexport sim2( 10, 1.0 );
	
	sim2.setLinearInput( M1, A1, B1 );
	sim2.setModel( f2 );
	sim2.setLinearOutput( M3, A3, f3 );
	sim2.set( INTEGRATOR_TYPE, INT_IRK_GL4 );
	
	sim2.set( NUM_INTEGRATOR_STEPS, 50 );
	sim2.setTimingSteps( 10000 );
	
	acadoPrintf( "-----------------------------------------------------------\n  Using a QuadCopter ODE model in 3-stage format:\n-----------------------------------------------------------\n" );
	sim2.exportAndRun( "quadcopter_export", "init_quadcopter.txt", "controls_quadcopter.txt" );


	return 0;
}
Exemplo n.º 20
0
 int main(void){
 Marray<double,3> A3(3,3,3);
 Marray<double,2> B2(3,3);
 Marray<double,1> C1Test(3);
 Marray<double,1> C1(3);
 A3.sucesion(0,1);
 B2.sucesion(0,1);
 Index<'i'> iG;
 Index<'j'> jG;
 Index<'k'> kG;
 for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C1(i)+=A3(i,j,k)*B2(j,k);
          }
     }
 }

C1Test(iG)=A3(iG,jG,kG)*B2(jG,kG);
assert(C1==C1Test);


C1=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C1(i)+=A3(i,j,k)*B2(k,j);
          }
     }
 }

C1Test(iG)=A3(iG,jG,kG)*B2(kG,jG);
assert(C1==C1Test);


C1=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C1(i)+=A3(j,i,k)*B2(j,k);
          }
     }
 }

C1Test(iG)=A3(jG,iG,kG)*B2(jG,kG);
assert(C1==C1Test);


C1=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C1(i)+=A3(j,i,k)*B2(k,j);
          }
     }
 }

C1Test(iG)=A3(jG,iG,kG)*B2(kG,jG);
assert(C1==C1Test);


C1=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C1(i)+=A3(j,k,i)*B2(j,k);
          }
     }
 }

C1Test(iG)=A3(jG,kG,iG)*B2(jG,kG);
assert(C1==C1Test);


C1=0;


for (int i=0;i<3;i++) {
     for (int j=0;j<3;j++){
         for(int k=0;k<3;k++){
               C1(i)+=A3(j,k,i)*B2(k,j);
          }
     }
 }

C1Test(iG)=A3(jG,kG,iG)*B2(kG,jG);
assert(C1==C1Test);


C1=0;


}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
  int ierr = 0, forierr = 0;
  bool debug = false;

#ifdef EPETRA_MPI

  // Initialize MPI

  MPI_Init(&argc,&argv);
  int rank; // My process ID

  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  Epetra_MpiComm Comm( MPI_COMM_WORLD );

#else

  int rank = 0;
  Epetra_SerialComm Comm;

#endif

  bool verbose = false;

  // Check if we should print results to standard out
  if (argc>1) if (argv[1][0]=='-' && argv[1][1]=='v') verbose = true;

  int verbose_int = verbose ? 1 : 0;
  Comm.Broadcast(&verbose_int, 1, 0);
  verbose = verbose_int==1 ? true : false;


  //  char tmp;
  //  if (rank==0) cout << "Press any key to continue..."<< std::endl;
  //  if (rank==0) cin >> tmp;
  //  Comm.Barrier();

  Comm.SetTracebackMode(0); // This should shut down any error traceback reporting
  int MyPID = Comm.MyPID();
  int NumProc = Comm.NumProc();

  if(verbose && MyPID==0)
    cout << Epetra_Version() << std::endl << std::endl;

  if (verbose) cout << "Processor "<<MyPID<<" of "<< NumProc
		    << " is alive."<<endl;

  bool verbose1 = verbose;

  // Redefine verbose to only print on PE 0
  if(verbose && rank!=0) 
		verbose = false;

  int NumMyEquations = 10000;
  int NumGlobalEquations = (NumMyEquations * NumProc) + EPETRA_MIN(NumProc,3);
  if(MyPID < 3) 
    NumMyEquations++;

  // Construct a Map that puts approximately the same Number of equations on each processor

  Epetra_Map Map(NumGlobalEquations, NumMyEquations, 0, Comm);
  
  // Get update list and number of local equations from newly created Map
  int* MyGlobalElements = new int[Map.NumMyElements()];
  Map.MyGlobalElements(MyGlobalElements);

  // Create an integer vector NumNz that is used to build the Petra Matrix.
  // NumNz[i] is the Number of OFF-DIAGONAL term for the ith global equation on this processor

  int* NumNz = new int[NumMyEquations];

  // We are building a tridiagonal matrix where each row has (-1 2 -1)
  // So we need 2 off-diagonal terms (except for the first and last equation)

  for (int i = 0; i < NumMyEquations; i++)
    if((MyGlobalElements[i] == 0) || (MyGlobalElements[i] == NumGlobalEquations - 1))
      NumNz[i] = 1;
    else
      NumNz[i] = 2;

  // Create a Epetra_Matrix

  Epetra_CrsMatrix A(Copy, Map, NumNz);
  EPETRA_TEST_ERR(A.IndicesAreGlobal(),ierr);
  EPETRA_TEST_ERR(A.IndicesAreLocal(),ierr);
  
  // Add  rows one-at-a-time
  // Need some vectors to help
  // Off diagonal Values will always be -1


  double* Values = new double[2];
  Values[0] = -1.0; 
	Values[1] = -1.0;
  int* Indices = new int[2];
  double two = 2.0;
  int NumEntries;

  forierr = 0;
  for (int i = 0; i < NumMyEquations; i++) {
    if(MyGlobalElements[i] == 0) {
			Indices[0] = 1;
			NumEntries = 1;
		}
    else if (MyGlobalElements[i] == NumGlobalEquations-1) {
			Indices[0] = NumGlobalEquations-2;
			NumEntries = 1;
		}
    else {
			Indices[0] = MyGlobalElements[i]-1;
			Indices[1] = MyGlobalElements[i]+1;
			NumEntries = 2;
		}
		forierr += !(A.InsertGlobalValues(MyGlobalElements[i], NumEntries, Values, Indices)==0);
		forierr += !(A.InsertGlobalValues(MyGlobalElements[i], 1, &two, MyGlobalElements+i)>0); // Put in the diagonal entry
  }
  EPETRA_TEST_ERR(forierr,ierr);

  int * indexOffsetTmp;
  int * indicesTmp;
  double * valuesTmp;
  // Finish up
  EPETRA_TEST_ERR(!(A.IndicesAreGlobal()),ierr);
  EPETRA_TEST_ERR(!(A.ExtractCrsDataPointers(indexOffsetTmp, indicesTmp, valuesTmp)==-1),ierr);  // Should fail
  EPETRA_TEST_ERR(!(A.FillComplete(false)==0),ierr);
  EPETRA_TEST_ERR(!(A.ExtractCrsDataPointers(indexOffsetTmp, indicesTmp, valuesTmp)==-1),ierr);  // Should fail
  EPETRA_TEST_ERR(!(A.IndicesAreLocal()),ierr);
  EPETRA_TEST_ERR(A.StorageOptimized(),ierr);
  A.OptimizeStorage();
  EPETRA_TEST_ERR(!(A.StorageOptimized()),ierr);
  EPETRA_TEST_ERR(!(A.ExtractCrsDataPointers(indexOffsetTmp, indicesTmp, valuesTmp)==0),ierr);  // Should succeed
  const Epetra_CrsGraph & GofA = A.Graph();
  EPETRA_TEST_ERR((indicesTmp!=GofA[0] || valuesTmp!=A[0]),ierr); // Extra check to see if operator[] is consistent
  EPETRA_TEST_ERR(A.UpperTriangular(),ierr);
  EPETRA_TEST_ERR(A.LowerTriangular(),ierr);
	
  int NumMyNonzeros = 3 * NumMyEquations;
  if(A.LRID(0) >= 0) 
		NumMyNonzeros--; // If I own first global row, then there is one less nonzero
  if(A.LRID(NumGlobalEquations-1) >= 0) 
		NumMyNonzeros--; // If I own last global row, then there is one less nonzero
  EPETRA_TEST_ERR(check(A, NumMyEquations, NumGlobalEquations, NumMyNonzeros, 3*NumGlobalEquations-2, 
	       MyGlobalElements, verbose),ierr);
  forierr = 0;
  for (int i = 0; i < NumMyEquations; i++) 
		forierr += !(A.NumGlobalEntries(MyGlobalElements[i])==NumNz[i]+1);
  EPETRA_TEST_ERR(forierr,ierr);
  forierr = 0;
  for (int i = 0; i < NumMyEquations; i++) 
		forierr += !(A.NumMyEntries(i)==NumNz[i]+1);
  EPETRA_TEST_ERR(forierr,ierr);

  if (verbose) cout << "\n\nNumEntries function check OK" << std::endl<< std::endl;

  EPETRA_TEST_ERR(check_graph_sharing(Comm),ierr);

  // Create vectors for Power method

  Epetra_Vector q(Map);
  Epetra_Vector z(Map);
  Epetra_Vector resid(Map);

  // variable needed for iteration
  double lambda = 0.0;
  // int niters = 10000;
  int niters = 200;
  double tolerance = 1.0e-1;

  /////////////////////////////////////////////////////////////////////////////////////////////////
	
  // Iterate

  Epetra_Flops flopcounter;
  A.SetFlopCounter(flopcounter);
  q.SetFlopCounter(A);
  z.SetFlopCounter(A);
  resid.SetFlopCounter(A);
	

  Epetra_Time timer(Comm);
  EPETRA_TEST_ERR(power_method(false, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr);
  double elapsed_time = timer.ElapsedTime();
  double total_flops = A.Flops() + q.Flops() + z.Flops() + resid.Flops();
  double MFLOPs = total_flops/elapsed_time/1000000.0;

  if (verbose) cout << "\n\nTotal MFLOPs for first solve = " << MFLOPs << std::endl<< std::endl;

  /////////////////////////////////////////////////////////////////////////////////////////////////
	
  // Solve transpose problem

  if (verbose) cout << "\n\nUsing transpose of matrix and solving again (should give same result).\n\n"
		    << std::endl;
  // Iterate
  lambda = 0.0;
  flopcounter.ResetFlops();
  timer.ResetStartTime();
  EPETRA_TEST_ERR(power_method(true, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr);
  elapsed_time = timer.ElapsedTime();
  total_flops = A.Flops() + q.Flops() + z.Flops() + resid.Flops();
  MFLOPs = total_flops/elapsed_time/1000000.0;

  if (verbose) cout << "\n\nTotal MFLOPs for transpose solve = " << MFLOPs << std::endl<< endl;

  /////////////////////////////////////////////////////////////////////////////////////////////////

  // Increase diagonal dominance

  if (verbose) cout << "\n\nIncreasing the magnitude of first diagonal term and solving again\n\n"
		    << endl;

  
  if (A.MyGlobalRow(0)) {
    int numvals = A.NumGlobalEntries(0);
    double * Rowvals = new double [numvals];
    int    * Rowinds = new int    [numvals];
    A.ExtractGlobalRowCopy(0, numvals, numvals, Rowvals, Rowinds); // Get A[0,0]

    for (int i=0; i<numvals; i++) if (Rowinds[i] == 0) Rowvals[i] *= 10.0;
    
    A.ReplaceGlobalValues(0, numvals, Rowvals, Rowinds);
    delete [] Rowvals;
    delete [] Rowinds;
  }
  // Iterate (again)
  lambda = 0.0;
  flopcounter.ResetFlops();
  timer.ResetStartTime();
  EPETRA_TEST_ERR(power_method(false, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr);
  elapsed_time = timer.ElapsedTime();
  total_flops = A.Flops() + q.Flops() + z.Flops() + resid.Flops();
  MFLOPs = total_flops/elapsed_time/1000000.0;

  if (verbose) cout << "\n\nTotal MFLOPs for second solve = " << MFLOPs << endl<< endl;

  /////////////////////////////////////////////////////////////////////////////////////////////////

  // Solve transpose problem

  if (verbose) cout << "\n\nUsing transpose of matrix and solving again (should give same result).\n\n"
		    << endl;

  // Iterate (again)
  lambda = 0.0;
  flopcounter.ResetFlops();
  timer.ResetStartTime();
  EPETRA_TEST_ERR(power_method(true, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr);
  elapsed_time = timer.ElapsedTime();
  total_flops = A.Flops() + q.Flops() + z.Flops() + resid.Flops();
  MFLOPs = total_flops/elapsed_time/1000000.0;


  if (verbose) cout << "\n\nTotal MFLOPs for tranpose of second solve = " << MFLOPs << endl<< endl;

  if (verbose) cout << "\n\n*****Testing constant entry constructor" << endl<< endl;

  Epetra_CrsMatrix AA(Copy, Map, 5);
  
  if (debug) Comm.Barrier();

  double dble_one = 1.0;
  for (int i=0; i< NumMyEquations; i++) AA.InsertGlobalValues(MyGlobalElements[i], 1, &dble_one, MyGlobalElements+i);

  // Note:  All processors will call the following Insert routines, but only the processor
  //        that owns it will actually do anything

  int One = 1;
  if (AA.MyGlobalRow(0)) {
    EPETRA_TEST_ERR(!(AA.InsertGlobalValues(0, 0, &dble_one, &One)==0),ierr);
  }
  else EPETRA_TEST_ERR(!(AA.InsertGlobalValues(0, 1, &dble_one, &One)==-1),ierr);
  EPETRA_TEST_ERR(!(AA.FillComplete(false)==0),ierr);
  EPETRA_TEST_ERR(AA.StorageOptimized(),ierr);
  EPETRA_TEST_ERR(!(AA.UpperTriangular()),ierr);
  EPETRA_TEST_ERR(!(AA.LowerTriangular()),ierr);
  
  if (debug) Comm.Barrier();
  EPETRA_TEST_ERR(check(AA, NumMyEquations, NumGlobalEquations, NumMyEquations, NumGlobalEquations, 
	       MyGlobalElements, verbose),ierr);

  if (debug) Comm.Barrier();

  forierr = 0;
  for (int i=0; i<NumMyEquations; i++) forierr += !(AA.NumGlobalEntries(MyGlobalElements[i])==1);
  EPETRA_TEST_ERR(forierr,ierr);

  if (verbose) cout << "\n\nNumEntries function check OK" << endl<< endl;

  if (debug) Comm.Barrier();

  if (verbose) cout << "\n\n*****Testing copy constructor" << endl<< endl;

  Epetra_CrsMatrix B(AA);
  EPETRA_TEST_ERR(check(B, NumMyEquations, NumGlobalEquations, NumMyEquations, NumGlobalEquations, 
	       MyGlobalElements, verbose),ierr);

  forierr = 0;
  for (int i=0; i<NumMyEquations; i++) forierr += !(B.NumGlobalEntries(MyGlobalElements[i])==1);
  EPETRA_TEST_ERR(forierr,ierr);

  if (verbose) cout << "\n\nNumEntries function check OK" << endl<< endl;

  if (debug) Comm.Barrier();

  if (verbose) cout << "\n\n*****Testing local view constructor" << endl<< endl;

  Epetra_CrsMatrix BV(View, AA.RowMap(), AA.ColMap(), 0);

  forierr = 0;
  int* Inds;
  double* Vals;
  for (int i = 0; i < NumMyEquations; i++) {
    forierr += !(AA.ExtractMyRowView(i, NumEntries, Vals, Inds)==0);
    forierr += !(BV.InsertMyValues(i, NumEntries, Vals, Inds)==0);
  }
  BV.FillComplete(false);
  EPETRA_TEST_ERR(check(BV, NumMyEquations, NumGlobalEquations, NumMyEquations, NumGlobalEquations, 
												MyGlobalElements, verbose),ierr);

  forierr = 0;
  for (int i=0; i<NumMyEquations; i++) forierr += !(BV.NumGlobalEntries(MyGlobalElements[i])==1);
  EPETRA_TEST_ERR(forierr,ierr);

  if (verbose) cout << "\n\nNumEntries function check OK" << endl<< endl;

  if (debug) Comm.Barrier();
  if (verbose) cout << "\n\n*****Testing post construction modifications" << endl<< endl;

  EPETRA_TEST_ERR(!(B.InsertGlobalValues(0, 1, &dble_one, &One)==-2),ierr);


  // Release all objects
  delete [] NumNz;
  delete [] Values;
  delete [] Indices;
  delete [] MyGlobalElements;
			

  if (verbose1) {
    // Test ostream << operator (if verbose1)
    // Construct a Map that puts 2 equations on each PE
    
    int NumMyElements1 = 2;
    int NumMyEquations1 = NumMyElements1;
    int NumGlobalEquations1 = NumMyEquations1*NumProc;

    Epetra_Map Map1(-1, NumMyElements1, 0, Comm);
    
    // Get update list and number of local equations from newly created Map
    int * MyGlobalElements1 = new int[Map1.NumMyElements()];
    Map1.MyGlobalElements(MyGlobalElements1);
    
    // Create an integer vector NumNz that is used to build the Petra Matrix.
    // NumNz[i] is the Number of OFF-DIAGONAL term for the ith global equation on this processor
    
    int * NumNz1 = new int[NumMyEquations1];
    
    // We are building a tridiagonal matrix where each row has (-1 2 -1)
    // So we need 2 off-diagonal terms (except for the first and last equation)
    
    for (int i=0; i<NumMyEquations1; i++)
      if (MyGlobalElements1[i]==0 || MyGlobalElements1[i] == NumGlobalEquations1-1)
	NumNz1[i] = 1;
      else
	NumNz1[i] = 2;
    
    // Create a Epetra_Matrix
    
    Epetra_CrsMatrix A1(Copy, Map1, NumNz1);
    
    // Add  rows one-at-a-time
    // Need some vectors to help
    // Off diagonal Values will always be -1
    
    
    double *Values1 = new double[2];
    Values1[0] = -1.0; Values1[1] = -1.0;
    int *Indices1 = new int[2];
    double two1 = 2.0;
    int NumEntries1;

    forierr = 0;
    for (int i=0; i<NumMyEquations1; i++)
      {
	if (MyGlobalElements1[i]==0)
	  {
	    Indices1[0] = 1;
	    NumEntries1 = 1;
	  }
	else if (MyGlobalElements1[i] == NumGlobalEquations1-1)
	  {
	    Indices1[0] = NumGlobalEquations1-2;
	    NumEntries1 = 1;
	  }
	else
	  {
	    Indices1[0] = MyGlobalElements1[i]-1;
	    Indices1[1] = MyGlobalElements1[i]+1;
	    NumEntries1 = 2;
	  }
	forierr += !(A1.InsertGlobalValues(MyGlobalElements1[i], NumEntries1, Values1, Indices1)==0);
	forierr += !(A1.InsertGlobalValues(MyGlobalElements1[i], 1, &two1, MyGlobalElements1+i)>0); // Put in the diagonal entry
      }
    EPETRA_TEST_ERR(forierr,ierr);
    delete [] Indices1;
    delete [] Values1;
    
    // Finish up
    EPETRA_TEST_ERR(!(A1.FillComplete(false)==0),ierr);
    
    // Test diagonal extraction function

    Epetra_Vector checkDiag(Map1);
    EPETRA_TEST_ERR(!(A1.ExtractDiagonalCopy(checkDiag)==0),ierr);

    forierr = 0;
    for (int i=0; i<NumMyEquations1; i++) forierr += !(checkDiag[i]==two1);
    EPETRA_TEST_ERR(forierr,ierr);

    // Test diagonal replacement method

    forierr = 0;
    for (int i=0; i<NumMyEquations1; i++) checkDiag[i]=two1*two1;
    EPETRA_TEST_ERR(forierr,ierr);

    EPETRA_TEST_ERR(!(A1.ReplaceDiagonalValues(checkDiag)==0),ierr);

    Epetra_Vector checkDiag1(Map1);
    EPETRA_TEST_ERR(!(A1.ExtractDiagonalCopy(checkDiag1)==0),ierr);

    forierr = 0;
    for (int i=0; i<NumMyEquations1; i++) forierr += !(checkDiag[i]==checkDiag1[i]);
    EPETRA_TEST_ERR(forierr,ierr);

    if (verbose) cout << "\n\nDiagonal extraction and replacement OK.\n\n" << endl;

    double orignorm = A1.NormOne();
    EPETRA_TEST_ERR(!(A1.Scale(4.0)==0),ierr);
    EPETRA_TEST_ERR(!(A1.NormOne()!=orignorm),ierr);
    
    if (verbose) cout << "\n\nMatrix scale OK.\n\n" << endl;

    if (verbose) cout << "\n\nPrint out tridiagonal matrix, each part on each processor.\n\n" << endl;
    cout << A1 << endl;
   

  // Release all objects
  delete [] NumNz1;
  delete [] MyGlobalElements1;

  }

  if (verbose) cout << "\n\n*****Testing LeftScale and RightScale" << endl << endl;

  int NumMyElements2 = 7;
  int NumMyRows2 = 1;//This value should not be changed without editing the
		// code below.
  Epetra_Map RowMap(-1,NumMyRows2,0,Comm);
  Epetra_Map ColMap(NumMyElements2,NumMyElements2,0,Comm);
  // The DomainMap needs to be different from the ColMap for the test to 
  // be meaningful.
  Epetra_Map DomainMap(NumMyElements2,0,Comm);
  int NumMyRangeElements2 = 0;
  // We need to distribute the elements differently for the range map also.
  if (MyPID % 2 == 0)
    NumMyRangeElements2 = NumMyRows2*2; //put elements on even number procs 
  if (NumProc % 2 == 1 && MyPID == NumProc-1)
    NumMyRangeElements2 = NumMyRows2; //If number of procs is odd, put
			// the last NumMyElements2 elements on the last proc
  Epetra_Map RangeMap(-1,NumMyRangeElements2,0,Comm);
  Epetra_CrsMatrix A2(Copy,RowMap,ColMap,NumMyElements2);
  double * Values2 = new double[NumMyElements2];
  int * Indices2 = new int[NumMyElements2]; 

  for (int i=0; i<NumMyElements2; i++) {
    Values2[i] = i+MyPID;
    Indices2[i]=i;
  }

  A2.InsertMyValues(0,NumMyElements2,Values2,Indices2);
  A2.FillComplete(DomainMap,RangeMap,false);
  Epetra_CrsMatrix A2copy(A2);

  double * RowLeftScaleValues = new double[NumMyRows2];
  double * ColRightScaleValues = new double[NumMyElements2];
  int RowLoopLength = RowMap.MaxMyGID()-RowMap.MinMyGID()+1;
  for (int i=0; i<RowLoopLength; i++)
    RowLeftScaleValues[i] = (i + RowMap.MinMyGID() ) % 2 + 1;
  // For the column map, all procs own all elements
  for (int  i=0; i<NumMyElements2;i++)
    ColRightScaleValues[i] = i % 2 + 1;

  int RangeLoopLength = RangeMap.MaxMyGID()-RangeMap.MinMyGID()+1;
  double * RangeLeftScaleValues = new double[RangeLoopLength];
  int DomainLoopLength = DomainMap.MaxMyGID()-DomainMap.MinMyGID()+1;
   double * DomainRightScaleValues = new double[DomainLoopLength];
  for (int i=0; i<RangeLoopLength; i++)
    RangeLeftScaleValues[i] = 1.0/((i + RangeMap.MinMyGID() ) % 2 + 1);
  for (int  i=0; i<DomainLoopLength;i++)
    DomainRightScaleValues[i] = 1.0/((i + DomainMap.MinMyGID() ) % 2 + 1);
                                                                                
  Epetra_Vector xRow(View,RowMap,RowLeftScaleValues);
  Epetra_Vector xCol(View,ColMap,ColRightScaleValues);
  Epetra_Vector xRange(View,RangeMap,RangeLeftScaleValues);
  Epetra_Vector xDomain(View,DomainMap,DomainRightScaleValues);

  double A2infNorm = A2.NormInf();
  double A2oneNorm = A2.NormOne();

  if (verbose1) cout << A2;
  EPETRA_TEST_ERR(A2.LeftScale(xRow),ierr);
  double A2infNorm1 = A2.NormInf();
  double A2oneNorm1 = A2.NormOne();
  bool ScalingBroke = false;
  if (A2infNorm1>2*A2infNorm||A2infNorm1<A2infNorm) {
    EPETRA_TEST_ERR(-31,ierr);
    ScalingBroke = true;
  }
  if (A2oneNorm1>2*A2oneNorm||A2oneNorm1<A2oneNorm) {

    EPETRA_TEST_ERR(-32,ierr);
    ScalingBroke = true;
  }
  if (verbose1) cout << A2;
  EPETRA_TEST_ERR(A2.RightScale(xCol),ierr);
  double A2infNorm2 = A2.NormInf();
  double A2oneNorm2 = A2.NormOne();
  if (A2infNorm2>=2*A2infNorm1||A2infNorm2<=A2infNorm1) {
    EPETRA_TEST_ERR(-33,ierr);
    ScalingBroke = true;
  }
  if (A2oneNorm2>2*A2oneNorm1||A2oneNorm2<=A2oneNorm1) {
    EPETRA_TEST_ERR(-34,ierr);
    ScalingBroke = true;
  }
  if (verbose1) cout << A2;
  EPETRA_TEST_ERR(A2.RightScale(xDomain),ierr);
  double A2infNorm3 = A2.NormInf();
  double A2oneNorm3 = A2.NormOne();
  // The last two scaling ops cancel each other out
  if (A2infNorm3!=A2infNorm1) {
    EPETRA_TEST_ERR(-35,ierr)
    ScalingBroke = true;
  }
  if (A2oneNorm3!=A2oneNorm1) {
    EPETRA_TEST_ERR(-36,ierr)
    ScalingBroke = true;
  }
  if (verbose1) cout << A2;
  EPETRA_TEST_ERR(A2.LeftScale(xRange),ierr);
  double A2infNorm4 = A2.NormInf();
  double A2oneNorm4 = A2.NormOne();
  // The 4 scaling ops all cancel out
  if (A2infNorm4!=A2infNorm) {
    EPETRA_TEST_ERR(-37,ierr)
    ScalingBroke = true;
  }
  if (A2oneNorm4!=A2oneNorm) {
    EPETRA_TEST_ERR(-38,ierr)
    ScalingBroke = true;
  }

  //
  //  Now try changing the values underneath and make sure that 
  //  telling one process about the change causes NormInf() and 
  //  NormOne() to recompute the norm on all processes.
  //
  
  double *values; 
  int num_my_rows = A2.NumMyRows() ; 
  int num_entries;

  for ( int  i=0 ; i< num_my_rows; i++ ) {
    EPETRA_TEST_ERR( A2.ExtractMyRowView( i, num_entries, values ), ierr );
    for ( int j = 0 ; j <num_entries; j++ ) {
      values[j] *= 2.0; 
    }
  }


  if ( MyPID == 0 )
    A2.SumIntoGlobalValues( 0, 0, 0, 0 ) ; 

  double A2infNorm5 = A2.NormInf();
  double A2oneNorm5 = A2.NormOne();

  if (A2infNorm5!=2.0 * A2infNorm4) {
    EPETRA_TEST_ERR(-39,ierr)
    ScalingBroke = true;
  }
  if (A2oneNorm5!= 2.0 * A2oneNorm4) {
    EPETRA_TEST_ERR(-40,ierr)
    ScalingBroke = true;
  }

  //
  //  Restore the values underneath
  //
  for ( int  i=0 ; i< num_my_rows; i++ ) {
    EPETRA_TEST_ERR( A2.ExtractMyRowView( i, num_entries, values ), ierr );
    for ( int j = 0 ; j <num_entries; j++ ) {
      values[j] /= 2.0; 
    }
  }

  if (verbose1) cout << A2;

  if (ScalingBroke) {
    if (verbose) cout << endl << "LeftScale and RightScale tests FAILED" << endl << endl;
  }
  else {
    if (verbose) cout << endl << "LeftScale and RightScale tests PASSED" << endl << endl;
  }

  Comm.Barrier();

  if (verbose) cout << "\n\n*****Testing InvRowMaxs and InvColMaxs" << endl << endl;

  if (verbose1) cout << A2 << endl;
  EPETRA_TEST_ERR(A2.InvRowMaxs(xRow),ierr);
  EPETRA_TEST_ERR(A2.InvRowMaxs(xRange),ierr);
  if (verbose1) cout << xRow << endl << xRange << endl;

  if (verbose) cout << "\n\n*****Testing InvRowSums and InvColSums" << endl << endl;
  bool InvSumsBroke = false;
// Works!
  EPETRA_TEST_ERR(A2.InvRowSums(xRow),ierr);
  if (verbose1) cout << xRow;
  EPETRA_TEST_ERR(A2.LeftScale(xRow),ierr);
  float A2infNormFloat = A2.NormInf();
  if (verbose1) cout << A2 << endl;
  if (fabs(1.0-A2infNormFloat) > 1.e-5) {
    EPETRA_TEST_ERR(-41,ierr);
    InvSumsBroke = true;
  }

  // Works
  int expectedcode = 1;
  if (Comm.NumProc()>1) expectedcode = 0;
  EPETRA_TEST_ERR(!(A2.InvColSums(xDomain)==expectedcode),ierr); // This matrix has a single row, the first column has a zero, so a warning is issued.
  if (verbose1) cout << xDomain << endl;
  EPETRA_TEST_ERR(A2.RightScale(xDomain),ierr);
  float A2oneNormFloat2 = A2.NormOne();
  if (verbose1) cout << A2;
  if (fabs(1.0-A2oneNormFloat2)>1.e-5) {
    EPETRA_TEST_ERR(-42,ierr)
    InvSumsBroke = true;
  }

// Works!
  EPETRA_TEST_ERR(A2.InvRowSums(xRange),ierr);

  if (verbose1) cout << xRange;
  EPETRA_TEST_ERR(A2.LeftScale(xRange),ierr);
  float A2infNormFloat2 = A2.NormInf(); // We use a float so that rounding error
	// will not prevent the sum from being 1.0.
  if (verbose1) cout << A2;
  if (fabs(1.0-A2infNormFloat2)>1.e-5) {
    cout << "InfNorm should be = 1, but InfNorm = " << A2infNormFloat2 << endl;
    EPETRA_TEST_ERR(-43,ierr);
    InvSumsBroke = true;
  }

  // Doesn't work - may not need this test because column ownership is not unique
  /*  EPETRA_TEST_ERR(A2.InvColSums(xCol),ierr);
cout << xCol;
  EPETRA_TEST_ERR(A2.RightScale(xCol),ierr);
  float A2oneNormFloat = A2.NormOne();
cout << A2;
  if (fabs(1.0-A2oneNormFloat)>1.e-5) {
    EPETRA_TEST_ERR(-44,ierr);
    InvSumsBroke = true;
  }
  */
  delete [] ColRightScaleValues;
  delete [] DomainRightScaleValues;
  if (verbose) cout << "Begin partial sum testing." << endl;
  // Test with a matrix that has partial sums for a subset of the rows 
  // on multiple processors. (Except for the serial case, of course.)
  int NumMyRows3 = 2; // Changing this requires further changes below
  int * myGlobalElements = new int[NumMyRows3];
  for (int i=0; i<NumMyRows3; i++) myGlobalElements[i] = MyPID+i;
  Epetra_Map RowMap3(NumProc*2, NumMyRows3, myGlobalElements, 0, Comm);
  int NumMyElements3 = 5;
  Epetra_CrsMatrix A3(Copy, RowMap3, NumMyElements3);
  double * Values3 = new double[NumMyElements3];
  int * Indices3 = new int[NumMyElements3];
  for (int i=0; i < NumMyElements3; i++) {
    Values3[i] = (int) (MyPID + (i+1));
    Indices3[i]=i;
  }
  for (int i=0; i<NumMyRows3; i++) {
    A3.InsertGlobalValues(myGlobalElements[i],NumMyElements3,Values3,Indices3);
  }
  Epetra_Map RangeMap3(NumProc+1, 0, Comm);
  Epetra_Map DomainMap3(NumMyElements3, 0, Comm);
  EPETRA_TEST_ERR(A3.FillComplete(DomainMap3, RangeMap3,false),ierr);
  if (verbose1) cout << A3;
  Epetra_Vector xRange3(RangeMap3,false);
  Epetra_Vector xDomain3(DomainMap3,false);

  EPETRA_TEST_ERR(A3.InvRowSums(xRange3),ierr);

  if (verbose1) cout << xRange3;
  EPETRA_TEST_ERR(A3.LeftScale(xRange3),ierr);
  float A3infNormFloat = A3.NormInf();
  if (verbose1) cout << A3;
  if (1.0!=A3infNormFloat) {
    cout << "InfNorm should be = 1, but InfNorm = " << A3infNormFloat <<endl;
    EPETRA_TEST_ERR(-61,ierr);
    InvSumsBroke = true;
  }
  // we want to take the transpose of our matrix and fill in different values.
  int NumMyColumns3 = NumMyRows3;
  Epetra_Map ColMap3cm(RowMap3); 
  Epetra_Map RowMap3cm(A3.ColMap());

  Epetra_CrsMatrix A3cm(Copy,RowMap3cm,ColMap3cm,NumProc+1);
  double *Values3cm = new double[NumMyColumns3];
  int * Indices3cm = new int[NumMyColumns3];
  for (int i=0; i<NumMyColumns3; i++) {
    Values3cm[i] = MyPID + i + 1;
    Indices3cm[i]= i + MyPID;
  }
  for (int ii=0; ii<NumMyElements3; ii++) {
    A3cm.InsertGlobalValues(ii, NumMyColumns3, Values3cm, Indices3cm);
  }

  // The DomainMap and the RangeMap from the last test will work fine for 
  // the RangeMap and DomainMap, respectively, but I will make copies to
  // avaoid confusion when passing what looks like a DomainMap where we
  // need a RangeMap and vice vera.
  Epetra_Map RangeMap3cm(DomainMap3);
  Epetra_Map DomainMap3cm(RangeMap3);
  EPETRA_TEST_ERR(A3cm.FillComplete(DomainMap3cm,RangeMap3cm),ierr);
  if (verbose1) cout << A3cm << endl;

  // Again, we can copy objects from the last example.
  //Epetra_Vector xRange3cm(xDomain3); //Don't use at this time
  Epetra_Vector xDomain3cm(DomainMap3cm,false);

  EPETRA_TEST_ERR(A3cm.InvColSums(xDomain3cm),ierr);

  if (verbose1) cout << xDomain3cm << endl;

  EPETRA_TEST_ERR(A3cm.RightScale(xDomain3cm),ierr);
  float A3cmOneNormFloat  = A3cm.NormOne();
  if (verbose1) cout << A3cm << endl;
  if (1.0!=A3cmOneNormFloat) {
    cout << "OneNorm should be = 1, but OneNorm = " << A3cmOneNormFloat << endl;
    EPETRA_TEST_ERR(-62,ierr);
    InvSumsBroke = true;
  }
  
  if (verbose) cout << "End partial sum testing" << endl;
  if (verbose) cout << "Begin replicated testing" << endl;

  // We will now view the shared row as a repliated row, rather than one 
  // that has partial sums of its entries on mulitple processors.
  // We will reuse much of the data used for the partial sum tesitng.
  Epetra_Vector xRow3(RowMap3,false); 
  Epetra_CrsMatrix A4(Copy, RowMap3, NumMyElements3);
  for (int ii=0; ii < NumMyElements3; ii++) {
    Values3[ii] = (int)((ii*.6)+1.0);
  }
  for (int ii=0; ii<NumMyRows3; ii++) {
    A4.InsertGlobalValues(myGlobalElements[ii],NumMyElements3,Values3,Indices3);
  }
  EPETRA_TEST_ERR(A4.FillComplete(DomainMap3, RangeMap3,false),ierr);
  if (verbose1) cout << A4 << endl;
  // The next two lines should be expanded into a verifiable test.
  EPETRA_TEST_ERR(A4.InvRowMaxs(xRow3),ierr);
  EPETRA_TEST_ERR(A4.InvRowMaxs(xRange3),ierr);
  if (verbose1) cout << xRow3 << xRange3;

  EPETRA_TEST_ERR(A4.InvRowSums(xRow3),ierr);                      
  if (verbose1) cout << xRow3;
  EPETRA_TEST_ERR(A4.LeftScale(xRow3),ierr);
  float A4infNormFloat = A4.NormInf();
  if (verbose1) cout << A4;
  if (2.0!=A4infNormFloat && NumProc != 1) {
    if (verbose1) cout << "InfNorm should be = 2 (because one column is replicated on two processors and NormOne() does not handle replication), but InfNorm = " << A4infNormFloat <<endl;
    EPETRA_TEST_ERR(-63,ierr);
    InvSumsBroke = true;
  }
  else if (1.0!=A4infNormFloat && NumProc == 1) {
    if (verbose1) cout << "InfNorm should be = 1, but InfNorm = " << A4infNormFloat <<endl;
    EPETRA_TEST_ERR(-63,ierr);
    InvSumsBroke = true;
  }
  
  Epetra_Vector xCol3cm(ColMap3cm,false);
  Epetra_CrsMatrix A4cm(Copy, RowMap3cm, ColMap3cm, NumProc+1);
  //Use values from A3cm
  for (int ii=0; ii<NumMyElements3; ii++) {
    A4cm.InsertGlobalValues(ii,NumMyColumns3,Values3cm,Indices3cm);
  }
  EPETRA_TEST_ERR(A4cm.FillComplete(DomainMap3cm, RangeMap3cm,false),ierr);
  if (verbose1) cout << A4cm << endl;
  // The next two lines should be expanded into a verifiable test.
  EPETRA_TEST_ERR(A4cm.InvColMaxs(xCol3cm),ierr);
  EPETRA_TEST_ERR(A4cm.InvColMaxs(xDomain3cm),ierr);
  if (verbose1) cout << xCol3cm << xDomain3cm;

  EPETRA_TEST_ERR(A4cm.InvColSums(xCol3cm),ierr);
 
  if (verbose1) cout << xCol3cm << endl;
  EPETRA_TEST_ERR(A4cm.RightScale(xCol3cm),ierr);
  float A4cmOneNormFloat = A4cm.NormOne();
  if (verbose1) cout << A4cm << endl;
  if (2.0!=A4cmOneNormFloat && NumProc != 1) {
    if (verbose1) cout << "OneNorm should be = 2 (because one column is replicated on two processors and NormOne() does not handle replication), but OneNorm = " << A4cmOneNormFloat << endl;
    EPETRA_TEST_ERR(-64,ierr);
    InvSumsBroke = true;
  }
  else if (1.0!=A4cmOneNormFloat && NumProc == 1) {
    if (verbose1) cout << "OneNorm should be = 1, but OneNorm = " << A4infNormFloat <<endl;
    EPETRA_TEST_ERR(-64,ierr);
    InvSumsBroke = true;
  }

  if (verbose) cout << "End replicated testing" << endl;

  if (InvSumsBroke) {
    if (verbose) cout << endl << "InvRowSums tests FAILED" << endl << endl;
  }
  else
    if (verbose) cout << endl << "InvRowSums tests PASSED" << endl << endl;

  A3cm.PutScalar(2.0);
  int nnz_A3cm = A3cm.Graph().NumGlobalNonzeros();
  double check_frobnorm = sqrt(nnz_A3cm*4.0);
  double frobnorm = A3cm.NormFrobenius();

  bool frobnorm_test_failed = false;
  if (fabs(check_frobnorm-frobnorm) > 5.e-5) {
    frobnorm_test_failed = true;
  }

  if (frobnorm_test_failed) {
    if (verbose) std::cout << "Frobenius-norm test FAILED."<<std::endl;
    EPETRA_TEST_ERR(-65, ierr);
  }

  delete [] Values2;
  delete [] Indices2;
  delete [] myGlobalElements;
  delete [] Values3;
  delete [] Indices3;
  delete [] Values3cm;
  delete [] Indices3cm;
  delete [] RangeLeftScaleValues;
  delete [] RowLeftScaleValues;
#ifdef EPETRA_MPI
  MPI_Finalize() ;
#endif

/* end main
*/
return ierr ;
}
Exemplo n.º 22
0
SolidesP	ConstruireNormale (FacesP Face)
// Construit un solide symbolisant la normale à la face.
// Le solide est placé sur le barycentre de la face et peut donc
// être hors de la face.
// Sa longueur est égale à 5% de la dimension du solide à laquelle la
// face appartient s'il existe. Sinon, c'est 10 % de la dimension de la face.
{
	SolidesP	Sol = Face.Solide () ;

	double	HauteurTot ;

	Englobants3D	EnglobantFace = Face.Englobant () ;

	if (Sol.EstInitialise ()) {
		Englobants3D	E = Sol.Englobant () ;
		Vecteurs3D		V (E.BasGauche (),E.HautDroit ()) ;
		HauteurTot = 0.05*V.Norme () ; ;
	}
	else {
		Vecteurs3D		V (EnglobantFace.BasGauche (),EnglobantFace.HautDroit ()) ;
		HauteurTot = 0.1*V.Norme () ; ;
	}

	double	LargeurPied = HauteurTot / 24,
            LargeurTete = HauteurTot / 4,
            HauteurPied = (7./8.)*HauteurTot ;

	// Construction d'un repère centré sur le "barycentre" de la face, dont
	// le (xOy) correspond au plan de la face et dont le z est la normale à
	// la face.
	Points3D	Origine = 0.5*(EnglobantFace.BasGauche ()+EnglobantFace.HautDroit ()) ;

	Vecteurs3D	K = Face.VecteurNormal ().VecteurNorme (),
				U (Face.ContourExterieur ().IemeAreteOrientee (0).Origine ().Point3D (),
				Face.ContourExterieur ().IemeAreteOrientee (0).Extremite ().Point3D ()),
				I = (K & U).VecteurNorme (),
				J = (K & I).VecteurNorme () ;

	SommetsP	S1 (Origine-LargeurPied/2*I - LargeurPied/2*J) ;
	SommetsP	S2 (Origine-LargeurPied/2*I + LargeurPied/2*J) ;
	SommetsP	S3 (Origine+LargeurPied/2*I + LargeurPied/2*J) ;
	SommetsP	S4 (Origine+LargeurPied/2*I - LargeurPied/2*J) ;
	SommetsP	S5 (Origine-LargeurPied/2*I - LargeurPied/2*J + HauteurPied*K) ;
	SommetsP	S6 (Origine-LargeurPied/2*I + LargeurPied/2*J + HauteurPied*K) ;
	SommetsP	S7 (Origine+LargeurPied/2*I + LargeurPied/2*J + HauteurPied*K) ;
	SommetsP	S8 (Origine+LargeurPied/2*I - LargeurPied/2*J + HauteurPied*K) ;
	SommetsP	S9 (Origine-LargeurTete/2*I - LargeurTete/2*J + HauteurPied*K) ;
	SommetsP	S10 (Origine-LargeurTete/2*I + LargeurTete/2*J + HauteurPied*K) ;
	SommetsP	S11 (Origine+LargeurTete/2*I + LargeurTete/2*J + HauteurPied*K) ;
	SommetsP	S12 (Origine+LargeurTete/2*I - LargeurTete/2*J + HauteurPied*K) ;
	SommetsP	S13 (Origine+HauteurTot*K) ;

	AretesP	A1 (S1,S2) ;
	AretesP	A2 (S2,S3) ;
	AretesP	A3 (S3,S4) ;
	AretesP	A4 (S4,S1) ;
	AretesP	A5 (S5,S6) ;
	AretesP	A6 (S6,S7) ;
	AretesP	A7 (S7,S8) ;
	AretesP	A8 (S8,S5) ;
	AretesP	A9 (S9,S10) ;
	AretesP	A10 (S10,S11) ;
	AretesP	A11 (S11,S12) ;
	AretesP	A12 (S12,S9) ;
	AretesP	A13 (S1,S5) ;
	AretesP	A14 (S2,S6) ;
	AretesP	A15 (S3,S7) ;
	AretesP	A16 (S4,S8) ;
	AretesP	A17 (S9,S13) ;
	AretesP	A18 (S10,S13) ;
	AretesP	A19 (S11,S13) ;
	AretesP	A20 (S12,S13) ;

	Listes <AretesP>	L1 ;
	L1.InsertionEnQueue (A1) ;
	L1.InsertionEnQueue (A2) ;
	L1.InsertionEnQueue (A3) ;
	L1.InsertionEnQueue (A4) ;

	Listes <AretesP>	L2 ;
	L2.InsertionEnQueue (A1) ;
	L2.InsertionEnQueue (A13) ;
	L2.InsertionEnQueue (A5) ;
	L2.InsertionEnQueue (A14) ;

	Listes <AretesP>	L3 ;
	L3.InsertionEnQueue (A2) ;
	L3.InsertionEnQueue (A14) ;
	L3.InsertionEnQueue (A6) ;
	L3.InsertionEnQueue (A15) ;

	Listes <AretesP>	L4 ;
	L4.InsertionEnQueue (A3) ;
	L4.InsertionEnQueue (A15) ;
	L4.InsertionEnQueue (A7) ;
	L4.InsertionEnQueue (A16) ;

	Listes <AretesP>	L5 ;
	L5.InsertionEnQueue (A4) ;
	L5.InsertionEnQueue (A16) ;
	L5.InsertionEnQueue (A8) ;
	L5.InsertionEnQueue (A13) ;

	Listes <AretesP>	L6 ;
	L6.InsertionEnQueue (A9) ;
	L6.InsertionEnQueue (A10) ;
	L6.InsertionEnQueue (A11) ;
	L6.InsertionEnQueue (A12) ;

	Listes <AretesP>	L7 ;
	L7.InsertionEnQueue (A8) ;
	L7.InsertionEnQueue (A7) ;
	L7.InsertionEnQueue (A6) ;
	L7.InsertionEnQueue (A5) ;

	Listes <AretesP>	L8 ;
	L8.InsertionEnQueue (A9) ;
	L8.InsertionEnQueue (A17) ;
	L8.InsertionEnQueue (A18) ;

	Listes <AretesP>	L9 ;
	L9.InsertionEnQueue (A10) ;
	L9.InsertionEnQueue (A18) ;
	L9.InsertionEnQueue (A19) ;

	Listes <AretesP>	L10 ;
	L10.InsertionEnQueue (A11) ;
	L10.InsertionEnQueue (A19) ;
	L10.InsertionEnQueue (A20) ;

	Listes <AretesP>	L11 ;
	L11.InsertionEnQueue (A12) ;
	L11.InsertionEnQueue (A20) ;
	L11.InsertionEnQueue (A17) ;

	Listes <FacesP>	ListeFaces ;
	AttributsFaces	*PAF = new AttributsFaces (PMateriauRouge) ;
	FacesP F1 (ContoursP (L1),PAF) ;
	ListeFaces.InsertionEnQueue (F1) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L2),PAF)) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L3),PAF)) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L4),PAF)) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L5),PAF)) ;
	ContoursP C (L6) ;
	FacesP	F (C,PAF) ;
	F.AjouterContourInterieur (ContoursP (L7)) ;
	ListeFaces.InsertionEnQueue (F) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L8),PAF)) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L9),PAF)) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L10),PAF)) ;
	ListeFaces.InsertionEnQueue (FacesP (ContoursP (L11),PAF)) ;

	return SolidesP (ListeFaces) ;
}
Exemplo n.º 23
0
/*
 * handle commands after CSI (ESC[)
 */
void
wsemul_vt100_handle_csi(struct wsemul_vt100_emuldata *edp, u_char c)
{
	int n, help, flags, fgcol, bgcol;
	long attr, bkgdattr;

#define A3(a, b, c) (((a) << 16) | ((b) << 8) | (c))
	switch (A3(edp->modif1, edp->modif2, c)) {
	    case A3('>', '\0', 'c'): /* DA secondary */
		wsdisplay_emulinput(edp->cbcookie, WSEMUL_VT_ID2,
				    sizeof(WSEMUL_VT_ID2));
		break;

	    case A3('\0', '\0', 'J'): /* ED selective erase in display */
	    case A3('?', '\0', 'J'): /* DECSED selective erase in display */
		wsemul_vt100_ed(edp, ARG(0));
		break;
	    case A3('\0', '\0', 'K'): /* EL selective erase in line */
	    case A3('?', '\0', 'K'): /* DECSEL selective erase in line */
		wsemul_vt100_el(edp, ARG(0));
		break;
	    case A3('\0', '\0', 'h'): /* SM */
		for (n = 0; n < edp->nargs; n++)
			vt100_ansimode(edp, ARG(n), VTMODE_SET);
		break;
	    case A3('?', '\0', 'h'): /* DECSM */
		for (n = 0; n < edp->nargs; n++)
			vt100_decmode(edp, ARG(n), VTMODE_SET);
		break;
	    case A3('\0', '\0', 'l'): /* RM */
		for (n = 0; n < edp->nargs; n++)
			vt100_ansimode(edp, ARG(n), VTMODE_RESET);
		break;
	    case A3('?', '\0', 'l'): /* DECRM */
		for (n = 0; n < edp->nargs; n++)
			vt100_decmode(edp, ARG(n), VTMODE_RESET);
		break;
	    case A3('\0', '$', 'p'): /* DECRQM request mode ANSI */
		vt100_ansimode(edp, ARG(0), VTMODE_REPORT);
		break;
	    case A3('?', '$', 'p'): /* DECRQM request mode DEC */
		vt100_decmode(edp, ARG(0), VTMODE_REPORT);
		break;
	    case A3('\0', '\0', 'i'): /* MC printer controller mode */
	    case A3('?', '\0', 'i'): /* MC printer controller mode */
		switch (ARG(0)) {
		    case 0: /* print screen */
		    case 1: /* print cursor line */
		    case 4: /* off */
		    case 5: /* on */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI%di ignored\n", ARG(0));
#endif
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%di unknown\n", ARG(0));
#endif
			break;
		}
		break;

#define A2(a, b) (((a) << 8) | (b))
	    case A2('!', 'p'): /* DECSTR soft reset VT300 only */
		wsemul_vt100_reset(edp);
		break;

	    case A2('"', 'p'): /* DECSCL */
		switch (ARG(0)) {
		    case 61: /* VT100 mode (no further arguments!) */
			break;
		    case 62:
		    case 63: /* VT300 mode */
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d\"p unknown\n", ARG(0));
#endif
			break;
		}
		switch (ARG(1)) {
		    case 0:
		    case 2: /* 8-bit controls */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI%d;%d\"p ignored\n", ARG(0), ARG(1));
#endif
			break;
		    case 1: /* 7-bit controls */
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d;%d\"p unknown\n", ARG(0), ARG(1));
#endif
			break;
		}
		break;
	    case A2('"', 'q'): /* DECSCA select character attribute VT300 */
		switch (ARG(0)) {
		    case 0:
		    case 1: /* erasable */
			break;
		    case 2: /* not erasable */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI2\"q ignored\n");
#endif
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d\"q unknown\n", ARG(0));
#endif
			break;
		}
		break;

	    case A2('$', 'u'): /* DECRQTSR request terminal status report */
		switch (ARG(0)) {
		    case 0: /* ignored */
			break;
		    case 1: /* terminal state report */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI1$u ignored\n");
#endif
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d$u unknown\n", ARG(0));
#endif
			break;
		}
		break;
	    case A2('$', 'w'): /* DECRQPSR request presentation status report
				(VT300 only) */
		switch (ARG(0)) {
		    case 0: /* error */
			break;
		    case 1: /* cursor information report */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI1$w ignored\n");
#endif
			break;
		    case 2: /* tab stop report */
			{
			int i, j, ps = 0;
			char buf[20];
			KASSERT(edp->tabs != 0);
			wsdisplay_emulinput(edp->cbcookie, "\033P2$u", 5);
			for (i = 0; i < edp->ncols; i++)
				if (edp->tabs[i]) {
					j = snprintf(buf, sizeof(buf), "%s%d",
					    (ps ? "/" : ""), i + 1);
					wsdisplay_emulinput(edp->cbcookie,
							    buf, j);
					ps = 1;
				}
			}
			wsdisplay_emulinput(edp->cbcookie, "\033\\", 2);
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d$w unknown\n", ARG(0));
#endif
			break;
		}
		break;
	    case A2('$', '}'): /* DECSASD select active status display */
		switch (ARG(0)) {
		    case 0: /* main display */
		    case 1: /* status line */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI%d$} ignored\n", ARG(0));
#endif
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d$} unknown\n", ARG(0));
#endif
			break;
		}
		break;
	    case A2('$', '~'): /* DECSSDD select status line type */
		switch (ARG(0)) {
		    case 0: /* none */
		    case 1: /* indicator */
		    case 2: /* host-writable */
#ifdef VT100_PRINTNOTIMPL
			printf("CSI%d$~ ignored\n", ARG(0));
#endif
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%d$~ unknown\n", ARG(0));
#endif
			break;
		}
		break;

	    case A2('&', 'u'): /* DECRQUPSS request user preferred
				  supplemental set */
		wsdisplay_emulinput(edp->cbcookie, "\033P0!u%5\033\\", 9);
		break;

	    case '@': /* ICH insert character VT300 only */
		n = min(DEF1_ARG(0), COLS_LEFT + 1);
		help = NCOLS - (edp->ccol + n);
		if (help > 0)
			COPYCOLS(edp->ccol, edp->ccol + n, help);
		ERASECOLS(edp->ccol, n, edp->bkgdattr);
		break;
	    case 'A': /* CUU */
		edp->crow -= min(DEF1_ARG(0), ROWS_ABOVE);
		CHECK_DW;
		break;
	    case 'B': /* CUD */
		edp->crow += min(DEF1_ARG(0), ROWS_BELOW);
		CHECK_DW;
		break;
	    case 'C': /* CUF */
		edp->ccol += min(DEF1_ARG(0), COLS_LEFT);
		break;
	    case 'D': /* CUB */
		edp->ccol -= min(DEF1_ARG(0), edp->ccol);
		edp->flags &= ~VTFL_LASTCHAR;
		break;
	    case 'H': /* CUP */
	    case 'f': /* HVP */
		if (edp->flags & VTFL_DECOM)
			edp->crow = edp->scrreg_startrow +
			    min(DEF1_ARG(0), edp->scrreg_nrows) - 1;
		else
			edp->crow = min(DEF1_ARG(0), edp->nrows) - 1;
		CHECK_DW;
		edp->ccol = min(DEF1_ARG(1), NCOLS) - 1;
		edp->flags &= ~VTFL_LASTCHAR;
		break;
	    case 'L': /* IL insert line */
	    case 'M': /* DL delete line */
		n = min(DEF1_ARG(0), ROWS_BELOW + 1);
		{
		int savscrstartrow, savscrnrows;
		savscrstartrow = edp->scrreg_startrow;
		savscrnrows = edp->scrreg_nrows;
		edp->scrreg_nrows -= ROWS_ABOVE;
		edp->scrreg_startrow = edp->crow;
		if (c == 'L')
			wsemul_vt100_scrolldown(edp, n);
		else
			wsemul_vt100_scrollup(edp, n);
		edp->scrreg_startrow = savscrstartrow;
		edp->scrreg_nrows = savscrnrows;
		}
		break;
	    case 'P': /* DCH delete character */
		n = min(DEF1_ARG(0), COLS_LEFT + 1);
		help = NCOLS - (edp->ccol + n);
		if (help > 0)
			COPYCOLS(edp->ccol + n, edp->ccol, help);
		ERASECOLS(NCOLS - n, n, edp->bkgdattr);
		break;
	    case 'X': /* ECH erase character */
		n = min(DEF1_ARG(0), COLS_LEFT + 1);
		ERASECOLS(edp->ccol, n, edp->bkgdattr);
		break;
	    case 'c': /* DA primary */
		if (ARG(0) == 0)
			wsdisplay_emulinput(edp->cbcookie, WSEMUL_VT_ID1,
					    sizeof(WSEMUL_VT_ID1));
		break;
	    case 'g': /* TBC */
		KASSERT(edp->tabs != 0);
		switch (ARG(0)) {
		    case 0:
			edp->tabs[edp->ccol] = 0;
			break;
		    case 3:
			memset(edp->tabs, 0, edp->ncols);
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%dg unknown\n", ARG(0));
#endif
			break;
		}
		break;
	    case 'm': /* SGR select graphic rendition */
		flags = edp->attrflags;
		fgcol = edp->fgcol;
		bgcol = edp->bgcol;
		for (n = 0; n < edp->nargs; n++) {
			switch (ARG(n)) {
			    case 0: /* reset */
				if (n == edp->nargs - 1) {
					edp->bkgdattr = edp->curattr = edp->defattr;
					edp->attrflags = edp->msgattrs.default_attrs;
					edp->fgcol = edp->msgattrs.default_fg;
					edp->bgcol = edp->msgattrs.default_bg;
					return;
				}
				flags = edp->msgattrs.default_attrs;
				fgcol = edp->msgattrs.default_fg;
				bgcol = edp->msgattrs.default_bg;
				break;
			    case 1: /* bold */
				flags |= WSATTR_HILIT;
				break;
			    case 4: /* underline */
				flags |= WSATTR_UNDERLINE;
				break;
			    case 5: /* blink */
				flags |= WSATTR_BLINK;
				break;
			    case 7: /* reverse */
				flags |= WSATTR_REVERSE;
				break;
			    case 22: /* ~bold VT300 only */
				flags &= ~WSATTR_HILIT;
				break;
			    case 24: /* ~underline VT300 only */
				flags &= ~WSATTR_UNDERLINE;
				break;
			    case 25: /* ~blink VT300 only */
				flags &= ~WSATTR_BLINK;
				break;
			    case 27: /* ~reverse VT300 only */
				flags &= ~WSATTR_REVERSE;
				break;
			    case 30: case 31: case 32: case 33:
			    case 34: case 35: case 36: case 37:
				/* fg color */
				flags |= WSATTR_WSCOLORS;
				fgcol = ARG(n) - 30;
				break;
			    case 40: case 41: case 42: case 43:
			    case 44: case 45: case 46: case 47:
				/* bg color */
				flags |= WSATTR_WSCOLORS;
				bgcol = ARG(n) - 40;
				break;
			    default:
#ifdef VT100_PRINTUNKNOWN
				printf("CSI%dm unknown\n", ARG(n));
#endif
				break;
			}
		}
		if (vt100_selectattribute(edp, flags, fgcol, bgcol, &attr,
		    &bkgdattr)) {
#ifdef VT100_DEBUG
			printf("error allocating attr %d/%d/%x\n",
			       fgcol, bgcol, flags);
#endif
		} else {
			edp->curattr = attr;
			edp->bkgdattr = bkgdattr;
			edp->attrflags = flags;
			edp->fgcol = fgcol;
			edp->bgcol = bgcol;
		}
		break;
	    case 'n': /* reports */
		switch (ARG(0)) {
		    case 5: /* DSR operating status */
			/* 0 = OK, 3 = malfunction */
			wsdisplay_emulinput(edp->cbcookie, "\033[0n", 4);
			break;
		    case 6: { /* DSR cursor position report */
			char buf[20];
			int row;
			if (edp->flags & VTFL_DECOM)
				row = ROWS_ABOVE;
			else
				row = edp->crow;
			n = snprintf(buf, sizeof(buf), "\033[%d;%dR",
			    row + 1, edp->ccol + 1);
			wsdisplay_emulinput(edp->cbcookie, buf, n);
			}
			break;
		    case 15: /* DSR printer status */
			/* 13 = no printer, 10 = ready, 11 = not ready */
			wsdisplay_emulinput(edp->cbcookie, "\033[?13n", 6);
			break;
		    case 25: /* UDK status - VT300 only */
			/* 20 = locked, 21 = unlocked */
			wsdisplay_emulinput(edp->cbcookie, "\033[?21n", 6);
			break;
		    case 26: /* keyboard dialect */
			/* 1 = north american , 7 = german */
			wsdisplay_emulinput(edp->cbcookie, "\033[?27;1n", 8);
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%dn unknown\n", ARG(0));
#endif
			break;
		}
		break;
	    case 'r': /* DECSTBM set top/bottom margins */
		help = min(DEF1_ARG(0), edp->nrows) - 1;
		n = min(DEFx_ARG(1, edp->nrows), edp->nrows) - help;
		if (n < 2) {
			/* minimal scrolling region has 2 lines */
			return;
		} else {
			edp->scrreg_startrow = help;
			edp->scrreg_nrows = n;
		}
		edp->crow = ((edp->flags & VTFL_DECOM) ?
			     edp->scrreg_startrow : 0);
		edp->ccol = 0;
		break;
	    case 'y':
		switch (ARG(0)) {
		    case 4: /* DECTST invoke confidence test */
			/* ignore */
			break;
		    default:
#ifdef VT100_PRINTUNKNOWN
			printf("CSI%dy unknown\n", ARG(0));
#endif
			break;
		}
		break;
	    default:
#ifdef VT100_PRINTUNKNOWN
		printf("CSI%c (%d, %d) unknown\n", c, ARG(0), ARG(1));
#endif
		break;
	}
}
Exemplo n.º 24
0
Vector3d cross2d(const Vector2d &A, const Vector2d &B, double z)
{
  Vector3d A3(A.x(),A.y(),z),  B3(B.x(),B.y(),z);
  return A3.cross(B3);
}
Exemplo n.º 25
0
void ConstructA_CG2(const mesh& Mesh, FullMatrix& A)
{
  const int NumPhysElems = Mesh.get_NumPhysElems();
  const int NumBndNodes  = Mesh.get_SubNumBndNodes();
  const int Asize = Mesh.get_SubNumPhysNodes();

  assert_eq(Asize,A.get_NumRows());
  assert_eq(Asize,A.get_NumCols());
  
  dTensor1 A1(6);
  dTensor1 A2(6);
  dTensor1 A3(6);
  dTensor1 A4(6);
  dTensor1 A5(6);
  dTensor1 A6(6);

  A1.set(1, -oneninth     );
  A1.set(2,  4.0*oneninth );
  A1.set(3, -oneninth     );
  A1.set(4,  4.0*oneninth );
  A1.set(5,  4.0*oneninth );
  A1.set(6, -oneninth     );
  
  A2.set(1, -onethird     );
  A2.set(2,  0.0          );
  A2.set(3,  onethird     );
  A2.set(4, -4.0*onethird );
  A2.set(5,  4.0*onethird );
  A2.set(6,  0.0          );
  
  A3.set(1, -onethird     );
  A3.set(2, -4.0*onethird );
  A3.set(3,  0.0          );
  A3.set(4,  0.0          );
  A3.set(5,  4.0*onethird );
  A3.set(6,  onethird     );
  
  A4.set(1,  4.0          );
  A4.set(2, -4.0          );
  A4.set(3,  0.0          );
  A4.set(4, -4.0          );
  A4.set(5,  4.0          );
  A4.set(6,  0.0          );

  A5.set(1,  2.0          );
  A5.set(2, -4.0          );
  A5.set(3,  2.0          );
  A5.set(4,  0.0          );
  A5.set(5,  0.0          );
  A5.set(6,  0.0          );
  
  A6.set(1,  2.0          );
  A6.set(2,  0.0          );
  A6.set(3,  0.0          );
  A6.set(4, -4.0          );
  A6.set(5,  0.0          );
  A6.set(6,  2.0          );

  dTensor2 spts(3,2);
  spts.set(1,1,  1.0/3.0 );
  spts.set(1,2, -1.0/6.0 );
  
  spts.set(2,1, -1.0/6.0 );
  spts.set(2,2, -1.0/6.0 );
  
  spts.set(3,1, -1.0/6.0 );
  spts.set(3,2,  1.0/3.0 );
  
  dTensor1 wgts(3);
  wgts.set(1, 1.0/6.0 );
  wgts.set(2, 1.0/6.0 );
  wgts.set(3, 1.0/6.0 );
  
  // Loop over all elements in the mesh
  for (int i=1; i<=NumPhysElems; i++)
    {
      // Information for element i
      iTensor1 tt(6);
      for (int k=1; k<=6; k++)
	{  tt.set(k, Mesh.get_node_subs(i,k) );  }
      
      // Evaluate gradients of the Lagrange polynomials on Gauss quadrature points      
      dTensor2 gpx(6,3);
      dTensor2 gpy(6,3);
      
      for (int m=1; m<=3; m++)
	{
	  double  xi = spts.get(m,1);
	  double eta = spts.get(m,2);
	  
	  for (int k=1; k<=6; k++)
	    {
	      double gp_xi  = A2.get(k) + 2.0*A5.get(k)*xi + A4.get(k)*eta;
	      double gp_eta = A3.get(k) + A4.get(k)*xi + 2.0*A6.get(k)*eta;

	      gpx.set(k,m, Mesh.get_jmat(i,1,1)*gp_xi
		         + Mesh.get_jmat(i,1,2)*gp_eta );
	      gpy.set(k,m, Mesh.get_jmat(i,2,1)*gp_xi
		         + Mesh.get_jmat(i,2,2)*gp_eta );
	    }
	}

      // Entries of the stiffness matrix A
      double Area = Mesh.get_area_prim(i);
      for (int j=1; j<=6; j++)
	for (int k=1; k<=6; k++)
	  {
	    double tmp = A.get(tt.get(j),tt.get(k));
	    for (int m=1; m<=3; m++)
	      {
		tmp = tmp + 2.0*Area*wgts.get(m)*(gpx.get(j,m)*gpx.get(k,m)+gpy.get(j,m)*gpy.get(k,m));
	      }
	    A.set(tt.get(j),tt.get(k), tmp );
	  }
    }

  // Replace boundary node equations by Dirichlet boundary condition enforcement
  for (int i=1; i<=NumBndNodes; i++)
    {
      const int j=Mesh.get_sub_bnd_node(i);
      
      for (int k=1; k<=A.get_NumCols(); k++)
	{
	  A.set(j,k, 0.0 );	  
	}
      for (int k=1; k<=A.get_NumRows(); k++)
	{
	  A.set(k,j, 0.0 );
	}
      A.set(j,j, 1.0 );
    }

  // Get sparse structure representation
  A.Sparsify();
  
}
Exemplo n.º 26
0
int main(int argc, char** argv) {
	const int TARIFFA = 2;
	
	Autovettura A1("bj066mx", "benzina", "suv", 6);
	Autovettura A2("kt887gg", "gpl", "monovolume", 5);
	Autovettura A3("dh572xc", "metano", "berlina", 5);
	Autovettura A4("mq111nd", "diesel", "utilitaria", 4);
	Autobus A5("cc789oi", "benzina", "bus", 50, "Milano", 200);
	Autobus A6("st230ks", "gpl", "bus", 50, "Roma", 300);
	Autobus A7("vv234sd", "metano", "bus", 25, "Napoli", 100);
	Autobus A8("we785ss", "diesel", "bus", 60, "Parma", 400);
	
	Autoveicolo * v[8];
	v[0] = &A1;
	v[1] = &A2;
	v[2] = &A3;
	v[3] = &A4;
	v[4] = &A5;
	v[5] = &A6;
	v[6] = &A7;
	v[7] = &A8;
	
	cout<<"Polimorfismo:\n";
	for(int i=0; i<8; i++) {
		v[i]->stampaDati();
		cout << "\n";
	}
	
	
	Coda C1, C2, C3;
	C1.append(&A1);
	C1.append(&A2);
	C1.append(&A3);
	C1.append(&A4);
	C1.append(&A5);
	C1.append(&A6);
	C1.append(&A7);
	C1.append(&A8);
	
	C2.append(&A1);
	C2.append(&A2);
	C2.append(&A3);
	C2.append(&A4);
	C2.append(&A5);
	C2.append(&A6);
	C2.append(&A7);
	
	C3.append(&A1);
	C3.append(&A2);
	C3.append(&A3);
	C3.append(&A4);
	C3.append(&A5);
	C3.append(&A6);
	
	
	
	cout<<"\n\n\nCoda1:\n";
	cout<<C1;
	cout<<"\n\n\nCoda2:\n";
	cout<<C2;
	cout<<"\n\n\nCoda3:\n";
	cout<<C3;
	cout<<"\n\n\n";
	
	int e1, e2, e3;
	e1 = C1.getNelem();
	e2 = C2.getNelem();
	e3 = C3.getNelem();
	
	for(int i = 0; i<e1; i++) {
		Autoveicolo * elem;
		C1.pop(elem, TARIFFA); 
		cout<<"Elemento rimosso -> ";
		elem->stampaDati();
		cout<<endl;
	}
	cout<<"\n\n\n";
	for(int i = 0; i<e2; i++) {
		Autoveicolo * elem;
		C2.pop(elem, TARIFFA); 
		cout<<"Elemento rimosso -> ";
		elem->stampaDati();
		cout<<endl;
	}
	cout<<"\n\n\n";
	for(int i = 0; i<e3; i++) {
		Autoveicolo * elem;
		C3.pop(elem, TARIFFA); 
		cout<<"Elemento rimosso -> ";
		elem->stampaDati();
		cout<<endl;
	}
	if(C1.getIncasso()>100) {
		cout<<"\n\n\nIncasso totale: "<<C1.getIncasso()<< " bombe!";
	} else {
		cout<<"\n\n\nIncasso totale: "<<C1.getIncasso()<<" frecce!";
	}
	
	return 0;
}
Exemplo n.º 27
0
void problem(DomainS *pDomain)
{
  GridS *pGrid = pDomain->Grid;
  ConsS **Soln;
  int i, is = pGrid->is, ie = pGrid->ie;
  int j, js = pGrid->js, je = pGrid->je;
  int k, ks = pGrid->ks, ke = pGrid->ke;
  int nx1, nx2;
  int dir;
  Real angle;    /* Angle the wave direction makes with the x1-direction */
  Real x1size,x2size,x1,x2,x3,cs,sn;
  Real v_par, v_perp, den, pres;
  Real lambda; /* Wavelength */
#ifdef RESISTIVITY
  Real v_A, kva, omega_h, omega_l, omega_r;
#endif
 
  nx1 = (ie - is + 1) + 2*nghost;
  nx2 = (je - js + 1) + 2*nghost;

  if (pGrid->Nx[1] == 1) {
    ath_error("[problem] Grid must be 2D");
  }

  if ((Soln = (ConsS**)calloc_2d_array(nx2,nx1,sizeof(ConsS))) == NULL)
    ath_error("[problem]: Error allocating memory for Soln\n");

  if (pDomain->Level == 0){
    if ((RootSoln =(ConsS**)calloc_2d_array(nx2,nx1,sizeof(ConsS)))==NULL)
      ath_error("[problem]: Error allocating memory for RootSoln\n");
  }

/* An angle =  0.0 is a wave aligned with the x1-direction. */
/* An angle = 90.0 is a wave aligned with the x2-direction. */

  angle = par_getd("problem","angle");
  x1size = pDomain->RootMaxX[0] - pDomain->RootMinX[0];
  x2size = pDomain->RootMaxX[1] - pDomain->RootMinX[1];

/* Compute the sin and cos of the angle and the wavelength. */
/* Put one wavelength in the grid */

  if (angle == 0.0) {
    sin_a = 0.0;
    cos_a = 1.0;
    lambda = x1size;
  }
  else if (angle == 90.0) {
    sin_a = 1.0;
    cos_a = 0.0;
    lambda = x2size;
  }
  else {

/* We put 1 wavelength in each direction.  Hence the wavelength
 *      lambda = (pDomain->RootMaxX[0] - pDomain->RootMinX[0])*cos_a
 *  AND lambda = (pDomain->RootMaxX[1] - pDomain->RootMinX[1])*sin_a;
 *  are both satisfied. */

    if(x1size == x2size){
      cos_a = sin_a = sqrt(0.5);
    }
    else{
      angle = atan((double)(x1size/x2size));
      sin_a = sin(angle);
      cos_a = cos(angle);
    }
/* Use the larger angle to determine the wavelength */
    if (cos_a >= sin_a) {
      lambda = x1size*cos_a;
    } else {
      lambda = x2size*sin_a;
    }
  }

/* Initialize k_parallel */

  k_par = 2.0*PI/lambda;
  b_par = par_getd("problem","b_par");
  den = 1.0;

  ath_pout(0,"va_parallel = %g\nlambda = %g\n",b_par/sqrt(den),lambda);

  b_perp = par_getd("problem","b_perp");
  v_perp = b_perp/sqrt((double)den);

  dir    = par_geti_def("problem","dir",1); /* right(1)/left(2) polarization */
  if (dir == 1) /* right polarization */
    fac = 1.0;
  else          /* left polarization */
    fac = -1.0;

#ifdef RESISTIVITY
  Q_Hall = par_getd("problem","Q_H");
  d_ind  = 0.0;
  v_A    = b_par/sqrt((double)den);
  if (Q_Hall > 0.0)
  {
    kva     = k_par*v_A;
    omega_h = 1.0/Q_Hall;

    omega_r = 0.5*SQR(kva)/omega_h*(sqrt(1.0+SQR(2.0*omega_h/kva)) + 1.0);
    omega_l = 0.5*SQR(kva)/omega_h*(sqrt(1.0+SQR(2.0*omega_h/kva)) - 1.0);

    if (dir == 1) /* right polarization (whistler wave) */
      v_perp = v_perp * kva / omega_r;
    else          /* left polarization */
      v_perp = v_perp * kva / omega_l;
  }
#endif

/* The gas pressure and parallel velocity are free parameters. */

  pres = par_getd("problem","pres");
  v_par = par_getd("problem","v_par");

/* Use the vector potential to initialize the interface magnetic fields
 * The iterface fields are located at the left grid cell face normal */

  for (k=ks; k<=ke; k++) {
    for (j=js; j<=je+1; j++) {
      for (i=is; i<=ie+1; i++) {
        cc_pos(pGrid,i,j,k,&x1,&x2,&x3);
        cs = cos(k_par*(x1*cos_a + x2*sin_a));

        x1 -= 0.5*pGrid->dx1;
        x2 -= 0.5*pGrid->dx2;

        pGrid->B1i[k][j][i] = -(A3(x1,(x2+pGrid->dx2)) - A3(x1,x2))/pGrid->dx2;
        pGrid->B2i[k][j][i] =  (A3((x1+pGrid->dx1),x2) - A3(x1,x2))/pGrid->dx1;
        pGrid->B3i[k][j][i] = b_perp*cs;
      }
    }
  }
  if (pGrid->Nx[2] > 1) {
    for (j=js; j<=je+1; j++) {
      for (i=is; i<=ie+1; i++) {
        cc_pos(pGrid,i,j,k,&x1,&x2,&x3);
        cs = cos(k_par*(x1*cos_a + x2*sin_a));
        pGrid->B3i[ke+1][j][i] = b_perp*cs;
      }
    }
  }

/* Now initialize the cell centered quantities */

  for (k=ks; k<=ke; k++) {
    for (j=js; j<=je; j++) {
      for (i=is; i<=ie; i++) {
        cc_pos(pGrid,i,j,k,&x1,&x2,&x3);

        sn = sin(k_par*(x1*cos_a + x2*sin_a)) * fac;
        cs = cos(k_par*(x1*cos_a + x2*sin_a));

        Soln[j][i].d  = den;
        Soln[j][i].M1 = den*(v_par*cos_a + v_perp*sn*sin_a);
        Soln[j][i].M2 = den*(v_par*sin_a - v_perp*sn*cos_a);
        Soln[j][i].M3 = -den*v_perp*cs;
        pGrid->U[k][j][i].d  = Soln[j][i].d;
        pGrid->U[k][j][i].M1 = Soln[j][i].M1;
        pGrid->U[k][j][i].M2 = Soln[j][i].M2;
        pGrid->U[k][j][i].M3 = Soln[j][i].M3;

        Soln[j][i].B1c = 0.5*(pGrid->B1i[k][j][i] + pGrid->B1i[k][j][i+1]);
        Soln[j][i].B2c = 0.5*(pGrid->B2i[k][j][i] + pGrid->B2i[k][j+1][i]);
        Soln[j][i].B3c = b_perp*cs;
        pGrid->U[k][j][i].B1c = Soln[j][i].B1c;
        pGrid->U[k][j][i].B2c = Soln[j][i].B2c;
        pGrid->U[k][j][i].B3c = Soln[j][i].B3c;

#ifndef ISOTHERMAL
        Soln[j][i].E = pres/Gamma_1 + 0.5*(SQR(pGrid->U[k][j][i].B1c) +
                 SQR(pGrid->U[k][j][i].B2c) + SQR(pGrid->U[k][j][i].B3c) )
          + 0.5*(SQR(pGrid->U[k][j][i].M1) + SQR(pGrid->U[k][j][i].M2) +
                 SQR(pGrid->U[k][j][i].M3) )/den;
        pGrid->U[k][j][i].E = Soln[j][i].E;
#endif
      }
    }
  }

/* save solution on root grid */

  if (pDomain->Level == 0) {
    for (j=js; j<=je; j++) {
    for (i=is; i<=ie; i++) {
      RootSoln[j][i].d  = Soln[j][i].d ;
      RootSoln[j][i].M1 = Soln[j][i].M1;
      RootSoln[j][i].M2 = Soln[j][i].M2;
      RootSoln[j][i].M3 = Soln[j][i].M3;
#ifndef ISOTHERMAL
      RootSoln[j][i].E  = Soln[j][i].E ;
#endif /* ISOTHERMAL */
#ifdef MHD
      RootSoln[j][i].B1c = Soln[j][i].B1c;
      RootSoln[j][i].B2c = Soln[j][i].B2c;
      RootSoln[j][i].B3c = Soln[j][i].B3c;
#endif
#if (NSCALARS > 0)
      for (n=0; n<NSCALARS; n++)
        RootSoln[j][i].s[n] = Soln[j][i].s[n];
#endif
    }}
  }

  return;
}
Exemplo n.º 28
0
	int test()
	{
		int Error(0);

		{
			float A0(3.0);
			float B0(2.0f);
			float C0 = glm::fmod(A0, B0);

			Error += glm::abs(C0 - 1.0f) < 0.00001f ? 0 : 1;

			glm::vec4 A1(3.0);
			float B1(2.0f);
			glm::vec4 C1 = glm::fmod(A1, B1);

			Error += glm::all(glm::epsilonEqual(C1, glm::vec4(1.0f), 0.00001f)) ? 0 : 1;

			glm::vec4 A2(3.0);
			glm::vec4 B2(2.0f);
			glm::vec4 C2 = glm::fmod(A2, B2);

			Error += glm::all(glm::epsilonEqual(C2, glm::vec4(1.0f), 0.00001f)) ? 0 : 1;

			glm::ivec4 A3(3);
			int B3(2);
			glm::ivec4 C3 = glm::fmod(A3, B3);

			Error += glm::all(glm::equal(C3, glm::ivec4(1))) ? 0 : 1;

			glm::ivec4 A4(3);
			glm::ivec4 B4(2);
			glm::ivec4 C4 = glm::fmod(A4, B4);

			Error += glm::all(glm::equal(C4, glm::ivec4(1))) ? 0 : 1;
		}

		{
			float A0(22.0);
			float B0(-10.0f);
			float C0 = glm::fmod(A0, B0);

			Error += glm::abs(C0 - 2.0f) < 0.00001f ? 0 : 1;

			glm::vec4 A1(22.0);
			float B1(-10.0f);
			glm::vec4 C1 = glm::fmod(A1, B1);

			Error += glm::all(glm::epsilonEqual(C1, glm::vec4(2.0f), 0.00001f)) ? 0 : 1;

			glm::vec4 A2(22.0);
			glm::vec4 B2(-10.0f);
			glm::vec4 C2 = glm::fmod(A2, B2);

			Error += glm::all(glm::epsilonEqual(C2, glm::vec4(2.0f), 0.00001f)) ? 0 : 1;

			glm::ivec4 A3(22);
			int B3(-10);
			glm::ivec4 C3 = glm::fmod(A3, B3);

			Error += glm::all(glm::equal(C3, glm::ivec4(2))) ? 0 : 1;

			glm::ivec4 A4(22);
			glm::ivec4 B4(-10);
			glm::ivec4 C4 = glm::fmod(A4, B4);

			Error += glm::all(glm::equal(C4, glm::ivec4(2))) ? 0 : 1;
		}

		// http://stackoverflow.com/questions/7610631/glsl-mod-vs-hlsl-fmod
		{
			for (float y = -10.0f; y < 10.0f; y += 0.1f)
			for (float x = -10.0f; x < 10.0f; x += 0.1f)
			{
				float const A(std::fmod(x, y));
				//float const B(std::remainder(x, y));
				float const C(glm::fmod(x, y));
				float const D(modTrunc(x, y));

				//Error += glm::epsilonEqual(A, B, 0.0001f) ? 0 : 1;
				//assert(!Error);
				Error += glm::epsilonEqual(A, C, 0.0001f) ? 0 : 1;
				assert(!Error);
				Error += glm::epsilonEqual(A, D, 0.00001f) ? 0 : 1;
				assert(!Error);
			}
		}

		return Error;
	}
Exemplo n.º 29
0
 operator A3 () { return A3(); }