Exemplo n.º 1
0
    void initAllTrainsVec(std::string initialInTrainsFilePath)
    {
        // get all the initial in trains
        FILE * pFile = fopen(initialInTrainsFilePath.c_str(), "r");
        if(pFile == NULL)
            perror ("Error opening file");
        else
        {
            // get arriving trains
            for(int i=0; i<allArrivalsVec.size(); i++)
            {
                Train t;
                t.setupFromAnArrival(allArrivalsVec[i]);
                allTrainsVec.push_back(t);
            }

            ignoreFirstLine(pFile);
            while(true)
            {
                if(feof(pFile)) break;
                Train t;
                t.setupTheInitialInTrainFromFile(pFile);
                allTrainsVec.push_back(t);
            }
            fclose(pFile);

        }

    }
Exemplo n.º 2
0
Passenger Station::fromTrainToQueue()
{
		Passenger curr;
		Train *train = aTrain;
		
	//This for loop goes through all train cars, finds everyone who needs to transfer at B3 and brings them to the appropriate station queue.
	for(int j=1;j<4;j++)
	{	
		for(int i=1; i<=train->getNumberInCar(j); i++)
		{
			curr=train->find(j, i);
	
			if(stationName=="B3R" && (curr.destination=="B1" || curr.destination=="B2" || curr.destination=="A5")) //If the station is B3-RED && Passenger wants to go to BLUE stations
				{
					curr=train->remove(j,i); //Remove the passenger at Car 1, pos i
					return curr; 			//Return the temp pointer for the removed passenger to transferB3()
				}

				//Else if north train is on a blue line.
			else if(stationName=="B3B" && (curr.destination=="A1" || curr.destination=="A2" ||
				curr.destination=="A3" || curr.destination=="A4" || curr.destination=="B4" ||
				curr.destination=="B5")) //If the station is B3-BLUE && Passenger wants to go to RED stations
				{
					curr=train->remove(j,i); //Car 1, at pos i
					return curr; //Return temp to transferB3()
				}
		}
	}
	//If nobody else wants to transfer, the desination is set to -1. This is used to end the loop in the caller function transferB3().
	curr.destination = "-1";
	return curr;
}
Exemplo n.º 3
0
Train * ArrivalEvent :: run()
{
    int i = 0;
    Train * currentTrain = dynamic_cast<Train *>((activeQueue)->get(i));

    if((activeQueue)->length() > 0)
    {
        while(i < (activeQueue)->length() && currentTrain->arrivalTime() > currentTime)
        {
            i++;
            (activeQueue)->insert(currentTrain);
            currentTrain = dynamic_cast<Train *>((activeQueue)->get(i));
        }

        if(i == (activeQueue)->length())
        {
            currentTrain = NULL;
        }

    }
    else
    {
        currentTrain = NULL;
    }

    if(i == (activeQueue)->length())
    {
        currentTrain = NULL;
    }

    return currentTrain;
}
Exemplo n.º 4
0
void addLocomotive(int t){
	Locomotive * locomotive = new Locomotive; 
	Train * train = new Train;
	train->addVehicle(0,locomotive);
	d.game->sim.addTrain(train);
	Point p = locomotive->getPos();
	Rail * r = d.game->sim.railMap.getRailAt(p.row,p.col);
	if(r) locomotive->gotoRail(r);
	d.locomotive = locomotive;
}
Exemplo n.º 5
0
int main(int argc,char** argv) {
    Train tr;
    Test te;
    std::cout << argv[1] << std::endl;
    string s = argv[1];
    if (s == "train")
        tr.train();
    else if (s == "test")
        te.test();
    system("pause");
}
Exemplo n.º 6
0
Records:: Records(const Real          scale,
                  const Matrix<Real> &neurodata,
                  const size_t        num_neurons) :
