<commit_before>#include <epitome-core.h>
#include <iostream>
#include <thread>
using namespace EPITOME;

#define window_width 640
#define window_height 480

static bool running = true;
static bool enter_pressed = false;

static void E3DKey(Window& win, Keys key, KeyState state)
{
	if (key == KEY_ESCAPE && state == KEYS_RELEASED) //this is in case we throw more keys in this loop
		win.close();
	if (key == KEY_ENTER && state == KEYS_PRESSED)
		enter_pressed = true;
	if (key == KEY_ENTER && state == KEYS_RELEASED)
		enter_pressed = false;
}

static void ErrorFn(int error, const char* description)
{
	fputs(description, stderr);
}

static void onMouseMove(Window window, Point<double> m1)
{
	fprintf(stdout, "Mouse (%s): %i %i\r\n", window.getTitle(), (int)m1.x, (int)m1.y);
}

static void ThreadLoop(Window* window)
{
	//set a few events
	window->keyboard->onKeyReleased(Keys::KEY_ESCAPE, E3DKey);
	window->keyboard->onKeyPressed(KEY_ENTER, E3DKey);
	window->keyboard->onKeyReleased(KEY_ENTER, E3DKey);
	window->mouse->onMove(onMouseMove);

	auto size = window->getBufferSize();
	auto winsize = window->getWindowSize();
	window->beginDraw();

	/*glViewport(0, 0, size.width, size.height);
	glMatrixMode(GL_PROJECTION);
	glEnable(GL_DEPTH_TEST);
	gluPerspective(45, (float)size.width / (float)size.height, .1, 100);
	glMatrixMode(GL_MODELVIEW);
	glfwSwapInterval(1);*/

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(0, size.width - 1, size.height - 1, 0);
	// Here we use orthographic projection
	glPopMatrix();
	// Back to the projection we were using before
	glMatrixMode(GL_MODELVIEW);  // Best switch back to modelview

	glViewport(0, 0, size.width, size.height);
	glfwSwapInterval(1);

	GLdouble outx, outy, outz;
	GLdouble outx2, outy2, outz2;
	GLint viewport[4];
	GLdouble modelview[16], projection[16];
	glGetIntegerv(GL_VIEWPORT, viewport);
	glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
	glGetDoublev(GL_PROJECTION_MATRIX, projection);

	while (running)
	{
		if (window->isClosing())
			running = false;

		glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);         // Clear the color buffer (background)
		Point<double> mPos = window->mouse->getPosition();

		GLfloat b = (window->keyboard->isKeyDown(Keys::KEY_SPACE)) ? 1.0f : 0.0f;
		GLfloat r = (enter_pressed) ? 1.0f : 0.0f;

		//find the 40x40 pixel square, inverting the y axis
		gluUnProject(mPos.x-20, size.height-mPos.y-20, 0.0, modelview, projection, viewport, &outx, &outy, &outz);
		gluUnProject(mPos.x+20, size.height-mPos.y+20, 0.0, modelview, projection, viewport, &outx2, &outy2, &outz2);

		// Draw the square
		glBegin(GL_QUADS);
		glColor3f(b, 1.0f, r);
		glVertex2f(outx, outy);
		glVertex2f(outx2, outy);
		glVertex2f(outx2, outy2);
		glVertex2f(outx, outy2);
		glEnd();

		// Swap buffers (color buffers, makes previous render visible)
		window->render();

		// Increase angle to rotate
		//angle += 0.25;

		//checks for events
		Update();
	}
	glfwMakeContextCurrent(NULL);
	running = false;
}

GLuint loadBMP(const char * imagepath)
{
	// Data read from the header of the BMP file
	unsigned char header[54]; // Each BMP file begins by a 54-bytes header
	unsigned int dataPos;     // Position in the file where the actual data begins
	unsigned int width, height;
	unsigned int imageSize;   // = width*height*3
							  // Actual RGB data
	unsigned char * data;
	// Open the file
	FILE * file = fopen(imagepath, "rb");
	if (!file) {
		return 0;
	}
	if (fread(header, 1, 54, file) != 54) { // If not 54 bytes read : problem
		// Not a correct BMP file
		return 0;
	}
	if (header[0] != 'B' || header[1] != 'M') {
		// Not a correct BMP file
		return 0;
	}

	// Read ints from the byte array
	dataPos = *(int*)&(header[0x0A]);
	imageSize = *(int*)&(header[0x22]);
	width = *(int*)&(header[0x12]);
	height = *(int*)&(header[0x16]);
	// Some BMP files are misformatted, guess missing information
	if (imageSize == 0)    imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
	if (dataPos == 0)      dataPos = 54; // The BMP header is done that way

	// Create a buffer
	data = new unsigned char[imageSize];

	// Read the actual data from the file into the buffer
	fread(data, 1, imageSize, file);

	//Everything is in memory now, the file can be closed
	fclose(file);

	// Bind to dummy texture beforehand
	glBindTexture(GL_TEXTURE_2D, 0);

	// Create one OpenGL texture
	GLuint textureID;
	glGenTextures(1, &textureID);

	// "Bind" the newly created texture : all future texture functions will modify this texture
	glBindTexture(GL_TEXTURE_2D, textureID);

	// Give the image to OpenGL
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	return textureID;
}

void DrawImage(const Size<int>& size, GLuint texture) {
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0.0, size.width, 0.0, size.height, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	glLoadIdentity();
	glDisable(GL_LIGHTING);

	glColor3f(1, 1, 1);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture);

	// Draw a textured quad
	glBegin(GL_QUADS);
	glTexCoord2f(0, 0); glVertex3f(0, 0, 0);
	glTexCoord2f(0, 1); glVertex3f(0, 100, 0);
	glTexCoord2f(1, 1); glVertex3f(100, 100, 0);
	glTexCoord2f(1, 0); glVertex3f(100, 0, 0);
	glEnd();

	glDisable(GL_TEXTURE_2D);
	glPopMatrix();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glMatrixMode(GL_MODELVIEW);

}

static void ThirdLoop(Window& win)
{
	GLuint tex = loadBMP("cat.bmp");
	auto size = win.getWindowSize();
	win.beginDraw();
	while (running)
	{
		if (win.isClosing())
			running = false;

		glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);         // Clear the color buffer (background)

		DrawImage(size, tex);
		win.render();

		Update();
	}
}

void Run()
{
	//Get display information
	Display primaryDisplay = Displays::getPrimary();
	Size<int> displaySize = primaryDisplay.getPhysicalSize();
	VideoMode videoMode = primaryDisplay.getBestVideoMode();

	//create a placebo window, then create a fullscreen window with the full properties
	Window* mainwindow = new Window(videoMode.getSize().width, videoMode.getSize().height, "One", E3D_WINDOW_MODE_NOTCREATED);
	mainwindow->setModeBorderless();
	//mainwindow->setPosition(100, 100); //useless in fullscreen
	mainwindow->show();

	//TODO when writing the Threading class, make sure to run this BEFORE creating the next window
	thread w1(ThreadLoop, mainwindow);

	Window* secondwindow = new Window(window_width, window_height, "Two");
	secondwindow->show();
	secondwindow->setPosition(100, 100);

	thread w2(ThreadLoop, secondwindow);

	Window thirdwindow(window_width, window_height, "Three");
	thirdwindow.show();
	thirdwindow.setPosition(300, 300);

	thread w3(ThirdLoop, thirdwindow);
	//ThirdLoop(thirdwindow);

	while (running)
	{
		glfwWaitEvents(); //necessary because some events must process on the main thread
	}

	mainwindow->hide();
	secondwindow->hide();

	w1.join();
	w2.join();

	delete mainwindow; //will call the destructor and the dispose() method
	delete secondwindow;
}

int main(int argc, char** argv)
{
	EPITOME::Initialize();

	Run();

	EPITOME::Exit();
}

#ifdef WINDOWS
#include <windows.h>
#include <shellapi.h>
#ifdef _DEBUG
#pragma comment(linker, "/subsystem:console") //display a debug console to show warnings and errors, etc.
#endif
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
{
	LPWSTR *szArglist;
	int argc;
	char** argv;
	szArglist = CommandLineToArgvW(GetCommandLineW(), &argc);
	argv = (char**)szArglist;

	main(argc, argv);
}

#endif<commit_msg>Made file assert where it should exist. Still shows white texture, but I have to go to bed. I've tried.<commit_after>#include <epitome-core.h>
#include <iostream>
#include <thread>
using namespace EPITOME;

#define window_width 640
#define window_height 480

static bool running = true;
static bool enter_pressed = false;

static void E3DKey(Window& win, Keys key, KeyState state)
{
	if (key == KEY_ESCAPE && state == KEYS_RELEASED) //this is in case we throw more keys in this loop
		win.close();
	if (key == KEY_ENTER && state == KEYS_PRESSED)
		enter_pressed = true;
	if (key == KEY_ENTER && state == KEYS_RELEASED)
		enter_pressed = false;
}

