<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>

#include "include/logging/enumCvType.hpp"

#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"

int main( int argc, char *argv[] )
{
	// Parameters for selecting which filters to apply
	int blur = 0;
	int color = 0;
    int dilate_erode = 0;
	int edge = 0;
	int laplacian = 0;
	int hough = 0;
	int depth_dist = 0;
	int merge = 0;

	// Parameters for applying filters even if windows are closed
	int apply_blur = 0;
	int apply_color = 0;
    int apply_dilate_erode = 0;
	int apply_edge = 0;
	int apply_laplacian = 0;
	int apply_hough = 0;
	int apply_depth_dist = 0;
	int apply_merge = 0;

	// gaussianBlur parameters
	int blur_ksize = 7;
	int sigmaX = 10;
	int sigmaY = 10;

	// hsvColorThreshold parameters
	int hMin = 0;
	int hMax = 255;
	int sMin = 0;
	int sMax = 255;
	int vMin = 0;
	int vMax = 255;
	int debugMode = 0; // 0 is none, 1 is debug mode
	int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v

	// dilateErode parameters
	int holes = 0;
	int noise = 0;
	int size = 1;
	cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
                      cv::Size(2 * size + 1, 2 * size + 1),
                      cv::Point(size, size) );

	// cannyEdgeDetect parameters
	int threshLow = 100;
	int threshHigh = 300;

	// laplacianSharpen parameters
	int laplacian_ksize = 3;
	int scale = 1; // optional scale value added to image
	int delta = 0; // optional delta value added to image
	int ddepth = CV_16S;

	// houghLines parameters
	int rho = 1;
	int theta = 180;
	int threshold = 50;
	int lineMin = 50;
	int maxGap = 10;

	// mergeFinal parameters
	int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100
	int weight2 = 100;
	int merge_type = 0; // 0 is none, 1 is rgb + rgb_orig, 2 is depth + depth_orig, 3 is rgb + depth

	// depthDistance parameters
	int center_x = 320; // point to calculate distance of
	int center_y = 240;
	int orig_x = 20; // point to display depth information text
	int orig_y = 450;

	std::cout << std::endl;
	std::cout << " =========== FILTER LIST =========== " << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << "| (0) No Filter                     |" << std::endl;
	std::cout << "| (1) Gaussian Blur Filter          |" << std::endl;
	std::cout << "| (2) HSV Color Filter              |" << std::endl;
	std::cout << "| (3) Dilate and Erode Filter       |" << std::endl;
	std::cout << "| (4) Canny Edge Detection Filter   |" << std::endl;
	std::cout << "| (5) Laplacian Sharpen Filter      |" << std::endl;
	std::cout << "| (6) Hough Lines Filter            |" << std::endl;
	std::cout << "| (7) Merge Final Outputs           |" << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << " =================================== " << std::endl;
	std::cout << std::endl;

	std::cout << std::endl;
	std::cout << " ============== NOTICE ============= " << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << "| Press 'q' to quit without saving  |" << std::endl;
	std::cout << "| Press ' ' to pause                |" << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << " =================================== " << std::endl;
	std::cout << std::endl;

	cv::VideoCapture camera(0);
	if( !camera.isOpened() && (argc < 2) )
	{
		std::cout << "Error - Unable to open Camera at Port 0" << std::endl;
		return -1;
	}

	// Matrices for holding image data
	cv::Mat rgb, rgb_orig;
	cv::Mat image;

	char kill = ' '; // Press q to quit the program

	while ((kill != 'q') && (kill != 's'))
	{
		if (kill == ' ') // Press space to pause program, then any key to resume
		{
			cv::waitKey(0);
		}

		// Create all the calibration windows
		selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);

		if (argc > 2) // Use images
		{
			rgb = cv::imread(argv[1]);
			rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end

			if (!rgb.data || !rgb_orig.data) // No data
			{
                std::cout << "No image data" << std::endl;
				return -1;
			}
		}
		else
		{
			camera >> rgb;
			rgb_orig = rgb.clone();
		}

		cv::imshow("BGR Feed", rgb);
        rgb.copyTo(image);

		// Filters are only applied if last parameter is true, otherwise their windows are destroyed
		gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
		hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
		dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
		cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
		laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);

#if 0
		// List sizes of images
		cv::Size rgbSize = rgb.size();
		std::cout << "RGB:   [" << rgbSize.height << " x " << rgbSize.width <<  "]" << std::endl;
		cv::Size depthSize = depth.size();
		std::cout << "Depth: [" << depthSize.height << " x " << depthSize.width << "]" << std::endl;
		cv::Size imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << std::endl;
#endif
		houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);

#if 0
		// List sizes of images
		rgbSize = rgb.size();
		std::cout << "RGB:   [" << rgbSize.height << " x " << rgbSize.width <<  "]" << std::endl;
		depthSize = depth.size();
		std::cout << "Depth: [" << depthSize.height << " x " << depthSize.width << "]" << std::endl;
		imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << std::endl;
#endif

		depthDistanceWindows(image, center_x, center_y, orig_x, orig_y, apply_depth_dist, depth_dist);

		kill = cv::waitKey(5);
	}
	return 0;
}
<commit_msg>Add drawBoundedRects method<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>

#include "include/logging/enumCvType.hpp"

#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"

void drawBoundedRects(cv::Mat& src, int thresh)
{
 	cv::Mat threshold_output;
 	std::vector<std::vector<cv::Point> > contours;
 	std::vector<cv::Vec4i> hierarchy;

	// Convert src to gray format
	cv::cvtColor(src, threshold_output, CV_BGR2GRAY);

 	/// Detect edges using Threshold
 	cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
 	/// Find contours
 	cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

 	/// Approximate contours to polygons + get bounding rects and circles
 	std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
 	std::vector<cv::Rect> boundRect(contours.size());

 	for(int i = 0; i < contours.size(); i++)
 	{
 		cv::approxPolyDP(cv::Mat(contours[i]), contours_poly[i], 3, true);
 		boundRect[i] = cv::boundingRect(cv::Mat(contours_poly[i]));
 	}

 	/// Draw polygonal contour + bonding rects + circles
 	cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
 	for(int i = 0; i < contours.size(); i++)
 	{
 		cv::Scalar color = cv::Scalar(0, 0, 255);
 		cv::drawContours(drawing, contours_poly, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
 		cv::rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0);
 	}

 	/// Show in a window
 	cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
 	cv::imshow("Contours", drawing);
}

int main( int argc, char *argv[])
{
	// Parameters for selecting which filters to apply
	int blur = 0;
	int color = 0;
    	int dilate_erode = 0;
	int edge = 0;
	int laplacian = 0;
	int hough = 0;
	int depth_dist = 0;
	int merge = 0;

	// Parameters for applying filters even if windows are closed
	int apply_blur = 0;
	int apply_color = 0;
    	int apply_dilate_erode = 0;
	int apply_edge = 0;
	int apply_laplacian = 0;
	int apply_hough = 0;
	int apply_depth_dist = 0;
	int apply_merge = 0;

	// gaussianBlur parameters
	int blur_ksize = 7;
	int sigmaX = 10;
	int sigmaY = 10;

	// hsvColorThreshold parameters
	int hMin = 0;
	int hMax = 360;
	int sMin = 0;
	int sMax = 255;
	int vMin = 0;
	int vMax = 255;
	int debugMode = 0; // 0 is none, 1 is debug mode
	int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v

	// dilateErode parameters
	int holes = 0;
	int noise = 0;
	int size = 1;
	cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
                      cv::Size(2 * size + 1, 2 * size + 1),
                      cv::Point(size, size) );

	// cannyEdgeDetect parameters
	int threshLow = 100;
	int threshHigh = 300;

	// laplacianSharpen parameters
	int laplacian_ksize = 3;
	int scale = 1; // optional scale value added to image
	int delta = 0; // optional delta value added to image
	int ddepth = CV_16S;

	// houghLines parameters
	int rho = 1;
	int theta = 180;
	int threshold = 50;
	int lineMin = 50;
	int maxGap = 10;

	// mergeFinal parameters
	int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100
	int weight2 = 100;
	int merge_type = 0; // 0 is none, 1 is rgb + rgb_orig, 2 is depth + depth_orig, 3 is rgb + depth

	// depthDistance parameters
	int center_x = 320; // point to calculate distance of
	int center_y = 240;
	int orig_x = 20; // point to display depth information text
	int orig_y = 450;

	std::cout << std::endl;
	std::cout << " =========== FILTER LIST =========== " << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << "| (0) No Filter                     |" << std::endl;
	std::cout << "| (1) Gaussian Blur Filter          |" << std::endl;
	std::cout << "| (2) HSV Color Filter              |" << std::endl;
	std::cout << "| (3) Dilate and Erode Filter       |" << std::endl;
	std::cout << "| (4) Canny Edge Detection Filter   |" << std::endl;
	std::cout << "| (5) Laplacian Sharpen Filter      |" << std::endl;
	std::cout << "| (6) Hough Lines Filter            |" << std::endl;
	std::cout << "| (7) Merge Final Outputs           |" << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << " =================================== " << std::endl;
	std::cout << std::endl;

	std::cout << std::endl;
	std::cout << " ============== NOTICE ============= " << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << "| Press 'q' to quit without saving  |" << std::endl;
	std::cout << "| Press ' ' to pause                |" << std::endl;
	std::cout << "|                                   |" << std::endl;
	std::cout << " =================================== " << std::endl;
	std::cout << std::endl;

	cv::VideoCapture camera(0);
	if( !camera.isOpened() && (argc < 2) )
	{
		std::cout << "Error - Unable to open Camera at Port 0" << std::endl;
		return -1;
	}

	// Matrices for holding image data
	cv::Mat rgb, rgb_orig;
	cv::Mat image;

	char kill = ' '; // Press q to quit the program

	int thresh = 0;

	while ((kill != 'q') && (kill != 's'))
	{
		if (kill == ' ') // Press space to pause program, then any key to resume
		{
			cv::waitKey(0);
		}

		// Create all the calibration windows
		selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);

		if (argc > 2) // Use images
		{
			rgb = cv::imread(argv[1]);
			rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end

			if (!rgb.data || !rgb_orig.data) // No data
			{
				std::cout << "No image data" << std::endl;
				return -1;
			}
		}
		else
		{
			camera >> rgb;
			rgb_orig = rgb.clone();
		}

		cv::imshow("BGR Feed", rgb);
		rgb.copyTo(image);

		cv::namedWindow("Source", CV_WINDOW_AUTOSIZE);
		cv::createTrackbar("Threshold:", "Source", &thresh, 255);

		// Filters are only applied if last parameter is true, otherwise their windows are destroyed
		gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
		hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
		dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
		drawBoundedRects(image, thresh);
		cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
		laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);

