<commit_before>//This program created by love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017. All right reserved. / Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir / Website: iasbs.ac.ir/~hkhojasteh, hadiabdikhojasteh.ir

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/ml/ml.hpp>

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <math.h>
#include <time.h>

using namespace std;
using namespace cv;
using namespace cv::ml;

typedef tuple<char, uint32_t> enumerate;
struct IncGenerator {
	uint32_t current_;
	IncGenerator(uint32_t start) : current_(start) {}
	uint32_t operator() () { return current_++; }
};

vector<uint32_t> sample(Mat1d, uint32_t, uint32_t);
void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev);

uint32_t data_size, vocab_size;
Mat1d Wxh, Whh, Why, bh, by;							//model parameters

uint32_t main() {
	srand(time(NULL));

	vector<char> data;
	vector<char> chars;
	vector<enumerate> charenum;
	FILE* inputfile;
	string fileName = "input.txt";
	inputfile = fopen(fileName.c_str(), "r");

	uint32_t i = 0;
	while (!feof(inputfile)) {
		char inchar[1] = { 0 };
		fscanf(inputfile, "%c", inchar);
		data.push_back(inchar[0]);

		auto it = find_if(chars.begin(), chars.end(),
			[&](const char element) { return element == inchar[0]; });
		//If this is not in the char set
		if (it == end(chars)) {
			chars.push_back(inchar[0]);
			charenum.push_back(make_tuple(inchar[0], i));
			i++;
		}
	}
	fclose(inputfile);

	data_size = data.size();
	vocab_size = chars.size();
	printf("data has %d characters, %d unique.\n", data_size, vocab_size);
	vector<enumerate> char_to_ix = charenum;
	reverse(charenum.begin(), charenum.end());
	vector<enumerate> ix_to_char = charenum;

	//hyperparameters
	uint32_t hidden_size = 100;							//size of hidden layer of neurons
	uint32_t seq_length = 25;							//number of steps to unroll the RNN for
	double learning_rate = 1e-1;

	Wxh.create(hidden_size, vocab_size);				//Or: Mat mat(2, 4, CV_64FC1);
	Whh.create(hidden_size, hidden_size);
	Why.create(vocab_size, hidden_size);
	double mean = 0.0, stddev = 1.0 / 3.0;				//99.7% of values will be inside [-1, +1] interval
	randn(Wxh, Scalar(mean), Scalar(stddev));			//input to hidden
	randn(Whh, Scalar(mean), Scalar(stddev));			//hidden to hidden
	randn(Why, Scalar(mean), Scalar(stddev));			//hidden to output
	bh = Mat::zeros(hidden_size, 1, CV_32F);			//hidden bias
	by = Mat::zeros(vocab_size, 1, CV_32F);				//output bias

	uint32_t n = 0, p = 0;
	//Make an array of zeros with the same shape and type as a Ws array.
	Mat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type());
	Mat1d mWhh = Mat::zeros(Whh.size(), Whh.type());
	Mat1d mWhy = Mat::zeros(Why.size(), Why.type());
	Mat1d mbh = Mat::zeros(bh.size(), bh.type());		//memory variables for Adagrad
	Mat1d mby = Mat::zeros(by.size(), by.type());		//memory variables for Adagrad
	//loss at iteration 0
	double smooth_loss = -log(1.0 / vocab_size) * seq_length;

	Mat1d loss, dWxh, dWhh, dWhy, dbh, dby, hprev;
	vector<enumerate> inputs, targets;
	for (uint32_t i = 0; i < 1000; i++) {
		//Prepare inputs (we're sweeping from left to right in steps seq_length long)
		if (p + seq_length + 1 >= data.size() || n == 0) {
			hprev = Mat::zeros(hidden_size, 1, CV_32F);	//reset RNN memory
			p = 0;										//go from start of data
		}

		inputs.clear();
		targets.clear();
		for (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size(); i++) {
			inputs.push_back(char_to_ix[p + i]);
			targets.push_back(char_to_ix[p + 1 + i]);
		}

		//Sample from the model now and then
		if (n % 100 == 0) {
			vector<uint32_t> sampWords = sample(hprev, p + i, 200);
			for (uint32_t i = 0; i < sampWords.size(); i++) {
				printf("%c", get<0>(ix_to_char[sampWords[i]]));
			}
		}

		lossFun(inputs, targets, hprev);

		p += seq_length;								//move data pointer
		n += 1;											//iteration counter
	}
	return 0;
}

vector<uint32_t> sample(Mat1d h, uint32_t seed_ix, uint32_t n) {
	//sample a sequence of integers from the model h is memory state,
	//     seed_ix is seed letter for first time step
	Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
	x[seed_ix][0] = 1.0;
	vector<uint32_t> ixes;
	for (uint32_t i = 0; i < n; i++) {
		Mat1d t = (Wxh * x) + (Whh * h) + bh;
		Mat1d h = Mat::zeros(t.size(), t.type());
		for (uint32_t i = 0; i < t.rows; i++) {
			h[i][0] = tanh(t[i][0]);
		}
		Mat1d y = (Why * h) + by;
		Mat1d expy;
		exp(y, expy);
		Mat1d p = expy / sum(expy)[0];
		p = p.reshape(1, 1);

		//Generates a random sample from a given 1-D array
		default_random_engine generator;
		discrete_distribution<int> distribution(p.begin(), p.end());
		vector<double> indices(p.size().width);
		generate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); });
		vector<int> incNumbers(p.size().width);
		IncGenerator gi(0);
		generate(incNumbers.begin(), incNumbers.end(), gi);
		Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
		int randSelect = (uint32_t)rand() % vocab_size;
		x[randSelect][0] = 1.0;
		ixes.push_back(randSelect);
	}
	return ixes;
}

void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev) {
	//inputs, targets are both list of integers.
	//     hprev is Hx1 array of initial hidden state
	//     returns the loss, gradients on model parameters, and last hidden state
	Mat1d hs = hprev;
	double loss = 0.0;
	//forward pass
	for (uint32_t t = 0; t < inputs.size(); t++) {
		//encode in 1-of-k
		Mat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F);
		xs[t][get<1>(inputs[t])] = 1;
		Mat1d val = (Wxh * xs.row(t).t());
		for (uint32_t i = 0; i < val.rows; i++) {
			hs[i][0] = tanh(val[i][0]);
			Mat1d temp = (Whh * hs[i - 1][0]);
			hs[i][0] += temp[i][0] + bh[i][0];				//hidden state
		}
		Mat1d ys = (Why * hs[t][0]) + by[t][0];				//unnormalized log probabilities for next chars
		for (uint32_t i = 0; i < ys.rows; i++) {
			hs[i][0] = tanh(val[i][0]);
			Mat1d temp = (Whh * hs[i - 1][0]);
			hs[i][0] += temp[i][0] + bh[i][0];				//hidden state
		}
	}
}
<commit_msg>softmax (cross-entropy loss)<commit_after>//This program created by love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017. All right reserved. / Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir / Website: iasbs.ac.ir/~hkhojasteh, hadiabdikhojasteh.ir

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/ml/ml.hpp>

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <math.h>
#include <time.h>

using namespace std;
using namespace cv;
using namespace cv::ml;

typedef tuple<char, uint32_t> enumerate;
struct IncGenerator {
	uint32_t current_;
	IncGenerator(uint32_t start) : current_(start) {}
	uint32_t operator() () { return current_++; }
};

vector<uint32_t> sample(Mat1d, uint32_t, uint32_t);
void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev);

uint32_t data_size, vocab_size;
Mat1d Wxh, Whh, Why, bh, by;							//model parameters

uint32_t main() {
	srand(time(NULL));

	vector<char> data;
	vector<char> chars;
	vector<enumerate> charenum;
	FILE* inputfile;
	string fileName = "input.txt";
	inputfile = fopen(fileName.c_str(), "r");

	uint32_t i = 0;
	while (!feof(inputfile)) {
		char inchar[1] = { 0 };
		fscanf(inputfile, "%c", inchar);
		data.push_back(inchar[0]);

		auto it = find_if(chars.begin(), chars.end(),
			[&](const char element) { return element == inchar[0]; });
		//If this is not in the char set
		if (it == end(chars)) {
			chars.push_back(inchar[0]);
			charenum.push_back(make_tuple(inchar[0], i));
			i++;
		}
	}
	fclose(inputfile);

	data_size = data.size();
	vocab_size = chars.size();
	printf("data has %d characters, %d unique.\n", data_size, vocab_size);
	vector<enumerate> char_to_ix = charenum;
	reverse(charenum.begin(), charenum.end());
	vector<enumerate> ix_to_char = charenum;

	//hyperparameters
	uint32_t hidden_size = 100;							//size of hidden layer of neurons
	uint32_t seq_length = 25;							//number of steps to unroll the RNN for
	double learning_rate = 1e-1;

	Wxh.create(hidden_size, vocab_size);				//Or: Mat mat(2, 4, CV_64FC1);
	Whh.create(hidden_size, hidden_size);
	Why.create(vocab_size, hidden_size);
	double mean = 0.0, stddev = 1.0 / 3.0;				//99.7% of values will be inside [-1, +1] interval
	randn(Wxh, Scalar(mean), Scalar(stddev));			//input to hidden
	randn(Whh, Scalar(mean), Scalar(stddev));			//hidden to hidden
	randn(Why, Scalar(mean), Scalar(stddev));			//hidden to output
	bh = Mat::zeros(hidden_size, 1, CV_32F);			//hidden bias
	by = Mat::zeros(vocab_size, 1, CV_32F);				//output bias

	uint32_t n = 0, p = 0;
	//Make an array of zeros with the same shape and type as a Ws array.
	Mat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type());
	Mat1d mWhh = Mat::zeros(Whh.size(), Whh.type());
	Mat1d mWhy = Mat::zeros(Why.size(), Why.type());
	Mat1d mbh = Mat::zeros(bh.size(), bh.type());		//memory variables for Adagrad
	Mat1d mby = Mat::zeros(by.size(), by.type());		//memory variables for Adagrad
	//loss at iteration 0
	double smooth_loss = -log(1.0 / vocab_size) * seq_length;

	Mat1d loss, dWxh, dWhh, dWhy, dbh, dby, hprev;
	vector<enumerate> inputs, targets;
	for (uint32_t i = 0; i < 1000; i++) {
		//Prepare inputs (we're sweeping from left to right in steps seq_length long)
		if (p + seq_length + 1 >= data.size() || n == 0) {
			hprev = Mat::zeros(hidden_size, 1, CV_32F);	//reset RNN memory
			p = 0;										//go from start of data
		}

		inputs.clear();
		targets.clear();
		for (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size(); i++) {
			inputs.push_back(char_to_ix[p + i]);
			targets.push_back(char_to_ix[p + 1 + i]);
		}

		//Sample from the model now and then
		if (n % 100 == 0) {
			vector<uint32_t> sampWords = sample(hprev, p + i, 200);
			for (uint32_t i = 0; i < sampWords.size(); i++) {
				printf("%c", get<0>(ix_to_char[sampWords[i]]));
			}
			printf("\n");
		}

		lossFun(inputs, targets, hprev);

		p += seq_length;								//move data pointer
		n += 1;											//iteration counter
	}
	return 0;
}