static void ErrorFn(int error, const char* description)
{
	fputs(description, stderr);
}

static void onMouseMove(Window window, Point<double> m1)
{
	fprintf(stdout, "Mouse (%s): %i %i\r\n", window.getTitle(), (int)m1.x, (int)m1.y);
}

static void ThreadLoop(Window* window)
{
	//set a few events
	window->keyboard->onKeyReleased(Keys::KEY_ESCAPE, E3DKey);
	window->keyboard->onKeyPressed(KEY_ENTER, E3DKey);
	window->keyboard->onKeyReleased(KEY_ENTER, E3DKey);
	window->mouse->onMove(onMouseMove);

	auto size = window->getBufferSize();
	auto winsize = window->getWindowSize();
	window->beginDraw();

	/*glViewport(0, 0, size.width, size.height);
	glMatrixMode(GL_PROJECTION);
	glEnable(GL_DEPTH_TEST);
	gluPerspective(45, (float)size.width / (float)size.height, .1, 100);
	glMatrixMode(GL_MODELVIEW);
	glfwSwapInterval(1);*/

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(0, size.width - 1, size.height - 1, 0);
	// Here we use orthographic projection
	glPopMatrix();
	// Back to the projection we were using before
	glMatrixMode(GL_MODELVIEW);  // Best switch back to modelview

	glViewport(0, 0, size.width, size.height);
	glfwSwapInterval(1);

	GLdouble outx, outy, outz;
	GLdouble outx2, outy2, outz2;
	GLint viewport[4];
	GLdouble modelview[16], projection[16];
	glGetIntegerv(GL_VIEWPORT, viewport);
	glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
	glGetDoublev(GL_PROJECTION_MATRIX, projection);

	while (running)
	{
		if (window->isClosing())
			running = false;

		glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);         // Clear the color buffer (background)
		Point<double> mPos = window->mouse->getPosition();

		GLfloat b = (window->keyboard->isKeyDown(Keys::KEY_SPACE)) ? 1.0f : 0.0f;
		GLfloat r = (enter_pressed) ? 1.0f : 0.0f;

		//find the 40x40 pixel square, inverting the y axis
		gluUnProject(mPos.x-20, size.height-mPos.y-20, 0.0, modelview, projection, viewport, &outx, &outy, &outz);
		gluUnProject(mPos.x+20, size.height-mPos.y+20, 0.0, modelview, projection, viewport, &outx2, &outy2, &outz2);

		// Draw the square
		glBegin(GL_QUADS);
		glColor3f(b, 1.0f, r);
		glVertex2f(outx, outy);
		glVertex2f(outx2, outy);
		glVertex2f(outx2, outy2);
		glVertex2f(outx, outy2);
		glEnd();

		// Swap buffers (color buffers, makes previous render visible)
		window->render();

		// Increase angle to rotate
		//angle += 0.25;

		//checks for events
		Update();
	}
	glfwMakeContextCurrent(NULL);
	running = false;
}

GLuint loadBMP(const char * imagepath)
{
	// Data read from the header of the BMP file
	unsigned char header[54]; // Each BMP file begins by a 54-bytes header
	unsigned int dataPos;     // Position in the file where the actual data begins
	unsigned int width, height;
	unsigned int imageSize;   // = width*height*3
							  // Actual RGB data
	unsigned char * data;
	// Open the file
	FILE * file = fopen(imagepath, "rb");
	if (!file) {
		return 0;
	}
	if (fread(header, 1, 54, file) != 54) { // If not 54 bytes read : problem
		// Not a correct BMP file
		return 0;
	}
	if (header[0] != 'B' || header[1] != 'M') {
		// Not a correct BMP file
		return 0;
	}

	// Read ints from the byte array
	dataPos = *(int*)&(header[0x0A]);
	imageSize = *(int*)&(header[0x22]);
	width = *(int*)&(header[0x12]);
	height = *(int*)&(header[0x16]);
	// Some BMP files are misformatted, guess missing information
	if (imageSize == 0)    imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
	if (dataPos == 0)      dataPos = 54; // The BMP header is done that way

	// Create a buffer
	data = new unsigned char[imageSize];

	// Read the actual data from the file into the buffer
	fread(data, 1, imageSize, file);

	//Everything is in memory now, the file can be closed
	fclose(file);

	// Bind to dummy texture beforehand
	glBindTexture(GL_TEXTURE_2D, 0);

	// Create one OpenGL texture
	GLuint textureID;
	glGenTextures(1, &textureID);

	// "Bind" the newly created texture : all future texture functions will modify this texture
	glBindTexture(GL_TEXTURE_2D, textureID);

	// Give the image to OpenGL
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	return textureID;
}

void DrawImage(const Size<int>& size, GLuint texture) {
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0.0, size.width, 0.0, size.height, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	glLoadIdentity();
	glDisable(GL_LIGHTING);

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture);

	// Draw a textured quad
	glBegin(GL_QUADS);
	glTexCoord2f(0, 0); glVertex3f(0, 0, 0);
	glTexCoord2f(0, 1); glVertex3f(0, 100, 0);
	glTexCoord2f(1, 1); glVertex3f(100, 100, 0);
	glTexCoord2f(1, 0); glVertex3f(100, 0, 0);
	glEnd();

	glDisable(GL_TEXTURE_2D);
	glPopMatrix();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glMatrixMode(GL_MODELVIEW);

}

static void ThirdLoop(Window& win)
{
	GLuint tex = loadBMP("cat.bmp");
	auto size = win.getWindowSize();
	win.beginDraw();
	while (running)
	{
		if (win.isClosing())
			running = false;

		glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);         // Clear the color buffer (background)

		DrawImage(size, tex);
		win.render();

		Update();
	}
}

void Run()
{
	//Get display information
	Display primaryDisplay = Displays::getPrimary();
	Size<int> displaySize = primaryDisplay.getPhysicalSize();
	VideoMode videoMode = primaryDisplay.getBestVideoMode();

	//create a placebo window, then create a fullscreen window with the full properties
	Window* mainwindow = new Window(videoMode.getSize().width, videoMode.getSize().height, "One", E3D_WINDOW_MODE_NOTCREATED);
	mainwindow->setModeBorderless();
	//mainwindow->setPosition(100, 100); //useless in fullscreen
	mainwindow->show();

	//TODO when writing the Threading class, make sure to run this BEFORE creating the next window
	thread w1(ThreadLoop, mainwindow);

	Window* secondwindow = new Window(window_width, window_height, "Two");
	secondwindow->show();
	secondwindow->setPosition(100, 100);

	thread w2(ThreadLoop, secondwindow);

	Window thirdwindow(window_width, window_height, "Three");
	thirdwindow.show();
	thirdwindow.setPosition(300, 300);

	//thread w3(ThirdLoop, thirdwindow);
	ThirdLoop(thirdwindow);

	while (running)
	{
		glfwWaitEvents(); //necessary because some events must process on the main thread
	}

	mainwindow->hide();
	secondwindow->hide();

	w1.join();
	w2.join();

	delete mainwindow; //will call the destructor and the dispose() method
	delete secondwindow;
}

int main(int argc, char** argv)
{
	EPITOME::Initialize();

	Run();

	EPITOME::Exit();
}

#ifdef WINDOWS
#include <windows.h>
#include <shellapi.h>
#ifdef _DEBUG
#pragma comment(linker, "/subsystem:console") //display a debug console to show warnings and errors, etc.
#endif
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
{
	LPWSTR *szArglist;
	int argc;
	char** argv;
	szArglist = CommandLineToArgvW(GetCommandLineW(), &argc);
	argv = (char**)szArglist;

	main(argc, argv);
}

#endif<|endoftext|>


<commit_before>//----------------------------------*-C++-*----------------------------------//
/*!
 * \file   mc_driver/Manager.cc
 * \author Thomas M. Evans
 * \date   Wed Jun 18 11:21:16 2014
 * \brief  Manager member definitions.
 * \note   Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
 */
//---------------------------------------------------------------------------//

#include <fstream>
#include <iomanip>

#include "Teuchos_XMLParameterListHelpers.hpp"

#include "harness/DBC.hh"
#include "comm/Timing.hh"
#include "comm/global.hh"
#include "utils/Serial_HDF5_Writer.hh"
#include "utils/Parallel_HDF5_Writer.hh"
#include "solvers/LinAlgTypedefs.hh"
#include "mc/Fission_Source.hh"
#include "mc/Uniform_Source.hh"
#include "mc/KCode_Solver.hh"
#include "mc/Anderson_Solver.hh"
#include "Manager.hh"

