<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2018, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/

 * Author: David Keeney, April, 2018
 * ---------------------------------------------------------------------
 */

/*---------------------------------------------------------------------
 * This is a test of the backtrackingTMCpp C++ implimentation (no Python).
 *
 * For those not familiar with GTest:
 * ASSERT_TRUE(value)   -- Fatal assertion that the value is true. Test
 *                         terminates if false.
 * ASSERT_FALSE(value)   -- Fatal assertion that the value
 *                         is false. Test terminates if true.
 * ASSERT_STREQ(str1, str2)   -- Fatal assertion that the strings are equal.
 *                         Test terminates if false.
 * EXPECT_TRUE(value)   -- Nonfatal assertion that the value is true. Test
 *                         continues if false.
 * EXPECT_FALSE(value)   -- Nonfatal assertion that the value is false.
 *                          Test continues if true.
 * EXPECT_STREQ(str1, str2) -- Nonfatal assertion that the strings are equal.
 *                          Test continues if false.
 * EXPECT_THROW(statement, exception_type) -- nonfatal exception, cought,
 *                         reported and continues.
 *---------------------------------------------------------------------
 */

#include <random>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>

#include <nupic/algorithms/BacktrackingTMCpp.hpp>
#include <nupic/os/Directory.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/types/Exception.hpp>

#include <gtest/gtest.h>

#define VERBOSITY 0
#define VERBOSE if (verbose) std::cerr << "[          ] "
static bool verbose =  true; // turn this on to print extra stuff for debugging the test.
#define SEED 12

using namespace nupic;
using namespace nupic::algorithms::backtracking_tm;
namespace testing {

////////////////////////////////////////////////////////////////////////////////
//     helper routines
////////////////////////////////////////////////////////////////////////////////
typedef shared_ptr<Real32> Pattern_t;

// Generate a single test pattern of random bits with given parameters.
//
//    Parameters :
//    @numCols -Number of columns in each pattern.
//    @minOnes -The minimum number of 1's in each pattern.
//    @maxOnes -The maximum number of 1's in each pattern.

static Pattern_t generatePattern(Size numCols = 100, Size minOnes = 21,
                                 Size maxOnes = 25) {
  NTA_ASSERT(minOnes <= maxOnes);
  NTA_ASSERT(maxOnes < numCols);
  Pattern_t p(new Real32[numCols], std::default_delete<Real32[]>());
  memset(p.get(), 0, numCols);

  int numOnes = (int)minOnes + std::rand() % (maxOnes - minOnes + 1);
  std::uniform_int_distribution<> distr(0, (int)numCols - 1); // define the range (requires C++11)
  for (int n = 0; n < numOnes; n++) {
    int idx = std::rand() % numCols;
    p.get()[idx] = 1.0f;
  }
  return p;
}

// Generates a sequence of n random patterns.
static std::vector<Pattern_t> generateSequence(Size n = 10, Size numCols = 100,
                                               Size minOnes = 21,
                                               Size maxOnes = 25) {
  std::vector<Pattern_t> seq;
  Pattern_t p;  // an empty pattern which means reset
  seq.push_back(p);

  for (Size i = 0; i < n; i++) {
    Pattern_t p = generatePattern(numCols, minOnes, maxOnes);
    seq.push_back(p);
  }
  return seq;
}

struct param_t {
  UInt32 numberOfCols;
  UInt32 cellsPerColumn;
  Real32 initialPerm;
  Real32 connectedPerm;
  UInt32 minThreshold;
  UInt32 newSynapseCount;
  Real32 permanenceInc;
  Real32 permanenceDec;
  Real32 permanenceMax;
  Real32 globalDecay;
  UInt32 activationThreshold;
  bool doPooling;
  UInt32 segUpdateValidDuration;
  UInt32 burnIn;
  bool collectStats;
  Int32 seed;
  Int32 verbosity;
  bool checkSynapseConsistency;
  UInt32 pamLength;
  UInt32 maxInfBacktrack;
  UInt32 maxLrnBacktrack;
  UInt32 maxAge;
  UInt32 maxSeqLength;
  Int32 maxSegmentsPerCell;
  Int32 maxSynapsesPerSegment;
  char outputType[25];
};

void initializeParameters(struct param_t &param) {
  // same as default settings
  param.numberOfCols = 10;
  param.cellsPerColumn = 3;
  param.initialPerm = 0.11f;
  param.connectedPerm = 0.5f;
  param.minThreshold = 8;
  param.newSynapseCount = 15;
  param.permanenceInc = 0.1f;
  param.permanenceDec = 0.1f;
  param.permanenceMax = 1.0f;
  param.globalDecay = 0.1f;
  param.activationThreshold = 12;
  param.doPooling = false;
  param.segUpdateValidDuration = 5;
  param.burnIn = 2;
  param.collectStats = false;
  param.seed = 42;
  param.verbosity = VERBOSITY;
  param.checkSynapseConsistency = false;
  param.pamLength = 1;
  param.maxInfBacktrack = 10;
  param.maxLrnBacktrack = 5;
  param.maxAge = 100000;
  param.maxSeqLength = 32;
  param.maxSegmentsPerCell = -1;
  param.maxSynapsesPerSegment = -1;
  strcpy(param.outputType, "normal");
}

//////////////////////////////////////////////////////////////////
//////////    Tests
//////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////
// Run a test of the basic TM class ported from backtracking_tm_test.py
TEST(BacktrackingTMTest, testCheckpointLearned) {

  struct param_t param;
  initializeParameters(param);
  param.numberOfCols = 100;
  param.cellsPerColumn = 12;
  param.verbosity = VERBOSITY;

  try {
    // Create TM object
    BacktrackingTMCpp tm1(
        param.numberOfCols, param.cellsPerColumn, param.initialPerm,
        param.connectedPerm, param.minThreshold, param.newSynapseCount,
        param.permanenceInc, param.permanenceDec, param.permanenceMax,
        param.globalDecay, param.activationThreshold, param.doPooling,
        param.segUpdateValidDuration, param.burnIn, param.collectStats,
        param.seed, param.verbosity, param.checkSynapseConsistency,
        param.pamLength, param.maxInfBacktrack, param.maxLrnBacktrack,
        param.maxAge, param.maxSeqLength, param.maxSegmentsPerCell,
        param.maxSynapsesPerSegment, param.outputType);

    // generate 5 sets of sequences
    // The first pattern in each sequence is empty (a reset)
    std::vector<std::vector<Pattern_t>> sequences;
    for (Size s = 0; s < 5; s++) {
      sequences.push_back(generateSequence());
    }
    // train with the first 3 sets of sequences.
    std::vector<Pattern_t> train;
    for (Size s = 0; s < 3; s++) {
      for (Size i = 0; i < sequences[s].size();i++) {
        train.push_back(sequences[s][i]);
      }
    }

    // process the patterns that are in the training set.
    for (Size t = 0; t < train.size(); t++) {
      if (!train[t]) {
        tm1.reset();
      } else {
        Real *bottomUpInput = train[t].get();
        tm1.compute(bottomUpInput, true, true);
      }
    }
    // Serialize and deserialized the TM.
    Directory::create("TestOutputDir", false, true);
    std::string checkpointPath = "TestOutputDir/tm.save";
    tm1.saveToFile(checkpointPath);

    BacktrackingTMCpp tm2;
    tm2.loadFromFile(checkpointPath);

    // Check that the TMs are the same.
    ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));

    // Feed remaining data into the models.
    train.clear();
    for (Size s = 3; s < sequences.size(); s++) {
      for (Size i = 0; i < sequences[s].size(); i++) {
        train.push_back(sequences[s][i]);
      }
    }

    for (Size t = 0; t < train.size(); t++) {
      if (!train[t]) {
        tm1.reset();
        tm2.reset();
      } else {
        Real *bottomUpInput = train[t].get();
        Real *result1 = tm1.compute(bottomUpInput, true, true);
        Real *result2 = tm2.compute(bottomUpInput, true, true);

        ASSERT_TRUE(tm1 == tm2);
        ASSERT_TRUE(tm1.getOutputBufferSize() == tm2.getOutputBufferSize());
        for (Size i = 0; i < tm1.getOutputBufferSize(); i++) {
          ASSERT_TRUE(result1[i] == result2[i]);
        }
      }
    }
  }
  catch (nupic::Exception &ex) {
    FAIL() << "Failure: Exception: " << ex.getFilename() << "("
           << ex.getLineNumber() << ") " << ex.getMessage() << "" << std::endl;
  }
  catch (std::exception &e) {
    FAIL() << "Failure: Exception: " << e.what() << "" << std::endl;
  }

    // cleanup .
  Directory::removeTree("TestOutputDir");

}