#if 0
		// List sizes of images
		cv::Size rgbSize = rgb.size();
		std::cout << "RGB:   [" << rgbSize.height << " x " << rgbSize.width <<  "]" << std::endl;
		cv::Size depthSize = depth.size();
		std::cout << "Depth: [" << depthSize.height << " x " << depthSize.width << "]" << std::endl;
		cv::Size imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << std::endl;
#endif
		houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);

#if 0
		// List sizes of images
		rgbSize = rgb.size();
		std::cout << "RGB:   [" << rgbSize.height << " x " << rgbSize.width <<  "]" << std::endl;
		depthSize = depth.size();
		std::cout << "Depth: [" << depthSize.height << " x " << depthSize.width << "]" << std::endl;
		imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << std::endl;
#endif

		depthDistanceWindows(image, center_x, center_y, orig_x, orig_y, apply_depth_dist, depth_dist);

		kill = cv::waitKey(5);
	}
	return 0;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP
#define STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP

#ifdef __GNUC__
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#ifdef __has_attribute
#if __has_attribute (noinline) && __has_attribute (cold)
/**
 * Functions tagged with this attribute are not inlined and moved
 *  to a cold branch to tell the CPU to not attempt to pre-fetch
 *  the associated function.
 */
#define STAN_COLD_PATH __attribute__((noinline, cold))
#endif
#endif
#else
#define likely(x) (x)
#define unlikely(x) (x)
#define STAN_COLD_PATH
#endif

/**
 * Turns all range and size checks into no-ops
 */
#ifndef STAN_NO_RANGE_AND_SIZE_CHECK
#ifdef STAN_NDEBUG
#define STAN_NO_RANGE_AND_SIZE_CHECK return
#endif
#else
#define STAN_NO_RANGE_AND_SIZE_CHECK
#endif

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP
#define STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP

#ifdef __GNUC__
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#ifdef __has_attribute
#if __has_attribute(noinline) && __has_attribute(cold)
/**
 * Functions tagged with this attribute are not inlined and moved
 *  to a cold branch to tell the CPU to not attempt to pre-fetch
 *  the associated function.
 */
#define STAN_COLD_PATH __attribute__((noinline, cold))
#endif
#endif
#else
#define likely(x) (x)
#define unlikely(x) (x)
#define STAN_COLD_PATH
#endif

/**
 * Turns all range and size checks into no-ops
 */
#ifndef STAN_NO_RANGE_AND_SIZE_CHECK
#ifdef STAN_NDEBUG
#define STAN_NO_RANGE_AND_SIZE_CHECK return
#endif
#else
#define STAN_NO_RANGE_AND_SIZE_CHECK
#endif

#endif
<|endoftext|>


<commit_before>#include <Core/Geometry/Normal/Normal.hpp>

#include <Core/Index/CircularIndex.hpp>
#include <Core/Geometry/Triangle/TriangleOperation.hpp>

namespace Ra {
namespace Core {
namespace Geometry {

//////////////
/// GLOBAL ///
//////////////

void uniformNormal( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, VectorArray< Vector3 >& normal ) {
    const uint N = p.size();
    normal.clear();
    normal.resize( N, Vector3::Zero() );
#pragma omp parallel for
    for( uint n = 0; n < T.size(); ++n ) {
    //for( const auto& t : T ) {
        const auto& t = T[n];
        const uint i = t( 0 );
        const uint j = t( 1 );
        const uint k = t( 2 );
        const Vector3 triN = triangleNormal( p[i], p[j], p[k] );
        if( !triN.allFinite() ) {
            continue;
        }
#pragma omp critical
{
        normal[i] += triN;
        normal[j] += triN;
        normal[k] += triN;
}
    }
#pragma omp parallel for
    for( uint i = 0; i < N; ++i ) {
        if( !normal[i].isApprox( Vector3::Zero() ) ) {
            normal[i].normalize();
        }
    }
}

void angleWeightedNormal( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, VectorArray< Vector3 >& normal ) {
    const uint N = p.size();
    normal.clear();
    normal.resize( N, Vector3::Zero() );
    for( const auto& t : T ) {
        uint i = t( 0 );
        uint j = t( 1 );
        uint k = t( 2 );
        const Vector3 triN = triangleNormal( p[i], p[j], p[k] );
        const Scalar theta_i = Vector::angle( ( p[j] - p[i] ), ( p[k] - p[i] ) );
        const Scalar theta_j = Vector::angle( ( p[i] - p[j] ), ( p[k] - p[j] ) );
        const Scalar theta_k = Vector::angle( ( p[i] - p[k] ), ( p[j] - p[k] ) );
        normal[i] += theta_i * triN;
        normal[j] += theta_j * triN;
        normal[k] += theta_k * triN;
    }
    for( auto& n : normal ) {
        n.normalize();
    }
}

void areaWeightedNormal( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, VectorArray< Vector3 >& normal ) {
    const uint N = p.size();
    normal.clear();
    normal.resize( N, Vector3::Zero() );
    for( const auto& t : T ) {
        uint i = t( 0 );
        uint j = t( 1 );
        uint k = t( 2 );
        const Scalar  area = triangleArea( p[i], p[j], p[k] );
        const Vector3 triN = area * triangleNormal( p[i], p[j], p[k] );
        normal[i] += triN;
        normal[j] += triN;
        normal[k] += triN;
    }
    for( auto& n : normal ) {
        n.normalize();
    }
}

////////////////
/// ONE RING ///
////////////////

Vector3 uniformNormal( const Vector3& v, const VectorArray< Vector3 >& one_ring ) {
    Vector3 normal;
    normal.setZero();
    uint N = one_ring.size();
    CircularIndex i;
    i.setSize( N );
    for( uint j = 0; j < N; ++j ) {
        i.setValue( j );
        normal += triangleNormal( v, one_ring[i], one_ring[i-1] );
    }
    return normal.normalized();
}

Vector3 angleWeightedNormal( const Vector3& v, const VectorArray< Vector3 >& one_ring ) {
    Vector3 normal;
    normal.setZero();
    uint N = one_ring.size();
    CircularIndex i;
    i.setSize( N );
    for( uint j = 0; j < N; ++j ) {
        i.setValue( j );
        Scalar theta = Vector::angle( ( one_ring[i] - v ), ( one_ring[i-1] - v ) );
        normal += theta * triangleNormal( v, one_ring[i], one_ring[i-1] );
    }
    return normal.normalized();
}

Vector3 areaWeightedNormal( const Vector3& v, const VectorArray< Vector3 >& one_ring ) {
    Vector3 normal;
    normal.setZero();
    uint N = one_ring.size();
    CircularIndex i;
    i.setSize( N );
    for( uint j = 0; j < N; ++j ) {
        i.setValue( j );
        Scalar area = triangleArea( v, one_ring[i], one_ring[i-1] );
        normal += area * triangleNormal( v, one_ring[i], one_ring[i-1] );
    }
    return normal.normalized();
}

}
}
}
<commit_msg>Fixed the normalization problem for all the function in Normal<commit_after>#include <Core/Geometry/Normal/Normal.hpp>

#include <Core/Index/CircularIndex.hpp>
#include <Core/Geometry/Triangle/TriangleOperation.hpp>

