<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_browser_process_test.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/appcache/appcache_database.h"
#include "webkit/appcache/appcache_storage_impl.h"
#include "webkit/appcache/appcache_test_helper.h"
#include "webkit/quota/mock_special_storage_policy.h"

#include <set>

namespace {
const FilePath::CharType kTestingAppCacheDirname[] =
    FILE_PATH_LITERAL("Application Cache");

// Examples of a protected and an unprotected origin, to be used througout the
// test.
const char kProtectedManifest[] = "http://www.protected.com/cache.manifest";
const char kNormalManifest[] = "http://www.normal.com/cache.manifest";

}  // namespace

namespace appcache {

class ChromeAppCacheServiceTest : public TestingBrowserProcessTest {
 public:
  ChromeAppCacheServiceTest()
      : message_loop_(MessageLoop::TYPE_IO),
        kProtectedManifestURL(kProtectedManifest),
        kNormalManifestURL(kNormalManifest),
        db_thread_(BrowserThread::DB, &message_loop_),
        file_thread_(BrowserThread::FILE, &message_loop_),
        cache_thread_(BrowserThread::CACHE, &message_loop_),
        io_thread_(BrowserThread::IO, &message_loop_) {
  }

 protected:
  scoped_refptr<ChromeAppCacheService> CreateAppCacheService(
      const FilePath& appcache_path,
      bool init_storage);
  void InsertDataIntoAppCache(ChromeAppCacheService* appcache_service);

  MessageLoop message_loop_;
  ScopedTempDir temp_dir_;
  const GURL kProtectedManifestURL;
  const GURL kNormalManifestURL;

 private:
  BrowserThread db_thread_;
  BrowserThread file_thread_;
  BrowserThread cache_thread_;
  BrowserThread io_thread_;
};

scoped_refptr<ChromeAppCacheService>
ChromeAppCacheServiceTest::CreateAppCacheService(
    const FilePath& appcache_path,
    bool init_storage) {
  scoped_refptr<ChromeAppCacheService> appcache_service =
      new ChromeAppCacheService(NULL);
  const content::ResourceContext* resource_context = NULL;
  scoped_refptr<quota::MockSpecialStoragePolicy> mock_policy =
      new quota::MockSpecialStoragePolicy;
  mock_policy->AddProtected(kProtectedManifestURL.GetOrigin());
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(appcache_service.get(),
                        &ChromeAppCacheService::InitializeOnIOThread,
                        appcache_path,
                        resource_context,
                        mock_policy));
  // Steps needed to initialize the storage of AppCache data.
  message_loop_.RunAllPending();
  if (init_storage) {
    appcache::AppCacheStorageImpl* storage =
        static_cast<appcache::AppCacheStorageImpl*>(
            appcache_service->storage());
    storage->database_->db_connection();
    storage->disk_cache();
    message_loop_.RunAllPending();
  }
  return appcache_service;
}

void ChromeAppCacheServiceTest::InsertDataIntoAppCache(
    ChromeAppCacheService* appcache_service) {
  AppCacheTestHelper appcache_helper;
  appcache_helper.AddGroupAndCache(appcache_service, kNormalManifestURL);
  appcache_helper.AddGroupAndCache(appcache_service, kProtectedManifestURL);

  // Verify that adding the data succeeded
  std::set<GURL> origins;
  appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
  ASSERT_EQ(2UL, origins.size());
  ASSERT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
  ASSERT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
}

TEST_F(ChromeAppCacheServiceTest, KeepOnDestruction) {
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);

  // Create a ChromeAppCacheService and insert data into it
  scoped_refptr<ChromeAppCacheService> appcache_service =
      CreateAppCacheService(appcache_path, true);
  ASSERT_TRUE(file_util::PathExists(appcache_path));
  ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
  InsertDataIntoAppCache(appcache_service);

  // Test: delete the ChromeAppCacheService
  appcache_service->set_clear_local_state_on_exit(false);
  appcache_service = NULL;
  message_loop_.RunAllPending();

  // Recreate the appcache (for reading the data back)
  appcache_service = CreateAppCacheService(appcache_path, false);

  // The directory is still there
  ASSERT_TRUE(file_util::PathExists(appcache_path));

  // The appcache data is also there
  AppCacheTestHelper appcache_helper;
  std::set<GURL> origins;
  appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
  EXPECT_EQ(2UL, origins.size());
  EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
  EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
}

TEST_F(ChromeAppCacheServiceTest, RemoveOnDestruction) {
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);

  // Create a ChromeAppCacheService and insert data into it
  scoped_refptr<ChromeAppCacheService> appcache_service =
      CreateAppCacheService(appcache_path, true);
  ASSERT_TRUE(file_util::PathExists(appcache_path));
  ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
  InsertDataIntoAppCache(appcache_service);

  // Test: delete the ChromeAppCacheService
  appcache_service->set_clear_local_state_on_exit(true);
  appcache_service = NULL;
  message_loop_.RunAllPending();

  // Recreate the appcache (for reading the data back)
  appcache_service = CreateAppCacheService(appcache_path, false);

  // The directory is still there
  ASSERT_TRUE(file_util::PathExists(appcache_path));

  // The appcache data for the protected origin is there, and the data for the
  // unprotected origin was deleted.
  AppCacheTestHelper appcache_helper;
  std::set<GURL> origins;
  appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
  EXPECT_EQ(1UL, origins.size());
  EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
  EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) == origins.end());
}

}  // namespace appcache
<commit_msg>Make the membots happy again.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_browser_process_test.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/appcache/appcache_database.h"
#include "webkit/appcache/appcache_storage_impl.h"
#include "webkit/appcache/appcache_test_helper.h"
#include "webkit/quota/mock_special_storage_policy.h"

#include <set>

namespace {
const FilePath::CharType kTestingAppCacheDirname[] =
    FILE_PATH_LITERAL("Application Cache");

// Examples of a protected and an unprotected origin, to be used througout the
// test.
const char kProtectedManifest[] = "http://www.protected.com/cache.manifest";
const char kNormalManifest[] = "http://www.normal.com/cache.manifest";

}  // namespace

namespace appcache {

class ChromeAppCacheServiceTest : public TestingBrowserProcessTest {
 public:
  ChromeAppCacheServiceTest()
      : message_loop_(MessageLoop::TYPE_IO),
        kProtectedManifestURL(kProtectedManifest),
        kNormalManifestURL(kNormalManifest),
        db_thread_(BrowserThread::DB, &message_loop_),
        file_thread_(BrowserThread::FILE, &message_loop_),
        cache_thread_(BrowserThread::CACHE, &message_loop_),
        io_thread_(BrowserThread::IO, &message_loop_) {
  }

 protected:
  scoped_refptr<ChromeAppCacheService> CreateAppCacheService(
      const FilePath& appcache_path,
      bool init_storage);
  void InsertDataIntoAppCache(ChromeAppCacheService* appcache_service);

  MessageLoop message_loop_;
  ScopedTempDir temp_dir_;
  const GURL kProtectedManifestURL;
  const GURL kNormalManifestURL;

 private:
  BrowserThread db_thread_;
  BrowserThread file_thread_;
  BrowserThread cache_thread_;
  BrowserThread io_thread_;
};

scoped_refptr<ChromeAppCacheService>
ChromeAppCacheServiceTest::CreateAppCacheService(
    const FilePath& appcache_path,
    bool init_storage) {
  scoped_refptr<ChromeAppCacheService> appcache_service =
      new ChromeAppCacheService(NULL);
  const content::ResourceContext* resource_context = NULL;
  scoped_refptr<quota::MockSpecialStoragePolicy> mock_policy =
      new quota::MockSpecialStoragePolicy;
  mock_policy->AddProtected(kProtectedManifestURL.GetOrigin());
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(appcache_service.get(),
                        &ChromeAppCacheService::InitializeOnIOThread,
                        appcache_path,
                        resource_context,
                        mock_policy));
  // Steps needed to initialize the storage of AppCache data.
  message_loop_.RunAllPending();
  if (init_storage) {
    appcache::AppCacheStorageImpl* storage =
        static_cast<appcache::AppCacheStorageImpl*>(
            appcache_service->storage());
    storage->database_->db_connection();
    storage->disk_cache();
    message_loop_.RunAllPending();
  }
  return appcache_service;
}

void ChromeAppCacheServiceTest::InsertDataIntoAppCache(
    ChromeAppCacheService* appcache_service) {
  AppCacheTestHelper appcache_helper;
  appcache_helper.AddGroupAndCache(appcache_service, kNormalManifestURL);
  appcache_helper.AddGroupAndCache(appcache_service, kProtectedManifestURL);

  // Verify that adding the data succeeded
  std::set<GURL> origins;
  appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
  ASSERT_EQ(2UL, origins.size());
  ASSERT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
  ASSERT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
}

