<commit_before>#include <ext/stdio_filebuf.h>
#include <iostream>
#include <fstream>
#include <random>
#include <cstdio>
#include <functional>
#include "tools/MatrixHelper.h"
#include "tools/Matrix.h"
#include "gtest/gtest.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>

using namespace std;

class MatrixMultiplyTest : public ::testing::TestWithParam<const char*>
{
private:

protected:

    virtual void SetUp() {
        //currentImplementation = GetParam();

        inputAFile = "a.txt";
        inputBFile = "b.txt";
        outputFile = "c.txt";

        referenceImplementation = "build/src/gold/gold";
        currentImplementation = "build/src/" + string(GetParam());
    }

    virtual void TearDown() {
        remove(inputAFile.c_str());
        remove(inputBFile.c_str());
        remove(outputFile.c_str());
    }

    Matrix<float> createRandomMatrix(size_t rows, size_t columns)
    {
        Matrix<float> m(rows, columns);
        MatrixHelper::fill(m, generator);
        return m;
    }

    void initRandom(uint seed)
    {
        auto distribution = uniform_real_distribution<float> (-100, +100);
        auto engine = mt19937(seed);
        generator = bind(distribution, engine);
    }

    Matrix<float> executeMultiplication(string implementation, Matrix<float> a, Matrix<float> b)
    {
        MatrixHelper::writeMatrixTo(inputAFile, a);
        MatrixHelper::writeMatrixTo(inputBFile, b);
        startProcess({implementation, inputAFile, inputBFile, outputFile});
        return MatrixHelper::readMatrixFrom(outputFile);
    }

    void startProcess(initializer_list<string> args)
    {
        system(boost::algorithm::join(args, " ").c_str());
    }

    function<float()> generator;

    string inputAFile;
    string inputBFile;
    string outputFile;

    string referenceImplementation;
    string currentImplementation;
};

::testing::AssertionResult AreMatricesEquals(Matrix<float> expected, Matrix<float>actual, float delta)
{
    if(expected.rows() != actual.rows())
    {
        return ::testing::AssertionFailure() << "different number of rows: " << expected.rows() << " != " << actual.rows();
    }
    if(expected.columns() != actual.columns())
    {
        return ::testing::AssertionFailure() << "different number of columns: " << expected.columns() << " != " << actual.columns();
    }
    for(size_t y = 0; y<expected.rows(); y++)
    {
        for(size_t x = 0; x<expected.columns(); x++)
        {
            float expectedVal = expected(y,x);
            float actualVal = actual(y,x);
            float maxVal = max(fabs(expectedVal), fabs(actualVal));
            float error = fabs(expectedVal - actualVal);
            error = (maxVal < 1e-10) ? error : error / maxVal;
            if(error > delta)
            {
                // dump matrices
                MatrixHelper::writeMatrixTo("dump_expected.txt", expected);
                MatrixHelper::writeMatrixTo("dump_actual.txt", actual);

                // return failure
                return ::testing::AssertionFailure()
                << "The relative error at (" << y << "," << x << ") is " << error << ", which exceeds " << delta << ", where" << endl
                << "expected(y,x) = " << expectedVal << " and" << endl
                << "actual(y,x) = " << actualVal << ".";
            }
        }
    }
    return ::testing::AssertionSuccess();

}
::testing::AssertionResult  AreMatricesEquals(Matrix<float> a, Matrix<float>b)
{
    return AreMatricesEquals(a, b, 1e-3);
}