namespace Ra {
namespace Core {
namespace Geometry {

//////////////
/// GLOBAL ///
//////////////

void uniformNormal( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, VectorArray< Vector3 >& normal ) {
    const uint N = p.size();
    normal.clear();
    normal.resize( N, Vector3::Zero() );
#pragma omp parallel for
    for( uint n = 0; n < T.size(); ++n ) {
    //for( const auto& t : T ) {
        const auto& t = T[n];
        const uint i = t( 0 );
        const uint j = t( 1 );
        const uint k = t( 2 );
        const Vector3 triN = triangleNormal( p[i], p[j], p[k] );
        if( !triN.allFinite() ) {
            continue;
        }
#pragma omp critical
{
        normal[i] += triN;
        normal[j] += triN;
        normal[k] += triN;
}
    }
#pragma omp parallel for
    for( uint i = 0; i < N; ++i ) {
        if( !normal[i].isApprox( Vector3::Zero() ) ) {
            normal[i].normalize();
        }
    }
}

void angleWeightedNormal( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, VectorArray< Vector3 >& normal ) {
    const uint N = p.size();
    normal.clear();
    normal.resize( N, Vector3::Zero() );
    for( const auto& t : T ) {
        uint i = t( 0 );
        uint j = t( 1 );
        uint k = t( 2 );
        const Vector3 triN = triangleNormal( p[i], p[j], p[k] );
        const Scalar theta_i = Vector::angle( ( p[j] - p[i] ), ( p[k] - p[i] ) );
        const Scalar theta_j = Vector::angle( ( p[i] - p[j] ), ( p[k] - p[j] ) );
        const Scalar theta_k = Vector::angle( ( p[i] - p[k] ), ( p[j] - p[k] ) );
        normal[i] += theta_i * triN;
        normal[j] += theta_j * triN;
        normal[k] += theta_k * triN;
    }
    for( auto& n : normal ) {
        if( !n.isApprox( Vector3::Zero() ) ) {
            n.normalize();
        }
    }
}

void areaWeightedNormal( const VectorArray< Vector3 >& p, const VectorArray< Triangle >& T, VectorArray< Vector3 >& normal ) {
    const uint N = p.size();
    normal.clear();
    normal.resize( N, Vector3::Zero() );
    for( const auto& t : T ) {
        uint i = t( 0 );
        uint j = t( 1 );
        uint k = t( 2 );
        const Scalar  area = triangleArea( p[i], p[j], p[k] );
        const Vector3 triN = area * triangleNormal( p[i], p[j], p[k] );
        normal[i] += triN;
        normal[j] += triN;
        normal[k] += triN;
    }
    for( auto& n : normal ) {
        if( !n.isApprox( Vector3::Zero() ) ) {
            n.normalize();
        }
    }
}

////////////////
/// ONE RING ///
////////////////

Vector3 uniformNormal( const Vector3& v, const VectorArray< Vector3 >& one_ring ) {
    Vector3 normal;
    normal.setZero();
    uint N = one_ring.size();
    CircularIndex i;
    i.setSize( N );
    for( uint j = 0; j < N; ++j ) {
        i.setValue( j );
        normal += triangleNormal( v, one_ring[i], one_ring[i-1] );
    }
    if( !normal.isApprox( Vector3::Zero() ) ) {
        return normal.normalized();
    }
    return Vector3::Zero();
}

Vector3 angleWeightedNormal( const Vector3& v, const VectorArray< Vector3 >& one_ring ) {
    Vector3 normal;
    normal.setZero();
    uint N = one_ring.size();
    CircularIndex i;
    i.setSize( N );
    for( uint j = 0; j < N; ++j ) {
        i.setValue( j );
        Scalar theta = Vector::angle( ( one_ring[i] - v ), ( one_ring[i-1] - v ) );
        normal += theta * triangleNormal( v, one_ring[i], one_ring[i-1] );
    }
    if( !normal.isApprox( Vector3::Zero() ) ) {
        return normal.normalized();
    }
    return Vector3::Zero();
}

Vector3 areaWeightedNormal( const Vector3& v, const VectorArray< Vector3 >& one_ring ) {
    Vector3 normal;
    normal.setZero();
    uint N = one_ring.size();
    CircularIndex i;
    i.setSize( N );
    for( uint j = 0; j < N; ++j ) {
        i.setValue( j );
        Scalar area = triangleArea( v, one_ring[i], one_ring[i-1] );
        normal += area * triangleNormal( v, one_ring[i], one_ring[i-1] );
    }
    if( !normal.isApprox( Vector3::Zero() ) ) {
        return normal.normalized();
    }
    return Vector3::Zero();
}

}
}
}
<|endoftext|>


<commit_before>#include "header.h"
#include <fstream>

/* Function to define geometry, initialize ants, and run/write simulation */
int main(int argc, char** argv)
{

	//First get number of ants in sim either from first arg of command line or hardcode
	int num_ants;
	if(argc == 1){
		num_ants = 20; // number of ants in simulation
	}else{
		num_ants = atoi(argv[1]);
	}
	//std::cout << "Number of Ants:\t" << num_ants << std::endl;

	/* Define Variables */
	long double R = 2;  // Box Radius (in cm)
	long double a = 1;  // aperture size (in cm)
	long double velo = .1; // initial ant velocity (in cm/s)
	long double r_enc = 0.1;  // encounter radius (cm)
	bool single_particle = false; // true means we start a single particle starting IN APERTURE CENTER
	bool fixed_velo = true; // if true, ants will never change velocity, only heading
	bool start_in_center = true; // true means one ant 0 starts in center of aperture facing down
	bool exit_flag = true; // true means the trial ends when ant 0 leaves
	int max_init = 500;  // max number of tries to initialize a given setup so no ants overlap
	int max_steps= 10000; // max number of events in simulation (event is collision w/ wall or ant)

	int ants_in_nest; // used to calculate how many ants are in nest
	bool collision_flag = true; // true means collisions are on
	bool all_clear = false;  // used to break out of main simulation
	int counter = 0; // counts simulation steps

	long double t_wall,t_ant; // variables to store the time until a collision
	int index1,index2,index3; // indices for particles involved in collision
	//int seed = 8;  // pass the same seed to 'populate' method to initialize trial the same way

	// Write parameters to file
	std::ofstream params("params.txt");
	params << "R\ta\tvelocity\tr_enc\tnum_ants\tcollision_flag\tcenter_flag\texit_flag" << std::endl;
	params << R << "\t" << a << "\t" << velo << "\t" << r_enc << "\t" << num_ants << "\t"
			<< collision_flag << "\t" << start_in_center << "\t" << exit_flag << std::endl;
	params.close();

	// Open file to hold simulation data
	std::ofstream data_file("output.txt");
	data_file << "Name\t" << "x\t" << "y\t" << "v_x\t" << "v_y\t" << "event_time\t"
				<< "exit_time\t" << "collisions\t" << "in_nest" << std::endl;

	/* Initialize ants */
	Ants ants = Ants(num_ants); // instance of Ants called ants
	try{
		if(single_particle){
			ants.populate(R,a,velo,r_enc); // initialize a single particle
		}
		else{
			ants.populate(R,velo,r_enc,max_init,start_in_center); // initialize positions and velocities
		}
	}
	catch(std::runtime_error &e){
		std::cerr << "RUNTIME ERROR: " << e.what() << std::endl;
		return 1;
	}

	data_file << ants; //prints all of ants to name.txt using overloaded operator <<

	/* Run Sim */
	while(all_clear == false){

		try{
			t_wall = get_t_wall(ants,R,r_enc,index1); // how long double until colliding with wall?
		}
		catch(std::runtime_error &e){
			std::cerr << "RUNTIME ERROR: " << e.what() << std::endl;
			return 1;
		}

		if(collision_flag == true && single_particle == false){
			try{
				t_ant = get_t_ant(ants,r_enc,t_wall,index2,index3); // how long double before colliding with another ant?
			}
			catch(std::runtime_error &e){
				std::cerr << "RUNTIME ERROR: " << e.what() << std::endl;
				return 1;
			}
			if(t_ant < t_wall && fixed_velo == false){
				ants.update(t_ant,r_enc,index2,index3); // run an ant-to-ant collision with conservation of momentum
			}else if(t_ant < t_wall && fixed_velo == true){
				ants.update(t_ant,r_enc,index2,index3,velo); // run an ant-to-ant collision with fixed velocity
			}else{
				ants.update(R,r_enc,a,t_wall,index1);	// run ant-to-wall collisions for single particle
			}
		}else{
			ants.update(R,r_enc,a,t_wall,index1);	// run ant-to-wall collisions for single particle
		}

		data_file << ants; //write to file

		// Test to see if the trial is done
		if(exit_flag == true){
			if(ants.nest_flag.at(0)==0){
				//std::cout << "Ant 0 has left nest -- trial complete.\n";

				std::cout << "Good\t" << num_ants << "\t" << ants.event_time[0] << "\t" << ants.collisions[0] << std::endl;
				all_clear = true;
			}
		}else{
			//Calculate how many ants are still in nest
			ants_in_nest = std::accumulate(ants.nest_flag.begin(),ants.nest_flag.end(),0);
			if(ants_in_nest == 0){
				std::cout << "OK\t" << ants.event_time[0] << "\t" << ants.collisions[0] << std::endl;
				//std::cout << "All ants have left nest -- trial complete.\n" << std::endl;
				all_clear = true;
			}else{
				counter++;
				//std::cout << "Counter: " << counter << "/" << max_steps << std::endl;
				if(counter >= max_steps){
					//std::cout << "Maximum iterations reached -- trial terminated.\n" << std::endl;
					std::cout << "Bad\t" << num_ants << "\t" << ants.event_time[0] << "\t" << ants.collisions[0] << std::endl;
					all_clear = true;
				}
			}
		}
	}

	data_file.close();
	// std::cout << "ANTS LEFT: " << ants_in_nest << std::endl;
	// std::cout << "SIMULATION COMPLETE." << std::endl;

}
<commit_msg>Fix max iter bug<commit_after>#include "header.h"
#include <fstream>

