void GaussSeidel::plotIterationLog()
{
    const std::string cmd_filename = "plotconfig_it.gnu";
    const std::string pic_filename = "iteractive_it.png";
    const std::string dat1_filename = "data_it.txt";

    // Solução numérica
    std::ofstream file1(dat1_filename.c_str());
    for(tInteger i=0; i<nit; i++)
        file1<<i<<"\t"<<QtoD(L[i]/L[0])<<std::endl;
    file1.close();

    std::ofstream file3(cmd_filename.c_str());
    file3 <<
             "set terminal pngcairo enhanced font \"arial,12\" size 1600, 1000 \n"
             "set output '" << pic_filename <<"'\n"
             "#set key inside right top vertical Right noreverse enhanced autotitles box linetype -1 linewidth 1.000\n"
             "set grid\n"
             "set logscale y\n"
             "set format y \"10^{%L}\" \n"
             "set lmargin 10 \n"
             "set title \"DESEMPENHO DE ITERAÇÃO \\n itmax = "<<imax<<"  itol = "<<QtoD(itol)<<"  nit = "<<nit-1<<"\"\n"
             "set ylabel \"L^{n}/L^{0}\" \n"
             "set xlabel 'Número de iterações'\n"

             "plot '" <<dat1_filename<<"' t\"\" with lines lt 2 lc 1 lw 2";
    file3.close();

    const std::string cmd1 = "gnuplot " + cmd_filename; // Gráfico com GNUPLOT
    const std::string cmd2 = "eog " + pic_filename; // Visualizador de imagem

    std::system(cmd1.c_str());
    std::system(cmd2.c_str());
}
Exemplo n.º 2
0
int main(void)
{
	IniFile file2("test.ini");
	IniFile file3(file2);
	IniFile file4 = file3;

	int v_int;
	double v_double;
	char v_char[10];

	for (int i = 0;i < 1000;i++)
	{
		IniFile file;
		file.createIniFile("test.ini");

		file.setStringValue("Another", "Test", "Succeed");
		file.setIntegerValue("Another", "Count", i);
		int count;
		file.getIntegerValue("Another", "Count", count);
		std::cout << count << std::endl;
	}

	file2.getStringValue("General", "Language", v_char,10);
	file3.getIntegerValue("General", "Age", v_int);
	file4.getDoubleValue("Info", "Cost", v_double);
	std::cout << v_char << std::endl;
	std::cout << v_int << std::endl;
	std::cout << v_double << std::endl;

	file2.setDoubleValue("Test", "Double", 478.1231);
	
	system("pause");
	return 0;
}
void Diffusion2Dp::plot(Functor2D &analyticalSolution)
{
    const std::string cmd_filename = "plotconfig.gnu";
    const std::string pic_filename = "plot.png";
    const std::string dat1_filename = "data1.txt";
    const std::string dat2_filename = "data2.txt";

    // Solução numérica
    std::ofstream file1(dat1_filename.c_str());
    for(tInteger i=0; i<nx*ny; i++)
        file1<<QtoD(nodes[i].x)<<"\t"<<QtoD(nodes[i].y)<<"\t"<<QtoD(T[i])<<std::endl;
    file1.close();

        // Solução Analítica
        std::ofstream file2(dat2_filename.c_str());
        int f = 10;
        tFloat hy_10 = ly/(f*ny-1); // Aumenta o número de pontos em f X
        tFloat hx_10 = lx/(f*nx-1);
        for(tInteger j=0; j<f*nx; j++)
        for(tInteger i=0; i<f*ny; i++)
        {
            tFloat yp = i*hy_10;
            tFloat xp = j*hx_10;
            file2<<QtoD(xp)<<"\t"<<QtoD(yp)<<"\t"<<QtoD(analyticalSolution(xp, yp))<<std::endl;
        }
        file2.close();

    std::ofstream file3(cmd_filename.c_str());
    file3 <<
             "set terminal pngcairo enhanced font \"arial,12\" size 1600, 1000 \n"
             "#set terminal wxt font \"arial,12\" size 1600, 1000 \n"
             "set output '" << pic_filename <<"'\n"
             "set key inside right top vertical Right noreverse enhanced autotitles box linetype -1 linewidth 1.000\n"
             "set grid\n"
             "set title \"DIFUSÃO DE CALOR BIDIMENSIONAL EM REGIME PERMANENTE\\nResolução com MDF / Aproximação com CDS-2\"\n"
             "set lmargin 8\n"
             "set xlabel 'x'\n"
             "set ylabel 'y'\n"
             "set zlabel 'T( x, y)'\n"
             "splot '" <<dat2_filename<<"' t\"Solução Analítica\" with points lt 2 lc 0 lw 2 pt 0, "
             " '" <<dat1_filename<<"' t\"Solução Numérica\" with points lt 2 lc 1 pt 13 lw 5\n"
             "#pause -1";
    file3.close();

    const std::string cmd1 = "gnuplot " + cmd_filename; // Gráfico com GNUPLOT
    const std::string cmd2 = "eog " + pic_filename; // Visualizador de imagem

    std::system(cmd1.c_str());
    std::system(cmd2.c_str());
}
Exemplo n.º 4
0
void TestChunks::compare()
{
    QByteArray rHighLighted;
    QByteArray rData = _chunks.data(0, -1, &rHighLighted);
    bool error = false;

    if (rData != _data)
        error = true;
    if (rHighLighted != _highlighted)
        error = true;

    _tCnt += 1;

    int chunkSize = _chunks.chunkSize();
    QString tName = QString("logs/%1_%2_%3").arg(_tName).arg(_tCnt).arg(chunkSize);
    if (error || (_tCnt >= _saveFile))
    {
        QFile file1(tName + "_data.txt");
        file1.open(QIODevice::WriteOnly);
        file1.write(_data);
        file1.close();

        QFile file2(tName + "_highlighted.txt");
        file2.open(QIODevice::WriteOnly);
        file2.write(_highlighted);
        file2.close();

        QFile file3(tName + "_rData.txt");
        file3.open(QIODevice::WriteOnly);
        file3.write(rData);
        file3.close();

        QFile file4(tName + "_rHighlighted.txt");
        file4.open(QIODevice::WriteOnly);
        file4.write(rHighLighted);
        file4.close();
    }

    if (error)
    {
        qDebug() << "NOK " << tName;
        *_log << "NOK " << tName << "\n";
    }
    else
    {
        qDebug() << "OK " << tName;
        *_log << "OK " << tName << "\n";
    }

}
Exemplo n.º 5
0
void XMLParserTest::initTestCase(){
    xmlParser = new XMLParser();
    QString path = QString("%1/%2").arg(StandardPaths::writeableLocation());
    QFile file(":/testData/transportations.xml");
    if(file.open(QIODevice::ReadOnly)){
        if(file.copy(path.arg("transportations.xml")))
            QFile::setPermissions(path.arg("transportations.xml"), QFile::WriteOwner | QFile::ReadOwner);
    }
    file.close();

    QFile file2(":/testData/equipments.xml");
    if(file2.open(QIODevice::ReadOnly)){
        if(file2.copy(path.arg("equipments.xml")))
            QFile::setPermissions(path.arg("equipments.xml"), QFile::WriteOwner | QFile::ReadOwner);
    }
    file2.close();

    QFile file3(":/testData/products.xml");
    if(file3.open(QIODevice::ReadOnly)){
        if(file3.copy(path.arg("products.xml")))
            QFile::setPermissions(path.arg("products.xml"), QFile::WriteOwner | QFile::ReadOwner);
    }
    file3.close();

    QFile file4(":/testData/employees.xml");
    if(file4.open(QIODevice::ReadOnly)){
        if(file4.copy(path.arg("employees.xml")))
            QFile::setPermissions(path.arg("employees.xml"), QFile::WriteOwner | QFile::ReadOwner);
    }
    file4.close();

    QFile file5(":/testData/workplaces.xml");
    if(file5.open(QIODevice::ReadOnly)){
        if(file5.copy(path.arg("workplaces.xml")))
            QFile::setPermissions(path.arg("workplaces.xml"), QFile::WriteOwner | QFile::ReadOwner);
    }
    file5.close();

    QFile file6(":/testData/workprocesslists.xml");
    if(file6.open(QIODevice::ReadOnly)){
        if(file6.copy(path.arg("workprocesslists.xml")))
            QFile::setPermissions(path.arg("workprocesslists.xml"), QFile::WriteOwner | QFile::ReadOwner);
    }
    file6.close();

}
void StatisticManager::load()
{
    QFile file( this->_path );
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }
    //
    QTextStream in(&file);
    QString nameLine = in.readLine();
    _names.append( nameLine.split( "\t" ) );
    while (!in.atEnd())
    {
        QString line = in.readLine();
        QStringList list = line.split( "\t" );
        this->_table.append( list );
    }
    //**********************************************************
    QFile file2( "data/1D_parameterData.txt" );
    if (!file2.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }
    QTextStream in2(&file2);
    while (!in2.atEnd())
    {
        QString line = in2.readLine();
        _1DparaName.append( line );
    }

    QFile file3( "data/1DT_parameterData.txt" );
    if (!file3.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }
    QTextStream in3(&file3);
    while (!in3.atEnd())
    {
        QString line = in3.readLine();
        _1DTparaName.append( line );
    }

    return;
}
Exemplo n.º 7
0
void ChannelH11::InputManagement(){
    static double h41[1000][300] = {0};
    //load pilot data
    QFile file2("./pilot/pilot_100_re.txt");
    if (!file2.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << file2.errorString() <<" NO FILE";
    QFile file3("./pilot/pilot_100_im.txt");
    if (!file3.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << file3.errorString() <<" NO FILE";

    char str[100];
    for( int i = 0 ; i < 100 ; i++){
        file2.readLine(str,100);
        int crr = char2int(str);
        pilot[i][0] = crr;
        //qDebug() << "pilot[ "<<i<<" ][0] is :" << pilot[i][0];
        file3.readLine(str,100);
        crr = char2int(str);
        pilot[i][1] = crr;
        //qDebug() << "pilot[ "<<i<<" ][1] is :" << pilot[i][1] << endl;
    }//for



    QFile file("h_300_1000_re.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << file.errorString();

    int length = 1000;
    for( int i = 0 ; i < length ; i++ ){
        for( int j = 0 ; j < 300 ; j++ ){
            file.readLine(str,100);
            double crr = 0;
            crr = char2double(str);
            //qDebug() << "crr is :"<<crr;
            //h41[i][j] = crr*10;
            h41[i][j] = 0;
        }
    }
    //qDebug() << "h41[40][299] one is :"<< h41[40][299] ;
    pdata = &h41[0][0];
    pdata2 = pdata;
    file.close();
}
Exemplo n.º 8
0
void tst_QFileInfo::isDir_data()
{
    // create a broken symlink
    QFile::remove("brokenlink.lnk");
    QFile::remove("dummyfile");
    QFile file3("dummyfile");
    file3.open(QIODevice::WriteOnly);
    if (file3.link("brokenlink.lnk")) {
        file3.remove();
        QFileInfo info3("brokenlink.lnk");
        QVERIFY( info3.isSymLink() );
    }

    QTest::addColumn<QString>("path");
    QTest::addColumn<bool>("expected");

    QTest::newRow("data0") << QDir::currentPath() << true;
    QTest::newRow("data1") << SRCDIR "tst_qfileinfo.cpp" << false;
    QTest::newRow("data2") << ":/tst_qfileinfo/resources/" << true;
    QTest::newRow("data3") << ":/tst_qfileinfo/resources/file1" << false;
    QTest::newRow("data4") << ":/tst_qfileinfo/resources/afilethatshouldnotexist" << false;

    QTest::newRow("simple dir") << SRCDIR "resources" << true;
    QTest::newRow("simple dir with slash") << SRCDIR "resources/" << true;

    QTest::newRow("broken link") << "brokenlink.lnk" << false;

#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
    QTest::newRow("drive 1") << "c:" << true;
    QTest::newRow("drive 2") << "c:/" << true;
    //QTest::newRow("drive 2") << "t:s" << false;
#endif
#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
    QTest::newRow("unc 1") << "//"  + QtNetworkSettings::winServerName() << true;
    QTest::newRow("unc 2") << "//"  + QtNetworkSettings::winServerName() + "/" << true;
    QTest::newRow("unc 3") << "//"  + QtNetworkSettings::winServerName() + "/testshare" << true;
    QTest::newRow("unc 4") << "//"  + QtNetworkSettings::winServerName() + "/testshare/" << true;
    QTest::newRow("unc 5") << "//"  + QtNetworkSettings::winServerName() + "/testshare/tmp" << true;
    QTest::newRow("unc 6") << "//"  + QtNetworkSettings::winServerName() + "/testshare/tmp/" << true;
    QTest::newRow("unc 7") << "//"  + QtNetworkSettings::winServerName() + "/testshare/adirthatshouldnotexist" << false;
#endif
}
void Thermoelasticity2Dp::plotX(tInteger p)
{
    const std::string cmd_filename = "plotconfig.gnu";
    const std::string pic_filename = "plotx.png";
    const std::string dat1_filename = "data1.txt";
    const std::string dat2_filename = "data2.txt";

    // Solução numérica
    std::ofstream file1(dat1_filename.c_str());
    for(tInteger i=0; i<nx; i++)
        file1<<QtoD(nodes[p*nx+i].x)<<"\t"<<QtoD(U[p*nx+i])<<std::endl;
    file1.close();

    std::ofstream file2(dat2_filename.c_str());
    for(tInteger i=0; i<nx; i++)
        file2<<QtoD(nodes[p*nx+i].x)<<"\t"<<QtoD(V[p*nx+i])<<std::endl;
    file2.close();


    std::ofstream file3(cmd_filename.c_str());
    file3 <<
             "set terminal pngcairo enhanced font \"arial,12\" size 1600, 1000 \n"
             "set output '" << pic_filename <<"'\n"
             "set key inside right top vertical Right noreverse enhanced autotitles box linetype -1 linewidth 1.000\n"
             "set grid\n"
             "set title \"TERMOELASTICIDADE BIDIMENSIONAL EM REGIME PERMANENTE\\nResolução com MDF / Aproximação com CDS-2\"\n"
             "set xlabel 'x'\n"
             "set ylabel \"u( x, "<<QtoD(p*hy)<<"), v( x, "<<QtoD(p*hy)<<")\"\n"
             "plot '" <<dat2_filename<<"' t\"u( x, "<<QtoD(p*hy)<<")\" with linespoints lt 2 lc 2 pt 4 lw 1, "
             "'" <<dat1_filename<<"' t\"v( x, "<<QtoD(p*hy)<<")\" with linespoints lt 2 lc 1 pt 3 lw 1";
    file3.close();

    const std::string cmd1 = "gnuplot " + cmd_filename; // Gráfico com GNUPLOT
    const std::string cmd2 = "eog " + pic_filename; // Visualizador de imagem

    std::system(cmd1.c_str());
    std::system(cmd2.c_str());
}
Exemplo n.º 10
0
// ==> createPovRayFile(outputPath)
//  Build a POV-Ray output file based on the camera/light/sections properties
//  The POV-Ray file is always a wrapper for the scene written to a chosen output path under the name "combined.pov"
//  It checks if a section needs to be added and check for the the type of the cross section
//--------------------------------------------------------------------
bool CameraManager::createPovRayFile(QString outputPath)
{
	QFile file(outputPath + "combined.pov");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return 0;

    QTextStream out(&file);
	out << "// POVRAY file created by MCNPXVisualizer\n";
	out << "\n";
		
	out << "#include \"colors.inc\"\n";
	out << "#include \"stones.inc\"\n";
	out << "#include \"camera.pov\"\n";
	out << "#include \"lights.pov\"\n"; 
	out << "\n";
	out << "global_settings\n";
	out << "{\n";
	out << "\tmax_trace_level " << _maxTraceLevel << "\n";
	out << "}\n\n";

	out << "background   { color rgb <" << _backgroundColorRed << ", " << _backgroundColorGreen << ", " << _backgroundColorBlue << "> }\n";
	
	out << "difference{ \n";
	
	out << "\t#include \"" << _inputFileName << "\"\n";
	if (_clippedByImp0)
		out << "\t#include \"" << _inputFileName << "_imp0.pov" << "\"\n";
	out << "\n";

	if (_sections->_useShortCut)
	{
		if (_sections->_typeShortCut == Sections3D::SHORTCUT_X)
		{
			out << "\tplane {x, " << _sections->_shortCutBase << " inverse}\n";
		}
		else if (_sections->_typeShortCut == Sections3D::SHORTCUT_X_INVERSE)
		{
			out << "\tplane {x, " << _sections->_shortCutBase << "}\n";
		}
		else if (_sections->_typeShortCut == Sections3D::SHORTCUT_Y)
		{
			out << "\tplane {y, " << _sections->_shortCutBase << " inverse}\n";
		}
		else if (_sections->_typeShortCut == Sections3D::SHORTCUT_Y_INVERSE)
		{
			out << "\tplane {y, " << _sections->_shortCutBase << "}\n";
		}
		else if (_sections->_typeShortCut == Sections3D::SHORTCUT_Z)
		{
			out << "\tplane {z, " << _sections->_shortCutBase << " inverse}\n";
		}
		else if (_sections->_typeShortCut == Sections3D::SHORTCUT_Z_INVERSE)
		{
			out << "\tplane {z, " << _sections->_shortCutBase << "}\n";
		}
		else
		{
			std::cout << "ERROR (CameraManager::createPovRayFile)" << std::endl;
		}
	}
	else
	{
		if (_sectionsEnabled)
		{
			if (_sections->_typeSections == Sections3D::SECTIONS_RECTANGULAR)
			{
				out << "\tplane {z, " << _sections->_zPlaneMinPos-1 << "}\n";
				out << "\tplane {z, " << _sections->_zPlaneMaxPos-1 << " inverse}\n";
				out << "\tplane {y, " << _sections->_yPlaneMinPos-1 << "}\n";
				out << "\tplane {y, " << _sections->_yPlaneMaxPos-1 << " inverse}\n";
				out << "\tplane {x, " << _sections->_xPlaneMinPos-1 << "}\n";
				out << "\tplane {x, " << _sections->_xPlaneMaxPos-1 << " inverse}\n";
			}
			else if (_sections->_typeSections == Sections3D::SECTIONS_XY)
			{
				bool greaterThan180 = std::abs(_sections->_angleMax - _sections->_angleMin) > 180;
				if (!greaterThan180)
				{
				out << "\tplane {y, 0\n";
				out << "\t\trotate <0,0," << _sections->_angleMin << "> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
				out << "\t}\n";
				out << "\tplane {-y, 0\n";
				out << "\t\trotate <0,0," << _sections->_angleMax << "> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
				out << "\t }\n";
				}
				out << "\tcylinder {\n";
				out << "\t<0,0," << -_sections->_height/2.0 << ">, <0,0," << _sections->_height/2.0 << ">, " << _sections->_radius << " translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << "> inverse}\n";
				
				out << "\t\n";
				if (greaterThan180)
				{
					out << "\tclipped_by {\n";
					out << "\tunion {\n";
					out << "\tplane {-y, 0\n";
					out << "\t\trotate <0,0," << _sections->_angleMin << "> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t }\n";
					out << "\tplane {y, 0\n";
					out << "\t\trotate <0,0," << _sections->_angleMax << "> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t }\n";
					out << "\t }\n";
					out << "\t }\n";
				}
				
			}
			else if (_sections->_typeSections == Sections3D::SECTIONS_YZ)
			{
				bool greaterThan180 = std::abs(_sections->_angleMax - _sections->_angleMin) > 180;
				if (!greaterThan180)
				{
				out << "\tplane {z, 0\n";
				out << "\t\trotate <" << _sections->_angleMin << ",0,0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
				out << "\t}\n";
				out << "\tplane {-z, 0\n";
				out << "\t\trotate <" << _sections->_angleMax << ",0,0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
				out << "\t}\n";
				}
				out << "\tcylinder {\n";
				out << "\t<" << -_sections->_height/2.0 << ",0,0>, <" << _sections->_height/2.0 << ",0,0>, " << _sections->_radius << " translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << "> inverse}\n";
				
				out << "\t\n";
				if (greaterThan180)
				{
					out << "\tclipped_by {\n";
					out << "\tunion {\n";
					out << "\tplane {-z, 0\n";
					out << "\t\trotate <" << _sections->_angleMin << ",0,0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t }\n";
					out << "\tplane {z, 0\n";
					out << "\t\trotate <" << _sections->_angleMax << ",0,0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t }\n";
					out << "\t }\n";
					out << "\t }\n";
				}
			}
			else if (_sections->_typeSections == Sections3D::SECTIONS_XZ)
			{
				bool greaterThan180 = std::abs(_sections->_angleMax - _sections->_angleMin) > 180;
				if (!greaterThan180)
				{
					out << "\tplane {x, 0\n";
					out << "\t\trotate <0," << _sections->_angleMin << ",0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t}\n";
					out << "\tplane {-x, 0\n";
					out << "\t\trotate <0," << _sections->_angleMax << ",0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t}\n";		
				}
				out << "\tcylinder {\n";
				out << "\t<0," << -_sections->_height/2.0 << ",0>, <0," << _sections->_height/2.0 << ",0>, " << _sections->_radius << " translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << "> inverse}\n";
				
				out << "\t\n";
				if (greaterThan180)
				{
					out << "\tclipped_by {\n";
					out << "\tunion {\n";
					out << "\tplane {-x, 0\n";
					out << "\t\trotate <0," << _sections->_angleMin << ",0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t }\n";
					out << "\tplane {x, 0\n";
					out << "\t\trotate <0," << _sections->_angleMax << ",0> translate <" << _sections->_strafeX << "," << _sections->_strafeY << "," << _sections->_strafeZ << ">\n";
					out << "\t }\n";
					out << "\t }\n";
					out << "\t }\n";
				}
			}
		
		}
	}
	
	out << "\n";
	out << "\tcutaway_textures\n";
	out << "} \n";
	
	file.close();

	QFile file2(outputPath + "camera.pov");
    if (!file2.open(QIODevice::WriteOnly | QIODevice::Text))
        return 0;

    QTextStream out2(&file2);
	out2 << "// POVRAY file created by MCNPXVisualizer\n";
	out2 << "\n";
	
	// Writes the camera object to file
	if (_cameraString == "")
	{
		out2 << "camera\n";
		out2 << "{   \n";   
		if (_useOrthographicProjection)
			out << "\torthographic\n";
		out2 << "\tlook_at <" << _camera->_camStrafeX << "," << _camera->_camStrafeY << "," << _camera->_camStrafeZ << ">\n";
		out2 << "\tlocation <" << _camera->_camPosX + _camera->_camStrafeX << "," << _camera->_camPosY + _camera->_camStrafeY << "," << _camera->_camPosZ + _camera->_camStrafeZ << "> \n";   
		out2 << "\tright  <-4/3,0,0>  \n"; 
		out2 << "\tangle 45.0\n";
		
		out2 << "}\n";
	}
	else
	{
		out2 << _cameraString;
	}

	file2.close();

	// Put the light object at the same position as the camera
	QFile file3(outputPath + "lights.pov");
    if (!file3.open(QIODevice::WriteOnly | QIODevice::Text))
        return 0;

    QTextStream out3(&file3);
	out3 << "// POVRAY file created by MCNPXVisualizer\n";
	out3 << "\n";
	if (_lightString == "")
	{
		out3 << "light_source\n";
		out3 << "{\n";
		  out3 << "\t<" << _camera->_camPosX << "," << _camera->_camPosY << "," << _camera->_camPosZ << "> \n";   
		  out3 << "\tcolor White\n";
		out3 << "}\n";
	}
	else
	{
		out3 << _lightString;
	}

	file3.close();
    return 1;
}
Exemplo n.º 11
0
bool CHistogram2D::compute() throw()
{
	typedef boost::shared_ptr<ImageType> ImagePtr;
	typedef typename ImageType::TDataType ValueType;
  ImagePtr imagePtr = static_pointer_cast<ImageType>( getInput() );
  ImagePtr classPtr = static_pointer_cast<ImageType>( getInput(1) );
  ImagePtr gradientPtr = static_pointer_cast<ImageType>( getInput(2) );
  if ( !checkInput<ImageType>( imagePtr, 2, 3 )
  	|| !checkInput<ImageType>( classPtr, 2, 3 )
  	|| !checkInput<ImageType>( gradientPtr, 2, 3 ) )
  {
    return false;
  }
	bModuleReady = true;
  deleteOldOutput();

  double dClassOneMean = 0.0;
  double dClassOneVariance = 0.0;
  vector<ValueType> classOneValuesVec;
  double dClassTwoMean = 0.0;
  double dClassTwoVariance = 0.0;
  vector<ValueType> classTwoValuesVec;

  uint uiClassOne = parameters.getUnsignedLong( "Class1" );
  uint uiClassTwo = parameters.getUnsignedLong( "Class2" );
  cerr << uiClassOne << " " << uiClassTwo << endl;
	// Calculate intensity mean and variance of the selected classes
	typename ImageType::iterator classIt = classPtr->begin();
	typename ImageType::iterator imageIt = imagePtr->begin();
	while( classIt != classPtr->end() )
	{
		if ( *classIt == static_cast<ValueType>( uiClassOne ) )
			classOneValuesVec.push_back( *imageIt );
		else if ( *classIt == static_cast<ValueType>( uiClassTwo ) )
			classTwoValuesVec.push_back( *imageIt );
		++classIt;
		++imageIt;
	}

  for_each( classOneValuesVec.begin(), classOneValuesVec.end(), dClassOneMean += _1 );
  dClassOneMean /= static_cast<double>( classOneValuesVec.size() );
  for_each( classOneValuesVec.begin(), classOneValuesVec.end(),
  	dClassOneVariance += ( _1 - dClassOneMean ) * ( _1 - dClassOneMean ) );
  dClassOneVariance /= static_cast<double>( classOneValuesVec.size() );
  dClassOneVariance = sqrt( dClassOneVariance );

	for_each( classTwoValuesVec.begin(), classTwoValuesVec.end(), dClassTwoMean += _1 );
  dClassTwoMean /= static_cast<double>( classTwoValuesVec.size() );
  for_each( classTwoValuesVec.begin(), classTwoValuesVec.end(),
  	dClassTwoVariance += ( _1 - dClassTwoMean ) * ( _1 - dClassTwoMean ) );
  dClassTwoVariance /= static_cast<double>( classTwoValuesVec.size() );
  dClassTwoVariance = sqrt( dClassTwoVariance );

cerr << " C1 (" << uiClassOne << ") : Mean " << dClassOneMean << " SD " << dClassOneVariance << endl
<< " C2 (" << uiClassTwo << ") : Mean " << dClassTwoMean << " SD " << dClassTwoVariance << endl;

	int rangeMin, rangeMax;
	rangeMin = static_cast<int>(
		std::min( dClassOneMean - dClassOneVariance, dClassTwoMean - dClassTwoVariance ) );
	rangeMax = static_cast<int>(
		std::max( dClassOneMean - dClassOneVariance, dClassTwoMean - dClassTwoVariance ) );

	ImagePtr tmp( new ImageType( *gradientPtr ) );
	classIt = imagePtr->begin();
	imageIt = tmp->begin();
	while( classIt != imagePtr->end() )
	{
		if ( *classIt < rangeMin || *classIt > rangeMax )
			*imageIt = 0;
		++classIt;
		++imageIt;
	}
	calculateHistogram( tmp );
	// Do a gaussian smoothing on the histogram
	// Compute gaussian mask
	double dSigma = parameters.getDouble( "HistoSmooth" );
cerr << "HistoSmooth " << dSigma << endl;
	int iMaskSize = static_cast<uint>( floor( 6.0 * dSigma + 0.5 ) );
	vector<double> dGaussMask;
	for( int i = -( iMaskSize / 2 ); i <= ( iMaskSize / 2 ); ++i )
	{
		double dExponential = ( 1.0 / sqrt( dSigma * dSigma * 2.0 * M_PI ) )
			* exp( static_cast<double>( -i * i ) / ( 2.0 * ( dSigma * dSigma ) ) );
		dGaussMask.push_back( dExponential );
	}

cerr << "Mask size " << iMaskSize << endl;

	// Shift histogram to attend smoothing
	vector<double> shiftedHisto;
	for( int i = 0; i < iMaskSize/2; ++i )
		shiftedHisto.push_back(0.0);
	for( uint i = 0; i < theHistogramVec[0].size(); ++i )
	{
		shiftedHisto.push_back( theHistogramVec[0][i] );
	}
	for( int i = 0; i <= iMaskSize/2; ++i )
		shiftedHisto.push_back(0.0);
   const uint uiShift = iMaskSize/2;
	vector<double> smoothedHisto( shiftedHisto.size() + uiShift);

	for( uint i = uiShift+1; i < shiftedHisto.size() - uiShift; ++i )
	{
		double smoothed = 0.0;
		for( int j = -(uiShift+1); j <= uiShift; ++j )
		{
			smoothed += shiftedHisto[i+j]*dGaussMask[j+uiShift+1];
		}
		smoothedHisto[i] = smoothed;
	}
   smoothedHisto = shiftedHisto;
	// Smooth
	// Reshift histogram
	// Determine the global maximum g1
	uint g1 = 0;
	double gv1 = 0.0;
	for( uint i = uiShift+1; i < smoothedHisto.size(); ++i )
	{
		if ( smoothedHisto[i] >= smoothedHisto[i-1] && smoothedHisto[i] >= gv1 )
		{
			gv1 = smoothedHisto[i]; g1 = i;
		}
		else if ( smoothedHisto[i] < smoothedHisto[i-1] )
			break;
	}
	// Determine next global maximum g2
/*	if ( g1 == 0 ) g1 = parameters.getUnsignedLong("Shift");*/
	uint t = g1 + parameters.getUnsignedLong("Shift");
	while( smoothedHisto[t] <= smoothedHisto[t-1] )
		++t;
	uint g2 = t+1;
	double gv2 = 0;
	for( uint i = t+1; i < smoothedHisto.size(); ++i )
	{
		if ( smoothedHisto[i] > smoothedHisto[i-1] && smoothedHisto[i] > gv2 )
		{
			gv2 = smoothedHisto[i]; g2 = i;
		}
		else if ( smoothedHisto[i] < smoothedHisto[i-1] )
			break;
	}
	if ( g1 == 0 )
	{
		g1 = g2;
		t = g1+parameters.getUnsignedLong("Shift");
		while( smoothedHisto[t] <= smoothedHisto[t-1] )
			++t;
		g2 = t+1;
		gv2 = 0;
		for( uint i = t+1; i < smoothedHisto.size(); ++i )
		{
			if ( smoothedHisto[i] > smoothedHisto[i-1] && smoothedHisto[i] > gv2 )
			{
				gv2 = smoothedHisto[i]; g2 = i;
			}
			else if ( smoothedHisto[i] < smoothedHisto[i-1] )
				break;
		}
	}
	if ( g2-g1 > (2 * parameters.getUnsignedLong("Shift")) )
		g2 = g1 + 2 * parameters.getUnsignedLong("Shift");
   g1--;
   g2--;
 	cerr << "Threshold values are " << g1 << " and " << g2;
	parameters.setUnsignedLong("T1", static_cast<ulong>( g1 * 0.33)-1 );
	parameters.setUnsignedLong("T2",
		static_cast<ulong>( std::max( g1 * 0.66, g1 + parameters.getDouble("Shift") + 1) ) - 1 );
ofstream file( "/home/hendrik/orig_histogram.data" );
	for( uint i = 0; i <= theHistogramVec[0].size(); ++i )
	{
		file << i << " " << theHistogramVec[0][i] << endl;
	}
	file.close();
ofstream file2( "/home/hendrik/shifted_histogram.data" );
	for( uint i = 0; i <= shiftedHisto.size(); ++i )
	{
		file2 << i << " " << shiftedHisto[i] << endl;
	}
	file2.close();
ofstream file3( "/home/hendrik/smoothed_histogram.data" );
	for( uint i = 0; i <= smoothedHisto.size(); ++i )
	{
		file3 << i << " " << smoothedHisto[i] << endl;
	}
	file3.close();
	return true;
}
Exemplo n.º 12
0
void TsDataAccessorFile::testGetFilesList()
{
  // Valid folders
  QTemporaryDir dir(QDir::tempPath() + QString::fromStdString("/2016"));

  QTemporaryDir subdir1(dir.path() + QString::fromStdString("/10"));
  QTemporaryDir subdir2(dir.path() + QString::fromStdString("/11"));
  QTemporaryDir subdir3(dir.path() + QString::fromStdString("/12"));

  QTemporaryDir subdir4(subdir1.path() + QString::fromStdString("/03"));
  QTemporaryDir subdir5(subdir3.path() + QString::fromStdString("/11"));

  QTemporaryDir subdir6(subdir2.path() + QString::fromStdString("/final"));
  QTemporaryDir subdir7(subdir4.path() + QString::fromStdString("/final"));

  QTemporaryDir subdir8(subdir5.path() + QString::fromStdString("/final"));

  // Invalid folders

  QTemporaryDir subdir9(dir.path() + QString::fromStdString("/03"));
  QTemporaryDir subdir10(subdir9.path() + QString::fromStdString("/aa"));

  QTemporaryDir dir3(QDir::tempPath() + QString::fromStdString("/2020"));
  QTemporaryDir dir4(QDir::tempPath() + QString::fromStdString("/folder"));

  terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider();
  terrama2::core::DataProviderPtr dataProviderPtr(dataProvider);

  terrama2::core::DataSeries* dataSeries = new terrama2::core::DataSeries();
  terrama2::core::DataSeriesPtr dataSeriesPtr(dataSeries);

  TestDataAccessorFile da(dataProviderPtr, dataSeriesPtr);

  std::vector<std::string> baseDirList;

  baseDirList.push_back(QDir::tempPath().toStdString());

  QTemporaryFile file1(subdir7.path() + QString::fromStdString("/file_2017_06_01_14:40_XXXXXX.file"));
  QTemporaryFile file2(subdir7.path() + QString::fromStdString("/file_2017_06_01_14:41_XXXXXX.file"));
  QTemporaryFile file3(subdir8.path() + QString::fromStdString("/file_2017_06_02_12:00_XXXXXX.file"));

  file1.open();
  file2.open();
  file3.open();

  {
    std::string fileMask = "file_%YYYY_%MM_%DD_%hh:%mm_*.file";
    std::string foldermask = "/%YYYY*/%MM*/%DD*/final*/";

    terrama2::core::Filter filter;
    std::string timezone = "03";
    auto remover = std::make_shared<terrama2::core::FileRemover>();

    QFileInfoList fileList;

    for(auto& baseDir : baseDirList)
      fileList.append(da.getFilesList(baseDir, fileMask, foldermask, filter, timezone, remover));

    if(fileList.size() < 3)
      QFAIL("Wrong number of folders matched!");
  }

}
Exemplo n.º 13
0
void overlay_plots(const string& fFile0, const string& fFile1, const string& fFile2, const string& fFile3, const string& fFile4, const string& fPlot0, const string& fPlot1, const string& fPlot2, const string& fPlot3, const string& fPlot4, const double fXmin, const double fXmax, const string& fXAxisLabel, const string& fName, const int logY, const int rescale, const double cutValue0, const double cutValue1, const string& label) {
  
  TH1F *h[5];
 
  TFile file0(fFile0.c_str());
  h[0] = (TH1F*)file0.Get(fPlot0.c_str()); 

  TFile file1(fFile1.c_str());
  h[1] = (TH1F*)file1.Get(fPlot1.c_str()); 

  TFile file2(fFile2.c_str());
  h[2] = (TH1F*)file2.Get(fPlot2.c_str()); 

  TFile file3(fFile3.c_str());
  h[3] = (TH1F*)file3.Get(fPlot3.c_str()); 
   
  TFile file4(fFile4.c_str());
  h[4] = (TH1F*)file4.Get(fPlot4.c_str()); 

  h[0]->Rebin(1);
  h[1]->Rebin(1);
  h[2]->Rebin(1);
  h[3]->Rebin(1);
  h[4]->Rebin(1);

  //    double ymax = (h[0]->GetMaximum()>h[1]->GetMaximum()) ? h[0]->GetMaximum() : h[1]->GetMaximum();
   
  h[0]->GetXaxis()->SetTitle(fXAxisLabel.c_str());
  h[0]->GetXaxis()->SetRangeUser(fXmin,fXmax);
  //    h[0]->GetYaxis()->SetRangeUser(0.5,1.25*ymax);

  h[0]->SetTitleOffset(1.2,"X");
  h[0]->GetXaxis()->SetTitleSize(0.04);
  h[0]->GetYaxis()->SetTitleSize(0.04);

  if(rescale) 
    {  

       if (h[0]->Integral()!=0)
	h[0]->Scale(1/h[0]->Integral());

       //----------------------------       
//        if (h[1]->Integral()!=0)
// 	 h[1]->Scale(1/h[1]->Integral());

//        if (h[2]->Integral()!=0)
// 	 h[2]->Scale(1/h[2]->Integral());
       //----------------------------       

       if (h[3]->Integral()!=0)
	 h[3]->Scale(1/h[3]->Integral());
 
       if (h[4]->Integral()!=0)
	 h[4]->Scale(1/h[4]->Integral());

    }

  TCanvas *c = new TCanvas("c","",800,800);
  c->cd();
  c->Range(-0.4638998,-0.01028103,4.210331,0.09111118);
  c->SetRightMargin(0.2286432);

  h[0]->SetLineWidth(3);
  //    h[0]->SetLineStyle(4);
  h[0]->SetLineColor(kRed);
  h[0]->SetFillColor(kRed);
  h[0]->SetFillStyle(3002);
  //    h[0]->SetMarkerSize(.6);
  //    h[0]->SetMarkerStyle(26);
  //    h[0]->SetMarkerColor(kRed);
  h[0]->Draw("hist");

  h[1]->SetLineWidth(3);
  //    h[1]->SetLineStyle(3);
  h[1]->SetLineColor(kBlack);
  //    h[1]->SetMarkerSize(.8);
  h[1]->SetMarkerStyle(20);
  h[1]->SetMarkerColor(kBlack);
  //----------------------------       
  //h[1]->Draw("sameshist");
  //----------------------------       

  h[2]->SetLineWidth(3);
  h[2]->SetLineStyle(3);
  h[2]->SetLineColor(kBlack);
  //    h[1]->SetMarkerSize(.8);
  h[2]->SetMarkerStyle(20);
  h[2]->SetMarkerColor(kBlack);
  //----------------------------       
  //h[2]->Draw("sameshist");
  //----------------------------       

  h[3]->SetLineWidth(3);
  h[3]->SetLineStyle(4);
  h[3]->SetLineColor(kBlack);
  //    h[1]->SetMarkerSize(.8);
  h[3]->SetMarkerStyle(20);
  h[3]->SetMarkerColor(kBlack);
  h[3]->Draw("sameshist");

  h[4]->SetLineWidth(3);
  h[4]->SetLineStyle(5);
  h[4]->SetLineColor(kBlack);
  //    h[1]->SetMarkerSize(.8);
  h[4]->SetMarkerStyle(20);
  h[4]->SetMarkerColor(kBlack);
  h[4]->Draw("sameshist");
    
  double maximum = 0;
  if( h[0]->GetMaximum() > maximum )
    maximum = h[0]->GetMaximum() ;
  //-------------------------------
  //   if( h[1]->GetMaximum() > maximum )
  //     maximum = h[1]->GetMaximum();
  //   if( h[2]->GetMaximum() > maximum )
  //     maximum = h[2]->GetMaximum();
  //-------------------------------
  if( h[3]->GetMaximum() > maximum )
    maximum = h[3]->GetMaximum();
  if( h[4]->GetMaximum() > maximum )
    maximum = h[4]->GetMaximum();
  
  h[0]->GetYaxis()->SetRangeUser(0,maximum+maximum*0.1);

  //update the current pad, needed to modify statboxes
  gPad->Update();
   
  // get the statboxes and set color
  TPaveStats *st1 = (TPaveStats*)h[0]->GetListOfFunctions()->FindObject("stats");
  st1->SetTextColor(kRed);
    st1->SetLineColor(kRed);
  st1->SetOptStat(1111111);
  //------------------------------
  //   TPaveStats *st2 = (TPaveStats*)h[1]->GetListOfFunctions()->FindObject("stats");
  //   st2->SetTextColor(kBlack);
  //   st2->SetLineColor(kBlack);
  //   st2->SetOptStat(1111111);
  //   TPaveStats *st3 = (TPaveStats*)h[2]->GetListOfFunctions()->FindObject("stats");
  //   st3->SetTextColor(kBlack);
  //   st3->SetLineColor(kBlack);
  //   st3->SetOptStat(1111111);
  //------------------------------
  TPaveStats *st4 = (TPaveStats*)h[3]->GetListOfFunctions()->FindObject("stats");
  st4->SetTextColor(kBlack);
  st4->SetLineColor(kBlack);
  st4->SetOptStat(1111111);
  TPaveStats *st5 = (TPaveStats*)h[4]->GetListOfFunctions()->FindObject("stats");
  st5->SetTextColor(kBlack);
  st5->SetLineColor(kBlack);
  st5->SetOptStat(1111111);


  // set the position of the statboxes
  double x1 = st1->GetX1NDC();
  double y1 = st1->GetY1NDC();
  double x2 = st1->GetX2NDC();
  double y2 = st1->GetY2NDC();
  //double xx = x2-x1;
  double yy = y2-y1;
  //--------------------------
  //   st2->SetX1NDC(x1);
  //   st2->SetY1NDC(y1-yy);
  //   st2->SetX2NDC(x2);
  //   st2->SetY2NDC(y1);
  //   st3->SetX1NDC(x1);
  //   st3->SetY1NDC(y1-yy-yy);
  //   st3->SetX2NDC(x2);
  //   st3->SetY2NDC(y1-yy);
  //--------------------------
  st4->SetX1NDC(x1);
  st4->SetY1NDC(y1-yy-yy-yy);
  st4->SetX2NDC(x2);
  st4->SetY2NDC(y1-yy-yy);
  st5->SetX1NDC(x1);
  st5->SetY1NDC(y1-yy-yy-yy-yy);
  st5->SetX2NDC(x2);
  st5->SetY2NDC(y1-yy-yy-yy);
  gPad->Modified();
   
  TLegend *legend = new TLegend(.4,.91,.75,.99);
  legend->SetBorderSize(1);
  legend->SetFillColor(0);
  //    legend->SetFillStyle(0);
  legend->AddEntry(h[0],"SM background","l");
  //--------------------------
  //   legend->AddEntry(h[1],"Axigluon + W , M = 150 GeV","l");
  //   legend->AddEntry(h[2],"Axigluon + W , M = 500 GeV","l");
  //--------------------------
  legend->AddEntry(h[3],"Axigluon + W , M = 1000 GeV","l");
  legend->AddEntry(h[4],"Axigluon + W , M = 1500 GeV","l");
  legend->Draw();

  //   TLine line0(cutValue0,0,cutValue0,h[1]->GetMaximum());
  //   line0.SetLineColor(kRed);
  //   line0.Draw("same");
  
  //   TLine line1(cutValue1,0,cutValue1,h[1]->GetMaximum());
  //   line1.SetLineColor(kRed);
  //   line1.Draw("same");
   
  TLatex l;
  l.SetTextAlign(12);
  l.SetTextSize(0.04);
  l.SetTextFont(62);
  l.SetNDC();
  l.DrawLatex(0.6,0.8,label.c_str());

  if(logY==1)
    c->SetLogy();
   
  string fileName = fName;
  c->SaveAs(fileName.c_str());
   
  delete legend;
  delete c;
}
Exemplo n.º 14
0
STKUNIT_UNIT_TEST(nodeRegistry, test_parallel_1_0)
{
  EXCEPTWATCH;
  MPI_Barrier( MPI_COMM_WORLD );

  // start_demo_nodeRegistry_test_parallel_1

  percept::PerceptMesh eMesh(3u);

  unsigned p_size = eMesh.get_parallel_size();
  unsigned p_rank = eMesh.get_rank();
  Util::setRank(eMesh.get_rank());

  eMesh.new_mesh(percept::GMeshSpec(std::string("1x1x")+toString(p_size)+std::string("|bbox:0,0,0,1,1,1")));

  // prepare for adding some quadratic elements
  mesh::Part& block_hex_20 = eMesh.get_fem_meta_data()->declare_part("block_hex_20", eMesh.element_rank());
  /// set cell topology for the part block_hex_20
  mesh::fem::set_cell_topology< shards::Hexahedron<20>  >( block_hex_20 );
  stk_classic::io::put_io_part_attribute(block_hex_20);

  eMesh.commit();
  eMesh.print_info();
  eMesh.save_as("./cube1x1x2_hex-20-orig.e");

  mesh::Part* block_hex_8 = const_cast<mesh::Part *>(eMesh.getPart("block_1"));

  NodeRegistry nodeRegistry(eMesh);
  nodeRegistry.initialize();

  if (p_size <= 2)
  {
    // pick an element on the processor boundary
    unsigned elem_num_local = 1;
    unsigned elem_num_ghost = 2;
    if (p_size == 1)
      elem_num_ghost = 1;

    stk_classic::mesh::Entity* element_local_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_local);
    stk_classic::mesh::Entity* element_ghost_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_ghost);
    if (p_rank == 1)
    {
      element_local_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_ghost);
      element_ghost_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_local);
    }

    dw() << "P["<<p_rank<<"] elem_num_local = " << elem_num_local << DWENDL;
    dw() << "P["<<p_rank<<"] elem_num_ghost = " << elem_num_ghost << DWENDL;

    stk_classic::mesh::Entity& element_local = *element_local_p;
    stk_classic::mesh::Entity& element_ghost = *element_ghost_p;

    std::cout << "P["<<p_rank<<"] element_local = " << element_local << std::endl;
    std::cout << "P["<<p_rank<<"] element_ghost = " << element_ghost << std::endl;

    // choose edges to be used for new node locations (i.e., this would model a serendipity-like element with only edge Lagrange nodes)
    stk_classic::mesh::EntityRank stk_mesh_Edge = 1;
    NeededEntityType needed_entity_rank( stk_mesh_Edge, 1u);
    std::vector<NeededEntityType> needed_entity_ranks(1, needed_entity_rank);

    /*
     * 1st of three steps to create and associate new nodes - register need for new nodes, then check if node is remote, then get
     *   from remote proc if necessary; finally, the local node database is ready to be queried
     *
     * The pattern is to begin the step, loop over all elements (including ghosts) and invoke the local operation
     * The method doForAllSubEntities is a utility for performing the operation on all the sub entities.
     * If more granularity is desired, the member functions can be invoked directly for a particular sub-entity.
     */
    nodeRegistry.beginRegistration();
    nodeRegistry.doForAllSubEntities(&NodeRegistry::registerNeedNewNode, element_local, needed_entity_ranks);
    nodeRegistry.doForAllSubEntities(&NodeRegistry::registerNeedNewNode, element_ghost, needed_entity_ranks);
    nodeRegistry.endRegistration();

    std::cout << "P["<<p_rank<<"] nodeRegistry size  = " << nodeRegistry.total_size() << std::endl;
    std::cout << "P["<<p_rank<<"] nodeRegistry lsize = " << nodeRegistry.local_size() << std::endl;

    dw() << "P["<<p_rank<<"] nodeRegistry size       = " << nodeRegistry.total_size() << DWENDL;
    dw() << "P["<<p_rank<<"] nodeRegistry lsize      = " << nodeRegistry.local_size() << DWENDL;

    // could do local create of elements here
    nodeRegistry.beginLocalMeshMods();
    nodeRegistry.endLocalMeshMods();

    // check if the newly requested nodes are local or remote
    nodeRegistry.beginCheckForRemote();
    nodeRegistry.doForAllSubEntities(&NodeRegistry::checkForRemote, element_local, needed_entity_ranks);
    nodeRegistry.doForAllSubEntities(&NodeRegistry::checkForRemote, element_ghost, needed_entity_ranks);
    nodeRegistry.endCheckForRemote();

    // get the new nodes from other procs if they are nonlocal
    nodeRegistry.beginGetFromRemote();
    nodeRegistry.doForAllSubEntities(&NodeRegistry::getFromRemote, element_local, needed_entity_ranks);
    nodeRegistry.doForAllSubEntities(&NodeRegistry::getFromRemote, element_ghost, needed_entity_ranks);
    nodeRegistry.endGetFromRemote();

    // now we can get the new node's id and entity
    unsigned iSubDimOrd = 4u;
    if (p_rank)
    {
      iSubDimOrd = 0u;
    }
    NodeIdsOnSubDimEntityType& nodeIds_onSE_0 = *( nodeRegistry.getNewNodesOnSubDimEntity(element_local, needed_entity_rank.first, iSubDimOrd));
    stk_classic::mesh::Entity*  node_0   = eMesh.get_bulk_data()->get_entity(stk_classic::mesh::fem::FEMMetaData::NODE_RANK, nodeIds_onSE_0[0]->identifier());

    // should be the same node on each proc
    std::cout << "P[" << p_rank << "] nodeId_0 = " << nodeIds_onSE_0 << " node_0= " << node_0 << std::endl;

    // end_demo

