<commit_before>#ifdef _DEBUG
#include <iostream>
#include <boost/format.hpp>
#endif

#include <vector>
#include <algorithm>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <data_type.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/adjacent.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/yrange5.hpp>
#include <gui.hpp>

// 2値座標系式から1値座標系式に変えながら和
// 指定した範囲の配列の和を返す
int yrange5::array_sum(return_type const& array_, int const x, int const y, int const height, int const width) const
{
	int sum = 0;
	for (int i = 0; i<height; ++i)
	{
		for (int j = 0; j < width; ++j)
		{
			auto const& target_point = array_[y + i][x + j];
			if (target_point.x == std::numeric_limits<int>::max() && target_point.y == std::numeric_limits<int>::max()) return -1;
			auto const point = target_point.y * width + target_point.x;
			sum += (point > 1000) ? 777 : point;
		}
	}
	return sum;
}

/*縦列単位で入れ替え*/
void yrange5::column_replacement(answer_type_y & answer)
{
	int const sepx = data_.split_num.first;
	int const sepy = data_.split_num.second;
	uint_fast64_t good_val;
	std::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));
	good_matrix = answer.points;
	good_val = form_evaluate(data_,comp_, good_matrix);

	for (int i = 0; i < sepx; ++i){
		for (int j = 0; j < sepy; ++j){
			answer.points[j].insert(answer.points[j].begin(), answer.points[j][sepx - 1]);
			answer.points[j].pop_back();
		}
		auto const temp_score = form_evaluate(data_,comp_, answer.points);
		if (good_val>temp_score){
			good_val = temp_score;
			good_matrix = answer.points;
		}
	}
	answer.points = good_matrix;
	answer.score = good_val;
}

/*横列単位で入れ替え*/
void yrange5::row_replacement(answer_type_y& answer)
{
	int const sepx = data_.split_num.first;
	int const sepy = data_.split_num.second;
	uint_fast64_t good_val;
	std::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));
	std::vector<point_type> temp_vec;
	good_matrix = answer.points;
	good_val = form_evaluate(data_,comp_, answer.points);
	for (int i = 0; i < sepy; ++i){
		answer.points.insert(answer.points.begin(), answer.points[sepy - 1]);
		answer.points.pop_back();
		auto const temp_score = form_evaluate(data_,comp_, answer.points);
		if (good_val>temp_score){
			good_val = temp_score;
			good_matrix = answer.points;
		}
	}
	answer.points = good_matrix;
	answer.score = good_val;
}

//cv::matの塊にする
cv::Mat yrange5::combine_image(answer_type_y const& answer)
{
	int const one_picx = data_.size.first / data_.split_num.first;
	int const one_picy = data_.size.second / data_.split_num.second;

	splitter sp;//どこからか持ってきてたsplitter
	split_image_type splitted = sp.split_image(data_);
	cv::Mat comb_pic(cv::Size(data_.size.first, data_.size.second), CV_8UC3);
	for (int i = 0; i < data_.split_num.second; ++i){
		for (int j = 0; j < data_.split_num.first; ++j){
			cv::Rect roi_rect(j*one_picx, i*one_picy, one_picx, one_picy);
			cv::Mat roi_mat(comb_pic, roi_rect);
			splitted[answer.points[i][j].y][answer.points[i][j].x].copyTo(roi_mat);
		}
	}
	return std::move(comb_pic.clone());
}

yrange5::yrange5(question_raw_data const& data, compared_type const& comp)
    : data_(data), comp_(comp), adjacent_data_(select_minimum(comp))
{
}

std::vector<answer_type_y> yrange5::operator() (std::vector<std::vector<std::vector<point_type>>> const& mother_matrix)
{
	auto const width = data_.split_num.first;
	auto const height = data_.split_num.second;
	constexpr int paramerter = 50;

	auto const exists = [height, width](point_type const& p)
	{
		return 0 <= p.x && p.x < width && 0 <= p.y && p.y < height;
	};

	std::vector<kind_rgb>kind_rgb_vector(width*height);
	std::vector<answer_type_y> to_iddfs;//kid_rgbで選考したもの入れとく
	std::vector<answer_type_y> answer;
	answer.reserve(height*width * 2);
	splitter sp;

	for (int c = 0; c < mother_matrix.size(); ++c)
	{
		//kind_rgb選考
		for (int i = 0; i < height; i++)	for (int j = 0; j < width; j++){
			kind_rgb_vector[j * height + i].x = j;
			kind_rgb_vector[j * height + i].y = i;
			kind_rgb_vector[j * height + i].kind = get_kind_num(data_, mother_matrix.at(c), j, i);
			kind_rgb_vector[j * height + i].score = (width*height - kind_rgb_vector[j * height + i].kind + 1) * range_evaluate(data_, comp_, mother_matrix.at(c), j, i);
		}
	}

	std::sort(kind_rgb_vector.begin(), kind_rgb_vector.end());

	for (int k = 0; k < kind_rgb_vector.size() / paramerter; k++)
	{
		std::vector<std::vector <point_type>> ans_temp2;
		for (int i = 0; i < height; ++i)
		{
			std::vector<point_type>ans_temp1;
			for (int j = 0; j < width; ++j)
			{
				ans_temp1.push_back(mother_matrix.at(k)[kind_rgb_vector[k].y + i][kind_rgb_vector[k].x + j]);
			}
			ans_temp2.push_back(ans_temp1);
		}
		to_iddfs.push_back(answer_type_y{ ans_temp2, 0, cv::Mat() });
	}

	//yrange5メインループ
	for (auto& matrix : to_iddfs)
	{
		//重複して入っているもののうち，悪い方を{width,height}に置き換え,今使われていないものを返す
		std::vector<point_type> usable = std::move(duplicate_delete(comp_, matrix.points));
		//gui::combine_show_image(data_, comp_, matrix.points);
		//It's show time!
		for (int i = 0; i < height; ++i)for (int j = 0; j < width; ++j)
		{
			std::vector<std::vector<point_type>> sorted_matrix(height, std::vector<point_type>(width, point_type{ width, height }));
			//全部並べ切れたら
			if (!try_matrix_copy(sorted_matrix, matrix.points, point_type{ j, i }))
			{
				//抜けてるところを並べていく
				point_type const invalid_val = { width, height };
				int const u_height = (height % 2 == 0) ? height / 2 + 1 : height / 2;
				int const r_width = width / 2;
				int const d_height = height / 2;
				int const l_width = (width % 2 == 0) ? height / 2 + 1 : width / 2;

				//上に見ていく
				for (int i = 0; i < height - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[height - 1 - i][width / 2];
					auto      & target = sorted_matrix[height - 2 - i][width / 2];
					if (target == invalid_val && adjacent != invalid_val) target = u_choose(comp_, adjacent, usable);
				}
				//下に見ていく
				for (int i = 0; i < height - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[i][width / 2];
					auto      & target = sorted_matrix[i + 1][width / 2];
					if (target == invalid_val && adjacent != invalid_val) target = d_choose(comp_, adjacent, usable);
				}
				//右に見ていく
				for (int i = 0; i < width - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[height / 2][i];
					auto      & target = sorted_matrix[height / 2][i + 1];
					if (target == invalid_val && adjacent != invalid_val) target = r_choose(comp_, adjacent, usable);
				}
				//左に見ていく
				for (int i = 0; i < width - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[height / 2][width - 1 - i];
					auto      & target = sorted_matrix[height / 2][width - 2 - i];
					if (target == invalid_val && adjacent != invalid_val) target = l_choose(comp_, adjacent, usable);
				}

				//中心を除き上に向かってループ，右に見ていく
				for (int i = 0; i < u_height - 1; ++i) for (int j = 0; j < r_width - 1; ++j)
				{
					auto      & target = sorted_matrix[height / 2 - 1 - i][width / 2 + 1 + j];
					auto const& center = sorted_matrix[height / 2 - i][width / 2 + j];
					auto const& upper = sorted_matrix[height / 2 - i - 1][width / 2 + j];
					auto const& right = sorted_matrix[height / 2 - i][width / 2 + j + 1];

					if (target == invalid_val && (exists(center) && exists(upper) && exists(right)))
						target = ur_choose(comp_, upper, center, right, usable);
				}
				//中心を除き上に向かってループ，左に見ていく
				for (int i = 0; i < u_height - 1; ++i) for (int j = 0; j < l_width - 1; ++j)
				{
					auto      & target = sorted_matrix[height / 2 - i - 1][width / 2 - j - 1];
					auto const& center = sorted_matrix[height / 2 - i][width / 2 - j];
					auto const& upper = sorted_matrix[height / 2 - i - 1][width / 2 - j];
					auto const& left = sorted_matrix[height / 2 - i][width / 2 - j - 1];

					if (target == invalid_val && (exists(center) && exists(upper) && exists(left)))
						target = ul_choose(comp_, upper, left, center, usable);
				}
				//中心を除き下に向かってループ，右に見ていく
				for (int i = 0; i < d_height - 1; ++i) for (int j = 0; j < r_width - 1; ++j)
				{
					auto	  & target = sorted_matrix[height / 2 + i + 1][width / 2 + j + 1];
					auto const& center = sorted_matrix[height / 2 + i][width / 2 + j];
					auto const& lower = sorted_matrix[height / 2 + i + 1][width / 2 + j];
					auto const& right = sorted_matrix[height / 2 + i][width / 2 + j + 1];

					if (target == invalid_val && (exists(center) && exists(lower) && exists(right)))
						target = dr_choose(comp_, center, right, lower, usable);
				}
				//中心を除き下に向かってループ，左に見ていく
				for (int i = 0; i < d_height - 1; ++i) for (int j = 0; j < l_width - 1; ++j)
				{
					auto      & target = sorted_matrix[height / 2 + i + 1][width / 2 - j - 1];
					auto const& center = sorted_matrix[height / 2 + i][width / 2 - j];
					auto const& lower = sorted_matrix[height / 2 + i + 1][width / 2 - j];
					auto const& left = sorted_matrix[height / 2 + i][width / 2 - j - 1];

					if (target == invalid_val && (exists(center) && exists(lower) && exists(left)))
						target = dl_choose(comp_, left, center, lower, usable);
				}
				//gui::combine_show_image(data_, comp_, sorted_matrix);
				if (array_sum(sorted_matrix, 0, 0, height, width) == ((width*height - 1)*(width*height) / 2) && get_kind_num(data_, sorted_matrix, 0, 0) == width*height)
				{
					answer.push_back(answer_type_y{ sorted_matrix, 0, cv::Mat() });
				}
			}
		}

		//現段階で重複しているものは1つに絞る
		// unique()を使う準備としてソートが必要
		std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
		// unique()をしただけでは後ろにゴミが残るので、eraseで削除する
		answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

		//縦入れ替え，横入れ替え
		for (auto &matrix : answer){
			row_replacement(matrix);
			column_replacement(matrix);
			row_replacement(matrix);
		}

		//もっかいやっとく
		std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
		answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

		//無駄に多く返してもしょうがないので枝抜き
		size_t yrange5_ans = answer.size();
		std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.score < b.score; });
		if (answer.size() >= 8) answer.resize(8);

		//一枚のcv::Matにする
		for (auto& one_answer : answer)
		{
			one_answer.mat_image = std::move(combine_image(one_answer));
		}