Object(scale),
RecordsBase( __get_num_trials(neurodata.rows,num_neurons), num_neurons ),
trials(rows),
neurones(cols),
maxCount(0),
tauMin(0),
tauMax(0)
{
    build_with<Train*>(NULL);
    RecordsBase &self = *this;
    size_t iTrain = 0;
    size_t count  = 0;
    Unit   tMin   = 0;
    Unit   tMax   = 0;
    bool   init   = true;
    for(size_t iN = 0; iN < neurones; ++iN )
    {
        for(size_t iT = 0; iT < trials; ++iT )
        {
            Train *tr = new Train(scale,neurodata,iTrain);
            self[iT][iN].reset(tr);
            const size_t trSize = tr->size();
            if(init)
            {
                if(trSize>0)
                {
                    tMin = (*tr)[0];
                    tMax = (*tr)[trSize-1];
                    init = false;
                }
            }
            else
            {
                if(trSize>0)
                {
                    tMin = min_of(tMin,(*tr)[0]);
                    tMax = max_of(tMax,(*tr)[trSize-1]);
                }
            }
            ++iTrain;
            if(trSize>count) count = trSize;
        }
    }
    (size_t&)maxCount = count;
    (size_t&)tauMin   = tMin;
    (size_t&)tauMax   = tMax;
}
Exemplo n.º 7
0
int main(int argc, char**argv)
{
	srand((unsigned)time(NULL));
	int method = 1;
	int n = 50;
	double rate = 0.001;
	double margin = 1;
	int i;

	if ((i = ArgPos((char *)"-l1", argc, argv)) > 0) L1_flag = atoi(argv[i + 1]);
	if ((i = ArgPos((char *)"-method", argc, argv)) > 0) method = atoi(argv[i + 1]);
	if ((i = ArgPos((char *)"-size", argc, argv)) > 0) n = atoi(argv[i + 1]);
	if ((i = ArgPos((char *)"-rate", argc, argv)) > 0) rate = atof(argv[i + 1]);
	if ((i = ArgPos((char *)"-margin", argc, argv)) > 0) margin = atof(argv[i + 1]);

	cout << "L1_Flag = " << L1_flag << endl;
	cout << "size = " << n << endl;
	cout << "rate = " << rate << endl;
	cout << "margin = " << margin << endl;
	if (method)
		version = "bern";
	else
		version = "unif";
	cout << "method = " << version << endl;
	prepare();
	train.run(n, rate, margin, method);
}
Exemplo n.º 8
0
	// The = operator is used to perform a deep copy of the Train contained
	// on the right hand side of the statement to the current instance. It 
	// copies the residing primitive element values to a new Node instance
	// so therefore it doesn't just simply copy the pointers. 
	Train Train::operator=(Train & rhs) {
		// Invokes the copy method corresponding to the internal list. It
		// passes the head Node of the train enabling for the list to be
		// traversed.
		this->linked_list->copy(rhs.getList()->getHead());
		// Returns the pointer to the current Train instance.
		return *this;
	}
Exemplo n.º 9
0
	// The += operator is used to append the contents of the right hand side
	// train to the left. It is used for example in a statement like train1 += train2.
	// It enables for the Train carriages to be simply appended together.
	Train Train::operator+=(Train & rhs) {
		// Iterates foreach node in the (right hand side) Train.
		for (const Node<Carriage>* current = rhs.getList()->getHead(); current != NULL; 
									current = current->link()) {
			// Adds the node data to the Last position of the LinkedList.
			this->linked_list->addLast(current->data());				
		}
		// Returns the pointer to the current Train instance.
		return *this;
	}
Exemplo n.º 10
0
/**
 * Highlight the position where a rail vehicle is dragged over by drawing a light gray background.
 * @param px        The current x position to draw from.
 * @param max_width The maximum space available to draw.
 * @param selection Selected vehicle that is dragged.
 * @param chain     Whether a whole chain is dragged.
 * @return The width of the highlight mark.
 */