vector<uint32_t> sample(Mat1d h, uint32_t seed_ix, uint32_t n) {
	//sample a sequence of integers from the model h is memory state,
	//     seed_ix is seed letter for first time step
	Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
	x[seed_ix][0] = 1.0;
	vector<uint32_t> ixes;
	for (uint32_t i = 0; i < n; i++) {
		Mat1d t = (Wxh * x) + (Whh * h) + bh;
		Mat1d h = Mat::zeros(t.size(), t.type());
		for (uint32_t i = 0; i < t.rows; i++) {
			h[i][0] = tanh(t[i][0]);
		}
		Mat1d y = (Why * h) + by;
		Mat1d expy;
		exp(y, expy);
		Mat1d p = expy / sum(expy)[0];
		p = p.reshape(1, 1);

		//Generates a random sample from a given 1-D array
		default_random_engine generator;
		discrete_distribution<int> distribution(p.begin(), p.end());
		vector<double> indices(p.size().width);
		generate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); });
		vector<int> incNumbers(p.size().width);
		IncGenerator gi(0);
		generate(incNumbers.begin(), incNumbers.end(), gi);
		Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
		int randSelect = (uint32_t)rand() % vocab_size;
		x[randSelect][0] = 1.0;
		ixes.push_back(randSelect);
	}
	return ixes;
}

void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev) {
	//inputs, targets are both list of integers.
	//     hprev is Hx1 array of initial hidden state
	//     returns the loss, gradients on model parameters, and last hidden state
	Mat1d hs = hprev;
	double loss = 0.0;
	//forward pass
	for (uint32_t t = 0; t < inputs.size(); t++) {
		//encode in 1-of-k
		Mat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F);
		xs[t][get<1>(inputs[t])] = 1;
		Mat1d val = (Wxh * xs.row(t).t());
		for (uint32_t i = 0; i < val.rows; i++) {
			hs[i][0] = tanh(val[i][0]);
			Mat1d temp = (Whh * hs[i - 1][0]);
			hs[i][0] += temp[i][0] + bh[i][0];				//hidden state
		}
		Mat1d ys = (Why * hs[t][0]) + by[t][0];				//unnormalized log probabilities for next chars
		//probabilities for next chars
		Mat1d ps = Mat::zeros(ys.size(), ys.type());
		double sum = 0.0;
		for (uint32_t i = 0; i < ys.rows; i++) {
			sum += ps[t][i];
			ps[t][i] = exp(ys[t][i]);
		}
		for (uint32_t i = 0; i < ys.rows; i++) {
			ps[t][0] = ps[t][0] / sum;
		}
		loss += -log(ps[t][get<1>(targets[t])]);			//softmax (cross-entropy loss)
	}
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
using namespace std;

#define min(a,b) ( (a) < (b) ? (a) : (b) )

const int maxn = 1111;
int N;
int code[maxn];
int guess[maxn];
int hash_code[9], hash_guess[9];

void solve() {
    int x = 0, y = 0;
    memset(hash_code, 0, sizeof(hash_code));
    memset(hash_guess, 0, sizeof(hash_guess));
    for(int i = 0; i < N; ++i) {
        if(code[i] == guess[i]) {
            ++x;
        } else {
            ++hash_code[code[i]-1];
            ++hash_guess[guess[i]-1];
        }
    }
    for(int i = 0; i < 9; ++i)
        y += min(hash_code[i], hash_guess[i]);
    printf("    (%d,%d)\n", x, y);
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int kase = 1;
    while(scanf("%d", &N) == 1 && N) {
        printf("Game %d:\n", kase++);
        for(int i = 0; i < N; ++i)
            scanf("%d", &code[i]);
        while(scanf("%d", &guess[0]) == 1) {
            for(int i = 1; i < N; ++i)
                scanf("%d", &guess[i]);
            if(guess[0] == 0) break;
            solve();
        }
    }
    return 0;
}

<commit_msg>Master-Mind Hints<commit_after>#include <cstdio>
#include <cstring>
using namespace std;

#define min(a,b) ( (a) < (b) ? (a) : (b) )

const int maxn = 1111;
int N;
int code[maxn];
int guess[maxn];
int hash_code[9], hash_guess[9];