namespace mc
{

//---------------------------------------------------------------------------//
// PRIVATE TEMPLATE FUNCTIONS
//---------------------------------------------------------------------------//
/*!
 * \brief Build an Anderson solver.
 */
template<class T>
void Manager::build_anderson(SP_Transporter    transporter,
                             SP_Fission_Source source)
{
    // make the solver
    auto anderson = std::make_shared< profugus::Anderson_Solver<T> >(d_db);

    // set the solver
    anderson->set(transporter, source);

    // assign the base solver
    d_keff_solver = anderson;
}

//---------------------------------------------------------------------------//
// CONSTRUCTOR
//---------------------------------------------------------------------------//
/*!
 * \brief Constructor.
 */
Manager::Manager()
    : d_node(profugus::node())
    , d_nodes(profugus::nodes())
{
}

//---------------------------------------------------------------------------//
/*!
 * \brief Setup the problem.
 * \param xml_file
 */
void Manager::setup(const std::string &xml_file)
{
    SCOPED_TIMER("Manager.setup");

    SCREEN_MSG("Reading xml file -> " << xml_file);
    SCREEN_MSG("Building and initializing geometry, physics, "
               << "variance reduction, and tallies");

    // use the problem builder to setup the problem
    Problem_Builder builder;
    builder.setup(xml_file);

    // get the problem database from the problem-builder
    d_db = builder.problem_db();
    CHECK(!d_db.is_null());

    // store the problem name
    d_problem_name = d_db->get("problem_name", std::string("MC"));
    d_db->setName(d_problem_name + "-PROBLEM");

    // get the geometry and physics
    d_geometry = builder.get_geometry();
    d_physics  = builder.get_physics();
    CHECK(d_geometry);
    CHECK(d_physics);

    // output the geometry
    if (d_db->get<bool>("output_geometry", false))
    {
        std::ostringstream g;
        g << d_db->get<std::string>("problem_name") << "_geo.out";

        if (d_node == 0)
        {
            // geo file
            std::ofstream gfile(g.str().c_str(), std::ofstream::out);

            // output the geometry
            d_geometry->array().output(gfile);
        }
    }

    // get the variance reduction
    auto var_reduction = builder.get_var_reduction();
    CHECK(var_reduction);

    // get the external source shape (it could be null)
    auto shape = builder.get_source_shape();

    // problem type
    std::string prob_type = shape ? "fixed" : "eigenvalue";

    // set the problem type in the final db
    d_db->set("problem_type", prob_type);

    // build the random controller
    d_rnd_control = std::make_shared<RNG_Control_t>(
        d_db->get<int>("seed", 32442));

    SCREEN_MSG("Building " << prob_type << " solver");

    // get the tallier
    SP_Tallier tallier = builder.get_tallier();

    // make the transporter
    SP_Transporter transporter(std::make_shared<Transporter_t>(
                                   d_db, d_geometry, d_physics));
    transporter->set(tallier);
    transporter->set(var_reduction);

    // build the appropriate solver (default is eigenvalue)
    if (prob_type == "eigenvalue")
    {
        // make the fission source
        std::shared_ptr<profugus::Fission_Source> source(
            std::make_shared<profugus::Fission_Source>(
                d_db, d_geometry, d_physics, d_rnd_control));

        // >>> determine eigensolver

        // Anderson
        if (d_db->isSublist("anderson_db"))
        {
            // determine the trilinos implementation
            auto &adb  = d_db->sublist("anderson_db");
            auto  impl = adb.get("trilinos_implementation",
                                 std::string("epetra"));

            VALIDATE(impl == "epetra" || impl == "tpetra", "Invalid "
                     << "trilinos_implementation " << impl << " must be "
                     << "epetra or tpetra");

            if (impl == "epetra")
            {
                build_anderson<profugus::EpetraTypes>(transporter, source);
            }
            else
            {
                build_anderson<profugus::TpetraTypes>(transporter, source);
            }
        }

        // Standard K-Code
        else
        {
            // make the solver
            auto kcode_solver = std::make_shared<profugus::KCode_Solver>(d_db);

            // set the solver
            kcode_solver->set(transporter, source);

            // set hybrid acceleration
            kcode_solver->set(builder.get_acceleration());

            // assign the base solver
            d_keff_solver = kcode_solver;
        }

        // assign the base solver
        d_solver = d_keff_solver;
    }
    else if (prob_type == "fixed")
    {
        // make the uniform source
        std::shared_ptr<profugus::Uniform_Source> source(
            std::make_shared<profugus::Uniform_Source>(
                d_db, d_geometry, d_physics, d_rnd_control));
        source->build_source(shape);

        // make the solver
        d_fixed_solver = std::make_shared<Fixed_Source_Solver_t>();

        // set it
        d_fixed_solver->set(transporter, source);

        // assign the base solver
        d_solver = d_fixed_solver;
    }
    else
    {
        throw profugus::assertion(
            "Undefined problem type; choose eigenvalue or fixed");
    }

    ENSURE(d_geometry);
    ENSURE(d_physics);
    ENSURE(d_solver);
}

//---------------------------------------------------------------------------//
/*!
 * \brief Solve the problem.
 */
void Manager::solve()
{
    if (d_db->get<bool>("do_transport", true))
    {
        SCOPED_TIMER("Manager.solve");

        SCREEN_MSG("Executing solver");

        // run the appropriate solver
        if (d_keff_solver)
        {
            CHECK(!d_fixed_solver);
            d_keff_solver->solve();
        }
        else if (d_fixed_solver)
        {
            CHECK(!d_keff_solver);
            d_fixed_solver->solve();
        }
        else
        {
            throw profugus::assertion("No legitimate solver built");
        }
    }
}

//---------------------------------------------------------------------------//
/*!
 * \brief Do output.
 */
void Manager::output()
{
    using std::string;

    SCOPED_TIMER("Manager.output");

    SCREEN_MSG("Outputting data");

    // >>> OUTPUT FINAL DATABASE

    // output the final database
    if (d_node == 0)
    {
        std::ostringstream m;
        m << d_problem_name << "_db.xml";
        Teuchos::writeParameterListToXmlFile(*d_db, m.str());
    }

    profugus::global_barrier();

    // >>> OUTPUT SOLUTION (only available if HDF5 is on)
#ifdef USE_HDF5

    // Output filename
    std::ostringstream m;
    m << d_problem_name << "_output.h5";
    string outfile = m.str();

    // scalar output for kcode
    if (d_keff_solver)
    {
        // get the kcode tally
        auto keff = d_keff_solver->keff_tally();
        CHECK(keff);

        // make the hdf5 file
        profugus::Serial_HDF5_Writer writer;
        writer.open(outfile);

        // output scalar quantities
        writer.begin_group("keff");

        writer.write(string("mean"), keff->mean());
        writer.write(string("variance"), keff->variance());
        writer.write(string("num_active_cycles"),
                     static_cast<int>(keff->cycle_count()));
        writer.write(string("cycle_estimates"), keff->all_keff());

        // do diagnostics on acceleration if it exists
        if (d_keff_solver->acceleration())
        {
            d_keff_solver->acceleration()->diagnostics(writer);
        }

        writer.end_group();

        writer.close();
    }

#endif // USE_HDF5
}

} // end namespace mc

//---------------------------------------------------------------------------//
//                 end of Manager.cc
//---------------------------------------------------------------------------//
<commit_msg>Hooking KDE fission source up to manager<commit_after>//----------------------------------*-C++-*----------------------------------//
/*!
 * \file   mc_driver/Manager.cc
 * \author Thomas M. Evans
 * \date   Wed Jun 18 11:21:16 2014
 * \brief  Manager member definitions.
 * \note   Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
 */
//---------------------------------------------------------------------------//

#include <fstream>
#include <iomanip>

#include "Teuchos_XMLParameterListHelpers.hpp"

#include "harness/DBC.hh"
#include "comm/Timing.hh"
#include "comm/global.hh"
#include "utils/Serial_HDF5_Writer.hh"
#include "utils/Parallel_HDF5_Writer.hh"
#include "solvers/LinAlgTypedefs.hh"
#include "mc/Fission_Source.hh"
#include "mc/KDE_Fission_Source.hh"
#include "mc/Uniform_Source.hh"
#include "mc/KCode_Solver.hh"
#include "mc/Anderson_Solver.hh"
#include "Manager.hh"