TEST_F(ChromeAppCacheServiceTest, KeepOnDestruction) {
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);

  // Create a ChromeAppCacheService and insert data into it
  scoped_refptr<ChromeAppCacheService> appcache_service =
      CreateAppCacheService(appcache_path, true);
  ASSERT_TRUE(file_util::PathExists(appcache_path));
  ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
  InsertDataIntoAppCache(appcache_service);

  // Test: delete the ChromeAppCacheService
  appcache_service->set_clear_local_state_on_exit(false);
  appcache_service = NULL;
  message_loop_.RunAllPending();

  // Recreate the appcache (for reading the data back)
  appcache_service = CreateAppCacheService(appcache_path, false);

  // The directory is still there
  ASSERT_TRUE(file_util::PathExists(appcache_path));

  // The appcache data is also there
  AppCacheTestHelper appcache_helper;
  std::set<GURL> origins;
  appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
  EXPECT_EQ(2UL, origins.size());
  EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
  EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());

  // Delete and let cleanup tasks run prior to returning.
  appcache_service = NULL;
  message_loop_.RunAllPending();
}

TEST_F(ChromeAppCacheServiceTest, RemoveOnDestruction) {
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);

  // Create a ChromeAppCacheService and insert data into it
  scoped_refptr<ChromeAppCacheService> appcache_service =
      CreateAppCacheService(appcache_path, true);
  ASSERT_TRUE(file_util::PathExists(appcache_path));
  ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
  InsertDataIntoAppCache(appcache_service);

  // Test: delete the ChromeAppCacheService
  appcache_service->set_clear_local_state_on_exit(true);
  appcache_service = NULL;
  message_loop_.RunAllPending();

  // Recreate the appcache (for reading the data back)
  appcache_service = CreateAppCacheService(appcache_path, false);

  // The directory is still there
  ASSERT_TRUE(file_util::PathExists(appcache_path));

  // The appcache data for the protected origin is there, and the data for the
  // unprotected origin was deleted.
  AppCacheTestHelper appcache_helper;
  std::set<GURL> origins;
  appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
  EXPECT_EQ(1UL, origins.size());
  EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
  EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) == origins.end());

  // Delete and let cleanup tasks run prior to returning.
  appcache_service = NULL;
  message_loop_.RunAllPending();
}

}  // namespace appcache
<|endoftext|>


<commit_before>#include <iostream>
#include <stdlib.h>
#include "glog/logging.h"
using namespace std;

enum level
{
    INFO=0,
    WARINIG=1,
    ERROR=2,
    FATAL=3
};

void test_glog()
{
    for(int i = 1; i < 101; i++)
    {
        //满足i==100才会打印
        LOG_IF(INFO,i==100)<<"LOG_IF(INFO,I==100),google::COUNTER=" << google::COUNTER << " i=" << i << endl;

        //每隔10次打印一次，对于刷屏的日志控制很好
        LOG_EVERY_N(INFO,10)<<"LOG_EVERY_N(INFO,10) google::COUNTER=" << google::COUNTER << " i=" << i;

        //满足i > 50的条件后，每隔10次打印一次，对于刷屏的日志控制很好
        LOG_IF_EVERY_N(WARNING,(i>50),10) << "LOG_IF_ERVER_N(INFO,(I>50),10) google::COUNTER="<<google::COUNTER<< " i=" << i;

        //只打印前5次
        LOG_FIRST_N(ERROR,5) << "LOG_FIRST_N(error,5) google::COUNTER=" << " i=" << i;

        //每次都打印
        LOG(ERROR) << "TEST BY TOPSLUO" << endl;
    }
}

int test_glog_main(int argc)
{
    google::InitGoogleLogging("vsc2");
    FLAGS_stderrthreshold=google::INFO;
    FLAGS_colorlogtostderr=true;
    google::SetStderrLogging(INFO);//设置级别高于google::INFO的日志同时输出到屏幕
    google::SetLogDestination(google::ERROR,"./log/error_");//设置google::ERROR级别的日志存储路径和文件名前缀
    google::SetLogDestination(google::WARNING,"./log/warning_");
    google::SetLogDestination(google::INFO,"./log/info_");
    FLAGS_logbufsecs = 0;//缓冲日志输出，默认为30秒，此处改为立刻
    FLAGS_max_log_size = 100;//最大日志大小为100M
    FLAGS_stop_logging_if_full_disk = true;//当磁盘被写满时，停止日志输出
    google::SetLogFilenameExtension("91_");//设置文件名扩展，如平台，或者其它需要区分的信息
    google::InstallFailureSignalHandler();//捕捉core dumped
    //google::InstallFailureWriter(&SignalHandle);//默认捕捉SIGSEGV信息输出会输出到sdtdrr

    test_glog();

    google::ShutdownGoogleLogging();//GLOG内存清理，一般与  google::InitGoogleLogging配对使用
    return 0;
}

int main(int, char**) {
    std::cout << "Hello, world!\n";
	test_glog_main(0);
#if __LINUX__
    char path[256];
    sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", 0);
    FILE* fp = fopen(path, "rb");
    if (!fp)
        return -1;

    int max_freq_khz = -1;
    int nscan = fscanf(fp, "%d", &max_freq_khz);

    std::cout << "fscanf, world! " << nscan << std::endl;

    sprintf(path, "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state", 0);
    sprintf(path, "/home/sf/time_in_state.txt");
    FILE* fp1 = fopen(path, "rb");
    max_freq_khz = 0;
    while (!feof(fp1))
    {
        int freq_khz = 0;
        int nscan = fscanf(fp1, "%d %*d", &freq_khz);
        std::cout << "fscanf, freq_khz! " << nscan << std::endl;
        if (nscan != 1)
            break;

        if (freq_khz > max_freq_khz)
            max_freq_khz = freq_khz;
    }
    #endif
    std::cout << "fscanf end \n";
}
<commit_msg>PREF c++ vscode test  error C2039: 'INFO': is not a member of 'google'<commit_after>#include <iostream>
#include <stdlib.h>
#include "glog/logging.h"
using namespace std;

enum level
{
    INFO=0,
    WARINIG=1,
    ERROR=2,
    FATAL=3
};

void test_glog()
{
    for(int i = 1; i < 101; i++)
    {
        //满足i==100才会打印
        LOG_IF(INFO,i==100)<<"LOG_IF(INFO,I==100),google::COUNTER=" << google::COUNTER << " i=" << i << endl;

        //每隔10次打印一次，对于刷屏的日志控制很好
        LOG_EVERY_N(INFO,10)<<"LOG_EVERY_N(INFO,10) google::COUNTER=" << google::COUNTER << " i=" << i;

        //满足i > 50的条件后，每隔10次打印一次，对于刷屏的日志控制很好
        LOG_IF_EVERY_N(WARNING,(i>50),10) << "LOG_IF_ERVER_N(INFO,(I>50),10) google::COUNTER="<<google::COUNTER<< " i=" << i;

        //只打印前5次
        LOG_FIRST_N(ERROR,5) << "LOG_FIRST_N(error,5) google::COUNTER=" << " i=" << i;

        //每次都打印
        LOG(ERROR) << "TEST BY TOPSLUO" << endl;
    }
}

int test_glog_main(int argc)
{
    google::InitGoogleLogging("vsc2");
    FLAGS_stderrthreshold=INFO;
    FLAGS_colorlogtostderr=true;
    google::SetStderrLogging(INFO);//设置级别高于google::INFO的日志同时输出到屏幕
    google::SetLogDestination(ERROR,"./log/error_");//设置google::ERROR级别的日志存储路径和文件名前缀
    google::SetLogDestination(WARNING,"./log/warning_");
    google::SetLogDestination(INFO,"./log/info_");
    FLAGS_logbufsecs = 0;//缓冲日志输出，默认为30秒，此处改为立刻
    FLAGS_max_log_size = 100;//最大日志大小为100M
    FLAGS_stop_logging_if_full_disk = true;//当磁盘被写满时，停止日志输出
    google::SetLogFilenameExtension("91_");//设置文件名扩展，如平台，或者其它需要区分的信息
    google::InstallFailureSignalHandler();//捕捉core dumped
    //google::InstallFailureWriter(&SignalHandle);//默认捕捉SIGSEGV信息输出会输出到sdtdrr

    test_glog();

    google::ShutdownGoogleLogging();//GLOG内存清理，一般与  google::InitGoogleLogging配对使用
    return 0;
}

int main(int, char**) {
    std::cout << "Hello, world!\n";
	test_glog_main(0);
#if __LINUX__
    char path[256];
    sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", 0);
    FILE* fp = fopen(path, "rb");
    if (!fp)
        return -1;

    int max_freq_khz = -1;
    int nscan = fscanf(fp, "%d", &max_freq_khz);

    std::cout << "fscanf, world! " << nscan << std::endl;

    sprintf(path, "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state", 0);
    sprintf(path, "/home/sf/time_in_state.txt");
    FILE* fp1 = fopen(path, "rb");
    max_freq_khz = 0;
    while (!feof(fp1))
    {
        int freq_khz = 0;
        int nscan = fscanf(fp1, "%d %*d", &freq_khz);
        std::cout << "fscanf, freq_khz! " << nscan << std::endl;
        if (nscan != 1)
            break;

        if (freq_khz > max_freq_khz)
            max_freq_khz = freq_khz;
    }
    #endif
    std::cout << "fscanf end \n";
}
<|endoftext|>