void solve() {
    int x = 0, y = 0;
    memset(hash_code, 0, sizeof(hash_code));
    memset(hash_guess, 0, sizeof(hash_guess));
    for(int i = 0; i < N; ++i) {
        if(code[i] == guess[i]) {
            ++x;
        }
        ++hash_code[code[i]-1];
        ++hash_guess[guess[i]-1];
    }
    for(int i = 0; i < 9; ++i)
        y += min(hash_code[i], hash_guess[i]);
    printf("    (%d,%d)\n", x, y-x);
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int kase = 1;
    while(scanf("%d", &N) == 1 && N) {
        printf("Game %d:\n", kase++);
        for(int i = 0; i < N; ++i)
            scanf("%d", &code[i]);
        while(scanf("%d", &guess[0]) == 1) {
            for(int i = 1; i < N; ++i)
                scanf("%d", &guess[i]);
            if(guess[0] == 0) break;
            solve();
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "cookie.hpp"

using namespace cookie;

/*
Cookie::Cookie(std::string& key, std::string& value)
  : key_(key), value_(value) {

}

Cookie::Cookie(std::string& key, std::string& value, std::string& options)
  : key_(key), value_(value), options_(options) {

}

Cookie::~Cookie() {

}
*/

const std::string Cookie::no_entry_value_;

inline static bool equiv_strs(std::string& s1, std::string& s2) {
  std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower());
  std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower());
  return s1 == s2;
}

inline auto Cookie::find(const std::string& keyword) const {
  return std::find_if(data_.begin(), data_.end(), [&keyword](const auto& k) {
    return equiv_strs(k.first, keyword);
  });
}

inline Cookie::Cookie(const std::string& data, Parser parser) : data_{}, parser_{parser} {
  parse(data);
}

inline const std::string& Cookie::name() const {
  return data_.at(0).first;
}

inline const std::string& Cookie::value() const {
  return data_.at(0).second;
}

inline const std::string& Cookie::expires() const {
  auto it = find("Expires");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const std::string& Cookie::max_age() const {
  auto it = find("Max-Age");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const std::string& Cookie::domanin() const {
  auto it = find("Domain");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const std::string& Cookie::path() const {
  auto it = find("Path");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const bool Cookie::is_secure() const noexcept {
  return find("Secure") not_eq data_.end();
}

inline const bool Cookie::is_http_only() const noexcept {
  return find("HttpOnly") not_eq data_.end();
}

// Fill in
std::string Cookie::to_string() const {
  std::string cookieString = "";

  cookieString += "";

  return cookieString;
}

Cookie::operator std::string () const {
  return to_string();
}

inline void Cookie::parse(const std::string& data) {
  if(parser_) {
    data_ = parser_(data);
  } else {
    static const std::regex pattern{"[^;]+"};
    auto position = std::sregex_iterator(data.begin(), data.end(), pattern);
    auto end = std::sregex_iterator();

    // And more ...

  }
}

inline std::ostream& operator << (std::ostream& output_device, const Cookie& cookie) {
  return output_device << cookie.to_string();
}

// ?
std::string Cookie::serialize(std::string& key, std::string& value) {
  //if(key.empty())

  std::string cookieString = "";

  cookieString += "";

  return cookieString;
}

// ?
std::string Cookie::serialize(std::string& key, std::string& value, std::string& options) {

}

// ?
bool Cookie::deserialize() {

}

// ?
std::shared_ptr<Cookie> Cookie::parse(std::string& str, std::string& options) {
  std::shared_ptr<Cookie> cookie(new Cookie());

  return cookie;
}
<commit_msg>Refactored Cookie::find<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "cookie.hpp"

using namespace cookie;

/*
Cookie::Cookie(std::string& key, std::string& value)
  : key_(key), value_(value) {

}

Cookie::Cookie(std::string& key, std::string& value, std::string& options)
  : key_(key), value_(value), options_(options) {

}

Cookie::~Cookie() {

}
*/

const std::string Cookie::no_entry_value_;

inline auto Cookie::find(const std::string& keyword) const {
  return std::find_if(data_.begin(), data_.end(), [&keyword](const auto& k){
    return std::equal(k.first.begin(), k.first.end(), keyword.begin(), keyword.end(),
           [](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);
    });
  });
}

inline Cookie::Cookie(const std::string& data, Parser parser) : data_{}, parser_{parser} {
  parse(data);
}

inline const std::string& Cookie::name() const {
  return data_.at(0).first;
}

inline const std::string& Cookie::value() const {
  return data_.at(0).second;
}

inline const std::string& Cookie::expires() const {
  auto it = find("Expires");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const std::string& Cookie::max_age() const {
  auto it = find("Max-Age");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const std::string& Cookie::domanin() const {
  auto it = find("Domain");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const std::string& Cookie::path() const {
  auto it = find("Path");
  return (it not_eq data_.end()) ? it->second : no_entry_value_;
}

inline const bool Cookie::is_secure() const noexcept {
  return find("Secure") not_eq data_.end();
}

inline const bool Cookie::is_http_only() const noexcept {
  return find("HttpOnly") not_eq data_.end();
}

// Fill in
std::string Cookie::to_string() const {
  std::string cookieString = "";

  cookieString += "";

  return cookieString;
}

Cookie::operator std::string () const {
  return to_string();
}

inline void Cookie::parse(const std::string& data) {
  if(parser_) {
    data_ = parser_(data);
  } else {
    static const std::regex pattern{"[^;]+"};
    auto position = std::sregex_iterator(data.begin(), data.end(), pattern);
    auto end = std::sregex_iterator();

    // And more ...

  }
}

inline std::ostream& operator << (std::ostream& output_device, const Cookie& cookie) {
  return output_device << cookie.to_string();
}

// ?
std::string Cookie::serialize(std::string& key, std::string& value) {
  //if(key.empty())

  std::string cookieString = "";

  cookieString += "";

  return cookieString;
}

// ?
std::string Cookie::serialize(std::string& key, std::string& value, std::string& options) {

}

// ?
bool Cookie::deserialize() {

}

// ?
std::shared_ptr<Cookie> Cookie::parse(std::string& str, std::string& options) {
  std::shared_ptr<Cookie> cookie(new Cookie());

  return cookie;
}
<|endoftext|>


<commit_before>#include "docking.h"
#include "docks.h"
#include "runtime/system/engine.h"
#include "../gui_window.h"
#include "core/logging/logging.h"

bool DockingSystem::initialize()
{
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());

	auto& scene = _docks[0];
	scene->initialize("Scene", true, ImVec2(200.0f, 200.0f), &Docks::render_scene);

	auto& game = _docks[1];
	game->initialize("Game", true, ImVec2(200.0f, 200.0f), &Docks::render_game);

	auto& hierarchy = _docks[2];
	hierarchy->initialize("Hierarchy", true, ImVec2(300.0f, 200.0f), &Docks::render_hierarchy);

	auto& inspector = _docks[3];
	inspector->initialize("Inspector", true, ImVec2(300.0f, 200.0f), &Docks::render_inspector);

	auto& assets = _docks[4];
	assets->initialize("Assets", true, ImVec2(200.0f, 200.0f), &Docks::render_assets);

	auto& console = _docks[5];
	console->initialize("Console", true, ImVec2(200.0f, 200.0f), [this](ImVec2 area)
	{
		Docks::render_console(area, *_console_log.get());
	});

	auto& style = _docks[6];
	style->initialize("Style", true, ImVec2(300.0f, 200.0f), &Docks::render_style);

	auto engine = core::get_subsystem<runtime::Engine>();
	const auto& windows = engine->get_windows();
	auto& window = static_cast<GuiWindow&>(*windows[0]);
	auto& dockspace = window.get_dockspace();
	dockspace.dock(scene.get(), ImGuiDock::DockSlot::None, 200, true);
	dockspace.dock_with(game.get(), scene.get(), ImGuiDock::DockSlot::Tab, 300, false);
	dockspace.dock_with(inspector.get(), scene.get(), ImGuiDock::DockSlot::Right, 300, true);
	dockspace.dock_with(hierarchy.get(), scene.get(), ImGuiDock::DockSlot::Left, 300, true);
	dockspace.dock(assets.get(), ImGuiDock::DockSlot::Bottom, 250, true);
	dockspace.dock_with(console.get(), assets.get(), ImGuiDock::DockSlot::Tab, 250, true);
	dockspace.dock_with(style.get(), assets.get(), ImGuiDock::DockSlot::Right, 300, true);

	auto logger = logging::get("Log");
	logger->add_sink(_console_log);

	std::function<void()> logVersion = [logger]()
	{
		logger->info() << "Version 1.0";
	};
	_console_log->register_command(
		"version",
		"Returns the current version of the Editor.",
		{},
		{},
		logVersion
	);

	return true;
}
<commit_msg>Cleanup.<commit_after>#include "docking.h"
#include "docks.h"
#include "runtime/system/engine.h"
#include "../gui_window.h"
#include "core/logging/logging.h"

bool DockingSystem::initialize()
{
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());
	_docks.emplace_back(std::make_unique<ImGuiDock::Dock>());

	auto& scene = _docks[0];
	scene->initialize("Scene", true, ImVec2(200.0f, 200.0f), &Docks::render_scene);

	auto& game = _docks[1];
	game->initialize("Game", true, ImVec2(200.0f, 200.0f), &Docks::render_game);

	auto& hierarchy = _docks[2];
	hierarchy->initialize("Hierarchy", true, ImVec2(300.0f, 200.0f), &Docks::render_hierarchy);

	auto& inspector = _docks[3];
	inspector->initialize("Inspector", true, ImVec2(300.0f, 200.0f), &Docks::render_inspector);

	auto& assets = _docks[4];
	assets->initialize("Assets", true, ImVec2(200.0f, 200.0f), &Docks::render_assets);

	auto& console = _docks[5];
	console->initialize("Console", true, ImVec2(200.0f, 200.0f), [this](ImVec2 area)
	{
		Docks::render_console(area, *_console_log.get());
	});

	auto& style = _docks[6];
	style->initialize("Style", true, ImVec2(300.0f, 200.0f), &Docks::render_style);

	auto engine = core::get_subsystem<runtime::Engine>();
	const auto& windows = engine->get_windows();
	auto& window = static_cast<GuiWindow&>(*windows[0]);
	auto& dockspace = window.get_dockspace();
	dockspace.dock(scene.get(), ImGuiDock::DockSlot::None, 200, true);
	dockspace.dock_with(game.get(), scene.get(), ImGuiDock::DockSlot::Tab, 300, false);
	dockspace.dock_with(inspector.get(), scene.get(), ImGuiDock::DockSlot::Right, 300, true);
	dockspace.dock_with(hierarchy.get(), scene.get(), ImGuiDock::DockSlot::Left, 300, true);
	dockspace.dock(console.get(), ImGuiDock::DockSlot::Bottom, 250, true);
	dockspace.dock_with(assets.get(), console.get(), ImGuiDock::DockSlot::Tab, 250, true);
	dockspace.dock_with(style.get(), assets.get(), ImGuiDock::DockSlot::Right, 300, true);

	auto logger = logging::get("Log");
	logger->add_sink(_console_log);

	std::function<void()> logVersion = [logger]()
	{
		logger->info() << "Version 1.0";
	};
	_console_log->register_command(
		"version",
		"Returns the current version of the Editor.",
		{},
		{},
		logVersion
	);

	return true;
}
<|endoftext|>


<commit_before>#include "Riostream.h"

#include "Coefficient.h"
#include "RooAbsReal.h"
#include "RooAbsCategory.h"
#include "RooCategory.h"
#include <math.h>
#include "TMath.h"

ClassImp(doofit::roofit::functions::bdecay::Coefficient)

namespace doofit {
namespace roofit {
namespace functions {
namespace bdecay {

Coefficient::Coefficient(const std::string& name,
                       RooAbsReal& _cp_coeff_,
                       CoeffType   _coeff_type_,
                       RooAbsCategory& _tag_,
                       RooAbsReal& _eta_,
                       RooAbsReal& _avg_eta_,
                       RooAbsReal& _p0_,
                       RooAbsReal& _p1_,
                       RooAbsReal& _delta_p0_,
                       RooAbsReal& _delta_p1_,
                       RooAbsReal& _production_asym_,
                       int         _tag_sign_) :
  RooAbsReal(name.c_str(),name.c_str()),
  cp_coeff_("cp_coeff_","cp_coeff_",this,_cp_coeff_),
  coeff_type_(_coeff_type_),
  tag_("tag_","tag_",this,_tag_),
  eta_("eta_","eta_",this,_eta_),
  avg_eta_("avg_eta_","avg_eta_",this,_avg_eta_),
  p0_("p0_","p0_",this,_p0_),
  p1_("p1_","p1_",this,_p1_),
  delta_p0_("delta_p0_","delta_p0_",this,_delta_p0_),
  delta_p1_("delta_p1_","delta_p1_",this,_delta_p1_),
  production_asym_("production_asym_","production_asym_",this,_production_asym_),
  tag_sign_(_tag_sign_)
{
}

Coefficient::Coefficient(const Coefficient& other, const char* name) :
  RooAbsReal(other,name),
  cp_coeff_("cp_coeff_",this,other.cp_coeff_),
  coeff_type_(other.coeff_type_),
  tag_("tag_",this,other.tag_),
  eta_("eta_",this,other.eta_),
  avg_eta_("avg_eta_",this,other.avg_eta_),
  p0_("p0_",this,other.p0_),
  p1_("p1_",this,other.p1_),
  delta_p0_("delta_p0_",this,other.delta_p0_),
  delta_p1_("delta_p1_",this,other.delta_p1_),
  production_asym_("production_asym_",this,other.production_asym_),
  tag_sign_(other.tag_sign_)
{
}

Double_t Coefficient::evaluate() const
{
  return evaluate(cp_coeff_, coeff_type_, tag_, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
}

Int_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const
{
  // debug
  // std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
  // allVars.Print();

  if (matchArgs(allVars, analVars, tag_)) return 1 ;
  return 0 ;
}

Int_t Coefficient::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* /*rangeName*/) const
{
  // debug
  std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
  allVars.Print();
  if (normSet) normSet->Print();

  if (matchArgs(allVars, analVars, tag_)) return 1 ;
  return 0 ;
}

Double_t Coefficient::analyticalIntegral(Int_t code, const char* rangeName) const
{
  // debug
  // std::printf("CHECK: In %s line %u (%s): Range: %s : Code: %d \n", __func__, __LINE__, __FILE__, rangeName, code);

  // first return analytical integral for defined range
  if (rangeName){
    double integral = 0;
    if (isTagInRange(tag_, +1, rangeName)){
      integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " Range: B0B0 : " << integral << std::endl;
    }
    if (isTagInRange(tag_, -1, rangeName)){
      integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " Range: B0barB0 : " << integral << std::endl;
    }
    if (isTagInRange(tag_, 0, rangeName)){
      integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " Range: B0barB0 : " << integral << std::endl;
    }
    return integral;
  }
  else{
    if (code == 1){
      double integral = 0.;
      if (hasTagState(tag_, +1)) integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      if (hasTagState(tag_, -1)) integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      if (hasTagState(tag_, 0)) integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " : OS Integral : " << integral << std::endl;
      return integral;
    }
    return 0;
  }

  // OLD: Explicit integrals
  // if (coeff_type_ == kSin){
  //   return +2.0 * production_asym_ * cp_coeff_;
  // }
  // else if (coeff_type_ == kCos){
  //   return -2.0 * production_asym_ * cp_coeff_;
  // }
  // else if (coeff_type_ == kSinh){
  //   return 2.0 * cp_coeff_;
  // }
  // else if (coeff_type_ == kCosh){
  //   return 2.0 * cp_coeff_;
  // }
  // else{
  //   std::printf("ERROR: In %s line %u (%s) : No valid coefficent! \n", __func__, __LINE__, __FILE__);
  //   return 0;
  //   abort();
  // }
}

std::pair<double, double> Coefficient::calibrate(double eta, double avg_eta, double p0, double p1, double delta_p0, double delta_p1) const
{
  double eta_cal = 0;
  double eta_cal_b = 0;
  double eta_cal_bbar = 0;

  // calculate calibrated average eta
  eta_cal = p0 + p1 * ( eta - avg_eta );

  // if eta is larger or equal 0.5 return 0.5
  if (eta >= 0.5){
    eta_cal      = 0.5;
    eta_cal_b    = 0.5;
    eta_cal_bbar = 0.5;
  }
  else{
    // calibrate eta
    eta_cal_b    = p0 + 0.5 * delta_p0 + ( p1 + 0.5 * delta_p1 ) * ( eta - avg_eta );
    eta_cal_bbar = p0 - 0.5 * delta_p0 + ( p1 - 0.5 * delta_p1 ) * ( eta - avg_eta );
  }
  // if calibrated average eta is larger or equal 0.5 return 0.5
  if (eta_cal >= 0.5){
    eta_cal_b    = 0.5;
    eta_cal_bbar = 0.5;
  }
  // if calibrated eta is smaller than 0 return 0
  if (eta_cal_b < 0.0)    eta_cal_b = 0;
  if (eta_cal_bbar < 0.0) eta_cal_bbar = 0;

  // the next few lines set every eta value (avg and high/low from asymmetries) to zero
  // if only one of them is below zero. This seems to introduce a fit bias on our CP
  // observables. (CC)
  // if (eta_cal < 0.0 || eta_cal_b < 0.0 || eta_cal_bbar < 0.0){
  //   eta_cal_b    = 0.0;
  //   eta_cal_bbar = 0.0;
  // }
  return std::make_pair(eta_cal_b, eta_cal_bbar);
}

Double_t Coefficient::evaluate(double cp_coeff,
                               CoeffType coeff_type,
                               int    tag,
                               double eta,
                               double avg_eta,
                               double p0,
                               double p1,
                               double delta_p0,
                               double delta_p1,
                               double production_asym,
                               int    tag_sign) const
{
  // calibrate single tagger
  std::pair<double, double> calibrated_mistag = calibrate(eta, avg_eta, p0, p1, delta_p0, delta_p1);

  double eta_b    = calibrated_mistag.first;
  double eta_bbar = calibrated_mistag.second;

  // calculate coefficients
  if (coeff_type == kSin){
    return -1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );
  }
  else if (coeff_type == kCos){
    return +1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );
  }
  else if (coeff_type == kSinh){
    return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );
  }
  else if (coeff_type == kCosh){
    return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );
  }
  else{
    std::cout << "ERROR\t" << "Coefficient::evaluate(): No valid coefficient type!" << std::endl;
    abort();
  }
}

bool Coefficient::isTagInRange(const RooCategoryProxy& tag, int tag_state, const char* rangeName) const
{
  return dynamic_cast<const RooCategory&>(tag.arg()).isStateInRange(rangeName, tag.arg().lookupType(tag_state)->GetName());
}

bool Coefficient::hasTagState(const RooCategoryProxy& tag, int tag_state) const
{
  return dynamic_cast<const RooCategory&>(tag.arg()).isValidIndex(tag_state);
}

int  Coefficient::getIndex(const RooCategoryProxy& tag) const
{
  return dynamic_cast<const RooCategory&>(tag.arg()).getIndex();
}

} // namespace bdecay
} // namespace functions
} // namespace roofit
} // namespace doofit
<commit_msg>roofit::functions::bdecay::Coefficient: fixed isTagInRange method<commit_after>#include "Riostream.h"

#include "Coefficient.h"
#include "RooAbsReal.h"
#include "RooAbsCategory.h"
#include "RooCategory.h"
#include <math.h>
#include "TMath.h"

ClassImp(doofit::roofit::functions::bdecay::Coefficient)

namespace doofit {
namespace roofit {
namespace functions {
namespace bdecay {

Coefficient::Coefficient(const std::string& name,
                       RooAbsReal& _cp_coeff_,
                       CoeffType   _coeff_type_,
                       RooAbsCategory& _tag_,
                       RooAbsReal& _eta_,
                       RooAbsReal& _avg_eta_,
                       RooAbsReal& _p0_,
                       RooAbsReal& _p1_,
                       RooAbsReal& _delta_p0_,
                       RooAbsReal& _delta_p1_,
                       RooAbsReal& _production_asym_,
                       int         _tag_sign_) :
  RooAbsReal(name.c_str(),name.c_str()),
  cp_coeff_("cp_coeff_","cp_coeff_",this,_cp_coeff_),
  coeff_type_(_coeff_type_),
  tag_("tag_","tag_",this,_tag_),
  eta_("eta_","eta_",this,_eta_),
  avg_eta_("avg_eta_","avg_eta_",this,_avg_eta_),
  p0_("p0_","p0_",this,_p0_),
  p1_("p1_","p1_",this,_p1_),
  delta_p0_("delta_p0_","delta_p0_",this,_delta_p0_),
  delta_p1_("delta_p1_","delta_p1_",this,_delta_p1_),
  production_asym_("production_asym_","production_asym_",this,_production_asym_),
  tag_sign_(_tag_sign_)
{
}

Coefficient::Coefficient(const Coefficient& other, const char* name) :
  RooAbsReal(other,name),
  cp_coeff_("cp_coeff_",this,other.cp_coeff_),
  coeff_type_(other.coeff_type_),
  tag_("tag_",this,other.tag_),
  eta_("eta_",this,other.eta_),
  avg_eta_("avg_eta_",this,other.avg_eta_),
  p0_("p0_",this,other.p0_),
  p1_("p1_",this,other.p1_),
  delta_p0_("delta_p0_",this,other.delta_p0_),
  delta_p1_("delta_p1_",this,other.delta_p1_),
  production_asym_("production_asym_",this,other.production_asym_),
  tag_sign_(other.tag_sign_)
{
}

Double_t Coefficient::evaluate() const
{
  return evaluate(cp_coeff_, coeff_type_, tag_, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
}

Int_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const
{
  // debug
  // std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
  // allVars.Print();

  if (matchArgs(allVars, analVars, tag_)) return 1 ;
  return 0 ;
}

Int_t Coefficient::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* /*rangeName*/) const
{
  // debug
  std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
  allVars.Print();
  if (normSet) normSet->Print();

  if (matchArgs(allVars, analVars, tag_)) return 1 ;
  return 0 ;
}

Double_t Coefficient::analyticalIntegral(Int_t code, const char* rangeName) const
{
  // debug
  // std::printf("CHECK: In %s line %u (%s): Range: %s : Code: %d \n", __func__, __LINE__, __FILE__, rangeName, code);

  // first return analytical integral for defined range
  if (rangeName){
    double integral = 0;
    if (isTagInRange(tag_, +1, rangeName)){
      integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " Range: B0B0 : " << integral << std::endl;
    }
    if (isTagInRange(tag_, -1, rangeName)){
      integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " Range: B0barB0 : " << integral << std::endl;
    }
    if (isTagInRange(tag_, 0, rangeName)){
      integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " Range: B0barB0 : " << integral << std::endl;
    }
    return integral;
  }
  else{
    if (code == 1){
      double integral = 0.;
      if (hasTagState(tag_, +1)) integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      if (hasTagState(tag_, -1)) integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      if (hasTagState(tag_, 0)) integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);
      // debug
      // std::cout << "Coeff: " << coeff_type_ << " : OS Integral : " << integral << std::endl;
      return integral;
    }
    return 0;
  }

  // OLD: Explicit integrals
  // if (coeff_type_ == kSin){
  //   return +2.0 * production_asym_ * cp_coeff_;
  // }
  // else if (coeff_type_ == kCos){
  //   return -2.0 * production_asym_ * cp_coeff_;
  // }
  // else if (coeff_type_ == kSinh){
  //   return 2.0 * cp_coeff_;
  // }
  // else if (coeff_type_ == kCosh){
  //   return 2.0 * cp_coeff_;
  // }
  // else{
  //   std::printf("ERROR: In %s line %u (%s) : No valid coefficent! \n", __func__, __LINE__, __FILE__);
  //   return 0;
  //   abort();
  // }
}

std::pair<double, double> Coefficient::calibrate(double eta, double avg_eta, double p0, double p1, double delta_p0, double delta_p1) const
{
  double eta_cal = 0;
  double eta_cal_b = 0;
  double eta_cal_bbar = 0;

  // calculate calibrated average eta
  eta_cal = p0 + p1 * ( eta - avg_eta );

  // if eta is larger or equal 0.5 return 0.5
  if (eta >= 0.5){
    eta_cal      = 0.5;
    eta_cal_b    = 0.5;
    eta_cal_bbar = 0.5;
  }
  else{
    // calibrate eta
    eta_cal_b    = p0 + 0.5 * delta_p0 + ( p1 + 0.5 * delta_p1 ) * ( eta - avg_eta );
    eta_cal_bbar = p0 - 0.5 * delta_p0 + ( p1 - 0.5 * delta_p1 ) * ( eta - avg_eta );
  }
  // if calibrated average eta is larger or equal 0.5 return 0.5
  if (eta_cal >= 0.5){
    eta_cal_b    = 0.5;
    eta_cal_bbar = 0.5;
  }
  // if calibrated eta is smaller than 0 return 0
  if (eta_cal_b < 0.0)    eta_cal_b = 0;
  if (eta_cal_bbar < 0.0) eta_cal_bbar = 0;

  // the next few lines set every eta value (avg and high/low from asymmetries) to zero
  // if only one of them is below zero. This seems to introduce a fit bias on our CP
  // observables. (CC)
  // if (eta_cal < 0.0 || eta_cal_b < 0.0 || eta_cal_bbar < 0.0){
  //   eta_cal_b    = 0.0;
  //   eta_cal_bbar = 0.0;
  // }
  return std::make_pair(eta_cal_b, eta_cal_bbar);
}

Double_t Coefficient::evaluate(double cp_coeff,
                               CoeffType coeff_type,
                               int    tag,
                               double eta,
                               double avg_eta,
                               double p0,
                               double p1,
                               double delta_p0,
                               double delta_p1,
                               double production_asym,
                               int    tag_sign) const
{
  // calibrate single tagger
  std::pair<double, double> calibrated_mistag = calibrate(eta, avg_eta, p0, p1, delta_p0, delta_p1);

  double eta_b    = calibrated_mistag.first;
  double eta_bbar = calibrated_mistag.second;

  // calculate coefficients
  if (coeff_type == kSin){
    return -1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );
  }
  else if (coeff_type == kCos){
    return +1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );
  }
  else if (coeff_type == kSinh){
    return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );
  }
  else if (coeff_type == kCosh){
    return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );
  }
  else{
    std::cout << "ERROR\t" << "Coefficient::evaluate(): No valid coefficient type!" << std::endl;
    abort();
  }
}