#if STK_ADAPT_HAVE_YAML_CPP
    if (p_size == 1)
      {
        if (1) {
          YAML::Emitter out;
          out << YAML::Anchor("NodeRegistry::map");
          out << YAML::BeginMap;
          out << YAML::Key << YAML::BeginSeq << 1 << 2 << YAML::EndSeq << YAML::Value << YAML::BeginSeq << -1 << -2 << YAML::EndSeq;
          out << YAML::Key << 1;
          out << YAML::Value << 2;
          out << YAML::Key << 3;
          out << YAML::Value << 4;
          out << YAML::EndMap;
          //std::cout << "out=\n" << out.c_str() << "\n=out" << std::endl;
          std::string expected_result = "&NodeRegistry::map\n?\n  - 1\n  - 2\n:\n  - -1\n  - -2\n1: 2\n3: 4";
          //std::cout << "out2=\n" << expected_result << std::endl;
          STKUNIT_EXPECT_TRUE(expected_result == std::string(out.c_str()));
        }

        YAML::Emitter yaml;
        std::cout << "\nnodeRegistry.serialize_write(yaml)" << std::endl;
        SerializeNodeRegistry::serialize_write(nodeRegistry, yaml, 0);
        //std::cout << yaml.c_str() << std::endl;
        if (!yaml.good())
          {
            std::cout << "Emitter error: " << yaml.good() << " " <<yaml.GetLastError() << "\n";
            STKUNIT_EXPECT_TRUE(false);
          }
        std::ofstream file1("out.yaml");
        file1 << yaml.c_str();
        file1.close();
        std::ifstream file2("out.yaml");
        YAML::Parser parser(file2);
        YAML::Node doc;

        try {
          while(parser.GetNextDocument(doc)) {
            std::cout << "\n read doc.Type() = " << doc.Type() << " doc.Tag()= " << doc.Tag() << " doc.size= " << doc.size() << std::endl;
            if (doc.Type() == YAML::NodeType::Map)
              {
                for(YAML::Iterator it=doc.begin();it!=doc.end();++it) {
                  int key, value;
                  std::cout << "read it.first().Type() = " << it.first().Type() << " it.first().Tag()= " << it.first().Tag() << std::endl;
                  std::cout << "read it.second().Type() = " << it.second().Type() << " it.second().Tag()= " << it.second().Tag() << std::endl;
                  const YAML::Node& keySeq = it.first();
                  for(YAML::Iterator itk=keySeq.begin();itk!=keySeq.end();++itk) {
                    *itk >> key;
                    std::cout << "read key= " << key << std::endl;
                  }
              
                  const YAML::Node& valSeq = it.second();
                  for(YAML::Iterator itv=valSeq.begin();itv!=valSeq.end();++itv) {
                    *itv >> value;
                    std::cout << "read value= " << value << std::endl;
                  }
              
                }
              }
          }
        }
        catch(YAML::ParserException& e) {
          std::cout << e.what() << "\n";
          STKUNIT_EXPECT_TRUE(false);
        }

        file2.close();
        std::ifstream file3("out.yaml");
        NodeRegistry nrNew(eMesh);
        SerializeNodeRegistry::serialize_read(nrNew, file3);
        YAML::Emitter yaml3;
        std::cout << "\nnrNew.serialize_write(yaml3)" << std::endl;
        SerializeNodeRegistry::serialize_write(nrNew, yaml3, 0);
        std::cout << yaml3.c_str() << std::endl;
        
        //exit(1);
      }