<commit_before>//
//  generateSimulatedData.cpp
//  cPWP
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#include "generateSimulatedData.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {
/*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed

    So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).
*/

    std::ofstream bamsFile;
    bamsFile.open("bamlist.txt", std::ios::out | std::ios::app);

    std::cout << "**********\nChecking if processor is available to run pirs...";
    if (system(NULL)) puts ("OK");
    else exit (EXIT_FAILURE);

    int pirsInd = 0;
    while(pirsInd < numIndividuals) {
        double mutRate = pirsInd * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStr;
        mutStr << mutRate;
        std::string mutRateString = mutStr.str();

        std::cout << "**********\nGenerating reference genome for individual " << pirsInd << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names
        std::ostringstream pirsIndSS;
        std::ostringstream pirsIndNumSS;
        pirsIndSS << "ind" + pirsInd;
        pirsIndNumSS << pirsInd;
        std::string pirsIndNum = pirsIndNumSS.str();
        std::string indName = pirsIndSS.str();
        std::string pirsGenomeSTDOUT = indName + "_genome.stdout";
        std::string pirsGenomeSTDERR = indName + "_genome.stderr";

        // Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize
        std::string pirsCommandToRun = "pirs diploid -s " + mutRateString + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" + pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR;
        if (system((pirsCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n";
        }
        // The following file is output by the pirs diploid command:
        std::string mutatedChromosome = indName + ".snp.fa";

        // After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the
        std::string pirsSimSTDOUT = indName + "_reads.stdout";
        std::string pirsSimSTDERR = indName + "_reads.stderr";
        std::string indReadsPrefix = indName + "_reads";
        std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
        if (system((pirsSimulateCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
        }

        // Generate the bwa mem command and then run it using a system call
        std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq";
        std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq";
        std::string bamOut = "ind" + pirsIndNum + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;

        pirsInd++; // Move on to the next individual
    }

    /* Implementation with wgsim
    std::cout << "**********\nChecking if processor is available to run wgsim...";
    if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);

    int step = 0;
    while(step <= numIndividuals) {
        double mutRate = step * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStrs;
        mutStrs << mutRate;
        std::string mutRateString = mutStrs.str();

        std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Get the number of the individual as a string
        std::ostringstream stepString;
        stepString << step;
        std::string ind = stepString.str();

        // Generate the output file names as strings
        std::string R1out = "ind" + ind + "_R1.fastq";
        std::string R2out = "ind" + ind + "_R2.fastq";
        std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt";

        // Generate the wgsim command and then run it using a system call
        std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize +  " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates
        if (system((wgsimCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n";

        }

        // Generate the bwa mem command and then run it using a system call
        std::string bamOut = "ind" + ind + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;
        step++; // Move on to the next individual
    }
    */
    bamsFile.close();
    return 0;
}

/*
 /home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1

*/

/*
 wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt
 wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq

 bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
 bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq

 samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam
 samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam

 echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt

 /home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &

*/

/*
 Usage:   wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>

 Options:
 -e FLOAT      base error rate [0.000]
 -d INT        outer distance between the two ends [500]
 -s INT        standard deviation [50]
 -N INT        number of read pairs [1000000]
 -1 INT        length of the first read [70]
 -2 INT        length of the second read [70]
 -r FLOAT      rate of mutations [0.0010]
 -R FLOAT      fraction of indels [0.15]
 -X FLOAT      probability an indel is extended [0.30]
 -S INT        seed for random generator [-1]
 -h            haplotype mode

 */

<commit_msg>minor changes<commit_after>//
//  generateSimulatedData.cpp
//  cPWP
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#include "generateSimulatedData.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {
/*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed

    So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).
*/

    std::ofstream bamsFile;
    bamsFile.open("bamlist.txt", std::ios::out | std::ios::app);

    std::cout << "**********\nChecking if processor is available to run pirs...";
    if (system(NULL)) puts ("OK");
    else exit (EXIT_FAILURE);

    int pirsInd = 0;
    while(pirsInd < numIndividuals) {
        double mutRate = pirsInd * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStr;
        mutStr << mutRate;
        std::string mutRateString = mutStr.str();

        std::cout << "**********\nGenerating reference genome for individual " << pirsInd << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names
        std::ostringstream pirsIndSS;
        std::ostringstream pirsIndNumSS;
        pirsIndSS << "ind" << pirsInd;
        pirsIndNumSS << pirsInd;
        std::string pirsIndNum = pirsIndNumSS.str();
        std::string indName = pirsIndSS.str();
        std::string pirsGenomeSTDOUT = indName + "_genome.stdout";
        std::string pirsGenomeSTDERR = indName + "_genome.stderr";

        // Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize
        std::string pirsCommandToRun = "pirs diploid -s " + mutRateString + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" + pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR;
        if (system((pirsCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n";
        }
        // The following file is output by the pirs diploid command:
        std::string mutatedChromosome = indName + ".snp.fa";

        // After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the
        std::string pirsSimSTDOUT = indName + "_reads.stdout";
        std::string pirsSimSTDERR = indName + "_reads.stderr";
        std::string indReadsPrefix = indName + "_reads";
        std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
        if (system((pirsSimulateCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
        }

        // Generate the bwa mem command and then run it using a system call
        std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq";
        std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq";
        std::string bamOut = "ind" + pirsIndNum + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;

        pirsInd++; // Move on to the next individual
    }

    /* Implementation with wgsim
    std::cout << "**********\nChecking if processor is available to run wgsim...";
    if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);

    int step = 0;
    while(step <= numIndividuals) {
        double mutRate = step * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStrs;
        mutStrs << mutRate;
        std::string mutRateString = mutStrs.str();

        std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Get the number of the individual as a string
        std::ostringstream stepString;
        stepString << step;
        std::string ind = stepString.str();

        // Generate the output file names as strings
        std::string R1out = "ind" + ind + "_R1.fastq";
        std::string R2out = "ind" + ind + "_R2.fastq";
        std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt";

        // Generate the wgsim command and then run it using a system call
        std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize +  " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates
        if (system((wgsimCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n";

        }

        // Generate the bwa mem command and then run it using a system call
        std::string bamOut = "ind" + ind + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;
        step++; // Move on to the next individual
    }
    */
    bamsFile.close();
    return 0;
}

/*
 /home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1

*/

/*
 wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt
 wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq

 bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
 bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq

 samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam
 samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam

 echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt

 /home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &

*/

/*
 Usage:   wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>

 Options:
 -e FLOAT      base error rate [0.000]
 -d INT        outer distance between the two ends [500]
 -s INT        standard deviation [50]
 -N INT        number of read pairs [1000000]
 -1 INT        length of the first read [70]
 -2 INT        length of the second read [70]
 -r FLOAT      rate of mutations [0.0010]
 -R FLOAT      fraction of indels [0.15]
 -X FLOAT      probability an indel is extended [0.30]
 -S INT        seed for random generator [-1]
 -h            haplotype mode

 */

<|endoftext|>


<commit_before>#include <iostream>

#include "libaps.h"
#include "constants.h"
#include <thread>

using namespace std;

int main ()
{
  cout << "BBN X6-1000 Test Executable" << endl;

  set_malibu_threading_enable(false);

  int numDevices;
  numDevices = get_numDevices();

  cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "")  << " found" << endl;

  if (numDevices < 1)
  	return 0;

  char s[] = "stdout";
  set_log(s);

  cout << "Attempting to initialize libaps" << endl;

  init();

  char serialBuffer[100];

  for (int cnt; cnt < numDevices; cnt++) {
  	get_deviceSerial(cnt, serialBuffer);
  	cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
  }

  int rc;
  rc = connect_by_ID(0);

  cout << "connect_by_ID(0) returned " << rc << endl;

  cout << "current logic temperature = " << get_logic_temperature(0) << endl;

  cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;

  cout << "setting trigger source = EXTERNAL" << endl;

  set_trigger_source(0, EXTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "setting trigger source = INTERNAL" << endl;

  set_trigger_source(0, INTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  cout << "set channel(0) enabled = 1" << endl;

  set_channel_enabled(0,0,true);

  cout << "enable ramp output" << endl;

  enable_test_generator(0,0,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "enable sine wave output" << endl;

  disable_test_generator(0);
  enable_test_generator(0,1,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "disabling channel" << endl;
  disable_test_generator(0);
  set_channel_enabled(0,0,false);

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  rc = disconnect_by_ID(0);

  cout << "disconnect_by_ID(0) returned " << rc << endl;

  return 0;
}<commit_msg>First output through X6_1000 class<commit_after>#include <iostream>

#include "libaps.h"
#include "constants.h"
#include <thread>

using namespace std;

int main ()
{
  cout << "BBN X6-1000 Test Executable" << endl;

  set_malibu_threading_enable(false);

  set_logging_level(5);

  int numDevices;
  numDevices = get_numDevices();

  cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "")  << " found" << endl;

  if (numDevices < 1)
  	return 0;

  char s[] = "stdout";
  set_log(s);

  cout << "Attempting to initialize libaps" << endl;

  init();

  char serialBuffer[100];

  for (int cnt; cnt < numDevices; cnt++) {
  	get_deviceSerial(cnt, serialBuffer);
  	cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
  }

  int rc;
  rc = connect_by_ID(0);

  cout << "connect_by_ID(0) returned " << rc << endl;

  cout << "current logic temperature = " << get_logic_temperature(0) << endl;

  cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;

  cout << "setting trigger source = EXTERNAL" << endl;

  set_trigger_source(0, EXTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "setting trigger source = INTERNAL" << endl;

  set_trigger_source(0, INTERNAL);

  cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  cout << "set channel(0) enabled = 1" << endl;

  set_channel_enabled(0,0,true);

  cout << "enable ramp output" << endl;

  enable_test_generator(0,0,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "enable sine wave output" << endl;

  disable_test_generator(0);
  enable_test_generator(0,1,0.001);

  std::this_thread::sleep_for(std::chrono::seconds(5));

  cout << "disabling channel" << endl;
  disable_test_generator(0);
  set_channel_enabled(0,0,false);

  cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;

  rc = disconnect_by_ID(0);

  cout << "disconnect_by_ID(0) returned " << rc << endl;

  return 0;
}<|endoftext|>


<commit_before>#include "MacroAIModule.h"
#include <BasicTaskExecutor.h>
#include <SpiralBuildingPlacer.h>
#include <BFSBuildingPlacer.h>
#include <UnitPump.h>
#include <TerminateIfWorkerLost.h>
#include <TerminateIfEmpty.h>
#include <BasicWorkerFinder.h>
#include <UnitCompositionProducer.h>
#include <MacroManager.h>
#include <ResourceRates.h>
#include <MacroSupplyManager.h>
#include <MacroDependencyResolver.h>

using namespace BWAPI;
int drag_index = -1;
bool lastMouseClick = false;
UnitCompositionProducer* infantryProducer = NULL;
UnitCompositionProducer* vehicleProducer = NULL;
MacroAIModule::MacroAIModule()
{
}
MacroAIModule::~MacroAIModule()
{
  if (TheMacroManager != NULL)
    delete TheMacroManager;
  if (TheMacroSupplyManager != NULL)
    delete TheMacroSupplyManager;
  if (TheMacroDependencyResolver != NULL)
    delete TheMacroDependencyResolver;
  if (TheResourceRates != NULL)
    delete TheResourceRates;
  if (infantryProducer != NULL)
    delete infantryProducer;
  if (vehicleProducer != NULL)
    delete vehicleProducer;
}
void MacroAIModule::onStart()
{
  Broodwar->enableFlag(Flag::UserInput);
  MacroManager::create(&arbitrator);
  MacroSupplyManager::create();
  MacroDependencyResolver::create();
  ResourceRates::create();

  TaskStream* ts = new TaskStream();
  TheMacroManager->taskStreams.push_back(ts);
  Unit* worker = NULL;
  for each(Unit* u in Broodwar->self()->getUnits())
  {
    if (u->getType()==UnitTypes::Terran_Command_Center)
      worker = u;
  }
  ts->setWorker(worker);
  ts->attach(BasicTaskExecutor::getInstance(),false);
  ts->attach(new UnitPump(UnitTypes::Terran_SCV),true);
  ts->attach(new TerminateIfWorkerLost(),true);
  infantryProducer = new UnitCompositionProducer(UnitTypes::Terran_Barracks);
  infantryProducer->setUnitWeight(UnitTypes::Terran_Marine,2.0);
  infantryProducer->setUnitWeight(UnitTypes::Terran_Medic,1.0);
  infantryProducer->setUnitWeight(UnitTypes::Terran_Firebat,0.5);
  vehicleProducer = new UnitCompositionProducer(UnitTypes::Terran_Factory);
  vehicleProducer->setUnitWeight(UnitTypes::Terran_Vulture,2.0);
  vehicleProducer->setUnitWeight(UnitTypes::Terran_Siege_Tank_Tank_Mode,1.0);
}
void MacroAIModule::onEnd(bool isWinner)
{
}
void MacroAIModule::onFrame()
{
  TheArbitrator->update();
  infantryProducer->update();
  vehicleProducer->update();
  TheMacroSupplyManager->update();
  TheMacroDependencyResolver->update();
  TheMacroManager->update();
  TheResourceRates->update();
  std::set<Unit*> units=Broodwar->self()->getUnits();
  for(std::set<Unit*>::iterator i=units.begin();i!=units.end();i++)
  {
    if (this->arbitrator.hasBid(*i))
    {
      int x=(*i)->getPosition().x();
      int y=(*i)->getPosition().y();
      std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> > bids=this->arbitrator.getAllBidders(*i);
      int y_off=0;
      bool first = false;
      const char activeColor = '\x07', inactiveColor = '\x16';
      char color = activeColor;
      for(std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> >::iterator j=bids.begin();j!=bids.end();j++)
      {
        Broodwar->drawTextMap(x,y+y_off,"%c%s: %d",color,j->first->getShortName().c_str(),(int)j->second);
        y_off+=15;
        color = inactiveColor;
      }
    }
  }
  if (drag_index<0)
  {
    if (Broodwar->getMouseState(M_LEFT) && !lastMouseClick)
    {
      drag_index = (Broodwar->getMouseY()-25)/20;
      if (drag_index<0) drag_index = 0;
    }
    if (drag_index>=(int)TheMacroManager->taskStreams.size())
      drag_index=-1;
  }
  if (drag_index>=0)
  {
    int land_index = (Broodwar->getMouseY()-30)/20;
    if (land_index<0) land_index = 0;
    if (land_index>=(int)TheMacroManager->taskStreams.size())
      land_index=(int)TheMacroManager->taskStreams.size()-1;
    if (land_index!=drag_index)
    {
      std::list<TaskStream*>::iterator td=TheMacroManager->taskStreams.end();
      std::list<TaskStream*>::iterator tl=TheMacroManager->taskStreams.end();
      TaskStream* tm=NULL;
      int j=0;
      for(std::list<TaskStream*>::iterator i=TheMacroManager->taskStreams.begin();i!=TheMacroManager->taskStreams.end();i++)
      {
        if (j==drag_index)
          td=i;
        if (j==land_index)
          tl=i;
        j++;
      }
      if (td!=TheMacroManager->taskStreams.end() && tl!=TheMacroManager->taskStreams.end())
      {
        tm=*td;
        *td=*tl;
        *tl=tm;
      }
      drag_index = land_index;
    }
    if (!Broodwar->getMouseState(M_LEFT) && lastMouseClick)
    {
      drag_index=-1;
    }
  }
  lastMouseClick = Broodwar->getMouseState(M_LEFT);
}
void MacroAIModule::onSendText(std::string text)
{
  Broodwar->sendText(text.c_str());
  if (text=="hide")
  {
    TheMacroManager->taskstream_list_visible = false;
  }
  if (text=="show")
  {
    TheMacroManager->taskstream_list_visible = true;
  }
  UnitType type=UnitTypes::getUnitType(text);
  if (type!=UnitTypes::Unknown)
  {
    TaskStream* ts = new TaskStream(Task(type));
    TheMacroManager->taskStreams.push_back(ts);
    ts->attach(new BasicWorkerFinder(),true);
    ts->attach(BasicTaskExecutor::getInstance(),false);
    ts->attach(new TerminateIfEmpty(),true);
    ts->attach(BFSBuildingPlacer::getInstance(),false);
  }
  else
  {
    TechType type=TechTypes::getTechType(text);
    if (type!=TechTypes::Unknown)
    {
      TaskStream* ts = new TaskStream(Task(type));
      TheMacroManager->taskStreams.push_back(ts);
      ts->attach(new BasicWorkerFinder(),true);
      ts->attach(BasicTaskExecutor::getInstance(),false);
      ts->attach(new TerminateIfEmpty(),true);
      ts->attach(BFSBuildingPlacer::getInstance(),false);
    }
    else
    {
      UpgradeType type=UpgradeTypes::getUpgradeType(text);
      if (type!=UpgradeTypes::Unknown)
      {
        TaskStream* ts = new TaskStream(Task(type));
        TheMacroManager->taskStreams.push_back(ts);
        ts->attach(new BasicWorkerFinder(),true);
        ts->attach(BasicTaskExecutor::getInstance(),false);
        ts->attach(new TerminateIfEmpty(),true);
        ts->attach(BFSBuildingPlacer::getInstance(),false);
      }
      else
        Broodwar->printf("You typed '%s'!",text.c_str());
    }
  }
}
void MacroAIModule::onUnitDestroy(BWAPI::Unit* unit)
{
  TheArbitrator->onRemoveObject(unit);
}
<commit_msg>A few initial changes to start working on protoss support for the macro manager, however I have yet to implement the main changes that will be needed:<commit_after>#include "MacroAIModule.h"
#include <BasicTaskExecutor.h>
#include <SpiralBuildingPlacer.h>
#include <BFSBuildingPlacer.h>
#include <UnitPump.h>
#include <TerminateIfWorkerLost.h>
#include <TerminateIfEmpty.h>
#include <BasicWorkerFinder.h>
#include <UnitCompositionProducer.h>
#include <MacroManager.h>
#include <ResourceRates.h>
#include <MacroSupplyManager.h>
#include <MacroDependencyResolver.h>

using namespace BWAPI;
int drag_index = -1;
bool lastMouseClick = false;
UnitCompositionProducer* infantryProducer = NULL;
UnitCompositionProducer* vehicleProducer = NULL;
MacroAIModule::MacroAIModule()
{
}
MacroAIModule::~MacroAIModule()
{
  if (TheMacroManager != NULL)
    delete TheMacroManager;
  if (TheMacroSupplyManager != NULL)
    delete TheMacroSupplyManager;
  if (TheMacroDependencyResolver != NULL)
    delete TheMacroDependencyResolver;
  if (TheResourceRates != NULL)
    delete TheResourceRates;
  if (infantryProducer != NULL)
    delete infantryProducer;
  if (vehicleProducer != NULL)
    delete vehicleProducer;
}
void MacroAIModule::onStart()
{
  Broodwar->enableFlag(Flag::UserInput);
  MacroManager::create(&arbitrator);
  MacroSupplyManager::create();
  MacroDependencyResolver::create();
  ResourceRates::create();

  TaskStream* ts = new TaskStream();
  TheMacroManager->taskStreams.push_back(ts);
  Unit* worker = NULL;
  for each(Unit* u in Broodwar->self()->getUnits())
  {
    if (u->getType().isResourceDepot())
      worker = u;
  }
  ts->setWorker(worker);
  ts->attach(BasicTaskExecutor::getInstance(),false);
  ts->attach(new UnitPump(Broodwar->self()->getRace().getWorker()),true);
  ts->attach(new TerminateIfWorkerLost(),true);

  if (Broodwar->self()->getRace()==Races::Terran)
  {
    infantryProducer = new UnitCompositionProducer(UnitTypes::Terran_Barracks);
    infantryProducer->setUnitWeight(UnitTypes::Terran_Marine,2.0);
    infantryProducer->setUnitWeight(UnitTypes::Terran_Medic,1.0);
    infantryProducer->setUnitWeight(UnitTypes::Terran_Firebat,0.5);

    vehicleProducer = new UnitCompositionProducer(UnitTypes::Terran_Factory);
    vehicleProducer->setUnitWeight(UnitTypes::Terran_Vulture,2.0);
    vehicleProducer->setUnitWeight(UnitTypes::Terran_Siege_Tank_Tank_Mode,1.0);
  }
  if (Broodwar->self()->getRace()==Races::Protoss)
  {
    infantryProducer = new UnitCompositionProducer(UnitTypes::Protoss_Gateway);
    infantryProducer->setUnitWeight(UnitTypes::Protoss_Dragoon,2.0);
    infantryProducer->setUnitWeight(UnitTypes::Protoss_Zealot,1.0);
  }
}
void MacroAIModule::onEnd(bool isWinner)
{
}
void MacroAIModule::onFrame()
{
  TheArbitrator->update();
  if (infantryProducer)
    infantryProducer->update();
  if (vehicleProducer)
    vehicleProducer->update();
  TheMacroSupplyManager->update();
  TheMacroDependencyResolver->update();
  TheMacroManager->update();
  TheResourceRates->update();
  std::set<Unit*> units=Broodwar->self()->getUnits();
  for(std::set<Unit*>::iterator i=units.begin();i!=units.end();i++)
  {
    if (this->arbitrator.hasBid(*i))
    {
      int x=(*i)->getPosition().x();
      int y=(*i)->getPosition().y();
      std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> > bids=this->arbitrator.getAllBidders(*i);
      int y_off=0;
      bool first = false;
      const char activeColor = '\x07', inactiveColor = '\x16';
      char color = activeColor;
      for(std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> >::iterator j=bids.begin();j!=bids.end();j++)
      {
        Broodwar->drawTextMap(x,y+y_off,"%c%s: %d",color,j->first->getShortName().c_str(),(int)j->second);
        y_off+=15;
        color = inactiveColor;
      }
    }
  }
  if (drag_index<0)
  {
    if (Broodwar->getMouseState(M_LEFT) && !lastMouseClick)
    {
      drag_index = (Broodwar->getMouseY()-25)/20;
      if (drag_index<0) drag_index = 0;
    }
    if (drag_index>=(int)TheMacroManager->taskStreams.size())
      drag_index=-1;
  }
  if (drag_index>=0)
  {
    int land_index = (Broodwar->getMouseY()-30)/20;
    if (land_index<0) land_index = 0;
    if (land_index>=(int)TheMacroManager->taskStreams.size())
      land_index=(int)TheMacroManager->taskStreams.size()-1;
    if (land_index!=drag_index)
    {
      std::list<TaskStream*>::iterator td=TheMacroManager->taskStreams.end();
      std::list<TaskStream*>::iterator tl=TheMacroManager->taskStreams.end();
      TaskStream* tm=NULL;
      int j=0;
      for(std::list<TaskStream*>::iterator i=TheMacroManager->taskStreams.begin();i!=TheMacroManager->taskStreams.end();i++)
      {
        if (j==drag_index)
          td=i;
        if (j==land_index)
          tl=i;
        j++;
      }
      if (td!=TheMacroManager->taskStreams.end() && tl!=TheMacroManager->taskStreams.end())
      {
        tm=*td;
        *td=*tl;
        *tl=tm;
      }
      drag_index = land_index;
    }
    if (!Broodwar->getMouseState(M_LEFT) && lastMouseClick)
    {
      drag_index=-1;
    }
  }
  lastMouseClick = Broodwar->getMouseState(M_LEFT);
}
void MacroAIModule::onSendText(std::string text)
{
  Broodwar->sendText(text.c_str());
  if (text=="hide")
  {
    TheMacroManager->taskstream_list_visible = false;
  }
  if (text=="show")
  {
    TheMacroManager->taskstream_list_visible = true;
  }
  UnitType type=UnitTypes::getUnitType(text);
  if (type!=UnitTypes::Unknown)
  {
    TaskStream* ts = new TaskStream(Task(type));
    TheMacroManager->taskStreams.push_back(ts);
    ts->attach(new BasicWorkerFinder(),true);
    ts->attach(BasicTaskExecutor::getInstance(),false);
    ts->attach(new TerminateIfEmpty(),true);
    ts->attach(BFSBuildingPlacer::getInstance(),false);
  }
  else
  {
    TechType type=TechTypes::getTechType(text);
    if (type!=TechTypes::Unknown)
    {
      TaskStream* ts = new TaskStream(Task(type));
      TheMacroManager->taskStreams.push_back(ts);
      ts->attach(new BasicWorkerFinder(),true);
      ts->attach(BasicTaskExecutor::getInstance(),false);
      ts->attach(new TerminateIfEmpty(),true);
      ts->attach(BFSBuildingPlacer::getInstance(),false);
    }
    else
    {
      UpgradeType type=UpgradeTypes::getUpgradeType(text);
      if (type!=UpgradeTypes::Unknown)
      {
        TaskStream* ts = new TaskStream(Task(type));
        TheMacroManager->taskStreams.push_back(ts);
        ts->attach(new BasicWorkerFinder(),true);
        ts->attach(BasicTaskExecutor::getInstance(),false);
        ts->attach(new TerminateIfEmpty(),true);
        ts->attach(BFSBuildingPlacer::getInstance(),false);
      }
      else
        Broodwar->printf("You typed '%s'!",text.c_str());
    }
  }
}
void MacroAIModule::onUnitDestroy(BWAPI::Unit* unit)
{
  TheArbitrator->onRemoveObject(unit);
}
<|endoftext|>


<commit_before>//
//  DiskII.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 23/04/2018.
//  Copyright © 2018 Thomas Harte. All rights reserved.
//

#include "DiskIICard.hpp"

using namespace AppleII;

DiskIICard::DiskIICard(const ROMMachine::ROMFetcher &rom_fetcher, bool is_16_sector) {
	auto roms = rom_fetcher(
		"DiskII",
		{
			"boot.rom",
			"state-machine.rom"
		});
	boot_ = std::move(*roms[0]);
	diskii_.set_state_machine(*roms[1]);
}

void DiskIICard::perform_bus_operation(CPU::MOS6502::BusOperation operation, uint16_t address, uint8_t *value) {
	if(isReadOperation(operation) && address < 0x100) {
		*value &= boot_[address];
	} else {
		using Control = Apple::DiskII::Control;
		using Mode = Apple::DiskII::Mode;
		switch(address & 0xf) {
			case 0x0:	diskii_.set_control(Control::P0, false);	break;
			case 0x1:	diskii_.set_control(Control::P0, true);		break;
			case 0x2:	diskii_.set_control(Control::P1, false);	break;
			case 0x3:	diskii_.set_control(Control::P1, true);		break;
			case 0x4:	diskii_.set_control(Control::P2, false);	break;
			case 0x5:	diskii_.set_control(Control::P2, true);		break;
			case 0x6:	diskii_.set_control(Control::P3, false);	break;
			case 0x7:	diskii_.set_control(Control::P3, true);		break;

			case 0x8:	diskii_.set_control(Control::Motor, false);	break;
			case 0x9:	diskii_.set_control(Control::Motor, true);	break;

			case 0xa:	diskii_.select_drive(0);					break;
			case 0xb:	diskii_.select_drive(1);					break;

			case 0xc: {
				/* shift register? */
				const uint8_t shift_value = diskii_.get_shift_register();
				if(isReadOperation(operation))
					*value = shift_value;
			} break;
			case 0xd:
				/* data register? */
				diskii_.set_data_register(*value);
			break;

			case 0xe:	diskii_.set_mode(Mode::Read);				break;
			case 0xf:	diskii_.set_mode(Mode::Write);				break;
		}
	}
}

void DiskIICard::run_for(Cycles cycles, int stretches) {
	diskii_.run_for(Cycles(cycles.as_int() * 2));
}

void DiskIICard::set_disk(const std::shared_ptr<Storage::Disk::Disk> &disk, int drive) {
	diskii_.set_disk(disk, drive);
}
<commit_msg>Ensures the contextually-proper boot and state machine ROMs are requested.<commit_after>//
//  DiskII.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 23/04/2018.
//  Copyright © 2018 Thomas Harte. All rights reserved.
//

#include "DiskIICard.hpp"

using namespace AppleII;

DiskIICard::DiskIICard(const ROMMachine::ROMFetcher &rom_fetcher, bool is_16_sector) {
	auto roms = rom_fetcher(
		"DiskII",
		{
			is_16_sector ? "boot-16.rom" : "boot-13.rom",
			is_16_sector ? "state-machine-16.rom" : "state-machine-13.rom"
		});
	boot_ = std::move(*roms[0]);
	diskii_.set_state_machine(*roms[1]);
}

void DiskIICard::perform_bus_operation(CPU::MOS6502::BusOperation operation, uint16_t address, uint8_t *value) {
	if(isReadOperation(operation) && address < 0x100) {
		*value &= boot_[address];
	} else {
		using Control = Apple::DiskII::Control;
		using Mode = Apple::DiskII::Mode;
		switch(address & 0xf) {
			case 0x0:	diskii_.set_control(Control::P0, false);	break;
			case 0x1:	diskii_.set_control(Control::P0, true);		break;
			case 0x2:	diskii_.set_control(Control::P1, false);	break;
			case 0x3:	diskii_.set_control(Control::P1, true);		break;
			case 0x4:	diskii_.set_control(Control::P2, false);	break;
			case 0x5:	diskii_.set_control(Control::P2, true);		break;
			case 0x6:	diskii_.set_control(Control::P3, false);	break;
			case 0x7:	diskii_.set_control(Control::P3, true);		break;

			case 0x8:	diskii_.set_control(Control::Motor, false);	break;
			case 0x9:	diskii_.set_control(Control::Motor, true);	break;

			case 0xa:	diskii_.select_drive(0);					break;
			case 0xb:	diskii_.select_drive(1);					break;

			case 0xc: {
				/* shift register? */
				const uint8_t shift_value = diskii_.get_shift_register();
				if(isReadOperation(operation))
					*value = shift_value;
			} break;
			case 0xd:
				/* data register? */
				diskii_.set_data_register(*value);
			break;

			case 0xe:	diskii_.set_mode(Mode::Read);				break;
			case 0xf:	diskii_.set_mode(Mode::Write);				break;
		}
	}
}

void DiskIICard::run_for(Cycles cycles, int stretches) {
	diskii_.run_for(Cycles(cycles.as_int() * 2));
}

void DiskIICard::set_disk(const std::shared_ptr<Storage::Disk::Disk> &disk, int drive) {
	diskii_.set_disk(disk, drive);
}
<|endoftext|>


<commit_before>#pragma once
#include "stdafx.h"

#define SafeDelete(x) {if((x) != nullptr) { delete (x); } x = nullptr; }
#define SafeDeleteArray(x) {if((x) != nullptr) { delete[] (x); } x = nullptr; }

namespace MCL
{
	namespace Util
	{
		static std::string ReadWholeFile(const std::string& path)
		{
			std::ifstream in(path);
			return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
		}

		static std::wstring StrToWStr(const std::string& str)
		{
			using convert_typeX = std::codecvt_utf8<wchar_t>;
			std::wstring_convert<convert_typeX, wchar_t> converterX;

			return converterX.from_bytes(str);
		}

		static std::string WStrToStr(const std::wstring& wstr)
		{
			using convert_typeX = std::codecvt_utf8<wchar_t>;
			std::wstring_convert<convert_typeX, wchar_t> converterX;

			return converterX.to_bytes(wstr);
		}
	}

	namespace ClUtil
	{
		static const char* MapErrorToString(cl_int error)
		{
			static const char* errorString[] = {
				"CL_SUCCESS",
				"CL_DEVICE_NOT_FOUND",
				"CL_DEVICE_NOT_AVAILABLE",
				"CL_COMPILER_NOT_AVAILABLE",
				"CL_MEM_OBJECT_ALLOCATION_FAILURE",
				"CL_OUT_OF_RESOURCES",
				"CL_OUT_OF_HOST_MEMORY",
				"CL_PROFILING_INFO_NOT_AVAILABLE",
				"CL_MEM_COPY_OVERLAP",
				"CL_IMAGE_FORMAT_MISMATCH",
				"CL_IMAGE_FORMAT_NOT_SUPPORTED",
				"CL_BUILD_PROGRAM_FAILURE",
				"CL_MAP_FAILURE",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"CL_INVALID_VALUE",
				"CL_INVALID_DEVICE_TYPE",
				"CL_INVALID_PLATFORM",
				"CL_INVALID_DEVICE",
				"CL_INVALID_CONTEXT",
				"CL_INVALID_QUEUE_PROPERTIES",
				"CL_INVALID_COMMAND_QUEUE",
				"CL_INVALID_HOST_PTR",
				"CL_INVALID_MEM_OBJECT - EX: WRONG R/W RIGHTS? WRONG STORAGE CLASS? WRONG ARG INDEX?",
				"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR",
				"CL_INVALID_IMAGE_SIZE",
				"CL_INVALID_SAMPLER",
				"CL_INVALID_BINARY",
				"CL_INVALID_BUILD_OPTIONS",
				"CL_INVALID_PROGRAM",
				"CL_INVALID_PROGRAM_EXECUTABLE",
				"CL_INVALID_KERNEL_NAME",
				"CL_INVALID_KERNEL_DEFINITION",
				"CL_INVALID_KERNEL",
				"CL_INVALID_ARG_INDEX",
				"CL_INVALID_ARG_VALUE",
				"CL_INVALID_ARG_SIZE",
				"CL_INVALID_KERNEL_ARGS",
				"CL_INVALID_WORK_DIMENSION",
				"CL_INVALID_WORK_GROUP_SIZE",
				"CL_INVALID_WORK_ITEM_SIZE",
				"CL_INVALID_GLOBAL_OFFSET",
				"CL_INVALID_EVENT_WAIT_LIST",
				"CL_INVALID_EVENT",
				"CL_INVALID_OPERATION",
				"CL_INVALID_GL_OBJECT",
				"CL_INVALID_BUFFER_SIZE",
				"CL_INVALID_MIP_LEVEL",
				"CL_INVALID_GLOBAL_WORK_SIZE",
			};

			const int errorCount = sizeof(errorString) / sizeof(errorString[0]);

			const int index = -error;

			return (index >= 0 && index < errorCount) ? errorString[index] : "";
		}

		static bool ResCheck(const cl_int val)
		{
			if (val != CL_SUCCESS)
			{
				std::string s;
				s.append("\OpenCL Error -> ");
				s.append(MapErrorToString(val));
				s.append("\n\n");
				std::wcout << s.c_str();
				return true;
			}
			return false;
		}

		static size_t RoundUpToWGSize(int value, int wgSize)
		{
			int remaining = value % wgSize;
			return value + (remaining == 0 ? 0 : (wgSize - remaining));
		}
	}
}<commit_msg>Update MCL_Utility.hpp<commit_after>#pragma once
#include "stdafx.h"

#define SafeDelete(x) {if((x) != nullptr) { delete (x); } x = nullptr; }
#define SafeDeleteArray(x) {if((x) != nullptr) { delete[] (x); } x = nullptr; }

namespace MUtil
{
	namespace Gen
	{
		static std::string ReadWholeFile(const std::string& path)
		{
			std::ifstream in(path);
			return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
		}

		static std::wstring StrToWStr(const std::string& str)
		{
			using convert_typeX = std::codecvt_utf8<wchar_t>;
			std::wstring_convert<convert_typeX, wchar_t> converterX;

			return converterX.from_bytes(str);
		}

		static std::string WStrToStr(const std::wstring& wstr)
		{
			using convert_typeX = std::codecvt_utf8<wchar_t>;
			std::wstring_convert<convert_typeX, wchar_t> converterX;

			return converterX.to_bytes(wstr);
		}
	}

	namespace CL
	{
		static unsigned int INVALID_OBJECT = 0xFFFFFFFF;
		static const wcahr_t* INVALID_NAME = L"[INVALID]";

		static const char* MapErrorToString(cl_int error)
		{
			static const char* errorString[] = {
				"CL_SUCCESS",
				"CL_DEVICE_NOT_FOUND",
				"CL_DEVICE_NOT_AVAILABLE",
				"CL_COMPILER_NOT_AVAILABLE",
				"CL_MEM_OBJECT_ALLOCATION_FAILURE",
				"CL_OUT_OF_RESOURCES",
				"CL_OUT_OF_HOST_MEMORY",
				"CL_PROFILING_INFO_NOT_AVAILABLE",
				"CL_MEM_COPY_OVERLAP",
				"CL_IMAGE_FORMAT_MISMATCH",
				"CL_IMAGE_FORMAT_NOT_SUPPORTED",
				"CL_BUILD_PROGRAM_FAILURE",
				"CL_MAP_FAILURE",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"CL_INVALID_VALUE",
				"CL_INVALID_DEVICE_TYPE",
				"CL_INVALID_PLATFORM",
				"CL_INVALID_DEVICE",
				"CL_INVALID_CONTEXT",
				"CL_INVALID_QUEUE_PROPERTIES",
				"CL_INVALID_COMMAND_QUEUE",
				"CL_INVALID_HOST_PTR",
				"CL_INVALID_MEM_OBJECT - EX: WRONG R/W RIGHTS? WRONG STORAGE CLASS? WRONG ARG INDEX?",
				"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR",
				"CL_INVALID_IMAGE_SIZE",
				"CL_INVALID_SAMPLER",
				"CL_INVALID_BINARY",
				"CL_INVALID_BUILD_OPTIONS",
				"CL_INVALID_PROGRAM",
				"CL_INVALID_PROGRAM_EXECUTABLE",
				"CL_INVALID_KERNEL_NAME",
				"CL_INVALID_KERNEL_DEFINITION",
				"CL_INVALID_KERNEL",
				"CL_INVALID_ARG_INDEX",
				"CL_INVALID_ARG_VALUE",
				"CL_INVALID_ARG_SIZE",
				"CL_INVALID_KERNEL_ARGS",
				"CL_INVALID_WORK_DIMENSION",
				"CL_INVALID_WORK_GROUP_SIZE",
				"CL_INVALID_WORK_ITEM_SIZE",
				"CL_INVALID_GLOBAL_OFFSET",
				"CL_INVALID_EVENT_WAIT_LIST",
				"CL_INVALID_EVENT",
				"CL_INVALID_OPERATION",
				"CL_INVALID_GL_OBJECT",
				"CL_INVALID_BUFFER_SIZE",
				"CL_INVALID_MIP_LEVEL",
				"CL_INVALID_GLOBAL_WORK_SIZE",
			};

			const int errorCount = sizeof(errorString) / sizeof(errorString[0]);

			const int index = -error;

			return (index >= 0 && index < errorCount) ? errorString[index] : "";
		}

		static bool ResultCheck(const cl_int val)
		{
			if (val != CL_SUCCESS)
			{
				std::string s;
				s.append("\OpenCL Error -> ");
				s.append(MapErrorToString(val));
				s.append("\n\n");
				std::wcout << s.c_str();
				return true;
			}
			return false;
		}

		static size_t RoundUpToWGSize(int value, int wgSize)
		{
			int remaining = value % wgSize;
			return value + (remaining == 0 ? 0 : (wgSize - remaining));
		}

		class CLImage2D
		{
		private:
			cl_mem mMemObject; // OpenCL image memory object
			std::wstring mName; // Readable name of the image object
			cl_image_format mFormat; // OpenCL image format
			cl_image_desc mDescr; // OpenCL image descriptor

		public:
			// Initializes the object with invalid values
			CLImage2D()
				: mMemObject(INVALID_OBJECT),
					mName(INVALID_NAME)
			{
			}

			// Creates the OpenCL image object and initializes internal variables. Throws and exception if failed.
			void Initialize(cl_context clContext, const std::wstring& name, size_t w, size_t h, size_t rowPitch, cl_channel_order channelOrder, cl_channel_type channelType)
			{
				mName = name;
				mFormat.image_channel_order = channelOrder;
				mFormat.image_channel_data_type = channelType;
				// Fill descriptor here

				// Create object here

			}

			// Returns true if teh object is alread created and returns false if it is not initialized yet.
			bool IsValid() const
			{
				return mMemObject == INVALID_OBJECT ? false : true;
			}

			// Returns the internal cl_mem object
			cl_mem getMemObject() const
			{
				return mMemObject;
			}

			// Returns the name of the image object
			std::wstring getName() const
			{
				return mName;
			}

			// Returns the format of the image
			cl_image_format getFormat() const
			{
				return mFormat;
			}

			// Returns the description of the image
			cl_image_desc getDescription() const
			{
				return mDescr;
			}
		}
	}
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIGeometryBuffer.cpp
    created:    Wed Jan 13 2010
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"

#include <vector>

// Start of CEGUI namespace section
namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial) :
    d_blendMode(BM_NORMAL)
    , d_renderMaterial(renderMaterial)
{
}

//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
    d_blendMode = mode;
}

//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
    return d_blendMode;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
    if(coloured_vertices.empty())
        return;

    appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const ColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
    if(textured_vertices.empty())
        return;

    appendGeometry(&textured_vertices[0], textured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const TexturedColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
    vertexData.push_back(vs->d_texCoords.x);
        vertexData.push_back(vs->d_texCoords.y);
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
                                    uint array_size)
{
    std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
    appendGeometry(vectorVertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[9];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();
    vertexData[7] = vertex.d_texCoords.x;
    vertexData[8] = vertex.d_texCoords.y;

    appendGeometry(vertexData, 9);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[7];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();

    appendGeometry(vertexData, 7);
}

//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
    int count = 0;

    const unsigned int attribute_count = d_vertexAttributes.size();
    for (unsigned int i = 0; i < attribute_count; ++i)
    {
        switch(d_vertexAttributes.at(i))
        {
            case VAT_POSITION0:
                count += 3;
                break;
            case VAT_COLOUR0:
                count += 4;
                break;
            case VAT_TEXCOORD0:
                count += 2;
                break;
            default:
                break;
        }
    }

    return count;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
    d_vertexAttributes.clear();
}

//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
    d_vertexAttributes.push_back(attribute);
}

//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
    return d_renderMaterial;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
    d_renderMaterial = render_material;
}

//---------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<commit_msg>MOD: format<commit_after>/***********************************************************************
    filename:   CEGUIGeometryBuffer.cpp
    created:    Wed Jan 13 2010
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"

#include <vector>

namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)
    : d_blendMode(BM_NORMAL)
    , d_renderMaterial(renderMaterial)
    , d_polygonFillRule(PFR_NONE)
{
}

//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
    d_blendMode = mode;
}

//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
    return d_blendMode;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
    if(coloured_vertices.empty())
        return;

    appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const ColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
    if(textured_vertices.empty())
        return;

    appendGeometry(&textured_vertices[0], textured_vertices.size());
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
                                    uint vertex_count)
{
    // Add the vertex data in their default order into an array
    std::vector<float> vertexData;
    const TexturedColouredVertex* vs = vertex_array;
    for (uint i = 0; i < vertex_count; ++i, ++vs)
    {
        // Add all the elements in the default order for textured and coloured
        // geometry into the vector
        vertexData.push_back(vs->d_position.x);
        vertexData.push_back(vs->d_position.y);
        vertexData.push_back(vs->d_position.z);
        vertexData.push_back(vs->d_colour.getRed());
        vertexData.push_back(vs->d_colour.getGreen());
        vertexData.push_back(vs->d_colour.getBlue());
        vertexData.push_back(vs->d_colour.getAlpha());
    vertexData.push_back(vs->d_texCoords.x);
        vertexData.push_back(vs->d_texCoords.y);
    }

    // Append the prepared geometry data
    appendGeometry(vertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
                                    uint array_size)
{
    std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
    appendGeometry(vectorVertexData);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[9];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();
    vertexData[7] = vertex.d_texCoords.x;
    vertexData[8] = vertex.d_texCoords.y;

    appendGeometry(vertexData, 9);
}

//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
    // Add the vertex data in their default order into an array
    float vertexData[7];

    // Copy the vertex attributes into the array
    vertexData[0] = vertex.d_position.x;
    vertexData[1] = vertex.d_position.y;
    vertexData[2] = vertex.d_position.z;
    vertexData[3] = vertex.d_colour.getRed();
    vertexData[4] = vertex.d_colour.getGreen();
    vertexData[5] = vertex.d_colour.getBlue();
    vertexData[6] = vertex.d_colour.getAlpha();

    appendGeometry(vertexData, 7);
}

//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
    int count = 0;

    const unsigned int attribute_count = d_vertexAttributes.size();
    for (unsigned int i = 0; i < attribute_count; ++i)
    {
        switch(d_vertexAttributes.at(i))
        {
            case VAT_POSITION0:
                count += 3;
                break;
            case VAT_COLOUR0:
                count += 4;
                break;
            case VAT_TEXCOORD0:
                count += 2;
                break;
            default:
                break;
        }
    }

    return count;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
    d_vertexAttributes.clear();
}

//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
    d_vertexAttributes.push_back(attribute);
}

//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
    return d_renderMaterial;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
    d_renderMaterial = render_material;
}

//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)
{
    d_polygonFillRule = fill_rule;
}

//---------------------------------------------------------------------------//
}