#ifdef _DEBUG
		std::cout << "There are " << /*yrange5_ans <<*/ " solutions by yrange5." << std::endl;
		for (auto const& one_answer : answer)
		{
			for (int i = 0; i < one_answer.points.size(); ++i)
			{
				for (int j = 0; j < one_answer.points.at(0).size(); ++j)
				{
					auto const& data = one_answer.points[i][j];
					std::cout << boost::format("(%2d,%2d) ") % data.x % data.y;
				}
				std::cout << "\n";
			}
			std::cout << "score = " << one_answer.score << std::endl;
		}
		gui::show_image(data_, comp_, answer);
#endif
		return answer;
	}
}

<commit_msg>openmp対応<commit_after>#ifdef _DEBUG
#include <iostream>
#include <boost/format.hpp>
#endif

#include <vector>
#include <algorithm>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <data_type.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/adjacent.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/yrange5.hpp>
#include <gui.hpp>

// 2値座標系式から1値座標系式に変えながら和
// 指定した範囲の配列の和を返す
int yrange5::array_sum(return_type const& array_, int const x, int const y, int const height, int const width) const
{
	int sum = 0;
	for (int i = 0; i<height; ++i)
	{
		for (int j = 0; j < width; ++j)
		{
			auto const& target_point = array_[y + i][x + j];
			if (target_point.x == std::numeric_limits<int>::max() && target_point.y == std::numeric_limits<int>::max()) return -1;
			auto const point = target_point.y * width + target_point.x;
			sum += (point > 1000) ? 777 : point;
		}
	}
	return sum;
}

//cv::matの塊にする
cv::Mat yrange5::combine_image(answer_type_y const& answer)
{
	int const one_picx = data_.size.first / data_.split_num.first;
	int const one_picy = data_.size.second / data_.split_num.second;

	splitter sp;//どこからか持ってきてたsplitter
	split_image_type splitted = sp.split_image(data_);
	cv::Mat comb_pic(cv::Size(data_.size.first, data_.size.second), CV_8UC3);
	for (int i = 0; i < data_.split_num.second; ++i){
		for (int j = 0; j < data_.split_num.first; ++j){
			cv::Rect roi_rect(j*one_picx, i*one_picy, one_picx, one_picy);
			cv::Mat roi_mat(comb_pic, roi_rect);
			splitted[answer.points[i][j].y][answer.points[i][j].x].copyTo(roi_mat);
		}
	}
	return std::move(comb_pic.clone());
}

yrange5::yrange5(question_raw_data const& data, compared_type const& comp)
    : data_(data), comp_(comp), adjacent_data_(select_minimum(comp))
{
}

std::vector<answer_type_y> yrange5::operator() (std::vector<std::vector<std::vector<point_type>>> const& mother_matrix)
{
	auto const width = data_.split_num.first;
	auto const height = data_.split_num.second;
	constexpr int paramerter = 50;

	auto const exists = [height, width](point_type const& p)
	{
		return 0 <= p.x && p.x < width && 0 <= p.y && p.y < height;
	};

	std::vector<kind_rgb>kind_rgb_vector(width*height);
	std::vector<answer_type_y> to_iddfs;//kid_rgbで選考したもの入れとく
	std::vector<answer_type_y> answer;
	answer.reserve(height*width * 2);
	splitter sp;

#pragma omp parallel for
	for (int c = 0; c < mother_matrix.size(); ++c)
	{
		//kind_rgb選考
		for (int i = 0; i < height; i++)	for (int j = 0; j < width; j++){
			kind_rgb_vector[j * height + i].x = j;
			kind_rgb_vector[j * height + i].y = i;
			kind_rgb_vector[j * height + i].kind = get_kind_num(data_, mother_matrix.at(c), j, i);
			kind_rgb_vector[j * height + i].score = (width*height - kind_rgb_vector[j * height + i].kind + 1) * range_evaluate(data_, comp_, mother_matrix.at(c), j, i);
		}
	}

	std::sort(kind_rgb_vector.begin(), kind_rgb_vector.end());

	for (int k = 0; k < kind_rgb_vector.size() / paramerter; k++)
	{
		std::vector<std::vector <point_type>> ans_temp2;
		for (int i = 0; i < height; ++i)
		{
			std::vector<point_type>ans_temp1;
			for (int j = 0; j < width; ++j)
			{
				ans_temp1.push_back(mother_matrix.at(k)[kind_rgb_vector[k].y + i][kind_rgb_vector[k].x + j]);
			}
			ans_temp2.push_back(ans_temp1);
		}
		to_iddfs.push_back(answer_type_y{ ans_temp2, 0, cv::Mat() });
	}

	//yrange5メインループ
#pragma omp parallel for
	for (int c = 0; c < to_iddfs.size(); ++c)
	{
		//重複して入っているもののうち，悪い方を{width,height}に置き換え,今使われていないものを返す
		std::vector<point_type> usable = std::move(duplicate_delete(comp_, to_iddfs.at(c).points));
		//It's show time!
		for (int i = 0; i < height; ++i)for (int j = 0; j < width; ++j)
		{
			std::vector<std::vector<point_type>> sorted_matrix(height, std::vector<point_type>(width, point_type{ width, height }));
			//全部並べ切れたら
			if (!try_matrix_copy(sorted_matrix, to_iddfs.at(c).points, point_type{ j, i }))
			{
				//抜けてるところを並べていく
				point_type const invalid_val = { width, height };
				int const u_height = (height % 2 == 0) ? height / 2 + 1 : height / 2;
				int const r_width = width / 2;
				int const d_height = height / 2;
				int const l_width = (width % 2 == 0) ? height / 2 + 1 : width / 2;

				//上に見ていく
				for (int i = 0; i < height - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[height - 1 - i][width / 2];
					auto      & target = sorted_matrix[height - 2 - i][width / 2];
					if (target == invalid_val && adjacent != invalid_val) target = u_choose(comp_, adjacent, usable);
				}
				//下に見ていく
				for (int i = 0; i < height - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[i][width / 2];
					auto      & target = sorted_matrix[i + 1][width / 2];
					if (target == invalid_val && adjacent != invalid_val) target = d_choose(comp_, adjacent, usable);
				}
				//右に見ていく
				for (int i = 0; i < width - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[height / 2][i];
					auto      & target = sorted_matrix[height / 2][i + 1];
					if (target == invalid_val && adjacent != invalid_val) target = r_choose(comp_, adjacent, usable);
				}
				//左に見ていく
				for (int i = 0; i < width - 1; ++i)
				{
					auto const& adjacent = sorted_matrix[height / 2][width - 1 - i];
					auto      & target = sorted_matrix[height / 2][width - 2 - i];
					if (target == invalid_val && adjacent != invalid_val) target = l_choose(comp_, adjacent, usable);
				}

				//中心を除き上に向かってループ，右に見ていく
				for (int i = 0; i < u_height - 1; ++i) for (int j = 0; j < r_width - 1; ++j)
				{
					auto      & target = sorted_matrix[height / 2 - 1 - i][width / 2 + 1 + j];
					auto const& center = sorted_matrix[height / 2 - i][width / 2 + j];
					auto const& upper = sorted_matrix[height / 2 - i - 1][width / 2 + j];
					auto const& right = sorted_matrix[height / 2 - i][width / 2 + j + 1];

					if (target == invalid_val && (exists(center) && exists(upper) && exists(right)))
						target = ur_choose(comp_, upper, center, right, usable);
				}
				//中心を除き上に向かってループ，左に見ていく
				for (int i = 0; i < u_height - 1; ++i) for (int j = 0; j < l_width - 1; ++j)
				{
					auto      & target = sorted_matrix[height / 2 - i - 1][width / 2 - j - 1];
					auto const& center = sorted_matrix[height / 2 - i][width / 2 - j];
					auto const& upper = sorted_matrix[height / 2 - i - 1][width / 2 - j];
					auto const& left = sorted_matrix[height / 2 - i][width / 2 - j - 1];

					if (target == invalid_val && (exists(center) && exists(upper) && exists(left)))
						target = ul_choose(comp_, upper, left, center, usable);
				}
				//中心を除き下に向かってループ，右に見ていく
				for (int i = 0; i < d_height - 1; ++i) for (int j = 0; j < r_width - 1; ++j)
				{
					auto	  & target = sorted_matrix[height / 2 + i + 1][width / 2 + j + 1];
					auto const& center = sorted_matrix[height / 2 + i][width / 2 + j];
					auto const& lower = sorted_matrix[height / 2 + i + 1][width / 2 + j];
					auto const& right = sorted_matrix[height / 2 + i][width / 2 + j + 1];

					if (target == invalid_val && (exists(center) && exists(lower) && exists(right)))
						target = dr_choose(comp_, center, right, lower, usable);
				}
				//中心を除き下に向かってループ，左に見ていく
				for (int i = 0; i < d_height - 1; ++i) for (int j = 0; j < l_width - 1; ++j)
				{
					auto      & target = sorted_matrix[height / 2 + i + 1][width / 2 - j - 1];
					auto const& center = sorted_matrix[height / 2 + i][width / 2 - j];
					auto const& lower = sorted_matrix[height / 2 + i + 1][width / 2 - j];
					auto const& left = sorted_matrix[height / 2 + i][width / 2 - j - 1];

					if (target == invalid_val && (exists(center) && exists(lower) && exists(left)))
						target = dl_choose(comp_, left, center, lower, usable);
				}
				//gui::combine_show_image(data_, comp_, sorted_matrix);
				if (array_sum(sorted_matrix, 0, 0, height, width) == ((width*height - 1)*(width*height) / 2) && get_kind_num(data_, sorted_matrix, 0, 0) == width*height)
				{
					answer.push_back(answer_type_y{ sorted_matrix, 0, cv::Mat() });
				}
			}
		}
	}

	//現段階で重複しているものは1つに絞る
	// unique()を使う準備としてソートが必要
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
	// unique()をしただけでは後ろにゴミが残るので、eraseで削除する
	answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

	//無駄に多く返してもしょうがないので枝抜き
	size_t yrange5_ans = answer.size();
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.score < b.score; });
	if (answer.size() >= 8) answer.resize(8);

	//一枚のcv::Matにする
	for (auto& one_answer : answer)
	{
		one_answer.mat_image = std::move(combine_image(one_answer));
	}

#ifdef _DEBUG
	std::cout << "There are " << /*yrange5_ans <<*/ " solutions by yrange5." << std::endl;
	for (auto const& one_answer : answer)
	{
		for (int i = 0; i < one_answer.points.size(); ++i)
		{
			for (int j = 0; j < one_answer.points.at(0).size(); ++j)
			{
				auto const& data = one_answer.points[i][j];
				std::cout << boost::format("(%2d,%2d) ") % data.x % data.y;
			}
			std::cout << "\n";
		}
		std::cout << "score = " << one_answer.score << std::endl;
	}
	gui::show_image(data_, comp_, answer);
#endif
	return answer;
}
<|endoftext|>


<commit_before><commit_msg>Change some logging for better debugging of abandoned streams.<commit_after><|endoftext|>


<commit_before>#include <Ice/Ice.h>
#include <IceUtil/Thread.h>

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#include "Solver.h"

extern "C" {
#include "backend.h"
#include "log.h"
#include "fitsioutils.h"
#include "ioutils.h"
}