TEST(BacktrackingTMTest, testCheckpointMiddleOfSequence)
{
    // Create a model and give it some inputs to learn.
    BacktrackingTMCpp tm1(100, 12);
    tm1.setVerbosity((Int32)VERBOSITY);

    // generate 5 sets of sequences
    std::vector<std::vector<Pattern_t>> sequences;
    for (Size s = 0; s < 5; s++) {
      sequences.push_back(generateSequence());
    }
    // separate train sets of sequences into halves
    std::vector<Pattern_t> firstHalf, secondHalf;
    const int HALF = 5*10 /2;
    int idx = 0;
    for (auto seq: sequences) {
      for (auto pattern : seq) {
	if(idx++ < HALF) firstHalf.push_back(pattern);
	else secondHalf.push_back(pattern);
      }
    }

    // compute each of the patterns in train, learn
    for (auto p: firstHalf) {
      const auto pat = p.get();
      if (!pat) {
        tm1.reset();
      } else {
        tm1.compute(pat, true, true);
      }
    }

    // Serialize and TM.
    Directory::create("TestOutputDir", false, true);
    std::string checkpointPath = "TestOutputDir/tm.save";
    tm1.saveToFile(checkpointPath);

    // Restore the saved TM into tm2.
    // Note that this resets the random generator to the same
    // point that the first TM used when it processed that second set
    // of patterns.
    BacktrackingTMCpp tm2;
    tm2.loadFromFile(checkpointPath);

    ASSERT_EQ(tm1, tm2) << "Deserialized TM is equal";
    ASSERT_TRUE(tm1 == tm2);

    // process the remaining patterns in train with the first TM.
    for (auto p: secondHalf) {
      const auto pat = p.get();
      if (!pat) {
        tm1.reset();
      } else {
        Real *result1 = tm1.compute(pat, true, true);
      }
    }

    ASSERT_TRUE(tm1 != tm2) << "TM1 moved, TM2 didn't";

    // process the same remaining patterns in the train with the second TM.
    for (auto p: secondHalf) {
      const auto pat = p.get();
      if (!pat) {
        tm2.reset();
      } else {
        Real *result22= tm2.compute(pat, true, true);
      }
    }

    ASSERT_EQ(tm1, tm2) << "Both TM trained";
    ASSERT_TRUE(tm1 == tm2);

    // cleanup if successful.
    Directory::removeTree("TestOutputDir");
 }

////////////////////////////////////////////////////////////////////////////////
// Run a test of the TM class ported from backtracking_tm_cpp2_test.py
TEST(BacktrackingTMTest, basicTest) {
    // Create a model and give it some inputs to learn.
    BacktrackingTMCpp tm1(10, 3, 0.2f, 0.8f, 2, 5, 0.10f, 0.05f, 1.0f, 0.05f, 4,
                          false, 5, 2, false, SEED, (Int32)VERBOSITY /* rest are defaults */);
    tm1.setRetrieveLearningStates(true);
    Size nCols = tm1.getnumCol();

    // Serialize and deserialized the TM.
    Directory::create("TestOutputDir", false, true);
    std::string checkpointPath = "TestOutputDir/tm.save";
    tm1.saveToFile(checkpointPath);

    BacktrackingTMCpp tm2;
    tm2.loadFromFile(checkpointPath);

    // Check that the TMs are the same.
    ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));

    // generate some test data and NT patterns from it.
    std::vector<Pattern_t> data = generateSequence(10, nCols, 2, 2);
    std::vector<std::vector<UInt>> nzData;
    for (Size i = 0; i < data.size(); i++) {
      if (data[i]) { // skip reset patterns
        const auto indices =
		nupic::algorithms::backtracking_tm::nonzero<Real>(data[i].get(), nCols);
        nzData.push_back(indices);
      }
    }

    // Learn
    for (Size i = 0; i < 5; i++) {
      if (data[i])
        tm1.learn(data[i].get());
    }
    tm1.reset();

    // save and reload again after learning.
    tm1.saveToFile(checkpointPath);
    BacktrackingTMCpp tm3;
    tm3.loadFromFile(checkpointPath);
    // Check that the TMs are the same.
    ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm3, std::cout, 2));

    // Infer
    for (Size i = 0; i < 10; i++) {
      if (data[i]) {
        tm1.infer(data[i].get());
        if (i > 0)
          tm1._checkPrediction(nzData);
      }
    }

    // cleanup if successful.
    Directory::removeTree("TestOutputDir");
}

} // namespace testing
<commit_msg>BackTM: test cleanup<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2018, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/

 * Author: David Keeney, April, 2018
 * ---------------------------------------------------------------------
 */

/*---------------------------------------------------------------------
 * This is a test of the backtrackingTMCpp C++ implimentation (no Python).
 *
 * For those not familiar with GTest:
 * ASSERT_TRUE(value)   -- Fatal assertion that the value is true. Test
 *                         terminates if false.
 * ASSERT_FALSE(value)   -- Fatal assertion that the value
 *                         is false. Test terminates if true.
 * ASSERT_STREQ(str1, str2)   -- Fatal assertion that the strings are equal.
 *                         Test terminates if false.
 * EXPECT_TRUE(value)   -- Nonfatal assertion that the value is true. Test
 *                         continues if false.
 * EXPECT_FALSE(value)   -- Nonfatal assertion that the value is false.
 *                          Test continues if true.
 * EXPECT_STREQ(str1, str2) -- Nonfatal assertion that the strings are equal.
 *                          Test continues if false.
 * EXPECT_THROW(statement, exception_type) -- nonfatal exception, cought,
 *                         reported and continues.
 *---------------------------------------------------------------------
 */

#include <random>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>

#include <nupic/algorithms/BacktrackingTMCpp.hpp>
#include <nupic/os/Directory.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/types/Exception.hpp>

#include <gtest/gtest.h>

#define VERBOSITY 0
#define VERBOSE if (verbose) std::cerr << "[          ] "
static bool verbose =  true; // turn this on to print extra stuff for debugging the test.
#define SEED 12

