<commit_before>
/*
 * From:
 * http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c
 */

#include <iostream>

#include "bpmf.h"

using namespace std;
using namespace Eigen;

/*
  We need a functor that can pretend it's const,
  but to be a good random number generator
  it needs mutable state.
*/

#ifndef __clang__
thread_local
#endif
static std::mt19937 rng;

#ifndef __clang__
thread_local
#endif
static normal_distribution<> nd;

double randn(double) {
  return nd(rng);
}

auto
nrandn(int n) -> decltype( VectorXd::NullaryExpr(n, ptr_fun(randn)) )
{
    return VectorXd::NullaryExpr(n, ptr_fun(randn));
}

/*
  Draw nn samples from a size-dimensional normal distribution
  with a specified mean and covariance
*/
MatrixXd MvNormal(MatrixXd covar, VectorXd mean, int nn = 1)
{
  int size = mean.rows(); // Dimensionality (rows)
  MatrixXd normTransform(size,size);

  LLT<MatrixXd> cholSolver(covar);
  normTransform = cholSolver.matrixL();

  auto normSamples = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
  MatrixXd samples = (normTransform * normSamples).colwise() + mean;

  return samples;
}

MatrixXd WishartUnit(int m, int df)
{
    MatrixXd c(m,m);
    c.setZero();

    for ( int i = 0; i < m; i++ ) {
        std::gamma_distribution<> gam(0.5*(df - i));
        c(i,i) = sqrt(2.0 * gam(rng));
        VectorXd r = nrandn(m-i-1).transpose();
        c.block(i,i+1,1,m-i-1) = r;
    }

    MatrixXd ret = c.transpose() * c;

#ifdef TEST_MVNORMAL
    cout << "WISHART UNIT {\n" << endl;
    cout << "  m:\n" << m << endl;
    cout << "  df:\n" << df << endl;
    cout << "  ret;\n" << ret << endl;
    cout << "  c:\n" << c << endl;
    cout << "}\n" << ret << endl;
#endif

    return ret;
}

MatrixXd Wishart(const MatrixXd &sigma, int df)
{
//  Get R, the upper triangular Cholesky factor of SIGMA.
  MatrixXd r = sigma.llt().matrixU();

//  Get AU, a sample from the unit Wishart distribution.
  MatrixXd au = WishartUnit(sigma.cols(), df);

//  Construct the matrix A = R' * AU * R.
  MatrixXd a = r.transpose() * au * r;

#ifdef TEST_MVNORMAL
    cout << "WISHART {\n" << endl;
    cout << "  sigma::\n" << sigma << endl;
    cout << "  r:\n" << r << endl;
    cout << "  au:\n" << au << endl;
    cout << "  df:\n" << df << endl;
    cout << "  a:\n" << a << endl;
    cout << "}\n" << endl;
#endif

  return a;
}

// from julia package Distributions: conjugates/normalwishart.jl
std::pair<VectorXd, MatrixXd> NormalWishart(VectorXd mu, double kappa, MatrixXd T, double nu)
{
  MatrixXd Lam = Wishart(T, nu);
  MatrixXd mu_o = MvNormal(Lam.inverse() / kappa, mu);

#ifdef TEST_MVNORMAL
    cout << "NORMAL WISHART {\n" << endl;
    cout << "  mu:\n" << mu << endl;
    cout << "  kappa:\n" << kappa << endl;
    cout << "  T:\n" << T << endl;
    cout << "  nu:\n" << nu << endl;
    cout << "  mu_o\n" << mu_o << endl;
    cout << "  Lam\n" << Lam << endl;
    cout << "}\n" << endl;
#endif

  return std::make_pair(mu_o , Lam);
}

double acc[9] = { .0 };

std::pair<VectorXd, MatrixXd> OldCondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
  int N = U.cols();
  auto start = tick();
  auto Um = U.rowwise().mean();

  // http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
  MatrixXd C = U.colwise() - Um;
  MatrixXd S = (C * C.adjoint()) / double(N - 1);
  VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
  double kappa_c = kappa + N;
  MatrixXd T_c = ( T + N * S.transpose() + (kappa * N)/(kappa + N) * (mu - Um) * ((mu - Um).transpose())).inverse();
  int nu_c = nu + N;

#ifdef TEST_MVNORMAL
  cout << "mu_c:\n" << mu_c << endl;
  cout << "kappa_c:\n" << kappa_c << endl;
  cout << "T_c:\n" << T_c << endl;
  cout << "nu_c:\n" << nu_c << endl;
#endif

  auto ret = NormalWishart(mu_c, kappa_c, T_c, nu_c);

  acc[8] += tick() - start;

  return ret;
}

// from bpmf.jl -- verified
std::pair<VectorXd, MatrixXd> CondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
         double   t[8];

  int N = U.cols();

  t[0] = tick();
  auto Um = U.rowwise().mean();
  t[1] = tick();
  acc[0] += t[1] - t[0];

  // http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
  MatrixXd C = U.colwise() - Um;
  MatrixXd S = (C * C.adjoint()) / double(N - 1);
  VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
  double kappa_c = kappa + N;
  t[2] = tick();
  acc[1] += t[2] - t[1];
  t[3] = tick();
  acc[2] += t[3] - t[2];
  t[4] = tick();
  acc[3] += t[4] - t[3];
  VectorXd mu_m = (mu - Um);
  double kappa_m = (kappa * N)/(kappa + N);
  auto X = ( T + N * S.transpose() + kappa_m * (mu_m * mu_m.transpose())); //.inverse();
  t[5] = tick();
  acc[4] += t[5] - t[4];
  MatrixXd T_c = X.inverse();
  t[6] = tick();
  acc[5] += t[6] - t[5];
  int nu_c = nu + N;

#ifdef TEST_MVNORMAL
  cout << "mu_c:\n" << mu_c << endl;
  cout << "kappa_c:\n" << kappa_c << endl;
  cout << "T_c:\n" << T_c << endl;
  cout << "nu_c:\n" << nu_c << endl;
#endif

  auto ret = NormalWishart(mu_c, kappa_c, T_c, nu_c);

  t[7] = tick();
  acc[6] += t[7] - t[6];
  acc[7] += t[7] - t[0];

  return ret;
}

#if defined(TEST_MVNORMAL) || defined (BENCH_MVNORMAL)

int main()
{

    MatrixXd U(32,32 * 1024);
    U.setOnes();

    VectorXd mu(32);
    mu.setZero();

    double kappa = 2;

    MatrixXd T(32,32);
    T.setIdentity(32,32);
    T.array() /= 4;

    int nu = 3;

    VectorXd mu_out;
    MatrixXd T_out;

#ifdef BENCH_MVNORMAL
    for(int i=0; i<300; ++i) {
        tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);
        cout << i << "\r" << flush;
    }
    cout << endl << flush;

    for(int i=0; i<7; ++i) {
        cout << i << ": " << (int)(100.0 * acc[i] / acc[7])  << endl;
    }
    cout << "total: " << acc[7] << endl;

    for(int i=0; i<300; ++i) {
        tie(mu_out, T_out) = OldCondNormalWishart(U, mu, kappa, T, nu);
        cout << i << "\r" << flush;
    }
    cout << endl << flush;

    cout << "total: " << acc[8] << endl;

#else
#if 1
    cout << "COND NORMAL WISHART\n" << endl;

    tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);

    cout << "mu_out:\n" << mu_out << endl;
    cout << "T_out:\n" << T_out << endl;

    cout << "\n-----\n\n";
#endif

#if 0
    cout << "NORMAL WISHART\n" << endl;

    tie(mu_out, T_out) = NormalWishart(mu, kappa, T, nu);
    cout << "mu_out:\n" << mu_out << endl;
    cout << "T_out:\n" << T_out << endl;

#endif

#if 0
    cout << "MVNORMAL\n" << endl;
    MatrixXd out = MvNormal(T, mu, 10);
    cout << "mu:\n" << mu << endl;
    cout << "T:\n" << T << endl;
    cout << "out:\n" << out << endl;
#endif
#endif
}

#endif
<commit_msg>sample from mvnormal using precision matrix<commit_after>
/*
 * From:
 * http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c
 */

#include <iostream>

#include "bpmf.h"

using namespace std;
using namespace Eigen;

/*
  We need a functor that can pretend it's const,
  but to be a good random number generator
  it needs mutable state.
*/

#ifndef __clang__
thread_local
#endif
static std::mt19937 rng;

#ifndef __clang__
thread_local
#endif
static normal_distribution<> nd;

double randn(double) {
  return nd(rng);
}

auto
nrandn(int n) -> decltype( VectorXd::NullaryExpr(n, ptr_fun(randn)) )
{
    return VectorXd::NullaryExpr(n, ptr_fun(randn));
}

MatrixXd MvNormal_prec(const MatrixXd & Lambda, const VectorXd & mean, int nn = 1)
{
  int size = mean.rows(); // Dimensionality (rows)

  LLT<MatrixXd> chol(Lambda);

  MatrixXd r = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
	chol.matrixU().solveInPlace(r);
  return r.colwise() + mean;
}

/*
  Draw nn samples from a size-dimensional normal distribution
  with a specified mean and covariance
*/
MatrixXd MvNormal(MatrixXd covar, VectorXd mean, int nn = 1)
{
  int size = mean.rows(); // Dimensionality (rows)
  MatrixXd normTransform(size,size);

  LLT<MatrixXd> cholSolver(covar);
  normTransform = cholSolver.matrixL();

  auto normSamples = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
  MatrixXd samples = (normTransform * normSamples).colwise() + mean;

  return samples;
}

MatrixXd WishartUnit(int m, int df)
{
    MatrixXd c(m,m);
    c.setZero();

    for ( int i = 0; i < m; i++ ) {
        std::gamma_distribution<> gam(0.5*(df - i));
        c(i,i) = sqrt(2.0 * gam(rng));
        VectorXd r = nrandn(m-i-1).transpose();
        c.block(i,i+1,1,m-i-1) = r;
    }

    MatrixXd ret = c.transpose() * c;

#ifdef TEST_MVNORMAL
    cout << "WISHART UNIT {\n" << endl;
    cout << "  m:\n" << m << endl;
    cout << "  df:\n" << df << endl;
    cout << "  ret;\n" << ret << endl;
    cout << "  c:\n" << c << endl;
    cout << "}\n" << ret << endl;
#endif

    return ret;
}