using namespace std;
using namespace SolverIce;

class SolverI : public Solver {
public:
	SolverI(const string& progname, int scale);

	int init();

    virtual Fileset solve(const string& jobid,
						 const Filedata& axy,
						 const LoggerPrx& logger,
						 bool& solved,
						  string& errmsg,
						 const ::Ice::Current& current);

    virtual void cancel(const string& jobid,
						const ::Ice::Current& current);

    virtual string status(const ::Ice::Current& current);

    virtual void shutdown(const ::Ice::Current& current);

private:
	string configfn;
	backend_t* backend;
};

// FIXME - this should be a class static in SolverI
map<string, string> solverdirs;

SolverI::SolverI(const string& progname, int scale) {
	cout << "Solver constructor: name " << progname << ", scale " << scale << endl;

	char configfnbuf[256];
	sprintf(configfnbuf, "/data1/dstn/dsolver/backend-config/backend-scale%i.cfg", scale);

	configfn = string(configfnbuf);
	cout << "Using config file " << configfn << endl;

	backend = backend_new();
	log_init((log_level)3);
	log_set_thread_specific();
	fits_use_error_system();
}

int SolverI::init() {
	if (backend_parse_config_file(backend, configfn.c_str())) {
		cout << "ERROR parsing config file" << endl;
		return -1;
	}
}

string SolverI::status(const ::Ice::Current& current) {
	cout << "status() called." << endl;
	return "A-OK";
}

class LogMessagePiper : public IceUtil::Thread {
public:
	LogMessagePiper(int therpipe, const LoggerPrx& thelogger) {
		quitNow = false;
		rpipe = therpipe;
		logger = thelogger;
		logger->logmessage("Hello from LogMessagePiper.\n");
	}

	virtual void run() {
		for (;;) {
			char buf[1024];
			int nread;
			if (quitNow) {
				break;
			}
			nread = read(rpipe, buf, sizeof(buf));
			if (nread == 0) {
				cout << "Hit end-of-file on log message pipe." << endl;
				break;
			}
			if (nread == -1) {
				cout << "Error reading from log message pipe: " << strerror(errno) << endl;
				break;
			}
			//cout << "Read " << nread << " bytes from log message pipe." << endl;
			//cout << "Sending to remote logger..." << endl;
			string logstr = string(buf, nread);
			logger->logmessage(logstr);
			//cout << "Sent to remote logger." << endl;
			sleep(1);
		}
		cout << "log message piper finished." << endl;
    }

	void quit() {
		quitNow = true;
	}

private:
	int rpipe;
	LoggerPrx logger;
	bool quitNow;
};

Fileset SolverI::solve(const string& jobid,
					   const Filedata& axy,
					   const LoggerPrx& logger,
					   bool& solved,
					   string& errmsg,
					   const ::Ice::Current& current) {
	cout << "solve() called." << endl;
	cout << "  jobid = " << jobid << endl;

	Fileset fs;
	solved = false;
	errmsg = string();

	int Naxy = axy.size();
	unsigned char* axydata = new unsigned char[Naxy];
	for (int i=0; i<Naxy; i++)
		axydata[i] = axy[i];

	cout << "axy is " << Naxy << " bytes" << endl;

	char* tempdir = "/tmp";

	char templ[256];
	sprintf(templ, "%s/backend-%s-XXXXXX", tempdir, jobid.c_str());
	char* mydir = mkdtemp(templ);

	solverdirs[jobid] = string(mydir);

	string cancelfn = string(mydir) + "/cancel";
	string axyfn = string(mydir) + "/job.axy";
	FILE* f = fopen(axyfn.c_str(), "wb");
	if ((fwrite(axydata, 1, Naxy, f) != Naxy) ||
		fclose(f)) {
		cout << "Failed to write axy data to file " << axyfn << endl;
		errmsg = "failed to write axy data";
		return fs;
	}
	cout << "Wrote axyfn = " << axyfn << endl;

	delete(axydata);

	int pipes[2];
	if (pipe(pipes)) {
		cout << "Error creating pipe for log messages." << endl;
		errmsg = "Error creating pipe for log messages.";
		return fs;
	}
	/*
	 long flags = fcntl(pipes[0], F_GETFL);
	 if (fcntl(pipes[0], F_SETFL, flags | O_NONBLOCK)) {
	 cout << "Failed to set read pipe non-blocking.\n" << endl;
	 }
	 */
	log_to_fd(pipes[1]);

	LogMessagePiper* t = new LogMessagePiper(pipes[0], logger);
	IceUtil::ThreadControl tc = t->start();

	job_t* job = backend_read_job_file(backend, axyfn.c_str());
	if (!job) {
		cout << "Failed to read job file " << axyfn << endl;
		errmsg = "failed to read job file";
		return fs;
	}

	job_set_base_dir(job, mydir);
	job_set_cancel_file(job, cancelfn.c_str());

	cout << "backend_run_job()" << endl;
	backend_run_job(backend, job);
	cout << "backend_run_job() done!" << endl;

	solverdirs.erase(jobid);

	job_free(job);

	cout << "cleaning up logging thread..." << endl;
	log_to(stdout);

	if (t->isAlive()) {
		t->quit();
	}

	// Read output files.
	sl* outfiles = dir_get_contents(mydir, NULL, TRUE, TRUE);
	for (int i=0; i<sl_size(outfiles); i++) {
		char* path = sl_get(outfiles, i);
		size_t len;
		unsigned char* data = (unsigned char*)file_get_contents(path, &len, FALSE);
		char* name = basename_safe(path);
		if (streq(name, "wcs.fits")) {
			solved = true;
		}
		if (streq(name, "job.axy")) {
			free(name);
			continue;
		}
		if (!data) {
			cout << "Failed to read output file " << path << endl;
			errmsg = "failed to read output file";
			return fs;
		}
		Filedata fd;
		for (size_t j=0; j<len; j++) {
			Ice::Byte ib = data[j];
			fd.push_back(ib);
		}

		File f;
		f.name = string(name);
		f.data = fd;
		fs.push_back(f);

		free(name);
		free(data);
	}
	sl_free2(outfiles);

	return fs;
}

void SolverI::cancel(const string& jobid,
					 const ::Ice::Current& current) {
	cout << "cancel(jobid=" << jobid << ") called." << endl;
	map<string,string>::iterator it = solverdirs.find(jobid);
	if (it == solverdirs.end()) {
		cout << "jobid " << jobid << " not found." << endl;
	}
	string dir = it->second;
	cout << "directory: " << dir << endl;
	string cancelfn = dir + "/cancel";
	FILE* f = fopen(cancelfn.c_str(), "w");
	if (!f || fclose(f)) {
		cout << "Failed to write cancel file: " << cancelfn << ":" << strerror(errno) << endl;
		return;
	}
	cout << "Wrote cancel file " << cancelfn << endl;
}

void SolverI::shutdown(const ::Ice::Current& current) {
	cout << "shutdown() called." << endl;
}

class Server : virtual public Ice::Application {
public:
    virtual int run(int argc, char* args[]) {
		cout << "run() called." << endl;
		cout << "Args:" << endl;
		for (int i=0; i<argc; i++)
			cout << "  " << args[i] << endl;

		if (argc != 2) {
			cout << "Need one arg: index scale." << endl;
			return -1;
		}

		int scale = atoi(args[1]);

		Ice::CommunicatorPtr ic = this->communicator();
		Ice::PropertiesPtr props = ic->getProperties();
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapter("OneSolver");
		string idstr = props->getProperty("Identity");
		Ice::Identity myid = ic->stringToIdentity(idstr);
		string progname = props->getProperty("Ice.ProgramName");
		cout << "Creating solver..." << endl;
		SolverI* si = new SolverI(progname, scale);
		cout << "Reading config file..." << endl;
		if (si->init()) {
			cout << "Error reading config file." << endl;
			return -1;
		}
		SolverPtr solver = si;
		adapter->add(solver, myid);
		cout << "Activating adapter..." << endl;
		adapter->activate();
		cout << "Running!" << endl;
		ic->waitForShutdown();
		return 0;
		/*
		 Ice::ObjectAdapterPtr adapter
		 = ic->createObjectAdapterWithEndpoints
		 ("SimplePrinterAdapter", "default -p 10000");
		 Ice::ObjectPtr object = new SolverI;
		 adapter->add(object,
		 ic->stringToIdentity("SimplePrinter"));
		 adapter->activate();
		 return 0;
		 */
    }
};

int main(int argc, char* argv[]) {
    cout << "SolverServer starting.  Command-line args:" << endl;
	for (int i=0; i<argc; i++)
		cout << "  " << argv[i] << endl;

    Server s;
    return s.main(argc, argv);
}

/*
	int status = 0;
    Ice::CommunicatorPtr ic;
    try {
        ic = Ice::initialize(argc, argv);
        Ice::ObjectAdapterPtr adapter
            = ic->createObjectAdapterWithEndpoints(
                "SimplePrinterAdapter", "default -p 10000");
        Ice::ObjectPtr object = new SolverI;
        adapter->add(object,
                     ic->stringToIdentity("SimplePrinter"));
        adapter->activate();
        ic->waitForShutdown();
    } catch (const Ice::Exception& e) {
        cerr << e << endl;
        status = 1;
    } catch (const char* msg) {
        cerr << msg << endl;
        status = 1;
    }
    if (ic) {
        try {
            ic->destroy();
        } catch (const Ice::Exception& e) {
            cerr << e << endl;
            status = 1;
        }
    }
    return status;
}

 */
<commit_msg>catch exceptions in log message piper.<commit_after>#include <Ice/Ice.h>
#include <IceUtil/Thread.h>

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#include "Solver.h"

extern "C" {
#include "backend.h"
#include "log.h"
#include "fitsioutils.h"
#include "ioutils.h"
}

using namespace std;
using namespace SolverIce;

class SolverI : public Solver {
public:
	SolverI(const string& progname, int scale);

	int init();

    virtual Fileset solve(const string& jobid,
						 const Filedata& axy,
						 const LoggerPrx& logger,
						 bool& solved,
						  string& errmsg,
						 const ::Ice::Current& current);

    virtual void cancel(const string& jobid,
						const ::Ice::Current& current);

    virtual string status(const ::Ice::Current& current);

    virtual void shutdown(const ::Ice::Current& current);

private:
	string configfn;
	backend_t* backend;
};

// FIXME - this should be a class static in SolverI
map<string, string> solverdirs;

SolverI::SolverI(const string& progname, int scale) {
	cout << "Solver constructor: name " << progname << ", scale " << scale << endl;

	char configfnbuf[256];
	sprintf(configfnbuf, "/data1/dstn/dsolver/backend-config/backend-scale%i.cfg", scale);

	configfn = string(configfnbuf);
	cout << "Using config file " << configfn << endl;

	backend = backend_new();
	log_init((log_level)3);
	log_set_thread_specific();
	fits_use_error_system();
}

int SolverI::init() {
	if (backend_parse_config_file(backend, configfn.c_str())) {
		cout << "ERROR parsing config file" << endl;
		return -1;
	}
}

string SolverI::status(const ::Ice::Current& current) {
	cout << "status() called." << endl;
	return "A-OK";
}