#endif
    // start_demo_nodeRegistry_test_parallel_1_quadratic_elem

    // change element to be a serendipity quadratic element
    eMesh.get_bulk_data()->modification_begin();

    //getCellTopologyData< shards::Node  >()
    const CellTopologyData *const cell_topo_data =stk_classic::percept::PerceptMesh::get_cell_topology(block_hex_20);
    CellTopology cell_topo(cell_topo_data);

    for (unsigned isd = 0; isd < 12; isd++)
    {
      nodeRegistry.makeCentroidCoords(element_local, needed_entity_rank.first, isd);
      NodeIdsOnSubDimEntityType& nodeIds_onSE_0_loc = *( nodeRegistry.getNewNodesOnSubDimEntity(element_local, needed_entity_rank.first, isd));

      stk_classic::mesh::Entity*  node   = eMesh.get_bulk_data()->get_entity(stk_classic::mesh::fem::FEMMetaData::NODE_RANK, nodeIds_onSE_0_loc[0]->identifier());

      unsigned edge_ord = 8u + isd;
      //unsigned n_edge_ord = cell_topo_data->edge[isd].topology->node_count;
      //std::cout << "n_edge_ord = " << n_edge_ord << std::endl;
      edge_ord = cell_topo_data->edge[isd].node[2];
      eMesh.get_bulk_data()->declare_relation(element_local, *node, edge_ord);
    }

    std::vector<stk_classic::mesh::Part*> add_parts(1, &block_hex_20);
    std::vector<stk_classic::mesh::Part*> remove_parts(1, block_hex_8);
    eMesh.get_bulk_data()->change_entity_parts( element_local, add_parts, remove_parts );

    eMesh.get_bulk_data()->modification_end();
    eMesh.print_info("After quadratic");

    eMesh.save_as("./cube1x1x2_hex-20.e");
    //exit(1);
  }