/* Function to define geometry, initialize ants, and run/write simulation */
int main(int argc, char** argv)
{

	//First get number of ants in sim either from first arg of command line or hardcode
	int num_ants;
	if(argc == 1){
		num_ants = 20; // number of ants in simulation
	}else{
		num_ants = atoi(argv[1]);
	}
	//std::cout << "Number of Ants:\t" << num_ants << std::endl;

	/* Define Variables */
	long double R = 2;  // Box Radius (in cm)
	long double a = 1;  // aperture size (in cm)
	long double velo = .1; // initial ant velocity (in cm/s)
	long double r_enc = 0.1;  // encounter radius (cm)
	bool single_particle = false; // true means we start a single particle starting IN APERTURE CENTER
	bool fixed_velo = true; // if true, ants will never change velocity, only heading
	bool start_in_center = true; // true means one ant 0 starts in center of aperture facing down
	bool exit_flag = true; // true means the trial ends when ant 0 leaves
	int max_init = 500;  // max number of tries to initialize a given setup so no ants overlap
	int max_steps= 50000; // max number of events in simulation (event is collision w/ wall or ant)

	int ants_in_nest; // used to calculate how many ants are in nest
	bool collision_flag = true; // true means collisions are on
	bool all_clear = false;  // used to break out of main simulation
	int counter = 0; // counts simulation steps

	long double t_wall,t_ant; // variables to store the time until a collision
	int index1,index2,index3; // indices for particles involved in collision
	//int seed = 8;  // pass the same seed to 'populate' method to initialize trial the same way

	// Write parameters to file
	std::ofstream params("params.txt");
	params << "R\ta\tvelocity\tr_enc\tnum_ants\tcollision_flag\tcenter_flag\texit_flag" << std::endl;
	params << R << "\t" << a << "\t" << velo << "\t" << r_enc << "\t" << num_ants << "\t"
			<< collision_flag << "\t" << start_in_center << "\t" << exit_flag << std::endl;
	params.close();

	// Open file to hold simulation data
	std::ofstream data_file("output.txt");
	data_file << "Name\t" << "x\t" << "y\t" << "v_x\t" << "v_y\t" << "event_time\t"
				<< "exit_time\t" << "collisions\t" << "in_nest" << std::endl;

	/* Initialize ants */
	Ants ants = Ants(num_ants); // instance of Ants called ants
	try{
		if(single_particle){
			ants.populate(R,a,velo,r_enc); // initialize a single particle
		}
		else{
			ants.populate(R,velo,r_enc,max_init,start_in_center); // initialize positions and velocities
		}
	}
	catch(std::runtime_error &e){
		std::cerr << "RUNTIME ERROR: " << e.what() << std::endl;
		return 1;
	}

	data_file << ants; //prints all of ants to name.txt using overloaded operator <<

	/* Run Sim */
	while(all_clear == false){

		try{
			t_wall = get_t_wall(ants,R,r_enc,index1); // how long double until colliding with wall?
		}
		catch(std::runtime_error &e){
			std::cerr << "RUNTIME ERROR: " << e.what() << std::endl;
			return 1;
		}

		if(collision_flag == true && single_particle == false){
			try{
				t_ant = get_t_ant(ants,r_enc,t_wall,index2,index3); // how long double before colliding with another ant?
			}
			catch(std::runtime_error &e){
				std::cerr << "RUNTIME ERROR: " << e.what() << std::endl;
				return 1;
			}
			if(t_ant < t_wall && fixed_velo == false){
				ants.update(t_ant,r_enc,index2,index3); // run an ant-to-ant collision with conservation of momentum
			}else if(t_ant < t_wall && fixed_velo == true){
				ants.update(t_ant,r_enc,index2,index3,velo); // run an ant-to-ant collision with fixed velocity
			}else{
				ants.update(R,r_enc,a,t_wall,index1);	// run ant-to-wall collisions for single particle
			}
		}else{
			ants.update(R,r_enc,a,t_wall,index1);	// run ant-to-wall collisions for single particle
		}

		data_file << ants; //write to file

		// Test to see if we've reached max iterations
		counter++;
		//std::cout << "Counter: " << counter << "/" << max_steps << std::endl;
		if(counter >= max_steps){
			//std::cout << "Maximum iterations reached -- trial terminated." << std::endl;
			std::cout << "Bad\t" << num_ants << "\t" << ants.event_time[0] << "\t" << ants.collisions[0] << std::endl;
			all_clear = true;
		}
		// Test to see if ant 0 has left
		if(exit_flag == true){
			if(ants.nest_flag.at(0)==0){
				//std::cout << "Ant 0 has left nest -- trial complete.\n";
				std::cout << "Good\t" << num_ants << "\t" << ants.event_time[0] << "\t" << ants.collisions[0] << std::endl;
				all_clear = true;
			}
		}else{
			//Calculate how many ants are still in nest
			ants_in_nest = std::accumulate(ants.nest_flag.begin(),ants.nest_flag.end(),0);
			if(ants_in_nest == 0){
				std::cout << "Good\t" << num_ants << "\t" << ants.event_time[0] << "\t" << ants.collisions[0] << std::endl;
				//std::cout << "All ants have left nest -- trial complete.\n" << std::endl;
				all_clear = true;
			}
		}
	}

	data_file.close();
	// std::cout << "ANTS LEFT: " << ants_in_nest << std::endl;
	// std::cout << "SIMULATION COMPLETE." << std::endl;

}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cinttypes>
#include <cstdint>
#include <array>

using namespace std;
/*
 * MEMO
 *  - 障害物はスコアに入らないので、スコアと障害物の両方を1として表すことはできない
 */

// -- Constant Values
// 石操作情報
constexpr uint8_t REVERSED = 1,     // これが立ってたら反転してる
  ROTATED_90 = 2,   // これが立ってたら90度回転
  ROTATED_180 = 4,  // これがry
  ROTATED_270 = 6;

// Type Declarations
using RawStone = std::array<std::array<char, 8>, 8>;
using RawField = std::array<std::array<char, 32>, 32>;
using STONE_MANIPULATION = uint8_t;

class Stone;
class Field;

// Variable Forward Declarations
extern Stone stones[256];

// Type Definitions
class Stone {
public:
  RawStone raw;
};

class Field {
private:
  const Stone* put_stones[256];
  STONE_MANIPULATION manipulations[256];
  uint16_t field_score = 0;
public:
  RawField raw;
public:
  void put_stone(const uint8_t n, STONE_MANIPULATION m) {
    put_stones[n] = &stones[n];
    manipulations[n] = m;
  }
  bool try_put_stone(const uint8_t n, int y, int x, STONE_MANIPULATION m);
  const uint16_t score() const { return field_score; };
};

// Member Functions
bool Field::try_put_stone(const uint8_t n, int displacement_y, int displacement_x, STONE_MANIPULATION m) {
  const RawStone& stone = stones[n].raw;
  RawField backup = raw;
  if (!(-7 <= displacement_y && displacement_y < 32 && -7 <= displacement_x && displacement_x < 32))  // 入力をVaridate
	  return false;
  switch (m) { // 害悪
    case ROTATED_90://90度反転 -> y終端でxインクリメント・x方向を反転(デクリメント)
      for (int x = 8; x < 0; --x) for (int y = 0; y > 0; ++y) {
        if (stone[y][x] == '1') {
          if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
          } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
        	continue;
          } else {
            raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++field_score;
          }
        }
      }
      break;
    case ROTATED_180://180度回転 -> x,y方向を反転(デクリメント)
      for (int y = 8; y > 0; --y) for (int x = 8; x > 0; --x) {
        if (stone[y][x] == '1') {
         if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
         } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
           	continue;
         } else {
           raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
           ++field_score;
        }
       }
      }
      break;
    case ROTATED_270://270度回転 -> y終端でxインクリメント・y方向を反転(デクリメント)
      for (int x = 8; x > 0; ++x) for (int y = 8; y > 0; --y) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
             return false;
            }else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
             continue;
            } else {
             raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++field_score;
           }
         }
        }
      break;
    case REVERSED://反転 -> x方向をデクリメントに
    	for (int y = 0; y < 8; ++y) for (int x = 8; x > 0; --x) {
    	 if (stone[y][x] == '1') {
    	    if (raw[y+displacement_y][x+displacement_x] != '0') {
    	        return false;
    	    } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
    	        continue;
    	    } else {
    	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
    	        ++field_score;
    	    }
    	  }
        }
    	break;
    case ROTATED_90 | REVERSED:
	//反転+90度回転 -> y終端でxデクリメント・y方向をデクリメントに
	   for (int x = 8; x > 0; --x) for (int y = 8; y > 0; --y) {
	    if (stone[y][x] == '1') {
	      if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	       } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	       } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	        }
	     }
	   }
      break;
    case ROTATED_180 | REVERSED:
	//反転+180度回転 -> yデクリメント
	   for (int y = 8; y > 0; --y) for (int x = 0; x < 8; ++x) {
	    if (stone[y][x] == '1') {
	     if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	     } else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	     } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	     }
	    }
	   }
      break;
    case ROTATED_270 | REVERSED:
	//y終端でxインクリメント
	  for (int x = 0; x < 8; ++x) for (int y = 0; y < 8; ++y) {
	   if (stone[y][x] == '1') {
	    if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	    } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	    } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	    }
	   }
	  }
      break;
    default: // Regard as a non-manipulated stone
      for (int y = 0; y < 8; ++y) for (int x = 0; x < 8; ++x) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
        	   return false;
        } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
        	   continue;
        } else {
        	   raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
        	    ++field_score;
        }
       }
      }
      break;
  }
  return true;
}