bool Coefficient::isTagInRange(const RooCategoryProxy& tag, int tag_state, const char* rangeName) const
{
  if (tag.arg().lookupType(tag_state) == nullptr){
    return false;
  }
  else{
    return dynamic_cast<const RooCategory&>(tag.arg()).isStateInRange(rangeName, tag.arg().lookupType(tag_state)->GetName());
  }
}

bool Coefficient::hasTagState(const RooCategoryProxy& tag, int tag_state) const
{
  return dynamic_cast<const RooCategory&>(tag.arg()).isValidIndex(tag_state);
}

int  Coefficient::getIndex(const RooCategoryProxy& tag) const
{
  return dynamic_cast<const RooCategory&>(tag.arg()).getIndex();
}

} // namespace bdecay
} // namespace functions
} // namespace roofit
} // namespace doofit
<|endoftext|>


<commit_before>#include <common.hpp>
#include <asset.hpp>
#include <settings.hpp>
#include <chrono>
#include <mutex>

namespace rack {
namespace logger {

static FILE *outputFile = NULL;
static std::chrono::high_resolution_clock::time_point startTime;
static std::mutex logMutex;

void init() {
	startTime = std::chrono::high_resolution_clock::now();
	if (settings::devMode) {
		outputFile = stderr;
	}
	else {
		std::string logFilename = asset::user("log.txt");
		outputFile = fopen(logFilename.c_str(), "w");
	}
}

void destroy() {
	if (outputFile != stderr) {
		fclose(outputFile);
	}
}

static const char* const levelLabels[] = {
	"debug",
	"info",
	"warn",
	"fatal"
};

static const int levelColors[] = {
	35,
	34,
	33,
	31
};

static void logVa(Level level, const char *filename, int line, const char *format, va_list args) {
	std::lock_guard<std::mutex> lock(logMutex);

	auto nowTime = std::chrono::high_resolution_clock::now();
	int duration = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - startTime).count();
	if (outputFile == stderr)
		fprintf(outputFile, "\x1B[%dm", levelColors[level]);
	fprintf(outputFile, "[%.03f %s %s:%d] ", duration / 1000.0, levelLabels[level], filename, line);
	if (outputFile == stderr)
		fprintf(outputFile, "\x1B[0m");
	vfprintf(outputFile, format, args);
	fprintf(outputFile, "\n");
	fflush(outputFile);
}

void log(Level level, const char *filename, int line, const char *format, ...) {
	va_list args;
	va_start(args, format);
	logVa(level, filename, line, format, args);
	va_end(args);
}

} // namespace logger
} // namespace rack
<commit_msg>Add error message to stderr if cannot open log.txt file.<commit_after>#include <common.hpp>
#include <asset.hpp>
#include <settings.hpp>
#include <chrono>
#include <mutex>