using namespace nupic;
using namespace nupic::algorithms::backtracking_tm;
namespace testing {

////////////////////////////////////////////////////////////////////////////////
//     helper routines
////////////////////////////////////////////////////////////////////////////////
typedef shared_ptr<Real32> Pattern_t;

// Generate a single test pattern of random bits with given parameters.
//
//    Parameters :
//    @numCols -Number of columns in each pattern.
//    @minOnes -The minimum number of 1's in each pattern.
//    @maxOnes -The maximum number of 1's in each pattern.

static Pattern_t generatePattern(Size numCols = 100, Size minOnes = 21,
                                 Size maxOnes = 25) {
  NTA_ASSERT(minOnes <= maxOnes);
  NTA_ASSERT(maxOnes < numCols);
  Pattern_t p(new Real32[numCols], std::default_delete<Real32[]>());
  memset(p.get(), 0, numCols);

  int numOnes = (int)minOnes + std::rand() % (maxOnes - minOnes + 1);
  std::uniform_int_distribution<> distr(0, (int)numCols - 1); // define the range (requires C++11)
  for (int n = 0; n < numOnes; n++) {
    int idx = std::rand() % numCols;
    p.get()[idx] = 1.0f;
  }
  return p;
}

// Generates a sequence of n random patterns.
static std::vector<Pattern_t> generateSequence(Size n = 10, Size numCols = 100,
                                               Size minOnes = 21,
                                               Size maxOnes = 25) {
  std::vector<Pattern_t> seq;
  Pattern_t p;  // an empty pattern which means reset
  seq.push_back(p);

  for (Size i = 0; i < n; i++) {
    Pattern_t p = generatePattern(numCols, minOnes, maxOnes);
    seq.push_back(p);
  }
  return seq;
}

struct param_t {
  UInt32 numberOfCols;
  UInt32 cellsPerColumn;
  Real32 initialPerm;
  Real32 connectedPerm;
  UInt32 minThreshold;
  UInt32 newSynapseCount;
  Real32 permanenceInc;
  Real32 permanenceDec;
  Real32 permanenceMax;
  Real32 globalDecay;
  UInt32 activationThreshold;
  bool doPooling;
  UInt32 segUpdateValidDuration;
  UInt32 burnIn;
  bool collectStats;
  Int32 seed;
  Int32 verbosity;
  bool checkSynapseConsistency;
  UInt32 pamLength;
  UInt32 maxInfBacktrack;
  UInt32 maxLrnBacktrack;
  UInt32 maxAge;
  UInt32 maxSeqLength;
  Int32 maxSegmentsPerCell;
  Int32 maxSynapsesPerSegment;
  char outputType[25];
};

void initializeParameters(struct param_t &param) {
  // same as default settings
  param.numberOfCols = 10;
  param.cellsPerColumn = 3;
  param.initialPerm = 0.11f;
  param.connectedPerm = 0.5f;
  param.minThreshold = 8;
  param.newSynapseCount = 15;
  param.permanenceInc = 0.1f;
  param.permanenceDec = 0.1f;
  param.permanenceMax = 1.0f;
  param.globalDecay = 0.1f;
  param.activationThreshold = 12;
  param.doPooling = false;
  param.segUpdateValidDuration = 5;
  param.burnIn = 2;
  param.collectStats = false;
  param.seed = 42;
  param.verbosity = VERBOSITY;
  param.checkSynapseConsistency = false;
  param.pamLength = 1;
  param.maxInfBacktrack = 10;
  param.maxLrnBacktrack = 5;
  param.maxAge = 100000;
  param.maxSeqLength = 32;
  param.maxSegmentsPerCell = -1;
  param.maxSynapsesPerSegment = -1;
  strcpy(param.outputType, "normal");
}

//////////////////////////////////////////////////////////////////
//////////    Tests
//////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////
// Run a test of the basic TM class ported from backtracking_tm_test.py
TEST(BacktrackingTMTest, testCheckpointLearned) {

  struct param_t param;
  initializeParameters(param);
  param.numberOfCols = 100;
  param.cellsPerColumn = 12;
  param.verbosity = VERBOSITY;

    // Create TM object
    BacktrackingTMCpp tm1(
        param.numberOfCols, param.cellsPerColumn, param.initialPerm,
        param.connectedPerm, param.minThreshold, param.newSynapseCount,
        param.permanenceInc, param.permanenceDec, param.permanenceMax,
        param.globalDecay, param.activationThreshold, param.doPooling,
        param.segUpdateValidDuration, param.burnIn, param.collectStats,
        param.seed, param.verbosity, param.checkSynapseConsistency,
        param.pamLength, param.maxInfBacktrack, param.maxLrnBacktrack,
        param.maxAge, param.maxSeqLength, param.maxSegmentsPerCell,
        param.maxSynapsesPerSegment, param.outputType);

    // generate 5 sets of sequences
    // The first pattern in each sequence is empty (a reset)
    std::vector<std::vector<Pattern_t>> sequences;
    for (Size s = 0; s < 5; s++) {
      sequences.push_back(generateSequence());
    }
    // train with the first 3 sets of sequences.
    std::vector<Pattern_t> train;
    for (Size s = 0; s < 3; s++) {
      for (Size i = 0; i < sequences[s].size();i++) {
        train.push_back(sequences[s][i]);
      }
    }

    // process the patterns that are in the training set.
    for (Size t = 0; t < train.size(); t++) {
      if (!train[t]) {
        tm1.reset();
      } else {
        Real *bottomUpInput = train[t].get();
        tm1.compute(bottomUpInput, true, true);
      }
    }
    // Serialize and deserialized the TM.
    Directory::create("TestOutputDir", false, true);
    std::string checkpointPath = "TestOutputDir/tm.save";
    tm1.saveToFile(checkpointPath);

    BacktrackingTMCpp tm2;
    tm2.loadFromFile(checkpointPath);

    // Check that the TMs are the same.
    ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));

    // Feed remaining data into the models.
    train.clear();
    for (Size s = 3; s < sequences.size(); s++) {
      for (Size i = 0; i < sequences[s].size(); i++) {
        train.push_back(sequences[s][i]);
      }
    }

    for (Size t = 0; t < train.size(); t++) {
      if (!train[t]) {
        tm1.reset();
        tm2.reset();
      } else {
        Real *bottomUpInput = train[t].get();
        Real *result1 = tm1.compute(bottomUpInput, true, true);
        Real *result2 = tm2.compute(bottomUpInput, true, true);

        ASSERT_TRUE(tm1 == tm2);
        ASSERT_TRUE(tm1.getOutputBufferSize() == tm2.getOutputBufferSize());
	ASSERT_EQ(tm1, tm2);
        for (Size i = 0; i < tm1.getOutputBufferSize(); i++) {
          ASSERT_TRUE(result1[i] == result2[i]);
        }
      }
    }

    // cleanup .
  Directory::removeTree("TestOutputDir");

}

TEST(BacktrackingTMTest, testCheckpointMiddleOfSequence)
{
    // Create a model and give it some inputs to learn.
    BacktrackingTMCpp tm1(100, 12);
    tm1.setVerbosity((Int32)VERBOSITY);

    // generate 5 sets of sequences
    std::vector<std::vector<Pattern_t>> sequences;
    for (Size s = 0; s < 5; s++) {
      sequences.push_back(generateSequence());
    }
    // separate train sets of sequences into halves
    std::vector<Pattern_t> firstHalf, secondHalf;
    const int HALF = 5*10 /2;
    int idx = 0;
    for (auto seq: sequences) {
      for (auto pattern : seq) {
	if(idx++ < HALF) firstHalf.push_back(pattern);
	else secondHalf.push_back(pattern);
      }
    }

    // compute each of the patterns in train, learn
    for (auto p: firstHalf) {
      const auto pat = p.get();
      if (!pat) {
        tm1.reset();
      } else {
        tm1.compute(pat, true, true);
      }
    }

    // Serialize and TM.
    Directory::create("TestOutputDir", false, true);
    std::string checkpointPath = "TestOutputDir/tm.save";
    tm1.saveToFile(checkpointPath);

    // Restore the saved TM into tm2.
    // Note that this resets the random generator to the same
    // point that the first TM used when it processed that second set
    // of patterns.
    BacktrackingTMCpp tm2;
    tm2.loadFromFile(checkpointPath);

    ASSERT_EQ(tm1, tm2) << "Deserialized TM is equal";
    ASSERT_TRUE(tm1 == tm2);

    // process the remaining patterns in train with the first TM.
    for (auto p: secondHalf) {
      const auto pat = p.get();
      if (!pat) {
        tm1.reset();
      } else {
        Real *result1 = tm1.compute(pat, true, true);
      }
    }

    ASSERT_TRUE(tm1 != tm2) << "TM1 moved, TM2 didn't";

    // process the same remaining patterns in the train with the second TM.
    for (auto p: secondHalf) {
      const auto pat = p.get();
      if (!pat) {
        tm2.reset();
      } else {
        Real *result22= tm2.compute(pat, true, true);
      }
    }

    ASSERT_EQ(tm1, tm2) << "Both TM trained";
    ASSERT_TRUE(tm1 == tm2);

    // cleanup if successful.
    Directory::removeTree("TestOutputDir");
 }

////////////////////////////////////////////////////////////////////////////////
// Run a test of the TM class ported from backtracking_tm_cpp2_test.py
TEST(BacktrackingTMTest, basicTest) {
    // Create a model and give it some inputs to learn.
    BacktrackingTMCpp tm1(10, 3, 0.2f, 0.8f, 2, 5, 0.10f, 0.05f, 1.0f, 0.05f, 4,
                          false, 5, 2, false, SEED, (Int32)VERBOSITY /* rest are defaults */);
    tm1.setRetrieveLearningStates(true);
    Size nCols = tm1.getnumCol();

    // Serialize and deserialized the TM.
    Directory::create("TestOutputDir", false, true);
    std::string checkpointPath = "TestOutputDir/tm.save";
    tm1.saveToFile(checkpointPath);

    BacktrackingTMCpp tm2;
    tm2.loadFromFile(checkpointPath);

    // Check that the TMs are the same.
    ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));

    // generate some test data and NT patterns from it.
    std::vector<Pattern_t> data = generateSequence(10, nCols, 2, 2);
    std::vector<std::vector<UInt>> nzData;
    for (Size i = 0; i < data.size(); i++) {
      if (data[i]) { // skip reset patterns
        const auto indices =
		nupic::algorithms::backtracking_tm::nonzero<Real>(data[i].get(), nCols);
        nzData.push_back(indices);
      }
    }

    // Learn
    for (Size i = 0; i < 5; i++) {
      if (data[i])
        tm1.learn(data[i].get());
    }
    tm1.reset();

    // save and reload again after learning.
    tm1.saveToFile(checkpointPath);
    BacktrackingTMCpp tm3;
    tm3.loadFromFile(checkpointPath);
    // Check that the TMs are the same.
    ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm3, std::cout, 2));

    // Infer
    for (Size i = 0; i < 10; i++) {
      if (data[i]) {
        tm1.infer(data[i].get());
        if (i > 0)
          tm1._checkPrediction(nzData);
      }
    }

    // cleanup if successful.
    Directory::removeTree("TestOutputDir");
}

} // namespace testing
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bootstrapcontext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-06-18 15:49:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_
#define CONFIGMGR_BOOTSTRAPCONTEXT_HXX_

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _RTL_BOOTSTRAP_H_
#include <rtl/bootstrap.h>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCURRENTCONTEXT_HPP_
#include <com/sun/star/uno/XCurrentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_

