Exemplo n.º 1
0
double p3d_gaussian_random2( const double& mean, const double& variance )
{
    double result;

    result = mersenne_twister_rng.randNorm(mean,variance);
    return(result);
}
Exemplo n.º 2
0
//*************************
//  Main
//
int main(int argc, char *argv[])
{
	int sckt;
	pthread_t recvThread;
	char sendBuffer[BUFFER_SIZE];
	int indexBuffer;
	int sharedRecs;
	RTDBconf_var rec[MAX_RECS];
	unsigned int frameCounter = 0;
	int i, j;
	int life;

	struct sched_param proc_sched;
	pthread_attr_t thread_attr;

	struct itimerval it;
	struct _frameHeader frameHeader;

	struct timeval tempTimeStamp;

  nosend = 0;
	if ((argc < 2) || (argc > 3))
	{
		printUsage();
		return (-1);
	}
	if (argc == 3)
	{
		if(strcmp(argv[2], "nosend") == 0)
		{
			printf("\n*** Running in listing only mode ***\n\n");
			nosend = 1;
		}
		else
		{
			printUsage();
			return (-1);
		}
	}

	/* initializations */
	delay = 0;
	timer = 0;
	end = 0;
	RUNNING_AGENTS = 1;

	/* Assign a real-time priority to process */
	proc_sched.sched_priority=60;
	if ((sched_setscheduler(getpid(), SCHED_FIFO, &proc_sched)) < 0)
	{
		PERRNO("setscheduler");
		return -1;
	}

	if(signal(SIGALRM, signal_catch) == SIG_ERR)
	{
		PERRNO("signal");
		return -1;
	}

	if(signal(SIGINT, signal_catch) == SIG_ERR)
	{
		PERRNO("signal");
		return -1;
	}

	if((sckt = openSocket(argv[1])) == -1)
	{
		PERR("openMulticastSocket");
		printf("\nUsage: comm <interface_name>\n\n");
		return -1;
	}

	if(DB_init() == -1)
	{
		PERR("DB_init");
		closeSocket(sckt);
		return -1;
	}
	
	if((sharedRecs = DB_comm_ini(rec)) < 1)
	{
		PERR("DB_comm_ini");
		DB_free();
		closeSocket(sckt);
		return -1;
	}

#ifdef FILEDEBUG
	if ((filedebug = fopen("log.txt", "w")) == NULL)
	{
		PERRNO("fopen");
		DB_free();
		closeSocket(sckt);
		return -1;
	}
#endif

	/* initializations */
	for (i=0; i<MAX_AGENTS; i++)
	{
		lostPackets[i]=0;
		agent[i].lastFrameCounter = 0;
		agent[i].state = NOT_RUNNING;
		agent[i].removeCounter = 0;
	}
	myNumber = Whoami();
	agent[myNumber].state = RUNNING;

	/* receive thread */
	pthread_attr_init (&thread_attr);
	pthread_attr_setinheritsched (&thread_attr, PTHREAD_INHERIT_SCHED);
	if ((pthread_create(&recvThread, &thread_attr, receiveDataThread, (void *)&sckt)) != 0)
	{
		PERRNO("pthread_create");
		DB_free();
		closeSocket(sckt);
		return -1;
	}

	/* Set itimer to reactivate the program */
	it.it_value.tv_usec=(__suseconds_t)(TTUP_US);
	it.it_value.tv_sec=0;
	it.it_interval.tv_usec=(__suseconds_t)(TTUP_US);
	it.it_interval.tv_sec=0;
	setitimer (ITIMER_REAL, &it, NULL);

	printf("communication: STARTED in ");
#ifdef UNSYNC
	printf("unsync mode...\n");
#else
	printf("sync mode...\n");
#endif 


	MTRand randomGenerator;
	while (!end)
	{
		//pause();
		double waitTime = randomGenerator.randNorm(0,1) * TTUP_US * 0.05 + TTUP_US;
		usleep(waitTime);

		// not timer event
		if (timer == 0)
			continue;

#ifndef UNSYNC
		// dynamic agent 0
		if ((delay > (int)MIN_UPDATE_DELAY_US) && (agent[myNumber].dynamicID == 0) && timer == 1)
		{
			it.it_value.tv_usec = (__suseconds_t)(delay - (int)MIN_UPDATE_DELAY_US/2);
			it.it_value.tv_sec = 0;
			setitimer (ITIMER_REAL, &it, NULL);
			delay = 0;
			continue;
		}
#endif

		timer = 0;

		indexBuffer = 0;
		bzero(sendBuffer, BUFFER_SIZE);

		update_stateTable();

		// update dynamicID
		j = 0;	
		for (i = 0; i < MAX_AGENTS; i++)
		{
			if ((agent[i].state == RUNNING) || (agent[i].state == REMOVE))
			{
				agent[i].dynamicID = j;
				j++;
			}
			agent[myNumber].stateTable[i] = agent[i].state;
		}
		RUNNING_AGENTS = j;

		MAX_DELTA = (int)(TTUP_US/RUNNING_AGENTS * 2/3);

		// frame header
		frameHeader.number = myNumber;
		frameHeader.counter = frameCounter;
		frameCounter ++;
		for (i = 0; i < MAX_AGENTS; i++)
			frameHeader.stateTable[i] = agent[myNumber].stateTable[i];
		frameHeader.noRecs = sharedRecs;
		memcpy(sendBuffer + indexBuffer, &frameHeader, sizeof(frameHeader));
		indexBuffer += sizeof(frameHeader);

		for(i = 0; i < sharedRecs; i++)
		{
			// id
			memcpy(sendBuffer + indexBuffer, &rec[i].id, sizeof(rec[i].id));
			indexBuffer += sizeof(rec[i].id);

			// size
			memcpy(sendBuffer + indexBuffer, &rec[i].size, sizeof(rec[i].size));
			indexBuffer += sizeof(rec[i].size);

			// life and data
			life = DB_get(myNumber, rec[i].id, sendBuffer + indexBuffer + sizeof(life));
			memcpy(sendBuffer + indexBuffer, &life, sizeof(life));
			indexBuffer = indexBuffer + sizeof(life) + rec[i].size;
		}

		if (indexBuffer > BUFFER_SIZE)
		{
			PERR("Pretended frame is bigger that the available buffer.");
			PERR("Please increase the buffer size or reduce the number of disseminated records");
			break;
		}
	
		if (nosend == 0) 
		{
			if (sendData(sckt, sendBuffer, indexBuffer) != indexBuffer)
				PERRNO("Error sending data");
		}

		gettimeofday (&tempTimeStamp, NULL);
		lastSendTimeStamp.tv_sec = tempTimeStamp.tv_sec;
		lastSendTimeStamp.tv_usec = tempTimeStamp.tv_usec;

		// reset values for next round
		for (i=0; i<MAX_AGENTS; i++)
		{
			agent[i].delta = 0;
			agent[i].received = NO;
		}
	}

	FDEBUG (filedebug, "\nLost Packets:\n");
	for (i=0; i<MAX_AGENTS; i++)
		FDEBUG (filedebug, "%d\t", lostPackets[i]);
	FDEBUG (filedebug, "\n");
	
	printf("communication: STOPED.\nCleaning process...\n");

#ifdef FILEDEBUG
	fclose (filedebug);
#endif

	closeSocket(sckt);

	pthread_join(recvThread, NULL);

	DB_free();

	printf("communication: FINISHED.\n");

	return 0;
}
void QFRDRFCSFitFunctionSimulator::replotFitFunction() {
    JKQTPdatastore* ds=ui->pltFunction->getDatastore();
    QScopedPointer<QFFitFunction> ffunc(getFitFunction(NULL));

    if (!ffunc) return;

    try {
        ui->pltFunction->set_doDrawing(false);
        ui->pltFunction->clearGraphs();
        ds->clear();
        updateTau();
        if (tauN) {


            /////////////////////////////////////////////////////////////////////////////////
            // retrieve fit parameters and errors. run calcParameters to fill in calculated parameters and make sure
            // we are working with a complete set of parameters
            /////////////////////////////////////////////////////////////////////////////////

            double* fullParams=(double*)qfCalloc(ffunc->paramCount(), sizeof(double));
            double* errors=(double*)qfCalloc(ffunc->paramCount(), sizeof(double));
            double Nparticle=0;
            bool hasNParticle=false;
            for (int p=0; p<ffunc->paramCount(); p++) {
                QFFitFunction::ParameterDescription d=ffunc->getDescription(p);
                QString id=d.id;
                if (params.contains(id)) {
                    fullParams[p]=params[id].value;
                    errors[p]=params[id].error;
                } else {
                    fullParams[p]=d.initialValue;
                    /*double value=0;
                    if (overrideFitFunctionPreset(id, value)) d.initialValue=value;*/

                    errors[p]=0;
                }
            }
            ffunc->calcParameter(fullParams, errors);
            used_params.clear();
            for (int p=0; p<ffunc->paramCount(); p++) {
                QFFitFunction::ParameterDescription d=ffunc->getDescription(p);
                QString id=d.id.toLower();
                bool visible=ffunc->isParameterVisible(ffunc->getParameterNum(id), fullParams);
                if (visible) {
                    if (id=="n_particle") {
                        Nparticle=fullParams[p];
                        hasNParticle=true;
                    }
                    if (id=="1n_particle" && !hasNParticle) {
                        Nparticle=1.0/fullParams[p];
                        hasNParticle=true;
                    }
                    used_params[id]=fullParams[p];
                }
            }

            used_params["tau_min"]=ui->edtMinTau->value();
            used_params["tau_max"]=ui->edtMaxTau->value();
            used_params["runs"]=ui->spinRuns->value();
            used_params["noise_enabled"]=ui->chkNoise->isChecked();
            used_params["model_function"]=ffunc->id();

            csv="";

            // evaluate correlation function and determine small-lag amplitude
            double tau0avg=0;
            for (int r=0; r<runs; r++) {
                for (int i=0; i<tauN; i++) {
                    corr[r*tauN+i]=ffunc->evaluate(tau[i], fullParams);
                }
                tau0avg=tau0avg+corr[r*tauN];
            }
            tau0avg=tau0avg/double(runs);
            if (!hasNParticle) Nparticle=1.0/tau0avg;

            // calc noise
            if (ui->chkNoise->isChecked()) {
                MTRand rng;
                if (ui->cmbNoiseModel->currentIndex()==0) {
                    double I=ui->spinAvgCountRate->value()*1000.0;
                    double I2=sqr(I);
                    double NN=Nparticle;
                    if (NN<=0) NN=1.0;
                    for (int r=0; r<runs; r++) {
                        double corr0=corr[r*tauN];
                        for (int i=0; i<tauN; i++) {
                            double corrT=corr[r*tauN+i];
                            double M=ui->spinMeasDuration->value()/tau[i];
                            double m=tau[0]/tau[i];
                            double var=((1.0+sqr(corr0))*(1.0+sqr(corrT))/(1.0-sqr(corr0))+2.0*m*sqr(corrT))/M/NN/NN+(2.0*(1.0+sqr(corrT))/NN/I+(1.0+corrT/NN)/I2)/M;
                            corr[r*tauN+i]=corr[r*tauN+i]+rng.randNorm(0,1)*sqrt(var);
                        }
                    }
                    used_params["noise_model"]=QString("Koppel");
                    used_params["noise_intensity_kHz"]=I;
                    used_params["noise_measurement_duration"]=ui->spinMeasDuration->value();
                } else if (ui->cmbNoiseModel->currentIndex()==1) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+rng.randNorm(0, 1)*(ui->spinNoiseLevel->value()/100.0*tau0avg);
                        }
                    }
                    used_params["noise_model"]=QString("gaussian");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                } else if (ui->cmbNoiseModel->currentIndex()==2) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+(rng.rand()*2.0-1.0)*ui->spinNoiseLevel->value()/100.0*tau0avg;
                        }
                    }
                    used_params["noise_model"]=QString("uniform");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                } else if (ui->cmbNoiseModel->currentIndex()==3) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+rng.randNorm(0, 1)*(ui->spinNoiseLevel->value()/100.0*corr[r*tauN+i]);
                        }
                    }
                    used_params["noise_model"]=QString("local gaussian");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                } else if (ui->cmbNoiseModel->currentIndex()==4) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+(rng.rand()*2.0-1.0)*ui->spinNoiseLevel->value()/100.0*corr[r*tauN+i];
                        }
                    }
                    used_params["noise_model"]=QString("local uniform");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                }
            }


            for (int i=0; i<tauN; i++) {
                csv=csv+CDoubleToQString(tau[i]);
                for (int r=0; r<runs; r++) {
                    csv=csv+", "+CDoubleToQString(corr[r*tauN+i]);
                }
                csv=csv+"\n";
            }


            size_t c_tau = ds->addCopiedColumn(tau, tauN, "tau");

            for (int r=0; r<runs; r++) {
                size_t c_fit = ds->addCopiedColumn(&(corr[r*tauN]), tauN, QString("function_r%1").arg(r));
                /////////////////////////////////////////////////////////////////////////////////
                // plot fit model and additional function graphs
                /////////////////////////////////////////////////////////////////////////////////
                JKQTPxyLineGraph* g_fit=new JKQTPxyLineGraph(ui->pltFunction->get_plotter());
                g_fit->set_drawLine(true);
                g_fit->set_title(tr("run %1").arg(r));
                g_fit->set_xColumn(c_tau);
                g_fit->set_yColumn(c_fit);
                ui->pltFunction->addGraph(g_fit);
            }
        }

        ui->pltFunction->zoomToFit();
        ui->pltFunction->set_doDrawing(true);
        ui->pltFunction->update_plot();
    } catch(std::exception& E) {
        services->log_error(tr("error during plotting, error message: %1\n").arg(E.what()));
    }

}