namespace rack {
namespace logger {

static FILE *outputFile = NULL;
static std::chrono::high_resolution_clock::time_point startTime;
static std::mutex logMutex;

void init() {
	startTime = std::chrono::high_resolution_clock::now();
	if (settings::devMode) {
		outputFile = stderr;
		return;
	}

	std::string logFilename = asset::user("log.txt");
	outputFile = fopen(logFilename.c_str(), "w");
	if (!outputFile) {
		fprintf(stderr, "Could not open log at %s\n", logFilename.c_str());
	}
}

void destroy() {
	if (outputFile != stderr) {
		fclose(outputFile);
	}
}

static const char* const levelLabels[] = {
	"debug",
	"info",
	"warn",
	"fatal"
};

static const int levelColors[] = {
	35,
	34,
	33,
	31
};

static void logVa(Level level, const char *filename, int line, const char *format, va_list args) {
	std::lock_guard<std::mutex> lock(logMutex);

	auto nowTime = std::chrono::high_resolution_clock::now();
	int duration = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - startTime).count();
	if (outputFile == stderr)
		fprintf(outputFile, "\x1B[%dm", levelColors[level]);
	fprintf(outputFile, "[%.03f %s %s:%d] ", duration / 1000.0, levelLabels[level], filename, line);
	if (outputFile == stderr)
		fprintf(outputFile, "\x1B[0m");
	vfprintf(outputFile, format, args);
	fprintf(outputFile, "\n");
	fflush(outputFile);
}

void log(Level level, const char *filename, int line, const char *format, ...) {
	va_list args;
	va_start(args, format);
	logVa(level, filename, line, format, args);
	va_end(args);
}

} // namespace logger
} // namespace rack
<|endoftext|>


<commit_before>// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: LpubTypes_begin[[SECNUM:[0-9]:]]
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: LpubTypes_end[[SECNUM]]

class G {
public:
  void foo();
};

void G::foo() {
}
<commit_msg>DebugInfo: Remove debug-info-pubtypes.ccp - pubnames/pubtypes are adequately tested in LLVM now.<commit_after><|endoftext|>


<commit_before>#ifndef UVPP_ZSOCK_HPP
#define UVPP_ZSOCK_HPP

#include "uvpp.hpp"

namespace uvpp
{
    class ZsockWatcher
    {
    public:
        ZsockWatcher(Loop& uvloop)
          : m_zsock(nullptr), m_events(0),
            m_prepare(uvloop), m_check(uvloop), m_idle(uvloop),
            m_poll(uvloop)
        {
            m_prepare.set_callback([this](){
                int revents = get_revents(m_zsock, m_events);
                if (revents) {
                    // idle ensures that libuv will not block
                    m_idle.start();
                }
            });

            m_check.set_callback([this](){
                m_idle.stop();
                int revents = get_revents(m_zsock, m_events);
                if (revents) {
                    m_callback();
                }
            });

            m_idle.set_callback([](){});
            m_poll.set_callback([](int status, int events){});
        }

        ZsockWatcher(Loop& uvloop, void *zsock)
          : ZsockWatcher(uvloop)
        {
            init(zsock);
        }

        void init(void *zsock)
        {
            assert(m_zsock==nullptr);

            m_zsock = zsock;

            uv_os_sock_t sockfd;
            size_t optlen = sizeof(sockfd);
            int rc = zmq_getsockopt(zsock, ZMQ_FD, &sockfd, &optlen);
            assert(rc==0);

            m_poll.init(sockfd);
        }

        void set_callback(BasicCallback cb)
        {
            m_callback = cb;
        }

        void start(int events = UV_READABLE)
        {
            assert(m_zsock != nullptr);

            m_events = events;
            m_prepare.start();
            m_check.start();
            m_poll.start(m_events ? UV_READABLE : 0);
        }

        void stop()
        {
            m_prepare.stop();
            m_check.stop();
            m_idle.stop();
            m_poll.stop();
        }

    private:
        int get_revents(void *zsock, int events)
        {
            int revents = 0;

            int zmq_events;
            size_t optlen = sizeof(zmq_events);
            int rc = zmq_getsockopt(zsock, ZMQ_EVENTS, &zmq_events, &optlen);

            if (rc==-1) {
                // on error, make callback get called
                return events;
            }

            if (zmq_events & ZMQ_POLLOUT)
                revents |= events & UV_WRITABLE;
            if (zmq_events & ZMQ_POLLIN)
                revents |= events & UV_READABLE;

            return revents;
        }

    private:
        BasicCallback m_callback;

        void *m_zsock;
        int m_events;
        Prepare m_prepare;
        Check m_check;
        Idle m_idle;
        Poll m_poll;
    };
}

#endif
<commit_msg>implement alternate Zsock watcher<commit_after>#ifndef UVPP_ZSOCK_HPP
#define UVPP_ZSOCK_HPP

#include "uvpp.hpp"

namespace uvpp
{
    class ZsockWatcher
    {
    public:
        ZsockWatcher(Loop& uvloop)
          : m_zsock(nullptr), m_events(0),
            m_prepare(uvloop), m_check(uvloop), m_idle(uvloop),
            m_poll(uvloop)
        {
            m_prepare.set_callback([this](){
                int revents = get_revents(m_zsock, m_events);
                if (revents) {
                    // idle ensures that libuv will not block
                    m_idle.start();
                }
            });

            m_check.set_callback([this](){
                m_idle.stop();
                int revents = get_revents(m_zsock, m_events);
                if (revents) {
                    m_callback();
                }
            });

            m_idle.set_callback([](){});
            m_poll.set_callback([](int status, int events){});
        }

        ZsockWatcher(Loop& uvloop, void *zsock)
          : ZsockWatcher(uvloop)
        {
            init(zsock);
        }

        void init(void *zsock)
        {
            assert(m_zsock==nullptr);

            m_zsock = zsock;

            uv_os_sock_t sockfd;
            size_t optlen = sizeof(sockfd);
            int rc = zmq_getsockopt(zsock, ZMQ_FD, &sockfd, &optlen);
            assert(rc==0);

            m_poll.init(sockfd);
        }

        void set_callback(BasicCallback cb)
        {
            m_callback = cb;
        }

        void start(int events = UV_READABLE)
        {
            assert(m_zsock != nullptr);

            m_events = events;
            m_prepare.start();
            m_check.start();
            m_poll.start(m_events ? UV_READABLE : 0);
        }

        void stop()
        {
            m_prepare.stop();
            m_check.stop();
            m_idle.stop();
            m_poll.stop();
        }

    private:
        int get_revents(void *zsock, int events)
        {
            int revents = 0;

            int zmq_events;
            size_t optlen = sizeof(zmq_events);
            int rc = zmq_getsockopt(zsock, ZMQ_EVENTS, &zmq_events, &optlen);

            if (rc==-1) {
                // on error, make callback get called
                return events;
            }

            if (zmq_events & ZMQ_POLLOUT)
                revents |= events & UV_WRITABLE;
            if (zmq_events & ZMQ_POLLIN)
                revents |= events & UV_READABLE;

            return revents;
        }

    private:
        BasicCallback m_callback;

        void *m_zsock;
        int m_events;
        Prepare m_prepare;
        Check m_check;
        Idle m_idle;
        Poll m_poll;
    };

    // alternate implementation that doesn't use prepare and check watchers.
    // after performing send on this zsock, you need to call Zsock::check()
    class Zsock
    {
    public:
        Zsock(Loop& uvloop)
          : m_zsock(nullptr), m_events(0),
            m_idle(uvloop), m_poll(uvloop)
        {
            m_idle.set_callback([this](){
                int revents = get_revents(m_zsock, m_events);
                if (revents) {
                    m_callback();
                } else {
                    // set level low
                    m_idle.stop();
                }
            });

            m_poll.set_callback([this](int status, int events){
                // set level high
                m_idle.start();
            });
        }

        Zsock(Loop& uvloop, void *zsock)
          : Zsock(uvloop)
        {
            init(zsock);
        }

        void check()
        {
            m_idle.start();
        }

        void init(void *zsock)
        {
            assert(m_zsock==nullptr);

            m_zsock = zsock;

            uv_os_sock_t sockfd;
            size_t optlen = sizeof(sockfd);
            int rc = zmq_getsockopt(zsock, ZMQ_FD, &sockfd, &optlen);
            assert(rc==0);

            m_poll.init(sockfd);
        }

        void set_callback(BasicCallback cb)
        {
            m_callback = cb;
        }

        void start(int events = UV_READABLE)
        {
            assert(m_zsock != nullptr);

            m_events = events;
            m_poll.start(m_events ? UV_READABLE : 0);
        }

        void stop()
        {
            m_idle.stop();
            m_poll.stop();
        }

    private:
        int get_revents(void *zsock, int events)
        {
            int revents = 0;

            int zmq_events;
            size_t optlen = sizeof(zmq_events);
            int rc = zmq_getsockopt(zsock, ZMQ_EVENTS, &zmq_events, &optlen);

            if (rc==-1) {
                // on error, make callback get called
                return events;
            }

            if (zmq_events & ZMQ_POLLOUT)
                revents |= events & UV_WRITABLE;
            if (zmq_events & ZMQ_POLLIN)
                revents |= events & UV_READABLE;

            return revents;
        }

    private:
        BasicCallback m_callback;

        void *m_zsock;
        int m_events;
        Idle m_idle;
        Poll m_poll;
    };
}

#endif
<|endoftext|>


<commit_before>#include "../include/pixkit-ml.hpp"

using namespace std;