namespace com { namespace sun { namespace star { namespace uno {
    class XComponentContext;
} } } }

// -----------------------------------------------------------------------------
#define SINGLETON_ "/singletons/"
#define SINGLETON( NAME ) OUString( RTL_CONSTASCII_USTRINGPARAM( SINGLETON_ NAME ) )
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace uno   = ::com::sun::star::uno;
    namespace lang  = ::com::sun::star::lang;
    namespace beans = ::com::sun::star::beans;
    using ::rtl::OUString;
// -----------------------------------------------------------------------------
    typedef ::cppu::WeakComponentImplHelper3 <
                    uno::XComponentContext,
                    uno::XCurrentContext,
                    lang::XServiceInfo
                > ComponentContext_Base;
    /** Base class for customized ComponentContext using bootstrap data and overrides
    */
    class ComponentContext : public ComponentContext_Base
    {
    public:
        typedef uno::Reference< uno::XComponentContext >        Context;
        typedef uno::Reference< lang::XMultiComponentFactory >  ServiceManager;

    // creation and destruction
    public:
        /** Constructs a ComponentContext based on the given overrides and context.
            Initially no bootstrap data will be used.

            @param _xContext
                The base context of this component context.
                Values from here take precedence over values from bootstrap data.

            @param _aOverrides
                The overrides used to create this component context.
                These values take precedence over values from the base context or bootstrap data.
        */
        explicit
        ComponentContext(Context const & _xContext);

        /// Destroys this BootstrapContext
        ~ComponentContext();

        /// changes the INI file to use for bootstrap data
        void changeBootstrapURL( const OUString& _aURL );

        // gets the INI in use for getting bootstrap data
        OUString getBootstrapURL() const;

        static sal_Bool isPassthrough(Context const & _xContext);

        static Context getBaseContext(Context const & _xContext);

        static beans::NamedValue makePassthroughMarker(sal_Bool bPassthrough = true);
    // interface implementations
    public:
    // XComponentContext & XCurrentContext
        /** Retrieves a value from this context.
            Can be overridden in derived implementations

            @param Name
                The name of the value to retrieve.

            @returns
                The requested value, or <VOID/> if the value is not found.
        */
        virtual uno::Any SAL_CALL
            getValueByName( const OUString& Name )
                throw (uno::RuntimeException) = 0;

    // XComponentContext only
        virtual ServiceManager SAL_CALL
            getServiceManager(  )
                throw (uno::RuntimeException);

    protected:
    // ComponentHelper
        virtual void SAL_CALL disposing();

    protected:
        // two phase construct - also initialized the bootstrap data
        void initialize(const OUString& _aBootstrapURL);

        bool lookupInContext  ( uno::Any & _rValue, const OUString& _aName ) const;
        bool lookupInBootstrap( uno::Any & _rValue, const OUString& _aName ) const;

        osl::Mutex & mutex() const { return m_aMutex; }
        Context const & basecontext() const { osl::MutexGuard lock(mutex()); return m_xContext; }

    private:
        /// The mutex protecting this component
        mutable osl::Mutex  m_aMutex;
        /// The context that most requests are delegated to
        Context             m_xContext;
        /// The bootstrap data consulted as fallback
        rtlBootstrapHandle  m_hBootstrapData;
    };
// -----------------------------------------------------------------------------

    class UnoContextTunnel
    {
    public:
        typedef uno::Reference< uno::XCurrentContext >  CurrentContext;
        typedef uno::Reference< lang::XUnoTunnel >      FailureTunnel;
        typedef uno::Reference< uno::XComponentContext > Context;
    public:
        UnoContextTunnel();
        ~UnoContextTunnel();
        void tunnel(Context const & xContext);
        void passthru(Context const & xContext);
        uno::Any recoverFailure(bool bRaise); // true, if there is a failure

        static Context recoverContext(Context const & xFallback = Context());
        static bool tunnelFailure(uno::Any const & aException, bool bRaise = false);
    private:
        CurrentContext  m_xOldContext;
        FailureTunnel   m_xActiveTunnel;
        class Tunnel;
    };
// -----------------------------------------------------------------------------

    class DisposingForwarder : public cppu::WeakImplHelper1< lang::XEventListener >
    {
        uno::Reference< lang::XComponent > m_xTarget;

        DisposingForwarder( uno::Reference< lang::XComponent > const & xTarget ) SAL_THROW( () )
        : m_xTarget( xTarget )
        { OSL_ASSERT( m_xTarget.is() ); }

        virtual void SAL_CALL disposing( lang::EventObject const & rSource )
            throw (uno::RuntimeException);
    public:
        // listens at source for disposing, then disposes target
        static inline void forward(
            uno::Reference< lang::XComponent > const & xSource,
            uno::Reference< lang::XComponent > const & xTarget )
            SAL_THROW( (uno::RuntimeException) );
    };
//__________________________________________________________________________________________________
    inline void DisposingForwarder::forward(
        uno::Reference< lang::XComponent > const & xSource,
        uno::Reference< lang::XComponent > const & xTarget )
        SAL_THROW( (uno::RuntimeException) )
    {
        if (xSource.is())
        {
            xSource->addEventListener( new DisposingForwarder( xTarget ) );
        }
    }
// -----------------------------------------------------------------------------
} // namespace configmgr

#endif

<commit_msg>INTEGRATION: CWS cfglooseends (1.3.30); FILE MERGED 2004/11/02 16:57:22 jb 1.3.30.1: #109882# Use own servicemanager (-wrapper) for bootstrap context<commit_after>/*************************************************************************
 *
 *  $RCSfile: bootstrapcontext.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-15 13:36:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_
#define CONFIGMGR_BOOTSTRAPCONTEXT_HXX_

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _RTL_BOOTSTRAP_H_
#include <rtl/bootstrap.h>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCURRENTCONTEXT_HPP_
#include <com/sun/star/uno/XCurrentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_

namespace com { namespace sun { namespace star { namespace uno {
    class XComponentContext;
} } } }

// -----------------------------------------------------------------------------
#define SINGLETON_ "/singletons/"
#define SINGLETON( NAME ) OUString( RTL_CONSTASCII_USTRINGPARAM( SINGLETON_ NAME ) )
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace uno   = ::com::sun::star::uno;
    namespace lang  = ::com::sun::star::lang;
    namespace beans = ::com::sun::star::beans;
    using ::rtl::OUString;