MatrixXd Wishart(const MatrixXd &sigma, int df)
{
//  Get R, the upper triangular Cholesky factor of SIGMA.
  MatrixXd r = sigma.llt().matrixU();

//  Get AU, a sample from the unit Wishart distribution.
  MatrixXd au = WishartUnit(sigma.cols(), df);

//  Construct the matrix A = R' * AU * R.
  MatrixXd a = r.transpose() * au * r;

#ifdef TEST_MVNORMAL
    cout << "WISHART {\n" << endl;
    cout << "  sigma::\n" << sigma << endl;
    cout << "  r:\n" << r << endl;
    cout << "  au:\n" << au << endl;
    cout << "  df:\n" << df << endl;
    cout << "  a:\n" << a << endl;
    cout << "}\n" << endl;
#endif

  return a;
}

// from julia package Distributions: conjugates/normalwishart.jl
std::pair<VectorXd, MatrixXd> NormalWishart(VectorXd mu, double kappa, MatrixXd T, double nu)
{
  MatrixXd Lam = Wishart(T, nu);
  MatrixXd mu_o = MvNormal_prec(Lam * kappa, mu);

#ifdef TEST_MVNORMAL
    cout << "NORMAL WISHART {\n" << endl;
    cout << "  mu:\n" << mu << endl;
    cout << "  kappa:\n" << kappa << endl;
    cout << "  T:\n" << T << endl;
    cout << "  nu:\n" << nu << endl;
    cout << "  mu_o\n" << mu_o << endl;
    cout << "  Lam\n" << Lam << endl;
    cout << "}\n" << endl;
#endif

  return std::make_pair(mu_o , Lam);
}

double acc[9] = { .0 };

std::pair<VectorXd, MatrixXd> OldCondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
  int N = U.cols();
  auto start = tick();
  auto Um = U.rowwise().mean();

  // http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
  MatrixXd C = U.colwise() - Um;
  MatrixXd S = (C * C.adjoint()) / double(N - 1);
  VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
  double kappa_c = kappa + N;
  MatrixXd T_c = ( T + N * S.transpose() + (kappa * N)/(kappa + N) * (mu - Um) * ((mu - Um).transpose())).inverse();
  int nu_c = nu + N;

#ifdef TEST_MVNORMAL
  cout << "mu_c:\n" << mu_c << endl;
  cout << "kappa_c:\n" << kappa_c << endl;
  cout << "T_c:\n" << T_c << endl;
  cout << "nu_c:\n" << nu_c << endl;
#endif

  auto ret = NormalWishart(mu_c, kappa_c, T_c, nu_c);

  acc[8] += tick() - start;

  return ret;
}

// from bpmf.jl -- verified
std::pair<VectorXd, MatrixXd> CondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
         double   t[8];

  int N = U.cols();

  t[0] = tick();
  auto Um = U.rowwise().mean();
  t[1] = tick();
  acc[0] += t[1] - t[0];

  // http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
  MatrixXd C = U.colwise() - Um;
  MatrixXd S = (C * C.adjoint()) / double(N - 1);
  VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
  double kappa_c = kappa + N;
  t[2] = tick();
  acc[1] += t[2] - t[1];
  t[3] = tick();
  acc[2] += t[3] - t[2];
  t[4] = tick();
  acc[3] += t[4] - t[3];
  VectorXd mu_m = (mu - Um);
  double kappa_m = (kappa * N)/(kappa + N);
  auto X = ( T + N * S.transpose() + kappa_m * (mu_m * mu_m.transpose())); //.inverse();
  t[5] = tick();
  acc[4] += t[5] - t[4];
  MatrixXd T_c = X.inverse();
  t[6] = tick();
  acc[5] += t[6] - t[5];
  int nu_c = nu + N;

#ifdef TEST_MVNORMAL
  cout << "mu_c:\n" << mu_c << endl;
  cout << "kappa_c:\n" << kappa_c << endl;
  cout << "T_c:\n" << T_c << endl;
  cout << "nu_c:\n" << nu_c << endl;
#endif

  auto ret = NormalWishart(mu_c, kappa_c, T_c, nu_c);

  t[7] = tick();
  acc[6] += t[7] - t[6];
  acc[7] += t[7] - t[0];

  return ret;
}

#if defined(TEST_MVNORMAL) || defined (BENCH_MVNORMAL)

int main()
{

    MatrixXd U(32,32 * 1024);
    U.setOnes();

    VectorXd mu(32);
    mu.setZero();

    double kappa = 2;

    MatrixXd T(32,32);
    T.setIdentity(32,32);
    T.array() /= 4;

    int nu = 3;

    VectorXd mu_out;
    MatrixXd T_out;

#ifdef BENCH_MVNORMAL
    for(int i=0; i<300; ++i) {
        tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);
        cout << i << "\r" << flush;
    }
    cout << endl << flush;

    for(int i=0; i<7; ++i) {
        cout << i << ": " << (int)(100.0 * acc[i] / acc[7])  << endl;
    }
    cout << "total: " << acc[7] << endl;

    for(int i=0; i<300; ++i) {
        tie(mu_out, T_out) = OldCondNormalWishart(U, mu, kappa, T, nu);
        cout << i << "\r" << flush;
    }
    cout << endl << flush;

    cout << "total: " << acc[8] << endl;

#else
#if 1
    cout << "COND NORMAL WISHART\n" << endl;

    tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);

    cout << "mu_out:\n" << mu_out << endl;
    cout << "T_out:\n" << T_out << endl;

    cout << "\n-----\n\n";
#endif

#if 0
    cout << "NORMAL WISHART\n" << endl;

    tie(mu_out, T_out) = NormalWishart(mu, kappa, T, nu);
    cout << "mu_out:\n" << mu_out << endl;
    cout << "T_out:\n" << T_out << endl;

#endif

#if 0
    cout << "MVNORMAL\n" << endl;
    MatrixXd out = MvNormal(T, mu, 10);
    cout << "mu:\n" << mu << endl;
    cout << "T:\n" << T << endl;
    cout << "out:\n" << out << endl;
#endif
#endif
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 odan
 * License: MIT License
 */
#ifndef INCLUDED_PARAMETERS_5GEN_HPP
#define INCLUDED_PARAMETERS_5GEN_HPP
#include <cstdint>

namespace RNGLib {
template<uint32_t nazo1_, uint32_t nazo2_, uint32_t nazo3_, uint32_t nazo4_, uint32_t nazo5_,
         uint32_t VCount_, uint32_t GxStat_, uint32_t Frame_>
class Parameters5Gen {
public:
    static constexpr uint32_t nazo1 = nazo1_;
    static constexpr uint32_t nazo2 = nazo2_;
    static constexpr uint32_t nazo3 = nazo3_;
    static constexpr uint32_t nazo4 = nazo4_;
    static constexpr uint32_t nazo5 = nazo5_;

    static constexpr uint32_t VCount = VCount_;
    static constexpr uint32_t GxStat = GxStat_;
    static constexpr uint32_t Frame  = Frame_;
private:
    uint32_t Timer0;
    uint32_t MAC_add1;
    uint32_t MAC_add2;
    uint32_t MAC_add3;
    uint32_t MAC_add4;
    uint32_t MAC_add5;
    uint32_t MAC_add6;
    uint32_t year;
    uint32_t month;
    uint32_t day;
    uint32_t hour;
    uint32_t minute;
    uint32_t sec;

    uint32_t key;

public:
    void set_MAC_add(uint32_t m1, uint32_t m2, uint32_t m3,
            uint32_t m4, uint32_t m5, uint32_t m6) {
        MAC_add1 = m1;
        MAC_add2 = m2;
        MAC_add3 = m3;
        MAC_add4 = m4;
        MAC_add5 = m5;
        MAC_add6 = m6;
    }

    void set_year(uint32_t yy) { year = yy; }
    void set_month(uint32_t mm) { month = mm; }
    void set_day(uint32_t dd) { day = dd; }

    void set_hour(uint32_t hh) { hour = hh; }
    void set_minute(uint32_t mi) { minute = mi; }
    void set_sec(uint32_t se) { sec = se; }

    void set_key(uint32_t key_) { key = key_; }
    void set_Timer0(uint32_t tt) { Timer0 = tt; }

    uint32_t get_MAC_add1() const { return MAC_add1; }
    uint32_t get_MAC_add2() const { return MAC_add2; }
    uint32_t get_MAC_add3() const { return MAC_add3; }
    uint32_t get_MAC_add4() const { return MAC_add4; }
    uint32_t get_MAC_add5() const { return MAC_add5; }
    uint32_t get_MAC_add6() const { return MAC_add6; }

    uint32_t get_year() const { return year; }
    uint32_t get_month() const { return month; }
    uint32_t get_day() const { return day; }
    uint32_t get_hour() const { return hour; }
    uint32_t get_minute() const { return minute; }
    uint32_t get_sec() const { return sec; }
    uint32_t get_week() const {
        return  ((2000+year-(month<3)) + (2000+year-(month<3))/4 -
            (2000+year-(month<3))/100 + (2000+year-(month<3))/400 +
            (13*(month+(month<3)*12)+8)/5 + day) % 7;
    }

    uint32_t get_nazo1() const { return nazo1; }
    uint32_t get_nazo2() const { return nazo2; }
    uint32_t get_nazo3() const { return nazo3; }
    uint32_t get_nazo4() const { return nazo4; }
    uint32_t get_nazo5() const { return nazo5; }

    uint32_t get_VCount() const { return VCount; }
    uint32_t get_Timer0() const { return Timer0; }
    uint32_t get_GxStat() const { return GxStat; }
    uint32_t get_Frame() const { return Frame; }
    uint32_t get_key() const { return key; }

};
typedef Parameters5Gen<0x2215f10, 0x221600c, 0x221600c, 0x2216058, 0x2216058, 0x60, 0x6000000, 6> ParametersB1Ja;
typedef Parameters5Gen<0x2215f30, 0x221602c, 0x221602c, 0x2216078, 0x2216078, 0x60, 0x6000000, 6> ParametersW1Ja;

} // end RNGLib

#endif
<commit_msg>Parameters5GenのテンプレートパラメータでTimer0の範囲を指定出来るように<commit_after>/*
 * Copyright (c) 2014 odan
 * License: MIT License
 */
#ifndef INCLUDED_PARAMETERS_5GEN_HPP
#define INCLUDED_PARAMETERS_5GEN_HPP
#include <cstdint>

namespace RNGLib {
template<uint32_t nazo1_, uint32_t nazo2_, uint32_t nazo3_, uint32_t nazo4_, uint32_t nazo5_,
         uint32_t VCount_, uint32_t GxStat_, uint32_t Frame_, uint32_t Timer0Min_, uint32_t Timer0Max_>
class Parameters5Gen {
public:
    static constexpr uint32_t nazo1 = nazo1_;
    static constexpr uint32_t nazo2 = nazo2_;
    static constexpr uint32_t nazo3 = nazo3_;
    static constexpr uint32_t nazo4 = nazo4_;
    static constexpr uint32_t nazo5 = nazo5_;