double Euclidean_Distance(const vector<double>& v1, const vector<double>& v2){
	assert(v1.size() == v2.size());
	double ret = 0.0;
	for (vector<double>::size_type i = 0; i != v1.size(); ++i){
		ret += (v1[i] - v2[i]) * (v1[i] - v2[i]);
	}
	return sqrt(ret);
}
void DistanceMatrix(std::vector<vector<double> >& dm, const std::vector<pixkit::classification::SSample> &dataset,const std::vector<pixkit::classification::SSample> &sample){
	for ( vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i){
		vector<double> DM_data;
		for (vector<pixkit::classification::SSample>::size_type j = 0; j != dataset.size(); ++j){
			DM_data.push_back(Euclidean_Distance(sample[i].features, dataset[j].features));
		}
		dm.push_back(DM_data);
	}
}
vector<double> kappa_Matrix(const vector<double>& v1, const vector<double>& v2, vector<double>& kappa)
{
	assert(v1.size() == v2.size()); //featureƥn@P test[i].features.size()

	for (vector<double>::size_type i = 0; i != v1.size(); ++i)
	{
		kappa[i] +=sqrt((v1[i] - v2[i]) * (v1[i] - v2[i])) ;
	}

	return (kappa);

}

void BandwidthMatrix(vector<vector<double> >& Bw, const vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset)
{

	for (vector<pixkit::classification::SSample>::size_type i = 0; i !=sample.size(); ++i)
	{
		vector<double> kappa_data,kappa(sample[i].features.size());

		for (vector<pixkit::classification::SSample>::size_type j = 0; j != dataset.size(); ++j)
		{

			kappa_data=kappa_Matrix(sample[i].features, dataset[j].features,kappa);

		}

		Bw.push_back(kappa_data);

	}

}

void Tradition_KNN_Process(vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset, const vector<vector<double> >& dm, unsigned int k){
	for (vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i){
		multimap<double, string> dts;
		for (vector<double>::size_type j = 0; j != dm[i].size(); ++j){
			if (dts.size() < k){
				dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
			}else{
				multimap<double, string>::iterator it = dts.end();
				--it;
				if (dm[i][j] < (it->first)){
					dts.erase(it);
					dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
				}
			}
		}
		map<string, double> tds;
		string type = "";
		double weight = 0.0;
		for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit){
			++tds[cit->second];
			if (tds[cit->second] > weight){
				weight = tds[cit->second];
				type = cit->second;
			}
		}
		for (map<string, double>::const_iterator cit = tds.begin(); cit != tds.end(); ++cit){
			cout<<cit->first <<"="<<cit->second<<'\n'<<endl;
		}
		sample[i].classnumber = type;
		cout<<"Result Class = "<<sample[i].classnumber<<'\n'<<endl;
		cout<<"=============================================="<<endl;
	}
}

void FKNN_Process(vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset, const vector<vector<double> >& dm, unsigned int k)
{
	for (vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i)
	{
		multimap<double, string> dts;
		for (vector<double>::size_type j = 0; j != dm[i].size(); ++j)
		{
			if (dts.size() < k )
			{
				dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
			}
			else
			{
				multimap<double, string>::iterator it = dts.end();
				--it;
				if (dm[i][j] < (it->first))
				{
					dts.erase(it);
					dts.insert(make_pair(dm[i][j], dataset[j].classnumber));

				}
			}
		}
		map<string, double> tds,fin;
		string type = "";
		double weight = 0.0;
		double now_weight = 0.0;
		double total_weight= 0.0;
		for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)
		{

			if (cit->first==0)
			{
				tds[cit->second] += 1.0 / (cit->first+1);
				total_weight=total_weight+(1.0 / (cit->first+1));

			}else{

				tds[cit->second] += 1.0 / cit->first;
				total_weight=total_weight+(1.0 / (cit->first));
			}

		}

		for (map<string, double>::const_iterator cit = tds.begin(); cit != tds.end(); ++cit)
		{

			now_weight=(cit->second/total_weight);

			if (now_weight > weight)
			{
				weight = now_weight;
				type = cit->first;

			}

		}

		sample[i].classnumber = type;
		cout<<"Result Class = "<<sample[i].classnumber<<'\n'<<endl;
		cout<<"=============================================="<<endl;
	}

}

void FRNN_Process(vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset, const vector<vector<double> >& dm,const vector<vector<double> >& Bw)
{
	for (vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i)
	{
		multimap<double, string> dts,dist,dist1;
		map<string, double> tds,fin,merbership,countnmber;

		for (vector<double>::size_type k = 0; k != dm[i].size(); ++k)
		{
			dist.insert(make_pair(dm[i][k], dataset[k].classnumber));

		}

		for (vector<double>::size_type j = 0; j != dataset.size(); ++j)
		{
			double d=0.0;
			for (vector<double>::size_type x = 0; x != Bw[i].size(); ++x)
			{
				if (Bw[i][x]==0)
				{
					d+=(dataset.size()/(2))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);

				}else{

					d+=(dataset.size()/(2*Bw[i][x]))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);

				}
			}
			dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
			d=d+(1/dataset.size())*exp(-d);

			for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)
			{

				if (cit->first==0)
				{
					tds[cit->second] += 1.0 / (cit->first+1);

				}else{

					tds[cit->second] += 1.0 / cit->first;
				}

			}
		}

		string type = "";
		double weight = 0.0;

		for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)
		{

			tds[cit->second] += cit->first;

			if (1/tds[cit->second] > weight)
			{
				weight = 1/tds[cit->second];
				type = cit->second;

			}

		}

		sample[i].classnumber = type;
		cout<<"Result Class = "<<sample[i].classnumber<<'\n'<<endl;
		cout<<"=============================================="<<endl;
	}

}

bool pixkit::classification::KNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset,int k){

	//////////////////////////////////////////////////////////////////////////
	/////
	if(k<0){
		CV_Error(CV_StsBadArg,"[pixkit::classification::KNN] k should >= 1.");
	}

	vector<vector<double> > DM;
    DistanceMatrix(DM, dataset, sample);
	Tradition_KNN_Process(sample, dataset, DM, k);

	return	true;
}

bool pixkit::classification::FKNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset,int k){

	//////////////////////////////////////////////////////////////////////////
	/////
	if(k<0){
		CV_Error(CV_StsBadArg,"[pixkit::classification::KNN] k should >= 1.");
	}

	vector<vector<double> > DM;
	DistanceMatrix(DM, dataset, sample);
	FKNN_Process(sample, dataset, DM, k);

	return	true;
}

bool pixkit::classification::FRNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset){

	//////////////////////////////////////////////////////////////////////////
	/////

	vector<vector<double> > DM,Bw;
	DistanceMatrix(DM, dataset, sample);
	BandwidthMatrix(Bw, dataset, sample);
	FRNN_Process(sample, dataset, DM,Bw);

	return	true;
}<commit_msg>那個沒是我自己的東西~<commit_after>#include "../include/pixkit-ml.hpp"

using namespace std;

double Euclidean_Distance(const vector<double>& v1, const vector<double>& v2){
	assert(v1.size() == v2.size());
	double ret = 0.0;
	for (vector<double>::size_type i = 0; i != v1.size(); ++i){
		ret += (v1[i] - v2[i]) * (v1[i] - v2[i]);
	}
	return sqrt(ret);
}
void DistanceMatrix(std::vector<vector<double> >& dm, const std::vector<pixkit::classification::SSample> &dataset,const std::vector<pixkit::classification::SSample> &sample){
	for ( vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i){
		vector<double> DM_data;
		for (vector<pixkit::classification::SSample>::size_type j = 0; j != dataset.size(); ++j){
			DM_data.push_back(Euclidean_Distance(sample[i].features, dataset[j].features));
		}
		dm.push_back(DM_data);
	}
}
vector<double> kappa_Matrix(const vector<double>& v1, const vector<double>& v2, vector<double>& kappa)
{
	assert(v1.size() == v2.size());

	for (vector<double>::size_type i = 0; i != v1.size(); ++i)
	{
		kappa[i] +=sqrt((v1[i] - v2[i]) * (v1[i] - v2[i])) ;
	}

	return (kappa);

}

void BandwidthMatrix(vector<vector<double> >& Bw, const vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset)
{

	for (vector<pixkit::classification::SSample>::size_type i = 0; i !=sample.size(); ++i)
	{
		vector<double> kappa_data,kappa(sample[i].features.size());

		for (vector<pixkit::classification::SSample>::size_type j = 0; j != dataset.size(); ++j)
		{

			kappa_data=kappa_Matrix(sample[i].features, dataset[j].features,kappa);

		}

		Bw.push_back(kappa_data);

	}

}

void Tradition_KNN_Process(vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset, const vector<vector<double> >& dm, unsigned int k){
	for (vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i){
		multimap<double, string> dts;
		for (vector<double>::size_type j = 0; j != dm[i].size(); ++j){
			if (dts.size() < k){
				dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
			}else{
				multimap<double, string>::iterator it = dts.end();
				--it;
				if (dm[i][j] < (it->first)){
					dts.erase(it);
					dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
				}
			}
		}
		map<string, double> tds;
		string type = "";
		double weight = 0.0;
		for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit){
			++tds[cit->second];
			if (tds[cit->second] > weight){
				weight = tds[cit->second];
				type = cit->second;
			}
		}
		for (map<string, double>::const_iterator cit = tds.begin(); cit != tds.end(); ++cit){
			cout<<cit->first <<"="<<cit->second<<'\n'<<endl;
		}
		sample[i].classnumber = type;
		cout<<"Result Class = "<<sample[i].classnumber<<'\n'<<endl;
		cout<<"=============================================="<<endl;
	}
}

void FKNN_Process(vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset, const vector<vector<double> >& dm, unsigned int k)
{
	for (vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i)
	{
		multimap<double, string> dts;
		for (vector<double>::size_type j = 0; j != dm[i].size(); ++j)
		{
			if (dts.size() < k )
			{
				dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
			}
			else
			{
				multimap<double, string>::iterator it = dts.end();
				--it;
				if (dm[i][j] < (it->first))
				{
					dts.erase(it);
					dts.insert(make_pair(dm[i][j], dataset[j].classnumber));

				}
			}
		}
		map<string, double> tds,fin;
		string type = "";
		double weight = 0.0;
		double now_weight = 0.0;
		double total_weight= 0.0;
		for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)
		{

			if (cit->first==0)
			{
				tds[cit->second] += 1.0 / (cit->first+1);
				total_weight=total_weight+(1.0 / (cit->first+1));

			}else{

				tds[cit->second] += 1.0 / cit->first;
				total_weight=total_weight+(1.0 / (cit->first));
			}

		}

		for (map<string, double>::const_iterator cit = tds.begin(); cit != tds.end(); ++cit)
		{

			now_weight=(cit->second/total_weight);

			if (now_weight > weight)
			{
				weight = now_weight;
				type = cit->first;

			}

		}

		sample[i].classnumber = type;
		cout<<"Result Class = "<<sample[i].classnumber<<'\n'<<endl;
		cout<<"=============================================="<<endl;
	}

}

