<commit_before>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;

// Roll the dice.
int diceRoll(int qty, int sides)
{
	int subTotal = 0; // Dice addition subtotal.
	// Roll the dice.

	// Loop to roll the dice
	for (int i = 0; i < qty; i++)
	{
		int currentRoll = rand() % sides + 1;
		subTotal += currentRoll;
	}

	return subTotal;
}

// Race Choices
enum RACE { HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD };

// Class Choices
enum OCC { FIGHTER, CLERIC, THEIF, BARD, ROUGE, TINKER, MAGE };

// Stats Tree
struct ATTRIBUTES
{
	unsigned int strength;
	unsigned int faith;
	unsigned int dexterity;
	unsigned int insperation;
	unsigned int cleverness;
	unsigned int focus;
};

// Display the stats of the roll.
void displayStats(ATTRIBUTES atts, bool split)
{
	cout << " +---------------------+ \n";
	cout << " | Attributes:         | \n";
	cout << " +---------------------+ \n";
	cout << "\n";
	cout << "   Strength:      " << atts.strength << "\n";
	cout << "   Faith:         " << atts.faith << "\n";
	cout << "   Dexterity:     " << atts.dexterity << "\n";
	cout << "   Insperation:   " << atts.insperation << "\n";
	cout << "   Cleverness:    " << atts.cleverness << "\n";
	cout << "   Focus:         " << atts.focus << "\n";

	if (split == true)
	{
		cout << "\n\n";
	}
}

// Class for the character.
class character
{
	protected:
		ATTRIBUTES atts;
		int copper; // Money var.
		OCC charClass;
		RACE charRace;
		unsigned int hp, hpMax;
		unsigned int mp, mpMax;

	public:
		// Constructors
		character()
		{
			copper = 50000;
		}

		// Accessors
		void setAtts(ATTRIBUTES tmpAtts)
		{
			atts = tmpAtts;
		}

		ATTRIBUTES getAtts()
		{
			return atts;
		}

		void displayAllStats()
		{
			cout << " +---------------------+\n";
			cout << " | " << charRace << "          |\n";
			cout << " | " << charClass << "          |\n";
			displayStats(atts, false);

			cout << "   Hitpoints:     " << hp << "/" << hpMax << "\n";
			cout << "   Mana:          " << mp << "/" << mpMax << "\n";
			cout << "\n\n";
		}
};

// Class for the fighter.
class fighter : public character
{
	public:
		fighter()
		{
			cout << "Fighter Created.\n";

			hpMax = hp = diceRoll(10, 6);
			mpMax = mp = 20;
		}
};

// Class for the Cleric.
class cleric : public character
{
	public:
		cleric()
		{
			cout << "Cleric Created.\n";

			hpMax = hp = diceRoll(7, 6);
			mpMax = mp = 50;
		}
};

// Class for the Rouge.
class rouge : public character
{
	public:
		rouge()
		{
			cout << "Rouge Created.\n";

			hpMax = hp = diceRoll(7, 6);
			mpMax = mp = 20;
		}
};

// Class for the Bard.
class bard : public character
{
	public:
		bard()
		{
			cout << "Bard Created.\n";

			hpMax = hp = diceRoll(5, 6);
			mpMax = mp = 50;
		}
};

// Class for the Tinker.
class tinker : public character
{
	public:
		tinker()
		{
			cout << "Tinker Created.\n";

			hpMax = hp = diceRoll(5, 6);
			mpMax = mp = 20;
		}
};

// Class for the Mage.
class mage : public character
{
	public:
		mage()
		{
			cout << "Mage Created.\n";

			hpMax = hp = diceRoll(3, 6);
			mpMax = mp = 50;
		}
};

// Startup
int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(NULL));

	RACE inputRace; // The race that is chosen.
	char inputs; // The inputs.
	ATTRIBUTES tmpStats; // The stats the player gets by random.
	bool reroll = true; // The bool for rerolling.
	OCC inputClass; // The class that is chosen.
	bool retry = true; // The fix for the race chooser.

	// Set the character to pointer var.
	character *player1;

	// Clear the console.
	system("cls");

	cout << "Welcome to Zoro\n";

	// Check for the reroll
	while (reroll == true)
	{
		// End the reroll;
		reroll = false;

		cout << "Please Select a Race:\n";
		cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";

		// Check for the retry
		while (retry == true)
		{
			// The input for the chosen race.
			cin >> inputs;

			// End the retry.
			retry = false;

			switch (inputs)
			{
				case 'h':
				case 'H':
					cout << "\nHuman!\n";
					inputRace = HUMAN;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					retry = false; // End the retry.
					break;
				case 'e':
				case 'E':
					cout << "\nElf!\n";
					inputRace = ELF;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(2, 6);
					tmpStats.focus = diceRoll(4, 6);
					break;
				case 'd':
				case 'D':
					cout << "\nDark Elf!\n";
					inputRace = DARKELF;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(4, 6);
					tmpStats.insperation = diceRoll(2, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'a':
				case 'A':
					cout << "Angel!\n";
					inputRace = ANGEL;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(4, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'm':
				case 'M':
					cout << "\nMongrel!\n";
					inputRace = MONGREL;
					tmpStats.strength = diceRoll(4, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(2, 6);
					break;
				case 's':
				case 'S':
					cout << "\nShamani!\n";
					inputRace = SHAMANI;
					tmpStats.strength = diceRoll(2, 6);
					tmpStats.faith = diceRoll(4, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'n':
				case 'N':
					cout << "\nNibelung!\n";
					inputRace = NIBELUNG;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(2, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(4, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'u':
				case 'U':
					cout << "\nUndead!\n";
					inputRace = UNDEAD;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(2, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				default:
					cout << "\nPlease input a vaild race.\n";
					retry = true; // Set the retry to default
					break;
			}
		}

		cout << "\n";

		// Display the stats
		displayStats(tmpStats, true);

		cout << "Reroll? [Y]es [N]o\n\n";

		// Input for the reroll.
		cin >> inputs;

		// End the reroll
		reroll = false;

		if (inputs == 'y' || inputs == 'Y')
		{
			cout << inputs;
			// Reset the reroll to default.
			reroll = true;
		}
	}

	// Reset the reroll to default for the second reroll.
	reroll = true;

	while (reroll) // While reroll == true
	{
		// End the reroll for now
		reroll = false;

		cout << "Please select a class\n";
		cout << "[F]ighter [C]leric [T]heif [B]ard [R]ouge [M]age\n";

		// Check for inputs of which class.
		cin >> inputs;

		// Check for which class.
		switch (inputs)
		{
			case 'f':
			case 'F':
				inputClass = FIGHTER;
				cout << "Fighter!\n";
				player1 = new fighter;
				break;
			case 'c':
			case 'C':
				inputClass = CLERIC;
				cout << "Cleric!\n";
				player1 = new fighter;
				break;
			case 't':
			case 'T':
				inputClass = THEIF;
				cout << "Theif!\n";
				player1 = new rouge;
				break;
			case 'b':
			case 'B':
				inputClass = BARD;
				cout << "Bard!\n";
				player1 = new bard;
				break;
			case 'r':
			case 'R':
				inputClass = ROUGE;
				cout << "Rouge!\n";
				player1 = new rouge;
				break;
			case 'm':
			case 'M':
				inputClass = MAGE;
				cout << "Mage!\n";
				player1 = new mage;
				break;
			default:
				cout << "Please input a valid class.\n";
				reroll = true;
				break;
		}
	}

	// Set the attributes as they are at this point.
	player1->setAtts(tmpStats);

	// Display the displayAllStats function.
	player1->displayAllStats();

	return 0;
}<commit_msg>Added Additions for tomarow (Friday Oct 10, 2014)<commit_after>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;

// Roll the dice.
int diceRoll(int qty, int sides)
{
	int subTotal = 0; // Dice addition subtotal.
	// Roll the dice.

	// Loop to roll the dice
	for (int i = 0; i < qty; i++)
	{
		int currentRoll = rand() % sides + 1;
		subTotal += currentRoll;
	}

	return subTotal;
}

// Race Choices
enum RACE { HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD };

// Class Choices
enum OCC { FIGHTER, CLERIC, THEIF, BARD, ROUGE, TINKER, MAGE };

// Stats Tree
struct ATTRIBUTES
{
	unsigned int strength;
	unsigned int faith;
	unsigned int dexterity;
	unsigned int insperation;
	unsigned int cleverness;
	unsigned int focus;
};

// - OLD - Display the stats of the roll.
void displayStats(ATTRIBUTES atts, bool split)
{
	cout << " +---------------------+ \n";
	cout << " | Attributes:         | \n";
	cout << " +---------------------+ \n";
	cout << "\n";
	cout << "   Strength:      " << atts.strength << "\n";
	cout << "   Faith:         " << atts.faith << "\n";
	cout << "   Dexterity:     " << atts.dexterity << "\n";
	cout << "   Insperation:   " << atts.insperation << "\n";
	cout << "   Cleverness:    " << atts.cleverness << "\n";
	cout << "   Focus:         " << atts.focus << "\n";

	if (split == true)
	{
		cout << "\n\n";
	}
}

// Class for the character.
class character
{
	protected:
		ATTRIBUTES atts;
		int copper; // Money var.
		OCC charClass;
		RACE charRace;
		unsigned int hp, hpMax;
		unsigned int mp, mpMax;
		char *charClassChar = "";

	public:
		// Constructors
		character()
		{
			copper = 50000;
		}

		// Accessors
		// Set the attributes from outside this class.
		void setAtts(ATTRIBUTES tmpAtts)
		{
			atts = tmpAtts;
		}

		// Get the attributes from outside this class.
		ATTRIBUTES getAtts()
		{
			return atts;
		}

		// To detect which class you are currently on.
		char detectClass(OCC tempClass)
		{
			switch(tempClass)
			{
				case FIGHTER:
					charClassChar = "Fighter";
					break;
				case CLERIC:
					charClassChar = "Cleric";
					break;
				case THEIF:
					charClassChar = "Theif";
					break;
				case BARD:
					charClassChar = "Bard";
					break;
				case ROUGE:
					charClassChar = "Rouge";
					break;
				case TINKER:
					charClassChar = "Tinker";
					break;
				case MAGE:
					charClassChar = "Mage";
					break;
			}
		}

		// To detect which race you are currently on.
		char detectRace(RACE tempRace)
		{
			switch(tempRace)
			{
				case HUMAN:
					charRaceChar = "Human";
					break;
				case ELF:
					charRaceChar = "Elf";
					break;
				case DARKELF:
					charRaceChar = "Dark Elf";
					break;
				case ANGEL:
					charRaceChar = "Angel";
					break;
				case MONGREL:
					charRaceChar = "Mongrel";
					break;
				case SHAMANI:
					charRaceChar = "Shamani";
					break;
				case NIBELUNG:
					charRaceChar = "Nibelung";
					break;
				case UNDEAD:
					charRaceChar = "Undead";
					break;
			}
		}

		// The new displayStats
		void displayStats(bool full)
		{
			cout << "\n";

			if (full) // full == true
			{
				cout << " +---------------------+ \n";
				cout << " | " << charClassChar(charClass) << "            | \n";
				cout << " | " << charRaceChar(charRace) << "               | \n";
			}

			cout << " +---------------------+ \n";
			cout << " | Attributes:         | \n";
			cout << " +---------------------+ \n";
			cout << "\n";
			cout << "   Strength:      " << atts.strength << "\n";
			cout << "   Faith:         " << atts.faith << "\n";
			cout << "   Dexterity:     " << atts.dexterity << "\n";
			cout << "   Insperation:   " << atts.insperation << "\n";
			cout << "   Cleverness:    " << atts.cleverness << "\n";
			cout << "   Focus:         " << atts.focus << "\n";

			if (full) // full == true
			{
				cout << "   Hitpoints:     " << hp << "/" << hpMax << "\n";
				cout << "   Hitpoints:     " << mp << "/" << mpMax << "\n";
			}

			cout << "\n\n"
		}
};

// Class for the fighter.
class fighter : public character
{
	public:
		fighter()
		{
			cout << "Fighter Created.\n";

			hpMax = hp = diceRoll(10, 6);
			mpMax = mp = 20;
		}
};

// Class for the Cleric.
class cleric : public character
{
	public:
		cleric()
		{
			cout << "Cleric Created.\n";

			hpMax = hp = diceRoll(7, 6);
			mpMax = mp = 50;
		}
};

// Class for the Rouge.
class rouge : public character
{
	public:
		rouge()
		{
			cout << "Rouge Created.\n";

			hpMax = hp = diceRoll(7, 6);
			mpMax = mp = 20;
		}
};

// Class for the Bard.
class bard : public character
{
	public:
		bard()
		{
			cout << "Bard Created.\n";

			hpMax = hp = diceRoll(5, 6);
			mpMax = mp = 50;
		}
};

// Class for the Tinker.
class tinker : public character
{
	public:
		tinker()
		{
			cout << "Tinker Created.\n";

			hpMax = hp = diceRoll(5, 6);
			mpMax = mp = 20;
		}
};

// Class for the Mage.
class mage : public character
{
	public:
		mage()
		{
			cout << "Mage Created.\n";

			hpMax = hp = diceRoll(3, 6);
			mpMax = mp = 50;
		}
};

// Startup
int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(NULL));

	RACE inputRace; // The race that is chosen.
	char inputs; // The inputs.
	ATTRIBUTES tmpStats; // The stats the player gets by random.
	bool reroll = true; // The bool for rerolling.
	OCC inputClass; // The class that is chosen.
	bool retry = true; // The fix for the race chooser.

	// Set the character to pointer var.
	character *player1;

	// Clear the console.
	system("cls");

	cout << "Welcome to Zoro\n";

	// Check for the reroll
	while (reroll == true)
	{
		// End the reroll;
		reroll = false;

		cout << "Please Select a Race:\n";
		cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";

		// Check for the retry
		while (retry == true)
		{
			// The input for the chosen race.
			cin >> inputs;

			// End the retry.
			retry = false;

			switch (inputs)
			{
				case 'h':
				case 'H':
					cout << "\nHuman!\n";
					inputRace = HUMAN;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					retry = false; // End the retry.
					break;
				case 'e':
				case 'E':
					cout << "\nElf!\n";
					inputRace = ELF;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(2, 6);
					tmpStats.focus = diceRoll(4, 6);
					break;
				case 'd':
				case 'D':
					cout << "\nDark Elf!\n";
					inputRace = DARKELF;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(4, 6);
					tmpStats.insperation = diceRoll(2, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'a':
				case 'A':
					cout << "Angel!\n";
					inputRace = ANGEL;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(4, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'm':
				case 'M':
					cout << "\nMongrel!\n";
					inputRace = MONGREL;
					tmpStats.strength = diceRoll(4, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(2, 6);
					break;
				case 's':
				case 'S':
					cout << "\nShamani!\n";
					inputRace = SHAMANI;
					tmpStats.strength = diceRoll(2, 6);
					tmpStats.faith = diceRoll(4, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(3, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'n':
				case 'N':
					cout << "\nNibelung!\n";
					inputRace = NIBELUNG;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(2, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(4, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				case 'u':
				case 'U':
					cout << "\nUndead!\n";
					inputRace = UNDEAD;
					tmpStats.strength = diceRoll(3, 6);
					tmpStats.faith = diceRoll(3, 6);
					tmpStats.dexterity = diceRoll(3, 6);
					tmpStats.insperation = diceRoll(3, 6);
					tmpStats.cleverness = diceRoll(2, 6);
					tmpStats.focus = diceRoll(3, 6);
					break;
				default:
					cout << "\nPlease input a vaild race.\n";
					retry = true; // Set the retry to default
					break;
			}
		}

		cout << "\n";

		// Display the stats
		player1->displayStats(false);

		cout << "Reroll? [Y]es [N]o\n\n";

		// Input for the reroll.
		cin >> inputs;

		// End the reroll
		reroll = false;

		if (inputs == 'y' || inputs == 'Y')
		{
			cout << inputs;
			// Reset the reroll to default.
			reroll = true;
		}
	}

	// Reset the reroll to default for the second reroll.
	reroll = true;

	while (reroll) // While reroll == true
	{
		// End the reroll for now
		reroll = false;

		cout << "Please select a class\n";
		cout << "[F]ighter [C]leric [T]heif [B]ard [R]ouge [M]age\n";

		// Check for inputs of which class.
		cin >> inputs;

		// Check for which class.
		switch (inputs)
		{
			case 'f':
			case 'F':
				inputClass = FIGHTER;
				cout << "Fighter!\n";
				player1 = new fighter;
				break;
			case 'c':
			case 'C':
				inputClass = CLERIC;
				cout << "Cleric!\n";
				player1 = new fighter;
				break;
			case 't':
			case 'T':
				inputClass = THEIF;
				cout << "Theif!\n";
				player1 = new rouge;
				break;
			case 'b':
			case 'B':
				inputClass = BARD;
				cout << "Bard!\n";
				player1 = new bard;
				break;
			case 'r':
			case 'R':
				inputClass = ROUGE;
				cout << "Rouge!\n";
				player1 = new rouge;
				break;
			case 'm':
			case 'M':
				inputClass = MAGE;
				cout << "Mage!\n";
				player1 = new mage;
				break;
			default:
				cout << "Please input a valid class.\n";
				reroll = true;
				break;
		}
	}

	// Set the attributes as they are at this point.
	player1->setAtts(tmpStats);

	// Display the displayAllStats function.
	player1->displayStats(true);

	return 0;
}<|endoftext|>


<commit_before>#include <stan/math/prim.hpp>
#include <test/unit/math/expect_near_rel.hpp>
#include <gtest/gtest.h>
#include <cmath>

template <typename T_N, typename T_n>
void test_binom_coefficient(const T_N& N, const T_n& n) {
  using stan::math::binomial_coefficient_log;
  EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1),
                  binomial_coefficient_log(N, n))
      << "N = " << N << ", n = " << n;
}

TEST(MathFunctions, binomial_coefficient_log) {
  using stan::math::binomial_coefficient_log;
  EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0)));
  EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0)));
  EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0)));
  EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001);

  EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116));

  EXPECT_EQ(binomial_coefficient_log(-1, 0), 0);  // Needed for neg_binomial_2
  EXPECT_EQ(binomial_coefficient_log(50, 0), 0);
  EXPECT_EQ(binomial_coefficient_log(10000, 0), 0);

  EXPECT_EQ(binomial_coefficient_log(10, 11), stan::math::NEGATIVE_INFTY);
  EXPECT_EQ(binomial_coefficient_log(10, -1), stan::math::NEGATIVE_INFTY);

  for (int n = 0; n < 1010; ++n) {
    test_binom_coefficient(1010, n);
    test_binom_coefficient(1010.0, n);
    test_binom_coefficient(1010, static_cast<double>(n));
    test_binom_coefficient(1010.0, static_cast<double>(n));
  }

  test_binom_coefficient(1e9, 1e5);
  test_binom_coefficient(1e50, 1e45);
  test_binom_coefficient(1e20, 1e15);
}