class LogMessagePiper : public IceUtil::Thread {
public:
	LogMessagePiper(int therpipe, const LoggerPrx& thelogger) {
		quitNow = false;
		rpipe = therpipe;
		logger = thelogger;
		//logger->logmessage("Hello from LogMessagePiper.\n");
	}

	virtual void run() {
		try {
			for (;;) {
				char buf[1024];
				int nread;
				if (quitNow) {
					break;
				}
				nread = read(rpipe, buf, sizeof(buf));
				if (nread == 0) {
					cout << "Hit end-of-file on log message pipe." << endl;
					break;
				}
				if (nread == -1) {
					cout << "Error reading from log message pipe: " << strerror(errno) << endl;
					break;
				}
				//cout << "Read " << nread << " bytes from log message pipe." << endl;
				//cout << "Sending to remote logger..." << endl;
				string logstr = string(buf, nread);
				try {
					logger->logmessage(logstr);
				} catch (Ice::ConnectionRefusedException cre) {
					cout << "Remote logger connection refused.  Logger quitting." << endl;
					break;
				}
				//cout << "Sent to remote logger." << endl;
				sleep(1);
			}
		} catch (...) {
			cout << "log message piper: caught generic exception." << endl;
		}
		cout << "log message piper finished." << endl;
    }

	void quit() {
		quitNow = true;
	}

private:
	int rpipe;
	LoggerPrx logger;
	bool quitNow;
};

Fileset SolverI::solve(const string& jobid,
					   const Filedata& axy,
					   const LoggerPrx& logger,
					   bool& solved,
					   string& errmsg,
					   const ::Ice::Current& current) {
	cout << "solve() called." << endl;
	cout << "  jobid = " << jobid << endl;

	Fileset fs;
	solved = false;
	errmsg = string();

	int Naxy = axy.size();
	unsigned char* axydata = new unsigned char[Naxy];
	for (int i=0; i<Naxy; i++)
		axydata[i] = axy[i];

	cout << "axy is " << Naxy << " bytes" << endl;

	char* tempdir = "/tmp";

	char templ[256];
	sprintf(templ, "%s/backend-%s-XXXXXX", tempdir, jobid.c_str());
	char* mydir = mkdtemp(templ);

	solverdirs[jobid] = string(mydir);

	string cancelfn = string(mydir) + "/cancel";
	string axyfn = string(mydir) + "/job.axy";
	FILE* f = fopen(axyfn.c_str(), "wb");
	if ((fwrite(axydata, 1, Naxy, f) != Naxy) ||
		fclose(f)) {
		cout << "Failed to write axy data to file " << axyfn << endl;
		errmsg = "failed to write axy data";
		return fs;
	}
	cout << "Wrote axyfn = " << axyfn << endl;

	delete(axydata);

	int pipes[2];
	if (pipe(pipes)) {
		cout << "Error creating pipe for log messages." << endl;
		errmsg = "Error creating pipe for log messages.";
		return fs;
	}
	/*
	 long flags = fcntl(pipes[0], F_GETFL);
	 if (fcntl(pipes[0], F_SETFL, flags | O_NONBLOCK)) {
	 cout << "Failed to set read pipe non-blocking.\n" << endl;
	 }
	 */
	log_to_fd(pipes[1]);

	LogMessagePiper* t = new LogMessagePiper(pipes[0], logger);
	IceUtil::ThreadControl tc = t->start();

	job_t* job = backend_read_job_file(backend, axyfn.c_str());
	if (!job) {
		cout << "Failed to read job file " << axyfn << endl;
		errmsg = "failed to read job file";
		return fs;
	}

	job_set_base_dir(job, mydir);
	job_set_cancel_file(job, cancelfn.c_str());

	cout << "backend_run_job()" << endl;
	backend_run_job(backend, job);
	cout << "backend_run_job() done!" << endl;

	solverdirs.erase(jobid);

	job_free(job);

	cout << "cleaning up logging thread..." << endl;
	log_to(stdout);

	if (t->isAlive()) {
		t->quit();
	}

	// Read output files.
	sl* outfiles = dir_get_contents(mydir, NULL, TRUE, TRUE);
	for (int i=0; i<sl_size(outfiles); i++) {
		char* path = sl_get(outfiles, i);
		size_t len;
		unsigned char* data = (unsigned char*)file_get_contents(path, &len, FALSE);
		char* name = basename_safe(path);
		if (streq(name, "wcs.fits")) {
			solved = true;
		}
		if (streq(name, "job.axy")) {
			free(name);
			continue;
		}
		if (!data) {
			cout << "Failed to read output file " << path << endl;
			errmsg = "failed to read output file";
			return fs;
		}
		Filedata fd;
		for (size_t j=0; j<len; j++) {
			Ice::Byte ib = data[j];
			fd.push_back(ib);
		}

		File f;
		f.name = string(name);
		f.data = fd;
		fs.push_back(f);

		free(name);
		free(data);
	}
	sl_free2(outfiles);

	return fs;
}

void SolverI::cancel(const string& jobid,
					 const ::Ice::Current& current) {
	cout << "cancel(jobid=" << jobid << ") called." << endl;
	map<string,string>::iterator it = solverdirs.find(jobid);
	if (it == solverdirs.end()) {
		cout << "jobid " << jobid << " not found." << endl;
	}
	string dir = it->second;
	cout << "directory: " << dir << endl;
	string cancelfn = dir + "/cancel";
	FILE* f = fopen(cancelfn.c_str(), "w");
	if (!f || fclose(f)) {
		cout << "Failed to write cancel file: " << cancelfn << ":" << strerror(errno) << endl;
		return;
	}
	cout << "Wrote cancel file " << cancelfn << endl;
}

void SolverI::shutdown(const ::Ice::Current& current) {
	cout << "shutdown() called." << endl;
}

class Server : virtual public Ice::Application {
public:
    virtual int run(int argc, char* args[]) {
		cout << "run() called." << endl;
		cout << "Args:" << endl;
		for (int i=0; i<argc; i++)
			cout << "  " << args[i] << endl;

		if (argc != 2) {
			cout << "Need one arg: index scale." << endl;
			return -1;
		}

		int scale = atoi(args[1]);

		Ice::CommunicatorPtr ic = this->communicator();
		Ice::PropertiesPtr props = ic->getProperties();
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapter("OneSolver");
		string idstr = props->getProperty("Identity");
		Ice::Identity myid = ic->stringToIdentity(idstr);
		string progname = props->getProperty("Ice.ProgramName");
		cout << "Creating solver..." << endl;
		SolverI* si = new SolverI(progname, scale);
		cout << "Reading config file..." << endl;
		if (si->init()) {
			cout << "Error reading config file." << endl;
			return -1;
		}
		SolverPtr solver = si;
		adapter->add(solver, myid);
		cout << "Activating adapter..." << endl;
		adapter->activate();
		cout << "Running!" << endl;
		ic->waitForShutdown();
		return 0;
		/*
		 Ice::ObjectAdapterPtr adapter
		 = ic->createObjectAdapterWithEndpoints
		 ("SimplePrinterAdapter", "default -p 10000");
		 Ice::ObjectPtr object = new SolverI;
		 adapter->add(object,
		 ic->stringToIdentity("SimplePrinter"));
		 adapter->activate();
		 return 0;
		 */
    }
};

int main(int argc, char* argv[]) {
    cout << "SolverServer starting.  Command-line args:" << endl;
	for (int i=0; i<argc; i++)
		cout << "  " << argv[i] << endl;

    Server s;
    return s.main(argc, argv);
}

/*
	int status = 0;
    Ice::CommunicatorPtr ic;
    try {
        ic = Ice::initialize(argc, argv);
        Ice::ObjectAdapterPtr adapter
            = ic->createObjectAdapterWithEndpoints(
                "SimplePrinterAdapter", "default -p 10000");
        Ice::ObjectPtr object = new SolverI;
        adapter->add(object,
                     ic->stringToIdentity("SimplePrinter"));
        adapter->activate();
        ic->waitForShutdown();
    } catch (const Ice::Exception& e) {
        cerr << e << endl;
        status = 1;
    } catch (const char* msg) {
        cerr << msg << endl;
        status = 1;
    }
    if (ic) {
        try {
            ic->destroy();
        } catch (const Ice::Exception& e) {
            cerr << e << endl;
            status = 1;
        }
    }
    return status;
}

 */
<|endoftext|>


<commit_before><commit_msg>Fix another instance of python_24 being used on Windows.<commit_after><|endoftext|>


