Exemple #1
0
void Fuzzer::UpdateCorpusDistribution() {
  size_t N = Corpus.size();
  std::vector<double> Intervals(N + 1);
  std::vector<double> Weights(N);
  std::iota(Intervals.begin(), Intervals.end(), 0);
  std::iota(Weights.begin(), Weights.end(), 1);
  CorpusDistribution = std::piecewise_constant_distribution<double>(
      Intervals.begin(), Intervals.end(), Weights.begin());
}
Exemple #2
0
gvl::shared_ptr<WormAI> createAi(int controller, Worm& worm, Settings& settings)
{
	if (controller == 1)
		return gvl::shared_ptr<WormAI>(new DumbLieroAI());
	else if (controller == 2)
		return gvl::shared_ptr<WormAI>(new FollowAI(
			Weights(), settings.aiParallels, worm.index == 0));

	return gvl::shared_ptr<WormAI>();
}
Exemple #3
0
int main(int argc, char *argv[])
{
  struct timeval start,end;
  gettimeofday(&start, NULL);
  int i;
  std::string arg,out_prefix;
  bool hasOut_prefix = false;
  unsigned int seed = time(NULL);
  bool verbose = false;

  if (argc == 1)
  {
	  return showUsage();
  }

  arg=argv[1];
  if(arg == "-help" || arg == "--help" || arg == "-Help" || arg == "--Help" || arg == "-h" || arg == "--h")
	  return showUsage();

  for(i=2;i<argc;i++){
  	  arg = argv[i];
  	  if(arg == "--o"){
  		  hasOut_prefix = true;
  	  }
  }
  std::cout<<"Reading network file ('"<<argv[1]<<"') ...";
  std::cout.flush();
  /* Create instance object of network */
  TrafficNetwork* network = new TrafficNetwork(argv[1],"Traffic Network 1",hasOut_prefix);
  if(!network->isCreated())
	  return 1;
  std::cout<<"Done"<<std::endl;

  std::cout<<"Reading configuration parameters...";
  /* Read inline parameters */

  // ============= learner  =============
  std::vector<NetworkLearner*> learners(0);
  bool hasSimplifiedLearner=false;
  bool hasMediumLearner=false;
  bool hasLVLearner=false;
  bool hasEBackpropLearner=false;
  std::vector<double> learnersWs(0);

  // ============= requestHandler =============
  RequestHandler* service = NULL;
  bool exploring = false;
  double explProb = DEFAULT_EXPL_PROB;
  int serviceType = -1;
  int depth = DEFAULT_DEPTH;
  bool useMarginal = false;

  // ============= sim =============
  NetworkSim* simulation = NULL;

  bool isMediumLearner = false;
  //for medium learner :
  int nbInterval = 24*4; //intervals of 15mins
  std::vector<double> wVec(0,0);
  wVec.push_back(0.05);
  wVec.push_back(0.2);
  wVec.push_back(0.5);
  wVec.push_back(0.2);
  wVec.push_back(0.05);
  Weights ws(wVec,-2);
  bool hasOtherWeights = false;

  int preset = -1;

  unsigned long nbFreeAgents = 0;
  unsigned long nbInformedAgents = 0;
  unsigned long nbDirectedAgents = 0;

  int nbDays = 0;

  int routesType = -1;
  for(i=2;i<argc;i++){
	  arg = argv[i];
	  if (arg == "--preset"){
		  preset = atoi(argv[i+1]);
		  i++;
	  }else if (arg == "-simplified"){
		  if(!hasSimplifiedLearner){
			  learners.push_back(new SimplifiedLearner(Road::roadCounter));
			  hasSimplifiedLearner = true;
		  }else{
			  return showUsageLearner("simplified");
		  }
	  }else if (arg == "-eBackprop"){
		  if(!hasEBackpropLearner){
			  learners.push_back(new EBackpropLearner(Road::roadCounter));
			  hasEBackpropLearner = true;
		  }else{
			  return showUsageLearner("error back-propagation");
		  }
	  }else if (arg == "--eBackprop"){
		  if(!hasEBackpropLearner){
			  learners.push_back(new EBackpropLearner(Road::roadCounter,atoi(argv[i+1])));
			  i++;
			  hasEBackpropLearner = true;
		  }else{
			  return showUsageLearner("error back-propagation");
		  }
	  }else if (arg == "--lastV"){
		  if(!hasLVLearner){
			  int nbEntries = atoi(argv[i+1]);
			  i++;
			  std::vector<double> w(0);
			  if(nbEntries != 1){
				  double weight;
				  for(int j=0; j<nbEntries; j++){
					  weight = atof(argv[i+1]);
					  i++;
					  w.push_back(weight);
				  }
			  }else{
				  w.push_back(1);
			  }
			  Weights lastV_weights(w);
			  learners.push_back(new LVLearner(Road::roadCounter,nbEntries,lastV_weights));
			  hasLVLearner=true;
		  }else{
			  return showUsageLearner("last visited");
		  }
	  }else if (arg == "--medium"){
		  if(!hasMediumLearner){
			  nbInterval = atoi(argv[i+1]);
			  i++;
			  isMediumLearner = true;
			  hasMediumLearner = true;
		  }else{
			  return showUsageLearner("medium");
		  }
	  }else if (arg == "--mediumWs"){
		  if(!hasOtherWeights == -1){
			  std::vector<double> w(0);
			  double wsSum = 0;
			  double weight;
			  while(wsSum != 1){
				  weight = atof(argv[i+1]);
				  i++;
				  wsSum+=weight;
				  w.push_back(weight);
			  }
			  ws = Weights(w,-w.size()/2);
			  hasOtherWeights = true;
		  }else{
			  return showUsageMediumWeights();
		  }
	  }else if (arg == "--learnerWs"){
		  if(learnersWs.size() == 0){
			  double weight;
			  int learnerCount = learners.size();
			  if(hasMediumLearner)
				  learnerCount++;
			  if(learnerCount>1){
				  for(int j = 0; j<learnerCount; j++){
					  weight = atof(argv[i+1]);
					  i++;
					  learnersWs.push_back(weight);
				  }
			  }else{
				  return showUsageLearnersWeights();
			  }
		  }else{
			  return showUsageLearnersWeights();
		  }
	  }else if (arg == "-simpleR"){
		  if(routesType == -1){
			  routesType = SIMPLESTROUTES;
		  }else{
			  return showUsageRoutesType();
		  }
	  }else if (arg == "-smartR"){
		  if(routesType == -1){
			  routesType = SMARTERROUTES;
		  }else{
			  return showUsageRoutesType();
		  }
	  }else if (arg == "-realR"){
		  if(routesType == -1){
			  routesType = REALROUTES;
		  }else{
			  return showUsageRoutesType();
		  }
	  }else if (arg == "-A*"){
		  if(serviceType == -1){
			  serviceType = ASTAR;
		  }else{
			  return showUsageHandler();
		  }
	  }else if (arg == "-RedA*"){
		  if(serviceType == -1){
			  serviceType = REDUCED_ASTAR;
		  }else{
			  return showUsageHandler();
		  }
	  }else if (arg == "--RedA*"){
		  if(serviceType == -1){
			  serviceType = REDUCED_ASTAR;
			  depth = atoi(argv[i+1]);
			  i++;
		  }else{
			  return showUsageHandler();
		  }
	  }else if (arg == "-Expl" && !exploring){
		  exploring= true;
	  }else if (arg == "--Expl" && !exploring){
		  exploring= true;
		  explProb = atof(argv[i+1]);
		  i++;
	  }else if (arg == "-marginal" && !useMarginal){
		  useMarginal = true;
	  }else if (arg == "--agents"){
		  nbFreeAgents = atoi(argv[i+1]);
		  i++;
		  nbInformedAgents = atoi(argv[i+1]);
		  i++;
		  nbDirectedAgents = atoi(argv[i+1]);
		  i++;
	  }else if (arg == "--seed"){
		  seed = atoi(argv[i+1]);
		  i++;
	  }else if (arg == "--days"){
		  nbDays = atoi(argv[i+1]);
		  i++;
	  }else if (arg == "--o"){
		  out_prefix = argv[i+1];
		  hasOut_prefix=true;
		  i++;
	  }else if (arg == "-v"){
		  verbose = true;
	  }else{
		  std::cout<<"WARNING: Read argument :'"<<arg<<"' -> unusable"<<std::endl;
	  }
  }
  if(isMediumLearner){
	  learners.push_back(new MediumDataLearner(Road::roadCounter,nbInterval,ws));
  }
  srand ( seed );

  //Test for preset
  switch(preset){
  case 0:
	  std::cout<<"WARNING: Using debug/testing preset"<<std::endl;
	  if(learners.size() == 0){
		  learners.push_back(new SimplifiedLearner(Road::roadCounter));
	  }

	  if(serviceType == -1){
		  serviceType = REDUCED_ASTAR;
	  }

	  if(nbFreeAgents == 0 && nbInformedAgents == 0 && nbDirectedAgents == 0){
		  nbFreeAgents = 1;
		  nbDirectedAgents = 1;
	  }

	  if(routesType == -1){
		  routesType = SIMPLESTROUTES;
	  }
	  if(nbDays == 0){
		  nbDays = 1;
	  }
	  break;
  case 1:
	  if(learners.size() == 0){
		  learners.push_back(new SimplifiedLearner(Road::roadCounter));
	  }

	  if(serviceType == -1){
		  serviceType = REDUCED_ASTAR;
	  }

	  if(nbFreeAgents == 0 && nbInformedAgents == 0 && nbDirectedAgents == 0){
		  nbFreeAgents = 900;
		  nbDirectedAgents = 100;
	  }

	  if(routesType == -1){
		  routesType = SIMPLESTROUTES;
	  }
	  if(nbDays == 0){
		  nbDays = 1;
	  }
	  break;
  case 2:
	  if(learners.size() == 0){
		  learners.push_back(new MediumDataLearner(Road::roadCounter,nbInterval,ws));
  	  }

  	  if(serviceType == -1){
  		  serviceType = ASTAR;
  	  }

  	  if(nbFreeAgents == 0 && nbInformedAgents == 0 && nbDirectedAgents == 0){
  		  nbFreeAgents = 900;
  		  nbDirectedAgents = 100;
  	  }

  	  if(routesType == -1){
  		  routesType = SMARTERROUTES;
  	  }
	  if(nbDays == 0){
		  nbDays = 7;
	  }
  	  break;
  default:
	  break;
  }

  //Test if all parameters are set
  if(learners.size() == 0 or (nbFreeAgents == 0 && nbInformedAgents == 0 && nbDirectedAgents == 0) or serviceType == -1){
	  return showUsage();
  }

  if(learners.size() != 0){
	  if(learners.size() != learnersWs.size()){
		  if(learnersWs.size()!=0){
			  std::cout<<"WARNING: Learners weights set are incoherent ; reverting to default value - all learners have equal weight"<<std::endl;
		  }

		  learnersWs = std::vector<double>(learners.size(),1/learners.size());
	  }
	  switch(serviceType){
	  case ASTAR:
		  if(!exploring){
			  service = new AStarHandler(network, learners, Weights(learnersWs));
		  }else{
			  service = new ExploringHandler(new AStarHandler(network, learners, Weights(learnersWs)),explProb);
		  }
		  break;
	  case REDUCED_ASTAR:
		  if(!exploring){
			  service = new ReducedAStarHandler(network, learners, Weights(learnersWs), depth);
		  }else{
			  service = new ExploringHandler(new ReducedAStarHandler(network, learners, Weights(learnersWs), depth),explProb);
		  }
		  break;
	  default:
		  break;
	  }
	  service->setMarginalUsage(useMarginal);
  }
  	//launching the simulation
	std::cout<<"Done"<<std::endl<<"Initializing simulation..."<<std::endl;

	simulation = new NetworkSim(network,service);
	//Create agents with correct routes type
	simulation->addAgents(nbFreeAgents,nbInformedAgents,nbDirectedAgents,routesType,nbDays);

	std::cout<<"Done"<<std::endl<<"Launching simulation..."<<std::endl;

	//for travel time monitoring
	double total_tt = 0;
	double dayTotal_tt = 0;
	double totalFree_tt = 0;
	double dayFree_tt = 0;
	double totalInformed_tt = 0;
	double dayInformed_tt = 0;
	double totalDir_tt = 0;
	double dayDir_tt = 0;

	//for traveled distance monitoring
	double total_di = 0;
	double dayTotal_di = 0;
	double totalFree_di = 0;
	double dayFree_di = 0;
	double totalInformed_di = 0;
	double dayInformed_di = 0;
	double totalDir_di = 0;
	double dayDir_di = 0;

	std::ofstream fileOut;
	bool openedAgentsStat = false;
	if(hasOut_prefix){
		fileOut.open((out_prefix+"_agents_stats.txt").c_str());
		if ( fileOut.is_open() ) {
			openedAgentsStat = true;
			fileOut<<seed<<" "<<nbFreeAgents<<" "<<nbInformedAgents<<" "<<nbDirectedAgents<<" "<<nbDays<<std::endl;
		}else{
			std::cout<< "WARNING: Could not open file '"<<out_prefix<<"_agents_stats.txt' to write down agents statistics ; proceeding without saving data" <<std::endl;
		}
	}

	double travelTime,travelDist;
	AgentsVec agents = simulation->getAgents();
	//Launch simulation
	int week = 0;
	char weekChar[21];
	sprintf(weekChar,"%d",week);
	for(int day = 0 ; day < nbDays ; day++){
		simulation->simulate(86400);
		if(hasOut_prefix){
			if(day == (week*7)+6 or day == nbDays-1){
				network->saveToFile(out_prefix+"_week"+weekChar,true);
				week+=1;
				sprintf(weekChar,"%d",week);
			}else{
				//network->saveToFile(out_prefix+"_week"+weekChar);
			}
		}
		//show (partial) results if verbose
		if(verbose){
			std::cout<<"######################## Day "<<day+1<<" ########################"<<std::endl;
			dayTotal_tt = 0;
			dayFree_tt = 0;
			dayInformed_tt = 0;
			dayDir_tt = 0;

			dayTotal_di = 0;
			dayFree_di = 0;
			dayInformed_di = 0;
			dayDir_di = 0;
			for(unsigned long i=0 ; i < nbFreeAgents ; i++){
				travelTime = agents[i]->getTravelTime();
				travelDist = agents[i]->getTravelDist();

				total_tt += travelTime;
				dayTotal_tt += travelTime;
				totalFree_tt += travelTime;
				dayFree_tt += travelTime;

				total_di += travelDist;
				dayTotal_di += travelDist;
				totalFree_di += travelDist;
				dayFree_di += travelDist;
				if(openedAgentsStat){
					fileOut<<i<<" "<<day<<" "<<travelTime<<" "<<travelDist<<std::endl;
				}
			}
			for(unsigned long i=nbFreeAgents ; i < nbFreeAgents+nbInformedAgents ; i++){
				travelTime = agents[i]->getTravelTime();
				travelDist = agents[i]->getTravelDist();

				total_tt += travelTime;
				dayTotal_tt += travelTime;
				totalInformed_tt += travelTime;
				dayInformed_tt += travelTime;

				total_di += travelDist;
				dayTotal_di += travelDist;
				totalInformed_di += travelDist;
				dayInformed_di += travelDist;
				if(openedAgentsStat){
					fileOut<<i<<" "<<day<<" "<<travelTime<<" "<<travelDist<<std::endl;
				}
			}
			for(unsigned long i=nbFreeAgents+nbInformedAgents ; i < nbFreeAgents+nbInformedAgents+nbDirectedAgents ; i++){
				travelTime = agents[i]->getTravelTime();
				travelDist = agents[i]->getTravelDist();

				total_tt += travelTime;
				dayTotal_tt += travelTime;
				totalDir_tt += travelTime;
				dayDir_tt += travelTime;

				total_di += travelDist;
				dayTotal_di += travelDist;
				totalDir_di += travelDist;
				dayDir_di += travelDist;
				if(openedAgentsStat){
					fileOut<<i<<" "<<day<<" "<<travelTime<<" "<<travelDist<<std::endl;
				}
			}
			if(nbFreeAgents !=0){
				std::cout<<"(Day) Total travel time of free agents: "<<dayFree_tt<<" ; average: "<<dayFree_tt/nbFreeAgents<<std::endl;
				std::cout<<"(Day) Total traveled distance of free agents: "<<dayFree_di<<" ; average: "<<dayFree_di/nbFreeAgents<<std::endl;
			}
			if(nbInformedAgents !=0){
				std::cout<<"(Day) Total travel time of informed agents: "<<dayInformed_tt<<" ; average: "<<dayInformed_tt/nbInformedAgents<<std::endl;
				std::cout<<"(Day) Total traveled distance of informed agents: "<<dayInformed_di<<" ; average: "<<dayInformed_di/nbInformedAgents<<std::endl;
			}
			if(nbDirectedAgents !=0){
				std::cout<<"(Day) Total travel time of directed agents: "<<dayDir_tt<<" ; average: "<<dayDir_tt/nbDirectedAgents<<std::endl;
				std::cout<<"(Day) Total traveled distance of directed agents: "<<dayDir_di<<" ; average: "<<dayDir_di/nbDirectedAgents<<std::endl;
			}
			std::cout<<"(Day) Total travel time of all agents: "<<dayTotal_tt<<" ; average: "<<dayTotal_tt/(nbFreeAgents + nbInformedAgents + nbDirectedAgents)<<std::endl;
			std::cout<<"(Day) Total traveled distance of all agents: "<<dayTotal_di<<" ; average: "<<dayTotal_di/(nbFreeAgents + nbInformedAgents + nbDirectedAgents)<<std::endl;

		}else if(openedAgentsStat){
			for(AgentsVec::iterator agentI = agents.begin(); agentI != agents.end(); agentI++){
				travelTime = (*agentI)->getTravelTime();
				travelDist = (*agentI)->getTravelDist();
				fileOut<<(*agentI)->getId()<<" "<<day<<" "<<travelTime<<" "<<travelDist<<std::endl;
			}
		}
	}

	//show final results
	if(verbose){
		std::cout<<"######################## Final Results ########################"<<std::endl;
		if(nbFreeAgents !=0){
		  std::cout<<"Total travel time of free agents: "<<totalFree_tt<<" ; average: "<<totalFree_tt/nbFreeAgents<<std::endl;
		  std::cout<<"Total traveled distance of free agents: "<<totalFree_di<<" ; average: "<<totalFree_di/nbFreeAgents<<std::endl;
		}
		if(nbInformedAgents !=0){
		  std::cout<<"Total travel time of informed agents: "<<totalInformed_tt<<" ; average: "<<totalInformed_tt/nbInformedAgents<<std::endl;
		  std::cout<<"Total traveled distance of informed agents: "<<totalInformed_di<<" ; average: "<<totalInformed_di/nbInformedAgents<<std::endl;
		}
		if(nbDirectedAgents !=0){
		  std::cout<<"Total travel time of directed agents: "<<totalDir_tt<<" ; average: "<<totalDir_tt/nbDirectedAgents<<std::endl;
		  std::cout<<"Total traveled distance of directed agents: "<<totalDir_di<<" ; average: "<<totalDir_di/nbDirectedAgents<<std::endl;
		}
		std::cout<<"Total travel time of all agents: "<<total_tt<<" ; average: "<<total_tt/(nbFreeAgents + nbInformedAgents + nbDirectedAgents)<<std::endl;
		std::cout<<"Total traveled distance of all agents: "<<total_di<<" ; average: "<<total_di/(nbFreeAgents + nbInformedAgents + nbDirectedAgents)<<std::endl;
	}

	if(openedAgentsStat){
		fileOut.close();
	}

	gettimeofday(&end, NULL);
	long seconds  = end.tv_sec  - start.tv_sec;
	long useconds = end.tv_usec - start.tv_usec;
	if (useconds<0){
	  useconds+=1000000;
	  seconds--;
	}

	long myTime []= {seconds, useconds};

	std::cout<<"Total computation time (in seconds) = "<<std::endl<<myTime[0]<<"."<<myTime[1]<<std::endl<<"Used seed : "<<seed<<std::endl;

	if(service != NULL)
		delete service;
	for(std::vector<NetworkLearner*>::iterator learner = learners.begin(); learner != learners.end(); learner++){
		if((*learner) != NULL){
			delete(*learner);
		}
	}
	if(simulation != NULL)
		delete simulation;
	if(network != NULL){
		delete network;
	}

	return 0;
}
int MultiVectorTests(const Epetra_BlockMap & Map, int NumVectors, bool verbose)
{
  const Epetra_Comm & Comm = Map.Comm();
  int ierr = 0, i;
  double *residual = new double[NumVectors];

  Epetra_BLAS BLAS;
  /* get number of processors and the name of this processor */

  // int NumProc = Comm.getNumProc();
  int MyPID   = Comm.MyPID();

  // Construct MultiVectors

  Epetra_MultiVector A(Map, NumVectors);
  Epetra_MultiVector sqrtA(Map, NumVectors);
  Epetra_MultiVector B(Map, NumVectors);
  Epetra_MultiVector C(Map, NumVectors);
  Epetra_MultiVector C_alphaA(Map, NumVectors);
  Epetra_MultiVector C_alphaAplusB(Map, NumVectors);
  Epetra_MultiVector C_plusB(Map, NumVectors);
  Epetra_MultiVector Weights(Map, NumVectors);

  // Construct double vectors
  double *dotvec_AB   = new double[NumVectors];
  double *norm1_A     = new double[NumVectors];
  double *norm2_sqrtA = new double[NumVectors];
  double *norminf_A = new double[NumVectors];
  double *normw_A = new double[NumVectors];
  double *minval_A = new double[NumVectors];
  double *maxval_A = new double[NumVectors];
  double *meanval_A = new double[NumVectors];

  // Generate data


  EPETRA_TEST_ERR(C.Random(),ierr); // Fill C with random numbers.
  double alpha = 2.0;
  BuildMultiVectorTests (C,alpha, A, sqrtA, B, C_alphaA, C_alphaAplusB,
			     C_plusB, dotvec_AB, norm1_A, norm2_sqrtA, norminf_A,
			     normw_A, Weights, minval_A, maxval_A, meanval_A);

  int err = 0;
  if (verbose) cout << "XXXXX Testing alpha * A     ";
  // Test alpha*A
  Epetra_MultiVector alphaA(A); // Copy of A
  EPETRA_TEST_ERR(alphaA.Scale(alpha),err);
  EPETRA_TEST_ERR(alphaA.Update(-1.0, C_alphaA, 1.0),err);
  EPETRA_TEST_ERR(alphaA.Norm2(residual),err);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing C = alpha * A + B      ";
  // Test alpha*A + B
  Epetra_MultiVector alphaAplusB(A); // Copy of A
  EPETRA_TEST_ERR(alphaAplusB.Update(1.0, B, alpha, A, 0.0),err);
  EPETRA_TEST_ERR(alphaAplusB.Update(-1.0, C_alphaAplusB, 1.0),err);
  EPETRA_TEST_ERR(alphaAplusB.Norm2(residual),err);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing C += B      ";
  // Test + B
  Epetra_MultiVector plusB(C); // Copy of C
  EPETRA_TEST_ERR(plusB.Update(1.0, B, 1.0),err);
  EPETRA_TEST_ERR(plusB.Update(-1.0, C_plusB, 1.0),err);
  EPETRA_TEST_ERR(plusB.Norm2(residual),err);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing A.dotProd(B)     ";
  // Test A.dotvec(B)
  double *dotvec = residual;
  EPETRA_TEST_ERR(A.Dot(B,dotvec),err);
  BLAS.AXPY(NumVectors,-1.0,dotvec_AB,dotvec);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing norm1_A      ";
  // Test A.norm1()
  double *norm1 = residual;
  EPETRA_TEST_ERR(A.Norm1(norm1),err);
  BLAS.AXPY(NumVectors,-1.0,norm1_A,norm1);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing norm2_sqrtA     ";
  // Test sqrtA.norm2()
  double *norm2 = residual;
  EPETRA_TEST_ERR(sqrtA.Norm2(norm2),err);
  BLAS.AXPY(NumVectors,-1.0,norm2_sqrtA,norm2);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing norminf_A     ";
  // Test A.norminf()
  double *norminf = residual;
  EPETRA_TEST_ERR(A.NormInf(norminf),err);
  BLAS.AXPY(NumVectors,-1.0,norminf_A,norminf);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing normw_A     ";
  // Test A.NormWeighted()
  double *normw = residual;
  EPETRA_TEST_ERR(A.NormWeighted(Weights, normw),err);
  BLAS.AXPY(NumVectors,-1.0,normw_A,normw);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing minval_A     ";
  // Test A.MinValue()
  double *minval = residual;
  EPETRA_TEST_ERR(A.MinValue(minval),err);
  BLAS.AXPY(NumVectors,-1.0,minval_A,minval);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing maxval_A     ";
  // Test A.MaxValue()
  double *maxval = residual;
  EPETRA_TEST_ERR(A.MaxValue(maxval),err);
  BLAS.AXPY(NumVectors,-1.0,maxval_A,maxval);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing meanval_A     ";
  // Test A.MeanValue()
  double *meanval = residual;
  EPETRA_TEST_ERR(A.MeanValue(meanval),err);
  BLAS.AXPY(NumVectors,-1.0,meanval_A,meanval);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing abs_A     ";
  // Test A.Abs()
  Epetra_MultiVector Abs_A = A;
  EPETRA_TEST_ERR(Abs_A.Abs(A),err);
  EPETRA_TEST_ERR(Abs_A.Update(1.0, A, -1.0),err); // Abs_A = A - Abs_A (should be zero since A > 0)
  EPETRA_TEST_ERR(Abs_A.Norm2(residual),err);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing random_A (Test1) ";
  // Test A.Random()
  Epetra_MultiVector Rand1_A(A);
  Epetra_MultiVector Rand2_A(A);
  EPETRA_TEST_ERR(Rand1_A.Random(),err);
  EPETRA_TEST_ERR(Rand2_A.Random(),err);
  // Rand2_A = Rand1_A - Rand2_A (should be nonzero since Random() should give different vectors > 0)
  EPETRA_TEST_ERR(Rand2_A.Update(1.0, Rand1_A, -1.0),err);
  EPETRA_TEST_ERR(Rand2_A.Norm2(residual),err);

  if (err) ierr += err;
  else {
    EPETRA_TEST_ERR(BadResidual1(verbose,residual, NumVectors),ierr);
  }

  err = 0;
  if (verbose) cout << "XXXXX Testing random_A (Test2) ";

  // Next test that each column of the multivector is different from all other columns by testing the first value
  // of each vector against the first value of every other vector.
  int randvalsdiffer = 1; // Assume they all differ
  for (i=0; i< NumVectors; i++)
    for (int j=i+1; j<NumVectors; j++)
      if (Rand1_A[i][0]==Rand1_A[j][0]) randvalsdiffer = 0; // make false if equal
  int allrandvals = 0;
  Comm.MinAll(&randvalsdiffer, &allrandvals, 1); // get min of all values across all processors

  EPETRA_TEST_ERR(1-allrandvals, err); // If allrandvals is anything but 1, this will cause an error
  int locerr = err;
  Comm.MinAll(&locerr, &err, 1);

  if (verbose) {
    if (err==0) {
      cout << "\t Checked OK" << endl;
    } else {
      cout << "\t Checked Failed" << endl;
    }
  }
  err = 0;
  if (verbose) cout << "XXXXX Testing random_A (Test3) ";

  // Next test that the first element on each processor of the first column of Rand1_A is different from all others
  // First we will gather them all to PE 0


  Epetra_Map RandstartsMap(-1, 1, 0, Comm); // This Map has a single element on each PE
  int itmp = 0;
  int nproc = Comm.NumProc();
  if (MyPID==0) itmp = nproc;
  Epetra_Map AllrandstartsMap(nproc, itmp, 0, Comm); // Map has NumProc elements on PE 0, none elsewhere
  Epetra_MultiVector Randstarts(RandstartsMap, NumVectors);
  Epetra_MultiVector Allrandstarts(AllrandstartsMap, NumVectors);
  for (i=0; i< NumVectors; i++) Randstarts[i][0] = Rand1_A[i][0]; // Load first value of local multivector

  Epetra_Import Randimporter(AllrandstartsMap,RandstartsMap);
  EPETRA_TEST_ERR(Allrandstarts.Import(Randstarts,Randimporter,Insert),err);
  // cout << "Randstarts = " << Randstarts << endl << "Allrandstarts = " << Allrandstarts << endl;
  // Allrandstarts now contains the first values for each local section of Rand1_A.
  // Next test that this is true.
  randvalsdiffer = 1; // Assume they all differ
  if (MyPID==0) {
    for (i=0; i< NumVectors; i++)
      for (int irand=0; irand<nproc; irand++)
	for (int jrand=irand+1; jrand<nproc; jrand++)
	  if (Allrandstarts[i][irand]==Allrandstarts[i][jrand]) randvalsdiffer = 0; // make false if equal
  }
  allrandvals = 0;
  Comm.MinAll(&randvalsdiffer, &allrandvals, 1); // get min of all values across all processors

  EPETRA_TEST_ERR(1-allrandvals, err); // If allrandvals is anything but 1, this will cause an error
  locerr = err;
  Comm.MinAll(&locerr, &err, 1);
  if (verbose) {
    if (err==0) {
      cout << "\t Checked OK" << endl;
    } else {
      cout << "\t Checked Failed" << endl;
    }
  }

  // Delete everything

  delete [] dotvec_AB;
  delete [] norm1_A;
  delete [] norm2_sqrtA;
  delete [] norminf_A;
  delete [] normw_A;
  delete [] minval_A;
  delete [] maxval_A;
  delete [] meanval_A;
  delete [] residual;

  //*******************************************************************
  // Post-construction modification tests
  //*******************************************************************

  if (verbose) cout <<  "\n\nXXXXX Testing Post-construction modification of a multivector"
		    <<endl<<endl;

  err = 0;

  Epetra_MultiVector X(Map, NumVectors);
  X.Random();

  // Pick middle range values for GID, LID and Vector Index
  int testGID = Map.NumGlobalElements()/2;
  int testVecIndex = NumVectors/2;

  int GIDSize = 1;
  int LIDOfGID = 0;
  int FirstEntryOfGID = 0;

  if (Map.MyGID(testGID)) {
    LIDOfGID = Map.LID(testGID);
    GIDSize = Map.ElementSize(LIDOfGID);
    FirstEntryOfGID = Map.FirstPointInElement(LIDOfGID);
  }

  // ========================================================================
  // Test int ReplaceGlobalValue (int GlobalRow, int VectorIndex, double ScalarValue)
  // ========================================================================

  double newGIDValue = 4.0;
  locerr = X.ReplaceGlobalValue(testGID, testVecIndex, newGIDValue);

  if (Map.MyGID(testGID)) {
    if (X[testVecIndex][FirstEntryOfGID]!=newGIDValue) err++;
    if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfGID<<"] = "
		      <<  X[testVecIndex][FirstEntryOfGID]
		      << " should = " << newGIDValue << endl;
  }
  else
    if (locerr!=1) err++; // Test for GID out of range error (=1)

  // ========================================================================
  // Test int ReplaceGlobalValue (int GlobalRow, intBlockRowOffset, int VectorIndex, double ScalarValue)
  // ========================================================================
  newGIDValue = 8.0;
  locerr = X.ReplaceGlobalValue(testGID, GIDSize-1, testVecIndex, newGIDValue);

  if (Map.MyGID(testGID)) {
    if (X[testVecIndex][FirstEntryOfGID+GIDSize-1]!=newGIDValue) err++;
    if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfGID+GIDSize-1<<"] = "
		      <<  X[testVecIndex][FirstEntryOfGID+GIDSize-1]
		      << " should = " << newGIDValue << endl;
  }
  else
    if (locerr!=1) err++; // Test for GID out of range error (=1)

  // ========================================================================
  // Test int SumIntoGlobalValue (int GlobalRow, int VectorIndex, double ScalarValue)
  // ========================================================================

  newGIDValue = 1.0;
  locerr = X.ReplaceGlobalValue(testGID, testVecIndex, newGIDValue);
  locerr = X.SumIntoGlobalValue(testGID, testVecIndex, newGIDValue);
  if (Map.MyGID(testGID)) {
    if (X[testVecIndex][FirstEntryOfGID]!=(newGIDValue+newGIDValue)) err++;
    if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfGID<<"] = "
		      <<  X[testVecIndex][FirstEntryOfGID]
		      << " should = " << newGIDValue << endl;
  }
  else
    if (locerr!=1) err++; // Test for GID out of range error (=1)

  // ========================================================================
  // Test int SumIntoGlobalValue (int GlobalRow, intBlockRowOffset, int VectorIndex, double ScalarValue)
  // ========================================================================

  newGIDValue = 1.0;
  locerr = X.ReplaceGlobalValue(testGID, GIDSize-1, testVecIndex, newGIDValue);
  locerr = X.SumIntoGlobalValue(testGID, GIDSize-1, testVecIndex, newGIDValue);

  if (Map.MyGID(testGID)) {
    if (X[testVecIndex][FirstEntryOfGID+GIDSize-1]!=(newGIDValue+newGIDValue)) err++;
    if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfGID+GIDSize-1<<"] = "
		      <<  X[testVecIndex][FirstEntryOfGID+GIDSize-1]
		      << " should = " << newGIDValue << endl;
  }
  else
    if (locerr!=1) err++; // Test for GID out of range error (=1)

  // ========================================================================
  // Test Local "My" versions of same routine (less complicated)
  // ========================================================================

  // Pick middle range values for LID
  int testLID = Map.NumMyElements()/2;

  int LIDSize = Map.ElementSize(testLID);
  int FirstEntryOfLID = Map.FirstPointInElement(testLID);


  double newLIDValue = 4.0;
  locerr = X.ReplaceMyValue(testLID, testVecIndex, newLIDValue);

  if (X[testVecIndex][FirstEntryOfLID]!=newLIDValue) err++;
  if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfLID<<"] = "
		    <<  X[testVecIndex][FirstEntryOfLID]
		    << " should = " << newLIDValue << endl;

  newLIDValue = 8.0;
  locerr = X.ReplaceMyValue(testLID, LIDSize-1, testVecIndex, newLIDValue);
  if (X[testVecIndex][FirstEntryOfLID+LIDSize-1]!=newLIDValue) err++;
  if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfLID+LIDSize-1<<"] = "
		    <<  X[testVecIndex][FirstEntryOfLID+LIDSize-1]
		    << " should = " << newLIDValue << endl;
  newLIDValue = 1.0;
  locerr = X.ReplaceMyValue(testLID, testVecIndex, newLIDValue);
  locerr = X.SumIntoMyValue(testLID, testVecIndex, newLIDValue);
  if (X[testVecIndex][FirstEntryOfLID]!=(newLIDValue+newLIDValue)) err++;
  if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfLID<<"] = "
		    <<  X[testVecIndex][FirstEntryOfLID]
		    << " should = " << newLIDValue << endl;
  newLIDValue = 2.0;
  locerr = X.ReplaceMyValue(testLID, LIDSize-1, testVecIndex, newLIDValue);
  locerr = X.SumIntoMyValue(testLID, LIDSize-1, testVecIndex, newLIDValue);
  if (verbose) cout << "X["<<testVecIndex<<"]["<<FirstEntryOfLID+LIDSize-1<<"] = "
		    <<  X[testVecIndex][FirstEntryOfLID+LIDSize-1]
		    << " should = " << newLIDValue << endl;
  if (X[testVecIndex][FirstEntryOfLID+LIDSize-1]!=(newLIDValue+newLIDValue)) err++;

  ierr += err;

  // ========================================================================
  // Test Post-construction modification of an Epetra_Vector using a vector
  // our multivector X
  // ========================================================================

  if (verbose) cout <<  "\n\nXXXXX Testing Post-construction modification of a vector"
		    << endl << endl;

  Epetra_Vector * x = X(testVecIndex);

  int NumEntries = 2;
  double * VecValues = new double[NumEntries];
  int * VecGIDs = new int[NumEntries];
  VecGIDs[0] = testGID;
  VecGIDs[1] = testGID+1; // Some pathological chance that these GIDs are not valid

  // ========================================================================
  // Test int ReplaceGlobalValues (int NumEntries, double *Values, int *Indices)
  // ========================================================================

  VecValues[0] = 2.0; VecValues[1] = 4.0;
  locerr = x->ReplaceGlobalValues(NumEntries, VecValues, VecGIDs);

  for (i=0; i<NumEntries; i++) {
    testGID = VecGIDs[i];
    if (Map.MyGID(testGID)) {
      LIDOfGID = Map.LID(testGID);
      GIDSize = EPETRA_MIN(GIDSize,Map.ElementSize(LIDOfGID)); // Need this value below
      FirstEntryOfGID = Map.FirstPointInElement(LIDOfGID);
      if ((*x)[FirstEntryOfGID]!=VecValues[i]) err++;
      if (verbose) cout << "x["<<FirstEntryOfGID<<"] = "
			<< (*x)[FirstEntryOfGID]
			<< " should = " << VecValues[i] << endl;
    }
    else
      if (locerr!=1) err++; // Test for GID out of range error (=1)
  }


  // ========================================================================
  // Test int ReplaceGlobalValues (int NumEntries, int BlockOffset, double *Values, int *Indices)
  // ========================================================================

  VecValues[0] = 4.0; VecValues[1] = 8.0;
  locerr = x->ReplaceGlobalValues(NumEntries, GIDSize-1, VecValues, VecGIDs);

  for (i=0; i<NumEntries; i++) {
    testGID = VecGIDs[i];
    if (Map.MyGID(testGID)) {
      LIDOfGID = Map.LID(testGID);
      FirstEntryOfGID = Map.FirstPointInElement(LIDOfGID);
      if ((*x)[FirstEntryOfGID+GIDSize-1]!=VecValues[i]) err++;
      if (verbose) cout << "x["<<FirstEntryOfGID+GIDSize-1<<"] = "
			<< (*x)[FirstEntryOfGID+GIDSize-1]
			<< " should = " << VecValues[i] << endl;
    }
    else
      if (locerr!=1) err++; // Test for GID out of range error (=1)
  }

  // ========================================================================
  // Test int SumIntoGlobalValues (int NumEntries, double *Values, int *Indices)
  // ========================================================================

  VecValues[0] = 1.0; VecValues[1] = 2.0;
  locerr = x->ReplaceGlobalValues(NumEntries, VecValues, VecGIDs);
  locerr = x->SumIntoGlobalValues(NumEntries, VecValues, VecGIDs);

  for (i=0; i<NumEntries; i++) {
    testGID = VecGIDs[i];
    if (Map.MyGID(testGID)) {
      LIDOfGID = Map.LID(testGID);
      FirstEntryOfGID = Map.FirstPointInElement(LIDOfGID);
      if ((*x)[FirstEntryOfGID]!=(VecValues[i]+VecValues[i])) err++;
      if (verbose) cout << "x["<<FirstEntryOfGID<<"] = "
			<< (*x)[FirstEntryOfGID]
			<< " should = " << (VecValues[i]+VecValues[i]) << endl;
    }
    else
      if (locerr!=1) err++; // Test for GID out of range error (=1)
  }
  // ========================================================================
  // Test int ReplaceGlobalValues (int NumEntries, int BlockOffset, double *Values, int *Indices)
  // ========================================================================

  VecValues[0] = 1.0; VecValues[1] = 2.0;
  locerr = x->ReplaceGlobalValues(NumEntries, GIDSize-1, VecValues, VecGIDs);
  locerr = x->SumIntoGlobalValues(NumEntries, GIDSize-1, VecValues, VecGIDs);

  for (i=0; i<NumEntries; i++) {
    testGID = VecGIDs[i];
    if (Map.MyGID(testGID)) {
      LIDOfGID = Map.LID(testGID);
      FirstEntryOfGID = Map.FirstPointInElement(LIDOfGID);
      if ((*x)[FirstEntryOfGID+GIDSize-1]!=(VecValues[i]+VecValues[i])) err++;
      if (verbose) cout << "x["<<FirstEntryOfGID+GIDSize-1<<"] = "
			<< (*x)[FirstEntryOfGID+GIDSize-1]
			<< " should = " << (VecValues[i]+VecValues[i]) << endl;
    }
    else
      if (locerr!=1) err++; // Test for GID out of range error (=1)
  }

  // ========================================================================
  // Test Local "My" versions of same routine (less complicated)
  // ========================================================================
  int * VecLIDs = new int[NumEntries];
  VecLIDs[0] = testLID;
  VecLIDs[1] = testLID+1; // Some pathological chance that these LIDs are not valid

  VecValues[0] = 2.0; VecValues[1] = 4.0;
  locerr = x->ReplaceMyValues(NumEntries, VecValues, VecLIDs);

  for (i=0; i<NumEntries; i++) {
    testLID = VecLIDs[i];
    LIDSize = EPETRA_MIN(LIDSize,Map.ElementSize(testLID)); // Need this value below
    FirstEntryOfLID = Map.FirstPointInElement(testLID);
    if ((*x)[FirstEntryOfLID]!=VecValues[i]) err++;
    if (verbose) cout << "x["<<FirstEntryOfLID<<"] = "
		      << (*x)[FirstEntryOfLID]
		      << " should = " << VecValues[i] << endl;
  }

  VecValues[0] = 4.0; VecValues[1] = 8.0;
  locerr = x->ReplaceMyValues(NumEntries, LIDSize-1, VecValues, VecLIDs);

  for (i=0; i<NumEntries; i++) {
    testLID = VecLIDs[i];
    LIDSize = EPETRA_MIN(LIDSize,Map.ElementSize(testLID)); // Need this value below
    FirstEntryOfLID = Map.FirstPointInElement(testLID);
    if ((*x)[FirstEntryOfLID+LIDSize-1]!=VecValues[i]) err++;
    if (verbose) cout << "x["<<FirstEntryOfLID+LIDSize-1<<"] = "
		      << (*x)[FirstEntryOfLID+LIDSize-1]
		      << " should = " << VecValues[i] << endl;
  }

  VecValues[0] = 1.0; VecValues[1] = 1.0;
  locerr = x->ReplaceMyValues(NumEntries, VecValues, VecLIDs);
  locerr = x->SumIntoMyValues(NumEntries, VecValues, VecLIDs);

  for (i=0; i<NumEntries; i++) {
    testLID = VecLIDs[i];
    LIDSize = EPETRA_MIN(LIDSize,Map.ElementSize(testLID)); // Need this value below
    FirstEntryOfLID = Map.FirstPointInElement(testLID);
    if ((*x)[FirstEntryOfLID]!=(VecValues[i]+VecValues[i])) err++;
    if (verbose) cout << "x["<<FirstEntryOfLID<<"] = "
		      << (*x)[FirstEntryOfLID]
		      << " should = " << (VecValues[i]+VecValues[i]) << endl;
  }

  VecValues[0] = 2.0; VecValues[1] = 4.0;
  locerr = x->ReplaceMyValues(NumEntries, LIDSize-1, VecValues, VecLIDs);
  locerr = x->SumIntoMyValues(NumEntries, LIDSize-1, VecValues, VecLIDs);

  for (i=0; i<NumEntries; i++) {
    testLID = VecLIDs[i];
    LIDSize = EPETRA_MIN(LIDSize,Map.ElementSize(testLID)); // Need this value below
    FirstEntryOfLID = Map.FirstPointInElement(testLID);
    if ((*x)[FirstEntryOfLID+LIDSize-1]!=(VecValues[i]+VecValues[i])) err++;
    if (verbose) cout << "x["<<FirstEntryOfLID+LIDSize-1<<"] = "
		      << (*x)[FirstEntryOfLID+LIDSize-1]
		      << " should = " << (VecValues[i]+VecValues[i]) << endl;
  }

    delete [] VecValues;
    delete [] VecGIDs;
    delete [] VecLIDs;

  return(ierr);
}