//method called by Passenger to update visitor's location, state.
int VisitorTerminalBehavior::update( ElapsedTime _time, Point _OwnerPreLocation, bool _bBackup )
{
	int nNextState = GetOwner()->getState();
	PaxTerminalBehavior* spTerminalBehavior = (PaxTerminalBehavior*)GetOwner()->getBehavior(MobElementBehavior::TerminalBehavior);
	if (spTerminalBehavior == NULL)
	{
		return 1;
	}

	if (IfHaveOwnFlow(_time))
	{
		//////create ConvergePair,and add to GreetPool.            6.21.2004
		//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

		TrayHostList* pTrayHostList = m_pTerm->GetTrayHostList();

		if (pTrayHostList->IfNonPaxExsit(m_pPerson->getType().GetTypeIndex()) && !m_bInTray)
		{
			spTerminalBehavior->CopyVisitListToTrayHost(_time);
		}

		if (pTrayHostList->FindHostItem(m_pPerson->getType().GetTypeIndex()) || !pTrayHostList->IfNonPaxExsit(m_pPerson->getType().GetTypeIndex())\
			|| (pTrayHostList->IfNonPaxExsit(m_pPerson->getType().GetTypeIndex()) && !m_bInTray))
		{
			if (!spTerminalBehavior->StickForDestProcsOverload(_time) && !StickNonPaxDestProcsOverload(_time))
			{
				GetVisitor()->NewConvergePair(GetOwnerId(),true);
				if(GetOwner()) GetOwner()->NewConvergePair(m_pPerson->getID(),m_pPerson->getType().GetTypeIndex());

				m_pPerson->setState(FreeMoving);
				m_nFreeMoving = 1;
				m_nFreeMovingIndex = m_pPerson->getLogEntry().getCurrentCount();
				//	m_bWithOwner = false;
				m_pPerson->m_pGroupInfo->SetFollowerWithOwner(false);
				setDestination(_OwnerPreLocation);
				ElapsedTime eTime = _time + moveTime();
				generateEvent(eTime,false);

				if( getNextProcessor( eTime ) )
					generateEvent( eTime+moveTime(),false );//

				return 0;
			}
			return 1;
		}
		return 0;
	}

	m_pPerson->setState(nNextState);
	m_nQueuePathSegmentIndex = spTerminalBehavior->getCurrentIndex();
	m_pProcessor = spTerminalBehavior->getProcessor();

	CString sstr1= m_pProcessor->getID()->GetIDString();
	// write log entry
	//writeLog( _time );
	//CString _strOwnerProcessor = m_pOwnerPax->getProcessor()->getID()->GetIDString();
	GetVisitor()->writeVisitorLog( _time,_OwnerPreLocation, _bBackup, false);
	return 1;
}
Example #2
0
void DistanceNode::processEvents(const QList<DetectedEvent> event)
{
    if(event.count() < 2){
        return;
    }
    QList<DetectedEvent> distanceEvent;
    distanceEvent = processEventsLocal(event);

    emit generateEvent(distanceEvent);
}
Example #3
0
bool Track::incoming(Vehicle *car) {
    if ((totalLenght - usedLenght) >= car->getLenght()) {
        carsIn++;
        cars->add(car);
        car->setupDir(-1);
        usedLenght += car->getLenght();
        int timeToGetOut = ( totalLenght - car->getLenght() ) / velocity;
        generateEvent(timeToGetOut);
        return true;
    }
    return false;
}
Example #4
0
void Teller::processEvent(Event* anEvent) {
	double simTime = SimPlus::getInstance()->getSimTime();

	if(anEvent->getEventType() == (getPrefix() + BEGIN_SERVICE)) {
		// see if there are any patients waiting
		currentCustomer = (Customer*)getBoundQueue("MY_QUEUE")->removeFirst();

		if(currentCustomer == NULL) {
			// if no customers are waiting, check again in 1 minute
			if(simTime < closingTime)
				generateEvent( BEGIN_SERVICE, simTime + getCheckDelay() );
		} else { // otherwise go to work
			generateEvent(END_SERVICE, simTime + myServiceTime->getRandom());
			lastStart = simTime;
			idleTimeStat->observe(simTime, simTime - lastStop);
		}

	} else if(anEvent->getEventType() == (getPrefix() + END_SERVICE))	{
		// increate the a coustomer processed counter
		++customerCount;

		currentCustomer = NULL;

		// collect some stats
		lastStop = simTime;
		serviceTimeStat->observe(simTime, simTime - lastStart);

		// generate a new service event
		generateEvent(BEGIN_SERVICE, simTime + getCheckDelay());

		// see if a customer jockies
		jockey();

	} else {
		reportError( "Teller" );
	}

	SimPlus::getInstance()->releaseEvent( anEvent );

}
Example #5
0
void Track::outgoing(int evtTime) {
    println("Track::outgoing");
    if (trackBlocked){
        trafficJam++;
        return;
    }
    // threat semaphore if open continue, else block track and add to semaphore notify
    if (semaphoreBlocked()) {
    println("Track::outgoing::blockedSem");
        waitingSemaphore();
        return;
    }
    //if (cars->empty())
    //    return;
    Vehicle *car = cars->get();
    int destination = car->getDirection();
    if (destination == -1) {
        int totalChances = 0, i;
        for (i = 0; i < targetProbability->sizeOf(); i++) {
            totalChances += *(targetProbability->get(i));
        }
        totalChances = std::rand() % totalChances;
        for (i = 0; totalChances >= 0; i++) {
            totalChances -= *(targetProbability->get(i));
            if (totalChances < 0)
                break;
        }
        destination = i;
        car->setupDir(destination);
        println("Track::outgoing::dirCalculated");
    }
    println("Track::outgoing::dirCalculated" << destination);
    bool test = targetTracks->get(destination)->incoming(car);
    println("Track::outgoing::tryIncoming" << test);
    if (test) {
        carsOut++;
        cars->remove();
        usedLenght -= car->getLenght();
        if (trafficJam) {
            trafficJam--;
            int timeToGetOut = car->getLenght() / velocity;
            generateEvent(evtTime + timeToGetOut);
        }
        while (!waitingTracks->empty())
            waitingTracks->remove(0)->notify(evtTime);
        return;
    }
    trackBlocked = true;
    targetTracks->get(destination)->waitingFor(this);
}
void connectionEvent(bool bConnectionUp)
{
    if(bConnectionUp)
    {
        if(generateEvent)
        {
            generateEvent(bleControl::EV_CONNECTION_UP);
        }
    }else
    {
        if(generateEvent)
        {
            generateEvent(bleControl::EV_CONNECTION_DOWN);
        }
        if(!bIsCentral)
        {
            //After connection goes down, advertizing must be restarted or the module will no longer be connectable.
            if(!rn.doAdvertizing(true,5000))
            {
                return;
            }
        }
    }
}
void bondingEvent(rn4020::BONDING_MODES bd)
{
    switch(bd)
    {
    case rn4020::BD_ESTABLISHED:
        bIsBonded=true;
        break;
    case rn4020::BD_PASSCODE_NEEDED:
        if(generateEvent)
        {
            generateEvent(bleControl::EV_PASSCODE_WANTED);
        }
        break;
    default:
        break;
    }
}
bool PerfConfigEventsModel::setData(const QModelIndex &dataIndex, const QVariant &value, int role)
{
    if (role != Qt::EditRole)
        return false;

    const int row = dataIndex.row();
    const int column = dataIndex.column();

    QStringList events = m_settings->events();
    EventDescription description = parseEvent(events[row]);
    switch (column) {
    case ColumnEventType:
        description.eventType = qvariant_cast<EventType>(value);
        break;
    case ColumnSubType:
        switch (description.eventType) {
        case EventTypeHardware:
        case EventTypeSoftware:
        case EventTypeCache:
            description.subType = qvariant_cast<SubType>(value);
            break;
        case EventTypeRaw:
            description.numericEvent = value.toULongLong();
            break;
        case EventTypeBreakpoint:
            description.numericEvent = value.toULongLong();
            break;
        case EventTypeCustom:
            description.customEvent = value.toString();
            break;
        default:
            break;
        }
        break;
    case ColumnOperation:
        description.operation = value.toInt();
        break;
    case ColumnResult:
        description.result = qvariant_cast<Result>(value);
        break;
    }
    events[row] = generateEvent(description);
    m_settings->setEvents(events);
    emit dataChanged(index(row, ColumnEventType), index(row, ColumnResult));
    return true;
}
Example #9
0
Teller::Teller(double mu, double cT, int id, EntityQueue* doorQueue) : ServerEntity() {
	SimPlus* handle = SimPlus::getInstance();
	idleTimeStat = handle->getSampST();
	waitTimeStat = handle->getSampST();
	serviceTimeStat = handle->getSampST();
	closingTime = cT;
	tellerID = id;
	customerCount = 0;

	myServiceTime = handle->getExponentialDist( mu );

	lastStart = 0;
	lastStop = 0;

	bind(doorQueue, "MY_QUEUE");

	tellerList.push_back(this);

	generateEvent( BEGIN_SERVICE, getCheckDelay() );
}
Example #10
0
bool
ICalReport::generate()
{
#if KDE_IS_VERSION(3,4,89)
    KCal::CalendarLocal cal("UTC");
#else
    KCal::CalendarLocal cal;
#endif

    if( !open())
    {
        tjWarning(i18n("Can not open ICal File '%1' for writing!")
                 .arg(fileName));
        return false;
    }

    TaskList filteredList;
    if (!filterTaskList(filteredList, 0, getHideTask(), getRollUpTask()))
        return false;

    // Make sure that parents are in front of childs. We need this later to set
    // the relation.
    filteredList.setSorting(CoreAttributesList::TreeMode, 0);
    filteredList.setSorting(CoreAttributesList::StartUp, 1);
    sortTaskList(filteredList);

    ResourceList filteredResourceList;
    if (!filterResourceList(filteredResourceList, 0, hideResource,
                            rollUpResource))
        return false;
    sortResourceList(filteredResourceList);

    QPtrDict<KCal::Todo> toDoDict;
    QPtrDict<KCal::Event> eventDict;
    for (TaskListIterator tli(filteredList); *tli != 0; ++tli)
    {
        // Generate a TODO item for each task.
        KCal::Todo* todo = generateTODO(*tli, filteredResourceList);

        // In case we have the parent in the list set the relation pointer.
        if((*tli)->getParent() && toDoDict.find((*tli)->getParent()))
            todo->setRelatedTo(toDoDict[(*tli)->getParent()]);

        // Insert the just created TODO into the calendar.
        cal.addTodo(todo);

        // Insert the TODO into the dict. We might need it as a parent.
        toDoDict.insert(*tli, todo);

        if ((*tli)->isLeaf() && !(*tli)->isMilestone())
        {
            // Generate an event item for each task.
            KCal::Event* event = generateEvent(*tli, filteredResourceList);

            // In case we have the parent in the list set the relation pointer.
            if((*tli)->getParent() && eventDict.find((*tli)->getParent()))
                event->setRelatedTo(eventDict[(*tli)->getParent()]);

            // Insert the just created EVENT into the calendar.
            cal.addEvent(event);

            // Insert the EVENT into the dict. We might need it as a parent.
            eventDict.insert(*tli, event);
        }
    }

    // Dump the calendar in ICal format into a text file.
    KCal::ICalFormat format;
    s << format.toString(&cal) << endl;

    return close();
}
Example #11
0
bool bleControl::secureConnect(const char* remoteBtAddress)
{
    unsigned long ulStartTime;
    CONNECT_STATE state=ST_NOTCONNECTED;
    do
    {
        switch(state)
        {
        case ST_NOTCONNECTED:
            if(!rn.doConnecting(remoteBtAddress))
            {
                //stop connecting process
                rn.doStopConnecting();
                return false;
            }
            delay(1000);
            bPassReady=false;
            if(!rn.startBonding())
            {
                rn.doDisconnect();
                return false;
            }
            ulStartTime=millis();
            state=ST_CONNECTED;
            break;
        case ST_CONNECTED:
            if(millis()>ulStartTime+10000)
            {
                disconnect();
                return false;
            }
            loop();
            if(bPassReady)
            {
                bIsBonded=false;
                generateEvent(EV_PASSCODE_GENERATED);
                state=ST_PASSCODE_GENERATED;
                ulStartTime=millis();
            }
            break;
        case ST_PASSCODE_GENERATED:
            if(millis()>ulStartTime+10000)
            {
                disconnect();
                return false;
            }
            loop();
            if(bIsBonded)
            {
                state=ST_PROV_BONDED;
            }
            break;
        case ST_PROV_BONDED:
            if(!rn.startBonding())
            {
                rn.doDisconnect();
                return false;
            }
            state=ST_BONDED;
        }
    }while(state!=ST_BONDED);

}
void BlobTrackingNode::process(const cv::Mat &img_input, const cv::Mat &img_mask, cv::Mat &img_output)
{
    //This is output event
    QList<DetectedEvent> blobEvent;
cv::Mat newInput;
img_input.copyTo(newInput);

    if(img_input.empty() || img_mask.empty()){
        return;
    }
    loadConfig();

    if(firstTime){
        saveConfig();
    }
    IplImage* frame = new IplImage(img_input);
    cvConvertScale(frame, frame, 1, 0);

    IplImage* segmentated = new IplImage(img_mask);

    IplConvKernel* morphKernel = cvCreateStructuringElementEx(5, 5, 1, 1, CV_SHAPE_RECT, NULL);
    cvMorphologyEx(segmentated, segmentated, NULL, morphKernel, CV_MOP_OPEN, 1);

    cv::Mat temp = cv::Mat(segmentated);
    if(showBlobMask){
        //cv::imshow("test",temp);
        ownerPlugin->updateFrameViewer("Tracking Mask",convertToQImage(temp));
    }
    IplImage* labelImg = cvCreateImage(cvGetSize(frame), IPL_DEPTH_LABEL, 1);

    cvb::CvBlobs blobs;
    cvb::cvLabel(segmentated, labelImg, blobs);

    cvb::cvFilterByArea(blobs, minArea, maxArea);
  
    if(debugBlob){
        cvb::cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX|CV_BLOB_RENDER_CENTROID|CV_BLOB_RENDER_ANGLE|CV_BLOB_RENDER_TO_STD);
    }
    else{
        cvb::cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX|CV_BLOB_RENDER_CENTROID|CV_BLOB_RENDER_ANGLE);
    }

    cvb::cvUpdateTracks(blobs, tracks,threshold_distance, threshold_inactive);



    //At this point, we have assigned each blob in current frame in to a track. so we can iterate through active tracks, and
    // find out out blobs within one of those tracks. Following loop does that. This is helpfull to have more generalized idea about
    // relationship between blobs with increasing time.

    for (cvb::CvTracks::const_iterator track = tracks.begin(); track!=tracks.end(); ++track)
    {
        if((*track).second->active != 0){
            for(std::map<cvb::CvLabel,cvb::CvBlob *>::iterator it = blobs.begin() ; it != blobs.end(); it++){

                cvb::CvLabel label = (*it).first;
                cvb::CvBlob * blob = (*it).second;

                if((*track).second->label == label){
                    //qDebug()<< blob->minx <<","<<blob->miny;
                    //This is smoothed time tracked blob lables
                    blobEvent.append(DetectedEvent("blob",QString("%1,%2,%3,%4,%5,%6,%7,%8").arg(frameIndex).arg((*track).first).arg(blob->centroid.x).arg(blob->centroid.y).arg(blob->minx).arg(blob->miny).arg(blob->maxx).arg(blob->maxy),1.0));
                }
            }
        }
    }

    if(debugTrack){
        cvb::cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID|CV_TRACK_RENDER_BOUNDING_BOX|CV_TRACK_RENDER_TO_STD);
    }
    else{
        cvb::cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID|CV_TRACK_RENDER_BOUNDING_BOX);
    }
    if(showFrameID){
        cv::Mat temp = cv::Mat(frame);
        cv::putText(temp,QString("%1").arg(frameIndex).toStdString(),cv::Point(40,120),cv::FONT_HERSHEY_PLAIN,2,cv::Scalar(0,255,0),2);
    }
    if(showOutput){
        cv::Mat temp = cv::Mat(frame);
        ownerPlugin->updateFrameViewer("Tracking Output",convertToQImage(temp));

        //cvShowImage("Blob Tracking", frame);
    }
    cv::Mat img_result(frame);

    cv::putText(img_result,QString("%1").arg(QString::number(frameIndex)).toUtf8().constData(), cv::Point(10,30), CV_FONT_HERSHEY_PLAIN,1.0, CV_RGB(255,255,255));

    img_result.copyTo(img_output);
    cvReleaseImage(&labelImg);
    delete frame;
    delete segmentated;
    cvReleaseBlobs(blobs);
    cvReleaseStructuringElement(&morphKernel);

    firstTime = false;
    frameIndex++;

    QImage input((uchar*)newInput.data, newInput.cols, newInput.rows, newInput.step1(), QImage::Format_RGB888);
    QImage output((uchar*)img_output.data, img_output.cols, img_output.rows, img_output.step1(), QImage::Format_RGB888);
    QList<QImage> images;

    images.append(input);
    images.append(output);
    emit generateEvent(blobEvent,images);

    //emit generateEvent(blobEvent);
}
bool LeftbagdetectorPlugin::init()
{

    QDateTime timestamp = QDateTime::currentDateTime();

    //connect(&blobPositionReader, SIGNAL(generateEvent(QList<DetectedEvent>)), this, SLOT(onCaptureEvent(QList<DetectedEvent>)));
    //connect(&blobPositionReader, SIGNAL(generateEvent(QList<DetectedEvent>)), &blobDistanceNode, SLOT(captureEvent(QList<DetectedEvent>)));
    //connect(&blobPositionReader, SIGNAL(generateEvent(QList<DetectedEvent>)), &blobSpeedNode, SLOT(captureEvent(QList<DetectedEvent>)));
    connect(this, SIGNAL(generateEvent(QList<DetectedEvent>)), &blobDistanceNode, SLOT(captureEvent(QList<DetectedEvent>)));
    connect(this, SIGNAL(generateEvent(QList<DetectedEvent>)), &blobSpeedNode, SLOT(captureEvent(QList<DetectedEvent>)));

    connect(&blobDistanceNode, SIGNAL(generateEvent(QList<DetectedEvent>)), &distanceChangeNode, SLOT(captureEvent(QList<DetectedEvent>)));
    connect(&blobDistanceNode, SIGNAL(generateEvent(QList<DetectedEvent>)), &leftBagNode, SLOT(captureEvent(QList<DetectedEvent>)));
    connect(&distanceChangeNode, SIGNAL(generateEvent(QList<DetectedEvent>)), &leftBagNode, SLOT(captureEvent(QList<DetectedEvent>)));
    connect(&blobSpeedNode, SIGNAL(generateEvent(QList<DetectedEvent>)), &leftBagNode, SLOT(captureEvent(QList<DetectedEvent>)));
    connect(&leftBagNode, SIGNAL(generateEvent(QList<DetectedEvent>)), &leftBagWriterNode, SLOT(captureEvent(QList<DetectedEvent>)));

    connect(this, SIGNAL(generateEvent(QList<DetectedEvent>)), &blobWriterNode, SLOT(captureEvent(QList<DetectedEvent>)));

    //connect(&blobDistanceNode, SIGNAL(generateEvent(QList<DetectedEvent>)), this, SLOT(onCaptureEvent(QList<DetectedEvent>)));
    //connect(&distanceChangeNode, SIGNAL(generateEvent(QList<DetectedEvent>)), this, SLOT(onCaptureEvent(QList<DetectedEvent>)));
    //connect(&blobSpeedNode, SIGNAL(generateEvent(QList<DetectedEvent>)), this, SLOT(onCaptureEvent(QList<DetectedEvent>)));
    connect(&leftBagNode, SIGNAL(generateEvent(QList<DetectedEvent>)), this, SLOT(onCaptureEvent(QList<DetectedEvent>)));
    //connect(this, SIGNAL(generateEvent(QList<DetectedEvent>)), this, SLOT(onCaptureEvent(QList<DetectedEvent>)));

    //QDir dir(QCoreApplication::instance()->applicationDirPath());
    QDir dir(QDir::home());
    if(!dir.exists("NoobaVSS")){
        dir.mkdir("NoobaVSS");
    }
    dir.cd("NoobaVSS");
    if(!dir.exists("data")){
        dir.mkdir("data");
    }
    dir.cd("data");
    if(!dir.exists("text")){
        dir.mkdir("text");
    }
    dir.cd("text");

    output_file = dir.absoluteFilePath(timestamp.currentDateTime().toString("yyyy-MM-dd-hhmm") + "-abobjects.txt");

    //createStringParam("input_file",input_file,false);
    createStringParam("output_file",output_file,true);

    createDoubleParam("still_object_speed_threshold",DEFAULT_STILL_OBJECT_SPEED_THRESHOLD,200.0,0.0);
    createDoubleParam("leaving_object_speed_threshold",DEFAULT_LEAVING_OBJECT_SPEED_THRESHOLD,200.0,0.0);
    createDoubleParam("distance_change_rate_threshold",DEFAULT_DISTANCE_CHANGE_RATE_THRESHOLD,200.0,0.0);
    createDoubleParam("split_min_limit",DEFAULT_SPLIT_MIN_LIMIT,500,0.0);
    createDoubleParam("split_max_limit",DEFAULT_SPLIT_MAX_LIMIT,500.0,0.0);


    //blobPositionReader.openFile(input_file);
    leftBagWriterNode.openFile(output_file);

    blobWriterNode.openFile(dir.absoluteFilePath(timestamp.currentDateTime().toString("yyyy-MM-dd-hhmm") + "-blobs.txt"));

    leftBagNode.setStillObjectSpeedThreshold(DEFAULT_STILL_OBJECT_SPEED_THRESHOLD);
    leftBagNode.setLeavingObjectSpeedThreshold(DEFAULT_LEAVING_OBJECT_SPEED_THRESHOLD);
    leftBagNode.setDistanceChangeRateThreshold(DEFAULT_DISTANCE_CHANGE_RATE_THRESHOLD);
    leftBagNode.setSplitMinLimit(DEFAULT_SPLIT_MIN_LIMIT);
    leftBagNode.setSplitMaxLimit(DEFAULT_SPLIT_MAX_LIMIT);

    debugMsg("Left Bag Detector Plugin Initialized");

    return true;
}
Example #14
0
void PhaseDplusKKpi( std::string filename = "bsdspi.root", int nToGen = 1e7) {


  // gROOT->ProcessLine(".x ~/lhcb/lhcbStyle.C");
	if (!gROOT->GetClass("TGenPhaseSpace")) gSystem->Load("libPhysics");


	// loaf the fonll stuff
        TFile* fonll = new TFile("fonll.root");
        TH1F* ptHisto = (TH1F*) fonll->Get("pthisto"); 
        TH1F* etaHisto = (TH1F*) fonll->Get("etahisto"); 

        // get the graph to smear with
        TFile* smearfile = new TFile("smear12.root");
        TGraphErrors* sgraph = (TGraphErrors*)smearfile->Get("data;1");

	Double_t masses[2] = {mDplus,mpi};
        Double_t masses2[3] = {mK,mpi,mpi};
        
	double min(5.2);
	double max(5.5);
     

	TH1F *h1 = new TH1F("h1","h1", 100, 4850, 5550);
        h1->Sumw2();

        TH1F *dh1 = new TH1F("dh1","dh1", 100, 0., 5000.);
        dh1->Sumw2();

        TH1F *dh2 = new TH1F("dh2","dh2", 100, 1000., 2000.);
        dh2->Sumw2();


        TH1F *dh3 = new TH1F("pi","pi", 100, 2000., 4000.);
        dh3->Sumw2();

        TH1F *dh4 = new TH1F("phi","phi", 100, 750, 1250);
        dh4->Sumw2();

        TRandom ran;

	for (Int_t n=0;n<nToGen; n++) {
	  //	   Double_t weight = event.Generate();
          TLorentzVector Bs = genB(ran,ptHisto,etaHisto, mBd);
          TGenPhaseSpace event;
          if (!generateEvent(Bs,event,masses,ran,1000)) continue;

          TLorentzVector dplus = *event.GetDecay(0); // ds
	  TLorentzVector pi1 = *event.GetDecay(1); //pi 
          
          // generate the Ds
          TGenPhaseSpace subevent; 
 
          if (!generateEvent(dplus,subevent,masses2,ran,1000)) continue;
          TLorentzVector k1 = *subevent.GetDecay(0);
          TLorentzVector pi2 = *subevent.GetDecay(1);
          TLorentzVector pi3 = *subevent.GetDecay(2);

	   // smear the vectors
	  TLorentzVector spi1 = smearedVec(pi1,sgraph,ran);
	  TLorentzVector spi2 = smearedVec(pi2,sgraph,ran);
	  TLorentzVector spi3 =  smearedVec(pi3,sgraph,ran);
          TLorentzVector sk1 =  smearedVec(k1,sgraph,ran);

          TLorentzVector fk2;  TLorentzVector fpi2;
          if (ran.Uniform() > 0.5){
            fk2 = reassignMass(spi2,mK);
	    fpi2 = spi3;
	  }
          else{
            fk2 = reassignMass(spi3,mK);
	    fpi2 = spi2;
	  }


           TLorentzVector sum = spi1 + spi2 + sk1 +fk2;
           TLorentzVector pipi = spi1 + fpi2 ;
           TLorentzVector phi = sk1+fk2 ;
           TLorentzVector dsum = spi1 + sk1 + fk2 ;
           TLorentzVector dsum2 = spi2 + sk1 + fk2 ;
 
	   if ( select(spi1,fpi2,sk1,fk2,ran)) {
              h1->Fill(1000*sum.M());
              dh1->Fill(1000*dsum.M());
              dh2->Fill(1000*dsum2.M());
              dh3->Fill(1000*pipi.M());
              dh4->Fill(1000*phi.M()); 
	   }
	   // std::cout << pipi.P() << std::endl;
	}

        TCanvas* can = new TCanvas("can","can", 800,600); 
        h1->Draw("HISTO");

        TCanvas* can2 = new TCanvas("can2","can2", 800,600); 
	dh1->Draw("HISTO");

        TCanvas* can3 = new TCanvas("can3","can3", 800,600); 
	dh2->Draw("HISTO");


        TCanvas* can4 = new TCanvas("can4","can4", 800,600); 
	dh3->Draw("HISTO");

        TCanvas* can5 = new TCanvas("can5","can5", 800,600); 
	dh4->Draw("HISTO");


        TFile* output = new TFile(filename.c_str(),"RECREATE","output ROOT file");
        dh1->Write(); 
        dh2->Write(); 
        dh3->Write(); 
        dh4->Write(); 
        h1->Write();  
        output->Close();
  
}
Example #15
0
int MovingTrain::move(ElapsedTime currentTime,bool bNoLog)
{
	PLACE_METHOD_TRACK_STRING();
	switch(state)
	{
	case Birth:
		{
			InitTrain();
			state = TrainFreeMoving;
			generateEvent(currentTime,false);
		}
		break;
	case TrainFreeMoving:
		{
			if (m_iPreState == Birth)
			{
				GetSchedule(currentTime);
			}
			else
			{
				GetSchedule(currentTime - m_TrainLogEntry.GetTurnAroundTime());
			}

			int nCount = m_movePath.size();
			double dPrevHeading = 0.0;

			for( int i=0; i<nCount; i++ )
			{
				CViehcleMovePath movePath = m_movePath[i];
				int nPathCount = movePath.GetCount();
				float fPrevHeading;
				for( int z=0; z<nPathCount; z++ )
				{
					CStateTimePoint timePt = movePath.GetItem( z );
					TrainEventStruct event;
					ElapsedTime t;
					event.time = timePt.GetTime();
					t.setPrecisely(event.time);
					if (currentTime < t)
					{
						currentTime = t;
					}
					event.x = (float)timePt.getX();
					event.y = (float)timePt.getY();
					event.z = (short)timePt.getZ();
					if( z < nPathCount - 1 )
					{
						CStateTimePoint nextTimePt = movePath.GetItem( z+1 );
						double dNewHeading = ( nextTimePt - timePt ).getHeading();
						event.heading = (float)dNewHeading;
						fPrevHeading = event.heading;
					}
					else
					{
						event.heading = fPrevHeading;
					}
					event.state = timePt.GetState();
					m_TrainLogEntry.addEvent( event );
				}
			}
			ElapsedTime delayTime;
			delayTime.setPrecisely(01l); 

			generateEvent(currentTime - delayTime,false);//notify passenger train arrival
			m_iPreState = state;
			state = TrainArriveAtStation;
		}
		break;
	case TrainArriveAtStation:
		{
			if (m_nFlowIndex + 1 == (int)m_TrainFlow.size())
			{
				m_nFlowIndex = 0;
			}
			m_nFlowIndex++;
			IntegratedStation* pSourceStation = GetSourceStation(m_nFlowIndex);
			pSourceStation->SetTrain(this);
			ElapsedTime delayTime;
			delayTime.setPrecisely(01l); 
			generateEvent(currentTime + delayTime,false);//for correct time to leave
			state = TrainWaitForLeave;
		}
		break;
	case TrainWaitForLeave:
		{
			currentTime += m_TrainLogEntry.GetTurnAroundTime();
			generateEvent(currentTime,false);
			m_iPreState = state;
			state = TrainLeaveStation;
		}
		break;
	case TrainLeaveStation:
		{
			if (m_TrainLogEntry.GetEndTime() < currentTime)
			{
				generateEvent(currentTime,false);
				state = Death;
			}
			else
			{
				generateEvent(currentTime,false);
				m_iPreState = state;
				state = TrainFreeMoving;
			}
			IntegratedStation* pSourceStation = GetSourceStation(m_nFlowIndex);
			pSourceStation->ClearStationTrain(this);
			ClearThisStationPerson(pSourceStation);

		}
		break;
	case Death:
		{
			FlushLog();
		}
		break;
	default:
		break;
	}
	return TRUE;
}
Example #16
0
void PhaseSignal(int mode =2, int nEvtToGen = 1000000) {

  // mode == which chic

  // gROOT->ProcessLine(".x ~/lhcb/lhcbStyle.C");
	if (!gROOT->GetClass("TGenPhaseSpace")) gSystem->Load("libPhysics");


	// loaf the fonll stuff
        TFile* fonll = new TFile("fonll.root");
        TH1F* ptHisto = (TH1F*) fonll->Get("pthisto"); 
        TH1F* etaHisto = (TH1F*) fonll->Get("etahisto"); 

        // get the graph to smear with
        TFile* smearfile = new TFile("smear12.root");
        TGraphErrors* sgraph = (TGraphErrors*)smearfile->Get("data;1");

	//make pdfs for phi and chi mass shape
        RooRealVar m1("m1","m1",0.6, 1.5);
        RooRealVar m2("m2","m2",3.2, 3.6);
        RooRealVar m3("m3","m3",3.6, 3.8);
        RooRelBreitWigner* bw = createPhiMassPdf(m1);
        RooRelBreitWigner* chibw= 0;
        if (mode ==0) {
          chibw = createChi0MassPdf(m2);      
       	}
        else if (mode == 2){
          chibw = createChi2MassPdf(m2); 
        } 
        else {
          chibw = createChi1MassPdf(m2);
	}
       
        // generate phi datasets
        RooDataSet *phidata = bw->generate(RooArgSet(m1),100000) ;
        RooDataSet *chicdata = chibw->generate(RooArgSet(m2),100000) ;
	// RooDataSet *psi2sdata = psi2bw->generate(RooArgSet(m3),100000) ;
       


	Double_t masses[2] = {mchic2,mphi};
        Double_t masses3[2] = {mpi,mpi};
        Double_t masses4[2] = {mK,mK};
	double min(5.2);
	double max(5.5);
     
	TH1F *h1 = new TH1F("h1","h1", 100, 5150, 5550);
        h1->Sumw2();

        TH1F *dh1 = new TH1F("dh1","dh1", 100, 0., 5000.);
        dh1->Sumw2();

        TH1F *dh2 = new TH1F("dh2","dh2", 100, 1000., 2000.);
        dh2->Sumw2();


        TH1F *dh3 = new TH1F("pi","pi", 100, 2000., 4000.);
        dh3->Sumw2();

        TH1F *dh4 = new TH1F("phi","phi", 100, 750, 1250);
        dh4->Sumw2();

        TRandom ran;

        int ngenerated = 0; int nselected = 0;
	for (Int_t n=0;n<nEvtToGen;n++) {
	  //	   Double_t weight = event.Generate();
          TLorentzVector Bs = genB(ran,ptHisto,etaHisto, mBs);
          TGenPhaseSpace event;
   	 
	   // Generate the Bs	 
           int ntoGen = 0; 
           masses[1] = pick(phidata,ran,std::string("m1"));
           masses[0] = pick(chicdata ,ran,std::string("m2"));
           if (!generateEvent(Bs,event,masses,ran,1000)) continue;
           TLorentzVector chic = *event.GetDecay(0); // psi
	   TLorentzVector phi = *event.GetDecay(1); //phi

           // chic decay to pipi
           TGenPhaseSpace subevent1;  
       	   if (!generateEvent(chic,subevent1,masses3,ran,1000)) continue;
           TLorentzVector pi1 = *subevent1.GetDecay(0);
	   TLorentzVector pi2 = *subevent1.GetDecay(1);

           // phi decays to kk
           TGenPhaseSpace subevent2;  
	   if (!generateEvent(phi,subevent2,masses4,ran,1000)) continue;
           TLorentzVector k1 = *subevent2.GetDecay(0);
	   TLorentzVector k2 = *subevent2.GetDecay(1);

	   // smear the vectors
	   TLorentzVector spi1 = smearedVec(pi1,sgraph,ran);
	   TLorentzVector spi2 = smearedVec(pi2,sgraph,ran);
	   TLorentzVector sk1 =  smearedVec(k1,sgraph,ran);
           TLorentzVector sk2 =  smearedVec(k2,sgraph,ran);
	   //           TLorentzVector sk2 = reassignMass(spi,mK);

           TLorentzVector sum = spi1 + spi2 + sk1 + sk2;
           TLorentzVector pipi = spi1 + spi2 ;
           TLorentzVector sphi = sk1+sk2 ;
           TLorentzVector dsum = spi1 + sk1 + sk2 ;
           TLorentzVector dsum2 = spi2 + sk1 + sk2 ;
 
	   ++ngenerated;
 
           if (select(spi1,spi2,sk1,sk2,ran)) {
              h1->Fill(sum.M()*1000);
              dh1->Fill(dsum.M()*1000);
              dh2->Fill(dsum2.M()*1000);
              dh3->Fill(pipi.M()*1000);
              dh4->Fill(sphi.M()*1000); 
              ++nselected;
          }
	   // std::cout << pipi.P() << std::endl;
	} //event loop	

        TCanvas* can1 = new TCanvas("can","can", 800,600); 
        h1->Fit("gaus");
        h1->Draw("HISTO");

        TCanvas* can2 = new TCanvas("can2","can2", 800,600); 
	dh1->Draw("HISTO");

        TCanvas* can3 = new TCanvas("can3","can3", 800,600); 
	dh2->Draw("HISTO");


        TCanvas* can4 = new TCanvas("can4","can4", 800,600); 
	dh3->Draw("HISTO");

        TCanvas* can5 = new TCanvas("can5","can5", 800,600); 
	dh4->Draw("HISTO");

	std::cout << "Generated " << ngenerated << std::endl;
        std::cout << "Selected " << nselected << std::endl;

	std::stringstream outputname; outputname << "radiative_signal_" << mode <<".root"; 

        TFile* output = new TFile(outputname.str().c_str(),"RECREATE","output ROOT file");
        dh1->Write(); 
        dh2->Write(); 
        dh3->Write(); 
        dh4->Write(); 
        h1->Write();  
        output->Close();
  
}