Exemplo n.º 15
0
int main( int argc, char ** argv )
{
	ros::init( argc, argv, "sonar_driver" );
	if (argc < 3) {
		ROS_ERROR("sonar_driver usage: sudo rosrun sonar_driver sonar_driver PORT BITRATE\n");
		//port 0, bitrate 40000kHz
  		return 1;
  	}

	// Initialize Cheetah parameters
	port = atoi(argv[1]);
	bitrate = atoi(argv[2]); //kHz

	// Open the device
	handle = ch_open(port);
	if (handle <= 0) {
		ROS_ERROR("Unable to open Cheetah device on port %d (Error code = %d: %s)", port, handle, ch_status_string(handle));
	  	exit(1);
	}
	ROS_INFO("Opened Cheetah device on port %d", port);
	ROS_INFO("Host interface is %s", (ch_host_ifce_speed(handle)) ? "high speed" : "full speed");

	// Configure SPI subsystem
	ch_spi_configure(handle, CH_SPI_POL_RISING_FALLING, CH_SPI_PHASE_SETUP_SAMPLE, CH_SPI_BITORDER_MSB, 0x0);
	ROS_INFO("SPI configuration set to mode %d, %s shift, SS[2:0] active low", mode, "MSB");

	// Power the target using the Cheetah's 5V power supply
	ch_target_power(handle, CH_TARGET_POWER_ON);
	ch_sleep_ms(100);

	// Set the bitrate
	bitrate = ch_spi_bitrate(handle, bitrate);
	ROS_INFO("Bitrate set to %d kHz", bitrate);

  
	// Make a simple queue to assert OE
	ch_spi_queue_clear(handle);
	ch_spi_queue_oe(handle, 1);
	ch_spi_batch_shift(handle, 0, 0);

	// Queue the batch
	ROS_INFO("Beginning to queue SPI packets...");
	ch_spi_queue_clear(handle);
	for (int i = 0; i < DATA_BLOCK_SIZE; ++i) {
		// Convert Slave 1
	 	ch_spi_queue_ss(handle, 0xF);
	 	ch_spi_queue_array(handle, 2, data_out);
	 	ch_spi_queue_ss(handle, 0xE);

	 	// Convert Slave 2
	 	ch_spi_queue_ss(handle, 0xF);
	 	ch_spi_queue_array(handle, 2, data_out);
	 	ch_spi_queue_ss(handle, 0xD);

	 	// Convert Slave 3
	 	ch_spi_queue_ss(handle, 0xF);
	 	ch_spi_queue_array(handle, 2, data_out);
	 	ch_spi_queue_ss(handle, 0xB);
	}
	ROS_INFO("Finished queueing packets\n");

	// Open output filestreams
	std::ofstream file1 ("1_adc_samples.txt");
	std::ofstream file2 ("2_adc_samples.txt");
	std::ofstream file3 ("3_adc_samples.txt");

	int batch_cnt = 1; //count number of sample batches
	double elapsed;
	s64    start;

	while( ros::ok() ) {
		// Submit the batch and collect data
		ROS_INFO("Collecting data from batch %d...", batch_cnt);
		start = _timeMillis();
   		ch_spi_async_submit(handle);
    		ret = ch_spi_async_collect(handle, TX_LENGTH, data_in);
		elapsed = ((double)(_timeMillis() - start)) / 1000;
		ROS_INFO("collected %d bytes from batch #%04d in %.4lf seconds\n", ret, batch_cnt, elapsed);
		if (ret < 0)  ROS_INFO("status error: %s\n", ch_status_string(ret));
		batch_cnt++;

		// Process raw data for the 12-bit ADC's, and write data to text files
    		int data_idx = 0;
		if ( file1.is_open() && file2.is_open() && file3.is_open() ) {
    			for (int j = 0; j < TX_LENGTH; j += 6) {
    				// SS3 Data
		    		input = (data_in[j] << 8) + data_in[j+1];
		    		valid_data_point = (input & 0x3ffc) >> 2;
		    		if(valid_data_point >= 0x0800)	valid_data_point = valid_data_point - 0x1000; //convert 2's comp to signed
		    		data3[data_idx] = valid_data_point;
				file3 << data3[data_idx] << ",";
	
		    		// SS1 Data
		    		input = (data_in[j+2] << 8) + data_in[j+3];
		    		valid_data_point = (input & 0x3ffc) >> 2;
		    		if(valid_data_point >= 0x0800)	valid_data_point = valid_data_point - 0x1000;
		    		data1[data_idx] = valid_data_point;
				file1 << data1[data_idx] << ",";
	
		    		// SS2 Data
		    		input = (data_in[j+4] << 8) + data_in[j+5];
		    		valid_data_point = (input & 0x3ffc) >> 2;
		    		if(valid_data_point >= 0x0800)	valid_data_point = valid_data_point - 0x1000;
		    		data2[data_idx] = valid_data_point;
				file2 << data2[data_idx] << ",";
		    		++data_idx;
    			}
		}
		else std::cout << "Error opening output filestream!" << std::endl;
	}
CRemoteControlRepeaterPanel::CRemoteControlRepeaterPanel(wxWindow* parent, int id, const wxString& callsign) :
wxPanel(parent, id),
m_callsign(callsign),
m_list(NULL),
m_reflector(NULL),
m_channel(NULL),
m_reconnect(NULL)
{
	wxBoxSizer* sizer1 = new wxBoxSizer(wxHORIZONTAL);

	m_list = new wxListCtrl(this, -1, wxDefaultPosition, wxSize(LIST_WIDTH, LIST_HEIGHT), wxLC_REPORT | wxLC_SINGLE_SEL);
	m_list->InsertColumn(0L, _("Callsign"));
	m_list->SetColumnWidth(0L, CALLSIGN_WIDTH);
	m_list->InsertColumn(1L, _("Protocol"));
	m_list->SetColumnWidth(1L, PROTOCOL_WIDTH);
	m_list->InsertColumn(2L, _("Direction"));
	m_list->SetColumnWidth(2L, DIRECTION_WIDTH);
	m_list->InsertColumn(3L, _("Type"));
	m_list->SetColumnWidth(3L, TYPE_WIDTH);
	m_list->InsertColumn(4L, _("State"));
	m_list->SetColumnWidth(4L, STATE_WIDTH);
	sizer1->Add(m_list, 0, wxTOP | wxBOTTOM | wxLEFT | wxEXPAND, BORDER_SIZE);

	wxBoxSizer* sizer2 = new wxBoxSizer(wxVERTICAL);

	wxButton* refreshButton = new wxButton(this, Button_Refresh, _("Refresh"), wxDefaultPosition, wxSize(BUTTON_WIDTH, -1));
	sizer2->Add(refreshButton, 0, wxALL, BORDER_SIZE);

	wxStaticText* dummy1Label = new wxStaticText(this, -1, wxEmptyString);
	sizer2->Add(dummy1Label, 0, wxALL, BORDER_SIZE);

	wxStaticText* dummy2Label = new wxStaticText(this, -1, wxEmptyString);
	sizer2->Add(dummy2Label, 0, wxALL, BORDER_SIZE);

	wxBoxSizer* sizer3 = new wxBoxSizer(wxHORIZONTAL);

	m_reflector = new wxChoice(this, -1, wxDefaultPosition, wxSize(REFLECTOR_WIDTH, -1));
	m_reflector->Append(_("None"));

	wxFileName fileName1(wxFileName::GetHomeDir(), DPLUS_HOSTS_FILE_NAME);
	if (!fileName1.IsFileReadable()) {
#if defined(__WINDOWS__)
		fileName1.Assign(::wxGetCwd(), DPLUS_HOSTS_FILE_NAME);
#else
		fileName1.Assign(wxT(DATA_DIR), DPLUS_HOSTS_FILE_NAME);
#endif
	}

	CHostFile file1(fileName1.GetFullPath(), false);

	for (unsigned int i = 0U; i < file1.getCount(); i++)
		m_reflector->Append(file1.getName(i));

	wxFileName fileName2(wxFileName::GetHomeDir(), DEXTRA_HOSTS_FILE_NAME);
	if (!fileName2.IsFileReadable()) {
#if defined(__WINDOWS__)
		fileName2.Assign(::wxGetCwd(), DEXTRA_HOSTS_FILE_NAME);
#else
		fileName2.Assign(wxT(DATA_DIR), DEXTRA_HOSTS_FILE_NAME);
#endif
	}

	CHostFile file2(fileName2.GetFullPath(), false);

	for (unsigned int i = 0U; i < file2.getCount(); i++)
		m_reflector->Append(file2.getName(i));

	wxFileName fileName3(wxFileName::GetHomeDir(), DCS_HOSTS_FILE_NAME);
	if (!fileName3.IsFileReadable()) {
#if defined(__WINDOWS__)
		fileName3.Assign(::wxGetCwd(), DCS_HOSTS_FILE_NAME);
#else
		fileName3.Assign(wxT(DATA_DIR), DCS_HOSTS_FILE_NAME);
#endif
	}

	CHostFile file3(fileName3.GetFullPath(), false);

	for (unsigned int i = 0U; i < file3.getCount(); i++)
		m_reflector->Append(file3.getName(i));

	sizer3->Add(m_reflector, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	m_reflector->SetSelection(0);

	m_channel = new wxChoice(this, -1, wxDefaultPosition, wxSize(CHANNEL_WIDTH, -1));
	m_channel->Append(wxT("A"));
	m_channel->Append(wxT("B"));
	m_channel->Append(wxT("C"));
	m_channel->Append(wxT("D"));
	m_channel->Append(wxT("E"));
	m_channel->Append(wxT("F"));
	m_channel->Append(wxT("G"));
	m_channel->Append(wxT("H"));
	m_channel->Append(wxT("I"));
	m_channel->Append(wxT("J"));
	m_channel->Append(wxT("K"));
	m_channel->Append(wxT("L"));
	m_channel->Append(wxT("M"));
	m_channel->Append(wxT("N"));
	m_channel->Append(wxT("O"));
	m_channel->Append(wxT("P"));
	m_channel->Append(wxT("Q"));
	m_channel->Append(wxT("R"));
	m_channel->Append(wxT("S"));
	m_channel->Append(wxT("T"));
	m_channel->Append(wxT("U"));
	m_channel->Append(wxT("V"));
	m_channel->Append(wxT("W"));
	m_channel->Append(wxT("X"));
	m_channel->Append(wxT("Y"));
	m_channel->Append(wxT("Z"));
	sizer3->Add(m_channel, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	m_channel->SetSelection(0);

	sizer2->Add(sizer3);

	m_reconnect = new wxChoice(this, -1, wxDefaultPosition, wxSize(RECONNECT_WIDTH, -1));
	m_reconnect->Append(_("Never"));
	m_reconnect->Append(_("Fixed"));
	m_reconnect->Append(_("5 minutes"));
	m_reconnect->Append(_("10 minutes"));
	m_reconnect->Append(_("15 minutes"));
	m_reconnect->Append(_("20 minutes"));
	m_reconnect->Append(_("25 minutes"));
	m_reconnect->Append(_("30 minutes"));
	m_reconnect->Append(_("60 minutes"));
	m_reconnect->Append(_("90 minutes"));
	m_reconnect->Append(_("120 minutes"));
	m_reconnect->Append(_("180 minutes"));
	sizer2->Add(m_reconnect, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	m_reconnect->SetSelection(0);

	wxStaticText* dummy3Label = new wxStaticText(this, -1, wxEmptyString);
	sizer2->Add(dummy3Label, 0, wxALL, BORDER_SIZE);

	wxButton* linkButton = new wxButton(this, Button_Link, _("Link"), wxDefaultPosition, wxSize(BUTTON_WIDTH, -1));
	sizer2->Add(linkButton, 0, wxALL, BORDER_SIZE);

	wxButton* unlinkButton = new wxButton(this, Button_Unlink, _("Unlink"), wxDefaultPosition, wxSize(BUTTON_WIDTH, -1));
	sizer2->Add(unlinkButton, 0, wxALL, BORDER_SIZE);

	sizer1->Add(sizer2);

	SetAutoLayout(true);

	SetSizer(sizer1);
}
Exemplo n.º 17
0
uninstallDialog::uninstallDialog(const QString &port, const QString &daddr,QWidget *parent) :
   QDialog(parent),m_port(port),m_daddr(daddr),
    ui(new Ui::uninstallDialog)




{



    if (ost == 1)
       {
        tmpdir = "./";
         adb2 = tmpdir+"adb.exe";
       }


     if (ost == 2)
       {
         tmpdir = QCoreApplication::applicationDirPath();
         tmpdir = tmpdir+"/adbfiles/";
        adb2 = tmpdir+"adb.osx";
       }

     if (ost == 0)
       {
         tmpdir = QCoreApplication::applicationDirPath();
         tmpdir = tmpdir+"/adbfiles/";
         adb2 = tmpdir+"adb.linux";
       }


    ui->setupUi(this);

tmpstr = tmpdir+"tempfl";
QString c1;
   QProcess packages;
   packages.setProcessChannelMode(QProcess::MergedChannels);

   if (m_port.isEmpty())
   argument = " -s "+m_daddr+ " shell pm list packages";
   else
   argument = " -s "+m_daddr+":"+m_port+" shell pm list packages";

    cstr = adb2 + argument;


   // QMessageBox::critical(0, "",cstr,QMessageBox::Cancel);

   packages.start(cstr);
   packages.waitForFinished(-1);
   commstr=packages.readAll();



                QFile file2(tmpstr);

                  if(!file2.open(QFile::WriteOnly |
                                QFile::Text))
                  {
                      QMessageBox::critical(this,"","Error creating file!");
                      return;
                  }


                  QTextStream out(&file2);
                  out  << commstr << endl;

                  file2.flush();
                  file2.close();



     QFile file3(tmpstr);
       if (!file3.open(QIODevice::ReadOnly | QIODevice::Text))
         {QMessageBox::critical(this,"","Error reading file!");
            return; }

       QTextStream in(&file3);
        while (!in.atEnd())
         {


          fline = in.readLine();

            if (!fline.isEmpty())
             {

            fline.remove(0,8);


                     ui->unlistWidget->addItem(fline);

           }

        }

          file3.close();

       QFile::remove(tmpstr);
}
Exemplo n.º 18
0
void FileManager::copyFile()
{
	string source, destination, content;

	FileReader emp(source);
	do
	{
		cout << "Enter the name of the source file: ";
		cin >> source;
		source.append(".txt");
		if (FileManager::fileExist(source))
		{
			cout << "This file does not exist. Try a file that exist." << endl;
		}
		if (emp.is_empty(source) && !FileManager::fileExist(source))
		{
			cout << "\aThis file is empty. Try a file with something on it.\n";
		}
	} while (emp.is_empty(source));


	fstream file(source);
	
	while (!file.eof())
	{
		getline(file, content, '~');
	}

	if (file.fail())
	{
		cout << "\aFile with the name of " << source << " does not exist" << endl;
	}
	else
	{
		do
		{
			cout << "Enter the name of the destination file: ";
			cin >> destination;
			destination.append(".txt");
			if (FileManager::toUpper(destination) == FileManager::toUpper(source))
			{
				cout << "\aYou cant clone a file to itself. Try Again. \n\n Destination File: ";
				cin >> destination;
				destination.append(".txt");
			}
		} while (FileManager::toUpper(destination) == FileManager::toUpper(source));
		destination.append(".txt");
		ofstream file2(destination);
		fstream file3(destination);
		if (file3.is_open())
		{
			file3 << content;
			FileManager::loading();
			cout << "\aFile Cloning Completed." << endl << "You are editing " << destination << endl;
		}
		file.close();
		if (file3.is_open())
		{
			file3.close();
			Editor edit(destination);
			edit.menu();
		}
		else
		{
			cout << "\aWhoops! You broke something. Try Again!" << endl;
		}
	}
}
Exemplo n.º 19
0
void scaling_by_n( std::string prefix, size_t dim, bool is_periodic,  Search_Factory::Search_Type search_type,
                  bool do_spoke = true, bool do_favored = false, bool do_two = false,
                  const double cutoff_t = 2., const size_t min_iter = 1, const size_t cutoff_n = 0,
                  bool do_bridson = false)
{
  // vary r, collect timings for each algorithm
  
  // Do at least min_iter runs of MPS   (set to 0 if no requirements)
  // Continue to do iterations until the time it takes is greater than cutoff_t              (set to 0 if no requirements)
  //   "  "  "                           number of samples produced is greater than cutoff_n (set to 0 if no requirements)
  //
  // Iterations will stop only when *all three* conditions are met
  
  Timing_Stats run_time;
  run_time.start_clock();

  // get file names
  std::stringstream file0ss, file1ss, file2ss, file3ss;
  
  // junk filenames in order to not overwrite any interesting data
  if (!do_spoke)
    file0ss << "00empty_";
  if (!do_favored)
    file1ss << "00empty_";
  if (!do_two)
    file2ss << "00empty_";
  if (!do_bridson)
    file3ss << "00empty_";
  
  file0ss << prefix << dim;
  file1ss << prefix << dim;
  file2ss << prefix << dim;
  file3ss << prefix << dim;
  if (is_periodic)
  {
    file0ss << "_P_";
    file1ss << "_P_";
    file2ss << "_P_";
    file3ss << "_P_";
  }
  else
  {
    file0ss << "_n_";
    file1ss << "_n_";
    file2ss << "_n_";
    file3ss << "_n_";
  }
  std::string search_s;
  switch (search_type)
  {
    case Search_Factory::ARRAY:
      search_s = "a";
      break;
    case Search_Factory::GRID:
      search_s = "g";
      break;
    case Search_Factory::RANGE:
      search_s = "r";
      break;
    case Search_Factory::TREE:
      search_s = "t";
      break;
    case Search_Factory::UNSPECIFIED:
      search_s = "u";
      break;
  }
  file0ss << search_s << "_0spoke.txt";
  file1ss << search_s << "_1favored.txt";
  file2ss << search_s << "_2two.txt";
  file3ss << search_s << "_3bridson.txt";
  
  // open files
  std::fstream file0( file0ss.str().c_str(), std::ios::out);
  std::fstream file1( file1ss.str().c_str(), std::ios::out);
  std::fstream file2( file2ss.str().c_str(), std::ios::out);
  std::fstream file3( file3ss.str().c_str(), std::ios::out);

  // header
  file0 << "0 " << dim << " " << is_periodic << " " << search_s <<   " spoke "     << dim << "d" << std::endl;
  file1 << "1 " << dim << " " << is_periodic << " " << search_s << " favored "     << dim << "d" << std::endl;
  file2 << "2 " << dim << " " << is_periodic << " " << search_s <<     " two "     << dim << "d" << std::endl;
  file3 << "3 " << dim << " " << is_periodic << " " << search_s <<     " bridson " << dim << "d" << std::endl;
  write_header(file0);
  write_header(file1);
  write_header(file2);
  write_header(file3);
  
  // number of seconds allowed
  // do one iteration past this value, which could take up to 4x as long if O(n^2)
//  const double cutoff = 540; // three minutes
//    const double cutoff = 180; // three minutes
//  const double cutoff = 24; // 2 seconds
//  const double cutoff = 4;
//  const double cutoff = 0.01; // testing
  
  // time taken last iter
  double t_spoke = 0.;
  double t_favored = 0.;
  double t_two = 0.;
  double t_bridson = 0.;
  
  // number of real samples produced last iter
  size_t n_spoke(0), n_favored(0), n_two(0), n_bridson(0);
  
  const double min_r0 = 1.; // MPS_Spoke::max_radius( is_periodic ); //  0.161;
  const double min_r1 = 1.; // MPS_Favored::max_radius( is_periodic ); // 0.102;
  const double min_r2 = 1.; // MPS_Two_Spoke::max_radius( is_periodic); // 0.071;
  const double min_r3 = 1.; // MPS_Bridson::max_radius( is_periodic); // 0.071;

//  double first_n = 10;
//  double r = 1. / ( pow( first_n, 1. / (double) (dim) ));
//  double r = 1. - (1. / (4. * (double) dim ) );
//  if ( r > min_r0 )
    double r = min_r0;
  
  size_t spoke_iter(0), favored_iter(0), two_iter(0), bridson_iter(0);
  
  for (int i=0; i<1000; ++i)
  {
    std::cout << std::endl << "scaling_by_n r = " << r  << std::endl;
    {
      if ( do_spoke && (r <= min_r0) && (more_t( t_spoke, cutoff_t) || more_n( n_spoke, cutoff_n ) || more_n( spoke_iter, min_iter)) )
      {
        t_spoke = run_spokes(file0, dim, is_periodic, r, search_type, n_spoke);
        spoke_iter++;
      }
      if ( do_favored && (r <= min_r1) && (more_t( t_favored, cutoff_t) || more_n( n_favored, cutoff_n ) || more_n( favored_iter, min_iter)))
      {
        t_favored = run_favored(file1, dim, is_periodic, r, search_type, n_favored);
        favored_iter++;
      }
      if ( do_two && (r <= min_r2) && (more_t( t_two, cutoff_t) || more_n( n_two, cutoff_n ) || more_n( two_iter, min_iter)) )
      {
        t_two = run_two(file2, dim, is_periodic, r, search_type, n_two);
        two_iter++;
      }
      if ( do_bridson && (r <= min_r3) && (more_t( t_bridson, cutoff_t) || more_n( n_bridson, cutoff_n ) || more_n( bridson_iter, min_iter)) )
      {
        t_bridson = run_bridson(file3, dim, is_periodic, r, search_type, n_bridson);
        bridson_iter++;
      }
    }
    
    // double n each time
    // this could quadruple time
    //    r *= 1./sqrt(2);
    r *= 1./ pow(2., 1./double(dim));
    
    if ( 1/r > 20000 )
      break;
  }
  
  file0.close();
  file1.close();
  file2.close();
  file3.close();  
  
  run_time.collect_stats();
  std::cout << "scaling_by_n runtime = " << run_time.cpu_time << std::endl;
}
Exemplo n.º 20
0
void MessageTreeWidget::importSms()
{
	QString filename = QFileDialog::getOpenFileName(NULL, "Open File",".","Sms (*.xml)");
	if(!filename.isEmpty())
	{
		QFile file1(strMessagePathOpen);
		QFile file2(filename);
		QFile file3(strMessagePathOpen);
		if (!file1.open(QIODevice::ReadOnly)) return ;
		if (!file2.open(QIODevice::ReadOnly)) return ;
		QDomDocument doc1;//文档1
		QDomDocument doc2;//文档2
		if (!doc1.setContent(&file1))
		{
			file1.close();
			return;
		}
		if (!doc2.setContent(&file2))
		{
			file2.close();
			return ;
		}
		QDomElement docElem1 = doc1.documentElement();
		QDomElement docElem2 = doc2.documentElement();
		
		QDomNodeList list1 = doc1.elementsByTagName("SmsSum");
		//以标签名进行查找
		QDomElement firstElement;
		for(int i=0; i<list1.count(); i++)
		{
			QDomElement e = list1.at(i).toElement();
			
			QString str= e.attribute("term");
			if(str.compare("信息")==0)
			{  
				firstElement = e;
				break;
			}
		}
		
		QDomNodeList list = doc2.elementsByTagName("Sms");
		//以标签名进行查找
		for(int j=0; j< list.count(); j++)
		{
			QDomElement e = list.at(j).toElement();
			QDomElement tmp = e.cloneNode(true).toElement();
			QString strContent = tmp.text();
			bool key = keydetect(strContent);
			if(!key)
				firstElement.appendChild(tmp);//加入以后list 内已经删除了
		}		
		if(!file3.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ;
			QTextStream out(&file3);
		doc1.save(out,4);   //将文档保存到文件,4为子元素缩进字符数
		file3.close();
		emit updateTreeAllItem();
		QMessageBox *message=new QMessageBox(QMessageBox::NoIcon, "导入短信", "导入成功"); 
		message->show();
		
	}
}
Exemplo n.º 21
0
int main( ) {

   std::string input_dir = "Input/";

   // Read Nucleus File
   std::string nucleus_string;
   std::ifstream nucleus_file( "domgen.config" );

   nucleus_file >> nucleus_string;

   nucleus_file.close();
   nucleus_file.clear();

   // Read Configuration file
   std::string config_filename = nucleus_string + ".config";
   std::ifstream config_file( config_filename.c_str() );

   std::string parameters_string;
   int fit_ph;
   double rmax;
   int rpts;
   int lmax;

   config_file >> parameters_string >> fit_ph;
   config_file >> rmax >> rpts >> lmax;

   cout<<"parameters_string = "<<parameters_string<<endl;

   int num_lj;
   config_file >> num_lj;

   config_file.close();
   config_file.clear();

   // Read in normalization
   double calc_Z = 20;
   double calc_N = 20;
   //std::cout << "Enter calculated Z: " << std::endl;
   //std::cin >> calc_Z; 

   //std::cout << "Enter calculated N: " << std::endl;
   //std::cin >> calc_N;

   std::string output_dir = "Output_" + parameters_string + "/Spectral_functions_kE/";
   std::string parameters_filename = parameters_string + ".inp";

   std::cout << "rmax = " << rmax << std::endl;
   std::cout << "rpts = " << rpts << std::endl;
   std::cout << "lmax = " << lmax << std::endl;

   std::string n_string = "n" + nucleus_string;
   std::string p_string = "p" + nucleus_string;

   std::string n_filename = input_dir + n_string + ".inp";
   std::string p_filename = input_dir + p_string + ".inp";

   // Create Nuclear Parameter Objects
   NuclearParameters Nu_n = read_nucleus_parameters( n_filename );
   NuclearParameters Nu_p = read_nucleus_parameters( p_filename );

   std::vector< NuclearParameters > Nu_vec;
   Nu_vec.push_back( Nu_n );
   Nu_vec.push_back( Nu_p );


   // Read in DOM parameters
   std::ifstream pfile( parameters_filename.c_str() );
   if ( pfile.is_open() !=1 ) {
      std::cout << "could not open file " << parameters_filename << std::endl;
      std::abort();
   }
   pfile.close();
   pfile.clear();

   // Create radial grid
   std::vector<double> rmesh;
   std::vector<double> rweights;
   double rdelt = rmax / rpts;
   for( int i = 0; i < rpts; ++i ) {

      rmesh.push_back( ( i + 0.5 ) * rdelt );
      rweights.push_back( rdelt );

   }

   // Create momentum space grid for k-slice
   std::vector<double> kmesh1;
   double kmax1 = 6.0;
   int kpts1 = 100;
   double deltak1 = kmax1 / kpts1;

   for ( int i = 0; i < kpts1; ++i ) {

      kmesh1.push_back( ( i + 0.5 ) * deltak1 );
   }

   // Create momentum space grid for E-slice
   std::vector<double> kmesh2; // wave number in units of fm^{-1}
std::vector<double> pmesh; // momentum in units of MeV / c
double pmin = 170; 
double pmax = 650;
double deltap = 40;
int ppts = static_cast<int> ( ( pmax - pmin ) / deltap ) + 1;

for ( int i = 0; i < ppts; ++i ) {

   double p = pmin + i * deltap;
   pmesh.push_back( p );

   double k = p / hbarc;
   kmesh2.push_back( k );
}

// Prepare stuff for output files
std::vector< std::string > np_strings;
np_strings.push_back( n_string );
np_strings.push_back( p_string );

// create L and J strings for output files
std::string L_array[8] = { "s", "p", "d", "f", "g", "h", "i", "j" };
std::string J_array[8] = { "1", "3", "5", "7", "9", "11", "13", "15" };

//Potential specifications
int type = 1; // 1 is P.B. form (average), 0 is V.N. form
int mvolume = 4;
int AsyVolume = 1;


/* CALCULATIONS */


// Loop over protons and neutrons
double Zp; // number of protons in projectile
omp_set_nested(1);
#pragma omp parallel num_threads(2)
{
#pragma omp for
   for ( unsigned int nu = 0; nu < Nu_vec.size(); ++nu ) {

      double tz = nu - 0.5; // +0.5 for protons, -0.5 for neutrons
      double calc_norm;
      if ( tz < 0 ) {

         Zp = 0;
         calc_norm = calc_N;
      }
      else { 

         Zp = 1;
         calc_norm = calc_Z;
      }

      // Nucleus Object
      const NuclearParameters &Nu = Nu_vec[nu];

      // Construct Parameters Object
      Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, Zp );

      // Construct Potential Object
      pot U = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
      pot *U1 = &U;

      // Construct Object for calculating bound-state properties
      boundRspace B( rmax, rpts, Nu.Ef, Nu.ph_gap, lmax, Nu.Z, Zp, Nu.A, U1 );

      // Create Energy Grid for k-slice
      double Emin1 = -225;
      double Emax1 = -25;
      double deltaE1 = 25;
      int epts1 = static_cast<int>( ( Emax1 - Emin1 ) / deltaE1 ) + 1;
      std::vector<double> emesh1;
      for ( int i = 0; i < epts1; ++i ) {

         emesh1.push_back( Emin1 + i * deltaE1 );
      }

      // Create Energy grid for E-slice
      double Emin2 = -300;
      double Emax2 = -25;
      double deltaE2 = 2;
      int epts2 = static_cast<int>( ( Emax2 - Emin2 ) / deltaE2 ) + 1;
      std::vector<double> emesh2;
      for ( int i = 0; i < epts2; ++i ) {

         emesh2.push_back( Emin2 + i * deltaE2 );
      }

      matrix_t S_of_kE_mtx1( kmesh1.size(), emesh1.size() );
      matrix_t S_of_kE_mtx2( kmesh2.size(), emesh2.size() );

      // intialize matrices to zero
      for ( unsigned int i = 0; i < kmesh1.size(); ++i ) {
         for ( unsigned int j = 0; j < emesh1.size(); ++j ) {

            S_of_kE_mtx1( i, j ) = 0;
         }
      }

      for ( unsigned int i = 0; i < kmesh2.size(); ++i ) {
         for ( unsigned int j = 0; j < emesh2.size(); ++j ) {

            S_of_kE_mtx2( i, j ) = 0;
         }
      }

      std::vector< matrix_t > S_of_kE_mtx2_lj_vec;

      // Loop over lj channels
      for ( int L = 0; L < lmax + 1; ++L ) {
         cout<<"l = "<<L<<endl;

         for( int up = -1; up < 2; up+=2 ) {

            double xj = L + up / 2.0;
            int j_index = ( up - 1 ) / 2;
            if ( xj < 0 ) continue;

            std::string j_string;
            if ( L == 0 ) j_string = J_array[ L ];
            else j_string = J_array[ L + j_index ];

            std::string lj_string = L_array[L] + j_string + "2";

            // Create Bessel Function matrix in k and r
            matrix_t bess_mtx1( kmesh1.size(), rmesh.size() );
            for( unsigned int nk = 0; nk < kmesh1.size(); ++nk ) {
               for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {

                  double rho = kmesh1[nk] * rmesh[nr];

                  bess_mtx1( nk, nr ) = gsl_sf_bessel_jl( L, rho );
               }
            }

            // Create Bessel Function matrix in k and r
            matrix_t bess_mtx2( kmesh2.size(), rmesh.size() );
            for( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {
               for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {

                  double rho = kmesh2[nk] * rmesh[nr];

                  bess_mtx2( nk, nr ) = gsl_sf_bessel_jl( L, rho );
               }
            }

            // Calculate S( k; E ) for k-slice 
            for ( unsigned int m = 0; m < emesh1.size(); ++m ) {

               double E = emesh1[m];

               /*
                  std::ostringstream e_strm;
                  e_strm << "m" << std::abs( E );
                  std::string s_of_kE_lj_filename1 = 
                  output_dir + np_strings[nu] + "_s_of_k_" + 
                  "E_at_" + e_strm.str() + "MeV_" + L_array[L] 
                  + j_string + "2.out";

                  std::ofstream file1( s_of_kE_lj_filename1.c_str() );
                  */
               // Propagator
               cmatrix_t G = B.propagator( rmesh, E, L, xj );

               // Spectral Function in momentum space, S( k; E ) 
               for( unsigned int nk = 0; nk < kmesh1.size(); ++nk ) {

                  double rsums = 0;
                  for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                     double jl1 = bess_mtx1( nk, i );

                     for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                        double jl2 = bess_mtx1( nk, j );

                        rsums -= rmesh[i] * jl1 * imag( G( i, j ) ) 
                           * rmesh[j] * jl2 * rdelt * 2 / M_PI / M_PI;
                     }
                  } // end loop over radial coordinates

                  //                        file1 << kmesh1[nk] << " " << rsums << std::endl;

                  S_of_kE_mtx1( nk, m ) += ( 2 * xj + 1 ) * rsums;

               } // end loop over k

               //                    file1.close();
               //                    file1.clear();

               // r-space spectral functions

            } // end loop over energy

            // Calculate S( k; E ) for E-slice 
            matrix_t S_of_kE_mtx_lj( kmesh2.size(), emesh2.size() );
            for ( unsigned int m = 0; m < emesh2.size(); ++m ) {

               double E = emesh2[m];

               // Propagator
               cmatrix_t G = B.propagator( rmesh, E, L, xj );

               // Spectral Function in momentum space, S( k; E ) 
               for( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {

                  double rsums = 0;
                  for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                     double jl1 = bess_mtx2( nk, i );

                     for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                        double jl2 = bess_mtx2( nk, j );

                        rsums -= rmesh[i] * jl1 * imag( G( i, j ) ) 
                           * rmesh[j] * jl2 * rdelt * 2 / M_PI / M_PI;
                     }
                  } // end loop over radial coordinates

                  S_of_kE_mtx_lj( nk, m ) = ( 2 * xj + 1 ) * rsums;
                  S_of_kE_mtx2( nk, m ) += ( 2 * xj + 1 ) * rsums;

               } // end loop over k

            } // end loop over energy

            S_of_kE_mtx2_lj_vec.push_back( S_of_kE_mtx_lj );

         }// end loop over j

      } // end loop over L

      // write out results summed over the lj combinations
      for ( unsigned int j = 0; j < emesh1.size(); ++j ) {

         std::ostringstream e_strm;
         e_strm << "m" << std::abs( emesh1[j] );
         std::string s_of_kE_filename1 = 
            output_dir + np_strings[nu] + "_s_of_k_" + 
            "E_at_" + e_strm.str() + "MeV.out"; 

         std::ofstream file3( s_of_kE_filename1.c_str() );

         for ( unsigned int i = 0; i < kmesh1.size(); ++i ) {

            file3 << kmesh1[i] << " " << S_of_kE_mtx1( i, j ) << std::endl;
         }

         file3.close();
         file3.clear();
      }

      // write in units of MeV^-4 sr^-1
      double fac = std::pow( hbarc, 3 ) * 4 * M_PI;
      for ( unsigned int i = 0; i < kmesh2.size(); ++i ) {
         std::ostringstream k_strm;
         k_strm << pmesh[i];
         std::string s_of_kE_filename2 = 
            output_dir + np_strings[nu] + "_s_of_E_" + 
            "p_at_" + k_strm.str() + "MeV_over_c.out"; 

         std::ofstream file4( s_of_kE_filename2.c_str() );

         for ( unsigned int j = 0; j < emesh2.size(); ++j ) {

            // write energy in terms of missing energy
            // and in units of GeV
            file4 << std::abs( emesh2[j]/1000) << " " 
               << S_of_kE_mtx2( i, j ) / fac << " "
               << S_of_kE_mtx2( i, j ) / fac / calc_norm << std::endl;
         }

         file4.close();
         file4.clear();
      }

      // write in units of MeV^-4 sr^-1
      for ( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {

         for ( int L = 0; L < lmax + 1; ++L ) {

            std::ostringstream k_strm;
            k_strm << pmesh[nk];

            std::string s_of_kE_lj_filename2 = 
               output_dir + np_strings[nu] + "_s_of_E_p_at_" 
               + k_strm.str() + "MeV_over_c_" + L_array[L] 
               + ".out";

            std::ofstream file2( s_of_kE_lj_filename2.c_str() );
            for ( unsigned int m = 0; m < emesh2.size(); ++m ) {

               // write energy in terms of missing energy
               // and in units of GeV
               if ( L == 0 ) {
                  file2 << std::abs( emesh2[m]/1000 ) << " " 
                     << S_of_kE_mtx2_lj_vec[0]( nk, m ) / fac 
                     << std::endl;
               }
               else {

                  double jg = S_of_kE_mtx2_lj_vec[2*L]( nk, m );
                  double jl = S_of_kE_mtx2_lj_vec[2*L- 1]( nk, m );

                  file2 << std::abs( emesh2[m]/1000) << " " 
                     << jg / fac << " " << jl / fac << " "
                     << ( jg + jl ) / fac << std::endl;
               }
            }

            file2.close();
            file2.clear();

         } // end loop over L

      } // end loop over momentum

   } // end loop over tz
}                                               /* end of pragma loop */

return 1;
}
Exemplo n.º 22
0
void TestEmailRedline::TestLongFileNames()
{
	/*This test function will create a redline file name in 2 different ways and idea of the test
	is to make sure the correct concatenation is returned and to test that the file name (if too long)
	has been shorted as to not create problems copy files with win32 functions*/

	AFX_MANAGE_STATE(AfxGetAppModuleState());
	
	CStdString sTempPath = CGeneral::GetTemporaryPath();
	CStdString sOrginalDesc =  _T("oringinal_sdhflisadjflsdawsjfkshflsjdgkjasfokhosjhgfsjhgkusdfslgaeihfkdfhowaujfkushfsdfgliajflihdfg;awikfkudlsijgfolsdhfasufuiosdefoisufoisdejfisdjfilsdjflijsf");
	CStdString sModifiedDesc = _T("modified_sdhflisadjflsdawsjfkshflsjdgkjasfokhosjhgfsjhgkusdfslgaeihfkdfhowaujfkushfsdfgliajflihdfg;awikfkudlsijgfolsdhfasufuiosdefoisufoisdejfisdjfilsdjflijsf");

	CTemporaryFileInTopDir file1(sOrginalDesc);
	CTemporaryFileInTopDir file2(sModifiedDesc);
	CTemporaryFileInTopDir file3(_T("sTemp.doc"));

	CDVController DVC;

	//store our created file by ID and description
	DVC.GetSourceConversionDocument(true).DocId(_T("file://") + file1);
	DVC.GetSourceConversionDocument(true).SetDisplayName(sOrginalDesc);

	DVC.GetSourceConversionDocument(false).DocId(_T("file://") + file2);
	DVC.GetSourceConversionDocument(false).SetDisplayName(sModifiedDesc);

	//test the first redline name
	CString sRedline1 = DVC.GetComparisonDocController().GetComparisonDocumentTitle();
	assertTest(!sRedline1.Compare(L"oringinal_sdhflisadjflsdawsjfkshflsjdgkjasfokhosjhgfsjhgkusdfslgaeihfkdfhowaujfkushfsdfgliajflihdfg;awikfkudlsijgfolsd-modified_sdhflisadjflsdawsjfkshflsjdgkjasfokhosjhgfsjhgkusdfslgaeihfkdfhowaujfkushfsdfgliajflihdfg;awikfkudlsijgfolsdh"));

	CStdString sOriginalFile = DVC.GetOriginalDoc().GetAttachmentName();
	PathRemoveExtension(sOriginalFile.GetBuffer(MAX_PATH));
	sOriginalFile.ReleaseBuffer();

	CStdString sModifiedFile = DVC.GetModifiedDoc().GetAttachmentName();
	PathRemoveExtension(sModifiedFile.GetBuffer(MAX_PATH));
	sModifiedFile.ReleaseBuffer();

	CStdString sRedline2 = sOriginalFile;
	sRedline2 += _T("-");
	sRedline2 += sModifiedFile;

	//test the second redline name
	assertTest(sRedline2.Equals(L"oringinal_sdhflisadjflsdawsjfkshflsjdgkjasfokhosjhgfsjhgkusdfslgaeihfkdfhowaujfkushfsdfgliajflihdfg;awikfkudlsijgfolsdhfasufuiosdefoisufoisdejfisdjfilsdjflijsf-modified_sdhflisadjflsdawsjfkshflsjdgkjasfokhosjhgfsjhgkusdfslgaeihfkdfhowaujfkushfsdfgliajflihdfg;awikfkudlsijgfolsdhfasufuiosdefoisufoisdejfisdjfilsdjflijsf"));
	
	//test copying the file
	CStdString sCopyName = sTempPath + sOrginalDesc + sModifiedDesc + _T(".doc");
	BOOL bWorks1 = CopyFile(file3, sCopyName, false);
	if (bWorks1)
	{
		DeleteFile(sCopyName);
	}
	assertTest(!bWorks1);					//this should fail because the file name is too long

	sCopyName = sTempPath + sRedline2 + _T(".doc");
	EmailRedline* sTemp;

	CDVController* tempController;
	tempController = new CDVController();
	sTemp = new EmailRedline(tempController);

	if(sTemp->IsFilePathTooLong(sCopyName))
	{
		sCopyName = sTemp->MakeFileNameShorter(sCopyName);
	}

	BOOL bWorks2 = CopyFile(file3, sCopyName, false);
	if (bWorks2)
	{
		DeleteFile(sCopyName);
	}
	
	assertTest(bWorks2);					//test to see if the created redlinefile name works

	delete sTemp;
	delete tempController;
}
Exemplo n.º 23
0
void ThroughPut::InputManagement(){
    //QFile file("datain.txt");
    QFile file0("./Pilot_send_data/pilot_1200_im.txt");
    if (!file0.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << file0.errorString();
        qDebug() << "Last sentence is in QPSK Inputmanagement." << endl;

    }
    //qDebug() << QObject::tr("file text:") << endl << file.readAll();
    //char str[100];
    char str6[100];
    for( int i = 0 ; i < 1200 ; i++ ){
        file0.readLine(str6,100);
        double crr = 0;
        crr = char2int(str6);
        //qDebug() << "pilot2[ "<< i <<"][0] is :"<<crr;
        pilot2[i][1] = crr;
    }
  file0.close();

  QFile file5("./Pilot_send_data/pilot_1200_re.txt");
  if (!file5.open(QIODevice::ReadOnly | QIODevice::Text)){
      qDebug() << file5.errorString();
      qDebug() << "Last sentence is in QPSK Inputmanagement." << endl;

  }
  //qDebug() << QObject::tr("file text:") << endl << file.readAll();
  //char str[100];

  for( int i = 0 ; i < 1200 ; i++ ){
      file5.readLine(str6,100);
      double crr = 0;
      crr = char2int(str6);
      //qDebug() << "pilot2[ "<< i <<"][0] is :"<<crr;
      pilot2[i][0] = crr;
  }
file5.close();

    //QFile file("./pilot4_send_data/pilot4_1200_re.txt");
    QFile file("./16qam_data_new/data_im.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << file.errorString();
        qDebug() << "Last sentence is in ThroughPut Inputmanagement." << endl;

    }
    //qDebug() << QObject::tr("file text:") << endl << file.readAll();
    //char str[100];
    char str[100];
    for( int i = 0 ; i < 1200 ; i++ ){
        file.readLine(str,100);
        double crr = 0;
        crr = char2int(str);
        //qDebug() << "pilot4[ "<< i <<"][0] is :"<<crr;
        pilot4[i][0] = crr;
    }

    //qDebug() << "last one is :"<< ThroughPut[9][0] ;
    file.close();

    //QFile file2("./pilot4_send_data/pilot4_1200_im.txt");
    QFile file2("./16qam_data_new/data_re.txt");
    if (!file2.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << file2.errorString();
        qDebug() << "Last sentence is in ThroughPut Inputmanagement." << endl;
    }
    //qDebug() << QObject::tr("file text:") << endl << file2.readAll();
    //char str[100];
    for( int i = 0 ; i < 1200 ; i++ ){
        file2.readLine(str,100);
        double crr = 0;
        crr = char2int(str);
        //qDebug() << "pilot4[ "<< i <<"][1] is :"<<crr;
        pilot4[i][1] = crr;
    }


    //qDebug() <<"apsk[0][0] is :"<< *(pdata) << endl;
    file2.close();


   // QFile file3("./16qam_data/data_re.txt");
    QFile file3("./16qam_data_new/data_re.txt");
    if (!file3.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << file3.errorString();
        qDebug() << "Last sentence is in ThroughPut Inputmanagement." << endl;

    }
    //qDebug() << QObject::tr("file text:") << endl << file.readAll();
    //char str[100];
    int cnt_2_500=0;
    for( int i = 0 ; i < 600 ; i++ ){
        file3.readLine(str,100);
        double crr = 0;
        if(i%6!=0){
        crr = char2double(str);
       // qDebug() << "re[ "<< i <<"][0] is :"<<crr;
        qam16_3[cnt_2_500][0] = crr;
        cnt_2_500++;
        }
    }

    //qDebug() << "last one is :"<< ThroughPut[9][0] ;
    file3.close();

   // QFile file4("./16qam_data/data_im.txt");
    QFile file4("./16qam_data_new/data_im.txt");
    if (!file4.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << file4.errorString();
        qDebug() << "Last sentence is in ThroughPut Inputmanagement." << endl;

    }
    //qDebug() << QObject::tr("file text:") << endl << file.readAll();
    //char str[100];
    int cnt_2_500_2;
    for( int i = 0 ; i < 600 ; i++ ){
        file4.readLine(str,100);
        double crr = 0;
        if(i%6!=0){
        crr = char2double(str);
        //qDebug() << "im[ "<< i <<"][0] is :"<<crr;
        qam16_3[cnt_2_500_2][1] = crr;
        cnt_2_500_2++;
        }
    }

    //qDebug() << "last one is :"<< ThroughPut[9][0] ;
    file4.close();







}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
//start clock
clock_t t0 = clock();

//declare three counters
int i = 0, j = 0, count = 0;

//arbitrary values, not CLIs for simplicity
int d = 100;	//plate separation
int h = 100;	//plate height
int dx = 1;	//step-size in x
int dy = 1;	//step-size in y
int nx = 100; 	//x points
int ny = 100; 	//y points
float R = 15; 	//radius of cylinder

//get command line arguments
int loops = atoi(argv[1]); 	//number of iterations

int V=1; //define arbitrary plate potential

//declare matrices for electrostatic potential
//requires second matrix to store previous values
double phi[nx+2][ny+2];
double phi_new[nx+2][ny+2];

std::cout << "Jacobi's iterative method\n";
std::cout << "-------------------------\n";
std::cout << "Defining boundaries...";

//define boundary conditions
for (i=0; i<=nx+1; i++)
{
 for (j=0; j<=ny+1; j++)
 {
  if (j==0 || j == ny+1)
  {
	//linearly decreasing at top and bottom
   	phi[i][j] = V-((double)2*V*i/(nx+1));
  }
  else if (i==0)
  {
	//V at left plate
   	phi[i][j] = V;
  }
  else if (i==nx+1)
  {
	//-V at right plate
   	phi[i][j] = -V;
  }
  else
  {
	//otherwise, initialise to zero
   	phi[i][j] = 0;
  }
 }
}

std::cout << "Done!\n";

//declare convergence
double convergence = 0;

std::cout << "Solving for potential...";

//iterate to find potential until max its
for (count = 0; count < loops; count++)
{
//set to zero at start of each loop
convergence = 0;

 //loop over grid, ignore potential at boundaries (first and last x,y)
 for (i=1; i<=nx; i++)
 {
  for (j=1; j<=ny; j++)
  {
	//if point in circle, potential is 0
   	if ( pow((i*dx-0.5*d),2)+pow((j*dy-0.5*h),2) < pow(R,2) )
   	{
    		phi_new[i][j] = 0;
   	}
   	else
   	{
    		//employ jacobi's iterative method
 	   	phi_new[i][j] = 0.25 * (phi[i-1][j] + phi[i+1][j] + phi[i][j-1] + phi[i][j+1]);
   	}
  }
 }

 //update all of matrix in second loop
 for (i=1; i<=nx; i++)
 {
  for (j=1; j<=ny; j++)
  {
	//increment convergence
	convergence += fabs(phi_new[i][j]-phi[i][j]);

   	phi[i][j] = phi_new[i][j];
  }
 }
}

std::cout << "Done!\n";

double r, theta; //declare polar co-ordinates

std::cout << "Finding differences and writing files...";

double error = 0; //declare difference of analytical and numerical

//output difference of numerical and analytical solution, for a given method
for (j=0; j<=ny+1; j++)
{
 for (i=0; i<=nx+1; i++)
 {
  r=sqrt((i*dx-0.5*d)*(i*dx-0.5*d)+(j*dy-0.5*h)*(j*dy-0.5*h));	//define the radius
  theta = atan2(j*dy-0.5*ny,i*dx-0.5*nx);			//define the angle

  //open file
  std::ofstream file("data/jacobi.dat", std::ios_base::app);

  //if in the circle, difference will be zero
  if (r*r < R*R)
  {
	//output numerical
   	file << i*dx << "\t" << j*dy << "\t" << 0 << std::endl;
  }
  else //otherwise
  {
	//output numerical
   	file << i*dx << "\t" << j*dy << "\t" << phi[i][j] << std::endl;

	//increment error
	error += fabs(phi[i][j]-((double)2*V/d)*((double)(R*R)/r - r)*cos(theta));
  }
 }
}

std::cout << "Done!\n";

//end clock
clock_t t1 = clock();

//open files for appending
std::ofstream file1("data/jacobi_time.dat", std::ios::out | std::ios::app);
std::ofstream file2("data/jacobi_conv.dat", std::ios::out | std::ios::app);
std::ofstream file3("data/jacobi_err.dat", std::ios::out | std::ios::app);

//output statistics
file1 << count << '\t' << double(t1 - t0) / CLOCKS_PER_SEC << std::endl;
file2 << count << '\t' << (double)convergence/(nx*ny) << std::endl;
file3 << count << '\t' << (double)error/((nx+2)*(ny+2)) << std::endl;

std::cout << std::endl;
}
Exemplo n.º 25
0
int main() {
	std::vector<cv::Point3d>x_1;
	std::vector<cv::Point3d>x_2;
	double x, y;

	std::ifstream file2("chess1.txt");
	// std::ifstream file2("chess1.txt");
	for (int i=0; i<N; i++) {
		file2 >> x >> y;
		cv::Point3d  x1i(x, y, 1);
		x_1.push_back(x1i);
	}
	std::cout << "x_1 = " <<   x_1 << endl;
	std::ifstream file3( "chess2.txt");
	// std::ifstream file3( "chess2.txt");
	for (int i=0; i<N; i++) {
		file3 >> x >> y;
		cv::Point3d  x2i(x, y, 1); 
		x_2.push_back(x2i);
	}
	std::cout << "x_2 = " <<  x_2 << endl;

	//////////  Camera1  focal length: 18mm,  sensor size:  23.5 x 15.7mm,
	Camera c1;
	c1.set_focal(18);
	c1.set_ccd(23);
	Camera c2;
	c2.set_focal(18);
	c2.set_ccd(23);

	cv::Mat A;
	for (int i=0; i<(int)x_1.size(); i++) {
		// std::cout << "i=" << i << ",  x_1=" << x_1[i] << ",  x_2=" << x_2 [i]<< std::endl;
		int x1 = x_1[i].x, y1 = x_1[i].y, w1 = x_1[i].z;
		int x2 = x_2[i].x, y2 = x_2[i].y, z2 = x_2[i].z;
		// Ai = (0   -w*X y*X
		//		 w*X 0    -x*X)
		cv::Mat  Ai = (cv::Mat_<double> (2,9)  << 0, 0,0,  -w1*x2, -w1*y2, -w1*z2,   y1*x2, y1*y2, y1*z2,
					w1*x2, w1*y2, w1*z2, 0, 0, 0,  -x1*x2, -x1*y2, -x1*z2);
		A.push_back(Ai);
	}
	std::cout << "A" << std::endl << A << std::endl << std::endl;
	cv::Mat_<double> w, u, vt;  // vt(9, 9)
	cv::SVD::compute(A, w, u, vt, cv::SVD::FULL_UV);
	////////////////////   h1, h2, h3 =  [vt00, vt10, vt20, ... , vt80]
	////////////////////   H = [h1, h2, h3]
	std::cout << "w=" 	<< w 	<< endl << endl;
	std::cout << "u=" 	<< u 	<< endl << endl;
	std::cout << "vt=" 	<< vt 	<< endl << endl;
	cv::Mat H = (cv::Mat_<double> (3, 3)  <<  vt(8,0), vt(8,1), vt(8,2), vt(8,3), vt(8,4), vt(8,5), vt(8,6), vt(8,7), vt(8,8) );
	// cv::Mat H = (cv::Mat_<double>(2,3) << vt(8,0) , vt(8,1) , vt(8,2) ,
	//  vt(8,3) , vt(8,4), vt(8,5) );
	 std::cout << "affin matrix" <<  std::endl << H << std::endl;




	 //////////////////////// image transform
	 cv::Mat img1 = cv::imread("img1.JPG", 0);
	 cv::Mat img2 = cv::imread("img2.JPG", 0);

 	 cv::Mat out_img = cv::Mat::zeros(img1.rows, img1.cols, img1.type());
	 AffinTransformer affin;
	 cv::Matx33d mat = affin.Translation(0,0);
	 // warpAffine(img, out_img, H, out_img.size());
	 out_img = affin.TransformE(img1, H, 0);
	 // out_img = affin.TransformL(img, H);
	 cv::imwrite("out.jpg", out_img);

	return 0;
}
Exemplo n.º 26
0
Arquivo: main.cpp Projeto: luckyyd/IMA
int main(int argc, char *argv[])
{
	//QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF8"));
	QApplication a(argc, argv);
	//QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
	/*QTextCodec *codec = QTextCodec::codecForName("GB2312");
	QTextCodec::setCodecForLocale(codec);
	QTextCodec::codecForUtfText("GB2312");*/
	QTextCodec *codec = QTextCodec::codecForName("GB18030");
	

	QSplashScreen *splash = new QSplashScreen;
	splash->setPixmap(QPixmap("start.png"));
	splash->show();
	for (int i = 0; i<300; i++)
	{
		splash->repaint();
	}

	#pragma region INVALID CODE
	//QWidget *win0 = new QWidget(0);
	/*
	QtCreate *w1 = new QtCreate(win0);
	w1->resize(1600, 1600);
	MyTimeSolveProject *w2 = new MyTimeSolveProject(win0);
	w2->resize(600, 600);
	*/

	/*MyTimeSolveProject *MyProject = new MyTimeSolveProject();
	QtCreate *w = new QtCreate();
	QHBoxLayout *lay = new QHBoxLayout();
	lay->addWidget(w);
	lay->addWidget(MyProject);
	win0->setLayout(lay);
	win0->show();*/

	//QWidget *win0 = new QWidget(0);
	//QtCreate *w = new QtCreate(win0);

	#pragma endregion

	QtCreate w;
	w.setWindowTitle(codec->toUnicode("IMA环境下多任务实时性能最优化系统"));
	w.show();
	
	splash->finish(&w);
	delete splash;

	//MyTimeSolveProject MyProject(ui.GantWidget);
	//MyTimeSolveProject MyPro(Ui::QtCreateClass);
	////MyTimeSolveProject *myproject = new MyTimeSolveProject(this.ui.GantWidget);
	//
	////MyProject.show();
	///*
	//MyProject.show();
	//*/

	//MyTimeSolveProject  MyProject;
	//MyProject.show();

	#pragma region VIDEOVIEW1
	QWidget *widget1 = new QWidget;
	widget1->resize(400, 300);   //
	widget1->setWindowTitle("View1");
	QVBoxLayout *layout1 = new QVBoxLayout;
	QMediaPlayer* player1 = new QMediaPlayer;
	QVideoWidget* vw1 = new QVideoWidget;

	layout1->addWidget(vw1);
	widget1->setLayout(layout1);

	player1->setVideoOutput(vw1);

	QFile file1("Video02.AVI");
	if (!file1.open(QIODevice::ReadOnly))
		qDebug() << "Could not open file";

	player1->setMedia(QUrl::fromLocalFile("Video02.AVI"));
	player1->play();
	widget1->show();
	#pragma endregion

	#pragma region VIDEOVIEW2
	QWidget *widget2 = new QWidget;
	widget2->resize(400, 300);   //
	widget2->setWindowTitle("View2");
	QVBoxLayout *layout2 = new QVBoxLayout;
	QMediaPlayer* player2 = new QMediaPlayer;
	QVideoWidget* vw2 = new QVideoWidget;

	layout2->addWidget(vw2);
	widget2->setLayout(layout2);

	player2->setVideoOutput(vw2);

	QFile file2("Video03.AVI");
	if (!file2.open(QIODevice::ReadOnly))
		qDebug() << "Could not open file";

	player2->setMedia(QUrl::fromLocalFile("Video03.AVI"));
	player2->play();
	widget2->show();
	#pragma endregion

	#pragma region VIDEOVIEWPANEL
	QWidget *widget3 = new QWidget;
	widget3->resize(400, 300);   //
	widget3->setWindowTitle("Panel");
	QVBoxLayout *layout3 = new QVBoxLayout;
	QMediaPlayer* player3 = new QMediaPlayer;
	QVideoWidget* vw3 = new QVideoWidget;

	layout3->addWidget(vw3);
	widget3->setLayout(layout3);

	player3->setVideoOutput(vw3);

	QFile file3("Video01.AVI");
	if (!file3.open(QIODevice::ReadOnly))
		qDebug() << "Could not open file";

	player3->setMedia(QUrl::fromLocalFile("Video01.AVI"));
	player3->play();
	widget3->show();
	#pragma endregion

	return a.exec();
}