<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH

// system
#include <map>
#include <set>

// dune-common
#include <dune/common/shared_ptr.hh>

// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
#include <dune/fem/gridpart/gridpartview.hh>

// dune-detailed-discretizations includes
#include <dune/detailed/discretizations/basefunctionset/continuous/lagrange.hh>
#include <dune/detailed/discretizations/mapper/continuous/lagrange.hh>

namespace Dune
{

namespace Detailed {

namespace Discretizations
{

namespace DiscreteFunctionSpace
{

namespace Continuous
{

template< class FunctionSpaceImp, class GridPartImp, int polOrder >
class Lagrange
{
public:

  typedef FunctionSpaceImp
    FunctionSpaceType;

  typedef GridPartImp
    GridPartType;

  typedef Dune::GridPartView< GridPartType > GridViewType;

  enum{ polynomialOrder = polOrder };

  typedef Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
    ThisType;

  typedef Dune::Detailed::Discretizations::Mapper::Continuous::Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
    MapperType;

  typedef Dune::Detailed::Discretizations::BaseFunctionSet::Continuous::Lagrange< ThisType >
    BaseFunctionSetType;

  typedef typename FunctionSpaceType::DomainFieldType
    DomainFieldType;

  typedef typename FunctionSpaceType::DomainType
    DomainType;