namespace mc
{

//---------------------------------------------------------------------------//
// PRIVATE TEMPLATE FUNCTIONS
//---------------------------------------------------------------------------//
/*!
 * \brief Build an Anderson solver.
 */
template<class T>
void Manager::build_anderson(SP_Transporter    transporter,
                             SP_Fission_Source source)
{
    // make the solver
    auto anderson = std::make_shared< profugus::Anderson_Solver<T> >(d_db);

    // set the solver
    anderson->set(transporter, source);

    // assign the base solver
    d_keff_solver = anderson;
}

//---------------------------------------------------------------------------//
// CONSTRUCTOR
//---------------------------------------------------------------------------//
/*!
 * \brief Constructor.
 */
Manager::Manager()
    : d_node(profugus::node())
    , d_nodes(profugus::nodes())
{
}

//---------------------------------------------------------------------------//
/*!
 * \brief Setup the problem.
 * \param xml_file
 */
void Manager::setup(const std::string &xml_file)
{
    SCOPED_TIMER("Manager.setup");

    SCREEN_MSG("Reading xml file -> " << xml_file);
    SCREEN_MSG("Building and initializing geometry, physics, "
               << "variance reduction, and tallies");

    // use the problem builder to setup the problem
    Problem_Builder builder;
    builder.setup(xml_file);

    // get the problem database from the problem-builder
    d_db = builder.problem_db();
    CHECK(!d_db.is_null());

    // store the problem name
    d_problem_name = d_db->get("problem_name", std::string("MC"));
    d_db->setName(d_problem_name + "-PROBLEM");

    // get the geometry and physics
    d_geometry = builder.get_geometry();
    d_physics  = builder.get_physics();
    CHECK(d_geometry);
    CHECK(d_physics);

    // output the geometry
    if (d_db->get<bool>("output_geometry", false))
    {
        std::ostringstream g;
        g << d_db->get<std::string>("problem_name") << "_geo.out";

        if (d_node == 0)
        {
            // geo file
            std::ofstream gfile(g.str().c_str(), std::ofstream::out);

            // output the geometry
            d_geometry->array().output(gfile);
        }
    }

    // get the variance reduction
    auto var_reduction = builder.get_var_reduction();
    CHECK(var_reduction);

    // get the external source shape (it could be null)
    auto shape = builder.get_source_shape();

    // problem type
    std::string prob_type = shape ? "fixed" : "eigenvalue";

    // set the problem type in the final db
    d_db->set("problem_type", prob_type);

    // build the random controller
    d_rnd_control = std::make_shared<RNG_Control_t>(
        d_db->get<int>("seed", 32442));

    SCREEN_MSG("Building " << prob_type << " solver");

    // get the tallier
    SP_Tallier tallier = builder.get_tallier();

    // make the transporter
    SP_Transporter transporter(std::make_shared<Transporter_t>(
                                   d_db, d_geometry, d_physics));
    transporter->set(tallier);
    transporter->set(var_reduction);

    // build the appropriate solver (default is eigenvalue)
    if (prob_type == "eigenvalue")
    {
        std::shared_ptr<profugus::Fission_Source> source;
        if (d_db->isType<bool>("use_kde") && d_db->get<bool>("use_kde"))
        {
            SCREEN_MSG("Using KDE fission source");
            source =
                std::make_shared<profugus::KDE_Fission_Source>(d_db, d_geometry,
                                                               d_physics,
                                                               d_rnd_control);
        }
        else
        {
            SCREEN_MSG("Using traditional fission source");
            source =
                std::make_shared<profugus::Fission_Source>(d_db, d_geometry,
                                                           d_physics,
                                                           d_rnd_control);
        }
        CHECK(source);

        // >>> determine eigensolver

        // Anderson
        if (d_db->isSublist("anderson_db"))
        {
            // determine the trilinos implementation
            auto &adb  = d_db->sublist("anderson_db");
            auto  impl = adb.get("trilinos_implementation",
                                 std::string("epetra"));

            VALIDATE(impl == "epetra" || impl == "tpetra", "Invalid "
                     << "trilinos_implementation " << impl << " must be "
                     << "epetra or tpetra");

            if (impl == "epetra")
            {
                build_anderson<profugus::EpetraTypes>(transporter, source);
            }
            else
            {
                build_anderson<profugus::TpetraTypes>(transporter, source);
            }
        }

        // Standard K-Code
        else
        {
            // make the solver
            auto kcode_solver = std::make_shared<profugus::KCode_Solver>(d_db);

            // set the solver
            kcode_solver->set(transporter, source);

            // set hybrid acceleration
            kcode_solver->set(builder.get_acceleration());

            // assign the base solver
            d_keff_solver = kcode_solver;
        }

        // assign the base solver
        d_solver = d_keff_solver;
    }
    else if (prob_type == "fixed")
    {
        // make the uniform source
        std::shared_ptr<profugus::Uniform_Source> source(
            std::make_shared<profugus::Uniform_Source>(
                d_db, d_geometry, d_physics, d_rnd_control));
        source->build_source(shape);

        // make the solver
        d_fixed_solver = std::make_shared<Fixed_Source_Solver_t>();

        // set it
        d_fixed_solver->set(transporter, source);

        // assign the base solver
        d_solver = d_fixed_solver;
    }
    else
    {
        throw profugus::assertion(
            "Undefined problem type; choose eigenvalue or fixed");
    }

    ENSURE(d_geometry);
    ENSURE(d_physics);
    ENSURE(d_solver);
}

//---------------------------------------------------------------------------//
/*!
 * \brief Solve the problem.
 */
void Manager::solve()
{
    if (d_db->get<bool>("do_transport", true))
    {
        SCOPED_TIMER("Manager.solve");

        SCREEN_MSG("Executing solver");

        // run the appropriate solver
        if (d_keff_solver)
        {
            CHECK(!d_fixed_solver);
            d_keff_solver->solve();
        }
        else if (d_fixed_solver)
        {
            CHECK(!d_keff_solver);
            d_fixed_solver->solve();
        }
        else
        {
            throw profugus::assertion("No legitimate solver built");
        }
    }
}

//---------------------------------------------------------------------------//
/*!
 * \brief Do output.
 */
void Manager::output()
{
    using std::string;

    SCOPED_TIMER("Manager.output");

    SCREEN_MSG("Outputting data");

    // >>> OUTPUT FINAL DATABASE

    // output the final database
    if (d_node == 0)
    {
        std::ostringstream m;
        m << d_problem_name << "_db.xml";
        Teuchos::writeParameterListToXmlFile(*d_db, m.str());
    }

    profugus::global_barrier();

    // >>> OUTPUT SOLUTION (only available if HDF5 is on)
#ifdef USE_HDF5

    // Output filename
    std::ostringstream m;
    m << d_problem_name << "_output.h5";
    string outfile = m.str();

    // scalar output for kcode
    if (d_keff_solver)
    {
        // get the kcode tally
        auto keff = d_keff_solver->keff_tally();
        CHECK(keff);

        // make the hdf5 file
        profugus::Serial_HDF5_Writer writer;
        writer.open(outfile);

        // output scalar quantities
        writer.begin_group("keff");

        writer.write(string("mean"), keff->mean());
        writer.write(string("variance"), keff->variance());
        writer.write(string("num_active_cycles"),
                     static_cast<int>(keff->cycle_count()));
        writer.write(string("cycle_estimates"), keff->all_keff());

        // do diagnostics on acceleration if it exists
        if (d_keff_solver->acceleration())
        {
            d_keff_solver->acceleration()->diagnostics(writer);
        }

        writer.end_group();

        writer.close();
    }

#endif // USE_HDF5
}

} // end namespace mc

//---------------------------------------------------------------------------//
//                 end of Manager.cc
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#include <string>
#include <sstream>
#include "FileSystem.h"
#include "curl-config-win32.h"
#include "curl/curl.h"
#include "zip/zip.h"

#ifdef _WIN32
#include "Process.h"
#define execl _execl
#endif

#define INFO(msg) (std::cout << "[INFO] " << (msg) << std::endl)
#define INFOS(msg) (std::cout << "[INFO] " << msg << std::endl)
#define FATAL(msg) (std::cerr << "[FATAL] " << (msg) << std::endl, throw std::runtime_error(msg))
#ifdef _DEBUG
#define CONTINUE (std::cout << "Press enter to continue.", std::cin.ignore(1))
#else
#define CONTINUE
#endif

size_t cbWrite(void *buffer, size_t size, size_t nmemb, void *userp) {
	size_t nBytes = size * nmemb;
	reinterpret_cast<std::string *>(userp)->append(reinterpret_cast<char *>(buffer), nBytes);
	return nBytes;
}

std::string GetRemote(const char *url) {
	std::string data;
	auto handle = curl_easy_init();
	if(handle == NULL) { FATAL("failed to init cURL easy handle"); }
	if(curl_easy_setopt(handle, CURLOPT_URL, url) != CURLE_OK) { FATAL("failed to set CURLOPT_URL"); }
	if(curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, cbWrite) != CURLE_OK) { FATAL("failed to set CURLOPT_WRITEFUNCTION"); }
	if(curl_easy_setopt(handle, CURLOPT_WRITEDATA, &data) != CURLE_OK) { FATAL("failed to set CURLOPT_WRITEDATA"); }
	if(curl_easy_setopt(handle, CURLOPT_FILETIME, 1) != CURLE_OK) { FATAL("failed to set CURLOPT_FILETIME"); }
	if(curl_easy_perform(handle) != CURLE_OK) { FATAL("failed to perform cURL request"); }
	curl_easy_cleanup(handle);
	return data;
}
std::string GetRemote(const std::string &url) { return GetRemote(url.c_str()); }
std::string GetRemote(std::string &&url) { return GetRemote(url.c_str()); }