TEST(MathFunctions, binomial_coefficient_log_nan) {
  double nan = stan::math::NOT_A_NUMBER;

  EXPECT_TRUE(std::isnan(stan::math::binomial_coefficient_log(2.0, nan)));
  EXPECT_TRUE(std::isnan(stan::math::binomial_coefficient_log(nan, 2.0)));
  EXPECT_TRUE(std::isnan(stan::math::binomial_coefficient_log(nan, nan)));
}

TEST(MathFunctions, binomial_coefficient_log_errors_edge_cases) {
  using stan::math::binomial_coefficient_log;
  using stan::math::INFTY;

  EXPECT_NO_THROW(binomial_coefficient_log(10, 11));
  EXPECT_THROW(binomial_coefficient_log(10, 11.01), std::domain_error);
  EXPECT_THROW(binomial_coefficient_log(10, -1.1), std::domain_error);
  EXPECT_THROW(binomial_coefficient_log(-1, 0.3), std::domain_error);
  EXPECT_NO_THROW(binomial_coefficient_log(-0.5, 0.49));
  EXPECT_NO_THROW(binomial_coefficient_log(10, -0.9));

  EXPECT_FLOAT_EQ(binomial_coefficient_log(0, -1), -INFTY);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(-1, 0), 0);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(-1, -0.3), INFTY);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(0.3, -1), -INFTY);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(5.0, 6.0), -INFTY);
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#include <stan/math/prim.hpp>
#include <test/unit/math/expect_near_rel.hpp>
#include <gtest/gtest.h>
#include <cmath>

template <typename T_N, typename T_n>
void test_binom_coefficient(const T_N& N, const T_n& n) {
  using stan::math::binomial_coefficient_log;
  EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1),
                  binomial_coefficient_log(N, n))
      << "N = " << N << ", n = " << n;
}

TEST(MathFunctions, binomial_coefficient_log) {
  using stan::math::binomial_coefficient_log;
  EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0)));
  EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0)));
  EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0)));
  EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001);

  EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116));

  EXPECT_EQ(binomial_coefficient_log(-1, 0), 0);  // Needed for neg_binomial_2
  EXPECT_EQ(binomial_coefficient_log(50, 0), 0);
  EXPECT_EQ(binomial_coefficient_log(10000, 0), 0);

  EXPECT_EQ(binomial_coefficient_log(10, 11), stan::math::NEGATIVE_INFTY);
  EXPECT_EQ(binomial_coefficient_log(10, -1), stan::math::NEGATIVE_INFTY);

  for (int n = 0; n < 1010; ++n) {
    test_binom_coefficient(1010, n);
    test_binom_coefficient(1010.0, n);
    test_binom_coefficient(1010, static_cast<double>(n));
    test_binom_coefficient(1010.0, static_cast<double>(n));
  }

  test_binom_coefficient(1e9, 1e5);
  test_binom_coefficient(1e50, 1e45);
  test_binom_coefficient(1e20, 1e15);
}

TEST(MathFunctions, binomial_coefficient_log_nan) {
  double nan = stan::math::NOT_A_NUMBER;

  EXPECT_TRUE(std::isnan(stan::math::binomial_coefficient_log(2.0, nan)));
  EXPECT_TRUE(std::isnan(stan::math::binomial_coefficient_log(nan, 2.0)));
  EXPECT_TRUE(std::isnan(stan::math::binomial_coefficient_log(nan, nan)));
}

TEST(MathFunctions, binomial_coefficient_log_errors_edge_cases) {
  using stan::math::INFTY;
  using stan::math::binomial_coefficient_log;

  EXPECT_NO_THROW(binomial_coefficient_log(10, 11));
  EXPECT_THROW(binomial_coefficient_log(10, 11.01), std::domain_error);
  EXPECT_THROW(binomial_coefficient_log(10, -1.1), std::domain_error);
  EXPECT_THROW(binomial_coefficient_log(-1, 0.3), std::domain_error);
  EXPECT_NO_THROW(binomial_coefficient_log(-0.5, 0.49));
  EXPECT_NO_THROW(binomial_coefficient_log(10, -0.9));

  EXPECT_FLOAT_EQ(binomial_coefficient_log(0, -1), -INFTY);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(-1, 0), 0);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(-1, -0.3), INFTY);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(0.3, -1), -INFTY);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(5.0, 6.0), -INFTY);
}
<|endoftext|>