    static constexpr uint32_t VCount = VCount_;
    static constexpr uint32_t GxStat = GxStat_;
    static constexpr uint32_t Frame  = Frame_;
    static constexpr uint32_t Timer0Min = Timer0Min_;
    static constexpr uint32_t Timer0Max = Timer0Max_;
private:
    uint32_t Timer0 = Timer0Min_;
    uint32_t MAC_add1;
    uint32_t MAC_add2;
    uint32_t MAC_add3;
    uint32_t MAC_add4;
    uint32_t MAC_add5;
    uint32_t MAC_add6;
    uint32_t year;
    uint32_t month;
    uint32_t day;
    uint32_t hour;
    uint32_t minute;
    uint32_t sec;

    uint32_t key = 0x2fff;

public:
    void set_MAC_add(uint32_t m1, uint32_t m2, uint32_t m3,
            uint32_t m4, uint32_t m5, uint32_t m6) {
        MAC_add1 = m1;
        MAC_add2 = m2;
        MAC_add3 = m3;
        MAC_add4 = m4;
        MAC_add5 = m5;
        MAC_add6 = m6;
    }

    void set_year(uint32_t yy) { year = yy; }
    void set_month(uint32_t mm) { month = mm; }
    void set_day(uint32_t dd) { day = dd; }

    void set_hour(uint32_t hh) { hour = hh; }
    void set_minute(uint32_t mi) { minute = mi; }
    void set_sec(uint32_t se) { sec = se; }

    void set_key(uint32_t key_) { key = key_; }
    void set_Timer0(uint32_t tt) { Timer0 = tt; }

    uint32_t get_MAC_add1() const { return MAC_add1; }
    uint32_t get_MAC_add2() const { return MAC_add2; }
    uint32_t get_MAC_add3() const { return MAC_add3; }
    uint32_t get_MAC_add4() const { return MAC_add4; }
    uint32_t get_MAC_add5() const { return MAC_add5; }
    uint32_t get_MAC_add6() const { return MAC_add6; }

    uint32_t get_year() const { return year; }
    uint32_t get_month() const { return month; }
    uint32_t get_day() const { return day; }
    uint32_t get_hour() const { return hour; }
    uint32_t get_minute() const { return minute; }
    uint32_t get_sec() const { return sec; }
    uint32_t get_week() const {
        return  ((2000+year-(month<3)) + (2000+year-(month<3))/4 -
            (2000+year-(month<3))/100 + (2000+year-(month<3))/400 +
            (13*(month+(month<3)*12)+8)/5 + day) % 7;
    }

    uint32_t get_nazo1() const { return nazo1; }
    uint32_t get_nazo2() const { return nazo2; }
    uint32_t get_nazo3() const { return nazo3; }
    uint32_t get_nazo4() const { return nazo4; }
    uint32_t get_nazo5() const { return nazo5; }

    uint32_t get_VCount() const { return VCount; }
    uint32_t get_Timer0() const { return Timer0; }
    uint32_t get_GxStat() const { return GxStat; }
    uint32_t get_Frame() const { return Frame; }
    uint32_t get_key() const { return key; }

    uint32_t get_Timer0Min() const { return Timer0Min; }
    uint32_t get_Timer0Max() const { return Timer0Max; }

};
typedef Parameters5Gen<0x2215f10, 0x221600c, 0x221600c, 0x2216058, 0x2216058, 0x60, 0x6000000, 6, 0xc79, 0xc7a> ParametersB1Ja;
typedef Parameters5Gen<0x2215f30, 0x221602c, 0x221602c, 0x2216078, 0x2216078, 0x60, 0x6000000, 6, 0xc68, 0xc69> ParametersW1Ja;

} // end RNGLib

#endif
<|endoftext|>


