Example #1
0
EXTERN_ENV
#define global extern

#include "stdinc.h"

/*
 * HACKGRAV: evaluate grav field at a given particle.
 */

void hackgrav(bodyptr p, long ProcessId)
{
   Local[ProcessId].pskip = p;
   SETV(Local[ProcessId].pos0, Pos(p));
   Local[ProcessId].phi0 = 0.0;
   CLRV(Local[ProcessId].acc0);
   Local[ProcessId].myn2bterm = 0;
   Local[ProcessId].mynbcterm = 0;
   Local[ProcessId].skipself = FALSE;
   hackwalk(ProcessId);
   Phi(p) = Local[ProcessId].phi0;
   SETV(Acc(p), Local[ProcessId].acc0);
#ifdef QUADPOLE
   Cost(p) = Local[ProcessId].myn2bterm + NDIM * Local[ProcessId].mynbcterm;
#else
   Cost(p) = Local[ProcessId].myn2bterm + Local[ProcessId].mynbcterm;
#endif
}
Example #2
0
	void cAStarHandler::AddOpenNode(cAINode *apAINode, cAStarNode *apParent, float afDistance)
	{
		//TODO: free path check with dynamic objects here.

		//TODO: Some pooling here would be good.
		cAStarNode *pNode = hplNew( cAStarNode, (apAINode) );

		//Check if it is in closed list.
		tAStarNodeSetIt it = m_setClosedList.find(pNode);
		if(it != m_setClosedList.end()){
			hplDelete(pNode);
			return;
		}

		//Try to add it to the open list
		std::pair<tAStarNodeSetIt, bool> testPair = m_setOpenList.insert(pNode);
		if(testPair.second == false){
			hplDelete(pNode);
			return;
		}

		pNode->mfDistance = afDistance;
		pNode->mfCost = Cost(afDistance,apAINode,apParent) + Heuristic(pNode->mpAINode->GetPosition(), mvGoal);
		pNode->mpParent = apParent;
	}