// -----------------------------------------------------------------------------
    typedef ::cppu::WeakComponentImplHelper3 <
                    uno::XComponentContext,
                    uno::XCurrentContext,
                    lang::XServiceInfo
                > ComponentContext_Base;
    /** Base class for customized ComponentContext using bootstrap data and overrides
    */
    class ComponentContext : public ComponentContext_Base
    {
    public:
        typedef uno::Reference< uno::XComponentContext >        Context;
        typedef uno::Reference< lang::XMultiComponentFactory >  ServiceManager;

    // creation and destruction
    public:
        /** Constructs a ComponentContext based on the given overrides and context.
            Initially no bootstrap data will be used.

            @param _xContext
                The base context of this component context.
                Values from here take precedence over values from bootstrap data.

            @param _aOverrides
                The overrides used to create this component context.
                These values take precedence over values from the base context or bootstrap data.
        */
        explicit
        ComponentContext(Context const & _xContext);

        /// Destroys this BootstrapContext
        ~ComponentContext();

        /// changes the INI file to use for bootstrap data
        void changeBootstrapURL( const OUString& _aURL );

        // gets the INI in use for getting bootstrap data
        OUString getBootstrapURL() const;

        static sal_Bool isPassthrough(Context const & _xContext);

        static Context getBaseContext(Context const & _xContext);

        static beans::NamedValue makePassthroughMarker(sal_Bool bPassthrough = true);
    // interface implementations
    public:
    // XComponentContext & XCurrentContext
        /** Retrieves a value from this context.
            Can be overridden in derived implementations

            @param Name
                The name of the value to retrieve.

            @returns
                The requested value, or <VOID/> if the value is not found.
        */
        virtual uno::Any SAL_CALL
            getValueByName( const OUString& Name )
                throw (uno::RuntimeException) = 0;

    // XComponentContext only
        virtual ServiceManager SAL_CALL
            getServiceManager(  )
                throw (uno::RuntimeException);

    protected:
    // ComponentHelper
        virtual void SAL_CALL disposing();

    protected:
        // two phase construct - also initialized the bootstrap data
        void initialize(const OUString& _aBootstrapURL);

        bool lookupInContext  ( uno::Any & _rValue, const OUString& _aName ) const;
        bool lookupInBootstrap( uno::Any & _rValue, const OUString& _aName ) const;

        osl::Mutex & mutex() const { return m_aMutex; }
        Context const & basecontext() const { osl::MutexGuard lock(mutex()); return m_xContext; }

    private:
        /// The mutex protecting this component
        mutable osl::Mutex  m_aMutex;
        /// The context that most requests are delegated to
        Context             m_xContext;
        /// The bootstrap data consulted as fallback
        rtlBootstrapHandle  m_hBootstrapData;
        /// The service manager associated with this context
        ServiceManager      m_xServiceManager;
    };
// -----------------------------------------------------------------------------

    class UnoContextTunnel
    {
    public:
        typedef uno::Reference< uno::XCurrentContext >  CurrentContext;
        typedef uno::Reference< lang::XUnoTunnel >      FailureTunnel;
        typedef uno::Reference< uno::XComponentContext > Context;
    public:
        UnoContextTunnel();
        ~UnoContextTunnel();
        void tunnel(Context const & xContext);
        void passthru(Context const & xContext);
        uno::Any recoverFailure(bool bRaise); // true, if there is a failure

        static Context recoverContext(Context const & xFallback = Context());
        static bool tunnelFailure(uno::Any const & aException, bool bRaise = false);
    private:
        CurrentContext  m_xOldContext;
        FailureTunnel   m_xActiveTunnel;
        class Tunnel;
    };
// -----------------------------------------------------------------------------

    class DisposingForwarder : public cppu::WeakImplHelper1< lang::XEventListener >
    {
        uno::Reference< lang::XComponent > m_xTarget;

        DisposingForwarder( uno::Reference< lang::XComponent > const & xTarget ) SAL_THROW( () )
        : m_xTarget( xTarget )
        { OSL_ASSERT( m_xTarget.is() ); }

        virtual void SAL_CALL disposing( lang::EventObject const & rSource )
            throw (uno::RuntimeException);
    public:
        // listens at source for disposing, then disposes target
        static inline void forward(
            uno::Reference< lang::XComponent > const & xSource,
            uno::Reference< lang::XComponent > const & xTarget )
            SAL_THROW( (uno::RuntimeException) );
    };
//__________________________________________________________________________________________________
    inline void DisposingForwarder::forward(
        uno::Reference< lang::XComponent > const & xSource,
        uno::Reference< lang::XComponent > const & xTarget )
        SAL_THROW( (uno::RuntimeException) )
    {
        if (xSource.is())
        {
            xSource->addEventListener( new DisposingForwarder( xTarget ) );
        }
    }
// -----------------------------------------------------------------------------
} // namespace configmgr

#endif

<|endoftext|>


<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 1000;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			t -= 1;
			//Pulse(out1, sin((2PI/2) * abs(1/t)));
			//Wait(sin((PI/2) * abs(1/t)));
			Pulse(out1, sin((2*PI) * abs(1/t)));
			Wait(sin((2*PI) * abs(1/t)));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 / resolution);
			Wait(1/resolution);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 1000;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			t -= 1;
			//Pulse(out1, sin((2PI/2) * abs(1/t)));
			//Wait(sin((PI/2) * abs(1/t)));
			Pulse(out1, sin((2*PI) * abs(1/t)));
			Wait(sin((2*PI) * abs(1/t)));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1/resolution);
			Wait(2/resolution);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<|endoftext|>


<commit_before>#include "VulkanGraphicsInstance.hpp"

#if defined(PLATFORM_WINDOWS)
#include <intrin.h>
#endif

VulkanGraphicsInstance::VulkanGraphicsInstance()
  : m_alloc_info(reinterpret_cast<void*>(&m_allocs), allocs::pfnAllocation, allocs::pfnReallocation, allocs::pfnFree, allocs::pfnInternalAllocation, allocs::pfnInternalFree)

  , m_instance(new vk::Instance, [=](vk::Instance* ist)
    {
      (*ist).destroy(&m_alloc_info);
    })
{
}

VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
  VkDebugReportFlagsEXT                       flags,
  VkDebugReportObjectTypeEXT                  /*objectType*/,
  uint64_t                                    /*object*/,
  size_t                                      /*Location*/,
  int32_t                                     messageCode,
  const char*                                 pLayerPrefix,
  const char*                                 pMessage,
  void*                                       /*pUserData*/)
{
	// Supressing unnecessary log messages.

  std::string msgType = "";
  #if defined(PLATFORM_WINDOWS)
  bool breakOn = false;
  #endif
  if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
  {
    msgType = "ERROR:";
    #if defined(PLATFORM_WINDOWS)
    breakOn = true;
      #endif
  }
  else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
  {
    msgType = "WARNING:";
    #if defined(PLATFORM_WINDOWS)
    breakOn = true;
      #endif
  }
  else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
  {
    msgType = "PERFORMANCE WARNING:";
  }
  else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
  {
    msgType = "INFO:";
  }
  else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
  {
    msgType = "DEBUG:";
  }
	if (std::string(pLayerPrefix) == "loader" || std::string(pLayerPrefix) == "DebugReport")
		return false;
  F_ILOG("Vulkan/DebugCallback", "%s %s {%d}: %s", msgType.c_str(), pLayerPrefix, messageCode, pMessage);
#if defined(PLATFORM_WINDOWS)
  if (breakOn && IsDebuggerPresent())
    __debugbreak();
#endif
  return false;
}