<commit_before>#pragma once

#include <iterator>
#include <type_traits>

namespace kl {

template <class Iterator>
class base_range
{
public:
    using iterator = Iterator;
    using value_type = typename std::iterator_traits<Iterator>::value_type;
    using difference_type =
        typename std::iterator_traits<Iterator>::difference_type;
    using pointer = typename std::iterator_traits<Iterator>::pointer;
    using reference = typename std::iterator_traits<Iterator>::reference;

public:
    explicit base_range() = default;
    base_range(Iterator first, Iterator last)
        : first_{std::move(first)}, last_{std::move(last)}
    {
    }

    Iterator begin() const { return first_; }
    Iterator end() const { return last_; }

    // default implementation (iterator_category is used for dispatching)
    size_t size() const { return std::distance(first_, last_); }

private:
    Iterator first_, last_;
};

template <class Iterator>
inline base_range<Iterator> make_range(Iterator a, Iterator b)
{
    return base_range<Iterator>{a, b};
}

template <class Container>
inline base_range<typename Container::iterator> make_range(Container& cont)
{
    return base_range<typename Container::iterator>{cont.begin(), cont.end()};
}

template <class Container>
inline base_range<typename Container::const_iterator>
    make_range(const Container& cont)
{
    return base_range<typename Container::const_iterator>{cont.cbegin(),
                                                          cont.cend()};
}

template <class ArrayType, size_t N>
inline base_range<std::add_pointer_t<ArrayType>>
    make_range(ArrayType (&arr)[N])
{
    using value_type = std::add_pointer_t<ArrayType>;
    auto b = std::begin(arr);
    auto e = std::end(arr);
    return base_range<value_type>{b, e};
}

template <class ArrayType, size_t N>
inline base_range<std::add_pointer_t<const ArrayType>>
    make_range(const ArrayType (&arr)[N])
{
    using value_type = std::add_pointer_t<const ArrayType>;
    auto b = std::begin(arr);
    auto e = std::end(arr);
    return base_range<value_type>{b, e};
}
} // namespace kl
<commit_msg>constexpr'ize base range<commit_after>#pragma once

#include <iterator>
#include <type_traits>

namespace kl {

template <class Iterator>
class base_range
{
public:
    using iterator = Iterator;
    using value_type = typename std::iterator_traits<Iterator>::value_type;
    using difference_type =
        typename std::iterator_traits<Iterator>::difference_type;
    using pointer = typename std::iterator_traits<Iterator>::pointer;
    using reference = typename std::iterator_traits<Iterator>::reference;

public:
    constexpr base_range() = default;
    constexpr base_range(Iterator first, Iterator last)
        : first_{std::move(first)}, last_{std::move(last)}
    {
    }

    constexpr Iterator begin() const { return first_; }
    constexpr Iterator end() const { return last_; }

    // default implementation (iterator_category is used for dispatching)
    constexpr size_t size() const { return std::distance(first_, last_); }

private:
    Iterator first_, last_;
};

template <class Iterator>
inline constexpr base_range<Iterator> make_range(Iterator a, Iterator b)
{
    return base_range<Iterator>{a, b};
}

template <class Container>
inline base_range<typename Container::iterator> make_range(Container& cont)
{
    return base_range<typename Container::iterator>{cont.begin(), cont.end()};
}

template <class Container>
inline base_range<typename Container::const_iterator>
    make_range(const Container& cont)
{
    return base_range<typename Container::const_iterator>{cont.cbegin(),
                                                          cont.cend()};
}

template <class ArrayType, size_t N>
inline constexpr base_range<std::add_pointer_t<ArrayType>>
    make_range(ArrayType (&arr)[N])
{
    using value_type = std::add_pointer_t<ArrayType>;
    return base_range<value_type>{std::begin(arr), std::end(arr)};
}

template <class ArrayType, size_t N>
inline constexpr base_range<std::add_pointer_t<const ArrayType>>
    make_range(const ArrayType (&arr)[N])
{
    using value_type = std::add_pointer_t<const ArrayType>;
    return base_range<value_type>{std::begin(arr), std::end(arr)};
}
} // namespace kl
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE generator
#include <boost/test/unit_test.hpp>

#include "../bf/generator.h"
#include "../bf/interpreter.h"

BOOST_AUTO_TEST_CASE(var__add) {
    std::string program;
    {
        bf::generator bfg;

        auto a = bfg.new_var("a");
        a->input();
        a->add(3);
        a->output();

        program = bfg.get_code();
    }

    // 2 + 3 == 5
    bf::interpreter<> test1(program);
    test1.set_input({2});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 5);

    // 7 + 3 == 10
    bf::interpreter<> test2(program);
    test2.set_input({7});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 10);
}

BOOST_AUTO_TEST_CASE(var__sub) {
    std::string program;
    {
        bf::generator bfg;

        auto a = bfg.new_var("a");
        a->input();
        a->sub(2);
        a->output();

        program = bfg.get_code();
    }

    // 5 - 2 == 3
    bf::interpreter<> test1(program);
    test1.set_input({5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 3);

    // 10 - 2 == 8
    bf::interpreter<> test2(program);
    test2.set_input({10});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 8);
}

BOOST_AUTO_TEST_CASE(var__mult) {
    std::string program;
    {
        bf::generator bfg;

        auto a = bfg.new_var("a");
        a->input();
        a->mult(3);
        a->output();

        program = bfg.get_code();
    }

    // 5 * 3 == 15
    bf::interpreter<> test1(program);
    test1.set_input({5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 15);

    // 8 * 3 == 24
    bf::interpreter<> test2(program);
    test2.set_input({8});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 24);
}

BOOST_AUTO_TEST_CASE(var__copy_to) {
    std::string program;
    {
        bf::generator bfg;
        auto begin = bfg.new_var();

        auto a = bfg.new_var("a");
        auto b = bfg.new_var("b");
        a->input();
        a->copy_to(*b);
        b->output();

        // Ensure correct SP movement
        begin->add(1);

        program = bfg.get_code();
    }

    // Simple copy test
    bf::interpreter<> test1(program);
    test1.set_input({5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 5);
    // Ensure correct SP movement
    BOOST_CHECK(test1.get_sp_position() == 0);
    BOOST_CHECK(test1.get_current_mem() == 1);
}
<commit_msg>Added test cases.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE generator
#include <boost/test/unit_test.hpp>

#include "../bf/generator.h"
#include "../bf/interpreter.h"

BOOST_AUTO_TEST_CASE(var__add) {
    std::string program;
    {
        bf::generator bfg;

        auto a = bfg.new_var("a");
        a->input();
        a->add(3);
        a->output();

        program = bfg.get_code();
    }

    // 2 + 3 == 5
    bf::interpreter<> test1(program);
    test1.set_input({2});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 5);

    // 7 + 3 == 10
    bf::interpreter<> test2(program);
    test2.set_input({7});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 10);
}

BOOST_AUTO_TEST_CASE(var__sub) {
    std::string program;
    {
        bf::generator bfg;

        auto a = bfg.new_var("a");
        a->input();
        a->sub(2);
        a->output();

        program = bfg.get_code();
    }

    // 5 - 2 == 3
    bf::interpreter<> test1(program);
    test1.set_input({5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 3);

    // 10 - 2 == 8
    bf::interpreter<> test2(program);
    test2.set_input({10});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 8);
}

BOOST_AUTO_TEST_CASE(var__mult) {
    std::string program;
    {
        bf::generator bfg;

        auto a = bfg.new_var("a");
        a->input();
        a->mult(3);
        a->output();

        program = bfg.get_code();
    }

    // 5 * 3 == 15
    bf::interpreter<> test1(program);
    test1.set_input({5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 15);

    // 8 * 3 == 24
    bf::interpreter<> test2(program);
    test2.set_input({8});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 24);
}

BOOST_AUTO_TEST_CASE(var__copy_to) {
    std::string program;
    {
        bf::generator bfg;
        auto begin = bfg.new_var();

        auto a = bfg.new_var("a");
        auto b = bfg.new_var("b");
        a->input();
        a->copy_to(*b);
        b->output();

        // Ensure correct SP movement
        begin->add(1);

        program = bfg.get_code();
    }

    // Simple copy test
    bf::interpreter<> test1(program);
    test1.set_input({5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 5);
    // Ensure correct SP movement
    BOOST_CHECK(test1.get_sp_position() == 0);
    BOOST_CHECK(test1.get_current_mem() == 1);
}

BOOST_AUTO_TEST_CASE(var__add_to) {
    std::string program;
    {
        bf::generator bfg;
        auto begin = bfg.new_var();

        auto a = bfg.new_var("a");
        auto b = bfg.new_var("b");
        a->input();
        b->input();
        a->add_to(*b);
        b->output();

        // Ensure correct SP movement
        begin->add(1);

        program = bfg.get_code();
    }

    // 3 + 4 == 7
    bf::interpreter<> test1(program);
    test1.set_input({3, 4});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 7);
    // Ensure correct SP movement
    BOOST_CHECK(test1.get_sp_position() == 0);
    BOOST_CHECK(test1.get_current_mem() == 1);

    // 5 + 8 == 13
    bf::interpreter<> test2(program);
    test2.set_input({5, 8});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 13);
    // Ensure correct SP movement
    BOOST_CHECK(test2.get_sp_position() == 0);
    BOOST_CHECK(test2.get_current_mem() == 1);
}

BOOST_AUTO_TEST_CASE(var__sub_from) {
    std::string program;
    {
        bf::generator bfg;
        auto begin = bfg.new_var();

        auto a = bfg.new_var("a");
        auto b = bfg.new_var("b");
        a->input();
        b->input();
        a->sub_from(*b);
        b->output();

        // Ensure correct SP movement
        begin->add(1);

        program = bfg.get_code();
    }

    // 5 - 3 == 2
    bf::interpreter<> test1(program);
    test1.set_input({3, 5});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 2);
    // Ensure correct SP movement
    BOOST_CHECK(test1.get_sp_position() == 0);
    BOOST_CHECK(test1.get_current_mem() == 1);

    // 20 - 7 == 13
    bf::interpreter<> test2(program);
    test2.set_input({7, 20});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 13);
    // Ensure correct SP movement
    BOOST_CHECK(test2.get_sp_position() == 0);
    BOOST_CHECK(test2.get_current_mem() == 1);
}

BOOST_AUTO_TEST_CASE(var__not_of) {
    std::string program;
    {
        bf::generator bfg;
        auto begin = bfg.new_var();

        auto a = bfg.new_var("a");
        auto b = bfg.new_var("b");
        a->input();
        b->not_of(*a);
        b->output();

        // Ensure correct SP movement
        begin->add(1);

        program = bfg.get_code();
    }

    // !0 == 1
    bf::interpreter<> test1(program);
    test1.set_input({0});
    test1.run();
    BOOST_CHECK(test1.get_output().at(0) == 1);
    // Ensure correct SP movement
    BOOST_CHECK(test1.get_sp_position() == 0);
    BOOST_CHECK(test1.get_current_mem() == 1);

    // !1 == 0
    bf::interpreter<> test2(program);
    test2.set_input({1});
    test2.run();
    BOOST_CHECK(test2.get_output().at(0) == 0);
    // Ensure correct SP movement
    BOOST_CHECK(test2.get_sp_position() == 0);
    BOOST_CHECK(test2.get_current_mem() == 1);

    // !7 == 0
    bf::interpreter<> test3(program);
    test3.set_input({7});
    test3.run();
    BOOST_CHECK(test3.get_output().at(0) == 0);
    // Ensure correct SP movement
    BOOST_CHECK(test3.get_sp_position() == 0);
    BOOST_CHECK(test3.get_current_mem() == 1);
}
<|endoftext|>