TEST_P(MatrixMultiplyTest, SingleElementMatrixTest) {
    initRandom(0);
    auto left = createRandomMatrix(1, 1);
    auto right = createRandomMatrix(1, 1);;

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

TEST_P(MatrixMultiplyTest, SmallSquareMatricesTest) {
    initRandom(12345);
    auto left = createRandomMatrix(5, 5);
    auto right = createRandomMatrix(5, 5);

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

TEST_P(MatrixMultiplyTest, MediumRectangularMatricesTest) {
    initRandom(333);
    auto left = createRandomMatrix(30, 50);
    auto right = createRandomMatrix(50, 40);

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

TEST_P(MatrixMultiplyTest, PrimeRectangularMatricesTest) {
    initRandom(333);
    auto left = createRandomMatrix(67, 83);
    auto right = createRandomMatrix(83, 109);

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

INSTANTIATE_TEST_CASE_P(MultiplePlatforms,
                        MatrixMultiplyTest,
                        ::testing::Values("cuda/cuda", "mpi/mpi-matrix", "smp/smp"));

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>randomized seed for new test<commit_after>#include <ext/stdio_filebuf.h>
#include <iostream>
#include <fstream>
#include <random>
#include <cstdio>
#include <functional>
#include "tools/MatrixHelper.h"
#include "tools/Matrix.h"
#include "gtest/gtest.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>

using namespace std;

class MatrixMultiplyTest : public ::testing::TestWithParam<const char*>
{
private:

protected:

    virtual void SetUp() {
        //currentImplementation = GetParam();

        inputAFile = "a.txt";
        inputBFile = "b.txt";
        outputFile = "c.txt";

        referenceImplementation = "build/src/gold/gold";
        currentImplementation = "build/src/" + string(GetParam());
    }

    virtual void TearDown() {
        remove(inputAFile.c_str());
        remove(inputBFile.c_str());
        remove(outputFile.c_str());
    }

    Matrix<float> createRandomMatrix(size_t rows, size_t columns)
    {
        Matrix<float> m(rows, columns);
        MatrixHelper::fill(m, generator);
        return m;
    }

    void initRandom(uint seed)
    {
        auto distribution = uniform_real_distribution<float> (-100, +100);
        auto engine = mt19937(seed);
        generator = bind(distribution, engine);
    }

    Matrix<float> executeMultiplication(string implementation, Matrix<float> a, Matrix<float> b)
    {
        MatrixHelper::writeMatrixTo(inputAFile, a);
        MatrixHelper::writeMatrixTo(inputBFile, b);
        startProcess({implementation, inputAFile, inputBFile, outputFile});
        return MatrixHelper::readMatrixFrom(outputFile);
    }

    void startProcess(initializer_list<string> args)
    {
        system(boost::algorithm::join(args, " ").c_str());
    }

    function<float()> generator;

    string inputAFile;
    string inputBFile;
    string outputFile;

    string referenceImplementation;
    string currentImplementation;
};

::testing::AssertionResult AreMatricesEquals(Matrix<float> expected, Matrix<float>actual, float delta)
{
    if(expected.rows() != actual.rows())
    {
        return ::testing::AssertionFailure() << "different number of rows: " << expected.rows() << " != " << actual.rows();
    }
    if(expected.columns() != actual.columns())
    {
        return ::testing::AssertionFailure() << "different number of columns: " << expected.columns() << " != " << actual.columns();
    }
    for(size_t y = 0; y<expected.rows(); y++)
    {
        for(size_t x = 0; x<expected.columns(); x++)
        {
            float expectedVal = expected(y,x);
            float actualVal = actual(y,x);
            float maxVal = max(fabs(expectedVal), fabs(actualVal));
            float error = fabs(expectedVal - actualVal);
            error = (maxVal < 1e-10) ? error : error / maxVal;
            if(error > delta)
            {
                // dump matrices
                MatrixHelper::writeMatrixTo("dump_expected.txt", expected);
                MatrixHelper::writeMatrixTo("dump_actual.txt", actual);

                // return failure
                return ::testing::AssertionFailure()
                << "The relative error at (" << y << "," << x << ") is " << error << ", which exceeds " << delta << ", where" << endl
                << "expected(y,x) = " << expectedVal << " and" << endl
                << "actual(y,x) = " << actualVal << ".";
            }
        }
    }
    return ::testing::AssertionSuccess();

}
::testing::AssertionResult  AreMatricesEquals(Matrix<float> a, Matrix<float>b)
{
    return AreMatricesEquals(a, b, 1e-3);
}

TEST_P(MatrixMultiplyTest, SingleElementMatrixTest) {
    initRandom(0);
    auto left = createRandomMatrix(1, 1);
    auto right = createRandomMatrix(1, 1);;

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

TEST_P(MatrixMultiplyTest, SmallSquareMatricesTest) {
    initRandom(12345);
    auto left = createRandomMatrix(5, 5);
    auto right = createRandomMatrix(5, 5);

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

TEST_P(MatrixMultiplyTest, MediumRectangularMatricesTest) {
    initRandom(333);
    auto left = createRandomMatrix(30, 50);
    auto right = createRandomMatrix(50, 40);

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

TEST_P(MatrixMultiplyTest, PrimeRectangularMatricesTest) {
    initRandom(6543452);
    auto left = createRandomMatrix(67, 83);
    auto right = createRandomMatrix(83, 109);

    auto expected = executeMultiplication(referenceImplementation, left, right);
    auto actual = executeMultiplication(currentImplementation, left, right);

    EXPECT_TRUE(AreMatricesEquals(expected, actual));
}

INSTANTIATE_TEST_CASE_P(MultiplePlatforms,
                        MatrixMultiplyTest,
                        ::testing::Values("cuda/cuda", "mpi/mpi-matrix", "smp/smp"));

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"

#include <algorithm>
#include <cassert>
#include <cstring>
#include <vector>

namespace meshopt
{

static unsigned int murmurHash2(const void* key, size_t len, unsigned int seed)
{
	const unsigned int m = 0x5bd1e995;
	const int r = 24;

	unsigned int h = seed ^ static_cast<unsigned int>(len);

	// Mix 4 bytes at a time into the hash
	const unsigned char* data = (const unsigned char*)key;

	while (len >= 4)
	{
		unsigned int k = *(unsigned int*)data;

		k *= m;
		k ^= k >> r;
		k *= m;

		h *= m;
		h ^= k;

		data += 4;
		len -= 4;
	}

	// Handle the last few bytes of the input array
	switch (len)
	{
	case 3:
		h ^= data[2] << 16;
	case 2:
		h ^= data[1] << 8;
	case 1:
		h ^= data[0];
		h *= m;
	};

	// Do a few final mixes of the hash to ensure the last few
	// bytes are well-incorporated.

	h ^= h >> 13;
	h *= m;
	h ^= h >> 15;

	return h;
}

struct VertexHasher
{
	const char* vertices;
	size_t vertex_size;

	unsigned int empty() const
	{
		return ~0u;
	}

	size_t operator()(unsigned int index) const
	{
		return murmurHash2(vertices + index * vertex_size, vertex_size, 0);
	}

	size_t operator()(unsigned int lhs, unsigned int rhs) const
	{
		return memcmp(vertices + lhs * vertex_size, vertices + rhs * vertex_size, vertex_size) == 0;
	}
};

struct VertexHashEntry
{
	unsigned int key;
	unsigned int value;
};

template <typename T, typename Hash>
static void hashInit(std::vector<T>& table, const Hash& hash, size_t count)
{
	size_t buckets = 1;
	while (buckets < count)
		buckets *= 2;

	T dummy = T();
	dummy.key = hash.empty();

	table.clear();
	table.resize(buckets, dummy);
}

template <typename T, typename Hash, typename Key>
static T* hashLookup(std::vector<T>& table, const Hash& hash, const Key& key)
{
	assert((table.size() & (table.size() - 1)) == 0);

	size_t hashmod = table.size() - 1;
	size_t hashval = hash(key);
	size_t bucket = hashval & hashmod;

	for (size_t probe = 0; probe <= hashmod; ++probe)
	{
		T& item = table[bucket];

		if (item.key == hash.empty())
			return &item;

		if (hash(item.key, key))
			return &item;

		// hash collision, quadratic probing
		bucket = (bucket + probe + 1) & hashmod;
	}

	assert(false && "Hash table is full");
	return 0;
}

} // namespace meshopt

size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
{
	using namespace meshopt;

	assert(indices || index_count == vertex_count);
	assert(index_count % 3 == 0);
	assert(vertex_size > 0);

	for (size_t i = 0; i < vertex_count; ++i)
	{
		destination[i] = ~0u;
	}

	VertexHasher hasher = {static_cast<const char*>(vertices), vertex_size};

	std::vector<VertexHashEntry> table;
	hashInit(table, hasher, vertex_count);

	unsigned int next_vertex = 0;

	for (size_t i = 0; i < index_count; ++i)
	{
		unsigned int index = indices ? indices[i] : unsigned(i);
		assert(index < vertex_count);

		if (destination[index] == ~0u)
		{
			VertexHashEntry* entry = hashLookup(table, hasher, index);

			if (entry->key == ~0u)
			{
				entry->key = index;
				entry->value = next_vertex++;
			}

			destination[index] = entry->value;
		}
	}

	return next_vertex;
}

void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap)
{
	assert(destination != vertices);
	assert(vertex_size > 0);

	for (size_t i = 0; i < vertex_count; ++i)
	{
		if (remap[i] != ~0u)
		{
			memcpy(static_cast<char*>(destination) + remap[i] * vertex_size, static_cast<const char*>(vertices) + i * vertex_size, vertex_size);
		}
	}
}

void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap)
{
	assert(index_count % 3 == 0);

	for (size_t i = 0; i < index_count; ++i)
	{
		unsigned int index = indices ? indices[i] : unsigned(i);
		assert(remap[index] != ~0u);

		destination[i] = remap[index];
	}
}
<commit_msg>indexgenerator: Simplify hashing function<commit_after>// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"

#include <algorithm>
#include <cassert>
#include <cstring>
#include <vector>

namespace meshopt
{

static unsigned int murmurHash(const char* key, size_t len, unsigned int h)
{
	const unsigned int m = 0x5bd1e995;
	const int r = 24;

	while (len >= 4)
	{
		unsigned int k = *reinterpret_cast<const unsigned int*>(key);

		k *= m;
		k ^= k >> r;
		k *= m;

		h *= m;
		h ^= k;

		key += 4;
		len -= 4;
	}

	return h;
}

struct VertexHasher
{
	const char* vertices;
	size_t vertex_size;

	unsigned int empty() const
	{
		return ~0u;
	}

	size_t operator()(unsigned int index) const
	{
		return murmurHash(vertices + index * vertex_size, vertex_size, 0);
	}

	size_t operator()(unsigned int lhs, unsigned int rhs) const
	{
		return memcmp(vertices + lhs * vertex_size, vertices + rhs * vertex_size, vertex_size) == 0;
	}
};

struct VertexHashEntry
{
	unsigned int key;
	unsigned int value;
};

template <typename T, typename Hash>
static void hashInit(std::vector<T>& table, const Hash& hash, size_t count)
{
	size_t buckets = 1;
	while (buckets < count)
		buckets *= 2;

	T dummy = T();
	dummy.key = hash.empty();

	table.clear();
	table.resize(buckets, dummy);
}

template <typename T, typename Hash, typename Key>
static T* hashLookup(std::vector<T>& table, const Hash& hash, const Key& key)
{
	assert((table.size() & (table.size() - 1)) == 0);

	size_t hashmod = table.size() - 1;
	size_t hashval = hash(key);
	size_t bucket = hashval & hashmod;

	for (size_t probe = 0; probe <= hashmod; ++probe)
	{
		T& item = table[bucket];

		if (item.key == hash.empty())
			return &item;

		if (hash(item.key, key))
			return &item;

		// hash collision, quadratic probing
		bucket = (bucket + probe + 1) & hashmod;
	}

	assert(false && "Hash table is full");
	return 0;
}

} // namespace meshopt

size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
{
	using namespace meshopt;

	assert(indices || index_count == vertex_count);
	assert(index_count % 3 == 0);
	assert(vertex_size > 0);

	for (size_t i = 0; i < vertex_count; ++i)
	{
		destination[i] = ~0u;
	}

	VertexHasher hasher = {static_cast<const char*>(vertices), vertex_size};

	std::vector<VertexHashEntry> table;
	hashInit(table, hasher, vertex_count);

	unsigned int next_vertex = 0;

	for (size_t i = 0; i < index_count; ++i)
	{
		unsigned int index = indices ? indices[i] : unsigned(i);
		assert(index < vertex_count);

		if (destination[index] == ~0u)
		{
			VertexHashEntry* entry = hashLookup(table, hasher, index);

			if (entry->key == ~0u)
			{
				entry->key = index;
				entry->value = next_vertex++;
			}

			destination[index] = entry->value;
		}
	}

	return next_vertex;
}

void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap)
{
	assert(destination != vertices);
	assert(vertex_size > 0);

	for (size_t i = 0; i < vertex_count; ++i)
	{
		if (remap[i] != ~0u)
		{
			memcpy(static_cast<char*>(destination) + remap[i] * vertex_size, static_cast<const char*>(vertices) + i * vertex_size, vertex_size);
		}
	}
}

void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap)
{
	assert(index_count % 3 == 0);

	for (size_t i = 0; i < index_count; ++i)
	{
		unsigned int index = indices ? indices[i] : unsigned(i);
		assert(remap[index] != ~0u);

		destination[i] = remap[index];
	}
}
<|endoftext|>


<commit_before>#include<iostream>
#include<cstdio>
#include<sstream>
#include<fstream>
#include<iomanip>
#include<unistd.h>
#include<map>
#include<sys/types.h>
#include<sys/wait.h>
#include"utils.h"
#include"sandbox.h"
#include"config.h"
#include"testsuite.h"
#include"server_io.h"

using namespace std;

int compile(const submission& target, int boxid, int spBoxid);
void eval(submission &sub, int td, int boxid, int spBoxid);
void getExitStatus(submission &sub, int td);

int testsuite(submission &sub, int MAXPARNUM, int BOXOFFSET)
{
   system("rm -f ./testzone/*");
   const int testBoxid = BOXOFFSET + 0, spBoxid = BOXOFFSET + 1;
   sandboxInit(testBoxid);
   sandboxInit(spBoxid);
   int status = compile(sub, testBoxid, spBoxid);
   if(status != OK) return status;

   //anyway, only have batch judge right now
   map<pid_t, int> proc;
   int procnum = 0;
   int problem_id = sub.problem_id;
   int* time_limit = sub.time_limit;
   int* mem_limit = sub.mem_limit;

   for(int i = 0; i < sub.testdata_count; ++i){
      while(procnum >= MAXPARNUM){
         int status;
         pid_t cid = waitpid(-1, &status, 0);
         if(cid == -1){
            perror("[ERROR] in testsuite,  `waitpid()` failed :");
            return ER;
         }
         int td = proc[cid];
         eval(sub, td, BOXOFFSET + 10 + td, spBoxid);
         sendResult(sub, OK, false);
         //cerr << "td" << td << " : " << sub.verdict[td] << endl;
         sandboxDele(BOXOFFSET + 10 + td);
         --procnum;
      }

      if(procnum < MAXPARNUM){
         //batch judge
         ostringstream command;
         command << "batchjudge " << problem_id;
         command << " " << i;
         command << " " << BOXOFFSET + 10 + i;
         command << " " << time_limit[i];
         command << " " << mem_limit[i];
         command << " " << testBoxid;
         //
         pid_t pid = fork();
         if(pid == -1){
            perror("[ERROR] in testsuite, `fork()` failed :");
            return ER;
         }
         if(pid == 0){
            //child proc
            execl("/bin/sh", "sh", "-c", command.str().c_str(), NULL);
            perror("[ERROR] in testsuite, `execl()` failed :");
            exit(0);
         }
         proc[pid] = i;
         ++procnum;
      }
   }
   while(procnum >= 1){
      int status;
      pid_t cid = waitpid(-1, &status, 0);
      if(cid == -1){
         perror("[ERROR] in testsuite,  `waitpid()` failed :");
         return ER;
      }
      const int td = proc[cid];
      //sub.verdict[td] = eval(problem_id, td);
      eval(sub, td, BOXOFFSET + 10 + td, spBoxid);
      sendResult(sub, OK, false);
      //cerr << "td" << td << " : " << sub.verdict[td] << endl;
      sandboxDele(BOXOFFSET + 10 + td);
      --procnum;
   }
   //clear box-10
   sandboxDele(testBoxid);
   sandboxDele(spBoxid);
   return OK;
}

void setExitStatus(submission &sub, int td)
{
   ostringstream sout;
   sout << "./testzone/META" << td;
   ifstream fin(sout.str());
   string line;
   map<string,string> META;
   while(!fin.eof() && getline(fin, line)){
      for(int i = 0; i < line.size(); ++i)
         if(line[i] == ':')
            line[i] = ' ';
      istringstream in(line);
      string a, b;
      in >> a >> b;
      META[a] = b;
   }

   //mem_used
   sub.mem[td] = cast(META["cg-mem"]).to<int>();
   //time_used
   sub.time[td] = 1000 * cast(META["time"]).to<double>();
   //verdict
   if(META["status"] == ""){
      sub.verdict[td] = OK;
   }else if(META["status"] == "TO"){
      sub.verdict[td] = TLE;
   }else if(META["status"] == "SG"){
      switch(cast(META["exitsig"]).to<int>()){
         case 11:
            sub.verdict[td] = MLE;
            break;
         default :
            sub.verdict[td] = RE;
      }
   }else if(META["status"] == "RE"){
      sub.verdict[td] = RE;
   }else{
      // "XX"
      sub.verdict[td] = ER;
   }
   return ;
}

void eval(submission &sub, int td, int boxid, int spBoxid)
{
   int problem_id = sub.problem_id;
   setExitStatus(sub, td);
   if(sub.verdict[td] != OK){
      return ;
   }

   if(sub.problem_type == 1){
      ostringstream sout;
      sout << "/tmp/box/" << spBoxid << "/box/sj.out ";
      string sjpath(sout.str());
      sout.str("");
      sout << "./testdata" << setfill('0') << setw(4) << problem_id << "/input" << setw(3) << td << ' ';
      string tdin(sout.str());
      sout.str("");
      sout << "./testdata" << setfill('0') << setw(4) << problem_id << "/output" << setw(3) << td << ' ';
      string tdout(sout.str());
      sout.str("");
      sout << "/tmp/box/" << boxid << "/box/output ";
      string ttout(sout.str());
      FILE* Pipe = popen((sjpath+ttout+tdin+tdout).c_str(), "r");
      int result = 1;
      fscanf(Pipe, "%d", &result);
      pclose(Pipe);
      if(result == 0)
         sub.verdict[td] = AC;
      else
         sub.verdict[td] = WA;
      return ;
   }

   int status = AC;
   string s, t;
   //solution output
   ostringstream sout;
   sout << "./testdata/" << setfill('0') << setw(4) << problem_id
      << "/output" << setw(3) << td;
   fstream tsol(sout.str());
   //user output
   sout.str("");
   sout << "/tmp/box/" << boxid << "/box/output";
   fstream mout(sout.str());
   while(1){
      s="";
      t="";
      getline(tsol,s);
      getline(mout,t);
      if(t==""&&s!=""){
         status = WA;
         break;
      }
      if(t!=""&&s==""){
         status = WA;
         break;
      }
      if(t==""&&s==""){
         break;
      }
      s.erase(s.find_last_not_of(" \n\r\t")+1);
      t.erase(t.find_last_not_of(" \n\r\t")+1);
      if(s!=t){
         status = WA;
         break;
      }
   }
   sub.verdict[td] = status;
   return ;
}

int compile(const submission& target, int boxid, int spBoxid)
{
   ostringstream sout;
   sout << "/tmp/box/" << boxid << "/box/";
   string boxdir(sout.str());

   ofstream fout(boxdir + "main.cpp");
   fout << target.code << flush;
   fout.close();

   if(target.problem_type == 2){
      sout.str("");
      sout << boxdir << "lib" << setw(4) << setfill('0') << target.problem_id << ".h";
      fout.open(sout.str());
      fout << target.interlib << flush;
      fout.close();
   }

   sout.str("");
   if(target.lang == "c++"){
      sout << "/usr/bin/g++ ./main.cpp -o ./main.out -O2 ";
   }else{
      sout << "/usr/bin/gcc ./main.cpp -o ./main.out -O2 ";
   }
   if(!target.std.empty()){
      sout << "-std=" << target.std << " ";
   }
   string comm(sout.str());
   sandboxOptions opt;
   opt.dirs.push_back("/etc/");
   opt.procs = 50;
   opt.preserve_env = true;
   opt.errout = "compile_error";
   opt.timeout = 60 * 1000;
   opt.meta = "./testzone/metacomp";

   sandboxExec(boxid, opt, comm);
   if(access((boxdir+"main.out").c_str(), F_OK) == -1){
      return CE;
   }

   if(target.problem_type == 1){
      sout.str("");
      sout << "/tmp/box/" << spBoxid << "/box/";
      string spBoxdir = sout.str();

      fout.open(spBoxdir + "sj.cpp");
      fout << target.sjcode << flush;
      fout.close();

      sout.str("");
      sout << "/usr/bin/g++ ./sj.cpp -o ./sj.out -O2 -std=c++11 ";

      opt.meta = "./testzone/metacompsj";

      sandboxExec(spBoxid, opt, sout.str());
      if(access((spBoxdir+"sj.out").c_str(), F_OK) == -1){
         return ER;
      }
   }

   return OK;
}
<commit_msg>add c support<commit_after>#include<iostream>
#include<cstdio>
#include<sstream>
#include<fstream>
#include<iomanip>
#include<unistd.h>
#include<map>
#include<sys/types.h>
#include<sys/wait.h>
#include"utils.h"
#include"sandbox.h"
#include"config.h"
#include"testsuite.h"
#include"server_io.h"

using namespace std;

int compile(const submission& target, int boxid, int spBoxid);
void eval(submission &sub, int td, int boxid, int spBoxid);
void getExitStatus(submission &sub, int td);

int testsuite(submission &sub, int MAXPARNUM, int BOXOFFSET)
{
   system("rm -f ./testzone/*");
   const int testBoxid = BOXOFFSET + 0, spBoxid = BOXOFFSET + 1;
   sandboxInit(testBoxid);
   sandboxInit(spBoxid);
   int status = compile(sub, testBoxid, spBoxid);
   if(status != OK) return status;

   //anyway, only have batch judge right now
   map<pid_t, int> proc;
   int procnum = 0;
   int problem_id = sub.problem_id;
   int* time_limit = sub.time_limit;
   int* mem_limit = sub.mem_limit;

   for(int i = 0; i < sub.testdata_count; ++i){
      while(procnum >= MAXPARNUM){
         int status;
         pid_t cid = waitpid(-1, &status, 0);
         if(cid == -1){
            perror("[ERROR] in testsuite,  `waitpid()` failed :");
            return ER;
         }
         int td = proc[cid];
         eval(sub, td, BOXOFFSET + 10 + td, spBoxid);
         sendResult(sub, OK, false);
         //cerr << "td" << td << " : " << sub.verdict[td] << endl;
         sandboxDele(BOXOFFSET + 10 + td);
         --procnum;
      }

      if(procnum < MAXPARNUM){
         //batch judge
         ostringstream command;
         command << "batchjudge " << problem_id;
         command << " " << i;
         command << " " << BOXOFFSET + 10 + i;
         command << " " << time_limit[i];
         command << " " << mem_limit[i];
         command << " " << testBoxid;
         //
         pid_t pid = fork();
         if(pid == -1){
            perror("[ERROR] in testsuite, `fork()` failed :");
            return ER;
         }
         if(pid == 0){
            //child proc
            execl("/bin/sh", "sh", "-c", command.str().c_str(), NULL);
            perror("[ERROR] in testsuite, `execl()` failed :");
            exit(0);
         }
         proc[pid] = i;
         ++procnum;
      }
   }
   while(procnum >= 1){
      int status;
      pid_t cid = waitpid(-1, &status, 0);
      if(cid == -1){
         perror("[ERROR] in testsuite,  `waitpid()` failed :");
         return ER;
      }
      const int td = proc[cid];
      //sub.verdict[td] = eval(problem_id, td);
      eval(sub, td, BOXOFFSET + 10 + td, spBoxid);
      sendResult(sub, OK, false);
      //cerr << "td" << td << " : " << sub.verdict[td] << endl;
      sandboxDele(BOXOFFSET + 10 + td);
      --procnum;
   }
   //clear box-10
   sandboxDele(testBoxid);
   sandboxDele(spBoxid);
   return OK;
}

void setExitStatus(submission &sub, int td)
{
   ostringstream sout;
   sout << "./testzone/META" << td;
   ifstream fin(sout.str());
   string line;
   map<string,string> META;
   while(!fin.eof() && getline(fin, line)){
      for(int i = 0; i < line.size(); ++i)
         if(line[i] == ':')
            line[i] = ' ';
      istringstream in(line);
      string a, b;
      in >> a >> b;
      META[a] = b;
   }

   //mem_used
   sub.mem[td] = cast(META["cg-mem"]).to<int>();
   //time_used
   sub.time[td] = 1000 * cast(META["time"]).to<double>();
   //verdict
   if(META["status"] == ""){
      sub.verdict[td] = OK;
   }else if(META["status"] == "TO"){
      sub.verdict[td] = TLE;
   }else if(META["status"] == "SG"){
      switch(cast(META["exitsig"]).to<int>()){
         case 11:
            sub.verdict[td] = MLE;
            break;
         default :
            sub.verdict[td] = RE;
      }
   }else if(META["status"] == "RE"){
      sub.verdict[td] = RE;
   }else{
      // "XX"
      sub.verdict[td] = ER;
   }
   return ;
}

void eval(submission &sub, int td, int boxid, int spBoxid)
{
   int problem_id = sub.problem_id;
   setExitStatus(sub, td);
   if(sub.verdict[td] != OK){
      return ;
   }

   if(sub.problem_type == 1){
      ostringstream sout;
      sout << "/tmp/box/" << spBoxid << "/box/sj.out ";
      string sjpath(sout.str());
      sout.str("");
      sout << "./testdata" << setfill('0') << setw(4) << problem_id << "/input" << setw(3) << td << ' ';
      string tdin(sout.str());
      sout.str("");
      sout << "./testdata" << setfill('0') << setw(4) << problem_id << "/output" << setw(3) << td << ' ';
      string tdout(sout.str());
      sout.str("");
      sout << "/tmp/box/" << boxid << "/box/output ";
      string ttout(sout.str());
      FILE* Pipe = popen((sjpath+ttout+tdin+tdout).c_str(), "r");
      int result = 1;
      fscanf(Pipe, "%d", &result);
      pclose(Pipe);
      if(result == 0)
         sub.verdict[td] = AC;
      else
         sub.verdict[td] = WA;
      return ;
   }

   int status = AC;
   string s, t;
   //solution output
   ostringstream sout;
   sout << "./testdata/" << setfill('0') << setw(4) << problem_id
      << "/output" << setw(3) << td;
   fstream tsol(sout.str());
   //user output
   sout.str("");
   sout << "/tmp/box/" << boxid << "/box/output";
   fstream mout(sout.str());
   while(1){
      s="";
      t="";
      getline(tsol,s);
      getline(mout,t);
      if(t==""&&s!=""){
         status = WA;
         break;
      }
      if(t!=""&&s==""){
         status = WA;
         break;
      }
      if(t==""&&s==""){
         break;
      }
      s.erase(s.find_last_not_of(" \n\r\t")+1);
      t.erase(t.find_last_not_of(" \n\r\t")+1);
      if(s!=t){
         status = WA;
         break;
      }
   }
   sub.verdict[td] = status;
   return ;
}

int compile(const submission& target, int boxid, int spBoxid)
{
   ostringstream sout;
   sout << "/tmp/box/" << boxid << "/box/";
   string boxdir(sout.str());

   ofstream fout;
   if(target.lang == "c++"){
      fout.open(boxdir + "main.cpp");
   }else{
      fout.open(boxdir + "main.c");
   }
   fout << target.code << flush;
   fout.close();

   if(target.problem_type == 2){
      sout.str("");
      sout << boxdir << "lib" << setw(4) << setfill('0') << target.problem_id << ".h";
      fout.open(sout.str());
      fout << target.interlib << flush;
      fout.close();
   }

   sout.str("");
   if(target.lang == "c++"){
      sout << "/usr/bin/g++ ./main.cpp -o ./main.out -O2 ";
   }else{
      sout << "/usr/bin/gcc ./main.c -o ./main.out -O2 ";
   }
   if(!target.std.empty()){
      sout << "-std=" << target.std << " ";
   }
   string comm(sout.str());
   sandboxOptions opt;
   opt.dirs.push_back("/etc/");
   opt.procs = 50;
   opt.preserve_env = true;
   opt.errout = "compile_error";
   opt.timeout = 60 * 1000;
   opt.meta = "./testzone/metacomp";

   sandboxExec(boxid, opt, comm);
   if(access((boxdir+"main.out").c_str(), F_OK) == -1){
      return CE;
   }

   if(target.problem_type == 1){
      sout.str("");
      sout << "/tmp/box/" << spBoxid << "/box/";
      string spBoxdir = sout.str();

      fout.open(spBoxdir + "sj.cpp");
      fout << target.sjcode << flush;
      fout.close();

      sout.str("");
      sout << "/usr/bin/g++ ./sj.cpp -o ./sj.out -O2 -std=c++11 ";

      opt.meta = "./testzone/metacompsj";

      sandboxExec(spBoxid, opt, sout.str());
      if(access((spBoxdir+"sj.out").c_str(), F_OK) == -1){
         return ER;
      }
   }

   return OK;
}
<|endoftext|>


<commit_before>// Program.cpp

#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/PropertyChoice.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
#include "CNCConfig.h"

bool COperations::CanAdd(HeeksObj* object)
{
	return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}

void COperations::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Operations" );
	root->LinkEndChild( element );
	WriteBaseXML(element);
}

//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
	COperations* new_object = new COperations;
	new_object->ReadBaseXML(pElem);
	return new_object;
}

static COperations* object_for_tools = NULL;

class SetAllActive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Active");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = true;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setactive");}
};