<commit_before>/*
    Copyright (c) 2010 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "dbconfig.h"

#include "dbconfigmysql.h"
#include "dbconfigmysqlembedded.h"
#include "dbconfigpostgresql.h"
#include "dbconfigsqlite.h"

#include "../../libs/xdgbasedirs_p.h"

using namespace Akonadi;

//TODO: make me Q_GLOBAL_STATIC
static DbConfig *s_DbConfigInstance = 0;

DbConfig::DbConfig()
{
  const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );
  QSettings settings( serverConfigFile, QSettings::IniFormat );

  mSizeThreshold = 4096;
  const QVariant value = settings.value( QLatin1String( "General/SizeThreshold" ), mSizeThreshold );
  if ( value.canConvert<qint64>() )
    mSizeThreshold = value.value<qint64>();
  else
    mSizeThreshold = 0;

  if ( mSizeThreshold < 0 )
    mSizeThreshold = 0;

  mUseExternalPayloadFile = false;
  mUseExternalPayloadFile = settings.value( QLatin1String( "General/ExternalPayload" ), mUseExternalPayloadFile ).toBool();
}

DbConfig::~DbConfig()
{
}

DbConfig* DbConfig::configuredDatabase()
{
  if ( !s_DbConfigInstance ) {
    const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );
    QSettings settings( serverConfigFile, QSettings::IniFormat );

    // determine driver to use
    const QString defaultDriver = QLatin1String( "QMYSQL" );
    QString driverName = settings.value( QLatin1String( "General/Driver" ), defaultDriver ).toString();
    if ( driverName.isEmpty() )
      driverName = defaultDriver;

    if ( driverName == QLatin1String( "QMYSQL" ) )
      s_DbConfigInstance = new DbConfigMysql;
    else if ( driverName == QLatin1String( "QMYSQL_EMBEDDED" ) )
      s_DbConfigInstance = new DbConfigMysqlEmbedded;
    else if ( driverName == QLatin1String( "QSQLITE" ) )
      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Default );
    else if ( driverName == QLatin1String( "QSQLITE3" ) )
      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Custom );
    else if ( driverName == QLatin1String( "QPSQL" ) )
      s_DbConfigInstance = new DbConfigPostgresql;
    else
      qDebug( "No sql driver defined!" );
  }

  return s_DbConfigInstance;
}

void DbConfig::startInternalServer()
{
  // do nothing
}

void DbConfig::stopInternalServer()
{
  // do nothing
}

qint64 DbConfig::sizeThreshold() const
{
  return mSizeThreshold;
}

bool DbConfig::useExternalPayloadFile() const
{
  return mUseExternalPayloadFile;
}
<commit_msg>enable fs payload store by default<commit_after>/*
    Copyright (c) 2010 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "dbconfig.h"

#include "dbconfigmysql.h"
#include "dbconfigmysqlembedded.h"
#include "dbconfigpostgresql.h"
#include "dbconfigsqlite.h"

#include <akdebug.h>
#include <libs/xdgbasedirs_p.h>

using namespace Akonadi;

//TODO: make me Q_GLOBAL_STATIC
static DbConfig *s_DbConfigInstance = 0;

DbConfig::DbConfig()
{
  const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );
  QSettings settings( serverConfigFile, QSettings::IniFormat );

  mSizeThreshold = 4096;
  const QVariant value = settings.value( QLatin1String( "General/SizeThreshold" ), mSizeThreshold );
  if ( value.canConvert<qint64>() )
    mSizeThreshold = value.value<qint64>();
  else
    mSizeThreshold = 0;

  if ( mSizeThreshold < 0 )
    mSizeThreshold = 0;

  mUseExternalPayloadFile = true;
  mUseExternalPayloadFile = settings.value( QLatin1String( "General/ExternalPayload" ), mUseExternalPayloadFile ).toBool();
}

DbConfig::~DbConfig()
{
}

DbConfig* DbConfig::configuredDatabase()
{
  if ( !s_DbConfigInstance ) {
    const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );
    QSettings settings( serverConfigFile, QSettings::IniFormat );

    // determine driver to use
    const QString defaultDriver = QLatin1String( "QMYSQL" );
    QString driverName = settings.value( QLatin1String( "General/Driver" ), defaultDriver ).toString();
    if ( driverName.isEmpty() )
      driverName = defaultDriver;

    if ( driverName == QLatin1String( "QMYSQL" ) )
      s_DbConfigInstance = new DbConfigMysql;
    else if ( driverName == QLatin1String( "QMYSQL_EMBEDDED" ) )
      s_DbConfigInstance = new DbConfigMysqlEmbedded;
    else if ( driverName == QLatin1String( "QSQLITE" ) )
      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Default );
    else if ( driverName == QLatin1String( "QSQLITE3" ) )
      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Custom );
    else if ( driverName == QLatin1String( "QPSQL" ) )
      s_DbConfigInstance = new DbConfigPostgresql;
    else
      akFatal() << "Unknown database driver: " << driverName;
  }

  return s_DbConfigInstance;
}

void DbConfig::startInternalServer()
{
  // do nothing
}

void DbConfig::stopInternalServer()
{
  // do nothing
}

qint64 DbConfig::sizeThreshold() const
{
  return mSizeThreshold;
}

bool DbConfig::useExternalPayloadFile() const
{
  return mUseExternalPayloadFile;
}
<|endoftext|>


<commit_before>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>

int main (void) {
    return 0;
}

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {
    typedef unsigned char BYTE;

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        // We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci)
        //int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line)
        //int totalLoci = size/(272*2);
        //std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0));
        //std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0));
        //long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates
        //unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;
        unsigned long long int lociPerThread = numLoci;

        //std::thread t;
        //std::thread t[numThreads];
        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            unsigned long long firstLocus = (unsigned long long) threadRunning * lociPerThread;
            unsigned long long finishingLocus = ((unsigned long long) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;

            std::cout << "Got to the function call" << std::endl;
            //calcPWPforRange(firstLocus, finishingLocus, 272, readCounts, pwp, weightings);
            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
            //std::thread t = std::thread(calcPWPforRange, firstLocus, finishingLocus, std::thread(readCounts), std::thread(pwpThreads[threadRunning]), std::thread(weightingsThreads[threadRunning]));
        }

        //t.join();
        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
        }

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0));
        std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0));
        for (int element = 0; element < 272; element++) {
            for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) {
                for (int threadVector = 0; threadVector <= numThreads; threadVector++) {
                    weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement];
                    pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement];
                }
            }
        }

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;

     //usage: calcPWPforRange(0, 1000000, readCounts) // where readCounts is a vector with all the read count data
     //this function will return both the pwp calculations for the matrix as well as the weightings, which will later
     //be summed across all threads

     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
     if (locus % 100000 == 0) {
     std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
     }

     int coverages[numIndividuals];
     double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

     for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
     unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
     unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

     //std::cout << "\tTrying to access readCounts[" << minorIndex << "]" << ". locus: " << locus << ". numIndividuals: " << numIndividuals << ". tortoise: " << tortoise << std::endl;

     coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
     //std::cout << "\t\tCalced coverage in line 232" << std::endl;
     //std::cout << coverages[tortoise] << std::endl;

     //std::cout << "Total coverage for tortoise " << tortoise << " at locus " << locus+1 << ": " << coverages[tortoise] << std::endl;

     if ( coverages[tortoise] > 0 ) {
     //std::cout << "Made it to line 222 for locus " << locus << std::endl;
     majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
     //std::cout << "Major allele frequency for individual " << tortoise << " at locus " << locus << ": " << majorAlleleFreqs[tortoise] << std::endl;
     //std::cout << "\t\t\tCalced majorAlleleFreqs[" << tortoise << "] in line 239" << std::endl;
     if (coverages[tortoise] > 1) {
     unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
     //std::cout << "\t\t\t\tCalced weightings in line 245 for tortoise[" << tortoise << "]" << std::endl;

     threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
     //std::cout << "\t\t\t\t\tCalced pwp in line 247 for tortoise[" << tortoise << "]" << std::endl;
     //std::cout << "Locus self weighting for individual " << tortoise << " at locus: " << locus << ": " << locusWeighting << ". Locus self PWP: " << double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]))) / (double((coverages[tortoise])-1.0)) << std::endl;
     //std::cout << "\tmajorAlleleFreq: " << majorAlleleFreqs[tortoise] << ". Coverages: " << double(coverages[tortoise]) << ". readCounts: " << double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]) << std::endl;
     //std::cout << "PWP for self:" << pwp[tortoise][tortoise] << std::endl;
     //std::cout << "Made it to line 233 for locus " << locus << ". Weightings = " << weightings[tortoise][tortoise] << ". PWP = " << pwp[tortoise][tortoise] << std::endl;
     }

     for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
     if (coverages[comparisonTortoise] > 0) {

     //std::cout << "Coverages for the two comparison individuals: " << std::to_string((double)coverages[tortoise]) << " and " << std::to_string((double)coverages[comparisonTortoise]) << std::endl;
     //std::cout << "Major allele freqs for the two comparison individuals: " << std::to_string(majorAlleleFreqs[tortoise]) << " and " << std::to_string(majorAlleleFreqs[comparisonTortoise]) << std::endl;
     double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
     threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
     //std::cout << "locusDiffPWP: " << (double)locusWeighting * ((double)majorAlleleFreqs[tortoise] * (1-(double)majorAlleleFreqs[comparisonTortoise]) + (double)majorAlleleFreqs[comparisonTortoise] * (1-(double)majorAlleleFreqs[tortoise])) << std::endl;
     threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
     //std::cout << "\t\t\t\t\t\tCalced pwp for tortoise[" << tortoise << "] and comparisonTortoise[" << comparisonTortoise << "]" << std::endl;
     //std::cout << pwp[tortoise][comparisonTortoise] << std::endl;
     //std::cout << "Cumulative weightings = " << weightings[tortoise][comparisonTortoise] << ". Cumulative PWP = " << pwp[tortoise][comparisonTortoise] << std::endl;
     }
     }
     }
     }
     delete[] majorAlleleFreqs; // Needed to avoid memory leaks
     //delete[] coverages; // Since that locus is done, and this variable holds per-locus coverages, we can nuke the coverages to start anew
     }
    return 0;

}
<commit_msg>Minor changes<commit_after>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>

int main (void) {
    return 0;
}

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        // We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci)
        //int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line)
        //int totalLoci = size/(272*2);
        //std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0));
        //std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0));
        //long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates
        //unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;
        unsigned long long int lociPerThread = numLoci;

        //std::thread t;
        //std::thread t[numThreads];
        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            unsigned long long firstLocus = (unsigned long long) threadRunning * lociPerThread;
            unsigned long long finishingLocus = ((unsigned long long) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;

            std::cout << "Got to the function call" << std::endl;
            //calcPWPforRange(firstLocus, finishingLocus, 272, readCounts, pwp, weightings);
            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
            //std::thread t = std::thread(calcPWPforRange, firstLocus, finishingLocus, std::thread(readCounts), std::thread(pwpThreads[threadRunning]), std::thread(weightingsThreads[threadRunning]));
        }

        //t.join();
        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
        }

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0));
        std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0));
        for (int element = 0; element < 272; element++) {
            for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) {
                for (int threadVector = 0; threadVector <= numThreads; threadVector++) {
                    weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement];
                    pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement];
                }
            }
        }

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
    /*

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;

     //usage: calcPWPforRange(0, 1000000, readCounts) // where readCounts is a vector with all the read count data
     //this function will return both the pwp calculations for the matrix as well as the weightings, which will later
     //be summed across all threads

     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
     if (locus % 100000 == 0) {
     std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
     }

     int coverages[numIndividuals];
     double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

     for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
     unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
     unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

     //std::cout << "\tTrying to access readCounts[" << minorIndex << "]" << ". locus: " << locus << ". numIndividuals: " << numIndividuals << ". tortoise: " << tortoise << std::endl;

     coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
     //std::cout << "\t\tCalced coverage in line 232" << std::endl;
     //std::cout << coverages[tortoise] << std::endl;

     //std::cout << "Total coverage for tortoise " << tortoise << " at locus " << locus+1 << ": " << coverages[tortoise] << std::endl;

     if ( coverages[tortoise] > 0 ) {
     //std::cout << "Made it to line 222 for locus " << locus << std::endl;
     majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
     //std::cout << "Major allele frequency for individual " << tortoise << " at locus " << locus << ": " << majorAlleleFreqs[tortoise] << std::endl;
     //std::cout << "\t\t\tCalced majorAlleleFreqs[" << tortoise << "] in line 239" << std::endl;
     if (coverages[tortoise] > 1) {
     unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
     //std::cout << "\t\t\t\tCalced weightings in line 245 for tortoise[" << tortoise << "]" << std::endl;

     threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
     //std::cout << "\t\t\t\t\tCalced pwp in line 247 for tortoise[" << tortoise << "]" << std::endl;
     //std::cout << "Locus self weighting for individual " << tortoise << " at locus: " << locus << ": " << locusWeighting << ". Locus self PWP: " << double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]))) / (double((coverages[tortoise])-1.0)) << std::endl;
     //std::cout << "\tmajorAlleleFreq: " << majorAlleleFreqs[tortoise] << ". Coverages: " << double(coverages[tortoise]) << ". readCounts: " << double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]) << std::endl;
     //std::cout << "PWP for self:" << pwp[tortoise][tortoise] << std::endl;
     //std::cout << "Made it to line 233 for locus " << locus << ". Weightings = " << weightings[tortoise][tortoise] << ". PWP = " << pwp[tortoise][tortoise] << std::endl;
     }

     for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
     if (coverages[comparisonTortoise] > 0) {

     //std::cout << "Coverages for the two comparison individuals: " << std::to_string((double)coverages[tortoise]) << " and " << std::to_string((double)coverages[comparisonTortoise]) << std::endl;
     //std::cout << "Major allele freqs for the two comparison individuals: " << std::to_string(majorAlleleFreqs[tortoise]) << " and " << std::to_string(majorAlleleFreqs[comparisonTortoise]) << std::endl;
     double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
     threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
     //std::cout << "locusDiffPWP: " << (double)locusWeighting * ((double)majorAlleleFreqs[tortoise] * (1-(double)majorAlleleFreqs[comparisonTortoise]) + (double)majorAlleleFreqs[comparisonTortoise] * (1-(double)majorAlleleFreqs[tortoise])) << std::endl;
     threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
     //std::cout << "\t\t\t\t\t\tCalced pwp for tortoise[" << tortoise << "] and comparisonTortoise[" << comparisonTortoise << "]" << std::endl;
     //std::cout << pwp[tortoise][comparisonTortoise] << std::endl;
     //std::cout << "Cumulative weightings = " << weightings[tortoise][comparisonTortoise] << ". Cumulative PWP = " << pwp[tortoise][comparisonTortoise] << std::endl;
     }
     }
     }
     }
     delete[] majorAlleleFreqs; // Needed to avoid memory leaks
     //delete[] coverages; // Since that locus is done, and this variable holds per-locus coverages, we can nuke the coverages to start anew
     }
     */
    return 0;

}
<|endoftext|>


<commit_before>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
 *

 *
 * @Version:		1.0.0
 * @Author:			Achim Grolimund (achim.grolimund@hf-ict.info)
 * @Date:			01.1.2017
 *
 * @Description:

 *
 * Beispiel:

 *
 * Anmerkung:
 *
 *
 *==============================================[ EOF RDM ]=============================================================================*/

#define DEBUG
#include <bits/stdc++.h>

#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"

using namespace std;

class Node
{
	public:
		Node * left;
		Node * right;
		int value;
		Node( int value);
};

Node::Node(int value)  : value(value), left(0), right(0){
}

class BinaryTree
{
	private:
		Node * root;
		void insert(int v, Node * n);
	public:
		BinaryTree();
		void insert(int v);
		int height();
};

void BinaryTree::insert(int v, Node *n)
{
	if (v < n->value) {
		//left
		if (n->left == 0) {
			n->left = new Node(v);
		}
	}else{
		//right
		if (n->right == 0) {
			n->right = new Node(v);
		}else{
			insert(v,n->right);
		}
	}
}

void BinaryTree::insert(int v){
	if (root == 0) {
		root = new Node(v);
	}else{
		insert(v,root);
	}
}

int BinaryTree::height()
{

}

int main()
{
	BinaryTree bt;
	int values[] {50,25,75,14,7,19,63,89,99,79};

	for(int &x : values){
		bt.insert(x);
	}

	return 0;
}

<commit_msg>Update<commit_after>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
 *

 *
 * @Version:		1.0.0
 * @Author:			Achim Grolimund (achim.grolimund@hf-ict.info)
 * @Date:			01.1.2017
 *
 * @Description:

 *
 * Beispiel:

 *
 * Anmerkung:
 *
 *
 *==============================================[ EOF RDM ]=============================================================================*/

#define DEBUG
#include <bits/stdc++.h>

#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"

using namespace std;

class Node {
public:
  Node * left;
  Node * right;
  int value;
  Node(int value);
};

Node::Node(int value) : left(0), right(0), value(value) {
}

class BinaryTree {
private:
  Node * root;
  void insert(int v, Node * n);
  void postOrder(Node * n);
public:
  BinaryTree();
  void insert(int v);
  int height(Node *n, int &ch, int &max);
  void postOrder();
};

BinaryTree::BinaryTree() : root(0) {
}