// Variable Declarations
Field max_score_field; // 最適な解があるField
Stone stones[256]; // 渡されるstoneを格納
uint16_t number_of_stones; // 渡されるstoneの数

// -- Function Declarations
void solve(Field f, uint8_t look_nth_stone);

void parse(Field*);
void parse_field(Field* f);
void parse_stone();

int main() {
  Field f;
//   get_problem_file();
  parse(&f);
  solve(f, 0);
  printf("%d\n", max_score_field.score());
  for (int y = 0; y < 32; ++y)  {
    for (int x = 0; x < 32; ++x) {
      printf("%c", max_score_field.raw[y][x]);
    }
    printf("\n");
  }
//   submit();
  return 0;
}

// -- Function Definitions

/**
 * solve
 *
 * 問題を解くぞい
 *
 * -- Args
 *  Field f: 現在のフィールドの状態
 *  uint8_t look_nth_stone: 何番の石を置こうとしているか
 *
 * -- Return
 *  void
 *
 * -- 副作用
 *  max_score_field
 */
void solve(Field f, uint8_t look_nth_stone) {

  if (look_nth_stone >= number_of_stones) { // 一番深いところでスコア更新
    if (f.score() > max_score_field.score()) { // より良い結果が出るならそれを最適解フィールドとして登録
      max_score_field = f;
    }
    return;
  }

  solve(f, look_nth_stone + 1); // 今回は石を置かなかった

  for (int i = 0; i < 8; ++i) { // 回転反転組み合わせを試す
    for (int y = -7; y < 32; ++y) for (int x = -7; x < 32; ++x) { // (32+8) * (32+8)のフィールドのどこかに置く
      if (f.try_put_stone(look_nth_stone, y, x, i))
        solve(f, look_nth_stone + 1);
    }
  }
}

/*
 * parse_field
 *
 * 入力からField部分をパースする
 * -- Args
 *  Field* f: パースした結果を格納するfield
 *
 * -- 副作用
 *  stdin
 */
void parse_field(Field* f) {
  for (int i = 0; i < 32; ++i) {
    fread(f->raw[i].data(), sizeof(char[32]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/*
 * parse_stone
 *
 * 入力からStone部分をパースする
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse_stone() {
  for (int i = 0; i < number_of_stones; ++i) for (int j = 0; j < 8; ++j) {
    fread(stones[i].raw[j].data(), sizeof(char[8]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/**
 * parse
 *
 * 入力をパースする
 *
 * -- Args
 *  Field* f: パースした結果を格納するFieldのポインタ
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse(Field* f) {
  parse_field(f);
  getc(stdin); // 改行読み捨て CR
  getc(stdin); // LF
  scanf("%" SCNu16 "¥n", &number_of_stones); // SCNu8 is placeholder for uint8_t declared in cinttypes
  for (int i = 0; i < number_of_stones; ++i) {
    parse_stone();
    getc(stdin); // 改行読み捨て CR
    getc(stdin); // LF
  }
}
<commit_msg>Add a class: StoneManipulations.<commit_after>#include <cstdio>
#include <cinttypes>
#include <cstdint>
#include <array>

using namespace std;
/*
 * MEMO
 *  - 障害物はスコアに入らないので、スコアと障害物の両方を1として表すことはできない
 */

// -- Constant Values
// 石操作情報
constexpr uint8_t REVERSED = 1,     // これが立ってたら反転してる
  ROTATED_90 = 2,   // これが立ってたら90度回転
  ROTATED_180 = 4,  // これがry
  ROTATED_270 = 6;

// Type Declarations
using RawStone = std::array<std::array<char, 8>, 8>;
using RawField = std::array<std::array<char, 32>, 32>;

class Stone;
class Field;
class StoneManipulations;

// Variable Forward Declarations
extern Stone stones[256];

// Type Definitions
class Stone {
public:
  RawStone raw;
};

class Field {
private:
  const Stone* put_stones[256];
  STONE_MANIPULATION manipulations[256];
  uint16_t field_score = 0;
public:
  RawField raw;
public:
  void put_stone(const uint8_t n, STONE_MANIPULATION m) {
    put_stones[n] = &stones[n];
    manipulations[n] = m;
  }
  bool try_put_stone(const uint8_t n, int y, int x, STONE_MANIPULATION m);
  const uint16_t score() const { return field_score; };
};

class StoneManipulations {
  public:
    StoneManipulations(int8_t x, int8_t y, uint8_t rotated):
      x(x), y(y), rotated(rotated) {} // This is correct. Initialize members variable by arguments.
    int8_t x, y;
    uint8_t rotated;
};

// Member Functions
bool Field::try_put_stone(const uint8_t n, int displacement_y, int displacement_x, STONE_MANIPULATION m) {
  const RawStone& stone = stones[n].raw;
  RawField backup = raw;
  if (!(-7 <= displacement_y && displacement_y < 32 && -7 <= displacement_x && displacement_x < 32))  // 入力をVaridate
	  return false;
  switch (m) { // 害悪
    case ROTATED_90://90度反転 -> y終端でxインクリメント・x方向を反転(デクリメント)
      for (int x = 8; x < 0; --x) for (int y = 0; y > 0; ++y) {
        if (stone[y][x] == '1') {
          if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
          } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
        	continue;
          } else {
            raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++field_score;
          }
        }
      }
      break;
    case ROTATED_180://180度回転 -> x,y方向を反転(デクリメント)
      for (int y = 8; y > 0; --y) for (int x = 8; x > 0; --x) {
        if (stone[y][x] == '1') {
         if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
         } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
           	continue;
         } else {
           raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
           ++field_score;
        }
       }
      }
      break;
    case ROTATED_270://270度回転 -> y終端でxインクリメント・y方向を反転(デクリメント)
      for (int x = 8; x > 0; ++x) for (int y = 8; y > 0; --y) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
             return false;
            }else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
             continue;
            } else {
             raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++field_score;
           }
         }
        }
      break;
    case REVERSED://反転 -> x方向をデクリメントに
    	for (int y = 0; y < 8; ++y) for (int x = 8; x > 0; --x) {
    	 if (stone[y][x] == '1') {
    	    if (raw[y+displacement_y][x+displacement_x] != '0') {
    	        return false;
    	    } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
    	        continue;
    	    } else {
    	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
    	        ++field_score;
    	    }
    	  }
        }
    	break;
    case ROTATED_90 | REVERSED:
	//反転+90度回転 -> y終端でxデクリメント・y方向をデクリメントに
	   for (int x = 8; x > 0; --x) for (int y = 8; y > 0; --y) {
	    if (stone[y][x] == '1') {
	      if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	       } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	       } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	        }
	     }
	   }
      break;
    case ROTATED_180 | REVERSED:
	//反転+180度回転 -> yデクリメント
	   for (int y = 8; y > 0; --y) for (int x = 0; x < 8; ++x) {
	    if (stone[y][x] == '1') {
	     if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	     } else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	     } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	     }
	    }
	   }
      break;
    case ROTATED_270 | REVERSED:
	//y終端でxインクリメント
	  for (int x = 0; x < 8; ++x) for (int y = 0; y < 8; ++y) {
	   if (stone[y][x] == '1') {
	    if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	    } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	    } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	    }
	   }
	  }
      break;
    default: // Regard as a non-manipulated stone
      for (int y = 0; y < 8; ++y) for (int x = 0; x < 8; ++x) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
        	   return false;
        } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
        	   continue;
        } else {
        	   raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
        	    ++field_score;
        }
       }
      }
      break;
  }
  return true;
}

// Variable Declarations
Field max_score_field; // 最適な解があるField
Stone stones[256]; // 渡されるstoneを格納
uint16_t number_of_stones; // 渡されるstoneの数

// -- Function Declarations
void solve(Field f, uint8_t look_nth_stone);

void parse(Field*);
void parse_field(Field* f);
void parse_stone();

int main() {
  Field f;
//   get_problem_file();
  parse(&f);
  solve(f, 0);
  printf("%d\n", max_score_field.score());
  for (int y = 0; y < 32; ++y)  {
    for (int x = 0; x < 32; ++x) {
      printf("%c", max_score_field.raw[y][x]);
    }
    printf("\n");
  }
//   submit();
  return 0;
}

// -- Function Definitions

/**
 * solve
 *
 * 問題を解くぞい
 *
 * -- Args
 *  Field f: 現在のフィールドの状態
 *  uint8_t look_nth_stone: 何番の石を置こうとしているか
 *
 * -- Return
 *  void
 *
 * -- 副作用
 *  max_score_field
 */