bool VulkanGraphicsInstance::createInstance(const char* appName, unsigned appVersion, const char* engineName, unsigned engineVersion)
{
  /////////////////////////////////
  // getting debug layers
  // TODO: These need to be saved for device creation also. which layers and extensions each use.
  auto layersInfos = vk::enumerateInstanceLayerProperties();

  std::vector<const char*> layers;
  {
    // lunargvalidation list order
    GFX_ILOG("Enabled Vulkan debug layers:");
    for (auto&& it : layerOrder)
    {
      auto found = std::find_if(layersInfos.begin(), layersInfos.end(), [&](const vk::LayerProperties& layer)
      {
        return it == layer.layerName;
      });
      if (found != layersInfos.end())
      {
        layers.push_back(it.c_str());
        m_layers.push_back(*found);
        GFX_ILOG("%s", found->layerName);
      }
      else
      {
        GFX_ILOG("not enabled %s", it.c_str());
      }
    }
  }
  /////////////////////////////////
  // Getting extensions
  std::vector<vk::ExtensionProperties> extInfos = vk::enumerateInstanceExtensionProperties();

  std::vector<const char*> extensions;
  {
    // lunargvalidation list order
    GFX_ILOG("Enabled Vulkan extensions:");

    for (auto&& it : extOrder)
    {
      auto found = std::find_if(extInfos.begin(), extInfos.end(), [&](const vk::ExtensionProperties& layer)
      {
        return it == layer.extensionName;
      });
      if (found != extInfos.end())
      {
        extensions.push_back(it.c_str());
        m_extensions.push_back(*found);
        GFX_ILOG("%s", found->extensionName);
      }
      else
      {
        GFX_ILOG("not enabled %s", it.c_str());
      }
    }
  }

  /////////////////////////////////
  // app instance
  app_info = vk::ApplicationInfo()
    .setPApplicationName(appName)
    .setApplicationVersion(appVersion)
    .setPEngineName(engineName)
    .setEngineVersion(engineVersion)
    .setApiVersion(VK_API_VERSION_1_0);

  instance_info = vk::InstanceCreateInfo()
    .setPApplicationInfo(&app_info)
    .setEnabledLayerCount(static_cast<uint32_t>(layers.size()))
    .setPpEnabledLayerNames(layers.data())
    .setEnabledExtensionCount(static_cast<uint32_t>(extensions.size()))
    .setPpEnabledExtensionNames(extensions.data());

  vk::Result res = vk::createInstance(&instance_info, &m_alloc_info, m_instance.get());

  if (res != vk::Result::eSuccess)
  {
    // quite hot shit baby yeah!
    auto error = vk::to_string(res);
    GFX_ILOG("Instance creation error: %s", error.c_str());
    return false;
  }
  m_devices = m_instance->enumeratePhysicalDevices();

  // get addresses for few functions
  PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;
  PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;

  dbgCreateDebugReportCallback =
    (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
      *m_instance, "vkCreateDebugReportCallbackEXT");
  if (!dbgCreateDebugReportCallback) {
    GFX_ILOG("GetInstanceProcAddr: Unable to find vkCreateDebugReportCallbackEXT function.");;
    return true;
  }

  dbgDestroyDebugReportCallback =
    (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
      *m_instance, "vkDestroyDebugReportCallbackEXT");
  if (!dbgDestroyDebugReportCallback) {
    GFX_ILOG("GetInstanceProcAddr: Unable to find vkDestroyDebugReportCallbackEXT function.");;
    return true;
  }
  // the debug things
  auto flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::eDebug;
  vk::DebugReportCallbackCreateInfoEXT info = vk::DebugReportCallbackCreateInfoEXT(flags, debugCallback, nullptr);

  auto lol = m_instance; // callback needs to keep instance alive until its destroyed... so this works :DD
  auto allocInfo = m_alloc_info;
  m_debugcallback = std::shared_ptr<vk::DebugReportCallbackEXT>(new vk::DebugReportCallbackEXT, [lol, allocInfo, dbgDestroyDebugReportCallback](vk::DebugReportCallbackEXT* ist)
  {
    dbgDestroyDebugReportCallback(*lol, *ist, reinterpret_cast<const VkAllocationCallbacks*>(&allocInfo));
  });
  dbgCreateDebugReportCallback(*m_instance, reinterpret_cast<const VkDebugReportCallbackCreateInfoEXT*>(&info), reinterpret_cast<const VkAllocationCallbacks*>(&m_alloc_info), reinterpret_cast<VkDebugReportCallbackEXT*>(m_debugcallback.get()));
  return true;
}

VulkanGpuDevice VulkanGraphicsInstance::createGpuDevice(FileSystem& fs)
{

  auto canPresent = [](vk::PhysicalDevice dev)
  {
    auto queueProperties = dev.getQueueFamilyProperties();
    for (auto&& queueProp : queueProperties)
    {
      for (uint32_t i = 0; i < queueProp.queueCount; ++i)
      {
#if defined(PLATFORM_WINDOWS)
        if (dev.getWin32PresentationSupportKHR(i))
#endif
        {
          return true;
        }
      }
    }
    return false;
  };
  int devId = 0;
  for (devId = 0; devId < static_cast<int>(m_devices.size()); ++devId)
  {
    if (canPresent(m_devices[devId]))
      break;
  }
  auto&& physDev = m_devices[devId]; // assuming first device is best

  // extensions
  std::vector<vk::ExtensionProperties> devExts = physDev.enumerateDeviceExtensionProperties();

  std::vector<const char*> extensions;
  {
    GFX_ILOG("Available extensions for device:");
    for (auto&& it : devExts)
    {
      GFX_ILOG("%s", it.extensionName);
    }
    // lunargvalidation list order
    GFX_ILOG("Enabled Vulkan extensions for device:");

    for (auto&& it : devExtOrder)
    {
      auto found = std::find_if(devExts.begin(), devExts.end(), [&](const vk::ExtensionProperties& layer)
      {
        return it == layer.extensionName;
      });
      if (found != devExts.end())
      {
        extensions.push_back(it.c_str());
        m_extensions.push_back(*found);
        GFX_ILOG("%s", found->extensionName);
      }
    }
  }
  // queue

  //auto queueProperties = vk::getPhysicalDeviceQueueFamilyProperties(physDev);
  auto queueProperties = physDev.getQueueFamilyProperties();
  std::vector<vk::DeviceQueueCreateInfo> queueInfos;
  uint32_t i = 0;
  std::vector<std::vector<float>> priorities;
  for (auto&& queueProp : queueProperties)
  {
    priorities.push_back(std::vector<float>());
    for (size_t k = 0; k < queueProp.queueCount; ++k)
    {
      priorities[i].push_back(1.f);
    }
    vk::DeviceQueueCreateInfo queueInfo = vk::DeviceQueueCreateInfo()
      .setQueueFamilyIndex(i)
      .setQueueCount(queueProp.queueCount)
      .setPQueuePriorities(priorities[i].data());
    // queue priorities go here.
    queueInfos.push_back(queueInfo);
    ++i;
  }

  auto features = physDev.getFeatures(); // ALL OF THEM FEATURES.

  auto heapInfos = physDev.getMemoryProperties();

  auto device_info = vk::DeviceCreateInfo()
    .setQueueCreateInfoCount(static_cast<uint32_t>(queueInfos.size()))
    .setPQueueCreateInfos(queueInfos.data())
    .setEnabledExtensionCount(static_cast<uint32_t>(extensions.size()))
    .setPpEnabledExtensionNames(extensions.data())
    .setPEnabledFeatures(&features);

  vk::Device dev = physDev.createDevice(device_info, m_alloc_info);

  std::shared_ptr<vk::Device> device(new vk::Device(dev), [=](vk::Device* ist)
  {
    ist->destroy(&m_alloc_info);
	delete ist;
  });

  return VulkanGpuDevice(device,physDev, fs, m_alloc_info, queueProperties, heapInfos, false);
}

#if defined(PLATFORM_WINDOWS)
VulkanSurface VulkanGraphicsInstance::createSurface(HWND hWnd, HINSTANCE instance)
{
	vk::Win32SurfaceCreateInfoKHR createInfo = vk::Win32SurfaceCreateInfoKHR()
		.setHwnd(hWnd)
		.setHinstance(instance);

	VulkanSurface surface;

	vk::SurfaceKHR surfacekhr = m_instance->createWin32SurfaceKHR(createInfo);

	auto inst = m_instance;

	std::shared_ptr<vk::SurfaceKHR> khrSur(new vk::SurfaceKHR(surfacekhr), [inst](vk::SurfaceKHR* ist)
	{
		inst->destroySurfaceKHR(*ist);
		delete ist;
	});

	surface.surface = khrSur;

	return surface;
}
#else
VulkanSurface VulkanGraphicsInstance::createSurface()
{
	return VulkanSurface();
}
#endif<commit_msg>added device information output, prettified<commit_after>#include "VulkanGraphicsInstance.hpp"

#if defined(PLATFORM_WINDOWS)
#include <intrin.h>
#endif

VulkanGraphicsInstance::VulkanGraphicsInstance()
  : m_alloc_info(reinterpret_cast<void*>(&m_allocs), allocs::pfnAllocation, allocs::pfnReallocation, allocs::pfnFree, allocs::pfnInternalAllocation, allocs::pfnInternalFree)

  , m_instance(new vk::Instance, [=](vk::Instance* ist)
    {
      (*ist).destroy(&m_alloc_info);
    })
{
}

VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
  VkDebugReportFlagsEXT                       flags,
  VkDebugReportObjectTypeEXT                  /*objectType*/,
  uint64_t                                    /*object*/,
  size_t                                      /*Location*/,
  int32_t                                     messageCode,
  const char*                                 pLayerPrefix,
  const char*                                 pMessage,
  void*                                       /*pUserData*/)
{
	// Supressing unnecessary log messages.

  std::string msgType = "";
  #if defined(PLATFORM_WINDOWS)
  bool breakOn = false;
  #endif
  if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
  {
    msgType = "ERROR:";
    #if defined(PLATFORM_WINDOWS)
    breakOn = true;
      #endif
  }
  else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
  {
    msgType = "WARNING:";
    #if defined(PLATFORM_WINDOWS)
    breakOn = true;
      #endif
  }
  else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
  {
    msgType = "PERFORMANCE WARNING:";
  }
  else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
  {
    msgType = "INFO:";
  }
  else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
  {
    msgType = "DEBUG:";
  }
	if (std::string(pLayerPrefix) == "loader" || std::string(pLayerPrefix) == "DebugReport")
		return false;
  F_ILOG("Vulkan/DebugCallback", "%s %s {%d}: %s", msgType.c_str(), pLayerPrefix, messageCode, pMessage);
#if defined(PLATFORM_WINDOWS)
  if (breakOn && IsDebuggerPresent())
    __debugbreak();
#endif
  return false;
}