Example #3
0
void do_repair(shiptype *ship)
{
    reg int drep, cost;
    reg double maxrep;

    maxrep = REPAIR_RATE/(double)segments;
    /* stations repair for free, and ships docked with them */
    if(Shipdata[ship->type][ABIL_REPAIR]) cost = 0;
    else if(ship->docked && ship->whatdest==LEVEL_SHIP &&
            ships[ship->destshipno]->type==STYPE_STATION) cost = 0;
    else if(ship->docked && ship->whatorbits==LEVEL_SHIP &&
            ships[ship->destshipno]->type==STYPE_STATION) cost=0;
    else {
        maxrep *= (double)(ship->popn) / (double)ship->max_crew;
        cost = (int)(0.005 * maxrep * Cost(ship));
    }
    if (cost <= ship->resource) {
        use_resource(ship, cost);
        drep = (int)maxrep;
        ship->damage = MAX(0, (int)(ship->damage) - drep);
    } else {
        /* use up all of the ships resources */
        drep = (int)(maxrep*((double)ship->resource/(int)cost));
        use_resource(ship, ship->resource);
        ship->damage = MAX(0, (int)(ship->damage) - drep);
    }
}
Example #4
0
void Decoder::readTable(const char filename[], double prune_threshold,	unsigned int prune_count){
//==================Einlesen der Phrasentabelle============================
	PTree< pair <unsigned int, double> > pruningTree; //speichert für jede Übersetzung die Anzahl der eingelesenen Übersetzungen und die beste Übersetzung
	pair <unsigned int, double> pruningStart; //die Startkombi für den PruningTree
	pruningStart.first=0;
	pruningStart.second=(1./0.);

	igzstream in(filename);
	std::string line,token;


	while(getline(in,line)){
		std::stringstream ist(line);

		double relfreq_f, relfreq_e, source_to_target, target_to_source, unigram_sprachmodell;
		unsigned int singlecf, singlece; 
		vector<uint> ephrase, fphrase;

		//Ausgabe: relfreq_f relfreq_e # quellphrase # zielphrase # singlecf singlece # source_to_target target_to_source #  unigram-sprachmodell
		ist >> relfreq_f  >> relfreq_e >>token; // token für "#"

		while(ist>>token && token != "#"){
			fphrase.push_back(flex->getWord_or_add(token).wordId());
		}
		while(ist>>token && token != "#"){
			ephrase.push_back(elex->getWord_or_add(token).wordId());
		}
		ist >> singlecf >> singlece >> token >> source_to_target >> target_to_source >> token >> unigram_sprachmodell;

		Cost kosten=Cost();
		kosten.calc(relfreq_f, relfreq_e, fphrase, ephrase, singlecf, singlece, source_to_target, target_to_source, unigram_sprachmodell);
		double kosten_insgesamt=kosten.cost();

		pair< unsigned int, double>* pruning_infos=&pruningTree.traverse(fphrase,true,pruningStart)->c;

		if (kosten_insgesamt > pruning_infos->second+prune_threshold || pruning_infos->first >prune_count)	continue; //pruning ergibt, wir wollen es nicht in den Ptree mitaufnehmen

		//if (kosten_insgesamt< pruning_infos->second)	pruning_infos->second=kosten_insgesamt;  _jetzt irrelevant, da ich von einer geordneten eingabe ausgehe
		pruning_infos->first++;

		schwarz->traverse(fphrase,true)->c.traverse(ephrase,true,Cost(1./0.))->c = kosten;

	}
	//cerr << " schwarz erstellt" << endl;

}
Example #5
0
void FalloffCode::Build(nat32 dim,const math::Distance & dist)
{
 // First sort the nodes in the big array, lowest to highest by cost...
  data.Sort< SortOp<Node> >();


 // Now construct the kd tree, starting with the lowest cost node and so on.
 // This allows us to check for and delete nodes that have no affect on the cost
 // terrain...
  data[0].left = null<Node*>();
  data[0].right = null<Node*>();
  
  for (nat32 i=1;i<data.Size();i++)
  {
   // Check if the node in question is of sufficiently low cost to be allowed
   // in...
    if (Cost(dim,dist,data[i].Pos())<data[i].cost) continue;
   
   // Add the node to the kd tree...
    data[i].left = null<Node*>();
    data[i].right = null<Node*>();
   
    nat32 depth = 0;
    Node * targ = &(data[0]);
    while (true)
    {
     nat32 ord = depth%dim;
     if (data[i].Pos()[ord]<targ->Pos()[ord])
     {
      // Left...
       if (targ->left)
       {
        targ = targ->left;
        depth += 1;
       }
       else
       {
        targ->left = &(data[i]);
        break;
       }
     }
     else
     {
      // Right...
       if (targ->right)
       {
        targ = targ->right;
        depth += 1;
       }
       else
       {
        targ->right = &(data[i]);
        break;
       }
     }
    }
  }
}
Example #6
0
ompl::base::Cost ompl::base::goalRegionCostToGo(const State* state, const Goal* goal)
{
    const GoalRegion* goalRegion = goal->as<GoalRegion>();

    // Ensures that all states within the goal region's threshold to
    // have a cost-to-go of exactly zero.
    return Cost(std::max(goalRegion->distanceGoal(state) - goalRegion->getThreshold(),
                         0.0));
}
Example #7
0
/*------------------------------------------------------------------
 * Function:  Feasible
 * Purpose:   Check whether nbr could possibly lead to a better
 *            solution if it is added to the current tour.  The
 *            function checks whether nbr has already been visited
 *            in the current tour, and, if not, whether adding the
 *            edge from the current city to nbr will result in
 *            a cost less than the current best cost.
 * In args:   All
 * Global in:
 *    best_tour
 * Return:    TRUE if the nbr can be added to the current tour.
 *            FALSE otherwise
 */
int Feasible(tour_t tour, city_t city) {
   city_t last_city = Last_city(tour);

   if (!Visited(tour, city) && 
        Tour_cost(tour) + Cost(last_city,city) < Tour_cost(best_tour))
      return TRUE;
   else
      return FALSE;
}  /* Feasible */
Example #8
0
/*------------------------------------------------------------------
 * Function:  Remove_last_city
 * Purpose:   Remove last city from end of tour
 * In/out arg:
 *    tour
 * Note:
 *    Function assumes there are at least two cities on the tour --
 *    i.e., the hometown in tour->cities[0] won't be removed.
 */