void BinaryTree::insert(int v, Node * n) {
  if (v < n->value) {
	// left
	if (n->left == 0) {
	  n->left = new Node(v);
	} else {
	  insert(v, n->left);
	}
  } else {
	// right
	if (n->right == 0) {
	  n->right = new Node(v);
	} else {
	  insert(v, n->right);
	}
  }
}

void BinaryTree::postOrder(Node *n)
{
	if(n != 0){
		postOrder(n->left);
		postOrder(n->right);
		cout<< n->value<<endl;
	}
}
void BinaryTree::postOrder()
{
	postOrder(root);
}

void BinaryTree::insert(int v) {
  if (root == 0) {
	root = new Node(v);
  } else {
	insert(v, root);
  }
}

int BinaryTree::height(Node *n, int &ch, int &max)
{
	return 0;
}

int main() {
  BinaryTree bt;
  int values[] = {50, 25, 75, 14, 7, 19, 63, 89, 99, 79};
  for (int &x : values) {
	bt.insert(x);
  }

bt.postOrder();
  return 0;
}

<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(c), c is unique count of pattern and words

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int cnt = str.empty() ? 0 : 1;
        for (const auto& c : str) {
            if (c == ' ') {
                ++cnt;
            }
        }
        if (pattern.size() != cnt) {
            return false;
        }

        unordered_map<string, char> w2p;
        unordered_map<char, string> p2w;
        int i = 0, j = 0;
        for (const auto& p : pattern) {
            j = str.find(" ", i);
            if (j == string::npos) {
                j = str.length();
            }
            const string word = str.substr(i, j - i);
            if (!w2p.count(word) && !p2w.count(p)) {
                w2p[word] = p;
                p2w[p] = word;
            } else if (w2p[word] != p) {
                return false;
            }
            i = j + 1;
        }
        return true;
    }
};
<commit_msg>Update word-pattern.cpp<commit_after>// Time:  O(n)
// Space: O(c), c is unique count of pattern and words

// Time:  O(n)
// Space: O(c), c is count of pattern

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int cnt = str.empty() ? 0 : 1;
        for (const auto& c : str) {
            if (c == ' ') {
                ++cnt;
            }
        }
        if (pattern.size() != cnt) {
            return false;
        }

        unordered_map<string, char> w2p;
        unordered_map<char, string> p2w;
        int i = 0, j = 0;
        for (const auto& p : pattern) {
            j = str.find(" ", i);
            if (j == string::npos) {
                j = str.length();
            }
            const string w = str.substr(i, j - i);
            if (!w2p.count(w) && !p2w.count(p)) {
                w2p[w] = p;
                p2w[p] = w;
            } else if (w2p[w] != p) {
                return false;
            }
            i = j + 1;
        }
        return true;
    }
};
<|endoftext|>


<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file HuginInterface.cpp Interface to Hugin panorama stitching software
//

// includes
#include "StdAfx.h"
#include "HuginInterface.hpp"
#include "Path.hpp"
#include "Process.hpp"

HuginInterface::HuginInterface(const CString& cszInstallPath)
:m_cszInstallPath(cszInstallPath)
{
   if (cszInstallPath.IsEmpty())
      Detect();
}

void HuginInterface::RunUI(const std::vector<CString>& vecImageFilenames)
{
   CString cszCommandLine = Path::Combine(m_cszInstallPath, _T("hugin.exe"));

   CString cszFilename;
   for (size_t i=0,iMax=vecImageFilenames.size(); i<iMax; i++)
   {
      cszFilename = vecImageFilenames[i];
      cszFilename.TrimLeft(_T('\"'));
      cszFilename.TrimRight(_T('\"'));

      cszCommandLine += _T(" \"");
      cszCommandLine += cszFilename;
      cszCommandLine += _T("\"");
   }

   Process process;
   process.WorkingDirectory(m_cszInstallPath);
   bool bRet = process.Create(cszCommandLine);

   ATLASSERT(true == bRet); bRet;
}

void HuginInterface::RunStitcher(const CString& cszPtoScript, const CString& cszOutputFile)
{
   CString cszCommandLine = Path::Combine(m_cszInstallPath, _T("nona.exe"));

   CString cszFilename(cszOutputFile);
   cszFilename.TrimLeft(_T('\"'));
   cszFilename.TrimRight(_T('\"'));

   cszCommandLine += _T("-o \"");
   cszCommandLine += cszFilename;
   cszCommandLine += _T("\" ");

   cszFilename = cszPtoScript;
   cszFilename.TrimLeft(_T('\"'));
   cszFilename.TrimRight(_T('\"'));

   cszCommandLine += _T("\"");
   cszCommandLine += cszFilename;
   cszCommandLine += _T("\"");

   Process process;
   process.WorkingDirectory(m_cszInstallPath);
   bool bRet = process.Create(cszCommandLine);

   ATLASSERT(true == bRet); bRet;
}

void HuginInterface::Detect()
{
   LPCTSTR apszRegKeys[] =
   {
      _T("Software\\hugin"), _T("startDir"),
   };

   CString cszInstallPath;
   for (int i=0, iMax=sizeof(apszRegKeys)/sizeof(*apszRegKeys); i<iMax; i+=2)
   {
      CRegKey regKey;
      if (ERROR_SUCCESS != regKey.Open(HKEY_CURRENT_USER, apszRegKeys[i+0], KEY_READ))
         continue;

      DWORD dwLength = MAX_PATH;
      LPTSTR pszBuffer = cszInstallPath.GetBuffer(MAX_PATH);
      regKey.QueryStringValue(apszRegKeys[i+1], pszBuffer, &dwLength);
      cszInstallPath.ReleaseBuffer();

      if (!cszInstallPath.IsEmpty())
      {
         if (cszInstallPath.Right(1) != _T("\\"))
            cszInstallPath += _T("\\");

         break;
      }
   }

   if (!cszInstallPath.IsEmpty())
      m_cszInstallPath = cszInstallPath;
}
<commit_msg>fixed Hugin path detection; Hugin 2015.0 doesn't write "startDir" key anymore, it seems<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file HuginInterface.cpp Interface to Hugin panorama stitching software
//

// includes
#include "StdAfx.h"
#include "HuginInterface.hpp"
#include "Path.hpp"
#include "Process.hpp"
#include <array>
#include <tuple>

HuginInterface::HuginInterface(const CString& cszInstallPath)
:m_cszInstallPath(cszInstallPath)
{
   if (cszInstallPath.IsEmpty())
      Detect();
}

void HuginInterface::RunUI(const std::vector<CString>& vecImageFilenames)
{
   CString cszCommandLine = Path::Combine(m_cszInstallPath, _T("hugin.exe"));

   CString cszFilename;
   for (size_t i=0,iMax=vecImageFilenames.size(); i<iMax; i++)
   {
      cszFilename = vecImageFilenames[i];
      cszFilename.TrimLeft(_T('\"'));
      cszFilename.TrimRight(_T('\"'));

      cszCommandLine += _T(" \"");
      cszCommandLine += cszFilename;
      cszCommandLine += _T("\"");
   }

   Process process;
   process.WorkingDirectory(m_cszInstallPath);
   bool bRet = process.Create(cszCommandLine);

   ATLASSERT(true == bRet); bRet;
}

void HuginInterface::RunStitcher(const CString& cszPtoScript, const CString& cszOutputFile)
{
   CString cszCommandLine = Path::Combine(m_cszInstallPath, _T("nona.exe"));

   CString cszFilename(cszOutputFile);
   cszFilename.TrimLeft(_T('\"'));
   cszFilename.TrimRight(_T('\"'));

   cszCommandLine += _T("-o \"");
   cszCommandLine += cszFilename;
   cszCommandLine += _T("\" ");

   cszFilename = cszPtoScript;
   cszFilename.TrimLeft(_T('\"'));
   cszFilename.TrimRight(_T('\"'));

   cszCommandLine += _T("\"");
   cszCommandLine += cszFilename;
   cszCommandLine += _T("\"");

   Process process;
   process.WorkingDirectory(m_cszInstallPath);
   bool bRet = process.Create(cszCommandLine);

   ATLASSERT(true == bRet); bRet;
}

void HuginInterface::Detect()
{
   std::array<std::tuple<HKEY, LPCTSTR, LPCTSTR>, 2> regKeys
   {
      std::tuple<HKEY, LPCTSTR, LPCTSTR> {
         HKEY_CURRENT_USER, _T("Software\\hugin"), _T("startDir")
      },
      std::tuple<HKEY, LPCTSTR, LPCTSTR> {
         HKEY_LOCAL_MACHINE, _T("Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hugin"), _T("DisplayIcon")
      }
      //HKEY_CLASSES_ROOT\Applications\hugin.exe\shell\open\command
   };

   CString cszInstallPath;
   for (int i=0, iMax=regKeys.size(); i<iMax; i++)
   {
      CRegKey regKey;
      if (ERROR_SUCCESS != regKey.Open(std::get<0>(regKeys[i]), std::get<1>(regKeys[i]), KEY_READ))
         continue;

      DWORD dwLength = MAX_PATH;
      LPTSTR pszBuffer = cszInstallPath.GetBuffer(MAX_PATH);
      regKey.QueryStringValue(std::get<2>(regKeys[i]), pszBuffer, &dwLength);
      cszInstallPath.ReleaseBuffer();

      if (!cszInstallPath.IsEmpty())
      {
         CString cszInstallPathLower(cszInstallPath);
         cszInstallPathLower.MakeLower();

         if (cszInstallPathLower.Find(_T(".exe")) != -1)
            cszInstallPath = Path(cszInstallPath).DirectoryName();

         Path::AddEndingBackslash(cszInstallPath);

         break;
      }
   }

   if (!cszInstallPath.IsEmpty())
      m_cszInstallPath = cszInstallPath;
}
<|endoftext|>


<commit_before>
//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// abstract_optimizer.cpp
//
// Identification: /peloton/src/optimizer/abstract_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/abstract_optimizer.h"

namespace peloton {
namespace optimizer {

//===--------------------------------------------------------------------===//
// Abstract Optimizer
//===--------------------------------------------------------------------===//
AbstractOptimizer::AbstractOptimizer(){};

AbstractOptimizer::~AbstractOptimizer(){};

AbstractOptimizer &AbstractOptimizer::GetInstance() {
  thread_local static AbstractOptimizer abstract_optimizer;
  return abstract_optimizer;
}

std::shared_ptr<planner::AbstractPlan> AbstractOptimizer::GeneratePlan(
    std::shared_ptr<std::string> plan_tree) {
  std::cout << "Just a placeholder for plan tree" << plan_tree << std::endl;
  return false;
}

bool AbstractOptimizer::ShouldOptimize(std::string parse) {
  std::cout << "Just a placeholder for prase string " << parse << std::endl;
  return false;
}

std::shared_ptr<std::string> AbstractOptimizer::TransformParseTreeToOptimizerPlanTree(
    std::string parse) {
  std::cout << "Just a placeholder for prase string " << parse << std::endl;
  return NULL;
}

} // namespace optimizer
} // namespace peloton
<commit_msg>Modification to pass validation<commit_after>
//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// abstract_optimizer.cpp
//
// Identification: /peloton/src/optimizer/abstract_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/abstract_optimizer.h"