<commit_before>//===-- VMRange.cpp ---------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/VMRange.h"

#include "lldb/Utility/Stream.h"
#include "lldb/lldb-types.h" // for addr_t

#include <algorithm>
#include <iterator> // for distance
#include <vector>   // for const_iterator

#include <stddef.h> // for size_t
#include <stdint.h> // for UINT32_MAX, uint32_t

using namespace lldb;
using namespace lldb_private;

bool VMRange::ContainsValue(const VMRange::collection &coll,
                            lldb::addr_t value) {
  ValueInRangeUnaryPredicate in_range_predicate(value);
  VMRange::const_iterator end = coll.end();
  return std::find_if(coll.begin(), end, in_range_predicate) != end;
}

bool VMRange::ContainsRange(const VMRange::collection &coll,
                            const VMRange &range) {
  RangeInRangeUnaryPredicate in_range_predicate(range);
  VMRange::const_iterator end = coll.end();
  return std::find_if(coll.begin(), end, in_range_predicate) != end;
}

size_t VMRange::FindRangeIndexThatContainsValue(const VMRange::collection &coll,
                                                lldb::addr_t value) {
  ValueInRangeUnaryPredicate in_range_predicate(value);
  VMRange::const_iterator begin = coll.begin();
  VMRange::const_iterator end = coll.end();
  VMRange::const_iterator pos = std::find_if(begin, end, in_range_predicate);
  if (pos != end)
    return std::distance(begin, pos);
  return UINT32_MAX;
}

void VMRange::Dump(Stream *s, lldb::addr_t offset, uint32_t addr_width) const {
  s->AddressRange(offset + GetBaseAddress(), offset + GetEndAddress(),
                  addr_width);
}

bool lldb_private::operator==(const VMRange &lhs, const VMRange &rhs) {
  return lhs.GetBaseAddress() == rhs.GetBaseAddress() &&
         lhs.GetEndAddress() == rhs.GetEndAddress();
}

bool lldb_private::operator!=(const VMRange &lhs, const VMRange &rhs) {
  return lhs.GetBaseAddress() != rhs.GetBaseAddress() ||
         lhs.GetEndAddress() != rhs.GetEndAddress();
}

bool lldb_private::operator<(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() < rhs.GetEndAddress();
}

bool lldb_private::operator<=(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() <= rhs.GetEndAddress();
}

bool lldb_private::operator>(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() > rhs.GetEndAddress();
}

bool lldb_private::operator>=(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() >= rhs.GetEndAddress();
}
<commit_msg>[VMRange] Use llvm::find_if. Thanks to Zachary for the suggestion.<commit_after>//===-- VMRange.cpp ---------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/VMRange.h"

#include "lldb/Utility/Stream.h"
#include "lldb/lldb-types.h" // for addr_t

#include <algorithm>
#include <iterator> // for distance
#include <vector>   // for const_iterator

#include <stddef.h> // for size_t
#include <stdint.h> // for UINT32_MAX, uint32_t

using namespace lldb;
using namespace lldb_private;

bool VMRange::ContainsValue(const VMRange::collection &coll,
                            lldb::addr_t value) {
  ValueInRangeUnaryPredicate in_range_predicate(value);
  return llvm::find_if(coll, in_range_predicate) != coll.end();
}

bool VMRange::ContainsRange(const VMRange::collection &coll,
                            const VMRange &range) {
  RangeInRangeUnaryPredicate in_range_predicate(range);
  return llvm::find_if(coll, in_range_predicate) != coll.end();
}

size_t VMRange::FindRangeIndexThatContainsValue(const VMRange::collection &coll,
                                                lldb::addr_t value) {
  ValueInRangeUnaryPredicate in_range_predicate(value);
  VMRange::const_iterator begin = coll.begin();
  VMRange::const_iterator end = coll.end();
  VMRange::const_iterator pos = std::find_if(begin, end, in_range_predicate);
  if (pos != end)
    return std::distance(begin, pos);
  return UINT32_MAX;
}

void VMRange::Dump(Stream *s, lldb::addr_t offset, uint32_t addr_width) const {
  s->AddressRange(offset + GetBaseAddress(), offset + GetEndAddress(),
                  addr_width);
}

bool lldb_private::operator==(const VMRange &lhs, const VMRange &rhs) {
  return lhs.GetBaseAddress() == rhs.GetBaseAddress() &&
         lhs.GetEndAddress() == rhs.GetEndAddress();
}

bool lldb_private::operator!=(const VMRange &lhs, const VMRange &rhs) {
  return lhs.GetBaseAddress() != rhs.GetBaseAddress() ||
         lhs.GetEndAddress() != rhs.GetEndAddress();
}

bool lldb_private::operator<(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() < rhs.GetEndAddress();
}

bool lldb_private::operator<=(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() <= rhs.GetEndAddress();
}

bool lldb_private::operator>(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() > rhs.GetEndAddress();
}

bool lldb_private::operator>=(const VMRange &lhs, const VMRange &rhs) {
  if (lhs.GetBaseAddress() > rhs.GetBaseAddress())
    return true;
  else if (lhs.GetBaseAddress() < rhs.GetBaseAddress())
    return false;
  return lhs.GetEndAddress() >= rhs.GetEndAddress();
}
<|endoftext|>


<commit_before>#include "CardiacKirchhoffStressDivergence.h"

#include "Material.h"
#include "SymmElasticityTensor.h"

template<>
InputParameters validParams<CardiacKirchhoffStressDivergence>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addRequiredCoupledVar("displacements", "The x, y, and z displacement");
  params.addCoupledVar("p", "The hydrostatic pressure (if using an incompressible material)");
  params.set<bool>("use_displaced_mesh") = false;
  return params;
}

CardiacKirchhoffStressDivergence::CardiacKirchhoffStressDivergence(const std::string & name, InputParameters parameters)
  :Kernel(name, parameters),
   _stress(getMaterialProperty<SymmTensor>("Kirchhoff_stress")),
   _stress_derivative(getMaterialProperty<SymmGenericElasticityTensor>("Kirchhoff_stress_derivative")),
   _Cinv(getMaterialProperty<SymmTensor>("Cinv")),
   _component(getParam<unsigned int>("component")),
   _has_p(isCoupled("p")),
   _p_var(_has_p ? coupled("p") : 0)
{
  // see http://mooseframework.org/wiki/Faq/#coupling-to-an-arbitrary-number-of-variables-back-to-top for details on this magic
  _grad_disp.resize(coupledComponents("displacements"));

  mooseAssert(_grad_disp.size() == 3, "CardiacKirchhoffStressDivergence: displacements must have exactly 3 components");

  for (unsigned int i=0; i<_grad_disp.size(); ++i) {
    _grad_disp[i] = &coupledGradient("displacements", i);
    _disp_var[i]  = coupled("displacements", i);
  }
}

Real
CardiacKirchhoffStressDivergence::computeQpResidual()
{
  // nonlinear variables are displacements u(i)=x(i)-X(i)
  // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
  RealVectorValue grad_xi(_grad_u[_qp]);
  grad_xi(_component) += 1;

  // compute _grad_xi * _stress[_qp] * _grad_test[_i][_qp]
  return grad_xi*(_stress[_qp]*_grad_test[_i][_qp]);
}

/// This produces the second term in the notes for the Jacobian
Real
CardiacKirchhoffStressDivergence::JacobianSecondOrderContribution(const RealVectorValue & grad_xi, const RealVectorValue & grad_xk)
{
  SymmTensor dE(/* 00 */      _grad_phi[_j][_qp](0)*grad_xk(0),
                /* 11 */      _grad_phi[_j][_qp](1)*grad_xk(1),
                /* 22 */      _grad_phi[_j][_qp](2)*grad_xk(2),
                /* 01 */ 0.5*(_grad_phi[_j][_qp](0)*grad_xk(1) + grad_xk(0)*_grad_phi[_j][_qp](1)),
                /* 12 */ 0.5*(_grad_phi[_j][_qp](1)*grad_xk(2) + grad_xk(1)*_grad_phi[_j][_qp](2)),
                /* 02 */ 0.5*(_grad_phi[_j][_qp](0)*grad_xk(2) + grad_xk(0)*_grad_phi[_j][_qp](2)));

  return _stress_derivative[_qp].doubleLeftSymmDoubleRightContraction(grad_xi, _grad_test[_i][_qp], dE);
}

Real
CardiacKirchhoffStressDivergence::computeQpJacobian()
{
  // nonlinear variables are displacements u(i)=x(i)-X(i)
  // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
  RealVectorValue grad_xi(_grad_u[_qp]);
  grad_xi(_component) += 1;

  return _grad_phi[_j][_qp]*(_stress[_qp]*_grad_test[_i][_qp])
    + JacobianSecondOrderContribution(grad_xi, grad_xi);
}

Real
CardiacKirchhoffStressDivergence::computeQpOffDiagJacobian(unsigned int jvar)
{
  int idx(-1);

  if (_has_p && jvar == _p_var) {
    // nonlinear variables are displacements u(i)=x(i)-X(i)
    // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
    RealVectorValue grad_xi(_grad_u[_qp]);
    grad_xi(_component) += 1;

    return -2.*_phi[_j][_qp]*grad_xi*(_Cinv[_qp]*_grad_test[_i][_qp]);
  }

  if (jvar == _disp_var[0])      { idx=0; }
  else if (jvar == _disp_var[1]) { idx=1; }
  else if (jvar == _disp_var[2]) { idx=2; }
  else return 0;

  // nonlinear variables are displacements u(i)=x(i)-X(i)
  // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
  RealVectorValue grad_xi(_grad_u[_qp]);
  grad_xi(_component) += 1;

  RealVectorValue grad_xk( (*_grad_disp[idx])[_qp] );
  grad_xk(idx) += 1;

  return JacobianSecondOrderContribution(grad_xi, grad_xk);
}
<commit_msg>fixed typo in pressure contribution to displacement Jacobian. - Now all pressure-related terms comply with the finite-difference values<commit_after>#include "CardiacKirchhoffStressDivergence.h"

#include "Material.h"
#include "SymmElasticityTensor.h"

template<>
InputParameters validParams<CardiacKirchhoffStressDivergence>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addRequiredCoupledVar("displacements", "The x, y, and z displacement");
  params.addCoupledVar("p", "The hydrostatic pressure (if using an incompressible material)");
  params.set<bool>("use_displaced_mesh") = false;
  return params;
}

CardiacKirchhoffStressDivergence::CardiacKirchhoffStressDivergence(const std::string & name, InputParameters parameters)
  :Kernel(name, parameters),
   _stress(getMaterialProperty<SymmTensor>("Kirchhoff_stress")),
   _stress_derivative(getMaterialProperty<SymmGenericElasticityTensor>("Kirchhoff_stress_derivative")),
   _Cinv(getMaterialProperty<SymmTensor>("Cinv")),
   _component(getParam<unsigned int>("component")),
   _has_p(isCoupled("p")),
   _p_var(_has_p ? coupled("p") : 0)
{
  // see http://mooseframework.org/wiki/Faq/#coupling-to-an-arbitrary-number-of-variables-back-to-top for details on this magic
  _grad_disp.resize(coupledComponents("displacements"));

  mooseAssert(_grad_disp.size() == 3, "CardiacKirchhoffStressDivergence: displacements must have exactly 3 components");

  for (unsigned int i=0; i<_grad_disp.size(); ++i) {
    _grad_disp[i] = &coupledGradient("displacements", i);
    _disp_var[i]  = coupled("displacements", i);
  }
}