void UpdateLauncher() {

	INFO("checking for newer version of launcher");

	const std::string versionPath = FileSystem::GetAppDir() + "/version";
	auto localVersion = FileSystem::FileExists(versionPath) ? FileSystem::ReadFile(versionPath) : "";

	auto remoteVersion = GetRemote("http://shockk.me/sub-terra/files/launcher-latest");
	std::istringstream iss(remoteVersion);
	std::getline(iss, remoteVersion);

	if(localVersion != remoteVersion) {
		INFO("newer version of launcher detected");
		INFOS("downloading launcher v" << remoteVersion);

		auto launcher = GetRemote("http://shockk.me/sub-terra/files/launcher-" + remoteVersion + ".exe");

		INFO("writing new launcher to disk");

		const std::string appPath = FileSystem::GetApp();
		const std::string old = appPath + ".old";
		if(FileSystem::FileExists(old)) { FileSystem::RemoveFile(old); }
		FileSystem::Rename(appPath, appPath + ".old");
		FileSystem::WriteFile(appPath, launcher);
		FileSystem::WriteFile(versionPath, remoteVersion);

		INFO("restarting launcher");

		curl_global_cleanup();

		auto sz = appPath.c_str();
		execl(sz, sz, 0);
	}
}

void UpdateSubTerra() {
	const std::string appDir = FileSystem::GetAppDir();
	const std::string subTerraDir = appDir + "/sub-terra";
	const std::string archiveName = "sub-terra-latest.zip";
	const std::string archivePath = appDir + '/' + archiveName;

	INFO("checking for newer version of Sub-Terra");

	const std::string versionPath = appDir + "/sub-terra-version";
	auto localVersion = FileSystem::FileExists(versionPath) ? FileSystem::ReadFile(versionPath) : "";

	auto remoteVersion = GetRemote("http://shockk.me/sub-terra/files/sub-terra-latest");
	std::istringstream iss(remoteVersion);
	std::getline(iss, remoteVersion);

	if(localVersion != remoteVersion) {
		INFO("newer version of Sub-Terra detected");
		INFOS("downloading Sub-Terra v" << remoteVersion);

		auto archiveData = GetRemote("http://shockk.me/sub-terra/files/sub-terra-" + remoteVersion + ".zip");

		INFO("writing archive to disk");
		FileSystem::WriteFile(archivePath, archiveData);
		FileSystem::WriteFile(versionPath, remoteVersion);

		FileSystem::CreateDir(subTerraDir);

		struct zip *archive = zip_open(archivePath.c_str(), ZIP_CHECKCONS, NULL);
		if(archive == NULL) { FATAL("failed to open archive `" + archiveName + '`'); }
		INFO("opened archive");

		for(int i = 0; i < zip_get_num_files(archive); ++i) {
			const char *szName = zip_get_name(archive, i, ZIP_FL_ENC_GUESS);
			if(szName == NULL) { FATAL("failed to get file name in `" + archiveName + "` at index " + std::to_string(i)); }
			std::string name(szName);

			if(name.back() == '/') { /* directory */
				FileSystem::CreateDir(subTerraDir + '/' + name);
				INFOS("D: " << name);
			} else {
				struct zip_stat st;
				if(zip_stat_index(archive, i, 0, &st) != 0) { FATAL("failed to stat `" + name + "` in `" + archiveName + '`'); }

				struct zip_file *fh = zip_fopen_index(archive, i, 0);
				if(fh == NULL) { FATAL("failed to open `" + name + "` in `" + archiveName + '`'); }

				char *buf = new char[st.size];

				zip_int64_t len = zip_fread(fh, buf, st.size);
				if(len == -1) { FATAL("failed to read `" + name + "` in `" + archiveName + '`'); }

				FileSystem::WriteFile(subTerraDir + '/' + name, std::string(buf, len));

				delete buf;

				INFOS("F: " << name);
			}
		}

		if(zip_close(archive) != 0) { FATAL("failed to close archive `" + archiveName + '`'); }
		INFO("closed archive");
	}
}

int main(int argc, char **argv) {
	if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { FATAL("failed to init cURL"); }

	UpdateLauncher();
	UpdateSubTerra();

	curl_global_cleanup();

	const std::string path = FileSystem::GetAppDir() + "/sub-terra/Sub-Terra.exe";
	auto sz = path.c_str();
	execl(sz, sz, 0);

	return 0;
}
<commit_msg>Fixed incorrect deletion.<commit_after>#include <string>
#include <sstream>
#include "FileSystem.h"
#include "curl-config-win32.h"
#include "curl/curl.h"
#include "zip/zip.h"

#ifdef _WIN32
#include "Process.h"
#define execl _execl
#endif

#define INFO(msg) (std::cout << "[INFO] " << (msg) << std::endl)
#define INFOS(msg) (std::cout << "[INFO] " << msg << std::endl)
#define FATAL(msg) (std::cerr << "[FATAL] " << (msg) << std::endl, throw std::runtime_error(msg))
#ifdef _DEBUG
#define CONTINUE (std::cout << "Press enter to continue.", std::cin.ignore(1))
#else
#define CONTINUE
#endif

size_t cbWrite(void *buffer, size_t size, size_t nmemb, void *userp) {
	size_t nBytes = size * nmemb;
	reinterpret_cast<std::string *>(userp)->append(reinterpret_cast<char *>(buffer), nBytes);
	return nBytes;
}

std::string GetRemote(const char *url) {
	std::string data;
	auto handle = curl_easy_init();
	if(handle == NULL) { FATAL("failed to init cURL easy handle"); }
	if(curl_easy_setopt(handle, CURLOPT_URL, url) != CURLE_OK) { FATAL("failed to set CURLOPT_URL"); }
	if(curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, cbWrite) != CURLE_OK) { FATAL("failed to set CURLOPT_WRITEFUNCTION"); }
	if(curl_easy_setopt(handle, CURLOPT_WRITEDATA, &data) != CURLE_OK) { FATAL("failed to set CURLOPT_WRITEDATA"); }
	if(curl_easy_setopt(handle, CURLOPT_FILETIME, 1) != CURLE_OK) { FATAL("failed to set CURLOPT_FILETIME"); }
	if(curl_easy_perform(handle) != CURLE_OK) { FATAL("failed to perform cURL request"); }
	curl_easy_cleanup(handle);
	return data;
}
std::string GetRemote(const std::string &url) { return GetRemote(url.c_str()); }
std::string GetRemote(std::string &&url) { return GetRemote(url.c_str()); }

void UpdateLauncher() {

	INFO("checking for newer version of launcher");

	const std::string versionPath = FileSystem::GetAppDir() + "/version";
	auto localVersion = FileSystem::FileExists(versionPath) ? FileSystem::ReadFile(versionPath) : "";

	auto remoteVersion = GetRemote("http://shockk.me/sub-terra/files/launcher-latest");
	std::istringstream iss(remoteVersion);
	std::getline(iss, remoteVersion);

	if(localVersion != remoteVersion) {
		INFO("newer version of launcher detected");
		INFOS("downloading launcher v" << remoteVersion);

		auto launcher = GetRemote("http://shockk.me/sub-terra/files/launcher-" + remoteVersion + ".exe");

		INFO("writing new launcher to disk");

		const std::string appPath = FileSystem::GetApp();
		const std::string old = appPath + ".old";
		if(FileSystem::FileExists(old)) { FileSystem::RemoveFile(old); }
		FileSystem::Rename(appPath, appPath + ".old");
		FileSystem::WriteFile(appPath, launcher);
		FileSystem::WriteFile(versionPath, remoteVersion);

		INFO("restarting launcher");

		curl_global_cleanup();

		auto sz = appPath.c_str();
		execl(sz, sz, 0);
	}
}