<commit_before>/** @file

  Implementation of Parent Proxy routing

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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 "HostStatus.h"
#include "ParentRoundRobin.h"

ParentRoundRobin::ParentRoundRobin(ParentRecord *parent_record, ParentRR_t _round_robin_type)
{
  round_robin_type = _round_robin_type;
  latched_parent   = 0;
  parents          = parent_record->parents;
  num_parents      = parent_record->num_parents;

  if (is_debug_tag_set("parent_select")) {
    switch (round_robin_type) {
    case P_NO_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_NO_ROUND_ROBIN.");
      break;
    case P_STRICT_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_STRICT_ROUND_ROBIN.");
      break;
    case P_HASH_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_HASH_ROUND_ROBIN.");
      break;
    case P_LATCHED_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_LATCHED_ROUND_ROBIN.");
      break;
    default:
      // should never see this, there is a problem if you do.
      Debug("parent_select", "Using a round robin parent selection strategy of type UNKNOWN TYPE.");
      break;
    }
  }
}

ParentRoundRobin::~ParentRoundRobin() = default;

void
ParentRoundRobin::selectParent(bool first_call, ParentResult *result, RequestData *rdata, unsigned int fail_threshold,
                               unsigned int retry_time)
{
  Debug("parent_select", "In ParentRoundRobin::selectParent(): Using a round robin parent selection strategy.");
  int cur_index          = 0;
  bool parentUp          = false;
  bool parentRetry       = false;
  HostStatus &pStatus    = HostStatus::instance();
  HostStatus_t host_stat = HostStatus_t::HOST_STATUS_UP;

  HttpRequestData *request_info = static_cast<HttpRequestData *>(rdata);

  ink_assert(num_parents > 0 || result->rec->go_direct == true);

  if (first_call) {
    if (parents == nullptr) {
      // We should only get into this state if
      //   if we are supposed to go direct
      ink_assert(result->rec->go_direct == true);
      // Could not find a parent
      if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) {
        result->result = PARENT_DIRECT;
      } else {
        result->result = PARENT_FAIL;
      }

      result->hostname = nullptr;
      result->port     = 0;
      return;
    } else {
      switch (round_robin_type) {
      case P_HASH_ROUND_ROBIN:
        // INKqa12817 - make sure to convert to host byte order
        // Why was it important to do host order here?  And does this have any
        // impact with the transition to IPv6?  The IPv4 functionality is
        // preserved for now anyway as ats_ip_hash returns the 32-bit address in
        // that case.
        if (rdata->get_client_ip() != nullptr) {
          cur_index = result->start_parent = ntohl(ats_ip_hash(rdata->get_client_ip())) % num_parents;
        } else {
          cur_index = 0;
        }
        break;
      case P_STRICT_ROUND_ROBIN:
        cur_index = ink_atomic_increment(reinterpret_cast<int32_t *>(&result->rec->rr_next), 1);
        cur_index = result->start_parent = cur_index % num_parents;
        break;
      case P_NO_ROUND_ROBIN:
        cur_index = result->start_parent = 0;
        break;
      case P_LATCHED_ROUND_ROBIN:
        cur_index = result->start_parent = latched_parent;
        break;
      default:
        ink_release_assert(0);
      }
    }
  } else {
    // Move to next parent due to failure
    latched_parent = cur_index = (result->last_parent + 1) % num_parents;

    // Check to see if we have wrapped around
    if (static_cast<unsigned int>(cur_index) == result->start_parent) {
      // We've wrapped around so bypass if we can
      if (result->rec->go_direct == true) {
        // Could not find a parent
        if (result->rec->parent_is_proxy == true) {
          result->result = PARENT_DIRECT;
        } else {
          result->result = PARENT_FAIL;
        }
        result->hostname = nullptr;
        result->port     = 0;
        return;
      }
    }
  }

  // Loop through the array of parent seeing if any are up or
  //   should be retried
  do {
    HostStatRec *hst = pStatus.getHostStatus(parents[cur_index].hostname);
    host_stat        = (hst) ? hst->status : HostStatus_t::HOST_STATUS_UP;
    // if the config ignore_self_detect is set to true and the host is down due to SELF_DETECT reason
    // ignore the down status and mark it as avaialble
    if (result->rec->ignore_self_detect && (hst && hst->status == HOST_STATUS_DOWN)) {
      if (hst->reasons == Reason::SELF_DETECT) {
        host_stat = HOST_STATUS_UP;
      }
    }
    Debug("parent_select", "cur_index: %d, result->start_parent: %d", cur_index, result->start_parent);
    // DNS ParentOnly inhibits bypassing the parent so always return that t
    if ((parents[cur_index].failedAt == 0) || (parents[cur_index].failCount < static_cast<int>(fail_threshold))) {
      if (host_stat == HOST_STATUS_UP) {
        Debug("parent_select", "FailThreshold = %d", fail_threshold);
        Debug("parent_select", "Selecting a parent due to little failCount (faileAt: %u failCount: %d)",
              (unsigned)parents[cur_index].failedAt, parents[cur_index].failCount);
        parentUp = true;
      }
    } else {
      if ((result->wrap_around) ||
          ((parents[cur_index].failedAt + retry_time) < request_info->xact_start && host_stat == HOST_STATUS_UP)) {
        Debug("parent_select", "Parent[%d].failedAt = %u, retry = %u,xact_start = %" PRId64 " but wrap = %d", cur_index,
              (unsigned)parents[cur_index].failedAt, retry_time, (int64_t)request_info->xact_start, result->wrap_around);
        // Reuse the parent
        parentUp    = true;
        parentRetry = true;
        Debug("parent_select", "Parent marked for retry %s:%d", parents[cur_index].hostname, parents[cur_index].port);
      } else {
        parentUp = false;
      }
    }

    if (parentUp == true && host_stat != HOST_STATUS_DOWN) {
      Debug("parent_select", "status for %s: %d", parents[cur_index].hostname, host_stat);
      result->result      = PARENT_SPECIFIED;
      result->hostname    = parents[cur_index].hostname;
      result->port        = parents[cur_index].port;
      result->last_parent = cur_index;
      result->retry       = parentRetry;
      ink_assert(result->hostname != nullptr);
      ink_assert(result->port != 0);
      Debug("parent_select", "Chosen parent = %s.%d", result->hostname, result->port);
      return;
    }
    latched_parent = cur_index = (cur_index + 1) % num_parents;
  } while (static_cast<unsigned int>(cur_index) != result->start_parent);

  if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) {
    result->result = PARENT_DIRECT;
  } else {
    result->result = PARENT_FAIL;
  }

  result->hostname = nullptr;
  result->port     = 0;
}

uint32_t
ParentRoundRobin::numParents(ParentResult *result) const
{
  return num_parents;
}
<commit_msg>Fix strict round robin cur_index increment<commit_after>/** @file

  Implementation of Parent Proxy routing

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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 "HostStatus.h"
#include "ParentRoundRobin.h"

ParentRoundRobin::ParentRoundRobin(ParentRecord *parent_record, ParentRR_t _round_robin_type)
{
  round_robin_type = _round_robin_type;
  latched_parent   = 0;
  parents          = parent_record->parents;
  num_parents      = parent_record->num_parents;

  if (is_debug_tag_set("parent_select")) {
    switch (round_robin_type) {
    case P_NO_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_NO_ROUND_ROBIN.");
      break;
    case P_STRICT_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_STRICT_ROUND_ROBIN.");
      break;
    case P_HASH_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_HASH_ROUND_ROBIN.");
      break;
    case P_LATCHED_ROUND_ROBIN:
      Debug("parent_select", "Using a round robin parent selection strategy of type P_LATCHED_ROUND_ROBIN.");
      break;
    default:
      // should never see this, there is a problem if you do.
      Debug("parent_select", "Using a round robin parent selection strategy of type UNKNOWN TYPE.");
      break;
    }
  }
}

ParentRoundRobin::~ParentRoundRobin() = default;

void
ParentRoundRobin::selectParent(bool first_call, ParentResult *result, RequestData *rdata, unsigned int fail_threshold,
                               unsigned int retry_time)
{
  Debug("parent_select", "In ParentRoundRobin::selectParent(): Using a round robin parent selection strategy.");
  int cur_index          = 0;
  bool parentUp          = false;
  bool parentRetry       = false;
  HostStatus &pStatus    = HostStatus::instance();
  HostStatus_t host_stat = HostStatus_t::HOST_STATUS_UP;

  HttpRequestData *request_info = static_cast<HttpRequestData *>(rdata);

  ink_assert(num_parents > 0 || result->rec->go_direct == true);

  if (first_call) {
    if (parents == nullptr) {
      // We should only get into this state if
      //   if we are supposed to go direct
      ink_assert(result->rec->go_direct == true);
      // Could not find a parent
      if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) {
        result->result = PARENT_DIRECT;
      } else {
        result->result = PARENT_FAIL;
      }

      result->hostname = nullptr;
      result->port     = 0;
      return;
    } else {
      switch (round_robin_type) {
      case P_HASH_ROUND_ROBIN:
        // INKqa12817 - make sure to convert to host byte order
        // Why was it important to do host order here?  And does this have any
        // impact with the transition to IPv6?  The IPv4 functionality is
        // preserved for now anyway as ats_ip_hash returns the 32-bit address in
        // that case.
        if (rdata->get_client_ip() != nullptr) {
          cur_index = result->start_parent = ntohl(ats_ip_hash(rdata->get_client_ip())) % num_parents;
        } else {
          cur_index = 0;
        }
        break;
      case P_STRICT_ROUND_ROBIN:
        cur_index = result->start_parent =
          ink_atomic_increment(reinterpret_cast<uint32_t *>(&result->rec->rr_next), 1) % num_parents;
        break;
      case P_NO_ROUND_ROBIN:
        cur_index = result->start_parent = 0;
        break;
      case P_LATCHED_ROUND_ROBIN:
        cur_index = result->start_parent = latched_parent;
        break;
      default:
        ink_release_assert(0);
      }
    }
  } else {
    // Move to next parent due to failure
    latched_parent = cur_index = (result->last_parent + 1) % num_parents;

    // Check to see if we have wrapped around
    if (static_cast<unsigned int>(cur_index) == result->start_parent) {
      // We've wrapped around so bypass if we can
      if (result->rec->go_direct == true) {
        // Could not find a parent
        if (result->rec->parent_is_proxy == true) {
          result->result = PARENT_DIRECT;
        } else {
          result->result = PARENT_FAIL;
        }
        result->hostname = nullptr;
        result->port     = 0;
        return;
      }
    }
  }

  // Loop through the array of parent seeing if any are up or
  //   should be retried
  do {
    HostStatRec *hst = pStatus.getHostStatus(parents[cur_index].hostname);
    host_stat        = (hst) ? hst->status : HostStatus_t::HOST_STATUS_UP;
    // if the config ignore_self_detect is set to true and the host is down due to SELF_DETECT reason
    // ignore the down status and mark it as avaialble
    if (result->rec->ignore_self_detect && (hst && hst->status == HOST_STATUS_DOWN)) {
      if (hst->reasons == Reason::SELF_DETECT) {
        host_stat = HOST_STATUS_UP;
      }
    }
    Debug("parent_select", "cur_index: %d, result->start_parent: %d", cur_index, result->start_parent);
    // DNS ParentOnly inhibits bypassing the parent so always return that t
    if ((parents[cur_index].failedAt == 0) || (parents[cur_index].failCount < static_cast<int>(fail_threshold))) {
      if (host_stat == HOST_STATUS_UP) {
        Debug("parent_select", "FailThreshold = %d", fail_threshold);
        Debug("parent_select", "Selecting a parent due to little failCount (faileAt: %u failCount: %d)",
              (unsigned)parents[cur_index].failedAt, parents[cur_index].failCount);
        parentUp = true;
      }
    } else {
      if ((result->wrap_around) ||
          ((parents[cur_index].failedAt + retry_time) < request_info->xact_start && host_stat == HOST_STATUS_UP)) {
        Debug("parent_select", "Parent[%d].failedAt = %u, retry = %u,xact_start = %" PRId64 " but wrap = %d", cur_index,
              (unsigned)parents[cur_index].failedAt, retry_time, (int64_t)request_info->xact_start, result->wrap_around);
        // Reuse the parent
        parentUp    = true;
        parentRetry = true;
        Debug("parent_select", "Parent marked for retry %s:%d", parents[cur_index].hostname, parents[cur_index].port);
      } else {
        parentUp = false;
      }
    }

    if (parentUp == true && host_stat != HOST_STATUS_DOWN) {
      Debug("parent_select", "status for %s: %d", parents[cur_index].hostname, host_stat);
      result->result      = PARENT_SPECIFIED;
      result->hostname    = parents[cur_index].hostname;
      result->port        = parents[cur_index].port;
      result->last_parent = cur_index;
      result->retry       = parentRetry;
      ink_assert(result->hostname != nullptr);
      ink_assert(result->port != 0);
      Debug("parent_select", "Chosen parent = %s.%d", result->hostname, result->port);
      return;
    }
    latched_parent = cur_index = (cur_index + 1) % num_parents;
  } while (static_cast<unsigned int>(cur_index) != result->start_parent);

  if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) {
    result->result = PARENT_DIRECT;
  } else {
    result->result = PARENT_FAIL;
  }

  result->hostname = nullptr;
  result->port     = 0;
}

uint32_t
ParentRoundRobin::numParents(ParentResult *result) const
{
  return num_parents;
}
<|endoftext|>


<commit_before>#include <testUtil.h>
#include "LinearSystem.h"
#include <iostream>

using namespace std;
using namespace Drake;
using namespace Eigen;

template <int StatesAtCompileTime, int InputsAtCompileTime, int OutputsAtCompileTime>
shared_ptr<AffineSystem<
      EigenVector<StatesAtCompileTime>::template type,
      EigenVector<InputsAtCompileTime>::template type,
      EigenVector<OutputsAtCompileTime>::template type >>
createRandomAffineSystem(size_t num_states, size_t num_inputs, size_t num_outputs) {
  using ReturnType = AffineSystem<
      EigenVector<StatesAtCompileTime>::template type,
      EigenVector<InputsAtCompileTime>::template type,
      EigenVector<OutputsAtCompileTime>::template type >;

  auto A = Matrix<double, StatesAtCompileTime, StatesAtCompileTime>::Random(num_states, num_states).eval();
  auto B = Matrix<double, StatesAtCompileTime, InputsAtCompileTime>::Random(num_states, num_inputs).eval();
  auto C = Matrix<double, OutputsAtCompileTime, StatesAtCompileTime>::Random(num_outputs, num_states).eval();
  auto D = Matrix<double, OutputsAtCompileTime, InputsAtCompileTime>::Random(num_outputs, num_inputs).eval();
  auto xdot0 = Matrix<double, StatesAtCompileTime, 1>::Random(num_states, 1).eval();
  auto y0 = Matrix<double, OutputsAtCompileTime, 1>::Random(num_outputs, 1).eval();
  return make_shared<ReturnType>(A, B, xdot0, C, D, y0);
};

template <typename Scalar>
using NonEigenStateVectorType = std::vector<Scalar>;

template <int StatesAtCompileTime, int InputsAtCompileTime, int OutputsAtCompileTime>
void testSizes(size_t num_states, size_t num_inputs, size_t num_outputs) {
  auto sys_ptr = createRandomAffineSystem<StatesAtCompileTime, InputsAtCompileTime, OutputsAtCompileTime>(num_states, num_inputs, num_outputs);
  const auto& sys = *sys_ptr;
  using SysType = typename remove_reference<decltype(sys)>::type;

  valuecheck(num_states, sys.getNumStates(), "Wrong number of states.");
  valuecheck(num_inputs, sys.getNumInputs(), "Wrong number of inputs.");
  valuecheck(num_outputs, sys.getNumOutputs(), "Wrong number of outputs.");

  static_assert(SysType::num_states == StatesAtCompileTime, "Wrong number of states at compile time");
  static_assert(SysType::num_inputs == InputsAtCompileTime, "Wrong number of inputs at compile time");
  static_assert(SysType::num_outputs == OutputsAtCompileTime, "Wrong number of outputs at compile time");

  valuecheck(num_states, getNumStates(sys));
  valuecheck(num_inputs, getNumInputs(sys));
  valuecheck(num_outputs, getNumOutputs(sys));

  auto x = createStateVector<double>(sys);
  valuecheck(num_states, static_cast<size_t>(x.size()), "State vector size wrong");
};

template <int NumStates1, int NumInputs1, int NumOutputs1, int NumStates2, int NumOutputs2>
void testCascade(size_t num_states_1, size_t num_inputs_1, size_t num_outputs_1, size_t num_states_2, size_t num_outputs_2) {
  auto sys1_ptr = createRandomAffineSystem<NumStates1, NumInputs1, NumOutputs1>(num_states_1, num_inputs_1, num_outputs_1);
  auto sys2_ptr = createRandomAffineSystem<NumStates2, NumOutputs1, NumOutputs2>(num_states_2, num_outputs_1, num_outputs_2);

  auto combined = cascade(sys1_ptr, sys2_ptr);

  valuecheck(num_states_1 + num_states_2, getNumStates(*combined), "Wrong number of states");
  valuecheck(num_inputs_1, getNumInputs(*combined), "Wrong number of inputs");
  valuecheck(num_outputs_2, getNumOutputs(*combined), "Wrong number of outputs");

  auto x = createStateVector<double>(*combined);
  valuecheck(getNumStates(*combined), static_cast<size_t>(x.size()), "State vector size wrong");
}

template <int NumStates1, int NumInputs1, int NumOutputs1, int NumStates2>
void testFeedback(size_t num_states_1, size_t num_inputs_1, size_t num_outputs_1, size_t num_states_2) {
  auto sys1_ptr = createRandomAffineSystem<NumStates1, NumInputs1, NumOutputs1>(num_states_1, num_inputs_1, num_outputs_1);
  auto sys2_ptr = createRandomAffineSystem<NumStates2, NumOutputs1, NumInputs1>(num_states_2, num_outputs_1, num_inputs_1);

  auto combined = feedback(sys1_ptr, sys2_ptr);

  valuecheck(num_states_1 + num_states_2, getNumStates(*combined), "Wrong number of states");
  valuecheck(num_inputs_1, getNumInputs(*combined), "Wrong number of inputs");
  valuecheck(num_outputs_1, getNumOutputs(*combined), "Wrong number of outputs");

  auto x = createStateVector<double>(*combined);
  valuecheck(getNumStates(*combined), static_cast<size_t>(x.size()), "State vector size wrong");
}

int main(int argc, char* argv[]) {
  testSizes<Dynamic, Dynamic, Dynamic>(3, 4, 5);
  testSizes<3, 4, 5>(3, 4, 5);
  testCascade<3, 4, 5, 6, 7>(3, 4, 5, 6, 7);
  testCascade<Dynamic, Dynamic, Dynamic, Dynamic, Dynamic>(3, 4, 5, 6, 7);
  testFeedback<4, 2, 3, 5>(4, 2, 3, 5);
  testFeedback<Dynamic, Dynamic, Dynamic, Dynamic>(4, 2, 3, 5);

  return 0;
}<commit_msg>Cleanup.<commit_after>#include <testUtil.h>
#include "LinearSystem.h"
#include <iostream>

using namespace std;
using namespace Drake;
using namespace Eigen;

template <int StatesAtCompileTime, int InputsAtCompileTime, int OutputsAtCompileTime>
shared_ptr<AffineSystem<
      EigenVector<StatesAtCompileTime>::template type,
      EigenVector<InputsAtCompileTime>::template type,
      EigenVector<OutputsAtCompileTime>::template type >>
createRandomAffineSystem(size_t num_states, size_t num_inputs, size_t num_outputs) {
  using ReturnType = AffineSystem<
      EigenVector<StatesAtCompileTime>::template type,
      EigenVector<InputsAtCompileTime>::template type,
      EigenVector<OutputsAtCompileTime>::template type >;

  auto A = Matrix<double, StatesAtCompileTime, StatesAtCompileTime>::Random(num_states, num_states).eval();
  auto B = Matrix<double, StatesAtCompileTime, InputsAtCompileTime>::Random(num_states, num_inputs).eval();
  auto C = Matrix<double, OutputsAtCompileTime, StatesAtCompileTime>::Random(num_outputs, num_states).eval();
  auto D = Matrix<double, OutputsAtCompileTime, InputsAtCompileTime>::Random(num_outputs, num_inputs).eval();
  auto xdot0 = Matrix<double, StatesAtCompileTime, 1>::Random(num_states, 1).eval();
  auto y0 = Matrix<double, OutputsAtCompileTime, 1>::Random(num_outputs, 1).eval();
  return make_shared<ReturnType>(A, B, xdot0, C, D, y0);
};

template <int StatesAtCompileTime, int InputsAtCompileTime, int OutputsAtCompileTime>
void testSizes(size_t num_states, size_t num_inputs, size_t num_outputs) {
  auto sys_ptr = createRandomAffineSystem<StatesAtCompileTime, InputsAtCompileTime, OutputsAtCompileTime>(num_states, num_inputs, num_outputs);
  const auto& sys = *sys_ptr;
  using SysType = typename remove_reference<decltype(sys)>::type;

  valuecheck(num_states, sys.getNumStates(), "Wrong number of states.");
  valuecheck(num_inputs, sys.getNumInputs(), "Wrong number of inputs.");
  valuecheck(num_outputs, sys.getNumOutputs(), "Wrong number of outputs.");

  static_assert(SysType::num_states == StatesAtCompileTime, "Wrong number of states at compile time");
  static_assert(SysType::num_inputs == InputsAtCompileTime, "Wrong number of inputs at compile time");
  static_assert(SysType::num_outputs == OutputsAtCompileTime, "Wrong number of outputs at compile time");

  valuecheck(num_states, getNumStates(sys));
  valuecheck(num_inputs, getNumInputs(sys));
  valuecheck(num_outputs, getNumOutputs(sys));

  auto x = createStateVector<double>(sys);
  valuecheck(num_states, static_cast<size_t>(x.size()), "State vector size wrong");
};

template <int NumStates1, int NumInputs1, int NumOutputs1, int NumStates2, int NumOutputs2>
void testCascade(size_t num_states_1, size_t num_inputs_1, size_t num_outputs_1, size_t num_states_2, size_t num_outputs_2) {
  auto sys1_ptr = createRandomAffineSystem<NumStates1, NumInputs1, NumOutputs1>(num_states_1, num_inputs_1, num_outputs_1);
  auto sys2_ptr = createRandomAffineSystem<NumStates2, NumOutputs1, NumOutputs2>(num_states_2, num_outputs_1, num_outputs_2);

  auto combined = cascade(sys1_ptr, sys2_ptr);

  valuecheck(num_states_1 + num_states_2, getNumStates(*combined), "Wrong number of states");
  valuecheck(num_inputs_1, getNumInputs(*combined), "Wrong number of inputs");
  valuecheck(num_outputs_2, getNumOutputs(*combined), "Wrong number of outputs");

  auto x = createStateVector<double>(*combined);
  valuecheck(getNumStates(*combined), static_cast<size_t>(x.size()), "State vector size wrong");
}

template <int NumStates1, int NumInputs1, int NumOutputs1, int NumStates2>
void testFeedback(size_t num_states_1, size_t num_inputs_1, size_t num_outputs_1, size_t num_states_2) {
  auto sys1_ptr = createRandomAffineSystem<NumStates1, NumInputs1, NumOutputs1>(num_states_1, num_inputs_1, num_outputs_1);
  auto sys2_ptr = createRandomAffineSystem<NumStates2, NumOutputs1, NumInputs1>(num_states_2, num_outputs_1, num_inputs_1);

  auto combined = feedback(sys1_ptr, sys2_ptr);

  valuecheck(num_states_1 + num_states_2, getNumStates(*combined), "Wrong number of states");
  valuecheck(num_inputs_1, getNumInputs(*combined), "Wrong number of inputs");
  valuecheck(num_outputs_1, getNumOutputs(*combined), "Wrong number of outputs");

  auto x = createStateVector<double>(*combined);
  valuecheck(getNumStates(*combined), static_cast<size_t>(x.size()), "State vector size wrong");
}

int main(int argc, char* argv[]) {
  testSizes<Dynamic, Dynamic, Dynamic>(3, 4, 5);
  testSizes<3, 4, 5>(3, 4, 5);
  testCascade<3, 4, 5, 6, 7>(3, 4, 5, 6, 7);
  testCascade<Dynamic, Dynamic, Dynamic, Dynamic, Dynamic>(3, 4, 5, 6, 7);
  testFeedback<4, 2, 3, 5>(4, 2, 3, 5);
  testFeedback<Dynamic, Dynamic, Dynamic, Dynamic>(4, 2, 3, 5);

  return 0;
}<|endoftext|>


<commit_before>
/*********************************************************************
 *                                                                   *
 * ConfigFemtoAnalysis.C - configuration macro for the femtoscopic   *
 * analysis, meant as a QA process for two-particle effects          *
 *                                                                   *
 * Author: Adam Kisiel (Adam.Kisiel@cern.ch)                         *
 *                                                                   *
 *********************************************************************/