static SetAllActive set_all_active;

class SetAllInactive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Inactive");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = false;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setinactive");}
};

static SetAllInactive set_all_inactive;

void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	object_for_tools = this;
	t_list->push_back(&set_all_active);
	t_list->push_back(&set_all_inactive);

	ObjList::GetTools(t_list, p);
}

CProgram::CProgram():m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
	CNCConfig config;
	config.Read(_T("ProgramMachine"), &m_machine, _T("nc.iso"));
	config.Read(_T("ProgramOutputFile"), &m_output_file, _T("/tmp/test.tap"));
	config.Read(_T("ProgramUnits"), &m_units, 1.0);
}

HeeksObj *CProgram::MakeACopy(void)const
{
	return new CProgram(*this);
}

void CProgram::CopyFrom(const HeeksObj* object)
{
	operator=(*((CProgram*)object));
}

static void on_set_machine(const wxChar* value, HeeksObj* object)
{
	((CProgram*)object)->m_machine = value;
	CNCConfig config;
	config.Write(_T("ProgramMachine"), ((CProgram*)object)->m_machine);
}

static void on_set_output_file(const wxChar* value, HeeksObj* object)
{
	((CProgram*)object)->m_output_file = value;
	CNCConfig config;
	config.Write(_T("ProgramOutputFile"), ((CProgram*)object)->m_output_file);
}