void UpdateSubTerra() {
	const std::string appDir = FileSystem::GetAppDir();
	const std::string subTerraDir = appDir + "/sub-terra";
	const std::string archiveName = "sub-terra-latest.zip";
	const std::string archivePath = appDir + '/' + archiveName;

	INFO("checking for newer version of Sub-Terra");

	const std::string versionPath = appDir + "/sub-terra-version";
	auto localVersion = FileSystem::FileExists(versionPath) ? FileSystem::ReadFile(versionPath) : "";

	auto remoteVersion = GetRemote("http://shockk.me/sub-terra/files/sub-terra-latest");
	std::istringstream iss(remoteVersion);
	std::getline(iss, remoteVersion);

	if(localVersion != remoteVersion) {
		INFO("newer version of Sub-Terra detected");
		INFOS("downloading Sub-Terra v" << remoteVersion);

		auto archiveData = GetRemote("http://shockk.me/sub-terra/files/sub-terra-" + remoteVersion + ".zip");

		INFO("writing archive to disk");
		FileSystem::WriteFile(archivePath, archiveData);
		FileSystem::WriteFile(versionPath, remoteVersion);

		FileSystem::CreateDir(subTerraDir);

		struct zip *archive = zip_open(archivePath.c_str(), ZIP_CHECKCONS, NULL);
		if(archive == NULL) { FATAL("failed to open archive `" + archiveName + '`'); }
		INFO("opened archive");

		for(int i = 0; i < zip_get_num_files(archive); ++i) {
			const char *szName = zip_get_name(archive, i, ZIP_FL_ENC_GUESS);
			if(szName == NULL) { FATAL("failed to get file name in `" + archiveName + "` at index " + std::to_string(i)); }
			std::string name(szName);

			if(name.back() == '/') { /* directory */
				FileSystem::CreateDir(subTerraDir + '/' + name);
				INFOS("D: " << name);
			} else {
				struct zip_stat st;
				if(zip_stat_index(archive, i, 0, &st) != 0) { FATAL("failed to stat `" + name + "` in `" + archiveName + '`'); }

				struct zip_file *fh = zip_fopen_index(archive, i, 0);
				if(fh == NULL) { FATAL("failed to open `" + name + "` in `" + archiveName + '`'); }

				char *buf = new char[st.size];

				zip_int64_t len = zip_fread(fh, buf, st.size);
				if(len == -1) { FATAL("failed to read `" + name + "` in `" + archiveName + '`'); }

				FileSystem::WriteFile(subTerraDir + '/' + name, std::string(buf, len));

				delete[] buf;

				INFOS("F: " << name);
			}
		}

		if(zip_close(archive) != 0) { FATAL("failed to close archive `" + archiveName + '`'); }
		INFO("closed archive");
	}
}

int main(int argc, char **argv) {
	if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { FATAL("failed to init cURL"); }

	UpdateLauncher();
	UpdateSubTerra();

	curl_global_cleanup();

	const std::string path = FileSystem::GetAppDir() + "/sub-terra/Sub-Terra.exe";
	auto sz = path.c_str();
	execl(sz, sz, 0);

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dispatchhelper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:29:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#define __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_

//_______________________________________________
// my own includes

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_______________________________________________
// interface includes

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHHELPER_HPP_
#include <com/sun/star/frame/XDispatchHelper.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRESULTLISTENER_HPP_
#include <com/sun/star/frame/XDispatchResultListener.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTEVENT_HPP_
#include <com/sun/star/frame/DispatchResultEvent.hpp>
#endif

//_______________________________________________
// other includes

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// exported const

//_______________________________________________
// exported definitions

/**
    @short      implements an easy way for dispatches
    @descr      Dispatches are splitted into different parts:
                    - parsing of the URL
                    - searching for a dispatcgh object
                    - dispatching of the URL
                All these steps are done inside one method call here.
*/

class DispatchHelper : public css::lang::XTypeProvider
                     , public css::lang::XServiceInfo
                     , public css::frame::XDispatchHelper
                     , public css::frame::XDispatchResultListener // => XEventListener
                     , public ThreadHelpBase                      // must be the first base class!
                     , public ::cppu::OWeakObject                 // => XInterface, XWeak
{

    //-------------------------------------------
    // member

    private:

        /** global uno service manager.
            Can be used to create own needed services. */
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;

        /** used to wait for asynchronous listener callbacks. */
        ::osl::Condition m_aBlock;

        css::uno::Any m_aResult;

        css::uno::Reference< css::uno::XInterface > m_xBroadcaster;

    //-------------------------------------------
    // interface

    public:

        //---------------------------------------
        // ctor/dtor

                 DispatchHelper( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
        virtual ~DispatchHelper(                                                                     );

        //---------------------------------------
        // XInterface, XTypeProvider, XServiceInfo

        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        //---------------------------------------
        // XDispatchHelper
        virtual css::uno::Any SAL_CALL executeDispatch(
                                        const css::uno::Reference< css::frame::XDispatchProvider >& xDispatchProvider ,
                                        const ::rtl::OUString&                                      sURL              ,
                                        const ::rtl::OUString&                                      sTargetFrameName  ,
                                              sal_Int32                                             nSearchFlags      ,
                                        const css::uno::Sequence< css::beans::PropertyValue >&      lArguments        )
        throw(css::uno::RuntimeException);

        //---------------------------------------
        // XDispatchResultListener
        virtual void SAL_CALL dispatchFinished(
                                const css::frame::DispatchResultEvent& aResult )
        throw(css::uno::RuntimeException);

        //---------------------------------------
        // XEventListener
        virtual void SAL_CALL disposing(
                                const css::lang::EventObject& aEvent )
        throw(css::uno::RuntimeException);
};

}

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.3.32); FILE MERGED 2005/10/28 14:48:15 cd 1.3.32.1: #i55991# Warning free code changes for gcc<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dispatchhelper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 10:58:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#define __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_

//_______________________________________________
// my own includes

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_______________________________________________
// interface includes

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHHELPER_HPP_
#include <com/sun/star/frame/XDispatchHelper.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRESULTLISTENER_HPP_
#include <com/sun/star/frame/XDispatchResultListener.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTEVENT_HPP_
#include <com/sun/star/frame/DispatchResultEvent.hpp>
#endif

//_______________________________________________
// other includes

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// exported const

//_______________________________________________
// exported definitions

/**
    @short      implements an easy way for dispatches
    @descr      Dispatches are splitted into different parts:
                    - parsing of the URL
                    - searching for a dispatcgh object
                    - dispatching of the URL
                All these steps are done inside one method call here.
*/

class DispatchHelper : public css::lang::XTypeProvider
                     , public css::lang::XServiceInfo
                     , public css::frame::XDispatchHelper
                     , public css::frame::XDispatchResultListener // => XEventListener
                     , public ThreadHelpBase                      // must be the first base class!
                     , public ::cppu::OWeakObject                 // => XInterface, XWeak
{

    //-------------------------------------------
    // member

    private:

        /** global uno service manager.
            Can be used to create own needed services. */
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;

        /** used to wait for asynchronous listener callbacks. */
        ::osl::Condition m_aBlock;

        css::uno::Any m_aResult;

        css::uno::Reference< css::uno::XInterface > m_xBroadcaster;

    //-------------------------------------------
    // interface

    public:

        //---------------------------------------
        // ctor/dtor

                 DispatchHelper( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
        virtual ~DispatchHelper(                                                                     );

        //---------------------------------------
        // XInterface, XTypeProvider, XServiceInfo

        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        //---------------------------------------
        // XDispatchHelper
        virtual css::uno::Any SAL_CALL executeDispatch(
                                        const css::uno::Reference< css::frame::XDispatchProvider >& xDispatchProvider ,
                                        const ::rtl::OUString&                                      sURL              ,
                                        const ::rtl::OUString&                                      sTargetFrameName  ,
                                              sal_Int32                                             nSearchFlags      ,
                                        const css::uno::Sequence< css::beans::PropertyValue >&      lArguments        )
        throw(css::uno::RuntimeException);

        //---------------------------------------
        // XDispatchResultListener
        virtual void SAL_CALL dispatchFinished(
                                const css::frame::DispatchResultEvent& aResult )
        throw(css::uno::RuntimeException);

        //---------------------------------------
        // XEventListener
        virtual void SAL_CALL disposing(
                                const css::lang::EventObject& aEvent )
        throw(css::uno::RuntimeException);
};

}

#endif
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief X11 Platform.
 *//*--------------------------------------------------------------------*/

#include "tcuX11Platform.hpp"

#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"

#if defined (DEQP_SUPPORT_GLX)
#	include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
#	include "tcuX11EglPlatform.hpp"
#endif

#include <sys/utsname.h>

namespace tcu
{
namespace x11
{

class X11GLPlatform : public glu::Platform
{
public:
	void		registerFactory	(de::MovePtr<glu::ContextFactory> factory)
	{
		m_contextFactoryRegistry.registerFactory(factory.release());
	}
};

class VulkanLibrary : public vk::Library
{
public:
	VulkanLibrary (void)
		: m_library	("libvulkan.so.1")
		, m_driver	(m_library)
	{
	}

	const vk::PlatformInterface& getPlatformInterface (void) const
	{
		return m_driver;
	}

private:
	const tcu::DynamicFunctionLibrary	m_library;
	const vk::PlatformDriver			m_driver;
};

class X11VulkanPlatform : public vk::Platform
{
public:
	vk::Library* createLibrary (void) const
	{
		return new VulkanLibrary();
	}