  typedef typename FunctionSpaceType::RangeFieldType
    RangeFieldType;

  typedef typename FunctionSpaceType::RangeType
    RangeType;

  typedef typename FunctionSpaceType::JacobianRangeType
    JacobianRangeType;

  typedef typename FunctionSpaceType::HessianRangeType
    HessianRangeType;

  static const unsigned int dimDomain = FunctionSpaceType::dimDomain;

  static const unsigned int dimRange = FunctionSpaceType::dimRange;

  typedef std::map< unsigned int, std::set< unsigned int > > PatternType;

  /**
      @name Convenience typedefs
      @{
   **/
  typedef typename GridPartType::template Codim< 0 >::IteratorType
    IteratorType;

  typedef typename IteratorType::Entity
    EntityType;
  /**
      @}
   **/

  Lagrange( const GridPartType& gridPart )
    : gridPart_( gridPart ),
      gridView_(gridPart_),
      mapper_( gridPart_ ),
      baseFunctionSet_( *this )
  {}

private:
  //! copy constructor
  Lagrange( const ThisType& other );

public:
  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const GridViewType& gridView() const
  {
    return gridView_;
  }

  const MapperType& map() const
  {
    return mapper_;
  }

  const BaseFunctionSetType& baseFunctionSet() const
  {
    return baseFunctionSet_;
  }