bool VulkanGraphicsInstance::createInstance(const char* appName, unsigned appVersion, const char* engineName, unsigned engineVersion)
{
  /////////////////////////////////
  // getting debug layers
  // TODO: These need to be saved for device creation also. which layers and extensions each use.
  auto layersInfos = vk::enumerateInstanceLayerProperties();

  std::vector<const char*> layers;
  {
    // lunargvalidation list order
    GFX_ILOG("Enabled Vulkan debug layers:");
    for (auto&& it : layerOrder)
    {
      auto found = std::find_if(layersInfos.begin(), layersInfos.end(), [&](const vk::LayerProperties& layer)
      {
        return it == layer.layerName;
      });
      if (found != layersInfos.end())
      {
        layers.push_back(it.c_str());
        m_layers.push_back(*found);
        GFX_ILOG("\t\t%s", found->layerName);
      }
      else
      {
        GFX_ILOG("not enabled %s", it.c_str());
      }
    }
  }
  /////////////////////////////////
  // Getting extensions
  std::vector<vk::ExtensionProperties> extInfos = vk::enumerateInstanceExtensionProperties();

  std::vector<const char*> extensions;
  {
    // lunargvalidation list order
    GFX_ILOG("Enabled Vulkan extensions:");

    for (auto&& it : extOrder)
    {
      auto found = std::find_if(extInfos.begin(), extInfos.end(), [&](const vk::ExtensionProperties& layer)
      {
        return it == layer.extensionName;
      });
      if (found != extInfos.end())
      {
        extensions.push_back(it.c_str());
        m_extensions.push_back(*found);
        GFX_ILOG("\t\t%s", found->extensionName);
      }
      else
      {
        GFX_ILOG("not enabled %s", it.c_str());
      }
    }
  }

  /////////////////////////////////
  // app instance
  app_info = vk::ApplicationInfo()
    .setPApplicationName(appName)
    .setApplicationVersion(appVersion)
    .setPEngineName(engineName)
    .setEngineVersion(engineVersion)
    .setApiVersion(VK_API_VERSION_1_0);

  instance_info = vk::InstanceCreateInfo()
    .setPApplicationInfo(&app_info)
    .setEnabledLayerCount(static_cast<uint32_t>(layers.size()))
    .setPpEnabledLayerNames(layers.data())
    .setEnabledExtensionCount(static_cast<uint32_t>(extensions.size()))
    .setPpEnabledExtensionNames(extensions.data());

  vk::Result res = vk::createInstance(&instance_info, &m_alloc_info, m_instance.get());

  if (res != vk::Result::eSuccess)
  {
    // quite hot shit baby yeah!
    auto error = vk::to_string(res);
    GFX_ILOG("Instance creation error: %s", error.c_str());
    return false;
  }
  m_devices = m_instance->enumeratePhysicalDevices();

  // get addresses for few functions
  PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;
  PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;

  dbgCreateDebugReportCallback =
    (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
      *m_instance, "vkCreateDebugReportCallbackEXT");
  if (!dbgCreateDebugReportCallback) {
    GFX_ILOG("GetInstanceProcAddr: Unable to find vkCreateDebugReportCallbackEXT function.");;
    return true;
  }

  dbgDestroyDebugReportCallback =
    (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
      *m_instance, "vkDestroyDebugReportCallbackEXT");
  if (!dbgDestroyDebugReportCallback) {
    GFX_ILOG("GetInstanceProcAddr: Unable to find vkDestroyDebugReportCallbackEXT function.");;
    return true;
  }
  // the debug things
  auto flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::eDebug;
  vk::DebugReportCallbackCreateInfoEXT info = vk::DebugReportCallbackCreateInfoEXT(flags, debugCallback, nullptr);

  auto lol = m_instance; // callback needs to keep instance alive until its destroyed... so this works :DD
  auto allocInfo = m_alloc_info;
  m_debugcallback = std::shared_ptr<vk::DebugReportCallbackEXT>(new vk::DebugReportCallbackEXT, [lol, allocInfo, dbgDestroyDebugReportCallback](vk::DebugReportCallbackEXT* ist)
  {
    dbgDestroyDebugReportCallback(*lol, *ist, reinterpret_cast<const VkAllocationCallbacks*>(&allocInfo));
  });
  dbgCreateDebugReportCallback(*m_instance, reinterpret_cast<const VkDebugReportCallbackCreateInfoEXT*>(&info), reinterpret_cast<const VkAllocationCallbacks*>(&m_alloc_info), reinterpret_cast<VkDebugReportCallbackEXT*>(m_debugcallback.get()));
  return true;
}

VulkanGpuDevice VulkanGraphicsInstance::createGpuDevice(FileSystem& fs)
{

  auto canPresent = [](vk::PhysicalDevice dev)
  {
    auto queueProperties = dev.getQueueFamilyProperties();
    for (auto&& queueProp : queueProperties)
    {
      for (uint32_t i = 0; i < queueProp.queueCount; ++i)
      {
#if defined(PLATFORM_WINDOWS)
        if (dev.getWin32PresentationSupportKHR(i))
#endif
        {
          return true;
        }
      }
    }
    return false;
  };
  int devId = 0;
  for (devId = 0; devId < static_cast<int>(m_devices.size()); ++devId)
  {
    if (canPresent(m_devices[devId]))
      break;
  }
  auto&& physDev = m_devices[devId]; // assuming first device is best

  // some info
  auto stuff = physDev.getProperties();
  GFX_ILOG("Creating gpu device:");
  GFX_ILOG("\t\tID: %u", stuff.deviceID);
  GFX_ILOG("\t\tVendor: %u", stuff.vendorID);
  GFX_ILOG("\t\tDevice: %s", stuff.deviceName);
  GFX_ILOG("\t\tApi: %u", stuff.apiVersion);
  GFX_ILOG("\t\tDriver: %u", stuff.driverVersion);
  GFX_ILOG("\t\tType: %s", vk::to_string(stuff.deviceType).c_str());

  // extensions
  std::vector<vk::ExtensionProperties> devExts = physDev.enumerateDeviceExtensionProperties();

  std::vector<const char*> extensions;
  {
    GFX_ILOG("Available extensions for device:");
    for (auto&& it : devExts)
    {
      GFX_ILOG("\t\t%s", it.extensionName);
    }
    // lunargvalidation list order
    GFX_ILOG("Enabled Vulkan extensions for device:");

    for (auto&& it : devExtOrder)
    {
      auto found = std::find_if(devExts.begin(), devExts.end(), [&](const vk::ExtensionProperties& layer)
      {
        return it == layer.extensionName;
      });
      if (found != devExts.end())
      {
        extensions.push_back(it.c_str());
        m_extensions.push_back(*found);
        GFX_ILOG("\t\t%s", found->extensionName);
      }
    }
  }

  // queue
  auto queueProperties = physDev.getQueueFamilyProperties();
  std::vector<vk::DeviceQueueCreateInfo> queueInfos;
  uint32_t i = 0;
  std::vector<std::vector<float>> priorities;
  for (auto&& queueProp : queueProperties)
  {
    priorities.push_back(std::vector<float>());
    for (size_t k = 0; k < queueProp.queueCount; ++k)
    {
      priorities[i].push_back(1.f);
    }
    vk::DeviceQueueCreateInfo queueInfo = vk::DeviceQueueCreateInfo()
      .setQueueFamilyIndex(i)
      .setQueueCount(queueProp.queueCount)
      .setPQueuePriorities(priorities[i].data());
    // queue priorities go here.
    queueInfos.push_back(queueInfo);
    ++i;
  }

  auto features = physDev.getFeatures(); // ALL OF THEM FEATURES.

  auto heapInfos = physDev.getMemoryProperties();

  auto device_info = vk::DeviceCreateInfo()
    .setQueueCreateInfoCount(static_cast<uint32_t>(queueInfos.size()))
    .setPQueueCreateInfos(queueInfos.data())
    .setEnabledExtensionCount(static_cast<uint32_t>(extensions.size()))
    .setPpEnabledExtensionNames(extensions.data())
    .setPEnabledFeatures(&features);

  vk::Device dev = physDev.createDevice(device_info, m_alloc_info);

  std::shared_ptr<vk::Device> device(new vk::Device(dev), [=](vk::Device* ist)
  {
    ist->destroy(&m_alloc_info);
	delete ist;
  });

  return VulkanGpuDevice(device,physDev, fs, m_alloc_info, queueProperties, heapInfos, false);
}

