Beispiel #1
0
void PodgladPostepu::update( evol::Population& population )
{
    Plan* best = evol::EvolFunctions::ptr_cast<evol::SubjectPtr, Plan>(
            population.getSubjects().at( population.getBestId() )
    );
    ++populationCounter;
    CzasWykonania czas;
    czas.calculate(*best);
    unsigned int current = czas.getTimeTotal();

    if( !bestTime || current < bestTime )
    {
        bestTime = current;
        lastBetter = populationCounter;
        std::cout << "Poprawil sie wynik najlepszego osobnika."<< std::endl;
        std::cout << "Obecny wynik (pokolenie nr. " << populationCounter << ") to: " << std::endl;
        best->print();
        std::cout << std::endl;
    }
    else if( populationCounter%100 == 0 )
    {
        std::cout << "Pokolenie nr. "<< populationCounter << std::endl << std::endl; 
    }

    if( timeLimit != 0 )
    {
        if( (time(NULL) - startTime) > timeLimit )
            population.stopLoop();
    }
}
Beispiel #2
0
int main_plan(int argc, char* argv[]) {
   if (argc != 2)
      return -1;
   Plan p;
   p.fromFile(argv[1]);
   p.print(std::cout);
   return 0;
}
Beispiel #3
0
 constexpr 
     bool operator ==(const Plan<I, J, T>& _lhs,
                      const Plan<I, J, T>& _rhs) noexcept
 {
     return (_lhs.id() == _rhs.id())
             && (_lhs.job() == _rhs.job())
             && (_lhs.times == _rhs.times);
 }
Beispiel #4
0
lionheart::Action lionheart::MathewWarenski::wait(Plan p)
{
  if (p.hasAttack())
  {
    return p.attackEnemy();
  }
  return Action();
}
Beispiel #5
0
void Worklist::rememberCodeBlocks(VM& vm)
{
    LockHolder locker(m_lock);
    for (PlanMap::iterator iter = m_plans.begin(); iter != m_plans.end(); ++iter) {
        Plan* plan = iter->value.get();
        if (&plan->vm != &vm)
            continue;
        plan->rememberCodeBlocks();
    }
}
Beispiel #6
0
lionheart::Action lionheart::MathewWarenski::playInFortDefend(
    Unit const &u, SituationReport report, Plan p)
{
  auto dir = setdefdir(u, report);
  if (dir != u.getFacing())
    return turn(dir);
  if (p.hasAttack())
  {
    return p.attackEnemy();
  }
  return Action();
}
			Point InterceptorPlans::GetIntersectionPoint(const Plan & a, const Plan & b, const Vector & direction){
				Vector AB = b.Origin()-a.Origin();
				Basis baseA = a.Position();
				Basis baseB = b.Position();

				if((baseA.AxisZ()^direction) != Vector(0,0,0)){
					double beta = ( (baseA.AxisY()*baseB.AxisY())*(AB*baseB.AxisY()) + ((baseA.AxisY()*baseB.AxisZ())*(AB*baseB.AxisZ()) - AB*baseA.AxisY()) )
									/ ( (baseA.AxisY()*baseB.AxisY())*(baseA.AxisZ()*baseB.AxisY()) + (baseA.AxisY()*baseB.AxisZ())*(baseA.AxisZ()*baseB.AxisZ()));
					return baseA.Origin() + beta*baseA.AxisZ();
				}
				else{
					double beta = ( (baseA.AxisZ()*baseB.AxisY())*(AB*baseB.AxisY()) + ((baseA.AxisZ()*baseB.AxisZ())*(AB*baseB.AxisZ()) - AB*baseA.AxisZ()) )
								/ ( (baseA.AxisZ()*baseB.AxisY())*(baseA.AxisY()*baseB.AxisY()) + (baseA.AxisY()*baseB.AxisZ())*(baseA.AxisZ()*baseB.AxisZ()));
					return baseA.Origin() + beta*baseA.AxisY();
				}
			}