Real
CardiacKirchhoffStressDivergence::computeQpResidual()
{
  // nonlinear variables are displacements u(i)=x(i)-X(i)
  // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
  RealVectorValue grad_xi(_grad_u[_qp]);
  grad_xi(_component) += 1;

  // compute _grad_xi * _stress[_qp] * _grad_test[_i][_qp]
  return grad_xi*(_stress[_qp]*_grad_test[_i][_qp]);
}

/// This produces the second term in the notes for the Jacobian
Real
CardiacKirchhoffStressDivergence::JacobianSecondOrderContribution(const RealVectorValue & grad_xi, const RealVectorValue & grad_xk)
{
  SymmTensor dE(/* 00 */      _grad_phi[_j][_qp](0)*grad_xk(0),
                /* 11 */      _grad_phi[_j][_qp](1)*grad_xk(1),
                /* 22 */      _grad_phi[_j][_qp](2)*grad_xk(2),
                /* 01 */ 0.5*(_grad_phi[_j][_qp](0)*grad_xk(1) + grad_xk(0)*_grad_phi[_j][_qp](1)),
                /* 12 */ 0.5*(_grad_phi[_j][_qp](1)*grad_xk(2) + grad_xk(1)*_grad_phi[_j][_qp](2)),
                /* 02 */ 0.5*(_grad_phi[_j][_qp](0)*grad_xk(2) + grad_xk(0)*_grad_phi[_j][_qp](2)));

  return _stress_derivative[_qp].doubleLeftSymmDoubleRightContraction(grad_xi, _grad_test[_i][_qp], dE);
}

Real
CardiacKirchhoffStressDivergence::computeQpJacobian()
{
  // nonlinear variables are displacements u(i)=x(i)-X(i)
  // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
  RealVectorValue grad_xi(_grad_u[_qp]);
  grad_xi(_component) += 1;

  return _grad_phi[_j][_qp]*(_stress[_qp]*_grad_test[_i][_qp])
    + JacobianSecondOrderContribution(grad_xi, grad_xi);
}

Real
CardiacKirchhoffStressDivergence::computeQpOffDiagJacobian(unsigned int jvar)
{
  int idx(-1);

  if (_has_p && jvar == _p_var) {
    // nonlinear variables are displacements u(i)=x(i)-X(i)
    // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
    RealVectorValue grad_xi(_grad_u[_qp]);
    grad_xi(_component) += 1;

    return -_phi[_j][_qp]*grad_xi*(_Cinv[_qp]*_grad_test[_i][_qp]);
  }

  if (jvar == _disp_var[0])      { idx=0; }
  else if (jvar == _disp_var[1]) { idx=1; }
  else if (jvar == _disp_var[2]) { idx=2; }
  else return 0;

  // nonlinear variables are displacements u(i)=x(i)-X(i)
  // However, we do need the deformation gradient here: dx(i)/dX(j) = du(i)/dX(j) + delta(ij)
  RealVectorValue grad_xi(_grad_u[_qp]);
  grad_xi(_component) += 1;

  RealVectorValue grad_xk( (*_grad_disp[idx])[_qp] );
  grad_xk(idx) += 1;

  return JacobianSecondOrderContribution(grad_xi, grad_xk);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <class T>
struct Node
{
	T data;
	Node<T>* left;
	Node<T>* right;
};

template <class T>
class BinaryTree
{
private:
	Node<T> *root;
public:
	BinaryTree();
	~BinaryTree();
	void deleteNode(Node<T>* temp);
	void insert_node(const T&);
	void print()const;
	Node<T>*root_()const;
	Node<T> *find_node(const T&, Node<T>*)const;
	void show(Node<T>*, unsigned int)const;
	void reading(const std::string&);
	void output(std::ostream& ost, Node<T>*)const;
	void writing(const std::string&)const;
	bool search_result(const T& value)const;
	Node<T>* get_pointer(const T& value, Node<T>* temp)const;

};

template<typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<class T>
Node<T>*BinaryTree<T>::root_()const
{
	return root;
}

template<typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
	if (temp == 0 || value == temp->element)
		return temp;
	if (value > temp->element)
		return get_pointer(value, temp->pRight);
	else return get_pointer(value, temp->pLeft);
}

template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
	return get_pointer(value, root);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
		return;
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
	ifstream fin(filename);
	if (root != nullptr)
		deleteNode(root);

	int k;
	fin >> k;
	T temp;
	for (int i = 0; i < k; ++i)
	{
		fin >> temp;
		insert_node(temp);
	}
	fin.close();
}

template<typename T>
void BinaryTree<T>::print() const
{
	output(cout, this->root);
}

template<typename T>
void BinaryTree<T>::output(ostream& ost, Node<T>* temp)const
{
	if (!temp) return;
	ost << temp->data << " ";
	output(ost, temp->left);
	output(ost, temp->right);
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream fout(filename);
	output(fout, root);
	fout.close();
}

template<typename T>
void BinaryTree<T>::show(Node<T>* temp, unsigned int level)const
{

	if (temp)
	{
		show(temp->left, level + 1);
		for (unsigned int i = 0; i < level; i++)
			std::cout << "-";
		std::cout << temp->data << std::endl;
		show(temp->right, level + 1);
	}
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <class T>
struct Node
{
	T data;
	Node<T>* left;
	Node<T>* right;
};

template <class T>
class BinaryTree
{
private:
	Node<T> *root;
public:
	BinaryTree();
	~BinaryTree();
	void deleteNode(Node<T>* temp);
	void insert_node(const T&);
	void print()const;
	Node<T>*root_()const;
	Node<T> *find_node(const T&, Node<T>*)const;
	void show(Node<T>*, unsigned int)const;
	void reading(const std::string&);
	void output(std::ostream& ost, Node<T>*)const;
	void writing(const std::string&)const;
	bool search_result(const T& value)const;
	Node<T>* get_pointer(const T& value, Node<T>* temp)const;

};

template<typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<class T>
Node<T>*BinaryTree<T>::root_()const
{
	return root;
}

template<typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return get_pointer(value, temp->right);
	else return get_pointer(value, temp->left);
}

template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
	return get_pointer(value, root);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
		return;
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
	ifstream fin(filename);
	if (root != nullptr)
		deleteNode(root);

	int k;
	fin >> k;
	T temp;
	for (int i = 0; i < k; ++i)
	{
		fin >> temp;
		insert_node(temp);
	}
	fin.close();
}

template<typename T>
void BinaryTree<T>::print() const
{
	output(cout, this->root);
}

template<typename T>
void BinaryTree<T>::output(ostream& ost, Node<T>* temp)const
{
	if (!temp) return;
	ost << temp->data << " ";
	output(ost, temp->left);
	output(ost, temp->right);
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream fout(filename);
	output(fout, root);
	fout.close();
}

template<typename T>
void BinaryTree<T>::show(Node<T>* temp, unsigned int level)const
{

	if (temp)
	{
		show(temp->left, level + 1);
		for (unsigned int i = 0; i < level; i++)
			std::cout << "-";
		std::cout << temp->data << std::endl;
		show(temp->right, level + 1);
	}
}
<|endoftext|>


<commit_before>/**************************************************************************/
/**
    Color Sensor

    @file     ColorSensor.cpp
    @author   Charlie Chen (CharmySoft)  <Charlie@CharmySoft.com>

    @section  Circuit
    - Color Sensor
      + SDA pin to analog pin 4
      + SCL pin to analog pin 5
*/
/**************************************************************************/
// Change the following line to enter calibration mode
#define F_CALIBRATING             false         /**< Is calibration in progress */
#define F_CALI_EMPTY_HOLE         false         /**< Is calibrating the empty hole's color */

// Constants
#define C_HOLE_CLEAR              300           /**< The clear value used to determine the hole's arrival */
#define C_IDEAL_CLEAR             96            /**< The ideal clear value for color detection */
#define C_ALLOWED_COLOR_VARIANCE  64            /**< Allowed color variance for color detection */
#define C_ALLOWED_CLEAR_VARIANCE  128           /**< Allowed clear variance for color detection */

#define C_ATIME TCS34725_INTEGRATIONTIME_154MS  /**< Color sensor integration time 154ms */
#define C_CYCLES (256 - C_ATIME)                /**< Color sensor cycles according to the integration time */

#include "ColorSensor.h"
#include "TopServo.h"
#include "BottomServo.h"
#include "ColorView.h"
#include "LCD.h"

ColorSensor::ColorSensor() : Adafruit_TCS34725(C_ATIME, TCS34725_GAIN_1X)
{
  lastSkittleTime = 0;
  isMeasuring = false;
}

void ColorSensor::setup() {
  if (!this->begin()) {
    // If the color sensor failed to initialize, print out an error
    Serial.println("Error: Color sensor not found.");
    lcd.setTopText("ERR: Color Sensor Connection");

    // Infinite loop so the program won't continue
    while (1);
  }
}

void ColorSensor::update()
{
  static C_Color bestColor(0, 0, 0);  // The best colors during a measuring cycle
  static uint16_t minClear;           // The minimum clear value during a measuring cycle
  uint16_t r, g, b, c;                // Red, green, blue and clear channel values

  // Reads the raw color values
  getRawData(&r, &g, &b, &c);

  // Create a C_Color object from raw colors
  C_Color colors = C_Color::createFromRawColors(C_CYCLES, r, g, b, c);

  // Check if the hole arrives at the color sensor
  if (colors.c < C_HOLE_CLEAR && !isMeasuring && millis() - lastSkittleTime > 1000) {
    Serial.println(millis() - lastSkittleTime);
    lastSkittleTime = millis();
    lcd.setBottomText("Start measuring");
    // Serial.println("Start measuring this Skittle's color.");
    isMeasuring = true;
    minClear = C_HOLE_CLEAR;
    bestColor = colors;
  }

  if (isMeasuring) {
    // Try and reach the ideal clear value
    if (colors.c < minClear && colors.c > C_IDEAL_CLEAR) {
      // The best color sample is picked when the clear is minimum while still larger than C_IDEAL_CLEAR
      minClear = colors.c;
      bestColor = colors;
    }
    // If the skittle moves away and there's nothing left for the color sensor there
    if (colors.c > C_HOLE_CLEAR) {
      bestColor.maximize(); // Maximize color
      bestColor.print();

      // Analyze the color
      colorResult result = _analyzeColor(bestColor);

      if (!servoTop.isRemeasuring() && HAS_RESULT(result)) {
        // Add 1 to the skittleCount if the color is not being re-measured and we've got the result
        skittleCount++;
        // Set the new Skittle count to the LCD screen
        lcd.setTopText(String("Count:") + skittleCount);
      }

      // Serial.println("Finish measuring.");
      isMeasuring = false;

    }
  }

  // printColors(r, g, b, c);
}

void ColorSensor::_calibrating(const C_Color& new_color) {
  static C_Color avg_c(new_color);  // The average color (result)
  static int count = 0;             // The amount of valid data samples

  // Get the color variance between the new color and the avarage color
  int diff = avg_c.compare(new_color);
  Serial.print("Diff: "); Serial.println(diff);

  // Check if the color variance is out of a valid range
  if (diff > C_ALLOWED_COLOR_VARIANCE) {
    Serial.println("Difference too big. This sample data is discarded.");
  } else {
    // If the new valid is valid, set the average color to include the new data
    avg_c.r = (avg_c.r * count + new_color.r) / (count + 1);
    avg_c.g = (avg_c.g * count + new_color.g) / (count + 1);
    avg_c.b = (avg_c.b * count + new_color.b) / (count + 1);
    avg_c.c = (avg_c.c * count + new_color.c) / (count + 1);
    count++;
    Serial.println("Average color:");
    avg_c.print();
  }
}