namespace peloton {
namespace optimizer {

//===--------------------------------------------------------------------===//
// Abstract Optimizer
//===--------------------------------------------------------------------===//
AbstractOptimizer::AbstractOptimizer(){};

AbstractOptimizer::~AbstractOptimizer(){};

AbstractOptimizer &AbstractOptimizer::GetInstance() {
  thread_local static AbstractOptimizer abstract_optimizer;
  return abstract_optimizer;
}

std::shared_ptr<planner::AbstractPlan> AbstractOptimizer::GeneratePlan(
    std::shared_ptr<std::string> plan_tree) {
  std::cout << "Just a placeholder for plan tree" << plan_tree << std::endl;
  return false;
}

bool AbstractOptimizer::ShouldOptimize(std::string parse) {
  LOG_INFO("Just a placeholder for parse string %s", parse);
  return false;
}

std::shared_ptr<std::string> AbstractOptimizer::TransformParseTreeToOptimizerPlanTree(
    std::string parse) {
	LOG_INFO("Just a placeholder for parse string %s", parse);
	return NULL;
}

} // namespace optimizer
} // namespace peloton
<|endoftext|>


<commit_before>#ifndef ___INANITY_GUI_TYPES_HPP___
#define ___INANITY_GUI_TYPES_HPP___

#include "gui.hpp"
#include "../inanity-math.hpp"
#include "../input/Key.hpp"
#include "../input/Event.hpp"

BEGIN_INANITY_GUI

/// GUI position type.
typedef Math::vec2 Position;
/// GUI size type.
typedef Math::vec2 Size;

/// Input mouse event type.
/** Contains:
enum Type
enum Button
*/
typedef Input::Event::Mouse MouseEvent;

/// Keyboard key type.
typedef Input::Key Key;

END_INANITY_GUI

#endif
<commit_msg>added Gui::Distance type<commit_after>#ifndef ___INANITY_GUI_TYPES_HPP___
#define ___INANITY_GUI_TYPES_HPP___

#include "gui.hpp"
#include "../inanity-math.hpp"
#include "../input/Key.hpp"
#include "../input/Event.hpp"

BEGIN_INANITY_GUI

/// GUI distance type.
typedef float Distance;
/// GUI position type.
typedef Math::xvec<Distance, 2> Position;
/// GUI size type.
typedef Math::xvec<Distance, 2> Size;

/// Input mouse event type.
/** Contains:
enum Type
enum Button
*/
typedef Input::Event::Mouse MouseEvent;

/// Keyboard key type.
typedef Input::Key Key;

END_INANITY_GUI

#endif
<|endoftext|>


<commit_before>// Streaming23_02_16.cpp : Defines the exported functions for the DLL application.
//

#include "xHacking.h"
#include "Utilities/Utilities.h"
#include "Loader/Loader.h"
#include "Detour/Detour.h"

#include <Tools/utils.h>
#include <Game/packet.h>
#include <Cryptography/login.h>
#include <Cryptography/game.h>

using namespace xHacking;
using namespace Net;

DWORD baseAddress = 0x68120C;
std::string sessionID;
Utils::Game::Session session;

inline bool isLogin()
{
	DWORD pointer1 = *(DWORD*)(baseAddress);
	DWORD pointer2 = *(DWORD*)(pointer1);
	return *(BYTE*)(pointer2 + 0x31) == 0x00;
}

Detour<int, int, const char*, int, int>* sendDetour = NULL;
Detour<int, int, char*, int, int>* recvDetour = NULL;
int WINAPI nuestro_send(SOCKET s, const char *buf, int len, int flags)
{
	int ret = (*sendDetour)(s, buf, len, flags);

	__asm PUSHAD;
	__asm PUSHFD;

	bool login = isLogin();
	Packet* packet = nullptr;
	if (login)
	{
		packet = gFactory->make(PacketType::SERVER_LOGIN, &session, std::string(buf, len));
		session.reset();
	}
	else
	{
		packet = gFactory->make(PacketType::SERVER_GAME, &session, std::string(buf, len));
	}

	auto packets = packet->decrypt();
	for (auto packet : packets)
	{
		if (!packet.empty())
		{
			auto tokens = Utils::tokenize(packet);

			if (tokens.size() < 2)
			{
				continue;
			}

			std::cout << tokens[1] << std::endl;
			if (tokens[1] == "u_s" || tokens[1] == "ncif" || tokens[1] == "walk")
			{
				printf("\nSend:\n");
				std::cout << ">> " << packet << std::endl;
			}
		}
	}

	// Set session after decrypting
	if (!login && session.id() == -1)
	{
		auto tokens = Utils::tokenize(packets[0]);
		session.setID(sessionID);
		session.setAlive(Utils::decimal_str2hex(tokens[0]));
	}

	__asm POPFD;
	__asm POPAD;

	gFactory->recycle(packet);

	return ret;
}

int WINAPI nuestro_recv(SOCKET s, char *buf, int len, int flags)
{
	int ret = (*recvDetour)(s, buf, len, flags);

	__asm PUSHAD;
	__asm PUSHFD;

	bool login = isLogin();
	Packet* packet = nullptr;
	if (login)
	{
		packet = gFactory->make(PacketType::CLIENT_LOGIN, &session, std::string(buf, ret));
	}
	else
	{
		packet = gFactory->make(PacketType::CLIENT_GAME, &session, std::string(buf, ret));
	}

	auto packets = packet->decrypt();
	for (std::string packet : packets)
	{
		if (!packet.empty())
		{
			auto tokens = Utils::tokenize(packet);
			if (tokens.size() < 1)
			{
				continue;
			}

			if (tokens[0] == "lev" || tokens[0] == "fd" || tokens[0] == "at" || tokens[0] == "c_map")
			{
				printf("\nRecv:\n");
				std::cout << "<< " << packet << std::endl;
			}
		}
	}
/*
	printf("\nRecv:\n");
	for (std::string data : packets)
	{
		std::cout << "<< " << data << std::endl;
	}
*/

	if (login)
	{
		auto tokens = Utils::tokenize(packets[0]);
		sessionID = tokens[1];
	}

	gFactory->recycle(packet);

	__asm POPFD;
	__asm POPAD;

	return ret;
}

void Hooks()
{
	sendDetour = new Detour<int, int, const char*, int, int>();
	sendDetour->Wait("WS2_32.dll", "send", (BYTE*)nuestro_send);

	recvDetour = new Detour<int, int, char*, int, int>();
	recvDetour->Wait("wsock32.dll", "recv", (BYTE*)nuestro_recv);
}

BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, DWORD reserved)
{
	if (reason == DLL_PROCESS_ATTACH)
	{
		// Use the xHacking::CreateConsole function
		CreateConsole();

		// Call our function
		Hooks();
	}

	return true;
}
<commit_msg>Advanced filtering for the bot<commit_after>#include <iostream>
#include <thread>

#include "xHacking.h"
#include "Utilities/Utilities.h"
#include "Loader/Loader.h"
#include "Detour/Detour.h"

#include <Tools/utils.h>
#include <Game/packet.h>
#include <Cryptography/login.h>
#include <Cryptography/game.h>

using namespace xHacking;
using namespace Net;

bool running;
std::thread inputThread;
std::vector<std::string> filterSend;
std::vector<std::string> filterRecv;

DWORD baseAddress = 0x68120C;
std::string sessionID;
Utils::Game::Session session;

inline bool isLogin()
{
	DWORD pointer1 = *(DWORD*)(baseAddress);
	DWORD pointer2 = *(DWORD*)(pointer1);
	return *(BYTE*)(pointer2 + 0x31) == 0x00;
}

Detour<int, int, const char*, int, int>* sendDetour = NULL;
Detour<int, int, char*, int, int>* recvDetour = NULL;
int WINAPI nuestro_send(SOCKET s, const char *buf, int len, int flags)
{
	int ret = (*sendDetour)(s, buf, len, flags);

	__asm PUSHAD;
	__asm PUSHFD;

	bool login = isLogin();
	Packet* packet = nullptr;
	if (login)
	{
		packet = gFactory->make(PacketType::SERVER_LOGIN, &session, std::string(buf, len));
		session.reset();
	}
	else
	{
		packet = gFactory->make(PacketType::SERVER_GAME, &session, std::string(buf, len));
	}

	auto packets = packet->decrypt();
	for (auto packet : packets)
	{
		if (!packet.empty())
		{
			auto tokens = Utils::tokenize(packet);

			if (tokens.size() < 2)
			{
				continue;
			}

			//std::cout << tokens[1] << std::endl;
			if (std::find(filterSend.begin(), filterSend.end(), tokens[1]) != filterSend.end())
			{
				printf("\nSend:\n");
				std::cout << ">> " << packet << std::endl;
			}
		}
	}

	// Set session after decrypting
	if (!login && session.id() == -1)
	{
		auto tokens = Utils::tokenize(packets[0]);
		session.setID(sessionID);
		session.setAlive(Utils::decimal_str2hex(tokens[0]));
	}

	__asm POPFD;
	__asm POPAD;

	gFactory->recycle(packet);

	return ret;
}

int WINAPI nuestro_recv(SOCKET s, char *buf, int len, int flags)
{
	int ret = (*recvDetour)(s, buf, len, flags);

	__asm PUSHAD;
	__asm PUSHFD;

	bool login = isLogin();
	Packet* packet = nullptr;
	if (login)
	{
		packet = gFactory->make(PacketType::CLIENT_LOGIN, &session, std::string(buf, ret));
	}
	else
	{
		packet = gFactory->make(PacketType::CLIENT_GAME, &session, std::string(buf, ret));
	}

	auto packets = packet->decrypt();
	for (std::string packet : packets)
	{
		if (!packet.empty())
		{
			auto tokens = Utils::tokenize(packet);
			if (tokens.size() < 1)
			{
				continue;
			}

			if (std::find(filterRecv.begin(), filterRecv.end(), tokens[0]) != filterRecv.end())
			{
				printf("\nRecv:\n");
				std::cout << "<< " << packet << std::endl;
			}
		}
	}

	if (login)
	{
		auto tokens = Utils::tokenize(packets[0]);
		sessionID = tokens[1];
	}

	gFactory->recycle(packet);

	__asm POPFD;
	__asm POPAD;

	return ret;
}