  int order() const
  {
    return polynomialOrder;
  }

  bool continuous() const
  {
    if( order() > 0 )
      return false;
    else
      return true;
  }

  /**
      @name Convenience methods
      @{
   **/
  IteratorType begin() const
  {
    return gridPart_.template begin< 0 >();
  }

  IteratorType end() const
  {
    return gridPart_.template end< 0 >();
  }
  /**
      @}
   **/

  template< class OtherDiscreteFunctionSpaceType>
  PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
  {
    std::map< unsigned int, std::set< unsigned int > > ret;
    // generate sparsity pattern
    for (IteratorType it = begin(); it != end(); ++it) {
      const EntityType& entity = *it;
      for(unsigned int i = 0; i < baseFunctionSet().local(entity).size(); ++i) {
        for(unsigned int j = 0; j < other.baseFunctionSet().local(entity).size(); ++j) {
          const unsigned int globalI = map().toGlobal(entity, i);
          const unsigned int globalJ = other.map().toGlobal(entity, j);
          std::map< unsigned int, std::set< unsigned int > >::iterator result = ret.find(globalI);
          if (result == ret.end())
            ret.insert(std::pair< unsigned int, std::set< unsigned int > >(globalI, std::set< unsigned int >()));
          result = ret.find(globalI);
          assert(result != ret.end());
          result->second.insert(globalJ);
        }
      }
    } // generate sparsity pattern
    return ret;
  } // PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const