colorResult ColorSensor::_analyzeColor(const C_Color& bestColor)
{
  // Use a macro to generate a constant array colorList
  // whose indexes correspond to the colorResult enum
#define COLOR_DEF( identifier, name, color, color_view )  color
  const C_Color colorList [] = { COLORS_DEFINITION };
#undef COLOR_DEF
  // Compare the best color with the colorList and get the closest result
  colorResult tempResult = bestColor.compareWithColorList(colorList, C_ALLOWED_COLOR_VARIANCE);

  if (tempResult != RESULT_EMPTY)
    Serial.println("A Skittle has been detected!");
  //Serial.println("Maximized colors:");

#if F_CALIBRATING
  // If we are calibrating colors

  if (!F_CALI_EMPTY_HOLE && tempResult == RESULT_EMPTY)
    // Ignore empty hole's data unless F_CALI_EMPTY_HOLE is set
    return tempResult;

  _calibrating(bestColor);
  return tempResult;
#endif

  // Check if the clear value is out of allowed range
  if (HAS_RESULT(tempResult) && abs(int(bestColor.c) - int(colorList[tempResult].c)) > C_ALLOWED_CLEAR_VARIANCE) {
    // If the clear value is out of range, then set this result back to unknown
    tempResult = RESULT_UNKNOWN;
  }

  // Set the result
  colorView.setColorByResult(tempResult);
  lcd.setBottomTextByResult(tempResult);
  if (HAS_RESULT(tempResult))
    servoBtm.setResult(tempResult);

  if (tempResult == RESULT_UNKNOWN) {
    // If color cannot be detected, try again
    servoTop.remeasureColor();
  } else {
    if (servoTop.isRemeasuring()) {
      Serial.println("We've got the color on re-measurement.");
      servoTop.stopRemeasuring();
    }
  }
  return tempResult;
}

unsigned long ColorSensor::getLastSkittleTime() {
  return lastSkittleTime;
}

<commit_msg>Shorten the text to be shown on the LCD<commit_after>/**************************************************************************/
/**
    Color Sensor

    @file     ColorSensor.cpp
    @author   Charlie Chen (CharmySoft)  <Charlie@CharmySoft.com>

    @section  Circuit
    - Color Sensor
      + SDA pin to analog pin 4
      + SCL pin to analog pin 5
*/
/**************************************************************************/
// Change the following line to enter calibration mode
#define F_CALIBRATING             false         /**< Is calibration in progress */
#define F_CALI_EMPTY_HOLE         false         /**< Is calibrating the empty hole's color */

// Constants
#define C_HOLE_CLEAR              300           /**< The clear value used to determine the hole's arrival */
#define C_IDEAL_CLEAR             96            /**< The ideal clear value for color detection */
#define C_ALLOWED_COLOR_VARIANCE  64            /**< Allowed color variance for color detection */
#define C_ALLOWED_CLEAR_VARIANCE  128           /**< Allowed clear variance for color detection */

#define C_ATIME TCS34725_INTEGRATIONTIME_154MS  /**< Color sensor integration time 154ms */
#define C_CYCLES (256 - C_ATIME)                /**< Color sensor cycles according to the integration time */

#include "ColorSensor.h"
#include "TopServo.h"
#include "BottomServo.h"
#include "ColorView.h"
#include "LCD.h"

ColorSensor::ColorSensor() : Adafruit_TCS34725(C_ATIME, TCS34725_GAIN_1X)
{
  lastSkittleTime = 0;
  isMeasuring = false;
}

void ColorSensor::setup() {
  if (!this->begin()) {
    // If the color sensor failed to initialize, print out an error
    Serial.println("Error: Color sensor not found.");
    lcd.setTopText("ERR: Sensor Cnct");

    // Infinite loop so the program won't continue
    while (1);
  }
}

void ColorSensor::update()
{
  static C_Color bestColor(0, 0, 0);  // The best colors during a measuring cycle
  static uint16_t minClear;           // The minimum clear value during a measuring cycle
  uint16_t r, g, b, c;                // Red, green, blue and clear channel values

  // Reads the raw color values
  getRawData(&r, &g, &b, &c);

  // Create a C_Color object from raw colors
  C_Color colors = C_Color::createFromRawColors(C_CYCLES, r, g, b, c);

  // Check if the hole arrives at the color sensor
  if (colors.c < C_HOLE_CLEAR && !isMeasuring && millis() - lastSkittleTime > 1000) {
    Serial.println(millis() - lastSkittleTime);
    lastSkittleTime = millis();
    lcd.setBottomText("Start measuring");
    // Serial.println("Start measuring this Skittle's color.");
    isMeasuring = true;
    minClear = C_HOLE_CLEAR;
    bestColor = colors;
  }

  if (isMeasuring) {
    // Try and reach the ideal clear value
    if (colors.c < minClear && colors.c > C_IDEAL_CLEAR) {
      // The best color sample is picked when the clear is minimum while still larger than C_IDEAL_CLEAR
      minClear = colors.c;
      bestColor = colors;
    }
    // If the skittle moves away and there's nothing left for the color sensor there
    if (colors.c > C_HOLE_CLEAR) {
      bestColor.maximize(); // Maximize color
      bestColor.print();

      // Analyze the color
      colorResult result = _analyzeColor(bestColor);

      if (!servoTop.isRemeasuring() && HAS_RESULT(result)) {
        // Add 1 to the skittleCount if the color is not being re-measured and we've got the result
        skittleCount++;
        // Set the new Skittle count to the LCD screen
        lcd.setTopText(String("Count:") + skittleCount);
      }

      // Serial.println("Finish measuring.");
      isMeasuring = false;

    }
  }

  // printColors(r, g, b, c);
}

void ColorSensor::_calibrating(const C_Color& new_color) {
  static C_Color avg_c(new_color);  // The average color (result)
  static int count = 0;             // The amount of valid data samples

  // Get the color variance between the new color and the avarage color
  int diff = avg_c.compare(new_color);
  Serial.print("Diff: "); Serial.println(diff);

  // Check if the color variance is out of a valid range
  if (diff > C_ALLOWED_COLOR_VARIANCE) {
    Serial.println("Difference too big. This sample data is discarded.");
  } else {
    // If the new valid is valid, set the average color to include the new data
    avg_c.r = (avg_c.r * count + new_color.r) / (count + 1);
    avg_c.g = (avg_c.g * count + new_color.g) / (count + 1);
    avg_c.b = (avg_c.b * count + new_color.b) / (count + 1);
    avg_c.c = (avg_c.c * count + new_color.c) / (count + 1);
    count++;
    Serial.println("Average color:");
    avg_c.print();
  }
}

colorResult ColorSensor::_analyzeColor(const C_Color& bestColor)
{
  // Use a macro to generate a constant array colorList
  // whose indexes correspond to the colorResult enum
#define COLOR_DEF( identifier, name, color, color_view )  color
  const C_Color colorList [] = { COLORS_DEFINITION };
#undef COLOR_DEF
  // Compare the best color with the colorList and get the closest result
  colorResult tempResult = bestColor.compareWithColorList(colorList, C_ALLOWED_COLOR_VARIANCE);

  if (tempResult != RESULT_EMPTY)
    Serial.println("A Skittle has been detected!");
  //Serial.println("Maximized colors:");

#if F_CALIBRATING
  // If we are calibrating colors

  if (!F_CALI_EMPTY_HOLE && tempResult == RESULT_EMPTY)
    // Ignore empty hole's data unless F_CALI_EMPTY_HOLE is set
    return tempResult;

  _calibrating(bestColor);
  return tempResult;
#endif

  // Check if the clear value is out of allowed range
  if (HAS_RESULT(tempResult) && abs(int(bestColor.c) - int(colorList[tempResult].c)) > C_ALLOWED_CLEAR_VARIANCE) {
    // If the clear value is out of range, then set this result back to unknown
    tempResult = RESULT_UNKNOWN;
  }

  // Set the result
  colorView.setColorByResult(tempResult);
  lcd.setBottomTextByResult(tempResult);
  if (HAS_RESULT(tempResult))
    servoBtm.setResult(tempResult);

  if (tempResult == RESULT_UNKNOWN) {
    // If color cannot be detected, try again
    servoTop.remeasureColor();
  } else {
    if (servoTop.isRemeasuring()) {
      Serial.println("We've got the color on re-measurement.");
      servoTop.stopRemeasuring();
    }
  }
  return tempResult;
}

unsigned long ColorSensor::getLastSkittleTime() {
  return lastSkittleTime;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <vector>

#include <queue>
#include <map>
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>

#include "filelib.h"
#include "aligner.h"
#include "alignment_pharaoh.h"

namespace po = boost::program_options;
using namespace std;
using boost::shared_ptr;

struct Command {
  virtual ~Command() {}
  virtual string Name() const = 0;

  // returns 1 for alignment grid output [default]
  // returns 2 if Summary() should be called [for AER, etc]
  virtual int Result() const { return 1; }

  virtual bool RequiresTwoOperands() const { return true; }
  virtual void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) = 0;
  void EnsureSize(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    x->resize(max(a.width(), b.width()), max(a.height(), b.height()));
  }
  static bool Safe(const Array2D<bool>& a, int i, int j) {
    if (i >= 0 && j >= 0 && i < a.width() && j < a.height())
      return a(i,j);
    else
      return false;
  }
  virtual void Summary() { assert(!"Summary should have been overridden"); }
};

// compute fmeasure, second alignment is reference, first is hyp
struct FMeasureCommand : public Command {
  FMeasureCommand() : matches(), num_predicted(), num_in_ref() {}
  int Result() const { return 2; }
  string Name() const { return "fmeasure"; }
  bool RequiresTwoOperands() const { return true; }
  void Apply(const Array2D<bool>& hyp, const Array2D<bool>& ref, Array2D<bool>* x) {
    (void) x;   // AER just computes statistics, not an alignment
    int i_len = ref.width();
    int j_len = ref.height();
    for (int i = 0; i < i_len; ++i) {
      for (int j = 0; j < j_len; ++j) {
        if (ref(i,j)) {
          ++num_in_ref;
          if (Safe(hyp, i, j)) ++matches;
        }
      }
    }
    for (int i = 0; i < hyp.width(); ++i)
      for (int j = 0; j < hyp.height(); ++j)
        if (hyp(i,j)) ++num_predicted;
  }
  void Summary() {
    if (num_predicted == 0 || num_in_ref == 0) {
      cerr << "Insufficient statistics to compute f-measure!\n";
      abort();
    }
    const double prec = static_cast<double>(matches) / num_predicted;
    const double rec = static_cast<double>(matches) / num_in_ref;
    cout << "P: " << prec << endl;
    cout << "R: " << rec << endl;
    const double f = (2.0 * prec * rec) / (rec + prec);
    cout << "F: " << f << endl;
  }
  int matches;
  int num_predicted;
  int num_in_ref;
};

struct DisplayCommand : public Command {
  string Name() const { return "display"; }
  bool RequiresTwoOperands() const { return false; }
  void Apply(const Array2D<bool>& in, const Array2D<bool>&not_used, Array2D<bool>* x) {
    *x = in;
    cout << *x << endl;
  }
};

struct ConvertCommand : public Command {
  string Name() const { return "convert"; }
  bool RequiresTwoOperands() const { return false; }
  void Apply(const Array2D<bool>& in, const Array2D<bool>&not_used, Array2D<bool>* x) {
    *x = in;
  }
};

struct InvertCommand : public Command {
  string Name() const { return "invert"; }
  bool RequiresTwoOperands() const { return false; }
  void Apply(const Array2D<bool>& in, const Array2D<bool>&not_used, Array2D<bool>* x) {
    Array2D<bool>& res = *x;
    res.resize(in.height(), in.width());
    for (int i = 0; i < in.height(); ++i)
      for (int j = 0; j < in.width(); ++j)
        res(i, j) = in(j, i);
  }
};