void Remove_last_city(tour_t tour) {
   city_t old_last_city = Last_city(tour);
   city_t new_last_city;
   
   tour->cities[tour->count-1] = NO_CITY;
   (tour->count)--;
   new_last_city = Last_city(tour);
   tour->cost -= Cost(new_last_city,old_last_city);
}  /* Remove_last_city */
Example #9
0
/*------------------------------------------------------------------
 * Function:    Best_tour
 * Purpose:     Determine whether addition of the hometown to the 
 *              n-city input tour will lead to a best tour.
 * In arg:
 *    tour:     tour visiting all n cities
 * Ret val:
 *    TRUE if best tour, FALSE otherwise
 */
int Best_tour(tour_t tour) {
   cost_t cost_so_far = Tour_cost(tour);
   city_t last_city = Last_city(tour);

   if (cost_so_far + Cost(last_city, home_town) < Tour_cost(best_tour))
      return TRUE;
   else
      return FALSE;
}  /* Best_tour */
void Solve(int K,int n){
    for(int i=1;i<=n;i++ ) {
        dp[i][1]=Cost(1,i);
    }
    for(int i=2;i<=K;i++) {
        k=i;
        Func(1,n,1,n);
    }
    cout<<dp[n][k]<<endl;
}
Example #11
0
direction_t SmallestNeighbourDirection (location_t loc)
{
  direction_t result = NORTH;
  location_t neighbour;
  cost_t smallestCost;
  cost_t cost;

  smallestCost = MAX_COST;
  if (HasExit (loc, NORTH)) {
    neighbour = Neighbour (loc, NORTH);
    cost = Cost (neighbour);
    if (cost < smallestCost) {
      smallestCost = cost;
      result = NORTH;
    }
  }
  if (HasExit (loc, EAST)) {
    neighbour = Neighbour (loc, EAST);
    cost = Cost (neighbour);
    if (cost < smallestCost) {
      smallestCost = cost;
      result = EAST;
    }
  }
  if (HasExit (loc, SOUTH)) {
    neighbour = Neighbour (loc, SOUTH);
    cost = Cost (neighbour);
    if (cost < smallestCost) {
      smallestCost = cost;
      result = SOUTH;
    }
  }
  if (HasExit (loc, WEST)) {
    neighbour = Neighbour (loc, WEST);
    cost = Cost (neighbour);
    if (cost < smallestCost) {
      smallestCost = cost;
      result = WEST;
    }
  }
  return result;
}
// OOD constructor
TessLangModEdge::TessLangModEdge(CubeRecoContext *cntxt, int class_id) {
  root_ = false;
  cntxt_ = cntxt;
  dawg_ = NULL;
  start_edge_ = 0;
  end_edge_ = 0;
  edge_mask_ = 0;
  class_id_ = class_id;
  str_ = cntxt_->CharacterSet()->ClassString(class_id);
  path_cost_ = Cost();
}
void ModifiedFlood (location_t here)
{
  direction_t direction;
  cost_t smallestCost;
  ListReset();
  ListAdd (here);
  while (!ListIsEmpty()) {
    here = ListStackPop();
    if (Cost (here) == 0) {
      continue;
    }
    direction = SmallestNeighbourDirection (here);
    smallestCost = Cost (Neighbour (here, direction));
    SetDirection (here, direction);
    if (Cost (here) != smallestCost + 1) {
      SetCost (here, smallestCost + 1);
      AddOpenNeighboursToList (here);
    }
  }
}
Example #14
0
signed spellLaunchC::TurnsRequired()
{
 signed cost = Cost();
 cost -= Caster->SkillAvl;

 if(this == Caster->SpellQueue)
    cost -= Caster->SkillCommitted;

 if(cost <= 0) return 0;
 return 1 + (cost / Caster->Skill);
}
// leading, trailing punc constructor and single byte UTF char
TessLangModEdge::TessLangModEdge(CubeRecoContext *cntxt,
    const Dawg *dawg, EDGE_REF edge_idx, int class_id) {
  root_ = false;
  cntxt_ = cntxt;
  dawg_ = dawg;
  start_edge_ = edge_idx;
  end_edge_ = edge_idx;
  edge_mask_ = 0;
  class_id_ = class_id;
  str_ = cntxt_->CharacterSet()->ClassString(class_id);
  path_cost_ = Cost();
}
ompl::base::Cost ompl::base::MultiOptimizationObjective::stateCost(const State *s) const
{
    Cost c = identityCost();
    for (std::vector<Component>::const_iterator comp = components_.begin();
         comp != components_.end();
         ++comp)
    {
        c = Cost(c.value() + comp->weight * (comp->objective->stateCost(s).value()));
    }

    return c;
}
Example #17
0
ompl::base::Cost ompl::base::StateCostIntegralObjective::motionCost(const State *s1, const State *s2) const
{
    if (interpolateMotionCost_)
    {
        Cost totalCost = this->identityCost();

        int nd = si_->getStateSpace()->validSegmentCount(s1, s2);

        State *test1 = si_->cloneState(s1);
        Cost prevStateCost = this->stateCost(test1);
        if (nd > 1)
        {
            State *test2 = si_->allocState();
            for (int j = 1; j < nd; ++j)
            {
                si_->getStateSpace()->interpolate(s1, s2, (double)j / (double)nd, test2);
                Cost nextStateCost = this->stateCost(test2);
                totalCost = Cost(totalCost.value() +
                                 this->trapezoid(prevStateCost, nextStateCost, si_->distance(test1, test2)).value());
                std::swap(test1, test2);
                prevStateCost = nextStateCost;
            }
            si_->freeState(test2);
        }

        // Lastly, add s2
        totalCost = Cost(totalCost.value() +
                         this->trapezoid(prevStateCost, this->stateCost(s2), si_->distance(test1, s2)).value());

        si_->freeState(test1);

        return totalCost;
    }

        return this->trapezoid(this->stateCost(s1), this->stateCost(s2), si_->distance(s1, s2));
}
void Func(int l,int r,int x,int y){
    if(l>r) return;
    int mid=(l+r)>>1;
    if(vis[mid][k]) return;
    ll &res=dp[mid][k];
    res=INT_MAX;
    int Id=-1;
    for(int i=x;i<=min(y,mid);i++) {
        ll Tp=dp[i][k-1]+Cost(i+1,mid);
        if(res>Tp) {
            res=Tp,Id=i;
        }
    }
    Func(l,mid-1,x,Id);
    Func(mid+1,r,Id,y);
}
Example #19
0
ompl::base::Cost ompl::base::OptimizationObjective::averageStateCost(unsigned int numStates) const
{
    StateSamplerPtr ss = si_->allocStateSampler();
    State *state = si_->allocState();
    Cost totalCost(this->identityCost());

    for (unsigned int i = 0 ; i < numStates ; ++i)
    {
        ss->sampleUniform(state);
        totalCost = this->combineCosts(totalCost, this->stateCost(state));
    }

    si_->freeState(state);

    return Cost(totalCost.v / (double)numStates);
}
Example #20
0
int
Cost_If_Swap(int current_cost, int i1, int i2)
{
  int x = sol[i1];
  int r;

  x = sol[i1];
  sol[i1] = sol[i2];
  sol[i2] = x;

  r = Cost(NULL);

  sol[i2] = sol[i1];
  sol[i1] = x;

  return r;  
}
        Cost PathLengthDirectInfSampler::heuristicSolnCost(const State* statePtr) const
        {
            //Variable
            //The raw data in the state
            std::vector<double> rawData(informedSubSpace_->getDimension());

            //Get the raw data
            if ( StateSampler::space_->isCompound() == false )
            {
                informedSubSpace_->copyToReals(rawData, statePtr);
            }
            else
            {
                informedSubSpace_->copyToReals(rawData, statePtr->as<CompoundState>()->components[informedIdx_]);
            }

            //Calculate and return the length
            return Cost(phsPtr_->getPathLength(informedSubSpace_->getDimension(), &rawData[0]));
        }