Beispiel #8
0
void CommandCreator::update(const Plan &plan, const GlobalMap &gMap)
{
  // make vector from current position to destination
  const Vector2DCont &vp=plan.getDst().getDstVect();
  // get vector of direction of robot
  const Vector2DCont &vd=gMap.getDir();

  // get angle between robot's direcion vector and destination in
  // radians (clock-wise)
  double angle=vd.getAngle(vp);

  TIERproto::Speed spd(0,0); // speed to set
  if( angle<_params._tolerance ||
      2*M_PI-_params._tolerance<angle)      // misdirection is suficiently
    spd=TIERproto::Speed( 250,  250);       // small not to change dir?
  else
    if(angle<M_PI)           // turn right?
      spd=TIERproto::Speed( 250, -250);
      //spd=TIERproto::Speed(   0,-250);
    else                     // turn left?
      spd=TIERproto::Speed(-250,  250);
      //spd=TIERproto::Speed(-250,   0);

  // critical section - set new speed
  {
    Lock lock(_mutex);
    _spdSet=spd;
  };
};
Beispiel #9
0
void addR_Cent(ADDvector& r_t, Plan& P, ADDvector& x, ADDvector& lambda, bool phase1 = false) {
	int t = 1;
	ADDvector R_Cent = -diag(lambda)*P.F(x, phase1) - ConstVector(1/t, lambda.count());
	for(int i = 0; i < R_Cent.count(); i++) {
		r_t[x.count() + i] = R_Cent[i];
	}
}
Beispiel #10
0
void addDiagFx(int offset, ADDvector x, SparceMatrix& lhs, Plan& P, bool phase1 = false) {
	ADDvector f_x = P.F(x, phase1);
	for(int i = 0; i < x.count(); i++) {
		lhs.set(offset, offset, -f_x[i]);
		offset++;
	}
}
Beispiel #11
0
void Worklist::removeDeadPlans(VM& vm)
{
    {
        LockHolder locker(m_lock);
        HashSet<CompilationKey> deadPlanKeys;
        for (PlanMap::iterator iter = m_plans.begin(); iter != m_plans.end(); ++iter) {
            Plan* plan = iter->value.get();
            if (&plan->vm != &vm)
                continue;
            if (plan->isKnownToBeLiveDuringGC())
                continue;
            RELEASE_ASSERT(plan->stage != Plan::Cancelled); // Should not be cancelled, yet.
            ASSERT(!deadPlanKeys.contains(plan->key()));
            deadPlanKeys.add(plan->key());
        }
        if (!deadPlanKeys.isEmpty()) {
            for (HashSet<CompilationKey>::iterator iter = deadPlanKeys.begin(); iter != deadPlanKeys.end(); ++iter)
                m_plans.take(*iter)->cancel();
            Deque<RefPtr<Plan>> newQueue;
            while (!m_queue.isEmpty()) {
                RefPtr<Plan> plan = m_queue.takeFirst();
                if (plan->stage != Plan::Cancelled)
                    newQueue.append(plan);
            }
            m_queue.swap(newQueue);
            for (unsigned i = 0; i < m_readyPlans.size(); ++i) {
                if (m_readyPlans[i]->stage != Plan::Cancelled)
                    continue;
                m_readyPlans[i] = m_readyPlans.last();
                m_readyPlans.removeLast();
            }
        }
    }
    
    // No locking needed for this part, see comment in visitWeakReferences().
    for (unsigned i = m_threads.size(); i--;) {
        ThreadData* data = m_threads[i].get();
        Safepoint* safepoint = data->m_safepoint;
        if (!safepoint)
            continue;
        if (&safepoint->vm() != &vm)
            continue;
        if (safepoint->isKnownToBeLiveDuringGC())
            continue;
        safepoint->cancel();
    }
}
Beispiel #12
0
bool operator<(const Plan &lhs,const Plan &rhs){
	std::vector<double> lhsP, rhsP;
	lhsP=lhs.getPriority();
	rhsP=rhs.getPriority();
	int counter=0;
	while(true){
		if(lhsP.size()<counter+1)
			return true;
		if(rhsP.size()<counter+1)
			return false;
		if(lhsP[counter]<rhsP[counter])
			return true;
		if(rhsP[counter]<lhsP[counter])
			return false;
		counter++;
	}
}
Beispiel #13
0
double evaluate(Plan& P) {
	//Compute Phase One
	ADDvector xPhase1(P.getNumStepsWithUnknownDurration() + P.getNumSteps() + P.getNumSlackVars() + 1);
	for(int i = 0; i < xPhase1.count(); i++) {
		xPhase1[i] = mgr.addZero();
	}
	xPhase1[xPhase1.count()-1] = mgr.constant(10000); //inital value for s
	ADDvector lambda(P.getNumFunctions());
	for(int i = 0; i < lambda.count(); i++) {
		lambda[i] = mgr.addZero();
	}
	ADDvector nu(P.getNumFunctions());
	for(int i = 0; i < nu.count(); i++) {
		nu[i] = mgr.addZero();
	}
	while(checkTeminationConditions(P, xPhase1, lambda, nu, true)) {
		ADDvector DxPhase1(xPhase1.count());
		ADDvector Dlambda(lambda.count());
		ADDvector Dnu(nu.count());
		calcStepDirection( xPhase1,  lambda,  nu,
				          DxPhase1, Dlambda, Dnu,
						   P, true);
		takeStep( xPhase1,  lambda,  nu,
				 DxPhase1, Dlambda, Dnu);
	}
	//Compute Phase two
	ADDvector x(xPhase1.count() -1);
	for(int i = 0; i < x.count(); i++) {
		x[i] = xPhase1[i];
	}
	while(checkTeminationConditions(P, x, lambda, nu, false)) {
		ADDvector Dx(x.count());
		ADDvector Dlambda(lambda.count());
		ADDvector Dnu(nu.count());
		calcStepDirection( x,  lambda,  nu,
				          Dx, Dlambda, Dnu,
						   P, false);
		takeStep( x,  lambda,  nu,
				 Dx, Dlambda, Dnu);
	}

	//Really I need to do some max's and sum's here but that can be added later.
	//Right now I need to add something to test all of this code.
	return 0;
}
Beispiel #14
0
void addR_Pri(ADDvector& r_t, Plan& P, ADDvector& x, ADDvector& lambda, bool phase1 = false) {
	//note phase 1 and 2 are the same here but the parameter is added for
	//symetry with the other calls
	int offset = lambda.count() + x.count();
	ADDvector R_Pri = *(P.A()) * x; // - b?
	for(int i = 0; i < lambda.count(); i++) {
		r_t[i+offset] = R_Pri[i];
	}
}
			Interception InterceptorPlans::Intercept(Plan& a, Plan& b) {
 				Interception interception;
				Vector direction = a.Normal() ^ b.Normal();
				if(direction == Vector(0,0,0)){
					if(a == b){
						interception.Type(InterceptionPlan);
						interception.SetPlan(a);
						return interception;
					}
					else{
						return interception;
					}
				}

				Line solution(GetIntersectionPoint(a,b,direction),direction);
				interception.Type(InterceptionLine);
				interception.SetLine(solution);
				return interception;
			}