#if !defined(__CINT__) || defined(__MAKECINT_)
#include "AliFemtoManager.h"
#include "AliFemtoEventReaderESDChain.h"
#include "AliFemtoEventReaderESDChainKine.h"
#include "AliFemtoEventReaderAODChain.h"
#include "AliFemtoSimpleAnalysis.h"
#include "AliFemtoBasicEventCut.h"
#include "AliFemtoESDTrackCut.h"
#include "AliFemtoCorrFctn.h"
#include "AliFemtoCutMonitorParticleYPt.h"
#include "AliFemtoCutMonitorParticleVertPos.h"
#include "AliFemtoCutMonitorParticleMomRes.h"
#include "AliFemtoCutMonitorParticlePID.h"
#include "AliFemtoCutMonitorEventMult.h"
#include "AliFemtoCutMonitorEventVertex.h"
#include "AliFemtoShareQualityTPCEntranceSepPairCut.h"
#include "AliFemtoPairCutAntiGamma.h"
#include "AliFemtoPairCutRadialDistanceKK.h"
#include "AliFemtoPairCutRadialDistanceLM.h"
#include "AliFemtoQinvCorrFctn.h"
#include "AliFemtoShareQualityCorrFctn.h"
#include "AliFemtoTPCInnerCorrFctn.h"
#include "AliFemtoAnalysisAzimuthalPbPb2Order.h"
#include "AliFemtoCorrFctn3DSpherical.h"
#include "AliFemtoChi2CorrFctn.h"
#include "AliFemtoCorrFctnTPCNcls.h"
#include "AliFemtoBPLCMS3DCorrFctn.h"
#include "AliFemtoCorrFctn3DLCMSSym.h"
#include "AliFemtoModelBPLCMSCorrFctn.h"
#include "AliFemtoModelCorrFctn3DSpherical.h"
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelGausRinvFreezeOutGenerator.h"
#include "AliFemtoModelManager.h"
#include "AliFemtoModelWeightGeneratorBasic.h"
#include "AliFemtoModelWeightGeneratorLednicky.h"
#include "AliFemtoCorrFctnDirectYlm.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
#include "AliFemtoModelCorrFctnSource.h"
#include "AliFemtoCutMonitorParticlePtPDG.h"
#include "AliFemtoKTPairCut.h"
#endif