Example #22
0
 virtual Cost cost(OperationContext &context, QueryExecutionContext &qec) const {
     return Cost();
 }
Example #23
0
ompl::base::Cost ompl::base::StateCostIntegralObjective::stateCost(const State *) const
{
    return Cost(1.0);
}
ompl::base::Cost ompl::base::PathLengthOptimizationObjective::motionCost(const State *s1, const State *s2) const
{
    return Cost(si_->distance(s1, s2));
}
Example #25
0
bool Plan_File::Read (long offset)
{
	//---- check the file status ----

	if (!Check_File ()) return (false);
	if (plan == NULL) return (Status (RECORD_SIZE));
	if (File_Access () != READ) return (Status (ERROR));

	//---- move to a specified location in the file ----

	if (offset >= 0) {
		if (!Offset (offset)) return (false);
	}

	//---- allocate space ----

	if (allocate_memory) {
		if (!Setup_Record ()) return (false);
	}

	//---- read the next plan ----

	if (Record_Format () == BINARY) {
		int num_token;

		if (!Db_File::Read (plan, (sizeof (Plan_Data) - sizeof (int)))) return (false);

		if (time_sort) {
			int temp = plan->key1;
			plan->key1 = plan->key2;
			plan->key2 = temp;
		}
		num_record++;
		num_plan++;

		if (Leg () == 2) {
			num_trip++;
		} else if (Leg () == 1 && Trip () == 1) {
			num_traveler++;
		}
		num_token = Tokens ();
		if (num_token > 0) {
			if (!Check_Size (num_token)) return (false);
			if (!Db_File::Read (&(plan->data [0]), num_token * sizeof (int))) return (Status (PLAN_FIELDS));

			num_record++;
		}
		return (true);
	} else {

		int field, max_field, value;
		char buffer [40], *ptr;

		field = max_field = 0;

		while (Db_File::Read ()) {
			num_record++;

			ptr = Clean_Record ();

			//---- check for a blank record ----

			if (ptr == NULL || *ptr == '\0') continue;

			//---- process the plan record ----

			while (ptr != NULL) {
				ptr = Get_Token (ptr, buffer, sizeof (buffer));

				if (buffer [0] == '\0') break;
				field++;
				value = atol (buffer);

				switch (field) {
					case 1:		//---- traveler id ----
						Traveler (value);
						num_plan++;
						break;
					case 2:		//---- user field ----
						break;
					case 3:		//---- trip id ----
						Trip (value);
						break;
					case 4:		//---- leg id ----
						Leg (value);
						if (value == 2) {
							num_trip++;
						} else if (value == 1 && Trip () == 1) {
							num_traveler++;
						}
						break;
					case 5:		//---- time ----
						Time (value);
						break;
					case 6:		//---- start id ----
						Start_ID (value);
						break;
					case 7:		//---- start type ----
						Start_Type (value);
						break;
					case 8:		//---- end id ----
						End_ID (value);
						break;
					case 9:		//---- end type ----
						End_Type (value);
						break;
					case 10:	//---- duration ----
						Duration (value);
						break;
					case 11:	//---- stop time ----
						Stop_Time (value);
						break;
					case 12:	//---- max time flag ----
						break;
					case 13:	//---- cost ----
						Cost (value);
						break;
					case 14:	//---- gcf ----
						GCF (value);
						break;
					case 15:	//---- driver flag ----
						Driver_Flag (value);
						break;
					case 16:	//---- mode ----
						Mode (value);
						break;
					case 17:	//---- number of tokens ----
						if (value < 0) {
							Status (PLAN_FIELDS);
							return (false);
						}
						Tokens (value);
						max_field = value + 17;

						if (value == 0) return (true);
						if (!Check_Size (value)) return (false);
						break;

					default:	//---- token value ----

						if (field > max_field) {
							Status (PLAN_FIELDS);
							return (false);
						}
						plan->data [field - 18] = value;

						if (field == max_field) return (true);
						break;
				}
			}
		}
		if (field != 0) {
			return (Status (PLAN_FIELDS));
		}
		return (false);
	}
}
Example #26
0
bool Plan_File::Write (Plan_Data *data)
{
	int num_token;
	FILE *file;

	//---- check the file status ----

	if (!Check_File ()) return (false);
	if (File_Access () == READ) return (Status (ERROR));

	Plan_Data *backup = NULL;

	if (data != NULL) {
		backup = plan;
		plan = data;
	} else {
		if (plan == NULL) return (Status (RECORD_SIZE));
	}

	//---- write the plan data ----

	file = File ();
	num_token = Tokens ();

	if (Record_Format () == BINARY) {
		if (time_sort) {
			int size, temp;
			size = sizeof (Plan_Data) - sizeof (int);

			memcpy (backup, plan, size);
			
			temp = backup->key1;
			backup->key1 = backup->key2;
			backup->key2 = temp;

			if (!Db_File::Write (backup, size)) goto reset;
		} else {
			if (!Db_File::Write (plan, (sizeof (Plan_Data) - sizeof (int)))) goto reset;
		}

		num_record++;
		num_plan++;

		if (Leg () == 2) {
			num_trip++;
		} else if (Leg () == 1 && Trip () == 1) {
			num_traveler++;
		}
		if (num_token > 0) {
			if (!Db_File::Write (&(plan->data [0]), num_token * sizeof (int))) goto reset;
			num_record++;
		}

	} else {

		if (fprintf (file, "%d 0 %d %d\n%d %d %d %d %d\n%d %d %d %d %d\n%d %d\n%d\n",
			Traveler (), Trip (), Leg (), 
			Time (), Start_ID (), Start_Type (), End_ID (), End_Type (),
			Duration (), Stop_Time (), 1, Cost (), GCF (), 
			Driver_Flag (), Mode (), 
			num_token) < 0) goto reset;

		num_record += 5;
		num_plan++;

		if (Leg () == 2) {
			num_trip++;
		} else if (Leg () == 1 && Trip () == 1) {
			num_traveler++;
		}

		//---- write tokens ----

		if (num_token > 0) {
			int field;
			int i = 0;

			switch (Mode ()) {
				case AUTO_MODE:		//---- auto ----
					if (Driver_Flag ()) {

						//---- vehicle ID and number of passengers ----

						i = 2;
						if (fprintf (file, "%d %d\n", plan->data [0], plan->data [1]) < 0) goto reset;
						num_record++;
					}
					break;
				case TRANSIT_MODE:		//---- transit ----
					if (Driver_Flag ()) {

						//---- schedule pairs, vehicle ID, and route ID ----

						i = 3;
						if (fprintf (file, "%d %d %d\n", plan->data [0], plan->data [1], plan->data [2]) < 0) goto reset;
						num_record++;
					}
					break;
				default:
					break;
			}

			//---- print the rest of the fields in groups of 10 ----

			for (field=0; i < num_token; i++, field++) {
				if (!field) {
					if (fprintf (file, "%d", plan->data [i]) < 0) goto reset;
					num_record++;
				} else if (!(field % 10)) {
					if (fprintf (file, "\n%d", plan->data [i]) < 0) goto reset;
					num_record++;
				} else {
					if (fprintf (file, " %d", plan->data [i]) < 0) goto reset;
				}
			}
			if (field) {
				if (fprintf (file, "\n") < 0) goto reset;
			}
		}

		//---- add a blank line at the end of the plan ----

		if (fprintf (file, "\n") < 0) goto reset;
		num_record++;

		Flush ();
	}
	if (data != NULL) {
		plan = backup;
	}
	return (true);

reset:
	if (data != NULL) {
		plan = backup;
	}
	return (false);
}
Example #27
0
ompl::base::Cost ompl::base::OptimizationObjective::infiniteCost() const
{
    return Cost(std::numeric_limits<double>::infinity());
}
Example #28
0
ompl::base::Cost ompl::base::OptimizationObjective::identityCost() const
{
    return Cost(0.0);
}
Example #29
0
ompl::base::Cost ompl::base::OptimizationObjective::combineCosts(Cost c1, Cost c2) const
{
    return Cost(c1.v + c2.v);
}
Example #30
0
ompl::base::Cost ompl::base::OptimizationObjective::stateCost(const State *s) const
{
    return Cost(1.0);
}