QInjTester::QInjTester(QextSerialPort *port)
{
	serial = port;
	setWindowTitle(tr("Injector tester"));
	move(380,80);
	//setGeometry(300,100,500,320);
	timeCount = 50;
	flowTimer = new QTimer(this);
	flowTimer->setSingleShot(true);
	pulseTimer = new QTimer(this);
	pulseTimer->setSingleShot(true);

	LCDFlowTimer = new QTimer(this);
	LCDPulseTimer = new QTimer(this);

	QGridLayout *grid = new QGridLayout;

	QTextEdit *editFlowHelp = new QTextEdit(tr("Choose test duration. Pressing\n"
		"the start button, the injector will "
		"remain open for the selected time, or until stop button is pressed."));
	editFlowHelp->setReadOnly(true);

	QLabel *flowDurationLabel = new QLabel(tr("Duration (ms):     "));
	editFlowDuration = new QLineEdit("1000");
	editFlowDuration->setAlignment(Qt::AlignRight);

	flowTimeLCD = new QLCDNumber(6);
	flowTimeLCD->setSegmentStyle(QLCDNumber::Filled);

	startFlowButton = new QPushButton(tr("Start"));
	stopFlowButton = new QPushButton(tr("Stop"));

	connect(startFlowButton,SIGNAL(released()),this,SLOT(startFlow()));
	connect(stopFlowButton,SIGNAL(released()),this,SLOT(stopFlow()));
	connect(flowTimer,SIGNAL(timeout()),this,SLOT(stopFlow()));
	connect(LCDFlowTimer,SIGNAL(timeout()),this,SLOT(displayFlowLCD()));

	QGroupBox *groupBox2 = new QGroupBox(tr("Flow Test"));
	QGridLayout *vbox2 = new QGridLayout;
	vbox2->addWidget(editFlowHelp,0,0);
	vbox2->addWidget(flowTimeLCD,1,0);
	vbox2->addWidget(flowDurationLabel,0,1);
	vbox2->addWidget(editFlowDuration,0,2);
	vbox2->addWidget(startFlowButton,1,1);
	vbox2->addWidget(stopFlowButton,1,2);
	groupBox2->setLayout(vbox2);

	QTextEdit *editPulseHelp = new QTextEdit(tr("Elija la duracion de la prueba (ms).\n"
		"Cuando pulse el boton Start,los inyectores se abriran el durante el tiempo elegido"
		" y no se cerraran hasta que termine la prueba o se presione el boton Stop."));
	editPulseHelp->setReadOnly(true);

	QLabel *pulseDurationLabel = new QLabel(tr("Duration (ms):     "));
	editPulseDuration = new QLineEdit("1000");
	editPulseDuration->setAlignment(Qt::AlignRight);

	QLabel *pulseONLabel = new QLabel(tr("ON time (ms):     "));
	editPulseON = new QLineEdit("2.5");
	editPulseON->setAlignment(Qt::AlignRight);

	QLabel *pulseOFFLabel = new QLabel(tr("OFF time (ms):     "));
	editPulseOFF = new QLineEdit("2.5");
	editPulseOFF->setAlignment(Qt::AlignRight);

	ONtime.entero = 2500;
	OFFtime.entero = 2500;

	pulseTimeLCD = new QLCDNumber(6);
	pulseTimeLCD->setSegmentStyle(QLCDNumber::Filled);

	pulseBar = new QProgressBar;
	pulseBar->setRange(0,5000);
	pulseBar->setValue(2500);

	startPulseButton = new QPushButton(tr("Start"));
	stopPulseButton = new QPushButton(tr("Stop"));

	connect(startPulseButton,SIGNAL(released()),this,SLOT(startPulse()));
	connect(stopPulseButton,SIGNAL(released()),this,SLOT(stopPulse()));
	connect(editPulseON,SIGNAL(textChanged(const QString)),this,SLOT(editONChange(const QString )));
	connect(editPulseOFF,SIGNAL(textChanged(const QString)),this,SLOT(editOFFChange(const QString )));
	connect(pulseTimer,SIGNAL(timeout()),this,SLOT(stopPulse()));
	connect(LCDPulseTimer,SIGNAL(timeout()),this,SLOT(displayPulseLCD()));

	QGroupBox *groupBox1 = new QGroupBox(tr("Pulse Test"));
	QGridLayout *vbox = new QGridLayout;
	vbox->addWidget(editPulseHelp,0,0,5,1);
	vbox->addWidget(pulseTimeLCD,6,0);
	vbox->addWidget(pulseDurationLabel,0,1);
	vbox->addWidget(editPulseDuration,0,2);
	vbox->addWidget(pulseONLabel,1,1);
	vbox->addWidget(editPulseON,1,2);
	vbox->addWidget(pulseOFFLabel,2,1);
	vbox->addWidget(editPulseOFF,2,2);
	vbox->addWidget(pulseBar,4,1,1,2);
	vbox->addWidget(startPulseButton,6,1);
	vbox->addWidget(stopPulseButton,6,2);
	groupBox1->setLayout(vbox);

	grid->addWidget(groupBox2,0,0,1,2);
	grid->addWidget(groupBox1,1,0,1,2);

	setLayout(grid);
}
示例#2
0
void SteadyStateAlgo::runEvolution()
{
	int startGeneration = 0;
	char statfile[64];
	char inFilename[128];
	char outFilename[128];
	char bestOutFilename[128];
	int bestGeneration = -1;
	float bestFitness = -1.0;
	// Define the final mutation rate (i.e., the lower bound for the mutation rate)
	const double finalMutRate = m_mutRate;
	// Initialise the mutation rate
	m_mutRate = m_initMutRate; // initially mutation (default 50%)
	// Set the seed
	setSeed(m_rngSeed);
	// Initialise the population
	randomisePopulation();
	// Check whether to recover a previous evolution
	sprintf(statfile, "S%d.fit", seed());
	// Check if the file exists
	DataChunk statTest(QString("stattest"), Qt::blue, 2000, false);
	if (statTest.loadRawData(QString(statfile), 0))
	{
		startGeneration = statTest.getIndex();
		sprintf(inFilename, "S%dG%d.gen", (seed()), startGeneration);
		Logger::info("Recovering from startGeneration: " + QString::number(startGeneration));
		Logger::info(QString("Loading file: ") + inFilename);
		QFile inData(inFilename);
		if (inData.open(QFile::ReadOnly))
		{
			QTextStream in(&inData);
			for (int i = 0; i < m_popSize; i++)
			{
				bool loaded = m_population[i]->loadGen(in);
				// Check possible errors during the loading operation
				if (!loaded)
				{
					Logger::error("Error in the loading of the genotype");
				}
				// Check the consistency of the genotype (i.e., the number of genes)
				if (m_population[i]->getLength() != m_numGenes)
				{
					Logger::error("Wrong genotype length!");
				}
			}
			inData.close();
		}
	}
	// Flow control
	pauseFlow();
	if (stopFlow())
	{
		// Cleanup
		return;
	}
	// Do all generations
	for (int gn = startGeneration; gn < m_numGenerations; gn++)
	{
		// Define a fitness array for all the individuals to be tested
		QVector<float> fit(m_popSize * 2);
		m_gae->setIndividualCounter();
		m_gae->initGeneration(gn);
		// Evaluate all the individuals
		for (int i = 0; i < m_popSize; i++)
		{
			// Set the genotype to be tested
			m_gt->setGenotype(m_population[i]);
			// Evaluate the genotype
			m_gae->evaluate();
			// Get the fitness
			fit[i] = m_gae->getFitness();
			// Set the fitness of the current genotype
			m_population[i]->setFitness(fit[i]);
			// Use subclasses for modifying and/or getting elements (i.e., genes)
			GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]);
			GenotypeInt* off = dynamic_cast<GenotypeInt*>(m_population[i + m_popSize]);
			// Now generate an offspring and evaluate it
			for (int g = 0; g < m_numGenes; g++)
			{
				int val = ind->getGene(g);
				// Mutate the value
				int newVal = mutate(val, m_mutRate);
				off->setGene(g, newVal);
			}
			m_gt->setGenotype(m_population[i + m_popSize]);
			// Evaluate the genotype
			m_gae->evaluate();
			// Get the fitness
			fit[i + m_popSize] = m_gae->getFitness();
			// Flow control
			pauseFlow();
			if (stopFlow())
			{
				return;
			}
		}
		m_gae->resetIndividualCounter();
		// Select the best <popSize> individuals
		QVector<int> indices = sortFit(fit);
		// Define a temporary array for storing
		// the best <popSize> individuals
		QVector<float*> tmpPop(m_popSize);
		// Define a temporary array for storing
		// the fitnesses of the best individuals
		QVector<float> tmpFit(m_popSize);
		for (int i = 0; i < m_popSize; i++)
		{
			tmpPop[i] = new float[m_numGenes];
			int idx = indices[i];
			GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[idx]);
			for (int g = 0; g < m_numGenes; g++)
			{
				tmpPop[i][g] = ind->getGene(g);
			}
			tmpFit[i] = fit[idx];
		}
		// Swap individuals
		for (int i = 0; i < m_popSize; i++)
		{
			GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]);
			for (int g = 0; g < m_numGenes; g++)
			{
				ind->setGene(g, tmpPop[i][g]);
				ind->setFitness(tmpFit[i]);
			}
		}

		// Flow control
		pauseFlow();
		if (stopFlow())
		{
			break;
		}

		// Save fitness statistics
		char fitStatFilename[64];
		sprintf(fitStatFilename, "S%d.fit", seed());
		QFile fitStatData(fitStatFilename);
		bool openOk = false;
		if (gn == 0)
		{
			openOk = fitStatData.open(QIODevice::WriteOnly);
		}
		else
		{
			openOk = fitStatData.open(QIODevice::Append);
		}
		if (openOk)
		{
			QTextStream fitStat(&fitStatData);
			// Compute maximum, minimum and average fitness and store them in a vector
			QVector<float> fitArray(3);
			// Max
			float maxFit = fit[indices[0]];
			fitArray[0] = maxFit;
			// Average
			float avgFit = 0.0;
			for (int i = 0; i < m_popSize; i++)
			{
				avgFit += fit[indices[i]];
			}
			avgFit /= m_popSize;
			fitArray[1] = avgFit;
			// Min
			float minFit = fit[indices[m_popSize - 1]];
			fitArray[2] = minFit;
			saveFitStats(fitArray, fitStat);
			fitStatData.close();
		}

		// Save all fitness statistics if <saveFitnessAllIndividuals> flag is set to true
		if (m_saveFitnessAllIndividuals)
		{
			char allFitStatFilename[64];
			sprintf(allFitStatFilename, "S%dall.fit", seed());
			QFile allFitStatData(allFitStatFilename);
			openOk = false;
			if (gn == 0)
			{
				openOk = allFitStatData.open(QIODevice::WriteOnly);
			}
			else
			{
				openOk = allFitStatData.open(QIODevice::Append);
			}
			if (openOk)
			{
				QTextStream allFitStat(&allFitStatData);
				saveFitStats(fit, allFitStat);
				allFitStatData.close();
			}
		}

		// Save the best genotype
		sprintf(bestOutFilename, "S%dB%d.gen", seed(), 0);
		QFile bestOutData(bestOutFilename);
		bool operation = false;
		if (gn == 0)
		{
			// Open the QFile in write mode
			operation = bestOutData.open(QIODevice::WriteOnly);
		}
		else
		{
			// Open the QFile in append mode
			operation = bestOutData.open(QFile::Append);
		}
		if (operation)
		{
			QTextStream bestOut(&bestOutData);
			GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[0]);
			ind->saveGen(bestOut);
			bestOutData.close();
		}

		// Save all the genotypes
		sprintf(outFilename, "S%dG%d.gen", seed(), (gn + 1));
		QFile outData(outFilename);
		if (outData.open(QIODevice::WriteOnly))
		{
			QTextStream out(&outData);
			// Save the population
			for (int i = 0; i < m_popSize; i++)
			{
				GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]);
				ind->saveGen(out);
			}
			outData.close();
		}
		// Decrease the mutation rate (until it becomes equal to the lower bound)
		if (m_mutRate > finalMutRate)
		{
			m_mutRate -= m_mutDecay;
		} 
		else 
		{
			m_mutRate = finalMutRate;
		}

		// Check the best generation
		if (fit[indices[0]] > bestFitness)
		{
			bestFitness = fit[indices[0]];
			bestGeneration = gn;
		}

		m_gae->endGeneration(gn);
	}
	// Save the information about the best generation
	char bestGenFileName[64];
	sprintf(bestGenFileName, "S%dbest.fit", seed());
	QFile bestGenData(bestGenFileName);
	// Open the QFile in write mode
	if (bestGenData.open(QIODevice::WriteOnly))
	{
		QTextStream bestGenOut(&bestGenData);
		QString outStr;
		//! Write the best generation index
		outStr = QString::number(bestGeneration);
		bestGenOut << outStr;
		//! Write the fitness of the best generation
		outStr = QString::number(bestFitness);
		bestGenOut << " " << outStr;
		bestGenOut << endl;
		bestGenData.close();
	}
}