//________________________________________________________________________
AliFemtoManager* ConfigFemtoAnalysis(int CentL=20, int CentH=30, int kTRange=1, int PhiBin=1) {

    double PionMass = 0.13956995;
    double KaonMass = 0.493677;

    if (CentL==0 && CentH==5) {
        int runmults[10] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==5 && CentH==10) {
        int runmults[10] = {0, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==10 && CentH==20) {
        int runmults[10] = {0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==20 && CentH==30) {
        int runmults[10] = {0, 0, 0, 1, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==30 && CentH==40) {
        int runmults[10] = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0};
    }
    if (CentL==40 && CentH==50 ) {
        int runmults[10] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
    }

    int multbins[11] = {0, 50, 100, 200, 300, 400, 500, 700, 800, 900, 990};

    const char *chrgs[2] = { "pip", "pim" };

    int runch[2] = {1, 1};

    int kTmax=1;
    kTmax=kTRange;
    double ktrng[5] = {0.2, 0.3, 0.4, 0.5, 0.7};

    int phimax=9;

    if(PhiBin==1){
        int phirange[10] = {-15, 5, 25, 45, 65, 85, 105, 125, 145, 165};
        phimax=9;
    }
    if (PhiBin==2) {
        int phirange[11] = {-9, 9, 27, 45, 63, 81, 99, 117, 136, 153, 171};
        phimax=9;
    }

    AliFemtoEventReaderAODChain *Reader = new AliFemtoEventReaderAODChain();
    Reader->SetFilterBit(7);
    Reader->SetCentralityPreSelection(0.001, 550);

    AliFemtoManager* Manager=new AliFemtoManager();
    Manager->SetEventReader(Reader);

    AliFemtoAnalysisAzimuthalPbPb2Order    *ana[2][7];
    AliFemtoBasicEventCut         *mecetaphitpc[2][7];
    AliFemtoCutMonitorEventMult   *cutPassEvMetaphitpc[2][7];
    AliFemtoCutMonitorEventMult   *cutFailEvMetaphitpc[2][7];
    AliFemtoCutMonitorEventVertex *cutPassEvVetaphitpc[2][7];
    AliFemtoCutMonitorEventVertex *cutFailEvVetaphitpc[2][7];
    AliFemtoESDTrackCut           *dtc1etaphitpc[2][7];

    AliFemtoPairCutRadialDistanceKK      *sqpcetaphitpc[2][7];
    AliFemtoPairCutRadialDistanceKK      *sqpcetaphitpcRD[2][7];

    AliFemtoKTPairCut             *ktpaircut[2][7][4][11];
    //  AliFemtoQinvCorrFctn            *cqqinv[2][11][3];
    AliFemtoBPLCMS3DCorrFctn     *cq3dlcmskttpc[2][7][4][11];

    for (int imult=0; imult<7; imult++) {
        if (runmults[imult]) {
            for (int ichg=0; ichg<2; ichg++) {
                if (runch[ichg]) {

                    ana[ichg][imult] = new AliFemtoAnalysisAzimuthalPbPb2Order(4, -8.0, 8.0, 5, multbins[imult], multbins[imult+1],phimax);
                    ana[ichg][imult]->SetNumEventsToMix(3);
                    ana[ichg][imult]->SetMinSizePartCollection(4);
                    ana[ichg][imult]->SetEPhistname(Form("hist%i%i",ichg,imult));
                    mecetaphitpc[ichg][imult] = new AliFemtoBasicEventCut();
                    mecetaphitpc[ichg][imult]->SetEventMult(5,100000);//was 0.001
                    mecetaphitpc[ichg][imult]->SetVertZPos(-8,8);

                    cutPassEvMetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventMult(Form("cutPass%stpcM%i", chrgs[ichg], imult));
                    cutFailEvMetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventMult(Form("cutFail%stpcM%i", chrgs[ichg], imult));
                    mecetaphitpc[ichg][imult]->AddCutMonitor(cutPassEvMetaphitpc[ichg][imult], cutFailEvMetaphitpc[ichg][imult]);

                    cutPassEvVetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventVertex(Form("cutPass%stpcM%i", chrgs[ichg], imult));
                    cutFailEvVetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventVertex(Form("cutFail%stpcM%i", chrgs[ichg], imult));
                    mecetaphitpc[ichg][imult]->AddCutMonitor(cutPassEvVetaphitpc[ichg][imult], cutFailEvVetaphitpc[ichg][imult]);

                    dtc1etaphitpc[ichg][imult] = new AliFemtoESDTrackCut();

                    if (ichg == 0)
                        dtc1etaphitpc[ichg][imult]->SetCharge(1.0);
                    else if (ichg == 1)
                        dtc1etaphitpc[ichg][imult]->SetCharge(-1.0);

                    dtc1etaphitpc[ichg][imult]->SetPt(0.15,1.5);
                    dtc1etaphitpc[ichg][imult]->SetEta(-0.8,0.8);
                    dtc1etaphitpc[ichg][imult]->SetMass(PionMass);
                    dtc1etaphitpc[ichg][imult]->SetMostProbablePion();

                    dtc1etaphitpc[ichg][imult]->SetStatus(AliESDtrack::kTPCin);
                    dtc1etaphitpc[ichg][imult]->SetminTPCncls(80);//was 0
                    dtc1etaphitpc[ichg][imult]->SetRemoveKinks(kTRUE);
                    dtc1etaphitpc[ichg][imult]->SetLabel(kFALSE);
                    dtc1etaphitpc[ichg][imult]->SetMaxTPCChiNdof(4.0);
                    dtc1etaphitpc[ichg][imult]->SetMaxImpactXY(2.4);//was 0.2
                    dtc1etaphitpc[ichg][imult]->SetMaxImpactZ(3.0);//0.15

                    sqpcetaphitpc[ichg][imult] = new AliFemtoPairCutRadialDistanceKK();
                    sqpcetaphitpcRD[ichg][imult] = new AliFemtoPairCutRadialDistanceKK();

                    sqpcetaphitpc[ichg][imult]->SetShareQualityMax(1.0);
                    sqpcetaphitpc[ichg][imult]->SetShareFractionMax(1);
                    sqpcetaphitpc[ichg][imult]->SetRemoveSameLabel(kFALSE);
                    sqpcetaphitpc[ichg][imult]->SetMinimumRadius(1.6);
                    sqpcetaphitpc[ichg][imult]->SetPhiStarDifferenceMinimum(0.0);
                    sqpcetaphitpc[ichg][imult]->SetEtaDifferenceMinimum(0.0);

                    sqpcetaphitpcRD[ichg][imult]->SetShareQualityMax(1.0);
                    sqpcetaphitpcRD[ichg][imult]->SetShareFractionMax(0.05);
                    sqpcetaphitpcRD[ichg][imult]->SetRemoveSameLabel(kFALSE);
                    sqpcetaphitpcRD[ichg][imult]->SetMinimumRadius(1.6);
                    sqpcetaphitpcRD[ichg][imult]->SetPhiStarDifferenceMinimum(0.017);
                    sqpcetaphitpcRD[ichg][imult]->SetEtaDifferenceMinimum(0.015);

                    ana[ichg][imult]->SetEventCut(mecetaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetFirstParticleCut(dtc1etaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetSecondParticleCut(dtc1etaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetPairCut(sqpcetaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetPairCutRD(sqpcetaphitpcRD[ichg][imult]);

                    for (int ikt=0; ikt<kTmax; ikt++){   //  kt range

                        //  cqqinv[ichg][imult][ikt] = new AliFemtoQinvCorrFctn(Form("cqqinv%imult%ikT", ichg, imult, ikt),30, 0,0.15);

                        for (int iphi=0; iphi<phimax; iphi++){
                            ktpaircut[ichg][imult][ikt][iphi] = new AliFemtoKTPairCut(ktrng[ikt],ktrng[ikt+1]);
                            ktpaircut[ichg][imult][ikt][iphi]->SetPhiRange(phirange[iphi],phirange[iphi+1]);

                            cq3dlcmskttpc[ichg][imult][ikt][iphi] = new AliFemtoBPLCMS3DCorrFctn(Form("cq3d%imult%ikT%iRP%i", ichg, imult, ikt, iphi),30,-0.15,0.15);
                            cq3dlcmskttpc[ichg][imult][ikt][iphi]->SetPairSelectionCut(ktpaircut[ichg][imult][ikt][iphi]);
                            ana[ichg][imult]->AddCorrFctn(cq3dlcmskttpc[ichg][imult][ikt][iphi]);
                        }
                        // ana[ichg][imult]->AddCorrFctn(cqqinv[ichg][imult][ikt]);

                    }
                    Manager->AddAnalysis(ana[ichg][imult]);
                }
            }
        }
    }
    return Manager;
}

<commit_msg>Updateing AzHBT config:MSaleh<commit_after>
/*********************************************************************
 *                                                                   *
 * ConfigFemtoAnalysis.C - configuration macro for the femtoscopic   *
 * analysis, meant as a QA process for two-particle effects          *
 *                                                                   *
 * Author: Adam Kisiel (Adam.Kisiel@cern.ch)                         *
 *                                                                   *
 *********************************************************************/

#if !defined(__CINT__) || defined(__MAKECINT_)
#include "AliFemtoManager.h"
#include "AliFemtoEventReaderESDChain.h"
#include "AliFemtoEventReaderESDChainKine.h"
#include "AliFemtoEventReaderAODChain.h"
#include "AliFemtoSimpleAnalysis.h"
#include "AliFemtoBasicEventCut.h"
#include "AliFemtoESDTrackCut.h"
#include "AliFemtoCorrFctn.h"
#include "AliFemtoCutMonitorParticleYPt.h"
#include "AliFemtoCutMonitorParticleVertPos.h"
#include "AliFemtoCutMonitorParticleMomRes.h"
#include "AliFemtoCutMonitorParticlePID.h"
#include "AliFemtoCutMonitorEventMult.h"
#include "AliFemtoCutMonitorEventVertex.h"
#include "AliFemtoShareQualityTPCEntranceSepPairCut.h"
#include "AliFemtoPairCutAntiGamma.h"
#include "AliFemtoPairCutRadialDistanceKK.h"
#include "AliFemtoPairCutRadialDistanceLM.h"
#include "AliFemtoQinvCorrFctn.h"
#include "AliFemtoShareQualityCorrFctn.h"
#include "AliFemtoTPCInnerCorrFctn.h"
#include "AliFemtoAnalysisAzimuthalPbPb2Order.h"
#include "AliFemtoCorrFctn3DSpherical.h"
#include "AliFemtoChi2CorrFctn.h"
#include "AliFemtoCorrFctnTPCNcls.h"
#include "AliFemtoBPLCMS3DCorrFctn.h"
#include "AliFemtoCorrFctn3DLCMSSym.h"
#include "AliFemtoModelBPLCMSCorrFctn.h"
#include "AliFemtoModelCorrFctn3DSpherical.h"
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelGausRinvFreezeOutGenerator.h"
#include "AliFemtoModelManager.h"
#include "AliFemtoModelWeightGeneratorBasic.h"
#include "AliFemtoModelWeightGeneratorLednicky.h"
#include "AliFemtoCorrFctnDirectYlm.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
#include "AliFemtoModelCorrFctnSource.h"
#include "AliFemtoCutMonitorParticlePtPDG.h"
#include "AliFemtoKTPairCut.h"
#endif

//________________________________________________________________________
AliFemtoManager* ConfigFemtoAnalysis(int CentL=20, int CentH=30, int kTRange=1, int PhiBin=1) {

    double PionMass = 0.13956995;
    double KaonMass = 0.493677;

    if (CentL==0 && CentH==5) {
        int runmults[10] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==5 && CentH==10) {
        int runmults[10] = {0, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==10 && CentH==20) {
        int runmults[10] = {0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==20 && CentH==30) {
        int runmults[10] = {0, 0, 0, 1, 0, 0, 0, 0, 0, 0};
    }
    if (CentL==30 && CentH==40) {
        int runmults[10] = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0};
    }
    if (CentL==40 && CentH==50 ) {
        int runmults[10] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
    }

    int multbins[11] = {0, 50, 100, 200, 300, 400, 500, 700, 800, 900, 990};

    const char *chrgs[2] = { "pip", "pim" };

    int runch[2] = {1, 1};

    int kTmax=1;
    kTmax=kTRange;
    double ktrng[5] = {0.2, 0.3, 0.4, 0.5, 0.7};

    int phimax=9;

    if(PhiBin==1){
        int phirange[10] = {-15, 5, 25, 45, 65, 85, 105, 125, 145, 165};
        phimax=9;
    }
    if (PhiBin==2) {
        int phirange[11] = {-9, 9, 27, 45, 63, 81, 99, 117, 136, 153, 171};
        phimax=9;
    }

    AliFemtoEventReaderAODChain *Reader = new AliFemtoEventReaderAODChain();
    Reader->SetFilterBit(7);
    Reader->SetCentralityPreSelection(0.001, 550);

    AliFemtoManager* Manager=new AliFemtoManager();
    Manager->SetEventReader(Reader);

    AliFemtoAnalysisAzimuthalPbPb2Order    *ana[2][7];
    AliFemtoBasicEventCut         *mecetaphitpc[2][7];
    AliFemtoCutMonitorEventMult   *cutPassEvMetaphitpc[2][7];
    AliFemtoCutMonitorEventMult   *cutFailEvMetaphitpc[2][7];
    AliFemtoCutMonitorEventVertex *cutPassEvVetaphitpc[2][7];
    AliFemtoCutMonitorEventVertex *cutFailEvVetaphitpc[2][7];
    AliFemtoESDTrackCut           *dtc1etaphitpc[2][7];

    AliFemtoPairCutRadialDistanceKK      *sqpcetaphitpc[2][7];
    AliFemtoPairCutRadialDistanceKK      *sqpcetaphitpcRD[2][7];

    AliFemtoKTPairCut             *ktpaircut[2][7][4][11];
    //  AliFemtoQinvCorrFctn            *cqqinv[2][11][3];
    AliFemtoBPLCMS3DCorrFctn     *cq3dlcmskttpc[2][7][4][11];

    for (int imult=0; imult<7; imult++) {
        if (runmults[imult]) {
            for (int ichg=0; ichg<2; ichg++) {
                if (runch[ichg]) {

                    ana[ichg][imult] = new AliFemtoAnalysisAzimuthalPbPb2Order(4, -8.0, 8.0, 5, multbins[imult], multbins[imult+1],phimax);
                    ana[ichg][imult]->SetNumEventsToMix(3);
                    ana[ichg][imult]->SetMinSizePartCollection(4);
                    ana[ichg][imult]->SetEPhistname(Form("hist%i%i",ichg,imult));
                    mecetaphitpc[ichg][imult] = new AliFemtoBasicEventCut();
                    mecetaphitpc[ichg][imult]->SetEventMult(5,100000);//was 0.001
                    mecetaphitpc[ichg][imult]->SetVertZPos(-8,8);

                    cutPassEvMetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventMult(Form("cutPass%stpcM%i", chrgs[ichg], imult));
                    cutFailEvMetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventMult(Form("cutFail%stpcM%i", chrgs[ichg], imult));
                    mecetaphitpc[ichg][imult]->AddCutMonitor(cutPassEvMetaphitpc[ichg][imult], cutFailEvMetaphitpc[ichg][imult]);

                    cutPassEvVetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventVertex(Form("cutPass%stpcM%i", chrgs[ichg], imult));
                    cutFailEvVetaphitpc[ichg][imult] = new AliFemtoCutMonitorEventVertex(Form("cutFail%stpcM%i", chrgs[ichg], imult));
                    mecetaphitpc[ichg][imult]->AddCutMonitor(cutPassEvVetaphitpc[ichg][imult], cutFailEvVetaphitpc[ichg][imult]);

                    dtc1etaphitpc[ichg][imult] = new AliFemtoESDTrackCut();

                    if (ichg == 0)
                        dtc1etaphitpc[ichg][imult]->SetCharge(1.0);
                    else if (ichg == 1)
                        dtc1etaphitpc[ichg][imult]->SetCharge(-1.0);

                    dtc1etaphitpc[ichg][imult]->SetPt(0.15,1.5);
                    dtc1etaphitpc[ichg][imult]->SetEta(-0.8,0.8);
                    dtc1etaphitpc[ichg][imult]->SetMass(PionMass);
                    dtc1etaphitpc[ichg][imult]->SetMostProbablePion();

                    dtc1etaphitpc[ichg][imult]->SetStatus(AliESDtrack::kTPCin);
                    dtc1etaphitpc[ichg][imult]->SetminTPCncls(80);//was 0
                    dtc1etaphitpc[ichg][imult]->SetRemoveKinks(kTRUE);
                    dtc1etaphitpc[ichg][imult]->SetLabel(kFALSE);
                    dtc1etaphitpc[ichg][imult]->SetMaxTPCChiNdof(4.0);
                    dtc1etaphitpc[ichg][imult]->SetMaxImpactXY(2.4);//was 0.2
                    dtc1etaphitpc[ichg][imult]->SetMaxImpactZ(3.0);//0.15

                    sqpcetaphitpc[ichg][imult] = new AliFemtoPairCutRadialDistanceKK();
                    sqpcetaphitpcRD[ichg][imult] = new AliFemtoPairCutRadialDistanceKK();

                    sqpcetaphitpc[ichg][imult]->SetShareQualityMax(1.0);
                    sqpcetaphitpc[ichg][imult]->SetShareFractionMax(1);
                    sqpcetaphitpc[ichg][imult]->SetRemoveSameLabel(kFALSE);
                    sqpcetaphitpc[ichg][imult]->SetMinimumRadius(1.6);
                    sqpcetaphitpc[ichg][imult]->SetPhiStarDifferenceMinimum(0.0);
                    sqpcetaphitpc[ichg][imult]->SetEtaDifferenceMinimum(0.0);

                    sqpcetaphitpcRD[ichg][imult]->SetShareQualityMax(1.0);
                    sqpcetaphitpcRD[ichg][imult]->SetShareFractionMax(0.05);
                    sqpcetaphitpcRD[ichg][imult]->SetRemoveSameLabel(kFALSE);
                    sqpcetaphitpcRD[ichg][imult]->SetMinimumRadius(1.6);
                    sqpcetaphitpcRD[ichg][imult]->SetPhiStarDifferenceMinimum(0.017);
                    sqpcetaphitpcRD[ichg][imult]->SetEtaDifferenceMinimum(0.015);

                    ana[ichg][imult]->SetEventCut(mecetaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetFirstParticleCut(dtc1etaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetSecondParticleCut(dtc1etaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetPairCut(sqpcetaphitpc[ichg][imult]);
                    ana[ichg][imult]->SetPairCutRD(sqpcetaphitpcRD[ichg][imult]);

                    for (int ikt=0; ikt<kTmax; ikt++){   //  kt range

                        //  cqqinv[ichg][imult][ikt] = new AliFemtoQinvCorrFctn(Form("cqqinv%imult%ikT", ichg, imult, ikt),30, 0,0.15);

                        for (int iphi=0; iphi<phimax; iphi++){
                            ktpaircut[ichg][imult][ikt][iphi] = new AliFemtoKTPairCut(ktrng[ikt],ktrng[ikt+1]);
                            ktpaircut[ichg][imult][ikt][iphi]->SetPhiRange(phirange[iphi],phirange[iphi+1]);

                            cq3dlcmskttpc[ichg][imult][ikt][iphi] = new AliFemtoBPLCMS3DCorrFctn(Form("cq3d%imult%ikT%iRP%i", ichg, imult, ikt, iphi),20,-0.2,0.2);
                            cq3dlcmskttpc[ichg][imult][ikt][iphi]->SetPairSelectionCut(ktpaircut[ichg][imult][ikt][iphi]);
                            ana[ichg][imult]->AddCorrFctn(cq3dlcmskttpc[ichg][imult][ikt][iphi]);
                        }
                        // ana[ichg][imult]->AddCorrFctn(cqqinv[ichg][imult][ikt]);

                    }
                    Manager->AddAnalysis(ana[ichg][imult]);
                }
            }
        }
    }
    return Manager;
}

<|endoftext|>