static void on_set_units(int value, HeeksObj* object)
{
	((CProgram*)object)->m_units = (value == 0) ? 1.0:25.4;
	CNCConfig config;
	config.Write(_T("ProgramUnits"), ((CProgram*)object)->m_units);

	// also change HeeksCAD's view units automatically
	heeksCAD->SetViewUnits(((CProgram*)object)->m_units, true);
}

void CProgram::GetProperties(std::list<Property *> *list)
{
	list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
	list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
	{
		std::list< wxString > choices;
		choices.push_back ( wxString ( _("mm") ) );
		choices.push_back ( wxString ( _("inch") ) );
		int choice = 0;
		if(m_units > 25.0)choice = 1;
		list->push_back ( new PropertyChoice ( _("units"),  choices, choice, this, on_set_units ) );
	}
	HeeksObj::GetProperties(list);
}

bool CProgram::CanAdd(HeeksObj* object)
{
	return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}

bool CProgram::CanAddTo(HeeksObj* owner)
{
	return owner->GetType() == DocumentType;
}

void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
	if(marked_object->m_map.size() > 0)
	{
		MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
		if(sub_marked_object)
		{
			HeeksObj* object = sub_marked_object->m_map.begin()->first;
			if(object && object->GetType() == NCCodeType)
			{
				((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
			}
		}
	}
}

void CProgram::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Program" );
	root->LinkEndChild( element );
	element->SetAttribute("machine", Ttc(m_machine.c_str()));
	element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
	element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
	element->SetDoubleAttribute("units", m_units);

	WriteBaseXML(element);
}

bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
	if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
	if(object->GetType() == OperationsType)m_operations = (COperations*)object;
	return ObjList::Add(object, prev_object);
}

void CProgram::Remove(HeeksObj* object)
{
	 // these shouldn't happen, though
	if(object == m_nc_code)m_nc_code = NULL;
	else if(object == m_operations)m_operations = NULL;

	ObjList::Remove(object);
}

// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
	CProgram* new_object = new CProgram;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
		else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
		else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
		else if(name == "units"){new_object->m_units = a->DoubleValue();}
	}

	new_object->ReadBaseXML(pElem);
	theApp.m_program = new_object;

	return new_object;
}

void CProgram::RewritePythonProgram()
{
	theApp.m_program_canvas->m_textCtrl->Clear();
	CZigZag::number_for_stl_file = 1;
	CAdaptive::number_for_stl_file = 1;

	bool profile_op_exists = false;
	bool pocket_op_exists = false;
	bool zigzag_op_exists = false;
	bool adaptive_op_exists = false;
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		if(object->GetType() == ProfileType)
		{
			if(((CProfile*)object)->m_active)profile_op_exists = true;
		}
		else if(object->GetType() == PocketType)
		{
			if(((CPocket*)object)->m_active)pocket_op_exists = true;
		}
		else if(object->GetType() == ZigZagType)
		{
			if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
		}
		else if(object->GetType() == AdaptiveType)
		{
			if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
		}
	}

	// add standard stuff at the top
	//hackhack, make it work on unix with FHS
#ifndef WIN32
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'/usr/local/lib/heekscnc/')\n"));
#endif
	// kurve related things
	if(profile_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
	}

	// area related things
	if(pocket_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
	}

	// pycam stuff
	if(zigzag_op_exists)
	{
#ifdef WIN32
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
#endif
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// actp
	if(adaptive_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// machine general stuff
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));

	// specific machine
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// output file
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));

	// begin program
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
	if(m_units > 25.0)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("imperial()\n"));
	}
	else
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
	}
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// write the operations
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		switch(object->GetType())
		{
		case ProfileType:
			if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
			break;
		case PocketType:
			if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
			break;
		case ZigZagType:
			if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
			break;
		case AdaptiveType:
			if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
			break;
		}
	}
}

ProgramUserType CProgram::GetUserType()
{
	if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
	if(m_script_edited)return ProgramUserTypeScript;
	if(m_operations->GetFirstChild())return ProgramUserTypeTree;
	return ProgramUserTypeUnkown;
}

void CProgram::UpdateFromUserType()
{
#if 0
	switch(GetUserType())
	{
	case ProgramUserTypeUnkown:

	case tree:
   Enable "Operations" icon in tree
     editing the tree, recreates the python script
   Read only "Program" window
     pressing "Post-process" creates the NC code ( and backplots it )
   Read only "Output" window
   Disable all buttons on "Output" window

	}
#endif
}
<commit_msg>my mistake...<commit_after>// Program.cpp

#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/PropertyChoice.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
#include "CNCConfig.h"

bool COperations::CanAdd(HeeksObj* object)
{
	return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}

void COperations::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Operations" );
	root->LinkEndChild( element );
	WriteBaseXML(element);
}

//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
	COperations* new_object = new COperations;
	new_object->ReadBaseXML(pElem);
	return new_object;
}

static COperations* object_for_tools = NULL;

class SetAllActive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Active");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = true;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setactive");}
};

static SetAllActive set_all_active;

class SetAllInactive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Inactive");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = false;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setinactive");}
};

static SetAllInactive set_all_inactive;

void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	object_for_tools = this;
	t_list->push_back(&set_all_active);
	t_list->push_back(&set_all_inactive);

	ObjList::GetTools(t_list, p);
}

CProgram::CProgram():m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
	CNCConfig config;
	config.Read(_T("ProgramMachine"), &m_machine, _T("nc.iso"));
	config.Read(_T("ProgramOutputFile"), &m_output_file, _T("/tmp/test.tap"));
	config.Read(_T("ProgramUnits"), &m_units, 1.0);
}

HeeksObj *CProgram::MakeACopy(void)const
{
	return new CProgram(*this);
}

void CProgram::CopyFrom(const HeeksObj* object)
{
	operator=(*((CProgram*)object));
}

static void on_set_machine(const wxChar* value, HeeksObj* object)
{
	((CProgram*)object)->m_machine = value;
	CNCConfig config;
	config.Write(_T("ProgramMachine"), ((CProgram*)object)->m_machine);
}

static void on_set_output_file(const wxChar* value, HeeksObj* object)
{
	((CProgram*)object)->m_output_file = value;
	CNCConfig config;
	config.Write(_T("ProgramOutputFile"), ((CProgram*)object)->m_output_file);
}

static void on_set_units(int value, HeeksObj* object)
{
	((CProgram*)object)->m_units = (value == 0) ? 1.0:25.4;
	CNCConfig config;
	config.Write(_T("ProgramUnits"), ((CProgram*)object)->m_units);

	// also change HeeksCAD's view units automatically
	heeksCAD->SetViewUnits(((CProgram*)object)->m_units, true);
}

void CProgram::GetProperties(std::list<Property *> *list)
{
	list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
	list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
	{
		std::list< wxString > choices;
		choices.push_back ( wxString ( _("mm") ) );
		choices.push_back ( wxString ( _("inch") ) );
		int choice = 0;
		if(m_units > 25.0)choice = 1;
		list->push_back ( new PropertyChoice ( _("units"),  choices, choice, this, on_set_units ) );
	}
	HeeksObj::GetProperties(list);
}

bool CProgram::CanAdd(HeeksObj* object)
{
	return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}

bool CProgram::CanAddTo(HeeksObj* owner)
{
	return owner->GetType() == DocumentType;
}

void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
	if(marked_object->m_map.size() > 0)
	{
		MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
		if(sub_marked_object)
		{
			HeeksObj* object = sub_marked_object->m_map.begin()->first;
			if(object && object->GetType() == NCCodeType)
			{
				((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
			}
		}
	}
}

void CProgram::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Program" );
	root->LinkEndChild( element );
	element->SetAttribute("machine", Ttc(m_machine.c_str()));
	element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
	element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
	element->SetDoubleAttribute("units", m_units);

	WriteBaseXML(element);
}

bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
	if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
	if(object->GetType() == OperationsType)m_operations = (COperations*)object;
	return ObjList::Add(object, prev_object);
}