#if defined(PLATFORM_WINDOWS)
VulkanSurface VulkanGraphicsInstance::createSurface(HWND hWnd, HINSTANCE instance)
{
	vk::Win32SurfaceCreateInfoKHR createInfo = vk::Win32SurfaceCreateInfoKHR()
		.setHwnd(hWnd)
		.setHinstance(instance);

	VulkanSurface surface;

	vk::SurfaceKHR surfacekhr = m_instance->createWin32SurfaceKHR(createInfo);

	auto inst = m_instance;

	std::shared_ptr<vk::SurfaceKHR> khrSur(new vk::SurfaceKHR(surfacekhr), [inst](vk::SurfaceKHR* ist)
	{
		inst->destroySurfaceKHR(*ist);
		delete ist;
	});

	surface.surface = khrSur;

	return surface;
}
#else
VulkanSurface VulkanGraphicsInstance::createSurface()
{
	return VulkanSurface();
}
#endif<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef _CONNECTIVITY_ADO_KEYS_HXX_
#include "ado/AKeys.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AKey.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
using namespace com::sun::star::container;

sdbcx::ObjectType OKeys::createObject(const ::rtl::OUString& _rName)
{
    return new OAdoKey(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OKeys::impl_refresh() throw(RuntimeException)
{
    m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OKeys::createDescriptor()
{
    return new OAdoKey(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OKeys::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
    OAdoKey* pKey = NULL;
    if ( !getImplementation( pKey, descriptor ) || pKey == NULL)
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not create key: invalid object descriptor." ),
            static_cast<XTypeProvider*>(this)
        );

    // To pass as column parameter to Key's Apppend method
    OLEVariant vOptional;
    vOptional.setNoArg();

#if OSL_DEBUG_LEVEL > 0
    KeyTypeEnum eKey =
#endif
        OAdoKey::Map2KeyRule(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))));
#if OSL_DEBUG_LEVEL > 0
    (void)eKey;
#endif

    WpADOKey aKey = pKey->getImpl();
    ::rtl::OUString sName = aKey.get_Name();
    if(!sName.getLength())
        aKey.put_Name(::rtl::OUString::createFromAscii("PrimaryKey") );

    ADOKeys* pKeys = m_aCollection;
    if ( FAILED(pKeys->Append(OLEVariant((ADOKey*)aKey),
                            adKeyPrimary, // must be every time adKeyPrimary
                            vOptional)) )
    {
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
        // just make sure that an SQLExceptionis thrown here
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not append key." ),
            static_cast<XTypeProvider*>(this)
        );
    }

    return new OAdoKey(isCaseSensitive(),m_pConnection,pKey->getImpl());
}
// -------------------------------------------------------------------------
// XDrop
void OKeys::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
    if(!m_aCollection.Delete(OLEVariant(_sElementName)))
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS sb59 (1.17.28); FILE MERGED 2006/08/08 08:28:53 sb 1.17.28.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AKeys.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:30:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef _CONNECTIVITY_ADO_KEYS_HXX_
#include "ado/AKeys.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AKey.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
using namespace com::sun::star::container;

sdbcx::ObjectType OKeys::createObject(const ::rtl::OUString& _rName)
{
    return new OAdoKey(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OKeys::impl_refresh() throw(RuntimeException)
{
    m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OKeys::createDescriptor()
{
    return new OAdoKey(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OKeys::appendObject( const ::rtl::OUString&, const Reference< XPropertySet >& descriptor )
{
    OAdoKey* pKey = NULL;
    if ( !getImplementation( pKey, descriptor ) || pKey == NULL)
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not create key: invalid object descriptor." ),
            static_cast<XTypeProvider*>(this)
        );

    // To pass as column parameter to Key's Apppend method
    OLEVariant vOptional;
    vOptional.setNoArg();

#if OSL_DEBUG_LEVEL > 0
    KeyTypeEnum eKey =
#endif
        OAdoKey::Map2KeyRule(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))));
#if OSL_DEBUG_LEVEL > 0
    (void)eKey;
#endif

    WpADOKey aKey = pKey->getImpl();
    ::rtl::OUString sName = aKey.get_Name();
    if(!sName.getLength())
        aKey.put_Name(::rtl::OUString::createFromAscii("PrimaryKey") );

    ADOKeys* pKeys = m_aCollection;
    if ( FAILED(pKeys->Append(OLEVariant((ADOKey*)aKey),
                            adKeyPrimary, // must be every time adKeyPrimary
                            vOptional)) )
    {
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
        // just make sure that an SQLExceptionis thrown here
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not append key." ),
            static_cast<XTypeProvider*>(this)
        );
    }

    return new OAdoKey(isCaseSensitive(),m_pConnection,pKey->getImpl());
}
// -------------------------------------------------------------------------
// XDrop
void OKeys::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
    if(!m_aCollection.Delete(OLEVariant(_sElementName)))
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "flow.h"
#include "ofpbuf.h"
#include "pcap-file.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  int retval;
  FILE *pcap;
  struct flow flow;
  struct ofpbuf *packet;
  uint8_t t[size+24];
  (unsigned int *)t[0] = 0xa1b2c3d4; /* magic */
  (unsigned int *)t[1] = 0x00040002; /* version */
  (unsigned int *)t[2] = 0; /* thiszone */
  (unsigned int *)t[3] = 0; /* sigfigs */
  (unsigned int *)t[4] = 65535; /* snaplen */
  (unsigned int *)t[5] = 1;     /* eth */
  for (size_t i = 0 ; i < size; i++) {
    t[24+i] = data[i];
  }
  fwrite(t, 1, sizeof(t), "test.pcap");
  pcap = fopen("test.pcap", "rb");
  if (!pcap) {
        ovs_fatal(errno, "failed to open %s for reading", "test.pcap");
  }

  retval = ovs_pcap_read_header(pcap);
  if (retval) {
        ovs_fatal(retval > 0 ? retval : 0, "reading pcap header failed");
  }

  retval = ovs_pcap_read(pcap, &packet, NULL);
  if (retval == EOF) {
    ovs_fatal(0, "unexpected end of file reading pcap file");
  } else if (retval) {
    ovs_fatal(retval, "error reading pcap file");
  }

  flow_extract(packet, NULL, &flow);
  unlink("test.pcap");
  return 0;
}
<commit_msg>Fixing clang errors<commit_after>#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "flow.h"
#include "ofpbuf.h"
#include "pcap-file.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  int retval;
  FILE *pcap;
  struct flow flow;
  struct ofpbuf *packet;
  uint8_t t[size+24];
  (unsigned int *)t[0] = 0xa1b2c3d4; /* magic */
  (unsigned int *)t[1] = 0x00040002; /* version */
  (unsigned int *)t[2] = 0; /* thiszone */
  (unsigned int *)t[3] = 0; /* sigfigs */
  (unsigned int *)t[4] = 65535; /* snaplen */
  (unsigned int *)t[5] = 1;     /* eth */
  for (size_t i = 0 ; i < size; i++) {
    t[24+i] = data[i];
  }
  pcap = fopen ("test.pcap", "wb");
  fwrite(t, 1, sizeof(t), pcap);
  fclose(pcap);
  pcap = fopen("test.pcap", "rb");
  if (!pcap) {
        ovs_fatal(errno, "failed to open %s for reading", "test.pcap");
  }

  retval = ovs_pcap_read_header(pcap);
  if (retval) {
        ovs_fatal(retval > 0 ? retval : 0, "reading pcap header failed");
  }

  retval = ovs_pcap_read(pcap, &packet, NULL);
  if (retval == EOF) {
    ovs_fatal(0, "unexpected end of file reading pcap file");
  } else if (retval) {
    ovs_fatal(retval, "error reading pcap file");
  }

  flow_extract(packet, NULL, &flow);
  unlink("test.pcap");
  return 0;
}
<|endoftext|>