	void describePlatform (std::ostream& dst) const
	{
		utsname		sysInfo;

		deMemset(&sysInfo, 0, sizeof(sysInfo));

		if (uname(&sysInfo) != 0)
			throw std::runtime_error("uname() failed");

		dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
		dst << "CPU: " << sysInfo.machine << "\n";
	}

	void getMemoryLimits (vk::PlatformMemoryLimits& limits) const
	{
		limits.totalSystemMemory					= 256*1024*1024;
		limits.totalDeviceLocalMemory				= 128*1024*1024;
		limits.deviceMemoryAllocationGranularity	= 64*1024;
		limits.devicePageSize						= 4096;
		limits.devicePageTableEntrySize				= 8;
		limits.devicePageTableHierarchyLevels		= 3;
	}
};

class X11Platform : public tcu::Platform
{
public:
							X11Platform			(void);
	bool					processEvents		(void) { return !m_eventState.getQuitFlag(); }
	const glu::Platform&	getGLPlatform		(void) const { return m_glPlatform; }

#if defined (DEQP_SUPPORT_EGL)
	const eglu::Platform&	getEGLPlatform		(void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL

	const vk::Platform&		getVulkanPlatform	(void) const { return m_vkPlatform; }

private:
	EventState				m_eventState;
#if defined (DEQP_SUPPORT_EGL)
	x11::egl::Platform		m_eglPlatform;
#endif // DEQP_SPPORT_EGL
	X11GLPlatform			m_glPlatform;
	X11VulkanPlatform		m_vkPlatform;
};

X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
	: m_eglPlatform	(m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
	m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
	m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}

} // x11
} // tcu

tcu::Platform* createPlatform (void)
{
	return new tcu::x11::X11Platform();
}
<commit_msg>x11: Call XInitThreads() am: 5d11c9d2c0<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief X11 Platform.
 *//*--------------------------------------------------------------------*/

#include "tcuX11Platform.hpp"

#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"

#if defined (DEQP_SUPPORT_GLX)
#	include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
#	include "tcuX11EglPlatform.hpp"
#endif

#include <sys/utsname.h>

namespace tcu
{
namespace x11
{

class X11GLPlatform : public glu::Platform
{
public:
	void		registerFactory	(de::MovePtr<glu::ContextFactory> factory)
	{
		m_contextFactoryRegistry.registerFactory(factory.release());
	}
};

class VulkanLibrary : public vk::Library
{
public:
	VulkanLibrary (void)
		: m_library	("libvulkan.so.1")
		, m_driver	(m_library)
	{
	}

	const vk::PlatformInterface& getPlatformInterface (void) const
	{
		return m_driver;
	}

private:
	const tcu::DynamicFunctionLibrary	m_library;
	const vk::PlatformDriver			m_driver;
};

class X11VulkanPlatform : public vk::Platform
{
public:
	vk::Library* createLibrary (void) const
	{
		return new VulkanLibrary();
	}

	void describePlatform (std::ostream& dst) const
	{
		utsname		sysInfo;

		deMemset(&sysInfo, 0, sizeof(sysInfo));

		if (uname(&sysInfo) != 0)
			throw std::runtime_error("uname() failed");

		dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
		dst << "CPU: " << sysInfo.machine << "\n";
	}