  PatternType computePattern() const
  {
    return computePattern(*this);
  }

protected:

  //! assignment operator
  ThisType& operator=( const ThisType& );

  const GridPartType& gridPart_;
  const GridViewType gridView_;
  const MapperType mapper_;
  const BaseFunctionSetType baseFunctionSet_;
}; // end class Lagrange

} // end namespace Continuous

} // end namespace DiscreteFunctionSpace

} // namespace Discretizations

} // namespace Detailed

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
<commit_msg>[discretefunctionspace.continuous.lagrange] minor change (should perform better)<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH

// system
#include <map>
#include <set>

// dune-common
#include <dune/common/shared_ptr.hh>

// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
#include <dune/fem/gridpart/gridpartview.hh>

// dune-detailed-discretizations includes
#include <dune/detailed/discretizations/basefunctionset/continuous/lagrange.hh>
#include <dune/detailed/discretizations/mapper/continuous/lagrange.hh>

namespace Dune
{

namespace Detailed {

namespace Discretizations
{

namespace DiscreteFunctionSpace
{

namespace Continuous
{

template< class FunctionSpaceImp, class GridPartImp, int polOrder >
class Lagrange
{
public:

  typedef FunctionSpaceImp
    FunctionSpaceType;

  typedef GridPartImp
    GridPartType;