void CProgram::Remove(HeeksObj* object)
{
	 // these shouldn't happen, though
	if(object == m_nc_code)m_nc_code = NULL;
	else if(object == m_operations)m_operations = NULL;

	ObjList::Remove(object);
}

// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
	CProgram* new_object = new CProgram;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
		else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
		else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
		else if(name == "units"){new_object->m_units = a->DoubleValue();}
	}

	new_object->ReadBaseXML(pElem);
	theApp.m_program = new_object;

	return new_object;
}

void CProgram::RewritePythonProgram()
{
	theApp.m_program_canvas->m_textCtrl->Clear();
	CZigZag::number_for_stl_file = 1;
	CAdaptive::number_for_stl_file = 1;

	bool profile_op_exists = false;
	bool pocket_op_exists = false;
	bool zigzag_op_exists = false;
	bool adaptive_op_exists = false;
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		if(object->GetType() == ProfileType)
		{
			if(((CProfile*)object)->m_active)profile_op_exists = true;
		}
		else if(object->GetType() == PocketType)
		{
			if(((CPocket*)object)->m_active)pocket_op_exists = true;
		}
		else if(object->GetType() == ZigZagType)
		{
			if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
		}
		else if(object->GetType() == AdaptiveType)
		{
			if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
		}
	}

	// add standard stuff at the top
	//hackhack, make it work on unix with FHS
#ifndef WIN32
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'/usr/lib/heekscnc/')\n"));
#endif
	// kurve related things
	if(profile_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
	}

	// area related things
	if(pocket_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
	}

	// pycam stuff
	if(zigzag_op_exists)
	{
#ifdef WIN32
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
#endif
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// actp
	if(adaptive_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// machine general stuff
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));

	// specific machine
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// output file
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));

	// begin program
	//theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
	if(m_units > 25.0)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("imperial()\n"));
	}
	else
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
	}
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// write the operations
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		switch(object->GetType())
		{
		case ProfileType:
			if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
			break;
		case PocketType:
			if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
			break;
		case ZigZagType:
			if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
			break;
		case AdaptiveType:
			if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
			break;
		}
	}
}

ProgramUserType CProgram::GetUserType()
{
	if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
	if(m_script_edited)return ProgramUserTypeScript;
	if(m_operations->GetFirstChild())return ProgramUserTypeTree;
	return ProgramUserTypeUnkown;
}

void CProgram::UpdateFromUserType()
{
#if 0
	switch(GetUserType())
	{
	case ProgramUserTypeUnkown:

	case tree:
   Enable "Operations" icon in tree
     editing the tree, recreates the python script
   Read only "Program" window
     pressing "Post-process" creates the NC code ( and backplots it )
   Read only "Output" window
   Disable all buttons on "Output" window

	}
#endif
}
<|endoftext|>


<commit_before>#include "ReactorX.h"
#include "structures.h"