static int HighlightDragPosition(int px, int max_width, VehicleID selection, bool chain)
{
	bool rtl = _current_text_dir == TD_RTL;

	assert(selection != INVALID_VEHICLE);
	int dragged_width = WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
	for (Train *t = Train::Get(selection); t != NULL; t = chain ? t->Next() : (t->HasArticulatedPart() ? t->GetNextArticulatedPart() : NULL)) {
		dragged_width += t->GetDisplayImageWidth(NULL);
	}

	int drag_hlight_left = rtl ? max(px -dragged_width, 0) : px;
	int drag_hlight_right = rtl ? px : min(px + dragged_width, max_width);
	int drag_hlight_width = max(drag_hlight_right - drag_hlight_left, 0);

	if (drag_hlight_width > 0) {
		GfxFillRect(drag_hlight_left + WD_FRAMERECT_LEFT, WD_FRAMERECT_TOP + 1,
				drag_hlight_right - WD_FRAMERECT_RIGHT, ScaleGUITrad(13) - WD_FRAMERECT_BOTTOM, _colour_gradient[COLOUR_GREY][7]);
	}

	return drag_hlight_width;
}
Exemplo n.º 11
0
int main(int argc,char**argv)
{
    srand((unsigned) time(NULL));
    if (argc!=2)
        return 0;
    else
    {
        version = argv[1];
        prepare();
        train.run();
    }
}
Exemplo n.º 12
0
void
PulseClusterer::allHitsLoaded()
{
	if (!isComplete()) {
		// scan multi-map in mid-bin order
		Train cluster;
		bool first = true;
		TripletList::iterator i;
	//	cout << (dec) << tripletList.size() << " triplets" << endl;
		lock();
		for (i = tripletList.begin(); i!= tripletList.end(); i++) {
			bool switchClusters = false;
			if (first)
				switchClusters = true;
			else if (!absorb(cluster, *i))
				switchClusters = true;

			if (switchClusters) {
				if (!first)
					clusterDone(cluster);
				first = false;
				// start new cluster
				cluster.pulses.clear();
				cluster.histogram.clear();
				int period = (*i).second.pulses[1].spectrum
							- (*i).second.pulses[0].spectrum;
				cluster.histogram[period].val += 1;
				for (int j=0; j<TSZ; j++)
					cluster.addPulse((*i).second.pulses[j]);
				cluster.loBin = cluster.hiBin = (*i).first;
			}

		}
		if (!first)
			clusterDone(cluster);

		ChildClusterer::allHitsLoaded();
		unlock();
	}
}
Exemplo n.º 13
0
int _tmain(int argc, _TCHAR* argv[])
{
	SetConsoleCP(1251);
	SetConsoleOutputCP(1251);
	setlocale(LC_ALL, "Rus");

	Train *trains = nullptr;
	int count = 0;

	cout << "¬ведите количество поездов: ";
	cin >> count;

	trains = new Train[count];

	cout << "=========================================================================\n";

	for (int i = 0; i < count; ++i) {
		trains[i].Show();
		cout << "=========================================================================\n";
	}

	Train *maxTrain = GetMaxTrain(trains, count);
	cout << "Ќаибольшее количество пассажиров в поезде номер " << maxTrain->GetTrainNumber() << endl;
	cout << " оличество пассажиров: " << maxTrain->GetPassengersCount() << endl;

	Train *minTrain = GetMinTrain(trains, count);
	cout << "Ќаименьшее количество пассажиров в поезде номер " << minTrain->GetTrainNumber() << endl;
	cout << " оличество пассажиров: " << minTrain->GetPassengersCount() << endl;


	delete[] trains;
	system("pause");
	return 0;
}
Exemplo n.º 14
0
int main(int argc, char* argv[])
{
  char c;
  int numStations, numCars, numActions;
  Action *actions = new Action[1000000];
  ifstream inf(argv[1]);
  inf >> numStations >> c >> numCars;
  Station *stations = new Station[numStations];
  Station *stations2 = new Station[numStations];
  Car *cars = new Car[numCars];
  readFile(inf, stations, numStations, numCars, cars);
  memcpy(stations2, stations, sizeof(Station) * numStations);
  CPUTimer ct;
  Train *train = new Train(stations, numStations);
  delete [] stations;
  train->run((const Car*) cars, numCars, actions, &numActions);
  double time = ct.cur_CPUTime();
  int totalDistance = checkActions(actions, numActions, stations2, 
    numStations,cars, numCars);
  cout << "CPU time: " << time << " Total distance: " << totalDistance << endl;
  return 0;
}  // main()
Exemplo n.º 15
0
void Station::fromQueueToTrain()
{


	Train *train = aTrain;
	Queue *queue = aQueue;

	if(!train)
		return; //If there is no train, end the function.

	for(int i=0; i<12; i++)
	{
		// all i that are less than 4 will be rounded to zero
		double cabin = floor(i/4);

		//convert the double to an int type
		int car= static_cast<int>(cabin);

		//get that number in car+1= from 1-3
		int numberInCar = train->getNumberInCar(car+1);
		//This while loop loads all passengers waiting on the queues into the trains.
		while(numberInCar != 64 && emptyQueues(car*4))
		{
				for(int i=car*4; i<((car*4)+4); i++)
				{
					if((queue)[i].isEmpty()==false && numberInCar < 64)
					{	
						train->load((queue)[i].dequeue(),car+1);
						numberInCar=train->getNumberInCar(car+1);
						
					}
				}

		}


	}
}
Exemplo n.º 16
0
void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	gluLookAt(0.0, 3.0, 10.0,
			  0.0, 0.0, 0.0,
			  0.0, 1.0, 0.0);

	track.draw();
	train1.draw();
	//train2.draw();

	glutSwapBuffers();
}
Exemplo n.º 17
0
bool
PulseClusterer::absorb(Train &cluster, const pair<float, Triplet>&i)
{
	if (i.first > cluster.hiBin + clusterRange)
		return false;
	// adjust signal
	Tr(detail,("absorb triplet at %f into train max %f",
			i.first, cluster.hiBin + clusterRange));
	int period = i.second.pulses[1].spectrum
				- i.second.pulses[0].spectrum;
	cluster.histogram[period].val += 1;
	cluster.hiBin = i.first;
	for (int j=0; j<TSZ; j++)
		cluster.addPulse(i.second.pulses[j]);
	return true;
}
Exemplo n.º 18
0
int main(int argc, const char* argv[])
{
	/** preprocessing **/
	srand( 0 );

	const char train_file[] = "../train_edges.bpr";
	const int K = 10;
	const double learning_rate = 0.1;
	const double reg_user = 0.01;
	const double reg_item = 0.01;

	/** data part **/
	Train train;
	train.Read_File(train_file);
	cerr << train.Nuser() << " " << train.Nitem() << endl;

	/** model declaration **/
	Model model(train.Nuser(), train.Nitem(), K);

	for (int iter = 0; iter < 1000; iter++) {
		cout << iter << endl;
		vector<Pair> sample = train.draw_sample(1);
		model.update(sample, learning_rate, reg_user, reg_item);

		if (iter % 100 == 99) {
			fstream f;
			f.open("../test_nodes.txt", ios::in);
			fstream p; 
			char filename[100];
			sprintf(filename, "predict_%d.txt", iter);
			p.open(filename, ios::out);
			size_t u;
			while (f >> u) 
			{
				p << u << ":";
				vector<Pair_i_y> predict = predict_top_N(train, model, u, 30);
				p << predict[0].i;
				for (size_t n = 1; n < 30; n++)
				{
					p << "," << predict[n].i;
				}
				p << endl;
			}
		}


	}
Exemplo n.º 19
0
void IncomingSwitch :: printList()
{
    int i = 0;
    cout << "Train #" << "     " << "Arrival Time" << "     " << "InSwitch Time"
    << "     " << "Station Time" << "     " << "Departure Time" << "     "
    << "OutSwitch Time" << "     " << "Total Wait Time" << endl;


    while(i < length())
    {
        Train * activeTrain = dynamic_cast<Train *>(get(i));

        cout << activeTrain->trainNumber() << "     " << activeTrain->arrivalTime() //Does the formating for the text block output
        << activeTrain->getInTime() << "     " << activeTrain->waitTime() << "     "
        << activeTrain->departureTime() << "     " << activeTrain->getOutTime()
        << "     " << activeTrain->getTotalWait() << endl;

        i++;
    }
}
Exemplo n.º 20
0
void idle(void)
{
	double delta_t;		// the time span since last display

	// calculate time span since last display and reset time variable
	delta_t = (clock() - t) / (double)CLOCKS_PER_SEC;
	t = clock();

	if (!play)
		return;

	train1.integrate_motion(delta_t, track);
	//train2.integrate_motion(delta_t, track);

	// detect collision


	glutPostRedisplay();
}
Exemplo n.º 21
0
/*
 * Link front and rear multiheaded engines to each other
 * This is done when loading a savegame
 */
void ConnectMultiheadedTrains()
{
	Train *v;

	FOR_ALL_TRAINS(v) {
		v->other_multiheaded_part = NULL;
	}

	FOR_ALL_TRAINS(v) {
		if (v->IsFrontEngine() || v->IsFreeWagon()) {
			/* Two ways to associate multiheaded parts to each other:
			 * sequential-matching: Trains shall be arranged to look like <..>..<..>..<..>..
			 * bracket-matching:    Free vehicle chains shall be arranged to look like ..<..<..>..<..>..>..
			 *
			 * Note: Old savegames might contain chains which do not comply with these rules, e.g.
			 *   - the front and read parts have invalid orders
			 *   - different engine types might be combined
			 *   - there might be different amounts of front and rear parts.
			 *
			 * Note: The multiheaded parts need to be matched exactly like they are matched on the server, else desyncs will occur.
			 *   This is why two matching strategies are needed.
			 */

			bool sequential_matching = v->IsFrontEngine();

			for (Train *u = v; u != NULL; u = u->GetNextVehicle()) {
				if (u->other_multiheaded_part != NULL) continue; // we already linked this one

				if (u->IsMultiheaded()) {
					if (!u->IsEngine()) {
						/* we got a rear car without a front car. We will convert it to a front one */
						u->SetEngine();
						u->spritenum--;
					}

					/* Find a matching back part */
					EngineID eid = u->engine_type;
					Train *w;
					if (sequential_matching) {
						for (w = u->GetNextVehicle(); w != NULL; w = w->GetNextVehicle()) {
							if (w->engine_type != eid || w->other_multiheaded_part != NULL || !w->IsMultiheaded()) continue;

							/* we found a car to partner with this engine. Now we will make sure it face the right way */
							if (w->IsEngine()) {
								w->ClearEngine();
								w->spritenum++;
							}
							break;
						}
					} else {
						uint stack_pos = 0;
						for (w = u->GetNextVehicle(); w != NULL; w = w->GetNextVehicle()) {
							if (w->engine_type != eid || w->other_multiheaded_part != NULL || !w->IsMultiheaded()) continue;

							if (w->IsEngine()) {
								stack_pos++;
							} else {
								if (stack_pos == 0) break;
								stack_pos--;
							}
						}
					}

					if (w != NULL) {
						w->other_multiheaded_part = u;
						u->other_multiheaded_part = w;
					} else {
						/* we got a front car and no rear cars. We will fake this one for forget that it should have been multiheaded */
						u->ClearMultiheaded();
					}
				}
			}
		}
	}
}
Exemplo n.º 22
0
/**
 *  Converts all trains to the new subtype format introduced in savegame 16.2
 *  It also links multiheaded engines or make them forget they are multiheaded if no suitable partner is found
 */
void ConvertOldMultiheadToNew()
{
	Train *t;
	FOR_ALL_TRAINS(t) SetBit(t->subtype, 7); // indicates that it's the old format and needs to be converted in the next loop

	FOR_ALL_TRAINS(t) {
		if (HasBit(t->subtype, 7) && ((t->subtype & ~0x80) == 0 || (t->subtype & ~0x80) == 4)) {
			for (Train *u = t; u != NULL; u = u->Next()) {
				const RailVehicleInfo *rvi = RailVehInfo(u->engine_type);

				ClrBit(u->subtype, 7);
				switch (u->subtype) {
					case 0: // TS_Front_Engine
						if (rvi->railveh_type == RAILVEH_MULTIHEAD) u->SetMultiheaded();
						u->SetFrontEngine();
						u->SetEngine();
						break;

					case 1: // TS_Artic_Part
						u->subtype = 0;
						u->SetArticulatedPart();
						break;

					case 2: // TS_Not_First
						u->subtype = 0;
						if (rvi->railveh_type == RAILVEH_WAGON) {
							/* normal wagon */
							u->SetWagon();
							break;
						}
						if (rvi->railveh_type == RAILVEH_MULTIHEAD && rvi->image_index == u->spritenum - 1) {
							/* rear end of a multiheaded engine */
							u->SetMultiheaded();
							break;
						}
						if (rvi->railveh_type == RAILVEH_MULTIHEAD) u->SetMultiheaded();
						u->SetEngine();
						break;

					case 4: // TS_Free_Car
						u->subtype = 0;
						u->SetWagon();
						u->SetFreeWagon();
						break;
					default: NOT_REACHED();
				}
			}
		}
	}
}
Exemplo n.º 23
0
void prepare()
{
    FILE* f1 = fopen("../data/entity2id.txt","r");
	FILE* f2 = fopen("../data/relation2id.txt","r");
	int x;
	while (fscanf(f1,"%s%d",buf,&x)==2)
	{
		string st=buf;
		entity2id[st]=x;
		id2entity[x]=st;
		entity_num++;
	}
	while (fscanf(f2,"%s%d",buf,&x)==2)
	{
		string st=buf;
		relation2id[st]=x;
		id2relation[x]=st;
		relation_num++;
	}
    FILE* f_kb = fopen("../data/train.txt","r");
	while (fscanf(f_kb,"%s",buf)==1)
    {
        string s1=buf;
        fscanf(f_kb,"%s",buf);
        string s2=buf;
        fscanf(f_kb,"%s",buf);
        string s3=buf;
        if (entity2id.count(s1)==0)
        {
            cout<<"miss entity:"<<s1<<endl;
        }
        if (entity2id.count(s2)==0)
        {
            cout<<"miss entity:"<<s2<<endl;
        }
        if (relation2id.count(s3)==0)
        {
            relation2id[s3] = relation_num;
            relation_num++;
        }
        int e1 = entity2id[s1];
        int e2 = entity2id[s2];
        int rel = relation2id[s3];
        if (left_candidate_ok[rel].count(e1)==0)
        {
            left_candidate_ok[rel][e1]=1;
            left_candidate[rel].push_back(e1);
        }
        if (right_candidate_ok[rel].count(e2)==0)
        {
            right_candidate_ok[rel][e2]=1;
            right_candidate[rel].push_back(e2);
        }
        entity2num[e1]++;
        entity2num[e2]++;
        left_entity[rel][e1].push_back(e2);
        right_entity[rel][e2].push_back(e1);
        train.add(e1,e2,rel);
    }
    for (int i=0; i<relation_num; i++)
    {
    	double sum1=0,sum2=0,sum3 = 0;
    	for (map<int,vector<int> >::iterator it = left_entity[i].begin(); it!=left_entity[i].end(); it++)
    	{
    		sum1++;
    		sum2+=it->second.size();
    		sum3+=sqr(it->second.size());
    	}
    	left_mean[i]=sum2/sum1;

    	left_var[i]=sum3/sum1-sqr(left_mean[i]);
    }
    for (int i=0; i<relation_num; i++)
    {
    	double sum1=0,sum2=0,sum3=0;
    	for (map<int,vector<int> >::iterator it = right_entity[i].begin(); it!=right_entity[i].end(); it++)
    	{
    		sum1++;
    		sum2+=it->second.size();
    		sum3+=sqr(it->second.size());
    	}
    	right_mean[i]=sum2/sum1;
    	right_var[i]=sum3/sum1-sqr(right_mean[i]);
    }

    for (int i=0; i<relation_num; i++)
    	cout<<i<<'\t'<<id2relation[i]<<' '<<left_mean[i]<<' '<<right_mean[i]<<endl;

    fclose(f_kb);


    cout<<"relation_num="<<relation_num<<endl;
    cout<<"entity_num="<<entity_num<<endl;
}
Exemplo n.º 24
0
void AddArticulatedParts(Vehicle *first)
{
	VehicleType type = first->type;
	if (!HasBit(EngInfo(first->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) return;

	Vehicle *v = first;
	for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
		bool flip_image;
		EngineID engine_type = GetNextArticPart(i, first->engine_type, first, &flip_image);
		if (engine_type == INVALID_ENGINE) return;

		/* In the (very rare) case the GRF reported wrong number of articulated parts
		 * and we run out of available vehicles, bail out. */
		if (!Vehicle::CanAllocateItem()) return;

		const Engine *e_artic = Engine::Get(engine_type);
		switch (type) {
			default: NOT_REACHED();

			case VEH_TRAIN: {
				Train *front = Train::From(first);
				Train *t = new Train();
				v->SetNext(t);
				v = t;

				t->subtype = 0;
				t->track = front->track;
				t->railtype = front->railtype;
				t->tcache.first_engine = front->engine_type; // needs to be set before first callback

				t->spritenum = e_artic->u.rail.image_index;
				if (e_artic->CanCarryCargo()) {
					t->cargo_type = e_artic->GetDefaultCargoType();
					t->cargo_cap = e_artic->u.rail.capacity;  // Callback 36 is called when the consist is finished
				} else {
					t->cargo_type = front->cargo_type; // Needed for livery selection
					t->cargo_cap = 0;
				}

				t->SetArticulatedPart();
			} break;

			case VEH_ROAD: {
				RoadVehicle *front = RoadVehicle::From(first);
				RoadVehicle *rv = new RoadVehicle();
				v->SetNext(rv);
				v = rv;

				rv->subtype = 0;
				rv->rcache.first_engine = front->engine_type; // needs to be set before first callback
				rv->rcache.cached_veh_length = 8; // Callback is called when the consist is finished
				rv->state = RVSB_IN_DEPOT;

				rv->roadtype = front->roadtype;
				rv->compatible_roadtypes = front->compatible_roadtypes;

				rv->spritenum = e_artic->u.road.image_index;
				if (e_artic->CanCarryCargo()) {
					rv->cargo_type = e_artic->GetDefaultCargoType();
					rv->cargo_cap = e_artic->u.road.capacity;  // Callback 36 is called when the consist is finished
				} else {
					rv->cargo_type = front->cargo_type; // Needed for livery selection
					rv->cargo_cap = 0;
				}

				rv->SetArticulatedPart();
			} break;
		}

		/* get common values from first engine */
		v->direction = first->direction;
		v->owner = first->owner;
		v->tile = first->tile;
		v->x_pos = first->x_pos;
		v->y_pos = first->y_pos;
		v->z_pos = first->z_pos;
		v->build_year = first->build_year;
		v->vehstatus = first->vehstatus & ~VS_STOPPED;

		v->cargo_subtype = 0;
		v->max_speed = 0;
		v->max_age = 0;
		v->engine_type = engine_type;
		v->value = 0;
		v->cur_image = SPR_IMG_QUERY;
		v->random_bits = VehicleRandomBits();

		if (flip_image) v->spritenum++;

		VehicleMove(v, false);
	}
}
Exemplo n.º 25
0
/**
 * Autoreplaces a vehicle
 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
 * @param tile not used
 * @param flags type of operation
 * @param p1 Index of vehicle
 * @param p2 not used
 * @param text unused
 * @return the cost of this operation or an error
 */
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
	Vehicle *v = Vehicle::GetIfValid(p1);
	if (v == NULL) return CMD_ERROR;

	CommandCost ret = CheckOwnership(v->owner);
	if (ret.Failed()) return ret;

	if (!v->IsInDepot()) return CMD_ERROR;
	if (v->vehstatus & VS_CRASHED) return CMD_ERROR;

	bool free_wagon = false;
	if (v->type == VEH_TRAIN) {
		Train *t = Train::From(v);
		if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
		free_wagon = !t->IsFrontEngine();
		if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
	} else {
		if (!v->IsPrimaryVehicle()) return CMD_ERROR;
	}

	const Company *c = Company::Get(_current_company);
	bool wagon_removal = c->settings.renew_keep_length;

	/* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
	Vehicle *w = v;
	bool any_replacements = false;
	while (w != NULL) {
		EngineID e;
		CommandCost cost = GetNewEngineType(w, c, e);
		if (cost.Failed()) return cost;
		any_replacements |= (e != INVALID_ENGINE);
		w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
	}

	CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
	bool nothing_to_do = true;

	if (any_replacements) {
		bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);

		/* Stop the vehicle */
		if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
		if (cost.Failed()) return cost;

		assert(v->IsStoppedInDepot());

		/* We have to construct the new vehicle chain to test whether it is valid.
		 * Vehicle construction needs random bits, so we have to save the random seeds
		 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
		SavedRandomSeeds saved_seeds;
		SaveRandomSeeds(&saved_seeds);
		if (free_wagon) {
			cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
		} else {
			cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
		}
		RestoreRandomSeeds(saved_seeds);

		if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
			CommandCost ret;
			if (free_wagon) {
				ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
			} else {
				ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
			}
			assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
		}

		/* Restart the vehicle */
		if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
	}

	if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
	return cost;
}
Exemplo n.º 26
0
/**
 * Replace a whole vehicle chain
 * @param chain vehicle chain to let autoreplace/renew operator on
 * @param flags command flags
 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
 * @return cost or error
 */
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
{
	Vehicle *old_head = *chain;
	assert(old_head->IsPrimaryVehicle());

	CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);

	if (old_head->type == VEH_TRAIN) {
		/* Store the length of the old vehicle chain, rounded up to whole tiles */
		uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;

		int num_units = 0; ///< Number of units in the chain
		for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;

		Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
		Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
		Money *new_costs = MallocT<Money>(num_units);   ///< Costs for buying and refitting the new vehicles

		/* Collect vehicles and build replacements
		 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
		int i;
		Train *w;
		for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
			assert(i < num_units);
			old_vehs[i] = w;

			CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
			cost.AddCost(ret);
			if (cost.Failed()) break;

			new_costs[i] = ret.GetCost();
			if (new_vehs[i] != NULL) *nothing_to_do = false;
		}
		Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);

		/* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
		if (cost.Succeeded()) {
			/* Separate the head, so we can start constructing the new chain */
			Train *second = Train::From(old_head)->GetNextUnit();
			if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));

			assert(Train::From(new_head)->GetNextUnit() == NULL);

			/* Append engines to the new chain
			 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
			 * That way we also have less trouble when exceeding the unitnumber limit.
			 * OTOH the vehicle attach callback is more expensive this way :s */
			Train *last_engine = NULL; ///< Shall store the last engine unit after this step
			if (cost.Succeeded()) {
				for (int i = num_units - 1; i > 0; i--) {
					Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);

					if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;

					if (new_vehs[i] != NULL) {
						/* Move the old engine to a separate row with DC_AUTOREPLACE. Else
						 * moving the wagon in front may fail later due to unitnumber limit.
						 * (We have to attach wagons without DC_AUTOREPLACE.) */
						CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
					}

					if (last_engine == NULL) last_engine = append;
					cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
					if (cost.Failed()) break;
				}
				if (last_engine == NULL) last_engine = new_head;
			}

			/* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
			if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);

			/* Append/insert wagons into the new vehicle chain
			 * We do this from back to front, so we can stop when wagon removal or maximum train length (i.e. from mammoth-train setting) is triggered.
			 */
			if (cost.Succeeded()) {
				for (int i = num_units - 1; i > 0; i--) {
					assert(last_engine != NULL);
					Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);

					if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
						/* Insert wagon after 'last_engine' */
						CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);

						/* When we allow removal of wagons, either the move failing due
						 * to the train becoming too long, or the train becoming longer
						 * would move the vehicle to the empty vehicle chain. */
						if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
							CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
							break;
						}

						cost.AddCost(res);
						if (cost.Failed()) break;
					} else {
						/* We have reached 'last_engine', continue with the next engine towards the front */
						assert(append == last_engine);
						last_engine = last_engine->GetPrevUnit();
					}
				}
			}

			/* Sell superfluous new vehicles that could not be inserted. */
			if (cost.Succeeded() && wagon_removal) {
				assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
				for (int i = 1; i < num_units; i++) {
					Vehicle *wagon = new_vehs[i];
					if (wagon == NULL) continue;
					if (wagon->First() == new_head) break;

					assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);

					/* Sell wagon */
					CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
					assert(ret.Succeeded());
					new_vehs[i] = NULL;

					/* Revert the money subtraction when the vehicle was built.
					 * This value is different from the sell value, esp. because of refitting */
					cost.AddCost(-new_costs[i]);
				}
			}

			/* The new vehicle chain is constructed, now take over orders and everything... */
			if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));

			if (cost.Succeeded()) {
				/* Success ! */
				if ((flags & DC_EXEC) != 0 && new_head != old_head) {
					*chain = new_head;
				}

				/* Transfer cargo of old vehicles and sell them */
				for (int i = 0; i < num_units; i++) {
					Vehicle *w = old_vehs[i];
					/* Is the vehicle again part of the new chain?
					 * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
					if (w->First() == new_head) continue;

					if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);

					/* Sell the vehicle.
					 * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
					 *       it from failing due to engine limits. */
					cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
					if ((flags & DC_EXEC) != 0) {
						old_vehs[i] = NULL;
						if (i == 0) old_head = NULL;
					}
				}

				if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
			}

			/* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
			 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
			 * Note: The vehicle attach callback is disabled here :) */
			if ((flags & DC_EXEC) == 0) {
				/* Separate the head, so we can reattach the old vehicles */
				Train *second = Train::From(old_head)->GetNextUnit();
				if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);

				assert(Train::From(old_head)->GetNextUnit() == NULL);

				for (int i = num_units - 1; i > 0; i--) {
					CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
					assert(ret.Succeeded());
				}
			}
		}

		/* Finally undo buying of new vehicles */
		if ((flags & DC_EXEC) == 0) {
			for (int i = num_units - 1; i >= 0; i--) {
				if (new_vehs[i] != NULL) {
					DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
					new_vehs[i] = NULL;
				}
			}
		}

		free(old_vehs);
		free(new_vehs);
		free(new_costs);
	} else {
		/* Build and refit replacement vehicle */
		Vehicle *new_head = NULL;
		cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));

		/* Was a new vehicle constructed? */
		if (cost.Succeeded() && new_head != NULL) {
			*nothing_to_do = false;

			/* The new vehicle is constructed, now take over orders and everything... */
			cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));

			if (cost.Succeeded()) {
				/* The new vehicle is constructed, now take over cargo */
				if ((flags & DC_EXEC) != 0) {
					TransferCargo(old_head, new_head, true);
					*chain = new_head;
				}

				/* Sell the old vehicle */
				cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
			}

			/* If we are not in DC_EXEC undo everything */
			if ((flags & DC_EXEC) == 0) {
				DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
			}
		}
	}

	return cost;
}
Exemplo n.º 27
0
void prepare()
{
	FILE* f1 = fopen("../data/entity2id.txt", "r");
	FILE* f2 = fopen("../data/relation2id.txt", "r");
	int x;
	while (fscanf(f1, "%s%d", buf, &x) == 2)
	{
		string st = buf;
		entity2id[st] = x;
		id2entity[x] = st;
		entity_num++;
	}
	while (fscanf(f2, "%s%d", buf, &x) == 2)
	{
		string st = buf;
		relation2id[st] = x;
		id2relation[x] = st;
		relation_num++;
	}
	FILE* f_kb = fopen("../data/train.txt", "r");
	while (fscanf(f_kb, "%s", buf) == 1)
	{
		string s1 = buf;
		fscanf(f_kb, "%s", buf);
		string s3 = buf;
		fscanf(f_kb, "%s", buf);
		string s2 = buf;
		if (entity2id.count(s1) == 0)
		{
			cout << "miss entity:" << s1 << endl;
		}
		if (entity2id.count(s2) == 0)
		{
			cout << "miss entity:" << s2 << endl;
		}
		if (relation2id.count(s3) == 0)
		{
			relation2id[s3] = relation_num;
			relation_num++;
		}
		left_entity[relation2id[s3]][entity2id[s1]]++;
		right_entity[relation2id[s3]][entity2id[s2]]++;
		train.add(entity2id[s1], entity2id[s2], relation2id[s3]);
	}
	for (int i = 0; i<relation_num; i++)
	{
		double sum1 = 0, sum2 = 0;
		for (map<int, int>::iterator it = left_entity[i].begin(); it != left_entity[i].end(); it++)
		{
			sum1++;
			sum2 += it->second;
		}
		left_num[i] = sum2 / sum1;
	}
	for (int i = 0; i<relation_num; i++)
	{
		double sum1 = 0, sum2 = 0;
		for (map<int, int>::iterator it = right_entity[i].begin(); it != right_entity[i].end(); it++)
		{
			sum1++;
			sum2 += it->second;
		}
		right_num[i] = sum2 / sum1;
	}
	cout << "relation_num=" << relation_num << endl;
	cout << "entity_num=" << entity_num << endl;
	fclose(f_kb);
}
Exemplo n.º 28
0
void prepare()
{
    FILE* f1 = fopen("../data/entity2id.txt","r");
	FILE* f2 = fopen("../data/relation2id.txt","r");
	int x;
	while (fscanf(f1,"%s%d",buf,&x)==2)
	{
		string st=buf;
		entity2id[st]=x;
		id2entity[x]=st;
		entity_num++;
	}
	while (fscanf(f2,"%s%d",buf,&x)==2)
	{
		string st=buf;
		relation2id[st]=x;
		id2relation[x]=st;
		id2relation[x+1345] = "-"+st;
		relation_num++;
	}
    FILE* f_kb = fopen("../data/train_pra.txt","r");
	while (fscanf(f_kb,"%s",buf)==1)
    {
        string s1=buf;
        fscanf(f_kb,"%s",buf);
        string s2=buf;
        if (entity2id.count(s1)==0)
        {
            cout<<"miss entity:"<<s1<<endl;
        }
        if (entity2id.count(s2)==0)
        {
            cout<<"miss entity:"<<s2<<endl;
        }
        int e1 = entity2id[s1];
        int e2 = entity2id[s2];
        int rel;
		fscanf(f_kb,"%d",&rel);
		fscanf(f_kb,"%d",&x);
		vector<pair<vector<int>,double> > b;
		b.clear();
		for (int i = 0; i<x; i++)
		{
			int y,z;
			vector<int> rel_path;
			rel_path.clear();
			fscanf(f_kb,"%d",&y);
			for (int j=0; j<y; j++)
			{
				fscanf(f_kb,"%d",&z);
				rel_path.push_back(z);
			}
			double pr;
			fscanf(f_kb,"%lf",&pr);
			b.push_back(make_pair(rel_path,pr));
		}
		//cout<<e1<<' '<<e2<<' '<<rel<<' '<<b.size()<<endl;
        train.add(e1,e2,rel,b);
    }
	relation_num*=2;
   
    cout<<"relation_num="<<relation_num<<endl;
    cout<<"entity_num="<<entity_num<<endl;
	
	FILE* f_confidence = fopen("../data/confidence.txt","r");
	while (fscanf(f_confidence,"%d",&x)==1)
	{
		string s = "";
		for (int i=0; i<x; i++)
		{
			fscanf(f_confidence,"%s",buf);
			s = s + string(buf)+" ";
		}
		fscanf(f_confidence,"%d",&x);
		for (int i=0; i<x; i++)
		{
			int y;
			double pr;
			fscanf(f_confidence,"%d%lf",&y,&pr);
		//	cout<<s<<' '<<y<<' '<<pr<<endl;
			path_confidence[make_pair(s,y)] = pr;
		}
	}
	fclose(f_confidence);
    fclose(f_kb);
}
Exemplo n.º 29
0
// Функция сортировки поездов в порядке убывания 
// по номеру поезда
bool cmpDescNum(Train &tr1, Train &tr2)
{
	return tr1.Num() > tr2.Num();
}
Exemplo n.º 30
0
	bool operator()(Train &tr1, Train &tr2)
	{
		return tr1.Station() < tr2.Station();
	}