void FRNN_Process(vector<pixkit::classification::SSample>& sample, const vector<pixkit::classification::SSample>& dataset, const vector<vector<double> >& dm,const vector<vector<double> >& Bw)
{
	for (vector<pixkit::classification::SSample>::size_type i = 0; i != sample.size(); ++i)
	{
		multimap<double, string> dts,dist,dist1;
		map<string, double> tds,fin,merbership,countnmber;

		for (vector<double>::size_type k = 0; k != dm[i].size(); ++k)
		{
			dist.insert(make_pair(dm[i][k], dataset[k].classnumber));

		}

		for (vector<double>::size_type j = 0; j != dataset.size(); ++j)
		{
			double d=0.0;
			for (vector<double>::size_type x = 0; x != Bw[i].size(); ++x)
			{
				if (Bw[i][x]==0)
				{
					d+=(dataset.size()/(2))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);

				}else{

					d+=(dataset.size()/(2*Bw[i][x]))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);

				}
			}
			dts.insert(make_pair(dm[i][j], dataset[j].classnumber));
			d=d+(1/dataset.size())*exp(-d);

			for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)
			{

				if (cit->first==0)
				{
					tds[cit->second] += 1.0 / (cit->first+1);

				}else{

					tds[cit->second] += 1.0 / cit->first;
				}

			}
		}

		string type = "";
		double weight = 0.0;

		for (multimap<double, string>::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)
		{

			tds[cit->second] += cit->first;

			if (1/tds[cit->second] > weight)
			{
				weight = 1/tds[cit->second];
				type = cit->second;

			}

		}

		sample[i].classnumber = type;
		cout<<"Result Class = "<<sample[i].classnumber<<'\n'<<endl;
		cout<<"=============================================="<<endl;
	}

}

bool pixkit::classification::KNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset,int k){

	//////////////////////////////////////////////////////////////////////////
	/////
	if(k<0){
		CV_Error(CV_StsBadArg,"[pixkit::classification::KNN] k should >= 1.");
	}

	vector<vector<double> > DM;
    DistanceMatrix(DM, dataset, sample);
	Tradition_KNN_Process(sample, dataset, DM, k);

	return	true;
}

bool pixkit::classification::FKNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset,int k){

	//////////////////////////////////////////////////////////////////////////
	/////
	if(k<0){
		CV_Error(CV_StsBadArg,"[pixkit::classification::KNN] k should >= 1.");
	}

	vector<vector<double> > DM;
	DistanceMatrix(DM, dataset, sample);
	FKNN_Process(sample, dataset, DM, k);

	return	true;
}

bool pixkit::classification::FRNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset){

	//////////////////////////////////////////////////////////////////////////
	/////

	vector<vector<double> > DM,Bw;
	DistanceMatrix(DM, dataset, sample);
	BandwidthMatrix(Bw, dataset, sample);
	FRNN_Process(sample, dataset, DM,Bw);

	return	true;
}<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2015 Nrupatunga

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.
*/

#include <string>
#include <iostream>
#include <opencv2\opencv.hpp>
#include <CannyED.hpp>
#include <vld.h>

#pragma comment(lib, "opencv_core300d.lib") // core functionalities
#pragma comment(lib, "opencv_highgui300d.lib") //GUI
#pragma comment(lib, "opencv_imgcodecs300d.lib")
#pragma comment(lib, "opencv_imgproc300d.lib") // Histograms, Edge detection
#pragma comment(lib, "opencv_video300d.lib")
#pragma comment(lib, "opencv_videoio300d.lib")

using namespace cv;
using namespace std;

#define PI (3.1412)

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:
 * =====================================================================================
 */

int main ( int argc, char *argv[] )
{
	 Mat sMatInput = imread("..\\flower.jpg", IMREAD_GRAYSCALE);
	 Mat sMatOutput;

	 String strWinIn = "Input";
	 String strWinOut = "Output";

	 CannyED(sMatInput, sMatOutput, 10, 40);
	 namedWindow(strWinIn, WINDOW_NORMAL);
	 namedWindow(strWinOut, WINDOW_NORMAL);
	 imshow(strWinIn, sMatInput);
	 imshow(strWinOut, sMatOutput);
	 waitKey(0);
	return EXIT_SUCCESS;

} /* ----------  end of function main  ---------- */

<commit_msg>removing unused code from main.cpp<commit_after>/*
The MIT License (MIT)

Copyright (c) 2015 Nrupatunga

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.
*/

#include <string>
#include <iostream>
#include <opencv2\opencv.hpp>
#include <CannyED.hpp>

#pragma comment(lib, "opencv_core300d.lib") // core functionalities
#pragma comment(lib, "opencv_highgui300d.lib") //GUI
#pragma comment(lib, "opencv_imgcodecs300d.lib")
#pragma comment(lib, "opencv_imgproc300d.lib") // Histograms, Edge detection

using namespace cv;
using namespace std;

#define PI (3.1412)

/*
* ===  FUNCTION  ======================================================================
*         Name:  main
*  Description:
* =====================================================================================
*/

int main ( int argc, char *argv[] )
{
	Mat sMatInput = imread("..\\flower.jpg", IMREAD_GRAYSCALE);
	Mat sMatOutput;

	String strWinIn = "Input";
	String strWinOut = "Output";

	CannyED(sMatInput, sMatOutput, 10, 40);
	namedWindow(strWinIn, WINDOW_NORMAL);
	namedWindow(strWinOut, WINDOW_NORMAL);
	imshow(strWinIn, sMatInput);
	imshow(strWinOut, sMatOutput);

	imwrite("Input.jpg", sMatInput);
	imwrite("OutputEdge.jpg", sMatOutput);
	waitKey(0);
	return EXIT_SUCCESS;

} /* ----------  end of function main  ---------- */

<|endoftext|>


<commit_before>
#include "cmdline/cmdline.h"
#include "mhap/overlap.h"
#include "mhap/parser.h"
#include "ra/include/ra/ra.hpp"
#include <algorithm>
#include <ctime>
#include <fstream>
#include <iostream>
#include <vector>
#include <sys/stat.h>

// trimming params
int READ_LEN_THRESHOLD = 100000;
uint32_t MAX_READS_IN_TIP = 2;
uint32_t MAX_DEPTH_WITHOUT_EXTRA_FORK = 5;

// BFS params in bubble popping
size_t MAX_NODES = 2000;
int MAX_DISTANCE = MAX_NODES * 10000;
double MAX_DIFFERENCE = 0.25;

// contig extraction params
size_t MAX_BRANCHES = 18;
size_t MAX_START_NODES = 100;
double LENGTH_THRESHOLD = 0.2;
double QUALITY_THRESHOLD = 0.2;

// filter reads param
size_t READS_MIN_LEN = 3000;

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;

// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {

  int max_id = -1;
  for (auto r: reads) {
    max_id = max(max_id, r->getId());
  }

  mapped->resize(max_id + 1, nullptr);
  for (auto r: reads) {
    (*mapped)[r->getId()] = r;
  }
}

string output_dir_name() {
  time_t rawtime;
  struct tm* timeinfo;
  char buffer[80];

  time(&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer, 80, "layout_%Y%m%d_%H%M%S", timeinfo);
  return string(buffer);
}

void must_mkdir(const string& path) {
    if (mkdir(path.c_str(), 0755) == -1) {
        fprintf(stderr, "Can't create directory %s\n", path.c_str());
        exit(1);
    }
}

void print_contigs_info(const vector<Contig *>& contigs, const vector<Read*>& reads) {

  for (uint32_t i = 0; i < contigs.size(); ++i) {
    const auto& contig = contigs[i];
    const auto& parts = contig->getParts();
    const auto& last_part = contig->getParts().back();

    fprintf(stdout, "contig %u; length: ≈%lu, reads: %lu\n",
        i, last_part.offset + reads[last_part.src]->getLength(), parts.size()
    );
    for (const auto& p: parts) {
      fprintf(stdout, "%d ", p.src);
    }
    fprintf(stdout, "\n");
  }
}

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

  cmdline::parser args;

  // input params
  args.add<string>("reads", 'r', "reads file", true);
  args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta");
  args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0);
  args.add<string>("overlaps", 'x', "overlaps file", true);
  args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");

  args.add<bool>("verbose", 'v', "verbose output", false);

  // bubble popping params
  args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750);
  args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25);

  args.parse_check(argc, argv);

  const int thread_num = std::max(std::thread::hardware_concurrency(), 1U);
  const string reads_filename = args.get<string>("reads");
  const string reads_format = args.get<string>("reads_format");
  const string overlaps_filename = args.get<string>("overlaps");
  const string overlaps_format = args.get<string>("overlaps_format");
  const bool verbose_output = args.get<bool>("verbose");
  const int reads_id_offset = args.get<int>("reads_id_offset");
  const string output_dir = output_dir_name();

  MAX_NODES = args.get<int>("bp_max_nodes");
  MAX_DISTANCE = MAX_NODES * 10000;
  MAX_DIFFERENCE = args.get<double>("bp_max_diff");

  vector<Overlap*> overlaps, filtered;
  vector<Read*> reads;
  vector<Read*> reads_mapped;

  must_mkdir(output_dir);
  std::cerr << "Output dir: " << output_dir << std::endl;

  if (reads_format == "fasta") {
    readFastaReads(reads, reads_filename.c_str());
  } else if (reads_format == "fastq") {
    readFastqReads(reads, reads_filename.c_str());
  } else if (reads_format == "afg") {
    readAfgReads(reads, reads_filename.c_str());
  } else {
    assert(false);
  }

  // map reads so we have reads_mapped[read_id] -> read
  map_reads(&reads_mapped, reads);

  std::cerr << "Read " << reads.size() << " reads" << std::endl;

  if (overlaps_format == "afg") {
    readAfgOverlaps(overlaps, overlaps_filename.c_str());
  } else if (overlaps_format == "mhap") {
    fstream overlaps_file(overlaps_filename);
    MHAP::read_overlaps(overlaps_file, &overlaps);
    overlaps_file.close();
  } else {
    assert(false);
  }

  // fix overlap read ids
  for (auto o: overlaps) {
    o->setA(o->getA() - reads_id_offset);
    o->setB(o->getB() - reads_id_offset);
  }

  for (auto o: overlaps) {
    const auto a = o->getA();
    const auto b = o->getB();
    if (reads_mapped[a] == nullptr) {
      cerr << "Read " << a << " not found" << endl;
      exit(1);
    }
    if (reads_mapped[b] == nullptr) {
      cerr << "Read " << b << " not found" << endl;
      exit(1);
    }

    o->setReadA(reads_mapped[a]);
    o->setReadB(reads_mapped[b]);
  }

  cerr << overlaps.size() << " overlaps read" << endl;

  int skipped = 0;
  for (uint32_t i = 0; i < overlaps.size(); ++i) {
    const auto o = overlaps[i];

    if (o->getReadA()->getLength() < READS_MIN_LEN || o->getReadB()->getLength() < READS_MIN_LEN) {
      skipped++;
      continue;
    }

    overlaps[i - skipped] = overlaps[i];
  }
  overlaps.resize(overlaps.size() - skipped);

  vector<Overlap*> nocontainments;
  filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);

  if (verbose_output) {
    writeOverlaps(nocontainments, (output_dir + "/nocont.afg").c_str());
  }

  vector<Overlap*> notransitives;
  filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);

  if (verbose_output) {
    writeOverlaps(notransitives, (output_dir + "/nocont.notran.afg").c_str());
  }

  createReverseComplements(reads, thread_num);

  StringGraph* graph = new StringGraph(reads, notransitives);
  graph->simplify();

  if (verbose_output) {
    vector<Overlap*> simplified_overlaps;
    graph->extractOverlaps(simplified_overlaps);
    writeOverlaps(simplified_overlaps, (output_dir + "/simplified.afg").c_str());
  }

  std::vector<StringGraphComponent*> components;
  graph->extractComponents(components);

  std::vector<Contig*> contigs;

  auto contigs_fast = fopen((output_dir + "/contigs_fast.fasta").c_str(), "w");
  int idx = 0;
  for (const auto& component : components) {
    string seq;
    component->extractSequence(seq);
    fprintf(contigs_fast, ">seq%d\n", idx);
    fprintf(contigs_fast, "%s\n", seq.c_str());
    idx++;

    ContigExtractor* extractor = new ContigExtractor(component);
    const auto& contig = extractor->extractContig();

    if (contig == nullptr) {
      continue;
    }

    contigs.emplace_back(contig);
  }
  fclose(contigs_fast);

  std::cerr << "number of contigs " << contigs.size() << std::endl;
  print_contigs_info(contigs, reads_mapped);

  writeAfgContigs(contigs, (output_dir + "/contigs.afg").c_str());

  for (auto r: reads)      delete r;
  for (auto o: overlaps)   delete o;
  for (auto c: components) delete c;
  for (auto c: contigs)    delete c;

  delete graph;

  return 0;
}
<commit_msg>add writing settings file to output directory (resolves #12)<commit_after>
#include "cmdline/cmdline.h"
#include "mhap/overlap.h"
#include "mhap/parser.h"
#include "ra/include/ra/ra.hpp"
#include <algorithm>
#include <ctime>
#include <fstream>
#include <iostream>
#include <vector>
#include <sys/stat.h>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;

// trimming params
int READ_LEN_THRESHOLD = 100000;
uint32_t MAX_READS_IN_TIP = 2;
uint32_t MAX_DEPTH_WITHOUT_EXTRA_FORK = 5;

// BFS params in bubble popping
size_t MAX_NODES = 2000;
int MAX_DISTANCE = MAX_NODES * 10000;
double MAX_DIFFERENCE = 0.25;

// contig extraction params
size_t MAX_BRANCHES = 18;
size_t MAX_START_NODES = 100;
double LENGTH_THRESHOLD = 0.2;
double QUALITY_THRESHOLD = 0.2;

// filter reads param
size_t READS_MIN_LEN = 3000;

// global vars
cmdline::parser args;
int thread_num;
string reads_filename;
string reads_format;
string overlaps_filename;
string overlaps_format;
bool verbose_output;
int reads_id_offset;

// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {

  int max_id = -1;
  for (auto r: reads) {
    max_id = max(max_id, r->getId());
  }

  mapped->resize(max_id + 1, nullptr);
  for (auto r: reads) {
    (*mapped)[r->getId()] = r;
  }
}