namespace reactorx {

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ReactorX::ReactorX(cyclus::Context* ctx) : cyclus::Facility(ctx) {
/*
    start_time_ = ctx->time();  // Start time is the current time
    cycle_end_ = start_time_;   // First cycle happens at the start time
*/
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string ReactorX::str() {
  return Facility::str();
}

//std::map<std::string, LibInfo> global_libs;

// First tick initializes the reactor. Not used later.
void ReactorX::Tick() {
    std::cout << "Hello world, I am ReactorX" << std::endl;

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ReactorX::Tock() {

}

// The reactor requests the amount of regions it needs
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr> ReactorX::GetMatlRequests() {
    /*
    using cyclus::RequestPortfolio;
    using cyclus::Material;
    using cyclus::CapacityConstraint;
    using cyclus::Composition;
    using cyclus::CompMap;

    std::set<RequestPortfolio<Material>::Ptr> ports;

    // Check refuel time
    cyclus::Context* ctx = context();
    if ((ctx->time() != cycle_end_ && inventory.count() != 0) || shutdown_ == true  ||
       outage_remaining_ > 0) {return ports;}

    CompMap cm;
    Material::Ptr target = Material::CreateUntracked(core_mass/regions, Composition::CreateFromAtom(cm));

    RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
    float qty;

    if (inventory.count() == 0) {
        // First loading, all regions need to be loaded with fuel

        if (target_burnup == 0) {
            // Forward mode

            for(int i = 0; i < regions; i++){
            // Handles if initial load regions are defined
            // Checks to see if there is a next in_commod to request, otherwise defualts to in_commods[0]
                if(in_commods.size() > i+1){
                    port->AddRequest(target, this, in_commods[i+1]);
                } else {
                    port->AddRequest(target, this, in_commods[0]);
                }
            }
        } else {
            // Blending mode

            for(int i = 0; i < regions; i++){
                port->AddRequest(target, this, in_commods[0]);
            }
        }
        qty = core_mass;
    } else {
        // One region refuel

        port->AddRequest(target, this, in_commods[0]);
        qty = core_mass/regions;
    }

    CapacityConstraint<Material> cc(qty);

    port->AddConstraint(cc);
    ports.insert(port);

    return ports;
    */
    using cyclus::RequestPortfolio;
    using cyclus::Material;
    std::set<RequestPortfolio<Material>::Ptr> ports;
    return ports;
}

// Accept fuel offered
void ReactorX::AcceptMatlTrades(const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
                                        cyclus::Material::Ptr> >& responses) {
/*
    if(shutdown_ != true){
        std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >::const_iterator it;
        cyclus::Composition::Ptr compost;

        if(target_burnup == 0){
            for (it = responses.begin(); it != responses.end(); ++it) {
                //std::cout << " incoming mass: " << it->second->quantity() << std::endl;
                inventory.Push(it->second);
                compost = it->second->comp();
                cyclus::CompMap cmap = compost->mass();
            }
        } else {
            //Operational reloading
            for (it = responses.begin(); it != responses.end(); ++it) {
                if(it->first.request->commodity() == in_commods[0]){
                    inventory.Push(it->second);
                }
            }
        }
    }
    */
}

// Offer materials
std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> ReactorX::GetMatlBids(
                            cyclus::CommodMap<cyclus::Material>::type& commod_requests) {

/*
    // Offer either a single batch or a full core based on shutdown condition
    //std::cout << "RX GetMatBid" << std::endl;
    using cyclus::BidPortfolio;
    using cyclus::CapacityConstraint;
    using cyclus::Converter;
    using cyclus::Material;
    using cyclus::Request;

    cyclus::Context* ctx = context();
    std::set<BidPortfolio<Material>::Ptr> ports;
    BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());

    // If its not the end of a cycle dont get rid of your fuel
    if (ctx->time() != cycle_end_ && storage_.count() == 0){
        return ports;
    }

    // If theres nothing to give dont offer anything
    if (storage_.count() == 0){return ports;}

    // Put everything in inventory to manifest
    std::vector<cyclus::Material::Ptr> manifest;
    //removing materials from storage
    int pop_number = 0;
    for(int i = 0; i < decay_times_.size(); i++){
        if(decay_times_[i] > decay_time_){
            pop_number++;
        }
    }
    manifest = cyclus::ResCast<Material>(storage_.PopN(storage_.count()));

    //Offering Bids
    std::vector<Request<Material>*>& requests = commod_requests[out_commod];
    std::vector<Request<Material>*>::iterator it;
    for (it = requests.begin(); it != requests.end(); ++it) {
        Request<Material>* req = *it;
        if (req->commodity() == out_commod) {
            for(int i = 0; i < pop_number; i++) {
                Material::Ptr offer = Material::CreateUntracked(core_mass/regions, manifest[i]->comp());
                port->AddBid(req, offer, this);
            }
        }
    }
    storage_.PushAll(manifest);
    ports.insert(port);
    //std::cout << "end getmatlbids" << std::endl;
    return ports;
*/
    using cyclus::BidPortfolio;
    using cyclus::Material;
    std::set<BidPortfolio<Material>::Ptr> ports;
    return ports;
}

// Discharging fuel from the reactor
void ReactorX::GetMatlTrades(const std::vector< cyclus::Trade<cyclus::Material> >& trades,
        std::vector<std::pair<cyclus::Trade<cyclus::Material>,cyclus::Material::Ptr> >& responses) {
    /*
    using cyclus::Material;
    using cyclus::Trade;
    cyclus::Context* ctx = context();
    //std::cout << "RX getTRADE START" << std::endl;
    std::vector< cyclus::Trade<cyclus::Material> >::const_iterator it;
    for (it = trades.begin(); it != trades.end(); ++it) {
        cyclus::Material::Ptr discharge = cyclus::ResCast<Material>(storage_.Pop());
        discharge->Decay(ctx->time());
        decay_times_.erase(decay_times_.begin());
        responses.push_back(std::make_pair(*it, discharge));
    }
    //std::cout << "RX getTRADE end" << std::endl;
    */
}

// WARNING! Do not change the following this function!!! This enables your
// archetype to be dynamically loaded and any alterations will cause your
// archetype to fail.
extern "C" cyclus::Agent* ConstructReactorX(cyclus::Context* ctx) {
  return new ReactorX(ctx);
}

}  // namespace ReactorX
<commit_msg>note for restarting work later<commit_after>#include "ReactorX.h"
#include "structures.h"

namespace reactorx {

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ReactorX::ReactorX(cyclus::Context* ctx) : cyclus::Facility(ctx) {
/*
    start_time_ = ctx->time();  // Start time is the current time
    cycle_end_ = start_time_;   // First cycle happens at the start time
*/
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string ReactorX::str() {
  return Facility::str();
}

//std::map<std::string, LibInfo> global_libs;

// First tick initializes the reactor. Not used later.
void ReactorX::Tick() {
    std::cout << "Hello world, I am ReactorX" << std::endl;

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ReactorX::Tock() {

}

// The reactor requests the amount of regions it needs
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr> ReactorX::GetMatlRequests() {
    /// gotta cast all connected fuel facilities here, calculate what's needed and request accordingly
    /*
    using cyclus::RequestPortfolio;
    using cyclus::Material;
    using cyclus::CapacityConstraint;
    using cyclus::Composition;
    using cyclus::CompMap;

    std::set<RequestPortfolio<Material>::Ptr> ports;

    // Check refuel time
    cyclus::Context* ctx = context();
    if ((ctx->time() != cycle_end_ && inventory.count() != 0) || shutdown_ == true  ||
       outage_remaining_ > 0) {return ports;}

    CompMap cm;
    Material::Ptr target = Material::CreateUntracked(core_mass/regions, Composition::CreateFromAtom(cm));

    RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
    float qty;

    if (inventory.count() == 0) {
        // First loading, all regions need to be loaded with fuel

        if (target_burnup == 0) {
            // Forward mode

            for(int i = 0; i < regions; i++){
            // Handles if initial load regions are defined
            // Checks to see if there is a next in_commod to request, otherwise defualts to in_commods[0]
                if(in_commods.size() > i+1){
                    port->AddRequest(target, this, in_commods[i+1]);
                } else {
                    port->AddRequest(target, this, in_commods[0]);
                }
            }
        } else {
            // Blending mode

            for(int i = 0; i < regions; i++){
                port->AddRequest(target, this, in_commods[0]);
            }
        }
        qty = core_mass;
    } else {
        // One region refuel

        port->AddRequest(target, this, in_commods[0]);
        qty = core_mass/regions;
    }

    CapacityConstraint<Material> cc(qty);

    port->AddConstraint(cc);
    ports.insert(port);

    return ports;
    */
    using cyclus::RequestPortfolio;
    using cyclus::Material;
    std::set<RequestPortfolio<Material>::Ptr> ports;
    return ports;
}

// Accept fuel offered
void ReactorX::AcceptMatlTrades(const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
                                        cyclus::Material::Ptr> >& responses) {
/*
    if(shutdown_ != true){
        std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >::const_iterator it;
        cyclus::Composition::Ptr compost;

        if(target_burnup == 0){
            for (it = responses.begin(); it != responses.end(); ++it) {
                //std::cout << " incoming mass: " << it->second->quantity() << std::endl;
                inventory.Push(it->second);
                compost = it->second->comp();
                cyclus::CompMap cmap = compost->mass();
            }
        } else {
            //Operational reloading
            for (it = responses.begin(); it != responses.end(); ++it) {
                if(it->first.request->commodity() == in_commods[0]){
                    inventory.Push(it->second);
                }
            }
        }
    }
    */
}

// Offer materials
std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> ReactorX::GetMatlBids(
                            cyclus::CommodMap<cyclus::Material>::type& commod_requests) {

/*
    // Offer either a single batch or a full core based on shutdown condition
    //std::cout << "RX GetMatBid" << std::endl;
    using cyclus::BidPortfolio;
    using cyclus::CapacityConstraint;
    using cyclus::Converter;
    using cyclus::Material;
    using cyclus::Request;

    cyclus::Context* ctx = context();
    std::set<BidPortfolio<Material>::Ptr> ports;
    BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());

    // If its not the end of a cycle dont get rid of your fuel
    if (ctx->time() != cycle_end_ && storage_.count() == 0){
        return ports;
    }

    // If theres nothing to give dont offer anything
    if (storage_.count() == 0){return ports;}

    // Put everything in inventory to manifest
    std::vector<cyclus::Material::Ptr> manifest;
    //removing materials from storage
    int pop_number = 0;
    for(int i = 0; i < decay_times_.size(); i++){
        if(decay_times_[i] > decay_time_){
            pop_number++;
        }
    }
    manifest = cyclus::ResCast<Material>(storage_.PopN(storage_.count()));

    //Offering Bids
    std::vector<Request<Material>*>& requests = commod_requests[out_commod];
    std::vector<Request<Material>*>::iterator it;
    for (it = requests.begin(); it != requests.end(); ++it) {
        Request<Material>* req = *it;
        if (req->commodity() == out_commod) {
            for(int i = 0; i < pop_number; i++) {
                Material::Ptr offer = Material::CreateUntracked(core_mass/regions, manifest[i]->comp());
                port->AddBid(req, offer, this);
            }
        }
    }
    storage_.PushAll(manifest);
    ports.insert(port);
    //std::cout << "end getmatlbids" << std::endl;
    return ports;
*/
    using cyclus::BidPortfolio;
    using cyclus::Material;
    std::set<BidPortfolio<Material>::Ptr> ports;
    return ports;
}

// Discharging fuel from the reactor
void ReactorX::GetMatlTrades(const std::vector< cyclus::Trade<cyclus::Material> >& trades,
        std::vector<std::pair<cyclus::Trade<cyclus::Material>,cyclus::Material::Ptr> >& responses) {
    /*
    using cyclus::Material;
    using cyclus::Trade;
    cyclus::Context* ctx = context();
    //std::cout << "RX getTRADE START" << std::endl;
    std::vector< cyclus::Trade<cyclus::Material> >::const_iterator it;
    for (it = trades.begin(); it != trades.end(); ++it) {
        cyclus::Material::Ptr discharge = cyclus::ResCast<Material>(storage_.Pop());
        discharge->Decay(ctx->time());
        decay_times_.erase(decay_times_.begin());
        responses.push_back(std::make_pair(*it, discharge));
    }
    //std::cout << "RX getTRADE end" << std::endl;
    */
}

// WARNING! Do not change the following this function!!! This enables your
// archetype to be dynamically loaded and any alterations will cause your
// archetype to fail.
extern "C" cyclus::Agent* ConstructReactorX(cyclus::Context* ctx) {
  return new ReactorX(ctx);
}

}  // namespace ReactorX
<|endoftext|>


<commit_before>/**
 * @file
 * @author lpraz
 *
 * @section DESCRIPTION
 * Defines methods for the TagFile class.
 */

// Stdlib includes
#include <algorithm>
#include <iostream>
#include <sstream>

// Local includes
#include "Operations.hpp"

// Include own header
#include "TagFile.hpp"

namespace Tiger {
    // private:

    /**
     * Reads the next string found within a pair of double quotation
     * marks ("), taking whitespace into account.
     *
     * @param stream The stream to read from.
     * @returns The string that was read.
     */
    std::string TagFile::readQuotedString(std::istream& stream) {
        stream >> std::noskipws;
        std::stringstream resultStream;
        char nextChar;

        while (stream >> nextChar)
            if (nextChar == '"')
                break;

        while (stream >> nextChar) {
            if (nextChar == '"')
                break;
            else
                resultStream << nextChar;
        }

        return resultStream.str();
    }

    // public:

    /**
     * Initializes (constructs) a TagFile by reading its contents from
     * disk, if they exist.
     */
    TagFile::TagFile() {
        std::ifstream tagFileInputStream;
        homeDirectory = getenv("HOME");
        tagFileInputStream.open(homeDirectory + tagFilePath);
        tagFileInputStream >> std::noskipws;

        if (!tagFileInputStream.good())
            return;

        // TODO: actually stop infinite loop when reading non-empty file here
        while (!tagFileInputStream.eof()) {
            std::string tag = readQuotedString(tagFileInputStream);
            std::vector<std::string> files;

            while (tagFileInputStream.peek() != '\n')
                files.push_back(readQuotedString(tagFileInputStream));

            tagDict.insert({tag, files});
        }
    }

    /**
     * Saves any changes to TagFile::tags to disk.
     */
    void TagFile::close() {
        std::ofstream tagFileOutputStream;
        tagFileOutputStream.open(homeDirectory + tagFilePath);

        bool firstTag = true;

        for (auto tag : tagDict) {
            if (firstTag)
                firstTag = false;
            else
                tagFileOutputStream << "\n";

            tagFileOutputStream << "\"" << tag.first << "\":";
            bool firstFile = true;

            for (auto file : tag.second) {
                if (firstFile)
                    firstFile = false;
                else
                    tagFileOutputStream << ",";

                tagFileOutputStream << "\"" << file << "\"";
            }
        }
    }

    /**
     * Accessor method for the TagFile::tags field.
     *
     * @returns The current hash table of strings (tags) and vectors of
     *          strings (files) held in TagFile::tagDict.
     */
    std::unordered_map<std::string, std::vector<std::string>>&
            TagFile::getTags(void) {
        return tagDict;
    }
}
<commit_msg>Fixed the infinite loop EOF bug in TagFile<commit_after>/**
 * @file
 * @author lpraz
 *
 * @section DESCRIPTION
 * Defines methods for the TagFile class.
 */

// Stdlib includes
#include <algorithm>
#include <iostream>
#include <sstream>

// Local includes
#include "Operations.hpp"

// Include own header
#include "TagFile.hpp"

namespace Tiger {
    // private:

    /**
     * Reads the next string found within a pair of double quotation
     * marks ("), taking whitespace into account.
     *
     * @param stream The stream to read from.
     * @returns The string that was read.
     */
    std::string TagFile::readQuotedString(std::istream& stream) {
        stream >> std::noskipws;
        std::stringstream resultStream;
        char nextChar;

        while (stream >> nextChar != '"')
            if (nextChar == '"')
                break;

        while (stream >> nextChar) {
            if (nextChar == '"')
                break;
            else
                resultStream << nextChar;
        }

        return resultStream.str();
    }

    // public:

    /**
     * Initializes (constructs) a TagFile by reading its contents from
     * disk, if they exist.
     */
    TagFile::TagFile() {
        std::ifstream tagFileInputStream;
        homeDirectory = getenv("HOME");
        tagFileInputStream.open(homeDirectory + tagFilePath);
        tagFileInputStream >> std::noskipws;

        if (!tagFileInputStream.good())
            return;

        // TODO: eliminate the null string tag
        while (tagFileInputStream.good()) {
            std::string tag = readQuotedString(tagFileInputStream);
            std::vector<std::string> files;

            while (tagFileInputStream.peek() != '\n' &&
                    tagFileInputStream.good())
                files.push_back(readQuotedString(tagFileInputStream));

            tagDict.insert({tag, files});
        }
    }

    /**
     * Saves any changes to TagFile::tags to disk.
     */
    void TagFile::close() {
        std::ofstream tagFileOutputStream;
        tagFileOutputStream.open(homeDirectory + tagFilePath);

        bool firstTag = true;

        for (auto tag : tagDict) {
            if (firstTag)
                firstTag = false;
            else
                tagFileOutputStream << "\n";

            tagFileOutputStream << "\"" << tag.first << "\":";
            bool firstFile = true;

            for (auto file : tag.second) {
                if (firstFile)
                    firstFile = false;
                else
                    tagFileOutputStream << ",";

                tagFileOutputStream << "\"" << file << "\"";
            }
        }
    }

    /**
     * Accessor method for the TagFile::tags field.
     *
     * @returns The current hash table of strings (tags) and vectors of
     *          strings (files) held in TagFile::tagDict.
     */
    std::unordered_map<std::string, std::vector<std::string>>&
            TagFile::getTags(void) {
        return tagDict;
    }
}
<|endoftext|>


<commit_before>#include "../ui.h"
#include "ui-node.h"
#include "nbind/api.h"

class UiWindow {
	DEFINE_EVENT(onClosing)
	DEFINE_EVENT(onContentSizeChanged)

  private:
	uiWindow *win;

  public:
	UiWindow(const char *title, int width, int height, bool hasMenubar);
	uiWindow *getHandle();
	void show();
	void close();
	void setMargined(bool margined);
	bool getMargined();
	void setChild(UiControl *control);
	void setTitle(const char *title);
	const char *getTitle();
	bool getFullscreen();
	void setFullscreen(bool value);
	bool getBorderless();
	void setBorderless(bool value);
	Size getContentSize();
	void setContentSize(Size value);
};

static int UiWindow_onClosing(uiWindow *w, void *data) {
	nbind::cbFunction *cb = (nbind::cbFunction *)data;
	(*cb)();
	return 0;
}

void UiWindow::onClosing(nbind::cbFunction &cb) {
	onClosingCallback = new nbind::cbFunction(cb);
	uiWindowOnClosing((uiWindow *)getHandle(), UiWindow_onClosing,
					  onClosingCallback);
}

static void UiWindow_onContentSizeChanged(uiWindow *w, void *data) {
	nbind::cbFunction *cb = (nbind::cbFunction *)data;
	(*cb)();
}

void UiWindow::onContentSizeChanged(nbind::cbFunction &cb) {
	onContentSizeChangedCallback = new nbind::cbFunction(cb);
	uiWindowOnContentSizeChanged((uiWindow *)getHandle(),
								 UiWindow_onContentSizeChanged,
								 onContentSizeChangedCallback);
}

UiWindow::UiWindow(const char *title, int width, int height, bool hasMenubar) {
	win = uiNewWindow(title, width, height, hasMenubar);
}

uiWindow *UiWindow::getHandle() {
	return win;
}

void UiWindow::show() {
	uiControlShow(uiControl(win));
}

void UiWindow::close() {
	uiControlDestroy(uiControl(win));
}

void UiWindow::setMargined(bool margined) {
	uiWindowSetMargined(win, margined);
}

bool UiWindow::getMargined() {
	return uiWindowMargined(win);
}

void UiWindow::setChild(UiControl *control) {
	uiWindowSetChild(win, control->getHandle());
}

void UiWindow::setTitle(const char *title) {
	uiWindowSetTitle(win, title);
}

const char *UiWindow::getTitle() {
	return uiWindowTitle(win);
}

bool UiWindow::getFullscreen() {
	return uiWindowFullscreen(win);
}

void UiWindow::setFullscreen(bool value) {
	uiWindowSetFullscreen(win, value);
}

void UiWindow::setBorderless(bool value) {
	uiWindowSetBorderless(win, value);
}
bool UiWindow::getBorderless() {
	return uiWindowBorderless(win);
}

void UiWindow::setContentSize(Size value) {
	uiWindowSetContentSize(win, value.getWidth(), value.getHeight());
}

Size UiWindow::getContentSize() {
	int w = 0;
	int h = 0;
	uiWindowContentSize(win, &w, &h);
	return Size(w, h);
}

NBIND_CLASS(UiWindow) {
	construct<const char *, int, int, bool>();
	method(show);
	method(close);
	method(setChild);
	method(onClosing);
	method(onContentSizeChanged);
	getset(getMargined, setMargined);
	getset(getTitle, setTitle);

	getset(getContentSize, setContentSize);
	method(getContentSize);
	method(setContentSize);
	method(onContentSizeChanged);

	getset(getFullscreen, setFullscreen);
	method(getFullscreen);
	method(setFullscreen);
	getset(getBorderless, setBorderless);
	method(getBorderless);
	method(setBorderless);
}

struct UiDialogs {

	static char *openFile(UiWindow *parent) {
		return uiOpenFile(parent->getHandle());
	}

	static char *saveFile(UiWindow *parent) {
		return uiSaveFile(parent->getHandle());
	}

	static void msgBox(UiWindow *parent, const char *title,
					   const char *description) {
		uiMsgBox(parent->getHandle(), title, description);
	}

	static void msgBoxError(UiWindow *parent, const char *title,
							const char *description) {
		uiMsgBoxError(parent->getHandle(), title, description);
	}
};

NBIND_CLASS(UiDialogs) {
	method(openFile);
	method(saveFile);
	method(msgBox);
	method(msgBoxError);
}
<commit_msg>std::string --> UiWindow<commit_after>#include <string>
#include "../ui.h"
#include "ui-node.h"
#include "nbind/api.h"

class UiWindow {
	DEFINE_EVENT(onClosing)
	DEFINE_EVENT(onContentSizeChanged)

  private:
	uiWindow *win;

  public:
	UiWindow(std::string title, int width, int height, bool hasMenubar);
	uiWindow *getHandle();
	void show();
	void close();
	void setMargined(bool margined);
	bool getMargined();
	void setChild(UiControl *control);
	void setTitle(std::string title);
	std::string getTitle();
	bool getFullscreen();
	void setFullscreen(bool value);
	bool getBorderless();
	void setBorderless(bool value);
	Size getContentSize();
	void setContentSize(Size value);
};

static int UiWindow_onClosing(uiWindow *w, void *data) {
	nbind::cbFunction *cb = (nbind::cbFunction *)data;
	(*cb)();
	return 0;
}

void UiWindow::onClosing(nbind::cbFunction &cb) {
	onClosingCallback = new nbind::cbFunction(cb);
	uiWindowOnClosing(uiWindow(getHandle()), UiWindow_onClosing,
					  onClosingCallback);
}

static void UiWindow_onContentSizeChanged(uiWindow *w, void *data) {
	nbind::cbFunction *cb = (nbind::cbFunction *)data;
	(*cb)();
}

void UiWindow::onContentSizeChanged(nbind::cbFunction &cb) {
	onContentSizeChangedCallback = new nbind::cbFunction(cb);
	uiWindowOnContentSizeChanged(uiWindow(getHandle()),
								 UiWindow_onContentSizeChanged,
								 onContentSizeChangedCallback);
}

UiWindow::UiWindow(std::string title, int width, int height, bool hasMenubar) {
	win = uiNewWindow(title.c_str(), width, height, hasMenubar);
}

uiWindow *UiWindow::getHandle() {
	return win;
}

void UiWindow::show() {
	uiControlShow(uiControl(win));
}

void UiWindow::close() {
	uiControlDestroy(uiControl(win));
}

void UiWindow::setMargined(bool margined) {
	uiWindowSetMargined(win, margined);
}

bool UiWindow::getMargined() {
	return uiWindowMargined(win);
}

void UiWindow::setChild(UiControl *control) {
	uiWindowSetChild(win, control->getHandle());
}

void UiWindow::setTitle(std::string title) {
	uiWindowSetTitle(win, title.c_str());
}

std::string UiWindow::getTitle() {
	char *char_ptr = uiWindowTitle(win);
	std::string s(char_ptr);
	uiFreeText(char_ptr);
	return s;
}

bool UiWindow::getFullscreen() {
	return uiWindowFullscreen(win);
}

void UiWindow::setFullscreen(bool value) {
	uiWindowSetFullscreen(win, value);
}

void UiWindow::setBorderless(bool value) {
	uiWindowSetBorderless(win, value);
}
bool UiWindow::getBorderless() {
	return uiWindowBorderless(win);
}

void UiWindow::setContentSize(Size value) {
	uiWindowSetContentSize(win, value.getWidth(), value.getHeight());
}

Size UiWindow::getContentSize() {
	int w = 0;
	int h = 0;
	uiWindowContentSize(win, &w, &h);
	return Size(w, h);
}

NBIND_CLASS(UiWindow) {
	construct<std::string, int, int, bool>();
	method(show);
	method(close);
	method(setChild);
	method(onClosing);
	method(onContentSizeChanged);
	getset(getMargined, setMargined);
	getset(getTitle, setTitle);

	getset(getContentSize, setContentSize);
	method(getContentSize);
	method(setContentSize);
	method(onContentSizeChanged);

	getset(getFullscreen, setFullscreen);
	method(getFullscreen);
	method(setFullscreen);
	getset(getBorderless, setBorderless);
	method(getBorderless);
	method(setBorderless);
}

struct UiDialogs {

	static std::string openFile(UiWindow *parent) {
		char *char_ptr = uiOpenFile(parent->getHandle());
		std::string s(char_ptr);
		uiFreeText(char_ptr);
		return s;
	}

	static std::string saveFile(UiWindow *parent) {
		char *char_ptr = uiSaveFile(parent->getHandle());
		std::string s(char_ptr);
		uiFreeText(char_ptr);
		return s;
	}

	static void msgBox(UiWindow *parent, std::string title,
					   std::string description) {
		uiMsgBox(parent->getHandle(), title.c_str(), description.c_str());
	}

	static void msgBoxError(UiWindow *parent, std::string title,
							std::string description) {
		uiMsgBoxError(parent->getHandle(), title.c_str(), description.c_str());
	}
};

NBIND_CLASS(UiDialogs) {
	method(openFile);
	method(saveFile);
	method(msgBox);
	method(msgBoxError);
}
<|endoftext|>


<commit_before>/*
 * Copyright 1993-2010 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

#include <shrUtils.h>
#include <shrQATest.h>
#include <cutil_inline.h>
#include <cuda_runtime.h>
#include "scan_common.h"

int main(int argc, char **argv)
{
    shrQAStart(argc, argv);

    // Start logs
    shrSetLogFileName ("scan.txt");

    //Use command-line specified CUDA device, otherwise use device with highest Gflops/s
    if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") )
        cutilDeviceInit(argc, argv);
    else
        cudaSetDevice( cutGetMaxGflopsDeviceId() );

    uint *d_Input, *d_Output;
    uint *h_Input, *h_OutputCPU, *h_OutputGPU;
    uint hTimer;
    const uint N = 13 * (1048576 / 2)/256;
    //const uint N = 13 * 1048576 / 2;

    shrLog("Allocating and initializing host arrays...\n");
        cutCreateTimer(&hTimer);
        h_Input     = (uint *)malloc(N * sizeof(uint));
        h_OutputCPU = (uint *)malloc(N * sizeof(uint));
        h_OutputGPU = (uint *)malloc(N * sizeof(uint));
        srand(2009);
        for(uint i = 0; i < N; i++)
            h_Input[i] = rand();

    shrLog("Allocating and initializing CUDA arrays...\n");
        cutilSafeCall( cudaMalloc((void **)&d_Input, N * sizeof(uint)) );
        cutilSafeCall( cudaMalloc((void **)&d_Output, N * sizeof(uint)) );
        cutilSafeCall( cudaMemcpy(d_Input, h_Input, N * sizeof(uint), cudaMemcpyHostToDevice) );

    shrLog("Initializing CUDA-C scan...\n\n");
        initScan();

    int globalFlag = 1;
    size_t szWorkgroup;
    const int iCycles = 1;
    shrLog("*** Running GPU scan for short arrays (%d identical iterations)...\n\n", iCycles);
        for(uint arrayLength = MIN_SHORT_ARRAY_SIZE; arrayLength <= MAX_SHORT_ARRAY_SIZE; arrayLength <<= 1){
            shrLog("Running scan for %u elements (%u arrays)...\n", arrayLength, N / arrayLength);
                cutilSafeCall( cutilDeviceSynchronize() );
                cutResetTimer(hTimer);
                cutStartTimer(hTimer);
                for(int i = 0; i < iCycles; i++)
                {
                    szWorkgroup = scanExclusiveShort(d_Output, d_Input, N / arrayLength, arrayLength);
                }
                cutilSafeCall( cutilDeviceSynchronize());
                cutStopTimer(hTimer);
                double timerValue = 1.0e-3 * cutGetTimerValue(hTimer) / iCycles;

            shrLog("Validating the results...\n");
                shrLog("...reading back GPU results\n");
                    cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, N * sizeof(uint), cudaMemcpyDeviceToHost) );

                shrLog(" ...scanExclusiveHost()\n");
                    scanExclusiveHost(h_OutputCPU, h_Input, N / arrayLength, arrayLength);

                // Compare GPU results with CPU results and accumulate error for this test
                shrLog(" ...comparing the results\n");
                    int localFlag = 1;
                    for(uint i = 0; i < N; i++)
                    {
                        if(h_OutputCPU[i] != h_OutputGPU[i])
                        {
                            localFlag = 0;
                            break;
                        }
                    }

                // Log message on individual test result, then accumulate to global flag
                shrLog(" ...Results %s\n\n", (localFlag == 1) ? "Match" : "DON'T Match !!!");
                globalFlag = globalFlag && localFlag;

                // Data log
                if (arrayLength == MAX_SHORT_ARRAY_SIZE)
                {
                    shrLog("\n");
                    shrLogEx(LOGBOTH | MASTER, 0, "scan-Short, Throughput = %.4f MElements/s, Time = %.5f s, Size = %u Elements, NumDevsUsed = %u, Workgroup = %u\n",
                           (1.0e-6 * (double)arrayLength/timerValue), timerValue, arrayLength, 1, szWorkgroup);
                    shrLog("\n");
                }
        }

    shrLog("***Running GPU scan for large arrays (%u identical iterations)...\n\n", iCycles);
        for(uint arrayLength = MIN_LARGE_ARRAY_SIZE; arrayLength <= MAX_LARGE_ARRAY_SIZE; arrayLength <<= 1){
            shrLog("Running scan for %u elements (%u arrays)...\n", arrayLength, N / arrayLength);
                cutilSafeCall( cutilDeviceSynchronize() );
                cutResetTimer(hTimer);
                cutStartTimer(hTimer);
                for(int i = 0; i < iCycles; i++)
                {
                    szWorkgroup = scanExclusiveLarge(d_Output, d_Input, N / arrayLength, arrayLength);
                }
                cutilSafeCall( cutilDeviceSynchronize() );
                cutStopTimer(hTimer);
                double timerValue = 1.0e-3 * cutGetTimerValue(hTimer) / iCycles;

            shrLog("Validating the results...\n");
                shrLog("...reading back GPU results\n");
                    cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, N * sizeof(uint), cudaMemcpyDeviceToHost) );

                shrLog("...scanExclusiveHost()\n");
                    scanExclusiveHost(h_OutputCPU, h_Input, N / arrayLength, arrayLength);

                // Compare GPU results with CPU results and accumulate error for this test
                shrLog(" ...comparing the results\n");
                    int localFlag = 1;
                    for(uint i = 0; i < N; i++)
                    {
                        if(h_OutputCPU[i] != h_OutputGPU[i])
                        {
                            localFlag = 0;
                            break;
                        }
                    }

                // Log message on individual test result, then accumulate to global flag
                shrLog(" ...Results %s\n\n", (localFlag == 1) ? "Match" : "DON'T Match !!!");
                globalFlag = globalFlag && localFlag;

                // Data log
                if (arrayLength == MAX_LARGE_ARRAY_SIZE)
                {
                    shrLog("\n");
                    shrLogEx(LOGBOTH | MASTER, 0, "scan-Large, Throughput = %.4f MElements/s, Time = %.5f s, Size = %u Elements, NumDevsUsed = %u, Workgroup = %u\n",
                           (1.0e-6 * (double)arrayLength/timerValue), timerValue, arrayLength, 1, szWorkgroup);
                    shrLog("\n");
                }
        }

    shrLog("Shutting down...\n");
        closeScan();
        cutilSafeCall( cudaFree(d_Output));
        cutilSafeCall( cudaFree(d_Input));

        cutilCheckError( cutDeleteTimer(hTimer) );

        cutilDeviceReset();
    // pass or fail (cumulative... all tests in the loop)
		shrQAFinishExit(argc, (const char**)argv, (globalFlag ? QA_PASSED : QA_FAILED));
}
<commit_msg>Making scan identical to Akshay's from SIGMETRICS<commit_after>/*
 * Copyright 1993-2010 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

#include <shrUtils.h>
#include <shrQATest.h>
#include <cutil_inline.h>
#include <cuda_runtime.h>
#include "scan_common.h"

int main(int argc, char **argv)
{
    shrQAStart(argc, argv);

    // Start logs
    shrSetLogFileName ("scan.txt");

    //Use command-line specified CUDA device, otherwise use device with highest Gflops/s
    if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") )
        cutilDeviceInit(argc, argv);
    else
        cudaSetDevice( cutGetMaxGflopsDeviceId() );

    uint *d_Input, *d_Output;
    uint *h_Input, *h_OutputCPU, *h_OutputGPU;
    uint hTimer;
    const uint N = 13 * 1048576 / 2;

    shrLog("Allocating and initializing host arrays...\n");
        cutCreateTimer(&hTimer);
        h_Input     = (uint *)malloc(N * sizeof(uint));
        h_OutputCPU = (uint *)malloc(N * sizeof(uint));
        h_OutputGPU = (uint *)malloc(N * sizeof(uint));
        srand(2009);
        for(uint i = 0; i < N; i++)
            h_Input[i] = rand();

    shrLog("Allocating and initializing CUDA arrays...\n");
        cutilSafeCall( cudaMalloc((void **)&d_Input, N * sizeof(uint)) );
        cutilSafeCall( cudaMalloc((void **)&d_Output, N * sizeof(uint)) );
        cutilSafeCall( cudaMemcpy(d_Input, h_Input, N * sizeof(uint), cudaMemcpyHostToDevice) );

    shrLog("Initializing CUDA-C scan...\n\n");
        initScan();

    int globalFlag = 1;
    size_t szWorkgroup;
    const int iCycles = 1;
    shrLog("*** Running GPU scan for short arrays (%d identical iterations)...\n\n", iCycles);
        for(uint arrayLength = MIN_SHORT_ARRAY_SIZE; arrayLength <= MAX_SHORT_ARRAY_SIZE; arrayLength <<= 1){
            shrLog("Running scan for %u elements (%u arrays)...\n", arrayLength, N / arrayLength);
                cutilSafeCall( cutilDeviceSynchronize() );
                cutResetTimer(hTimer);
                cutStartTimer(hTimer);
                for(int i = 0; i < iCycles; i++)
                {
                    szWorkgroup = scanExclusiveShort(d_Output, d_Input, N / arrayLength, arrayLength);
                }
                cutilSafeCall( cutilDeviceSynchronize());
                cutStopTimer(hTimer);
                double timerValue = 1.0e-3 * cutGetTimerValue(hTimer) / iCycles;

            shrLog("Validating the results...\n");
                shrLog("...reading back GPU results\n");
                    cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, N * sizeof(uint), cudaMemcpyDeviceToHost) );

                shrLog(" ...scanExclusiveHost()\n");
                    scanExclusiveHost(h_OutputCPU, h_Input, N / arrayLength, arrayLength);

                // Compare GPU results with CPU results and accumulate error for this test
                shrLog(" ...comparing the results\n");
                    int localFlag = 1;
                    for(uint i = 0; i < N; i++)
                    {
                        if(h_OutputCPU[i] != h_OutputGPU[i])
                        {
                            localFlag = 0;
                            break;
                        }
                    }

                // Log message on individual test result, then accumulate to global flag
                shrLog(" ...Results %s\n\n", (localFlag == 1) ? "Match" : "DON'T Match !!!");
                globalFlag = globalFlag && localFlag;

                // Data log
                if (arrayLength == MAX_SHORT_ARRAY_SIZE)
                {
                    shrLog("\n");
                    shrLogEx(LOGBOTH | MASTER, 0, "scan-Short, Throughput = %.4f MElements/s, Time = %.5f s, Size = %u Elements, NumDevsUsed = %u, Workgroup = %u\n",
                           (1.0e-6 * (double)arrayLength/timerValue), timerValue, arrayLength, 1, szWorkgroup);
                    shrLog("\n");
                }
        }

    shrLog("***Running GPU scan for large arrays (%u identical iterations)...\n\n", iCycles);
        for(uint arrayLength = MIN_LARGE_ARRAY_SIZE; arrayLength <= MAX_LARGE_ARRAY_SIZE; arrayLength <<= 1){
            shrLog("Running scan for %u elements (%u arrays)...\n", arrayLength, N / arrayLength);
                cutilSafeCall( cutilDeviceSynchronize() );
                cutResetTimer(hTimer);
                cutStartTimer(hTimer);
                for(int i = 0; i < iCycles; i++)
                {
                    szWorkgroup = scanExclusiveLarge(d_Output, d_Input, N / arrayLength, arrayLength);
                }
                cutilSafeCall( cutilDeviceSynchronize() );
                cutStopTimer(hTimer);
                double timerValue = 1.0e-3 * cutGetTimerValue(hTimer) / iCycles;

            shrLog("Validating the results...\n");
                shrLog("...reading back GPU results\n");
                    cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, N * sizeof(uint), cudaMemcpyDeviceToHost) );

                shrLog("...scanExclusiveHost()\n");
                    scanExclusiveHost(h_OutputCPU, h_Input, N / arrayLength, arrayLength);

                // Compare GPU results with CPU results and accumulate error for this test
                shrLog(" ...comparing the results\n");
                    int localFlag = 1;
                    for(uint i = 0; i < N; i++)
                    {
                        if(h_OutputCPU[i] != h_OutputGPU[i])
                        {
                            localFlag = 0;
                            break;
                        }
                    }

                // Log message on individual test result, then accumulate to global flag
                shrLog(" ...Results %s\n\n", (localFlag == 1) ? "Match" : "DON'T Match !!!");
                globalFlag = globalFlag && localFlag;

                // Data log
                if (arrayLength == MAX_LARGE_ARRAY_SIZE)
                {
                    shrLog("\n");
                    shrLogEx(LOGBOTH | MASTER, 0, "scan-Large, Throughput = %.4f MElements/s, Time = %.5f s, Size = %u Elements, NumDevsUsed = %u, Workgroup = %u\n",
                           (1.0e-6 * (double)arrayLength/timerValue), timerValue, arrayLength, 1, szWorkgroup);
                    shrLog("\n");
                }
        }

    shrLog("Shutting down...\n");
        closeScan();
        cutilSafeCall( cudaFree(d_Output));
        cutilSafeCall( cudaFree(d_Input));

        cutilCheckError( cutDeleteTimer(hTimer) );

        cutilDeviceReset();
    // pass or fail (cumulative... all tests in the loop)
		shrQAFinishExit(argc, (const char**)argv, (globalFlag ? QA_PASSED : QA_FAILED));
}
<|endoftext|>