  typedef Dune::GridPartView< GridPartType > GridViewType;

  enum{ polynomialOrder = polOrder };

  typedef Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
    ThisType;

  typedef Dune::Detailed::Discretizations::Mapper::Continuous::Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
    MapperType;

  typedef Dune::Detailed::Discretizations::BaseFunctionSet::Continuous::Lagrange< ThisType >
    BaseFunctionSetType;

  typedef typename FunctionSpaceType::DomainFieldType
    DomainFieldType;

  typedef typename FunctionSpaceType::DomainType
    DomainType;

  typedef typename FunctionSpaceType::RangeFieldType
    RangeFieldType;

  typedef typename FunctionSpaceType::RangeType
    RangeType;

  typedef typename FunctionSpaceType::JacobianRangeType
    JacobianRangeType;

  typedef typename FunctionSpaceType::HessianRangeType
    HessianRangeType;

  static const unsigned int dimDomain = FunctionSpaceType::dimDomain;

  static const unsigned int dimRange = FunctionSpaceType::dimRange;

  typedef std::map< unsigned int, std::set< unsigned int > > PatternType;

  /**
      @name Convenience typedefs
      @{
   **/
  typedef typename GridPartType::template Codim< 0 >::IteratorType
    IteratorType;

  typedef typename IteratorType::Entity
    EntityType;
  /**
      @}
   **/

  Lagrange( const GridPartType& gridPart )
    : gridPart_( gridPart ),
      gridView_(gridPart_),
      mapper_( gridPart_ ),
      baseFunctionSet_( *this )
  {}

private:
  //! copy constructor
  Lagrange( const ThisType& other );

public:
  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const GridViewType& gridView() const
  {
    return gridView_;
  }

  const MapperType& map() const
  {
    return mapper_;
  }

  const BaseFunctionSetType& baseFunctionSet() const
  {
    return baseFunctionSet_;
  }

  int order() const
  {
    return polynomialOrder;
  }

  bool continuous() const
  {
    if( order() > 0 )
      return false;
    else
      return true;
  }

  /**
      @name Convenience methods
      @{
   **/
  IteratorType begin() const
  {
    return gridPart_.template begin< 0 >();
  }

  IteratorType end() const
  {
    return gridPart_.template end< 0 >();
  }
  /**
      @}
   **/

  template< class OtherDiscreteFunctionSpaceType>
  PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
  {
    std::map< unsigned int, std::set< unsigned int > > ret;
    // generate sparsity pattern
    for (IteratorType it = begin(); it != end(); ++it) {
      const EntityType& entity = *it;
      for(unsigned int i = 0; i < baseFunctionSet().local(entity).size(); ++i) {
        const unsigned int globalI = map().toGlobal(entity, i);
        std::map< unsigned int, std::set< unsigned int > >::iterator result = ret.find(globalI);
        if (result == ret.end())
          ret.insert(std::pair< unsigned int, std::set< unsigned int > >(globalI, std::set< unsigned int >()));
        result = ret.find(globalI);
        assert(result != ret.end());
        for(unsigned int j = 0; j < other.baseFunctionSet().local(entity).size(); ++j) {
          const unsigned int globalJ = other.map().toGlobal(entity, j);
          result->second.insert(globalJ);
        }
      }
    } // generate sparsity pattern
    return ret;
  } // PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const

  PatternType computePattern() const
  {
    return computePattern(*this);
  }

protected:

  //! assignment operator
  ThisType& operator=( const ThisType& );

  const GridPartType& gridPart_;
  const GridViewType gridView_;
  const MapperType mapper_;
  const BaseFunctionSetType baseFunctionSet_;
}; // end class Lagrange

} // end namespace Continuous

} // end namespace DiscreteFunctionSpace

} // namespace Discretizations

} // namespace Detailed

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
<|endoftext|>