string output_dir_name() {
  time_t rawtime;
  struct tm* timeinfo;
  char buffer[80];

  time(&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer, 80, "layout_%Y%m%d_%H%M%S", timeinfo);
  return string(buffer);
}

void must_mkdir(const string& path) {
    if (mkdir(path.c_str(), 0755) == -1) {
        fprintf(stderr, "Can't create directory %s\n", path.c_str());
        exit(1);
    }
}

void print_contigs_info(const vector<Contig *>& contigs, const vector<Read*>& reads) {

  for (uint32_t i = 0; i < contigs.size(); ++i) {
    const auto& contig = contigs[i];
    const auto& parts = contig->getParts();
    const auto& last_part = contig->getParts().back();

    fprintf(stdout, "contig %u; length: ≈%lu, reads: %lu\n",
        i, last_part.offset + reads[last_part.src]->getLength(), parts.size()
    );
    for (const auto& p: parts) {
      fprintf(stdout, "%d ", p.src);
    }
    fprintf(stdout, "\n");
  }
}

void init_args(int argc, char** argv) {
  // input params
  args.add<string>("reads", 'r', "reads file", true);
  args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta");
  args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0);
  args.add<string>("overlaps", 'x', "overlaps file", true);
  args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");

  args.add<bool>("verbose", 'v', "verbose output", false);

  // bubble popping params
  args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750);
  args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25);

  args.parse_check(argc, argv);
}

void read_args() {
  thread_num = std::max(std::thread::hardware_concurrency(), 1U);
  reads_filename = args.get<string>("reads");
  reads_format = args.get<string>("reads_format");
  overlaps_filename = args.get<string>("overlaps");
  overlaps_format = args.get<string>("overlaps_format");
  verbose_output = args.get<bool>("verbose");
  reads_id_offset = args.get<int>("reads_id_offset");

  MAX_NODES = args.get<int>("bp_max_nodes");
  MAX_DISTANCE = MAX_NODES * 10000;
  MAX_DIFFERENCE = args.get<double>("bp_max_diff");
}

FILE* must_fopen(const char* path, const char* mode) {
  FILE* res = fopen(path, mode);
  if (res == nullptr) {
    fprintf(stderr, "Cannot open %s with mode %s\n", path, mode);
    exit(1);
  }

  return res;
}

void write_settings(FILE *fd) {
  fprintf(fd, "# filter reads parameters\n");
  fprintf(fd, "READS_MIN_LEN: %lu\n", READS_MIN_LEN);
  fprintf(fd, "\n");

  fprintf(fd, "# trimming parameters\n");
  fprintf(fd, "READ_LEN_THRESHOLD: %d\n", READ_LEN_THRESHOLD);
  fprintf(fd, "MAX_READS_IN_TIP: %d\n", MAX_READS_IN_TIP);
  fprintf(fd, "MAX_DEPTH_WITHOUT_EXTRA_FORK: %d\n", MAX_DEPTH_WITHOUT_EXTRA_FORK);
  fprintf(fd, "\n");

  fprintf(fd, "# bubble popping parameters\n");
  fprintf(fd, "MAX_NODES: %lu\n", MAX_NODES);
  fprintf(fd, "MAX_DISTANCE: %d\n", MAX_DISTANCE);
  fprintf(fd, "MAX_DIFFERENCE: %f\n", MAX_DIFFERENCE);
  fprintf(fd, "\n");

  fprintf(fd, "# contig extraction parameters\n");
  fprintf(fd, "MAX_BRANCHES: %lu\n", MAX_BRANCHES);
  fprintf(fd, "MAX_START_NODES: %lu\n", MAX_START_NODES);
  fprintf(fd, "LENGTH_THRESHOLD: %f\n", LENGTH_THRESHOLD);
  fprintf(fd, "QUALITY_THRESHOLD: %f\n", QUALITY_THRESHOLD);
  fprintf(fd, "\n");
}

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

  init_args(argc, argv);
  read_args();

  string output_dir = output_dir_name();

  must_mkdir(output_dir);
  std::cerr << "Output dir: " << output_dir << std::endl;

  auto settings_file = must_fopen((output_dir + "/run_args.txt").c_str(), "w");
  write_settings(settings_file);
  fclose(settings_file);

  vector<Overlap*> overlaps, filtered;
  vector<Read*> reads;
  vector<Read*> reads_mapped;

  if (reads_format == "fasta") {
    readFastaReads(reads, reads_filename.c_str());
  } else if (reads_format == "fastq") {
    readFastqReads(reads, reads_filename.c_str());
  } else if (reads_format == "afg") {
    readAfgReads(reads, reads_filename.c_str());
  } else {
    assert(false);
  }

  // map reads so we have reads_mapped[read_id] -> read
  map_reads(&reads_mapped, reads);

  std::cerr << "Read " << reads.size() << " reads" << std::endl;

  if (overlaps_format == "afg") {
    readAfgOverlaps(overlaps, overlaps_filename.c_str());
  } else if (overlaps_format == "mhap") {
    fstream overlaps_file(overlaps_filename);
    MHAP::read_overlaps(overlaps_file, &overlaps);
    overlaps_file.close();
  } else {
    assert(false);
  }

  // fix overlap read ids
  for (auto o: overlaps) {
    o->setA(o->getA() - reads_id_offset);
    o->setB(o->getB() - reads_id_offset);
  }

  for (auto o: overlaps) {
    const auto a = o->getA();
    const auto b = o->getB();
    if (reads_mapped[a] == nullptr) {
      cerr << "Read " << a << " not found" << endl;
      exit(1);
    }
    if (reads_mapped[b] == nullptr) {
      cerr << "Read " << b << " not found" << endl;
      exit(1);
    }

    o->setReadA(reads_mapped[a]);
    o->setReadB(reads_mapped[b]);
  }

  cerr << overlaps.size() << " overlaps read" << endl;

  int skipped = 0;
  for (uint32_t i = 0; i < overlaps.size(); ++i) {
    const auto o = overlaps[i];

    if (o->getReadA()->getLength() < READS_MIN_LEN || o->getReadB()->getLength() < READS_MIN_LEN) {
      skipped++;
      continue;
    }

    overlaps[i - skipped] = overlaps[i];
  }
  overlaps.resize(overlaps.size() - skipped);

  vector<Overlap*> nocontainments;
  filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);

  if (verbose_output) {
    writeOverlaps(nocontainments, (output_dir + "/nocont.afg").c_str());
  }

  vector<Overlap*> notransitives;
  filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);

  if (verbose_output) {
    writeOverlaps(notransitives, (output_dir + "/nocont.notran.afg").c_str());
  }

  createReverseComplements(reads, thread_num);

  StringGraph* graph = new StringGraph(reads, notransitives);
  graph->simplify();

  if (verbose_output) {
    vector<Overlap*> simplified_overlaps;
    graph->extractOverlaps(simplified_overlaps);
    writeOverlaps(simplified_overlaps, (output_dir + "/simplified.afg").c_str());
  }

  std::vector<StringGraphComponent*> components;
  graph->extractComponents(components);

  std::vector<Contig*> contigs;

  auto contigs_fast = must_fopen((output_dir + "/contigs_fast.fasta").c_str(), "w");
  int idx = 0;
  for (const auto& component : components) {
    string seq;
    component->extractSequence(seq);
    fprintf(contigs_fast, ">seq%d\n", idx);
    fprintf(contigs_fast, "%s\n", seq.c_str());
    idx++;

    ContigExtractor* extractor = new ContigExtractor(component);
    const auto& contig = extractor->extractContig();

    if (contig == nullptr) {
      continue;
    }

    contigs.emplace_back(contig);
  }
  fclose(contigs_fast);

  std::cerr << "number of contigs " << contigs.size() << std::endl;
  print_contigs_info(contigs, reads_mapped);

  writeAfgContigs(contigs, (output_dir + "/contigs.afg").c_str());

  for (auto r: reads)      delete r;
  for (auto o: overlaps)   delete o;
  for (auto c: components) delete c;
  for (auto c: contigs)    delete c;

  delete graph;

  return 0;
}
<|endoftext|>