Safepoint::Safepoint(Plan& plan, Result& result)
    : m_vm(plan.vm())
    , m_plan(plan)
    , m_didCallBegin(false)
    , m_result(result)
{
    RELEASE_ASSERT(result.m_wasChecked);
    result.m_wasChecked = false;
    result.m_didGetCancelled = false;
}
Beispiel #17
0
Plan DOptimization::optimizeÑontinuousPlan()
{
	double maxX = 0;
	double maxTrace = 0;

	mainOwnershipFunction = new OwnershipFunction(3, 2, 0.1, optimal->remarkCount);
	mainOwnershipFunction->calcFCMWithoutCenter((*optimal)[0]);
	mainLocalModel->calcFisherMatrix(*mainOwnershipFunction, *optimal);

	Plan newPlan = *optimal;

	for (double x = beginPoint; x <= endPoint; x += step)
	{
		double trace = isOptimal(x);

		if (abs(maxTrace - mainOwnershipFunction->elementCount) > abs(trace - mainOwnershipFunction->elementCount))
		{
			maxTrace = trace;
			maxX = x;
		}
	}

	if (abs(maxTrace - mainOwnershipFunction->elementCount) > 0.0001)
	{
		newPlan.enlarge(maxX);
		newPlan.clean();

		double newTrace = isOptimal(maxX, newPlan);

		if (abs(newTrace - mainOwnershipFunction->elementCount) > 0.0001)
		{
			*optimal = newPlan;
			return optimizeÑontinuousPlan();
		}
		else return *optimal;

	} 
	else
	{
		return newPlan;
	}
}
Beispiel #18
0
bool checkTeminationConditions(Plan& P, ADDvector& x, ADDvector& lambda, ADDvector& nu, bool phase1) {
	double epsilon_feas = .01;
	double epsilon = .01;
	ADDvector r_t = R_T(P, x, lambda, nu, phase1);
	ADD dist_r_pri = CalcDist(r_t, 0, x.count());
	ADD dist_r_dual = CalcDist(r_t, x.count() + lambda.count(), r_t.count());
	ADD lambdaTest = dotProduct(-P.F(x, phase1), lambda);
	return maximum(dist_r_pri) < epsilon_feas && 
		   maximum(dist_r_dual) < epsilon_feas && 
		   maximum(lambdaTest) < epsilon;
}
Beispiel #19
0
int main()
{
	HANDLE G;

	G = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(G, FOREGROUND_BLUE|FOREGROUND_INTENSITY);
	
	iKonto *wsk;

	FB_konto_ fbKonto; 
	Dziekanat_konto_ wdKonto;
	Wyswietlacz Wys;
	Plan P;

	wsk = &fbKonto;
	wsk->zaloguj();

	wsk = &wdKonto;
	wsk->zaloguj();
	
	if (fbKonto.zalogowanyFB == true && wdKonto.zalogowanyWD == true)
	{
		P.wczytaj_z_pliku();
		fbKonto.pobierz_wydarzenia(P);
		wdKonto.pobierz_wydarzenia(P);
		Wys.wyswietl_powiadomienia(P);
		Wys.wyswietl_menu(P);
	}
	
	wsk = &fbKonto;
	wsk->wyloguj();

	wsk = &wdKonto;
	wsk->wyloguj();

	P.zapisz_do_pliku();

	system("PAUSE");
}
Beispiel #20
0
void Worklist::visitWeakReferences(SlotVisitor& visitor)
{
    VM* vm = visitor.heap()->vm();
    {
        LockHolder locker(m_lock);
        for (PlanMap::iterator iter = m_plans.begin(); iter != m_plans.end(); ++iter) {
            Plan* plan = iter->value.get();
            if (&plan->vm != vm)
                continue;
            plan->checkLivenessAndVisitChildren(visitor);
        }
    }
    // This loop doesn't need locking because:
    // (1) no new threads can be added to m_threads. Hence, it is immutable and needs no locks.
    // (2) ThreadData::m_safepoint is protected by that thread's m_rightToRun which we must be
    //     holding here because of a prior call to suspendAllThreads().
    for (unsigned i = m_threads.size(); i--;) {
        ThreadData* data = m_threads[i].get();
        Safepoint* safepoint = data->m_safepoint;
        if (safepoint && &safepoint->vm() == vm)
            safepoint->checkLivenessAndVisitChildren(visitor);
    }
}
Beispiel #21
0
void addD2(SparceMatrix& lhs, ADDvector& x, Plan& P, bool phase1 = false) {
	if(phase1)
		return; //The second dirivative of s is 0. So leave it alone.

	int nSteps = P.getNumSteps();
	for(int i = 0; i < nSteps; i++) {
		ADD tmp = x[i] - x[i+nSteps];
		ADD val = mgr.addOne().Divide(tmp*tmp);
		lhs.set(i,i,-val);
		lhs.set(i,i+nSteps,-val);
		lhs.set(i+nSteps,i,val);
		lhs.set(i+nSteps,i+nSteps,val);
	}
}
Beispiel #22
0
lionheart::Action lionheart::MathewWarenski::playSmartCharge(
    Unit const &u, SituationReport report, Plan p)
{

  if (u.getType() == CROWN)
  {

    // if (p.movesToEnemy() < 6) return p.moveToLocation(15, 15);
    return Action();
  }

  if (p.movesToEnemyCrown() <= u.getMoveSpeed())
  {
    if (!p.hasAttack())
    {
      return p.moveToEnemyCrown();
    }
  }
  if (u.getType() == ARCHER)
  {
    if (!p.hasAttack())
    {
      if (enemyWaiting)
      {

        bool kingOnWall = false;
        for (int i = 0; i < 30; i++)
        {
          for (int j = 1; j <= 2; j++)
          {
            auto backwall = flipIfWest(ENEMY_EAST_WALL - j, 29);

            if (report.things[i][backwall].unit == CROWN)
            {
              kingY = i;
              kingX = backwall;
              kingOnWall = true;
            }
          }
        }

        if (kingOnWall)
        {
          auto col = flipIfWest(29, 29);
          auto loc = u.getLocation();
          if (loc.row == kingY && loc.col == col)
          {

            if (facingEast && u.getFacing() != lionheart::Direction::WEST)
            {
              return turn(lionheart::Direction::WEST);
            }
            else if (!facingEast && u.getFacing() != lionheart::Direction::EAST)
            {
              return turn(lionheart::Direction::EAST);
            }

            return lionheart::attack({ kingY, kingX });
          }
          else if (report.things[kingY][col].unit == ARCHER)
          {
            return p.attackEnemy();
          }

          return p.moveToLocation(kingY, col);
        }
      }

      return p.moveToEnemyCrown();
    }
  }
  if (p.hasAttack())
  {
    return p.attackEnemy();
  }
  return p.moveToEnemyCrown();
}
Beispiel #23
0
// function for game play
lionheart::Action lionheart::BrandonSmith::recommendAction(
  Unit const& u, SituationReport report, Plan p)
{
  ++numberofturns;
  auto loc = u.getLocation();
  find_kings(report);
  if (akingloc.col < 15) west = true;
  if (akingloc.col > 15) west = false;
  defpos(u, report);
  setdefdir(u, report);
  auto row = loc.row;
  auto col = loc.col;
  auto drow = defloc.row;
  auto dcol = defloc.col;

  if (u.getId() ==
      44) // give king bodyguard and prevents draw with non attacking armies
  {
    if (p.hasAttack()) return p.attackEnemy();
    if ((p.movesToAllyCrown() > 2) && (p.movesToEnemy() < 2))
      return p.moveToEnemy();
    if (p.movesToAllyCrown() > 2) return p.moveToAllyCrown();
  }

  if (u.getType() == CROWN) // rules for the king
  {
    if (p.hasAttack())
    {
      return p.attackEnemy();
    }
    if (mykingstupid(report))
    {
      if (west)
      {
        defloc.row = 14;
        defloc.col = 4;
        if ((row != 14) || (col != 4))
        {
          return p.moveToLocation(14, 4);
        }
      }
      if (!west)
      {
        defloc.row = 14;
        defloc.col = 25;
        if ((row != 14) || (col != 25))
        {
          return p.moveToLocation(14, 25);
        }
      }
    }

    if ((safe(row, col, report)) && (numberofturns < 300))
    {
      return turn(defdir);
    }

    if ((!safe(row, col, report)) || (enemyinthebox(report)))
    {
      ++whattodo;
      switch (whattodo)
      {
      case 0:
      case 1:
      case 2:
      case 3:
        if ((west) &&
            (report.things[19][3].type == lionheart::SituationReport::ALLY))
        {
          return p.moveToLocation(19, 2);
        }
        if ((west) &&
            (report.things[10][3].type == lionheart::SituationReport::ALLY))
        {
          return p.moveToLocation(10, 2);
        }
        if ((west))
        {
          return p.moveToLocation(19, 2);
        }
        if ((!west) &&
            (report.things[19][26].type == lionheart::SituationReport::ALLY))
        {
          return p.moveToLocation(19, 27);
        }
        if ((!west) &&
            (report.things[10][26].type == lionheart::SituationReport::ALLY))
        {
          return p.moveToLocation(10, 27);
        }
        if (!west)
        {
          return p.moveToLocation(19, 27);
        }
        break;
      case 4:
        if (akingloc.row > 15)
        {
          if (p.hasAttack())
            return p.attackEnemy();
          else
            return lionheart::turn(lionheart::Direction::NORTH);
        }

        else if (p.hasAttack())
          return p.attackEnemy();
        else
          return lionheart::turn(lionheart::Direction::SOUTH);
        break;
      case 5:
      case 6:
      case 7:
        if (safe(row, col, report))
        {
          return wait();
        }
        else
          return p.attackEnemy();
        break;
      }
    }
    if (safe(row, col, report))
    {
      return wait();
    }
    else
      return p.attackEnemy();
  }
  if ((numberofturns / 30) <
      10) // tells everyone what direction to face for defense;
  {
    if ((u.getFacing()) != defdir)
      return turn(defdir);
    else
      return wait();
  }

  if ((numberofturns / 30) <
      50) // this will stall in defense for half the game then attack
  {
    if (p.hasAttack()) return p.attackEnemy();
    if (enemyinthebox(report))
    {
      return p.attackEnemy();
    }
    if ((u.getId() == 39) || (u.getId() == 40))
    {
      if (p.movesToEnemy() < 3) return p.moveToEnemy();
      if ((row != drow) || (col != dcol)) return p.moveToLocation(drow, dcol);
      if ((u.getFacing()) != defdir)
        return turn(defdir);
      else
        return wait();
    }
    if ((u.getType() == KNIGHT) && (p.movesToEnemy() < 2))
      return p.moveToEnemy();
    if ((u.getType() != KNIGHT) && (p.movesToEnemy() < 5))
      return p.moveToEnemy();
    if ((row != drow) || (col != dcol)) return p.moveToLocation(drow, dcol);
    if ((u.getFacing()) != defdir)
      return turn(defdir);
    else
      return wait();
  }

  if (u.getType() == ARCHER) // sends archers around the fort if they can shoot
                             // over the wall and kill the king
  {
    return shootoverwall(u, report, p);
  }

  // tells everyone to attack
  if (p.hasAttack()) return p.attackEnemy();
  if (enemyinthebox(report)) return p.attackEnemy();
  if (p.movesToEnemyCrown() < 2)
    return p.moveToEnemyCrown();
  else
    return p.attackEnemy();
}
Beispiel #24
0
void addDF_x(int offset, ADDvector& x, ADDvector& lambda, SparceMatrix& lhs, Plan& P, bool phase1 = false) {
	SparceMatrix DF_x = P.DF_x(phase1);
	DF_x.Transpose().insertWithOffset(lhs, 0, offset);
	(-diag(lambda)*DF_x).insertWithOffset(lhs, offset, 0);
}
Beispiel #25
0
void event_privmsg(irc_session_t * session, const char * event, const char * origin, const char ** params, unsigned int count)
{

    char *pch;
    std::string comandos = params[1];
    std::vector<std::string> notificar;

    sql::Driver *driver;
    sql::Connection *con;
    sql::Statement *stmt;
    sql::ResultSet *res;

    driver = get_driver_instance();
    con = driver->connect(direccion, usuario, password);


    if ( !origin || count != 2 )
    return;

    irc_ctx_t * ctx = (irc_ctx_t *) irc_get_ctx (session);

    char nickbuf[128], text[1024];
    irc_target_get_nick (origin, nickbuf, sizeof(nickbuf));

    pch = strtok ((char *)params[1]," ,.-/\r\n");

    if(pch != NULL)
    {
        if(strcmp(pch,"login") == 0)
        {
            char *arg1;
            char *arg2;

            pch = strtok (NULL," ,.-/\r\n");
            if(pch == NULL){return;}
            arg1 = pch;

            pch = strtok (NULL," ,.-/\r\n");
            if(pch == NULL){return;}
            arg2 = pch;

            con->setSchema("bigbug");
            stmt = con->createStatement();
            char querysql[256];
            sprintf (querysql, "SELECT * from users where usuario = '%s' and clave = md5('%s');", arg1,arg2);
            res = stmt->executeQuery(querysql);
            while (res->next()) {

            if ( ctx->userLogged.find(nickbuf) == ctx->userLogged.end() )
            ctx->userLogged[nickbuf] = arg1;

                sprintf (text, "%s, estas loggeado.", nickbuf);
                irc_cmd_notice (session,  nickbuf, text);
            }
            delete res;
            delete stmt;
            delete con;
        }

        else if(strcmp(pch,"amilogin") == 0)
        {
            if ( ctx->userLogged.find(nickbuf) != ctx->userLogged.end() )
            {
                sprintf (text, "%s, estas loggeado. Usuario: %s", nickbuf,ctx->userLogged[nickbuf].c_str());
                irc_cmd_notice (session,  nickbuf, text);
            }
        }
        else if(strcmp(pch,"plan") == 0)
        {
            if ( ctx->userLogged.find(nickbuf) != ctx->userLogged.end() )
            {
                Plan *plan = new Plan(direccion, usuario, password);
                notificar = plan->procesar(ctx->userLogged[nickbuf],comandos.c_str());
                for(size_t i=0; i<notificar.size(); i++)
                {
                    irc_cmd_notice (session,  nickbuf, irc_color_convert_to_mirc(notificar[i].c_str()));
                }
                delete plan;
            }
        }


    }


}
Beispiel #26
0
void addR_Dual(ADDvector& r_t, Plan& P, ADDvector& x, ADDvector& lambda, ADDvector& mu, bool phase1 = false) {
	ADDvector R_Dual = P.DeltaF_0(x, phase1) + P.DF_x(phase1).Transpose() * lambda + P.A()->Transpose() * mu;
	for(int i = 0; i < R_Dual.count(); i++) {
		r_t[i] = R_Dual[i];
	}
}
Beispiel #27
0
void addAandAT(int offset, SparceMatrix& lhs, Plan& P) {
	P.A()->insertWithOffset(lhs, offset, 0);
	P.A()->Transpose().insertWithOffset(lhs, 0, offset);
}
Beispiel #28
0
std::unique_ptr<const bfly::PotentialField<R,d,q>>
transform
( const bfly::Context<R,d,q>& context,
  const Plan<d>& plan,
  const Amplitude<R,d>& amplitude,
  const Phase<R,d>& phase,
  const Box<R,d>& sBox,
  const Box<R,d>& tBox,
  const vector<Source<R,d>>& mySources )
{
#ifdef TIMING
    bfly::ResetTimers();
    bfly::timer.Start();
#endif
    typedef complex<R> C;
    const size_t q_to_d = Pow<q,d>::val;

    // Extract our communicator and its size
    MPI_Comm comm = plan.GetComm();
    int rank, numProcesses;
    MPI_Comm_rank( comm, &rank );
    MPI_Comm_size( comm, &numProcesses ); 

    // Get the problem-specific parameters
    const size_t N = plan.GetN();
    const size_t log2N = Log2( N );
    const array<size_t,d>& myInitialSBoxCoords = 
        plan.GetMyInitialSourceBoxCoords();
    const array<size_t,d>& log2InitialSBoxesPerDim = 
        plan.GetLog2InitialSourceBoxesPerDim();
    array<size_t,d> mySBoxCoords = myInitialSBoxCoords;
    array<size_t,d> log2SBoxesPerDim = log2InitialSBoxesPerDim;
    Box<R,d> mySBox;
    for( size_t j=0; j<d; ++j )
    {
        mySBox.widths[j] = sBox.widths[j] / (1u<<log2SBoxesPerDim[j]);
        mySBox.offsets[j] = sBox.offsets[j] + mySBox.widths[j]*mySBoxCoords[j];
    }

    array<size_t,d> myTBoxCoords, log2TBoxesPerDim;
    myTBoxCoords.fill(0);
    log2TBoxesPerDim.fill(0);
    Box<R,d> myTBox;
    myTBox = tBox;
    const size_t bootstrap = plan.GetBootstrapSkip();

    // Compute the number of source and target boxes that our process is 
    // responsible for initializing weights in
    size_t log2WeightGridSize = 0;
    size_t log2LocalSBoxes = 0;
    size_t log2LocalTBoxes = 0;
    array<size_t,d> log2LocalSBoxesPerDim, log2LocalTBoxesPerDim;
    log2LocalTBoxesPerDim.fill(0);
    for( size_t j=0; j<d; ++j )
    {
        if( log2N-log2SBoxesPerDim[j] >= bootstrap )
            log2LocalSBoxesPerDim[j]= (log2N-log2SBoxesPerDim[j]) - bootstrap;
        else
            log2LocalSBoxesPerDim[j] = 0;
        log2LocalTBoxesPerDim[j] = bootstrap;
        log2LocalSBoxes += log2LocalSBoxesPerDim[j];
        log2LocalTBoxes += log2LocalTBoxesPerDim[j];
        log2WeightGridSize += log2N-log2SBoxesPerDim[j];
    }

    // Initialize the weights using Lagrangian interpolation on the 
    // smooth component of the kernel.
    WeightGridList<R,d,q> weightGridList( 1u<<log2WeightGridSize );
#ifdef TIMING
    bfly::initializeWeightsTimer.Start();
#endif
    bfly::InitializeWeights
    ( context, plan, phase, sBox, tBox, mySBox, 
      log2LocalSBoxes, log2LocalSBoxesPerDim, mySources, weightGridList );
#ifdef TIMING
    bfly::initializeWeightsTimer.Stop();
#endif

    // Now cut the target domain if necessary
    for( size_t j=0; j<d; ++j )
    {
        if( log2LocalSBoxesPerDim[j] == 0 )
        {
            log2LocalTBoxesPerDim[j] -= bootstrap - (log2N-log2SBoxesPerDim[j]);
            log2LocalTBoxes -= bootstrap - (log2N-log2SBoxesPerDim[j]);
        }
    }

    // Start the main recursion loop
    if( bootstrap == log2N/2 )
    {
#ifdef TIMING
        bfly::M2LTimer.Start();
#endif
        bfly::M2L
        ( context, plan, amplitude, phase, sBox, tBox, mySBox, myTBox, 
          log2LocalSBoxes, log2LocalTBoxes,
          log2LocalSBoxesPerDim, log2LocalTBoxesPerDim, weightGridList );
#ifdef TIMING
        bfly::M2LTimer.Stop();
#endif
    }
    for( size_t level=bootstrap+1; level<=log2N; ++level )
    {
        // Compute the width of the nodes at this level
        array<R,d> wA, wB;
        for( size_t j=0; j<d; ++j )
        {
            wA[j] = tBox.widths[j] / (1<<level);
            wB[j] = sBox.widths[j] / (1<<(log2N-level));
        }

        if( log2LocalSBoxes >= d )
        {
            // Refine target domain and coursen the source domain
            for( size_t j=0; j<d; ++j )
            {
                --log2LocalSBoxesPerDim[j];
                ++log2LocalTBoxesPerDim[j];
            }
            log2LocalSBoxes -= d;
            log2LocalTBoxes += d;

            // Loop over boxes in target domain. 
            ConstrainedHTreeWalker<d> AWalker( log2LocalTBoxesPerDim );
            WeightGridList<R,d,q> oldWeightGridList( weightGridList );
            for( size_t tIndex=0; 
                 tIndex<(1u<<log2LocalTBoxes); ++tIndex, AWalker.Walk() )
            {
                const array<size_t,d> A = AWalker.State();

                // Compute coordinates and center of this target box
                array<R,d> x0A;
                for( size_t j=0; j<d; ++j )
                    x0A[j] = myTBox.offsets[j] + (A[j]+R(1)/R(2))*wA[j];

                // Loop over the B boxes in source domain
                ConstrainedHTreeWalker<d> BWalker( log2LocalSBoxesPerDim );
                for( size_t sIndex=0; 
                     sIndex<(1u<<log2LocalSBoxes); ++sIndex, BWalker.Walk() )
                {
                    const array<size_t,d> B = BWalker.State();

                    // Compute coordinates and center of this source box
                    array<R,d> p0B;
                    for( size_t j=0; j<d; ++j )
                        p0B[j] = mySBox.offsets[j] + (B[j]+R(1)/R(2))*wB[j];

                    // We are storing the interaction pairs source-major
                    const size_t iIndex = sIndex + (tIndex<<log2LocalSBoxes);

                    // Grab the interaction offset for the parent of target box 
                    // i interacting with the children of source box k
                    const size_t parentIOffset = 
                        ((tIndex>>d)<<(log2LocalSBoxes+d)) + (sIndex<<d);

                    if( level <= log2N/2 )
                    {
#ifdef TIMING
                        bfly::M2MTimer.Start();
#endif
                        bfly::M2M
                        ( context, plan, phase, level, x0A, p0B, wB, 
                          parentIOffset, oldWeightGridList,
                          weightGridList[iIndex] );
#ifdef TIMING
                        bfly::M2MTimer.Stop();
#endif
                    }
                    else
                    {
                        array<R,d> x0Ap;
                        array<size_t,d> globalA;
                        size_t ARelativeToAp = 0;
                        for( size_t j=0; j<d; ++j )
                        {
                            globalA[j] = A[j]+
                                (myTBoxCoords[j]<<log2LocalTBoxesPerDim[j]);
                            x0Ap[j] = tBox.offsets[j] + (globalA[j]|1)*wA[j];
                            ARelativeToAp |= (globalA[j]&1)<<j;
                        }
#ifdef TIMING
                        bfly::L2LTimer.Start();
#endif
                        bfly::L2L
                        ( context, plan, phase, level,
                          ARelativeToAp, x0A, x0Ap, p0B, wA, wB,
                          parentIOffset, oldWeightGridList, 
                          weightGridList[iIndex] );
#ifdef TIMING
                        bfly::L2LTimer.Stop();
#endif
                    }
                }
            }
        }
        else 
        {
            const size_t log2NumMerging = d-log2LocalSBoxes;

            log2LocalSBoxes = 0; 
            for( size_t j=0; j<d; ++j )
                log2LocalSBoxesPerDim[j] = 0;

            // Fully refine target domain and coarsen source domain.
            // We partition the target domain after the SumScatter.
            const vector<size_t>& sDimsToMerge = 
                plan.GetSourceDimsToMerge( level );
            for( size_t i=0; i<log2NumMerging; ++i )
            {
                const size_t j = sDimsToMerge[i];
                if( mySBoxCoords[j] & 1 )
                    mySBox.offsets[j] -= mySBox.widths[j];
                mySBoxCoords[j] /= 2;
                mySBox.widths[j] *= 2;
            }
            for( size_t j=0; j<d; ++j )
            {
                ++log2LocalTBoxesPerDim[j];
                ++log2LocalTBoxes;
            }

            // Compute the coordinates and center of this source box
            array<R,d> p0B;
            for( size_t j=0; j<d; ++j )
                p0B[j] = mySBox.offsets[j] + wB[j]/R(2);

            // Form the partial weights by looping over the boxes in the  
            // target domain.
            ConstrainedHTreeWalker<d> AWalker( log2LocalTBoxesPerDim );
            WeightGridList<R,d,q> partialWeightGridList( 1<<log2LocalTBoxes );
            for( size_t tIndex=0; 
                 tIndex<(1u<<log2LocalTBoxes); ++tIndex, AWalker.Walk() )
            {
                const array<size_t,d> A = AWalker.State();

                // Compute coordinates and center of this target box
                array<R,d> x0A;
                for( size_t j=0; j<d; ++j )
                    x0A[j] = myTBox.offsets[j] + (A[j]+R(1)/R(2))*wA[j];

                // Compute the interaction offset of A's parent interacting 
                // with the remaining local source boxes
                const size_t parentIOffset = ((tIndex>>d)<<(d-log2NumMerging));
                if( level <= log2N/2 )
                {
#ifdef TIMING
                    bfly::M2MTimer.Start();
#endif
                    bfly::M2M
                    ( context, plan, phase, level, x0A, p0B, wB,
                      parentIOffset, weightGridList,
                      partialWeightGridList[tIndex] );
#ifdef TIMING
                    bfly::M2MTimer.Stop();
#endif
                }
                else
                {
                    array<R,d> x0Ap;
                    array<size_t,d> globalA;
                    size_t ARelativeToAp = 0;
                    for( size_t j=0; j<d; ++j )
                    {
                        globalA[j] = A[j] +
                            (myTBoxCoords[j]<<log2LocalTBoxesPerDim[j]);
                        x0Ap[j] = tBox.offsets[j] + (globalA[j]|1)*wA[j];
                        ARelativeToAp |= (globalA[j]&1)<<j;
                    }
#ifdef TIMING
                    bfly::L2LTimer.Start();
#endif
                    bfly::L2L
                    ( context, plan, phase, level,
                      ARelativeToAp, x0A, x0Ap, p0B, wA, wB,
                      parentIOffset, weightGridList, 
                      partialWeightGridList[tIndex] );
#ifdef TIMING
                    bfly::L2LTimer.Stop();
#endif
                }
            }

            // Scatter the summation of the weights
#ifdef TIMING
            bfly::sumScatterTimer.Start();
#endif
            const size_t recvSize = 2*weightGridList.Length()*q_to_d;
            // Currently two types of planned communication are supported, as 
            // they are the only required types for transforming and inverting 
            // the transform:
            //  1) partitions of dimensions 0 -> c
            //  2) partitions of dimensions c -> d-1
            // Both 1 and 2 include partitioning 0 -> d-1, but, in general, 
            // the second category never requires packing.
            const size_t log2SubclusterSize = plan.GetLog2SubclusterSize(level);
            if( log2SubclusterSize == 0 )
            {
                MPI_Comm clusterComm = plan.GetClusterComm( level );
                SumScatter    
                ( partialWeightGridList.Buffer(), weightGridList.Buffer(),
                  recvSize, clusterComm );
            }
            else
            {
                const size_t log2NumSubclusters = 
                    log2NumMerging-log2SubclusterSize;
                const size_t numSubclusters = 1u<<log2NumSubclusters;
                const size_t subclusterSize = 1u<<log2SubclusterSize;

                const size_t numChunksPerProcess = subclusterSize;
                const size_t chunkSize = recvSize / numChunksPerProcess;
                const R* partialBuffer = partialWeightGridList.Buffer();
                vector<R> sendBuffer( recvSize<<log2NumMerging );
                for( size_t sc=0; sc<numSubclusters; ++sc )
                {
                    R* subclusterSendBuffer = 
                        &sendBuffer[sc*subclusterSize*recvSize];
                    const R* subclusterPartialBuffer = 
                        &partialBuffer[sc*subclusterSize*recvSize];
                    for( size_t p=0; p<subclusterSize; ++p )
                    {
                        R* processSend = &subclusterSendBuffer[p*recvSize];
                        for( size_t c=0; c<numChunksPerProcess; ++c )
                        {
                            memcpy 
                            ( &processSend[c*chunkSize],
                              &subclusterPartialBuffer
                              [(p+c*subclusterSize)*chunkSize],
                              chunkSize*sizeof(R) );
                        }
                    }
                }
                MPI_Comm clusterComm = plan.GetClusterComm( level );
                SumScatter
                ( &sendBuffer[0], weightGridList.Buffer(), 
                  recvSize, clusterComm );
            }
#ifdef TIMING
            bfly::sumScatterTimer.Stop();
#endif

            const vector<size_t>& tDimsToCut = plan.GetTargetDimsToCut( level );
            const vector<bool>& rightSideOfCut=plan.GetRightSideOfCut( level );
            for( size_t i=0; i<log2NumMerging; ++i )
            {
                const size_t j = tDimsToCut[i];
                myTBox.widths[j] /= 2;
                myTBoxCoords[j] *= 2;
                if( rightSideOfCut[i] )
                {
                    myTBoxCoords[j] |= 1;
                    myTBox.offsets[j] += myTBox.widths[j];
                }
                --log2LocalTBoxesPerDim[j];
                --log2LocalTBoxes;
            }
        }
        if( level==log2N/2 )
        {
#ifdef TIMING
            bfly::M2LTimer.Start();
#endif
            bfly::M2L
            ( context, plan, amplitude, phase, sBox, tBox, mySBox, myTBox,
              log2LocalSBoxes, log2LocalTBoxes, 
              log2LocalSBoxesPerDim, log2LocalTBoxesPerDim, weightGridList );
#ifdef TIMING
            bfly::M2LTimer.Stop();
#endif
        }
    }
Beispiel #29
0
int main(int ac, char ** av)
{
   SLBag<XDString,StringComp>* additions, *deletions, *preconditions;
   additions = new SLBag<XDString,StringComp>;          
   deletions = new SLBag<XDString,StringComp>;
   preconditions = new SLBag<XDString,StringComp>;
   additions->addMember(new XDString("on c a"));
   additions->addMember(new XDString("on a table"));
   additions->addMember(new XDString("on b table"));
   additions->addMember(new XDString("clear c"));
   additions->addMember(new XDString("clear b"));              
   Operator* one = new Operator(additions,preconditions,deletions);
   delete additions;
   delete preconditions;
   delete deletions;
   additions = new SLBag<XDString,StringComp>;          
   deletions = new SLBag<XDString,StringComp>;
   preconditions = new SLBag<XDString,StringComp>;
   preconditions->addMember(new XDString("on a b"));
   preconditions->addMember(new XDString("on b c"));
   Operator* two = new Operator(additions,preconditions,deletions);  
   delete additions;
   delete preconditions;
   delete deletions;
   
   Step *start = new Step(one);
   Step *finish = new Step(two);
   
   Requirement* req = new Requirement(finish, new XDString("on a b"));
   Requirement* req2 = new Requirement(finish, new XDString("on b c"));
   SLBag<Step,StepComp>* steps = new SLBag<Step,StepComp>;
   SLBag<Constrain,ConstComp>* constraints = new SLBag<Constrain,ConstComp>;
   SLBag<Conflict,ConflictComp>* conflicts = new SLBag<Conflict,ConflictComp>;
   SLBag<Link,LinkComp>* links = new SLBag<Link,LinkComp>;
   SLBag<Requirement,ReqComp>* requirements = new SLBag<Requirement,ReqComp>;
   SLBag<Operator, OperatorComp>* operators = new SLBag<Operator, OperatorComp>;
   Constrain* constraint = new Constrain(start, finish);
   constraints->addMember(constraint);
  
   requirements->addMember(req);
   requirements->addMember(req2);
   steps->addMember(start);
   steps->addMember(finish);

   additions = new SLBag<XDString,StringComp>;          
   deletions = new SLBag<XDString,StringComp>;
   preconditions = new SLBag<XDString,StringComp>;
   preconditions->addMember(new XDString("on c a"));
   preconditions->addMember(new XDString("clear c"));
   additions->addMember(new XDString("on c table"));
   additions->addMember(new XDString("clear a"));
   deletions->addMember(new XDString("on c a"));
   Operator* op1 = new Operator(additions,preconditions,deletions);
   delete additions;
   delete preconditions;
   delete deletions;
   additions = new SLBag<XDString,StringComp>;          
   deletions = new SLBag<XDString,StringComp>;
   preconditions = new SLBag<XDString,StringComp>;
   preconditions->addMember(new XDString("on a table"));
   preconditions->addMember(new XDString("clear a"));
   preconditions->addMember(new XDString("clear b"));
   additions->addMember(new XDString("on a b"));
   deletions->addMember(new XDString("on a table"));
   deletions->addMember(new XDString("clear b"));
   Operator* op2 = new Operator(additions,preconditions,deletions);
   delete additions;
   delete preconditions;
   delete deletions;
   additions = new SLBag<XDString,StringComp>;          
   deletions = new SLBag<XDString,StringComp>;
   preconditions = new SLBag<XDString,StringComp>;
   preconditions->addMember(new XDString("on b table"));
   preconditions->addMember(new XDString("clear b"));
   preconditions->addMember(new XDString("clear c"));
   additions->addMember(new XDString("on b c"));
   deletions->addMember(new XDString("on b table"));
   deletions->addMember(new XDString("clear c"));
   Operator* op3 = new Operator(additions,preconditions,deletions);
   operators->addMember(op1);
   operators->addMember(op2);
   operators->addMember(op3);
   Plan* plan = new Plan(steps, conflicts, constraints, links, requirements, operators);   
   Heuristic* heuristic = new Heuristic;
   plan  = (Plan* )best(plan, plan, heuristic);
   plan->display();
   return 1;
}
Beispiel #30
0
int main(int argc, char** argv) {
//	if (argc != 2) {
//		cerr << "usage: " << argv[0] << " <planFile>" << endl;
//		return -1;
//	}

	// parse schema
	cout << "-- parse schema from " << fileCreate << endl;
	Parser parser(fileCreate);
	unique_ptr<Schema> schema;
	try {
		schema = parser.parse();
		cout << schema->toString() << endl;
	} catch (ParserError& e) {
		cerr << e.what() << endl;
		return -1;
	}


	// setting everything up
	cout << endl << "-- init Buffer- and SegmentManager" << endl;
	BufferManager bm("/tmp/db", 10ul * 1024ul * 1024ul); // bogus arguments
	SegmentManager sm(bm);
	SegmentID spId = sm.createSegment(Segment::SegmentType::Schema, 200);
	SchemaSegment& scs = static_cast<SchemaSegment&>(sm.getSegment(spId));
	// read schema
	scs.readSchemaFromFile(fileCreate, &sm);


	// insert tuples
	cout << endl << "-- insert 5 tuples in each relation" << endl;
	SPSegment& students = static_cast<SPSegment&>(sm.getSegment(scs.getRelationSegmentID("student")));
	struct {int id; char name[64];} sstudent;
	for(int i=1; i<=5; i++){
		sstudent.id = i;
//		sstudent.name = "Student "+string(i);
		stringstream ss;
		ss << "Student " << i;
		strcpy(sstudent.name, ss.str().c_str());
		Record r(sizeof(sstudent), (char*) ((void*) (&sstudent)));
		students.insert(r); // TID id =
	}
	SPSegment& lectures = static_cast<SPSegment&>(sm.getSegment(
			scs.getRelationSegmentID("lecture")));
	struct {
		int id;
		char name[64];
	} slecture;
	for (int i = 1; i <= 5; i++) {
		slecture.id = i;
		stringstream ss;
		ss << "Lecture " << i;
		strcpy(slecture.name, ss.str().c_str());
		Record r(sizeof(slecture), (char*) ((void*) (&slecture)));
		lectures.insert(r);
	}
	SPSegment& exams = static_cast<SPSegment&>(sm.getSegment(
			scs.getRelationSegmentID("exam")));
	struct {
		int l_id;
		int s_id;
		int grade;
	} sexam;
	for (int i = 1; i <= 5; i++) {
		sexam.l_id = i;
		sexam.s_id = i; // 5-i
		sexam.grade = i + 3;
		Record r(sizeof(sexam), (char*) ((void*) (&sexam)));
		exams.insert(r);
	}


	// parse query plan
	cout << endl << "-- parse query plan from " << filePlan << endl;
	Plan p;
	p.fromFile(argv[1]);
	p.print(cout);
//	const plan::Operator* root = &p.getRoot();


	// walk down tree and execute the corresponding physical operators
	cout << endl << "-- generate tree of physical operators" << endl;
	operators::Operator* op = walkTree(p.getRoot(), scs, sm);


	// print results
	cout << endl << "-- print results" << endl;
	operators::Print print(op, cout);
	print.open();
	while(print.next()){}
	print.close();

	return 0;
}