void Hooks()
{
	sendDetour = new Detour<int, int, const char*, int, int>();
	sendDetour->Wait("WS2_32.dll", "send", (BYTE*)nuestro_send);

	recvDetour = new Detour<int, int, char*, int, int>();
	recvDetour->Wait("wsock32.dll", "recv", (BYTE*)nuestro_recv);
}

void processInput()
{
	std::cout << "Welcome to ReverseTale-Bot, you can filter packets by issuing:" << std::endl;
	std::cout << "\t<packetOpcode : Adds a recv for `packetOpcode`" << std::endl;
	std::cout << "\t<-packetOpcode : Removes a recv for `packetOpcode`" << std::endl;
	std::cout << "\t>packetOpcode : Adds a send for `packetOpcode`" << std::endl;
	std::cout << "\t>-packetOpcode : Removes a send for `packetOpcode`" << std::endl;

	while (running)
	{
		std::string input;
		std::cout << "Enter Filter: ";
		std::cin >> input;

		if (input.length() > 2)
		{
			std::vector<<std::string>* filter;
			bool recv = input[0] == '<';
			bool rem = input[1] == '-';

			if (recv)
			{
				filter = &filterRecv;
			}
			else
			{
				filter = &filterSend;
			}

			if (rem)
			{
				std::string filter = input.substr(2);
				vec.erase(std::remove(vec.begin(), vec.end(), filter), vec.end());
			}
			else
			{
				std::string filter = input.substr(1);
				vec.push_back(filter);
			}
		}
	}
}

BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, DWORD reserved)
{
	if (reason == DLL_PROCESS_ATTACH)
	{
		// Use the xHacking::CreateConsole function
		CreateConsole();

		// Call our function
		Hooks();

		running = true;
		inputThread = std::thread(processInput);
	}
	else if (reason == DLL_PROCESS_DETTACH)
	{
		running = false;
		inputThread.join();
	}

	return true;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (C) 2014 Denis Rotanov <drotanov@gmail.com>
 *
 * 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 OR COPYRIGHT HOLDERS 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.
 ******************************************************************************/

#pragma once

#include <string>

#include "defines.hpp"
#include "type_info.hpp"

namespace mflect
{

enum class pflag : unsigned
{
  inplace = 0x01,
  array = 0x02,
  pointer = 0x04,
  identity_mask = 0xffffffff,
};

inline unsigned operator &(const unsigned lhs, const pflag rhs)
  { return lhs & static_cast<unsigned>(rhs); }
inline unsigned operator &(const pflag lhs, const pflag rhs)
  { return static_cast<unsigned>(lhs) & rhs; }
inline unsigned operator |(const unsigned lhs, const pflag rhs)
  { return lhs | static_cast<unsigned>(rhs); }
inline unsigned operator |(const pflag lhs, const pflag rhs)
  { return static_cast<unsigned>(lhs) | rhs; }

class property_info
{
public:
  /**
   * @brief name
   * @return property name as it was passed to declaration macro.
   */
  virtual const char* name() const = 0;

  /**
   * @brief type_name
   * @return type name of property disregarding flags
   */
  virtual const char* type_name() const = 0;

  /**
   * @brief owner_type_name
   * @return type name of owner
   */
  virtual const char* owner_type_name() const = 0;

  inline bool is_pointer() const;
  inline bool is_array() const;
  inline bool is_inplace() const;

  inline virtual void set_value(void* owner, const void* property) const;
  inline virtual void get_value(const void* owner, void*& value) const;
  inline virtual void get_value_inplace(void* owner, void*& value) const;

  inline virtual void push_value(void* owner, void* value) const;
  inline virtual void get_value(const void* owner, void*& value, unsigned index) const;

  inline virtual unsigned array_size(const void* owner) const;
  inline virtual void clear(void* owner) const;

protected:
  inline type_info::property_db_type& type_info_properties_(type_info* typeInfo);
  inline void not_implemented_(const std::string what) const;

  unsigned flags_;
};

//==============================================================================
bool property_info::is_pointer() const
{
  return flags_ & pflag::pointer;
}

//==============================================================================
bool property_info::is_array() const
{
  return flags_ & pflag::array;
}

//==============================================================================
bool property_info::is_inplace() const
{
  return flags_ & pflag::inplace;
}

//==============================================================================
void property_info::set_value(void* /*owner*/, const void* /*property*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::get_value(const void* /*owner*/, void*& /*value*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::get_value_inplace(void* /*owner*/, void*& /*value*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::push_value(void* /*owner*/, void* /*value*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::get_value(const void* /*owner*/, void*& /*value*/,
                              unsigned /*index*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
unsigned property_info::array_size(const void* /*owner*/) const
{
  not_implemented_(__FUNCTION__);
  return 0;
}

//==============================================================================
void property_info::clear(void* /*owner*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
type_info::property_db_type& property_info::type_info_properties_(type_info* typeInfo)
{
  return typeInfo->properties_;
}

//==============================================================================
void property_info::not_implemented_(const std::string what) const
{
  MFLECT_RUNTIME_ERROR(std::string(owner_type_name()) + ":" +
                       std::string(name()) + ":" + what + " not imlpemented");
}

} // namespace mflect
<commit_msg>fix warnings<commit_after>/*******************************************************************************
 * Copyright (C) 2014 Denis Rotanov <drotanov@gmail.com>
 *
 * 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 OR COPYRIGHT HOLDERS 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.
 ******************************************************************************/

#pragma once

#include <string>

#include "defines.hpp"
#include "type_info.hpp"

namespace mflect
{

enum class pflag : unsigned
{
  inplace = 0x01,
  array = 0x02,
  pointer = 0x04,
  identity_mask = 0xffffffff,
};

inline unsigned operator &(const unsigned lhs, const pflag rhs)
  { return lhs & static_cast<unsigned>(rhs); }
inline unsigned operator &(const pflag lhs, const pflag rhs)
  { return static_cast<unsigned>(lhs) & rhs; }
inline unsigned operator |(const unsigned lhs, const pflag rhs)
  { return lhs | static_cast<unsigned>(rhs); }
inline unsigned operator |(const pflag lhs, const pflag rhs)
  { return static_cast<unsigned>(lhs) | rhs; }

class property_info
{
public:
  /**
   * @brief name
   * @return property name as it was passed to declaration macro.
   */
  virtual const char* name() const = 0;

  /**
   * @brief type_name
   * @return type name of property disregarding flags
   */
  virtual const char* type_name() const = 0;

  /**
   * @brief owner_type_name
   * @return type name of owner
   */
  virtual const char* owner_type_name() const = 0;

  inline bool is_pointer() const;
  inline bool is_array() const;
  inline bool is_inplace() const;

  inline virtual void set_value(void* owner, const void* property) const;
  inline virtual void get_value(const void* owner, void*& value) const;
  inline virtual void get_value_inplace(void* owner, void*& value) const;

  inline virtual void push_value(void* owner, void* value) const;
  inline virtual void get_value(const void* owner, void*& value, unsigned index) const;

  inline virtual unsigned array_size(const void* owner) const;
  inline virtual void clear(void* owner) const;

protected:
  inline type_info::property_db_type& type_info_properties_(type_info* typeInfo);
  inline void not_implemented_(const std::string what) const;

  unsigned flags_;
};

//==============================================================================
bool property_info::is_pointer() const
{
  return (flags_ & pflag::pointer) > 0;
}

//==============================================================================
bool property_info::is_array() const
{
  return (flags_ & pflag::array) > 0;
}

//==============================================================================
bool property_info::is_inplace() const
{
  return (flags_ & pflag::inplace) > 0;
}

//==============================================================================
void property_info::set_value(void* /*owner*/, const void* /*property*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::get_value(const void* /*owner*/, void*& /*value*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::get_value_inplace(void* /*owner*/, void*& /*value*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::push_value(void* /*owner*/, void* /*value*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
void property_info::get_value(const void* /*owner*/, void*& /*value*/,
                              unsigned /*index*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
unsigned property_info::array_size(const void* /*owner*/) const
{
  not_implemented_(__FUNCTION__);
  return 0;
}

//==============================================================================
void property_info::clear(void* /*owner*/) const
{
  not_implemented_(__FUNCTION__);
}

//==============================================================================
type_info::property_db_type& property_info::type_info_properties_(type_info* typeInfo)
{
  return typeInfo->properties_;
}

//==============================================================================
void property_info::not_implemented_(const std::string what) const
{
  MFLECT_RUNTIME_ERROR(std::string(owner_type_name()) + ":" +
                       std::string(name()) + ":" + what + " not imlpemented");
}

} // namespace mflect
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ST7565(R) LCD ドライバー @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "common/delay.hpp"

namespace chip {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ST7565 テンプレートクラス
		@param[in]	CSI_IO	CSI(SPI) 制御クラス
		@param[in]	CS	デバイス選択、レジスター選択、制御クラス
		@param[in]	A0	制御切り替え、レジスター選択、制御クラス
		@param[in]	RES	リセット、制御クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class CSI_IO, class CS, class A0, class RES>
	class ST7565 {

		CSI_IO&	csi_;

		enum class CMD : uint8_t {
			DISPLAY_OFF = 0xAE,
			DISPLAY_ON  = 0xAF,
			SET_DISP_START_LINE = 0x40,
			SET_PAGE = 0xB0,

			SET_COLUMN_UPPER = 0x10,
			SET_COLUMN_LOWER = 0x00,

			SET_ADC_NORMAL  = 0xA0,
			SET_ADC_REVERSE = 0xA1,

			SET_DISP_NORMAL = 0xA6,
			SET_DISP_REVERSE = 0xA7,

			SET_ALLPTS_NORMAL = 0xA4,
			SET_ALLPTS_ON = 0xA5,
			SET_BIAS_9 = 0xA2,
			SET_BIAS_7 = 0xA3,

			RMW = 0xE0,
			RMW_CLEAR = 0xEE,
			INTERNAL_RESET = 0xE2,
			SET_COM_NORMAL = 0xC0,
			SET_COM_REVERSE = 0xC8,
			SET_POWER_CONTROL = 0x28,
			SET_RESISTOR_RATIO = 0x20,
			SET_VOLUME_FIRST = 0x81,
			SET_VOLUME_SECOND = 0x00,
			SET_STATIC_OFF = 0xAC,
			SET_STATIC_ON = 0xAD,
			SET_STATIC_REG = 0x00,
			SET_BOOSTER_FIRST = 0xF8,
			SET_BOOSTER_234 = 0,
			SET_BOOSTER_5 = 1,
			SET_BOOSTER_6 = 3,
			NOP = 0xE3,
			TEST = 0xF0,
		};

		inline void write_(CMD cmd) {
			csi_.xchg(static_cast<uint8_t>(cmd));
		}

		inline void write_(CMD cmd, uint8_t ord) {
			csi_.xchg(static_cast<uint8_t>(cmd) | ord);
		}

		inline void chip_enable_(bool f = true) const {
			CS::P = !f;
		}

		inline void reg_select_(bool f) const {
			A0::P = f;
		}

		void init_(bool comrvs, bool bias9) {

			reg_select_(0);
			chip_enable_();

			// toggle RST low to reset; CS low so it'll listen to us
			// if (cs > 0)
    		//     digitalWrite(cs, LOW);

			// digitalWrite(rst, LOW);
			// _delay_ms(500);
			// digitalWrite(rst, HIGH);

			write_(CMD::DISPLAY_OFF);

			// LCD bias select
			if(bias9) {
				write_(CMD::SET_BIAS_9);
			} else {
				write_(CMD::SET_BIAS_7);
			}
			// ADC select
			write_(CMD::SET_ADC_NORMAL);
			// SHL select
			if(comrvs) {
				write_(CMD::SET_COM_REVERSE);
			} else {
				write_(CMD::SET_COM_NORMAL);
			}

			// Initial display line
			write_(CMD::SET_DISP_START_LINE);

			// turn on voltage converter (VC=1, VR=0, VF=0)
			write_(CMD::SET_POWER_CONTROL, 0x4);
			// wait for 50% rising
			utils::delay::milli_second(50);

			// turn on voltage regulator (VC=1, VR=1, VF=0)
			write_(CMD::SET_POWER_CONTROL, 0x6);

			// wait >=50ms
			utils::delay::milli_second(50);

			// turn on voltage follower (VC=1, VR=1, VF=1)
			write_(CMD::SET_POWER_CONTROL, 0x7);

			// wait 10ms
			utils::delay::milli_second(10);

			// set lcd operating voltage (regulator resistor, ref voltage resistor)
			write_(CMD::SET_RESISTOR_RATIO, 0x6);
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		ST7565(CSI_IO& csi) : csi_(csi) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  ブライトネス設定
			@param[in]	val	ブライトネス値
		*/
		//-----------------------------------------------------------------//
		void set_brightness(uint8_t val)
		{
    		write_(CMD::SET_VOLUME_FIRST);
    		write_(CMD::SET_VOLUME_SECOND, (val & 0x3f));
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  開始
			@param[in]	contrast コントラスト
			@param[in]	comrvs	コモンライン・リバースの場合：true
			@param[in]	bias9	BIAS9 選択の場合「true」
		*/
		//-----------------------------------------------------------------//
		void start(uint8_t contrast, bool comrvs = false, bool bias9 = false)
		{
			CS::DIR = 1;  // (/CS) output
			A0::DIR = 1;  // (A0) output
			RES::DIR = 1; // (/RES) output

			RES::P = 0;  // assert /RES signal

			reg_select_(0);
			chip_enable_(false);

			utils::delay::milli_second(100);

			RES::P = 1;  // negate /RES signal

			utils::delay::milli_second(10);

			init_(comrvs, bias9);
			write_(CMD::DISPLAY_ON);
	  		write_(CMD::SET_ALLPTS_NORMAL);
			set_brightness(contrast);
			chip_enable_(false);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  コピー
			@param[in]	src	フレームバッファソース
			@param[in]	num	転送ページ数
			@param[in]	ofs	転送オフセット
		*/
		//-----------------------------------------------------------------//
		void copy(const uint8_t* src, uint8_t num, uint8_t ofs = 0) {
			chip_enable_();
			uint8_t o = 0x00;
			for(uint8_t page = ofs; page < (ofs + num); ++page) {
				reg_select_(0);
				write_(CMD::SET_PAGE, page);
				write_(CMD::SET_COLUMN_LOWER, o & 0x0f);
				write_(CMD::SET_COLUMN_UPPER, o >> 4);
				reg_select_(1);
				csi_.send(src, 128);
				src += 128;
			}
			reg_select_(0);
			chip_enable_(false);
		}

	};
}
<commit_msg>update bias<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ST7565(R) LCD ドライバー @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "common/delay.hpp"

namespace chip {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ST7565 テンプレートクラス
		@param[in]	CSI_IO	CSI(SPI) 制御クラス
		@param[in]	CS	デバイス選択、レジスター選択、制御クラス
		@param[in]	A0	制御切り替え、レジスター選択、制御クラス
		@param[in]	RES	リセット、制御クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class CSI_IO, class CS, class A0, class RES>
	class ST7565 {

		CSI_IO&	csi_;

		enum class CMD : uint8_t {
			DISPLAY_OFF = 0xAE,
			DISPLAY_ON  = 0xAF,
			SET_DISP_START_LINE = 0x40,
			SET_PAGE = 0xB0,

			SET_COLUMN_UPPER = 0x10,
			SET_COLUMN_LOWER = 0x00,

			SET_ADC_NORMAL  = 0xA0,
			SET_ADC_REVERSE = 0xA1,

			SET_DISP_NORMAL = 0xA6,
			SET_DISP_REVERSE = 0xA7,

			SET_ALLPTS_NORMAL = 0xA4,
			SET_ALLPTS_ON = 0xA5,
			SET_BIAS_9 = 0xA2,
			SET_BIAS_7 = 0xA3,

			RMW = 0xE0,
			RMW_CLEAR = 0xEE,
			INTERNAL_RESET = 0xE2,
			SET_COM_NORMAL = 0xC0,
			SET_COM_REVERSE = 0xC8,
			SET_POWER_CONTROL = 0x28,
			SET_RESISTOR_RATIO = 0x20,
			SET_VOLUME_FIRST = 0x81,
			SET_VOLUME_SECOND = 0x00,
			SET_STATIC_OFF = 0xAC,
			SET_STATIC_ON = 0xAD,
			SET_STATIC_REG = 0x00,
			SET_BOOSTER_FIRST = 0xF8,
			SET_BOOSTER_234 = 0,
			SET_BOOSTER_5 = 1,
			SET_BOOSTER_6 = 3,
			NOP = 0xE3,
			TEST = 0xF0,
		};

		inline void write_(CMD cmd) {
			csi_.xchg(static_cast<uint8_t>(cmd));
		}

		inline void write_(CMD cmd, uint8_t ord) {
			csi_.xchg(static_cast<uint8_t>(cmd) | ord);
		}

		inline void chip_enable_(bool f = true) const {
			CS::P = !f;
		}

		inline void reg_select_(bool f) const {
			A0::P = f;
		}

		void init_(bool comrvs, bool bias9, uint8_t vratio) {

			reg_select_(0);
			chip_enable_();

			// toggle RST low to reset; CS low so it'll listen to us
			// if (cs > 0)
    		//     digitalWrite(cs, LOW);

			// digitalWrite(rst, LOW);
			// _delay_ms(500);
			// digitalWrite(rst, HIGH);

			write_(CMD::DISPLAY_OFF);

			// LCD bias select
			if(bias9) {
				write_(CMD::SET_BIAS_9);
			} else {
				write_(CMD::SET_BIAS_7);
			}
			// ADC select
			write_(CMD::SET_ADC_NORMAL);
			// SHL select
			if(comrvs) {
				write_(CMD::SET_COM_REVERSE);
			} else {
				write_(CMD::SET_COM_NORMAL);
			}

			// Initial display line
			write_(CMD::SET_DISP_START_LINE);

			// turn on voltage converter (VC=1, VR=0, VF=0)
			write_(CMD::SET_POWER_CONTROL, 0x4);
			// wait for 50% rising
			utils::delay::milli_second(50);

			// turn on voltage regulator (VC=1, VR=1, VF=0)
			write_(CMD::SET_POWER_CONTROL, 0x6);

			// wait >=50ms
			utils::delay::milli_second(50);

			// turn on voltage follower (VC=1, VR=1, VF=1)
			write_(CMD::SET_POWER_CONTROL, 0x7);

			// wait 10ms
			utils::delay::milli_second(10);

			// set lcd operating voltage (regulator resistor, ref voltage resistor)
///			write_(CMD::SET_RESISTOR_RATIO, 0x6);
///			write_(CMD::SET_RESISTOR_RATIO, 0x3);
			write_(CMD::SET_RESISTOR_RATIO, vratio);
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		ST7565(CSI_IO& csi) : csi_(csi) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  ブライトネス設定
			@param[in]	val	ブライトネス値
		*/
		//-----------------------------------------------------------------//
		void set_brightness(uint8_t val)
		{
    		write_(CMD::SET_VOLUME_FIRST);
    		write_(CMD::SET_VOLUME_SECOND, (val & 0x3f));
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  開始
			@param[in]	contrast コントラスト
			@param[in]	comrvs	コモンライン・リバースの場合：true
			@param[in]	bias9	BIAS9 選択の場合「true」
			@param[in]	vratio	ボルテージ・レシオ
		*/
		//-----------------------------------------------------------------//
		void start(uint8_t contrast, bool comrvs = false, bool bias9 = false, uint8_t vratio = 6)
		{
			CS::DIR = 1;  // (/CS) output
			A0::DIR = 1;  // (A0) output
			RES::DIR = 1; // (/RES) output

			RES::P = 0;  // assert /RES signal

			reg_select_(0);
			chip_enable_(false);

			utils::delay::milli_second(100);

			RES::P = 1;  // negate /RES signal

			utils::delay::milli_second(10);

			init_(comrvs, bias9, vratio);
			write_(CMD::DISPLAY_ON);
	  		write_(CMD::SET_ALLPTS_NORMAL);
			set_brightness(contrast);
			chip_enable_(false);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  コピー
			@param[in]	src	フレームバッファソース
			@param[in]	num	転送ページ数
			@param[in]	ofs	転送オフセット
		*/
		//-----------------------------------------------------------------//
		void copy(const uint8_t* src, uint8_t num, uint8_t ofs = 0) {
			chip_enable_();
			uint8_t o = 0x00;
			for(uint8_t page = ofs; page < (ofs + num); ++page) {
				reg_select_(0);
				write_(CMD::SET_PAGE, page);
				write_(CMD::SET_COLUMN_LOWER, o & 0x0f);
				write_(CMD::SET_COLUMN_UPPER, o >> 4);
				reg_select_(1);
				csi_.send(src, 128);
				src += 128;
			}
			reg_select_(0);
			chip_enable_(false);
		}

	};
}
<|endoftext|>