void solve(Field f, uint8_t look_nth_stone) {

  if (look_nth_stone >= number_of_stones) { // 一番深いところでスコア更新
    if (f.score() > max_score_field.score()) { // より良い結果が出るならそれを最適解フィールドとして登録
      max_score_field = f;
    }
    return;
  }

  solve(f, look_nth_stone + 1); // 今回は石を置かなかった

  for (int i = 0; i < 8; ++i) { // 回転反転組み合わせを試す
    for (int y = -7; y < 32; ++y) for (int x = -7; x < 32; ++x) { // (32+8) * (32+8)のフィールドのどこかに置く
      if (f.try_put_stone(look_nth_stone, y, x, i))
        solve(f, look_nth_stone + 1);
    }
  }
}

/*
 * parse_field
 *
 * 入力からField部分をパースする
 * -- Args
 *  Field* f: パースした結果を格納するfield
 *
 * -- 副作用
 *  stdin
 */
void parse_field(Field* f) {
  for (int i = 0; i < 32; ++i) {
    fread(f->raw[i].data(), sizeof(char[32]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/*
 * parse_stone
 *
 * 入力からStone部分をパースする
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse_stone() {
  for (int i = 0; i < number_of_stones; ++i) for (int j = 0; j < 8; ++j) {
    fread(stones[i].raw[j].data(), sizeof(char[8]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/**
 * parse
 *
 * 入力をパースする
 *
 * -- Args
 *  Field* f: パースした結果を格納するFieldのポインタ
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse(Field* f) {
  parse_field(f);
  getc(stdin); // 改行読み捨て CR
  getc(stdin); // LF
  scanf("%" SCNu16 "¥n", &number_of_stones); // SCNu8 is placeholder for uint8_t declared in cinttypes
  for (int i = 0; i < number_of_stones; ++i) {
    parse_stone();
    getc(stdin); // 改行読み捨て CR
    getc(stdin); // LF
  }
}
<|endoftext|>


<commit_before>/*****************************
 *
 * Libraries
 *
 * ****************************/
#include <boost/program_options.hpp>

#include <ltiTimer.h>

/*****************************
 *
 * NameSpaces
 *
 * ****************************/
 namespace po = boost::program_options;

/******************************************************
 *
 * Help Function
 *
 * **********************************************/
void help()  {
	cout << "usage: \n" << endl;

	cout << "usage: Campbell-Robson [option] [N] [option] [N] ... \n" << endl;
	cout << "       -r|--rows <M>     the number of rows" 			<< endl;
	cout << "       -c|--columns <N>  the number of columns" 			<< endl;
	cout << "       -l|--lineal       if the use what linear scale" 	<< endl;
	cout << "       -x|--rowShow <N>  the number of row to show" 		<< endl;
	cout << "       -h|--help        show this help\n"	<< endl;

}

/******************************************************
 *
 * The main function
 *
 * **********************************************/
int main(int argc, char *argv[])
{

	// 64×48 pixeles y 1920×1080 pixeles
	// 10 valores intermedios

	// 3×3 pixeles y 1023×1023 pixeles
	// 10 valores intermedios

	// Generar una tabla con 100 campos del cruze de esos datos
	// Tomar n muestras de cada funcion

	// Example of how to use boost program options

	if (argc > 1) {

		// If the user is asked about info
		if (std::string(argv[1])=="-h" || std::string(argv[1])=="--help") {
			help();
			return EXIT_SUCCESS;
		}

		po::options_description desc("Usage");
		desc.add_options()
		("robots", po::value<int>()->default_value(3),
		"How many robots do you want to send on a murderous rampage?");

		po::variables_map opts;
		po::store(po::parse_command_line(argc, argv, desc), opts);

		try {
			po::notify(opts);
		} catch (std::exception& e) {
			std::cerr << "Error: " << e.what() << "\n";
			return 1;
		}

		int nRobots = opts["robots"].as<int>();
		// automatically assigns default when option not supplied by user!!

		std::cout << nRobots << " robots have begun the silicon revolution" << std::endl;

		// End example

		lti::timer chron;

		chron.start();

		lti::loadImage loader; // functor to load images
		lti::image img;        // the image loaded will be left here.

		loader.load("Lenna.png",img);  // load PNG image

		lti::channel  imgGray;
		imgGray.castFrom(img);

		double variance;

		// kSize NEEDS TO BE DEFINED AS AN ENTRY PARAMETER
		variance = pow((kSize+2)/6, 2)

		//Guassian kernel
		lti::gaussKernel2D<lti::channel::value_type> gKernel(kSize,variance);
		lti::convolution gFilter;                        // convolution operator
		lti::convolution::parameters gParam;             // parameters
		gParam.setKernel(gKernel);                        // use the gauss kernel
		gFilter.setParameters(gParam);                    // set parameters
		gFilter.apply(imgGray);

		//Octogonal kernel
		lti::octagonalKernel<lti::channel::value_type> oKernel(kSize,variance);
		lti::convolution oFilter;                        // convolution operator
		lti::convolution::parameters oParam;             // parameters
		oParam.setKernel(oKernel);                        // use the ortogonal kernel
		oFilter.setParameters(oParam);                    // set parameters
		oFilter.apply(imgGray);

		//In frequency domain

		// NEED TO APPLY BOUNDARY EXPANSION

		lti::fft fft2d;     // for 2-dimensional FFT
		lti::ifft ifft2d;   // for 2-dimensional inverse FFT

		/* NOT SURE WHY */
		par2d.mode = lti::fft::Polar;
		ifft2d.setParameters(par2d);
		fft2d.setParameters(par2d);
		/**************************/

		lti::channel back;
		lti::channel re,im;

		fft2d.apply(R, re, im);       // the actual FFT, Parameters: source, real result part, imaginary result part
		ifft2d.apply(re, im, back);   // inverse FF, Parameters: real part, imaginary part, destination

		// Multiply 2 channels
		lti::channel  result;

		result = lti::matrix< T >::emultiply(a,b )//not sure if so for channel instead of matrix

		chron.stop();

		cout << "Duration: " << chron.getTime() << " microseconds\n";

		return EXIT_SUCCESS;
	}

	return EXIT_FAILURE;
}
<commit_msg>Create the another class<commit_after>/*****************************
 *
 * Libraries
 *
 * ****************************/
#include <boost/program_options.hpp>

#include <ltiTimer.h>

/*****************************
 *
 * NameSpaces
 *
 * ****************************/
 namespace po = boost::program_options;

/******************************************************
 *
 * Help Function
 *
 * **********************************************/
void help()  {

	cout << "usage: main [option] [N] [option] [N] ... \n" << endl;
	cout << "       -pi|--pathimage <Path>   the path of the image" << endl;
	cout << "       -pf|--pathfilter <Path>  the path of the filter" << endl;

}

/******************************************************
 *
 * The main function
 *
 * **********************************************/
int main(int argc, char *argv[])
{

	// 64×48 pixeles y 1920×1080 pixeles
	// 10 valores intermedios

	// 3×3 pixeles y 1023×1023 pixeles
	// 10 valores intermedios

	// Generar una tabla con 100 campos del cruze de esos datos
	// Tomar n muestras de cada funcion

	// Example of how to use boost program options
	if (argc > 1) {

		// If the user is asked about info
		if (std::string(argv[1])=="-h" || std::string(argv[1])=="--help") {
			help();
			return EXIT_SUCCESS;
		}

		po::options_description desc("Usage");
		desc.add_options()
		("pathimage", po::value<string>()->default_value("./Lenna.png"),
		"Where is the path of the image?");
		desc.add_options()
		("pathfilter", po::value<string>()->default_value("./filter.png"),
		"Where is the path of the filter?");

		po::variables_map opts;
		po::store(po::parse_command_line(argc, argv, desc), opts);

		try {
			po::notify(opts);
		} catch (std::exception& e) {
			std::cerr << "Error: " << e.what() << "\n";
			return EXIT_FAILURE;
		}

		string pathImg = opts["pathimage"].as<string>();
		string pathFilter = opts["pathfilter"].as<string>();

		// End example
		lti::timer chron;

		chron.start();

		lti::loadImage loader;
		lti::image img;

		// Load PNG image
		loader.load("Lenna.png",img);

		lti::channel  imgGray;
		imgGray.castFrom(img);

		// *************************************
		// We create the filter
		// *************************************

		// We get the size in x or y of the filter and set the kSize
		double variance = pow((kSize+2)/6, 2);

		//Guassian kernel
		lti::gaussKernel2D<lti::channel::value_type> gKernel(kSize,variance);
		lti::convolution gFilter;                        // convolution operator
		lti::convolution::parameters gParam;             // parameters
		gParam.setKernel(gKernel);                        // use the gauss kernel
		gFilter.setParameters(gParam);                    // set parameters
		gFilter.apply(imgGray);

		//Octogonal kernel
		lti::octagonalKernel<lti::channel::value_type> oKernel(kSize,variance);
		lti::convolution oFilter;                        // convolution operator
		lti::convolution::parameters oParam;             // parameters
		oParam.setKernel(oKernel);                        // use the ortogonal kernel
		oFilter.setParameters(oParam);                    // set parameters
		oFilter.apply(imgGray);

		//In frequency domain

		// NEED TO APPLY BOUNDARY EXPANSION

		lti::fft fft2d;     // for 2-dimensional FFT
		lti::ifft ifft2d;   // for 2-dimensional inverse FFT

		/* NOT SURE WHY */
		par2d.mode = lti::fft::Polar;
		ifft2d.setParameters(par2d);
		fft2d.setParameters(par2d);
		/**************************/

		lti::channel back;
		lti::channel re,im;

		fft2d.apply(R, re, im);       // the actual FFT, Parameters: source, real result part, imaginary result part
		ifft2d.apply(re, im, back);   // inverse FF, Parameters: real part, imaginary part, destination

		// Multiply 2 channels
		lti::channel  result;

		result = lti::matrix< T >::emultiply(a,b )//not sure if so for channel instead of matrix

		chron.stop();

		cout << "Duration: " << chron.getTime() << " microseconds\n";

		return EXIT_SUCCESS;
	}

	return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>0e8f89d1-ad5b-11e7-84dd-ac87a332f658<commit_msg>This'll fix that<commit_after>0f1bf01e-ad5b-11e7-bfc0-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <stdlib.h>     /* srand, rand */
#include <time.h>

using namespace std;

int main()
{
    // Initialize variables
    int randomInt, userMove;
    char playAgain;

    const string moves[] = {"rock", "paper", "scissors"};

    // Initialize rng
    srand(time(NULL));

    bool playing = true;

    cout << "Welcome. Please press the enter key to begin playing Rock Paper Scissors SHOOT!";
    cin.get(); // "Pauses" the program until the enter key is pressed

    while(playing)
    {
        // Create random integer in range [1,3] to simulate the 'computer' selecting a move
        randomInt = rand() % 3 + 1;

        cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
        cin >> userMove;

        if(userMove != 1 and userMove !=2 and userMove !=3)
            playing = false;
        else
        {
            if(userMove == randomInt)
                cout << "Tie game! Both you and the computer chose " << moves[randomInt - 1] << endl;
            else
            {
                if(userMove - randomInt == 1 or userMove - randomInt == -2)
                    cout << "Congratulations, you won!" << endl;
                else
                    cout << "Sorry, better luck next time!" << endl;

                cout << "You chose " << moves[userMove - 1] << " and the computer chose " << moves[randomInt - 1] << endl;
            }

            cout << "Play again? [y/n]: ";
            cin >> playAgain;

            if(playAgain != 'y')
                playing = false;
        }

    }

    return 0;
}
<commit_msg>Count score<commit_after>#include <iostream>
#include <string>
#include <stdlib.h>     /* srand, rand */
#include <time.h>

using namespace std;

int main()
{
    // Initialize variables
    int randomInt, userMove;
    char playAgain;
    int playerWins = 0;
    int compWins = 0;

    const string moves[] = {"rock", "paper", "scissors"};

    // Initialize rng
    srand(time(NULL));

    bool playing = true;

    cout << "Welcome. Please press the enter key to begin playing Rock Paper Scissors SHOOT!";
    cin.get(); // "Pauses" the program until the enter key is pressed

    while(playing)
    {
        // Create random integer in range [1,3] to simulate the 'computer' selecting a move
        randomInt = rand() % 3 + 1;

        cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
        cin >> userMove;

        if(userMove != 1 and userMove !=2 and userMove !=3)
            cout << "Unknown command! Please try that again..." << endl;
        else
        {
            if(userMove == randomInt)
                cout << "Tie game! Both you and the computer chose " << moves[randomInt - 1] << endl;
            else
            {
                if(userMove - randomInt == 1 or userMove - randomInt == -2)
                {
                    cout << "Congratulations, you won!" << endl;
                    playerWins++;
                } else
                {
                    cout << "Sorry, better luck next time!" << endl;
                    compWins++;
                }

                cout << "You chose " << moves[userMove - 1] << " and the computer chose " << moves[randomInt - 1] << endl;
            }

            cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << endl;

            cout << "Play again? [y/n]: ";
            cin >> playAgain;

            if(playAgain != 'y')
                playing = false;
        }

    }

    return 0;
}
<|endoftext|>


<commit_before>8ea62402-4b02-11e5-83df-28cfe9171a43<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>8eb51ba8-4b02-11e5-991d-28cfe9171a43<|endoftext|>


<commit_before>cad11a6e-ad58-11e7-94ef-ac87a332f658<commit_msg>For bobby to integrate at some point<commit_after>cb315385-ad58-11e7-8c6e-ac87a332f658<|endoftext|>


<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <fstream>

#include <cloog/cloog.h>

#include "version.h"

#include "program.h"
//#include "ast_transform.h"

extern "C"{
#include "pluto.h"
#include "constraints.h"
#include "math_support.h"
void pluto_mark_parallel(struct clast_stmt *root, const PlutoProg *prog, CloogOptions *options);
void pluto_mark_vector(struct clast_stmt *root, const PlutoProg *prog, CloogOptions *options);
}

#include "pluto_codegen_clang.hpp"
#include "clast_clang.hpp"

using namespace std;

namespace pluto_codegen_clang{

static int get_first_point_loop(Stmt *stmt, const PlutoProg *prog)
{
    int i, first_point_loop;

    if (stmt->type != ORIG) {
        for (i=0; i<prog->num_hyperplanes; i++)   {
            if (!pluto_is_hyperplane_scalar(stmt, i)) {
                return i;
            }
        }
        /* No non-scalar hyperplanes */
        return 0;
    }

    for (i=stmt->last_tile_dim+1; i<stmt->trans->nrows; i++)   {
        if (stmt->hyp_types[i] == H_LOOP)  break;
    }

    if (i < prog->num_hyperplanes) {
        first_point_loop = i;
    }else{
        /* Should come here only if
         * it's a 0-d statement */
        first_point_loop = 0;
    }

    return first_point_loop;
}

/* Call cloog and generate code for the transformed program
 *
 * cloogf, cloogl: set to -1 if you want the function to decide
 *
 * --cloogf, --cloogl overrides everything; next cloogf, cloogl if != -1,
 *  then the function takes care of the rest
 */
int pluto_gen_cloog_code_clang(const PlutoProg *prog, int cloogf, int cloogl,
        FILE *cloogfp, ofstream& outfp)
{
    CloogInput *input ;
    CloogOptions *cloogOptions ;
    CloogState *state;
    int i;

    struct clast_stmt *root;

    Stmt **stmts = prog->stmts;
    int nstmts = prog->nstmts;

    state = cloog_state_malloc();
    cloogOptions = cloog_options_malloc(state);

    cloogOptions->fs = (int*)malloc (nstmts*sizeof(int));
    cloogOptions->ls = (int*)malloc(nstmts*sizeof(int));
    cloogOptions->fs_ls_size = nstmts;

    for (i=0; i<nstmts; i++) {
        cloogOptions->fs[i] = -1;
        cloogOptions->ls[i] = -1;
    }

    cloogOptions->name = "CLooG file produced by PLUTO";
    cloogOptions->compilable = 0;
    cloogOptions->esp = 1;
    cloogOptions->strides = 1;
    cloogOptions->quiet = options->silent;

    /* Generates better code in general */
    cloogOptions->backtrack = options->cloogbacktrack;

    if (options->cloogf >= 1 && options->cloogl >= 1) {
        cloogOptions->f = options->cloogf;
        cloogOptions->l = options->cloogl;
    }else{
        if (cloogf >= 1 && cloogl >= 1) {
            cloogOptions->f = cloogf;
            cloogOptions->l = cloogl;
        }else if (options->tile)   {
            for (i=0; i<nstmts; i++) {
                cloogOptions->fs[i] = get_first_point_loop(stmts[i], prog)+1;
                cloogOptions->ls[i] = prog->num_hyperplanes;
            }
        }else{
            /* Default */
            cloogOptions->f = 1;
            /* last level to optimize: number of hyperplanes;
             * since Pluto provides full-ranked transformations */
            cloogOptions->l = prog->num_hyperplanes;
        }
    }

    if (!options->silent)   {
        if (nstmts >= 1 && cloogOptions->fs[0] >= 1) {
            printf("[pluto] using statement-wise -fs/-ls options: ");
            for (i=0; i<nstmts; i++) {
                printf("S%d(%d,%d), ", i+1, cloogOptions->fs[i],
                        cloogOptions->ls[i]);
            }
            printf("\n");
        }else{
            printf("[pluto] using Cloog -f/-l options: %d %d\n",
                    cloogOptions->f, cloogOptions->l);
        }
    }

    if (options->cloogsh)
        cloogOptions->sh = 1;

    cloogOptions->name = "PLUTO-produced CLooG file";

    outfp << "/* Start of CLooG code */" << endl;
    /* Get the code from CLooG */
    IF_DEBUG(printf("[pluto] cloog_input_read\n"));
    input = cloog_input_read(cloogfp, cloogOptions) ;
    IF_DEBUG(printf("[pluto] cloog_clast_create\n"));
    root = cloog_clast_create_from_input(input, cloogOptions);
    if (options->prevector) {
        pluto_mark_vector(root, prog, cloogOptions);
    }
    if (options->parallel) {
        pluto_mark_parallel(root, prog, cloogOptions);
    }

    clast_clang::clast_pprint(outfp, root, 0, cloogOptions);
    cloog_clast_free(root);

    //fprintf(outfp, "/* End of CLooG code */\n");
    outfp << "/* End of CLooG code */" << endl;

    cloog_options_free(cloogOptions);
    cloog_state_free(state);

    return 0;
}

/* Generate code for a single multicore; the ploog script will insert openmp
 * pragmas later */
int pluto_multicore_codegen(FILE *cloogfp, ofstream& outfp, const PlutoProg *prog)
{
#if 0
    if (options->parallel)  {
        fprintf(outfp, "#include <omp.h>\n\n");
    }
    generate_declarations(prog, outfp);
#endif

    if (options->multipar) {
      assert( 0 && "not tested" );
      //fprintf(outfp, "\tomp_set_nested(1);\n");
      outfp << "\tomp_set_nested(1);" << endl;
      //fprintf(outfp, "\tomp_set_num_threads(2);\n");
      outfp << "\tomp_set_num_threads(2);" << endl;
    }

    pluto_gen_cloog_code_clang(prog, -1, -1, cloogfp, outfp);

    return 0;
}

}
<commit_msg>first cosmetical changes: - removed the variable generation<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <sstream>

#include <cloog/cloog.h>

#include "version.h"

#include "program.h"
//#include "ast_transform.h"

extern "C"{
#include "pluto.h"
#include "constraints.h"
#include "math_support.h"
void pluto_mark_parallel(struct clast_stmt *root, const PlutoProg *prog, CloogOptions *options);
void pluto_mark_vector(struct clast_stmt *root, const PlutoProg *prog, CloogOptions *options);
}

#include "pluto_codegen_clang.hpp"
#include "clast_clang.hpp"

using namespace std;

namespace pluto_codegen_clang{

static int get_first_point_loop(Stmt *stmt, const PlutoProg *prog)
{
    int i, first_point_loop;

    if (stmt->type != ORIG) {
        for (i=0; i<prog->num_hyperplanes; i++)   {
            if (!pluto_is_hyperplane_scalar(stmt, i)) {
                return i;
            }
        }
        /* No non-scalar hyperplanes */
        return 0;
    }

    for (i=stmt->last_tile_dim+1; i<stmt->trans->nrows; i++)   {
        if (stmt->hyp_types[i] == H_LOOP)  break;
    }

    if (i < prog->num_hyperplanes) {
        first_point_loop = i;
    }else{
        /* Should come here only if
         * it's a 0-d statement */
        first_point_loop = 0;
    }

    return first_point_loop;
}

/* Call cloog and generate code for the transformed program
 *
 * cloogf, cloogl: set to -1 if you want the function to decide
 *
 * --cloogf, --cloogl overrides everything; next cloogf, cloogl if != -1,
 *  then the function takes care of the rest
 */
int pluto_gen_cloog_code_clang(const PlutoProg *prog, int cloogf, int cloogl,
        FILE *cloogfp, stringstream& outfp)
{
    CloogInput *input ;
    CloogOptions *cloogOptions ;
    CloogState *state;
    int i;

    struct clast_stmt *root;

    Stmt **stmts = prog->stmts;
    int nstmts = prog->nstmts;

    state = cloog_state_malloc();
    cloogOptions = cloog_options_malloc(state);

    cloogOptions->fs = (int*)malloc (nstmts*sizeof(int));
    cloogOptions->ls = (int*)malloc(nstmts*sizeof(int));
    cloogOptions->fs_ls_size = nstmts;

    for (i=0; i<nstmts; i++) {
        cloogOptions->fs[i] = -1;
        cloogOptions->ls[i] = -1;
    }

    cloogOptions->name = "CLooG file produced by PLUTO";
    cloogOptions->compilable = 0;
    cloogOptions->esp = 1;
    cloogOptions->strides = 1;
    cloogOptions->quiet = options->silent;

    /* Generates better code in general */
    cloogOptions->backtrack = options->cloogbacktrack;

    if (options->cloogf >= 1 && options->cloogl >= 1) {
        cloogOptions->f = options->cloogf;
        cloogOptions->l = options->cloogl;
    }else{
        if (cloogf >= 1 && cloogl >= 1) {
            cloogOptions->f = cloogf;
            cloogOptions->l = cloogl;
        }else if (options->tile)   {
            for (i=0; i<nstmts; i++) {
                cloogOptions->fs[i] = get_first_point_loop(stmts[i], prog)+1;
                cloogOptions->ls[i] = prog->num_hyperplanes;
            }
        }else{
            /* Default */
            cloogOptions->f = 1;
            /* last level to optimize: number of hyperplanes;
             * since Pluto provides full-ranked transformations */
            cloogOptions->l = prog->num_hyperplanes;
        }
    }

    if (!options->silent)   {
        if (nstmts >= 1 && cloogOptions->fs[0] >= 1) {
            printf("[pluto] using statement-wise -fs/-ls options: ");
            for (i=0; i<nstmts; i++) {
                printf("S%d(%d,%d), ", i+1, cloogOptions->fs[i],
                        cloogOptions->ls[i]);
            }
            printf("\n");
        }else{
            printf("[pluto] using Cloog -f/-l options: %d %d\n",
                    cloogOptions->f, cloogOptions->l);
        }
    }

    if (options->cloogsh)
        cloogOptions->sh = 1;

    cloogOptions->name = "PLUTO-produced CLooG file";

    outfp << "/* Start of CLooG code */" << endl;
    /* Get the code from CLooG */
    IF_DEBUG(printf("[pluto] cloog_input_read\n"));
    input = cloog_input_read(cloogfp, cloogOptions) ;
    IF_DEBUG(printf("[pluto] cloog_clast_create\n"));
    root = cloog_clast_create_from_input(input, cloogOptions);
    if (options->prevector) {
        pluto_mark_vector(root, prog, cloogOptions);
    }
    if (options->parallel) {
        pluto_mark_parallel(root, prog, cloogOptions);
    }

    clast_clang::clast_pprint(outfp, root, 0, cloogOptions);
    cloog_clast_free(root);

    //fprintf(outfp, "/* End of CLooG code */\n");
    outfp << "/* End of CLooG code */" << endl;

    cloog_options_free(cloogOptions);
    cloog_state_free(state);

    return 0;
}

static void gen_stmt_macro(const Stmt *stmt, stringstream& outfp)
{
    int j;

    for (j=0; j<stmt->dim; j++) {
        if (stmt->iterators[j] == NULL) {
            printf("Iterator name not set for S%d; required \
                    for generating declarations\n", stmt->id+1);
            assert(0);
        }
    }
    outfp << "#define S"<< stmt->id+1;
    outfp << "(";
    for (j=0; j<stmt->dim; j++)  {
        if (j!=0) {
	  outfp << ",";
	}
        outfp << stmt->iterators[j];
    }
    outfp << ")\t";

#if 0
    /* Generate pragmas for Bee/Cl@k */
    if (options->bee)   {
        outfp << " __bee_schedule";
        for (j=0; j<stmt->trans->nrows; j++)    {
            outfp << "[";
            //pluto_affine_function_print(outfp, stmt->trans->val[j],
                    stmt->dim, stmt->iterators);
            fprintf(outfp, "]");
        }
        fprintf(outfp, " _NL_DELIMIT_ ");
    }
#endif
    outfp << stmt->text << endl;
}

/* Generate variable declarations and macros */
int generate_declarations(const PlutoProg *prog, stringstream& outfp)
{
    int i;

    Stmt **stmts = prog->stmts;
    int nstmts = prog->nstmts;

    /* Generate statement macros */
    for (i=0; i<nstmts; i++)    {
        gen_stmt_macro(stmts[i], outfp);
    }
    outfp << endl;

#if 0
    /* Scattering iterators. */
    if (prog->num_hyperplanes >= 1)    {
        outfp << "\t\tint ";
        for (i=0; i<prog->num_hyperplanes; i++)  {
            if (i!=0) {
	      outfp << ", ";
	    }
            outfp << "t" << i+1;
            if (prog->hProps[i].unroll)   {
                outfp << ", t" << i+1 << "t, newlb_t" << i+1 << ", newub_t" << i+1 ;
            }
        }
        outfp << ";\n\n";
    }

    if (options->parallel)   {
        outfp << "\tint lb, ub, lbp, ubp, lb2, ub2;\n";
    }
    /* For vectorizable loop bound replacement */
    outfp << "\tregister int lbv, ubv;\n\n";
#endif

    return 0;
}

/* Generate code for a single multicore; the ploog script will insert openmp
 * pragmas later */
int pluto_multicore_codegen(FILE *cloogfp, stringstream& outfp, const PlutoProg *prog)
{
  // TODO left on for compatibility reasons
#if 1
    if (options->parallel)  {
        //fprintf(outfp, "#include <omp.h>\n\n");
	outfp << "#include <omp.h>" << endl << endl;
    }
    generate_declarations(prog, outfp);
#endif

    if (options->multipar) {
      assert( 0 && "not tested" );
      //fprintf(outfp, "\tomp_set_nested(1);\n");
      outfp << "\tomp_set_nested(1);" << endl;
      //fprintf(outfp, "\tomp_set_num_threads(2);\n");
      outfp << "\tomp_set_num_threads(2);" << endl;
    }

    pluto_gen_cloog_code_clang(prog, -1, -1, cloogfp, outfp);

    return 0;
}

}
<|endoftext|>


<commit_before>b65e508f-ad5a-11e7-8f0b-ac87a332f658<commit_msg>Deal with it<commit_after>b6f071b3-ad5a-11e7-843f-ac87a332f658<|endoftext|>