	void getMemoryLimits (vk::PlatformMemoryLimits& limits) const
	{
		limits.totalSystemMemory					= 256*1024*1024;
		limits.totalDeviceLocalMemory				= 128*1024*1024;
		limits.deviceMemoryAllocationGranularity	= 64*1024;
		limits.devicePageSize						= 4096;
		limits.devicePageTableEntrySize				= 8;
		limits.devicePageTableHierarchyLevels		= 3;
	}
};

class X11Platform : public tcu::Platform
{
public:
							X11Platform			(void);
	bool					processEvents		(void) { return !m_eventState.getQuitFlag(); }
	const glu::Platform&	getGLPlatform		(void) const { return m_glPlatform; }

#if defined (DEQP_SUPPORT_EGL)
	const eglu::Platform&	getEGLPlatform		(void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL

	const vk::Platform&		getVulkanPlatform	(void) const { return m_vkPlatform; }

private:
	EventState				m_eventState;
#if defined (DEQP_SUPPORT_EGL)
	x11::egl::Platform		m_eglPlatform;
#endif // DEQP_SPPORT_EGL
	X11GLPlatform			m_glPlatform;
	X11VulkanPlatform		m_vkPlatform;
};

X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
	: m_eglPlatform	(m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
	m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
	m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}

} // x11
} // tcu

tcu::Platform* createPlatform (void)
{
	// From man:XinitThreads(3):
	//
	//     The XInitThreads function initializes Xlib support for concurrent
	//     threads.  This function must be the first Xlib function
	//     a multi-threaded program calls, and it must complete before any other
	//     Xlib call is made.
	DE_CHECK_RUNTIME_ERR(XInitThreads() != 0);

	return new tcu::x11::X11Platform();
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "DT2Transient.h"
#include "Problem.h"

//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "nonlinear_solver.h"
#include "transient_system.h"
#include "numeric_vector.h"

// C++ Includes
#include <iomanip>

template<>
InputParameters validParams<DT2Transient>()
{
  InputParameters params = validParams<Transient>();
  params.addRequiredParam<Real>("e_tol","Target error tolerance.");
  params.addRequiredParam<Real>("e_max","Maximum acceptable error.");
  params.addParam<Real>("max_increase", 1.0e9,    "Maximum ratio that the time step can increase.");

  return params;
}

DT2Transient::DT2Transient(const std::string & name, InputParameters parameters) :
    Transient(name, parameters),
    _u_diff(NULL),
    _u1(NULL),
    _u2(NULL),
    _u_saved(NULL),
    _u_older_saved(NULL),
    _aux1(NULL),
    _aux_saved(NULL),
    _aux_older_saved(NULL),
    _e_tol(getParam<Real>("e_tol")),
    _e_max(getParam<Real>("e_max")),
    _max_increase(getParam<Real>("max_increase"))
{
}

DT2Transient::~DT2Transient()
{
}

void
DT2Transient::preExecute()
{
  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  _u1 = &nl_sys.add_vector("u1", true, GHOSTED);
  _u2 = &nl_sys.add_vector("u2", false, GHOSTED);
  _u_diff = &nl_sys.add_vector("u_diff", false, GHOSTED);

  _u_saved = &nl_sys.add_vector("u_saved", false, GHOSTED);
  _u_older_saved = &nl_sys.add_vector("u_older_saved", false, GHOSTED);

  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();
  _aux1 = &aux_sys.add_vector("aux1", true, GHOSTED);
  _aux_saved = &aux_sys.add_vector("aux_saved", false, GHOSTED);
  _aux_older_saved = &aux_sys.add_vector("aux_older_saved", false, GHOSTED);

  Transient::preExecute();
}

void
DT2Transient::preSolve()
{
  /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything?
  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();

  // save solution vectors
  *_u_saved = *nl_sys.current_local_solution;
  *_u_older_saved = *nl_sys.older_local_solution;

  *_aux_saved = *aux_sys.solution;
  *_aux_older_saved = *aux_sys.older_local_solution;

  _u_saved->close();
  _u_older_saved->close();
  _aux_saved->close();
  _aux_older_saved->close();

  // save dt
  _dt_full = _dt;
}

void
DT2Transient::postSolve()
{
  /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything?
  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();
  if (_converged)
  {
    // save the solution (for time step with dt)
    *_u1 = *nl_sys.current_local_solution;
    _u1->close();

    *_aux1 = *aux_sys.current_local_solution;
    _aux1->close();

    // take two steps with dt/2
    std::cout << "Taking two dt/2 time steps" << std::endl;

    // go back in time
    *nl_sys.current_local_solution = *_u_saved;
    *aux_sys.current_local_solution = *_aux_saved;
    nl_sys.current_local_solution->close();
    aux_sys.current_local_solution->close();

    _time -= _dt_full;

    _problem.computePostprocessors();

    // cut the time step in half
    _dt = _dt_full / 2;

    // 1. step
    _problem.onTimestepBegin();
    _time += _dt;

    std::cout << "  - 1. step" << std::endl;
    Moose::setSolverDefaults(_problem);
    nl_sys.solve();

    _converged = nl_sys.nonlinear_solver->converged;
    if (!_converged) return;
    nl_sys.update();

    _problem.copyOldSolutions();
    _problem.computePostprocessors();

    // 2. step
    _problem.onTimestepBegin();
    _time += _dt;

    std::cout << "  - 2. step" << std::endl;
    Moose::setSolverDefaults(_problem);
    nl_sys.solve();

    _converged = nl_sys.nonlinear_solver->converged;
    if (!_converged) return;
    nl_sys.update();

    *_u2 = *nl_sys.current_local_solution;
    _u2->close();

    // compute error
    *_u_diff = *_u2;
    *_u_diff -= *_u1;
    _u_diff->close();

    _error = (_u_diff->l2_norm() / std::max(_u1->l2_norm(), _u2->l2_norm())) / _dt_full;

    _dt = _dt_full;
    Transient::postSolve();
  }
}

bool
DT2Transient::lastSolveConverged()
{
  if (!_converged)
    return false;

  if (_error < _e_max)
    return true;
  else
    return false;
}

Real
DT2Transient::computeDT()
{
  if(_t_step < 2)
    return Transient::computeDT();

  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();

  if(lastSolveConverged())
  {
    Real new_dt = _dt_full * std::pow(_e_tol / _error, 1.0 / _problem.getNonlinearSystem().getTimeSteppingOrder());

    if (new_dt/_dt_full > _max_increase)
      _dt = _dt_full*_max_increase;
    else
      _dt = new_dt;

    *nl_sys.current_local_solution= *_u1;
    *nl_sys.old_local_solution = *_u1;
    *nl_sys.older_local_solution = *_u_saved;

    *aux_sys.current_local_solution = *_aux1;
    *aux_sys.old_local_solution = *_aux1;
    *aux_sys.older_local_solution = *_aux_saved;

    nl_sys.current_local_solution->close();
    nl_sys.old_local_solution->close();
    nl_sys.older_local_solution->close();
    aux_sys.current_local_solution->close();
    aux_sys.old_local_solution->close();
    aux_sys.older_local_solution->close();
  }
  else
  {
    // reject the step
    _time -= _dt;

    // recover initial state
    *nl_sys.current_local_solution = *_u_saved;
    *nl_sys.old_local_solution = *_u_saved;
    *nl_sys.older_local_solution = *_u_older_saved;

    *aux_sys.current_local_solution = *_aux_saved;
    *aux_sys.old_local_solution = *_aux_saved;
    *aux_sys.older_local_solution = *_aux_older_saved;

    nl_sys.solution->close();
    nl_sys.old_local_solution->close();
    nl_sys.older_local_solution->close();
    aux_sys.solution->close();
    aux_sys.old_local_solution->close();
    aux_sys.older_local_solution->close();
  }

  return Transient::computeDT();
}
<commit_msg>Print helpful status message in DT2Transient.<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "DT2Transient.h"
#include "Problem.h"

//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "nonlinear_solver.h"
#include "transient_system.h"
#include "numeric_vector.h"

// C++ Includes
#include <iomanip>

template<>
InputParameters validParams<DT2Transient>()
{
  InputParameters params = validParams<Transient>();
  params.addRequiredParam<Real>("e_tol","Target error tolerance.");
  params.addRequiredParam<Real>("e_max","Maximum acceptable error.");
  params.addParam<Real>("max_increase", 1.0e9,    "Maximum ratio that the time step can increase.");

  return params;
}

DT2Transient::DT2Transient(const std::string & name, InputParameters parameters) :
    Transient(name, parameters),
    _u_diff(NULL),
    _u1(NULL),
    _u2(NULL),
    _u_saved(NULL),
    _u_older_saved(NULL),
    _aux1(NULL),
    _aux_saved(NULL),
    _aux_older_saved(NULL),
    _e_tol(getParam<Real>("e_tol")),
    _e_max(getParam<Real>("e_max")),
    _max_increase(getParam<Real>("max_increase"))
{
}

DT2Transient::~DT2Transient()
{
}

void
DT2Transient::preExecute()
{
  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  _u1 = &nl_sys.add_vector("u1", true, GHOSTED);
  _u2 = &nl_sys.add_vector("u2", false, GHOSTED);
  _u_diff = &nl_sys.add_vector("u_diff", false, GHOSTED);

  _u_saved = &nl_sys.add_vector("u_saved", false, GHOSTED);
  _u_older_saved = &nl_sys.add_vector("u_older_saved", false, GHOSTED);

  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();
  _aux1 = &aux_sys.add_vector("aux1", true, GHOSTED);
  _aux_saved = &aux_sys.add_vector("aux_saved", false, GHOSTED);
  _aux_older_saved = &aux_sys.add_vector("aux_older_saved", false, GHOSTED);

  Transient::preExecute();
}

void
DT2Transient::preSolve()
{
  /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything?
  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();

  // save solution vectors
  *_u_saved = *nl_sys.current_local_solution;
  *_u_older_saved = *nl_sys.older_local_solution;

  *_aux_saved = *aux_sys.solution;
  *_aux_older_saved = *aux_sys.older_local_solution;

  _u_saved->close();
  _u_older_saved->close();
  _aux_saved->close();
  _aux_older_saved->close();

  // save dt
  _dt_full = _dt;
}

void
DT2Transient::postSolve()
{
  /*NonlinearSystem & nl =*/ _problem.getNonlinearSystem(); // returned reference is not used for anything?
  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();
  if (_converged)
  {
    // save the solution (for time step with dt)
    *_u1 = *nl_sys.current_local_solution;
    _u1->close();

    *_aux1 = *aux_sys.current_local_solution;
    _aux1->close();

    // take two steps with dt/2
    std::cout << "Taking two dt/2 time steps" << std::endl;

    // go back in time
    *nl_sys.current_local_solution = *_u_saved;
    *aux_sys.current_local_solution = *_aux_saved;
    nl_sys.current_local_solution->close();
    aux_sys.current_local_solution->close();

    _time -= _dt_full;

    _problem.computePostprocessors();

    // cut the time step in half
    _dt = _dt_full / 2;

    // 1. step
    _problem.onTimestepBegin();
    _time += _dt;

    std::cout << "  - 1. step" << std::endl;
    Moose::setSolverDefaults(_problem);
    nl_sys.solve();

    _converged = nl_sys.nonlinear_solver->converged;
    if (!_converged) return;
    nl_sys.update();

    _problem.copyOldSolutions();
    _problem.computePostprocessors();

    // 2. step
    _problem.onTimestepBegin();
    _time += _dt;

    std::cout << "  - 2. step" << std::endl;
    Moose::setSolverDefaults(_problem);
    nl_sys.solve();

    _converged = nl_sys.nonlinear_solver->converged;
    if (!_converged) return;
    nl_sys.update();

    *_u2 = *nl_sys.current_local_solution;
    _u2->close();

    // compute error
    *_u_diff = *_u2;
    *_u_diff -= *_u1;
    _u_diff->close();

    _error = (_u_diff->l2_norm() / std::max(_u1->l2_norm(), _u2->l2_norm())) / _dt_full;

    _dt = _dt_full;
    Transient::postSolve();
  }
}

bool
DT2Transient::lastSolveConverged()
{
  if (!_converged)
    return false;

  if (_error < _e_max)
    return true;
  else
  {
    std::cout << "DT2Transient: Marking last solve not converged since |U2-U1|/max(|U2|,|U1|) >= e_max." << std::endl;
    return false;
  }
}

Real
DT2Transient::computeDT()
{
  if(_t_step < 2)
    return Transient::computeDT();

  TransientNonlinearImplicitSystem & nl_sys = _problem.getNonlinearSystem().sys();
  TransientExplicitSystem & aux_sys = _problem.getAuxiliarySystem().sys();

  if(lastSolveConverged())
  {
    Real new_dt = _dt_full * std::pow(_e_tol / _error, 1.0 / _problem.getNonlinearSystem().getTimeSteppingOrder());

    if (new_dt/_dt_full > _max_increase)
      _dt = _dt_full*_max_increase;
    else
      _dt = new_dt;

    *nl_sys.current_local_solution= *_u1;
    *nl_sys.old_local_solution = *_u1;
    *nl_sys.older_local_solution = *_u_saved;

    *aux_sys.current_local_solution = *_aux1;
    *aux_sys.old_local_solution = *_aux1;
    *aux_sys.older_local_solution = *_aux_saved;

    nl_sys.current_local_solution->close();
    nl_sys.old_local_solution->close();
    nl_sys.older_local_solution->close();
    aux_sys.current_local_solution->close();
    aux_sys.old_local_solution->close();
    aux_sys.older_local_solution->close();
  }
  else
  {
    // reject the step
    _time -= _dt;

    // recover initial state
    *nl_sys.current_local_solution = *_u_saved;
    *nl_sys.old_local_solution = *_u_saved;
    *nl_sys.older_local_solution = *_u_older_saved;

    *aux_sys.current_local_solution = *_aux_saved;
    *aux_sys.old_local_solution = *_aux_saved;
    *aux_sys.older_local_solution = *_aux_older_saved;

    nl_sys.solution->close();
    nl_sys.old_local_solution->close();
    nl_sys.older_local_solution->close();
    aux_sys.solution->close();
    aux_sys.old_local_solution->close();
    aux_sys.older_local_solution->close();
  }

  return Transient::computeDT();
}
<|endoftext|>