struct IntersectCommand : public Command {
  string Name() const { return "intersect"; }
  bool RequiresTwoOperands() const { return true; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    EnsureSize(a, b, x);
    Array2D<bool>& res = *x;
    for (int i = 0; i < a.width(); ++i)
      for (int j = 0; j < a.height(); ++j)
        res(i, j) = Safe(a, i, j) && Safe(b, i, j);
  }
};

struct UnionCommand : public Command {
  string Name() const { return "union"; }
  bool RequiresTwoOperands() const { return true; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    EnsureSize(a, b, x);
    Array2D<bool>& res = *x;
    for (int i = 0; i < res.width(); ++i)
      for (int j = 0; j < res.height(); ++j)
        res(i, j) = Safe(a, i, j) || Safe(b, i, j);
  }
};

struct RefineCommand : public Command {
  RefineCommand() {
    neighbors_.push_back(make_pair(1,0));
    neighbors_.push_back(make_pair(-1,0));
    neighbors_.push_back(make_pair(0,1));
    neighbors_.push_back(make_pair(0,-1));
  }
  bool RequiresTwoOperands() const { return true; }

  void Align(int i, int j) {
    res_(i, j) = true;
    is_i_aligned_[i] = true;
    is_j_aligned_[j] = true;
  }

  bool IsNeighborAligned(int i, int j) const {
    for (int k = 0; k < neighbors_.size(); ++k) {
      const int di = neighbors_[k].first;
      const int dj = neighbors_[k].second;
      if (Safe(res_, i + di, j + dj))
        return true;
    }
    return false;
  }

  bool IsNeitherAligned(int i, int j) const {
    return !(is_i_aligned_[i] || is_j_aligned_[j]);
  }

  bool IsOneOrBothUnaligned(int i, int j) const {
    return !(is_i_aligned_[i] && is_j_aligned_[j]);
  }

  bool KoehnAligned(int i, int j) const {
    return IsOneOrBothUnaligned(i, j) && IsNeighborAligned(i, j);
  }

  typedef bool (RefineCommand::*Predicate)(int i, int j) const;

 protected:
  void InitRefine(
      const Array2D<bool>& a,
      const Array2D<bool>& b) {
    res_.clear();
    EnsureSize(a, b, &res_);
    in_.clear(); un_.clear(); is_i_aligned_.clear(); is_j_aligned_.clear();
    EnsureSize(a, b, &in_);
    EnsureSize(a, b, &un_);
    is_i_aligned_.resize(res_.width(), false);
    is_j_aligned_.resize(res_.height(), false);
    for (int i = 0; i < in_.width(); ++i)
      for (int j = 0; j < in_.height(); ++j) {
        un_(i, j) = Safe(a, i, j) || Safe(b, i, j);
        in_(i, j) = Safe(a, i, j) && Safe(b, i, j);
        if (in_(i, j)) Align(i, j);
    }
  }
  // "grow" the resulting alignment using the points in adds
  // if they match the constraints determined by pred
  void Grow(Predicate pred, bool idempotent, const Array2D<bool>& adds) {
    if (idempotent) {
      for (int i = 0; i < adds.width(); ++i)
        for (int j = 0; j < adds.height(); ++j) {
          if (adds(i, j) && !res_(i, j) &&
              (this->*pred)(i, j)) Align(i, j);
        }
      return;
    }
    set<pair<int, int> > p;
    for (int i = 0; i < adds.width(); ++i)
      for (int j = 0; j < adds.height(); ++j)
        if (adds(i, j) && !res_(i, j))
          p.insert(make_pair(i, j));
    bool keep_going = !p.empty();
    while (keep_going) {
      keep_going = false;
      for (set<pair<int, int> >::iterator pi = p.begin();
           pi != p.end(); ++pi) {
        if ((this->*pred)(pi->first, pi->second)) {
          Align(pi->first, pi->second);
          p.erase(pi);
          keep_going = true;
        }
      }
    }
  }
  Array2D<bool> res_;  // refined alignment
  Array2D<bool> in_;   // intersection alignment
  Array2D<bool> un_;   // union alignment
  vector<bool> is_i_aligned_;
  vector<bool> is_j_aligned_;
  vector<pair<int,int> > neighbors_;
};

struct DiagCommand : public RefineCommand {
  DiagCommand() {
    neighbors_.push_back(make_pair(1,1));
    neighbors_.push_back(make_pair(-1,1));
    neighbors_.push_back(make_pair(1,-1));
    neighbors_.push_back(make_pair(-1,-1));
  }
};

struct GDCommand : public DiagCommand {
  string Name() const { return "grow-diag"; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    InitRefine(a, b);
    Grow(&RefineCommand::KoehnAligned, false, un_);
    *x = res_;
  }
};

struct GDFCommand : public DiagCommand {
  string Name() const { return "grow-diag-final"; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    InitRefine(a, b);
    Grow(&RefineCommand::KoehnAligned, false, un_);
    Grow(&RefineCommand::IsOneOrBothUnaligned, true, a);
    Grow(&RefineCommand::IsOneOrBothUnaligned, true, b);
    *x = res_;
  }
};

struct GDFACommand : public DiagCommand {
  string Name() const { return "grow-diag-final-and"; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    InitRefine(a, b);
    Grow(&RefineCommand::KoehnAligned, false, un_);
    Grow(&RefineCommand::IsNeitherAligned, true, a);
    Grow(&RefineCommand::IsNeitherAligned, true, b);
    *x = res_;
  }
};

map<string, boost::shared_ptr<Command> > commands;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  ostringstream os;
  os << "[REQ] Operation to perform:";
  for (map<string, boost::shared_ptr<Command> >::iterator it = commands.begin();
       it != commands.end(); ++it) {
    os << ' ' << it->first;
  }
  string cstr = os.str();
  opts.add_options()
        ("input_1,i", po::value<string>(), "[REQ] Alignment 1 file, - for STDIN")
        ("input_2,j", po::value<string>(), "[OPT] Alignment 2 file, - for STDIN")
	("command,c", po::value<string>()->default_value("convert"), cstr.c_str())
        ("help,h", "Print this help message and exit");
  po::options_description clo("Command line options");
  po::options_description dcmdline_options;
  dcmdline_options.add(opts);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  po::notify(*conf);

  if (conf->count("help") || conf->count("input_1") == 0 || conf->count("command") == 0) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
  const string cmd = (*conf)["command"].as<string>();
  if (commands.count(cmd) == 0) {
    cerr << "Don't understand command: " << cmd << endl;
    exit(1);
  }
  if (commands[cmd]->RequiresTwoOperands()) {
    if (conf->count("input_2") == 0) {
      cerr << "Command '" << cmd << "' requires two alignment files\n";
      exit(1);
    }
    if ((*conf)["input_1"].as<string>() == "-" && (*conf)["input_2"].as<string>() == "-") {
      cerr << "Both inputs cannot be STDIN\n";
      exit(1);
    }
  } else {
    if (conf->count("input_2") != 0) {
      cerr << "Command '" << cmd << "' requires only one alignment file\n";
      exit(1);
    }
  }
}

template<class C> static void AddCommand() {
  C* c = new C;
  commands[c->Name()].reset(c);
}

int main(int argc, char **argv) {
  AddCommand<ConvertCommand>();
  AddCommand<DisplayCommand>();
  AddCommand<InvertCommand>();
  AddCommand<IntersectCommand>();
  AddCommand<UnionCommand>();
  AddCommand<GDCommand>();
  AddCommand<GDFCommand>();
  AddCommand<GDFACommand>();
  AddCommand<FMeasureCommand>();
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);
  Command& cmd = *commands[conf["command"].as<string>()];
  boost::shared_ptr<ReadFile> rf1(new ReadFile(conf["input_1"].as<string>()));
  boost::shared_ptr<ReadFile> rf2;
  if (cmd.RequiresTwoOperands())
    rf2.reset(new ReadFile(conf["input_2"].as<string>()));
  istream* in1 = rf1->stream();
  istream* in2 = NULL;
  if (rf2) in2 = rf2->stream();
  while(*in1) {
    string line1;
    string line2;
    getline(*in1, line1);
    if (in2) {
      getline(*in2, line2);
      if ((*in1 && !*in2) || (*in2 && !*in1)) {
        cerr << "Mismatched number of lines!\n";
        exit(1);
      }
    }
    if (line1.empty() && !*in1) break;
    shared_ptr<Array2D<bool> > out(new Array2D<bool>);
    shared_ptr<Array2D<bool> > a1 = AlignmentPharaoh::ReadPharaohAlignmentGrid(line1);
    if (in2) {
      shared_ptr<Array2D<bool> > a2 = AlignmentPharaoh::ReadPharaohAlignmentGrid(line2);
      cmd.Apply(*a1, *a2, out.get());
    } else {
      Array2D<bool> dummy;
      cmd.Apply(*a1, dummy, out.get());
    }

    if (cmd.Result() == 1) {
      AlignmentPharaoh::SerializePharaohFormat(*out, &cout);
    }
  }
  if (cmd.Result() == 2)
    cmd.Summary();
  return 0;
}

<commit_msg>clean up alignment tools<commit_after>#include <iostream>
#include <sstream>
#include <vector>

#include <queue>
#include <map>
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>

#include "filelib.h"
#include "alignment_pharaoh.h"

namespace po = boost::program_options;
using namespace std;
using boost::shared_ptr;

struct Command {
  virtual ~Command() {}
  virtual string Name() const = 0;

  // returns 1 for alignment grid output [default]
  // returns 2 if Summary() should be called [for AER, etc]
  virtual int Result() const { return 1; }

  virtual bool RequiresTwoOperands() const { return true; }
  virtual void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) = 0;
  void EnsureSize(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    x->resize(max(a.width(), b.width()), max(a.height(), b.height()));
  }
  static bool Safe(const Array2D<bool>& a, int i, int j) {
    if (i >= 0 && j >= 0 && i < a.width() && j < a.height())
      return a(i,j);
    else
      return false;
  }
  virtual void Summary() { assert(!"Summary should have been overridden"); }
};

// compute fmeasure, second alignment is reference, first is hyp
struct FMeasureCommand : public Command {
  FMeasureCommand() : matches(), num_predicted(), num_in_ref() {}
  int Result() const { return 2; }
  string Name() const { return "fmeasure"; }
  bool RequiresTwoOperands() const { return true; }
  void Apply(const Array2D<bool>& hyp, const Array2D<bool>& ref, Array2D<bool>* x) {
    (void) x;   // AER just computes statistics, not an alignment
    int i_len = ref.width();
    int j_len = ref.height();
    for (int i = 0; i < i_len; ++i) {
      for (int j = 0; j < j_len; ++j) {
        if (ref(i,j)) {
          ++num_in_ref;
          if (Safe(hyp, i, j)) ++matches;
        }
      }
    }
    for (int i = 0; i < hyp.width(); ++i)
      for (int j = 0; j < hyp.height(); ++j)
        if (hyp(i,j)) ++num_predicted;
  }
  void Summary() {
    if (num_predicted == 0 || num_in_ref == 0) {
      cerr << "Insufficient statistics to compute f-measure!\n";
      abort();
    }
    const double prec = static_cast<double>(matches) / num_predicted;
    const double rec = static_cast<double>(matches) / num_in_ref;
    cout << "P: " << prec << endl;
    cout << "R: " << rec << endl;
    const double f = (2.0 * prec * rec) / (rec + prec);
    cout << "F: " << f << endl;
  }
  int matches;
  int num_predicted;
  int num_in_ref;
};

struct DisplayCommand : public Command {
  string Name() const { return "display"; }
  bool RequiresTwoOperands() const { return false; }
  void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {
    *x = in;
    cout << *x << endl;
  }
};

struct ConvertCommand : public Command {
  string Name() const { return "convert"; }
  bool RequiresTwoOperands() const { return false; }
  void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {
    *x = in;
  }
};

struct InvertCommand : public Command {
  string Name() const { return "invert"; }
  bool RequiresTwoOperands() const { return false; }
  void Apply(const Array2D<bool>& in, const Array2D<bool>&, Array2D<bool>* x) {
    Array2D<bool>& res = *x;
    res.resize(in.height(), in.width());
    for (int i = 0; i < in.height(); ++i)
      for (int j = 0; j < in.width(); ++j)
        res(i, j) = in(j, i);
  }
};

struct IntersectCommand : public Command {
  string Name() const { return "intersect"; }
  bool RequiresTwoOperands() const { return true; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    EnsureSize(a, b, x);
    Array2D<bool>& res = *x;
    for (int i = 0; i < a.width(); ++i)
      for (int j = 0; j < a.height(); ++j)
        res(i, j) = Safe(a, i, j) && Safe(b, i, j);
  }
};

struct UnionCommand : public Command {
  string Name() const { return "union"; }
  bool RequiresTwoOperands() const { return true; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    EnsureSize(a, b, x);
    Array2D<bool>& res = *x;
    for (int i = 0; i < res.width(); ++i)
      for (int j = 0; j < res.height(); ++j)
        res(i, j) = Safe(a, i, j) || Safe(b, i, j);
  }
};

struct RefineCommand : public Command {
  RefineCommand() {
    neighbors_.push_back(make_pair(1,0));
    neighbors_.push_back(make_pair(-1,0));
    neighbors_.push_back(make_pair(0,1));
    neighbors_.push_back(make_pair(0,-1));
  }
  bool RequiresTwoOperands() const { return true; }

  void Align(int i, int j) {
    res_(i, j) = true;
    is_i_aligned_[i] = true;
    is_j_aligned_[j] = true;
  }

  bool IsNeighborAligned(int i, int j) const {
    for (int k = 0; k < neighbors_.size(); ++k) {
      const int di = neighbors_[k].first;
      const int dj = neighbors_[k].second;
      if (Safe(res_, i + di, j + dj))
        return true;
    }
    return false;
  }

  bool IsNeitherAligned(int i, int j) const {
    return !(is_i_aligned_[i] || is_j_aligned_[j]);
  }

  bool IsOneOrBothUnaligned(int i, int j) const {
    return !(is_i_aligned_[i] && is_j_aligned_[j]);
  }

  bool KoehnAligned(int i, int j) const {
    return IsOneOrBothUnaligned(i, j) && IsNeighborAligned(i, j);
  }

  typedef bool (RefineCommand::*Predicate)(int i, int j) const;

 protected:
  void InitRefine(
      const Array2D<bool>& a,
      const Array2D<bool>& b) {
    res_.clear();
    EnsureSize(a, b, &res_);
    in_.clear(); un_.clear(); is_i_aligned_.clear(); is_j_aligned_.clear();
    EnsureSize(a, b, &in_);
    EnsureSize(a, b, &un_);
    is_i_aligned_.resize(res_.width(), false);
    is_j_aligned_.resize(res_.height(), false);
    for (int i = 0; i < in_.width(); ++i)
      for (int j = 0; j < in_.height(); ++j) {
        un_(i, j) = Safe(a, i, j) || Safe(b, i, j);
        in_(i, j) = Safe(a, i, j) && Safe(b, i, j);
        if (in_(i, j)) Align(i, j);
    }
  }
  // "grow" the resulting alignment using the points in adds
  // if they match the constraints determined by pred
  void Grow(Predicate pred, bool idempotent, const Array2D<bool>& adds) {
    if (idempotent) {
      for (int i = 0; i < adds.width(); ++i)
        for (int j = 0; j < adds.height(); ++j) {
          if (adds(i, j) && !res_(i, j) &&
              (this->*pred)(i, j)) Align(i, j);
        }
      return;
    }
    set<pair<int, int> > p;
    for (int i = 0; i < adds.width(); ++i)
      for (int j = 0; j < adds.height(); ++j)
        if (adds(i, j) && !res_(i, j))
          p.insert(make_pair(i, j));
    bool keep_going = !p.empty();
    while (keep_going) {
      keep_going = false;
      for (set<pair<int, int> >::iterator pi = p.begin();
           pi != p.end(); ++pi) {
        if ((this->*pred)(pi->first, pi->second)) {
          Align(pi->first, pi->second);
          p.erase(pi);
          keep_going = true;
        }
      }
    }
  }
  Array2D<bool> res_;  // refined alignment
  Array2D<bool> in_;   // intersection alignment
  Array2D<bool> un_;   // union alignment
  vector<bool> is_i_aligned_;
  vector<bool> is_j_aligned_;
  vector<pair<int,int> > neighbors_;
};

struct DiagCommand : public RefineCommand {
  DiagCommand() {
    neighbors_.push_back(make_pair(1,1));
    neighbors_.push_back(make_pair(-1,1));
    neighbors_.push_back(make_pair(1,-1));
    neighbors_.push_back(make_pair(-1,-1));
  }
};

struct GDCommand : public DiagCommand {
  string Name() const { return "grow-diag"; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    InitRefine(a, b);
    Grow(&RefineCommand::KoehnAligned, false, un_);
    *x = res_;
  }
};

struct GDFCommand : public DiagCommand {
  string Name() const { return "grow-diag-final"; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    InitRefine(a, b);
    Grow(&RefineCommand::KoehnAligned, false, un_);
    Grow(&RefineCommand::IsOneOrBothUnaligned, true, a);
    Grow(&RefineCommand::IsOneOrBothUnaligned, true, b);
    *x = res_;
  }
};

struct GDFACommand : public DiagCommand {
  string Name() const { return "grow-diag-final-and"; }
  void Apply(const Array2D<bool>& a, const Array2D<bool>& b, Array2D<bool>* x) {
    InitRefine(a, b);
    Grow(&RefineCommand::KoehnAligned, false, un_);
    Grow(&RefineCommand::IsNeitherAligned, true, a);
    Grow(&RefineCommand::IsNeitherAligned, true, b);
    *x = res_;
  }
};

map<string, boost::shared_ptr<Command> > commands;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  ostringstream os;
  os << "[REQ] Operation to perform:";
  for (map<string, boost::shared_ptr<Command> >::iterator it = commands.begin();
       it != commands.end(); ++it) {
    os << ' ' << it->first;
  }
  string cstr = os.str();
  opts.add_options()
        ("input_1,i", po::value<string>(), "[REQUIRED] Alignment 1 file, - for STDIN")
        ("input_2,j", po::value<string>(), "Alignment 2 file, - for STDIN")
	("command,c", po::value<string>()->default_value("convert"), cstr.c_str())
        ("help,h", "Print this help message and exit");
  po::options_description clo("Command line options");
  po::options_description dcmdline_options;
  dcmdline_options.add(opts);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  po::notify(*conf);

  if (conf->count("help") || conf->count("input_1") == 0 || conf->count("command") == 0) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
  const string cmd = (*conf)["command"].as<string>();
  if (commands.count(cmd) == 0) {
    cerr << "Don't understand command: " << cmd << endl;
    exit(1);
  }
  if (commands[cmd]->RequiresTwoOperands()) {
    if (conf->count("input_2") == 0) {
      cerr << "Command '" << cmd << "' requires two alignment files\n";
      exit(1);
    }
    if ((*conf)["input_1"].as<string>() == "-" && (*conf)["input_2"].as<string>() == "-") {
      cerr << "Both inputs cannot be STDIN\n";
      exit(1);
    }
  } else {
    if (conf->count("input_2") != 0) {
      cerr << "Command '" << cmd << "' requires only one alignment file\n";
      exit(1);
    }
  }
}

template<class C> static void AddCommand() {
  C* c = new C;
  commands[c->Name()].reset(c);
}

int main(int argc, char **argv) {
  AddCommand<ConvertCommand>();
  AddCommand<DisplayCommand>();
  AddCommand<InvertCommand>();
  AddCommand<IntersectCommand>();
  AddCommand<UnionCommand>();
  AddCommand<GDCommand>();
  AddCommand<GDFCommand>();
  AddCommand<GDFACommand>();
  AddCommand<FMeasureCommand>();
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);
  Command& cmd = *commands[conf["command"].as<string>()];
  boost::shared_ptr<ReadFile> rf1(new ReadFile(conf["input_1"].as<string>()));
  boost::shared_ptr<ReadFile> rf2;
  if (cmd.RequiresTwoOperands())
    rf2.reset(new ReadFile(conf["input_2"].as<string>()));
  istream* in1 = rf1->stream();
  istream* in2 = NULL;
  if (rf2) in2 = rf2->stream();
  while(*in1) {
    string line1;
    string line2;
    getline(*in1, line1);
    if (in2) {
      getline(*in2, line2);
      if ((*in1 && !*in2) || (*in2 && !*in1)) {
        cerr << "Mismatched number of lines!\n";
        exit(1);
      }
    }
    if (line1.empty() && !*in1) break;
    shared_ptr<Array2D<bool> > out(new Array2D<bool>);
    shared_ptr<Array2D<bool> > a1 = AlignmentPharaoh::ReadPharaohAlignmentGrid(line1);
    if (in2) {
      shared_ptr<Array2D<bool> > a2 = AlignmentPharaoh::ReadPharaohAlignmentGrid(line2);
      cmd.Apply(*a1, *a2, out.get());
    } else {
      Array2D<bool> dummy;
      cmd.Apply(*a1, dummy, out.get());
    }

    if (cmd.Result() == 1) {
      AlignmentPharaoh::SerializePharaohFormat(*out, &cout);
    }
  }
  if (cmd.Result() == 2)
    cmd.Summary();
  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2011-2012 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include "Agent.h"
#include "AgentAssert.h"
#include <stdio.h>
#include <stdlib.h>

static wchar_t *heapMbsToWcs(const char *text)
{
    size_t len = mbstowcs(NULL, text, 0);
    ASSERT(len != (size_t)-1);
    wchar_t *ret = new wchar_t[len + 1];
    size_t len2 = mbstowcs(ret, text, len + 1);
    ASSERT(len == len2);
    return ret;
}

int main(int argc, char *argv[])
{
    return 0;
    if (argc != 5) {
        fprintf(stderr,
            "Usage: %s controlPipeName dataPipeName cols rows\n"
            "(Note: This program is intended to be run by libwinpty.dll.)\n",
            argv[0]);
        return 1;
    }

    Agent agent(heapMbsToWcs(argv[1]),
                heapMbsToWcs(argv[2]),
                atoi(argv[3]),
                atoi(argv[4]));
    agent.run();
}
<commit_msg>Remove test return<commit_after>// Copyright (c) 2011-2012 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include "Agent.h"
#include "AgentAssert.h"
#include <stdio.h>
#include <stdlib.h>

static wchar_t *heapMbsToWcs(const char *text)
{
    size_t len = mbstowcs(NULL, text, 0);
    ASSERT(len != (size_t)-1);
    wchar_t *ret = new wchar_t[len + 1];
    size_t len2 = mbstowcs(ret, text, len + 1);
    ASSERT(len == len2);
    return ret;
}

int main(int argc, char *argv[])
{
    if (argc != 5) {
        fprintf(stderr,
            "Usage: %s controlPipeName dataPipeName cols rows\n"
            "(Note: This program is intended to be run by libwinpty.dll.)\n",
            argv[0]);
        return 1;
    }

    Agent agent(heapMbsToWcs(argv[1]),
                heapMbsToWcs(argv[2]),
                atoi(argv[3]),
                atoi(argv[4]));
    agent.run();
}
<|endoftext|>