Option getAction(void) {
	// print the list of options
	printOptions();
	Option answer = INVALID;

	while (answer == INVALID) {
		// read the user command
		char input[32];
		fgets(input, 31, stdin);
		input[strlen(input)-1] = '\0';

		// update answer
		if (strcmp(input, "quit") == 0)			answer = QUIT;
		else if (strcmp(input, "addlist") == 0)		answer = ADD_LIST;
		else if (strcmp(input, "addsong") == 0)		answer = ADD_SONG;
		else if (strcmp(input, "show") == 0)		answer = PRINT_LIST;
		else if (strcmp(input, "size") == 0)		answer = LIST_SIZE;
		else if (strcmp(input, "stats") == 0)		answer = STATS;
		else if (strcmp(input, "addorder") == 0)	answer = ADD_LIST_ORDERED;
		else if (strcmp(input, "songorder") == 0)	answer = ADD_SONG_ORDERED;
		else if (strcmp(input, "dumplist") == 0)	answer = REMOVE_LIST;
		else if (strcmp(input, "dumpsong") == 0)	answer = REMOVE_SONG;
		else if (strcmp(input, "help") == 0)		answer = HELP;
		else {
			if (strlen(input)>0) {
				printf("\nINVALID OPTION\n");
				printOptions();
			}
		}
	}
	return answer;
}
int main(int argc, char **argv) {
    std::cout << "Mask #1: ";
    printOptions(OPTION_1 | OPTION_4);
    std::cout << "Mask #2: ";
    printOptions(OPTION_2 | OPTION_3);
    return 0;
}
Beispiel #3
0
HashObjectPtr removeThings()
{
	char * input = (char *)malloc(sizeof(char)*MAX_INPUT_LENGTH);
	printf("Please enter the word you wish to remove\n\n");
	fgets(input, MAX_INPUT_LENGTH, stdin);

	int j = 0;
	for (; j < strlen(input); j++)
	{
		if (input[j] == '\n')
		{
			input[j] = '\0';
			break;
		}
	}
	HashObjectPtr hobj = HashRemove(table, input);
	if (hobj == NULL)
	{
		printf("That word was not found, returning to main menu\n\n");
		printOptions();
	}
	else
	{
		printf("That word has been successfully removed\n");
		printf("The word and frequency were %s\n", toString(hobj));
		printf("Please do something else\n\n");
		printOptions();
	}
	free(input);
	return hobj;
}
Beispiel #4
0
void Logger::saveBeginInfo(){
	
	FILE* file = NULL;
	
    fopen_s(&file,m_CurrentLogFile.c_str(),"r+");

	endOffile(file);

	fprintf_s(file,"# Game ID \n");

	fprintf_s(file,"%d \n",m_game_id);	

	fprintf_s(file,"# Begin play Date and Time \n");

	struct tm Today;
	time_t now;

	time(&now);

	localtime_s(&Today, &now);

	saveTimeDate(file,&Today);	

	printOptions(file);

	fprintf_s(file, "### Game start ### \n ");

	fclose(file);

	m_game_id++;
}
Beispiel #5
0
int main(int argc, char **argv) {

		parseCommandLine(argc, argv);
		printOptions();
		start(&options);

		return 0;
}
options* initProgram(int argc, char** argv)
{
    // init, get options and init SMC
    if(setHandler(sigintHandler, SIGINT))
        FILE_ERR("Can't set sigint handler");
    options* opt = getOptions(argc, argv);
    CHECK_ERROR_WHEN_NULL( opt );
    smcInit();
    printOptions(opt);
    return opt;
}
/**
 * Displays the Main Menu and related options
 */
void Ohmbrewer::MenuMain::displayMenu() {

    _screen->resetTextSize();
    _screen->resetTextColor();

    // Print the section title
    _screen->print("======= MENU =======");
    _screen->printMargin(2);
    _screen->print(" ---- Main Menu --- ");
    _screen->printMargin(2);

    printOptions();

}
void CombatCommand::execute(Game& game)
{
	if (game.getHero().getLocation().hasAliveEnemies())
	{
		game.setInCombat();

		while (true)
		{
			printOptions(game);
			string input{ IOHelper::read() };

			if (IOHelper::isInputGameReady(input, game))
			{
				int i{ IOHelper::parseToInt(input) };

				if (i > 0 && i <= static_cast<int>(game.getHero().getLocation().getAliveEnemies().size()))
				{
					if (game.getHero().getLocation().isDark()) {
						IOHelper::writeLine("It's too dark to attack!");
					}
					else {
						int damage{ game.getHero().attack(*game.getHero().getLocation().getAliveEnemies()[i - 1]) };
						IOHelper::writeLine("You did " + to_string(damage) + " damage!");
					}
					return;
				}
				else if (i == game.getHero().getLocation().getAliveEnemies().size() + 1)
				{
					IOHelper::clearScreen();
					// Cancel operation called
					return;
				}
				else
				{
					IOHelper::writeInvalidCommand();
				}
			}
		}
	}
	else if (game.getHero().getLocation().hasEnemies())
	{
		IOHelper::writeLine("There are no alive enemies to attack.");
		IOHelper::writeLine("");
	}
	else
	{
		IOHelper::writeLine("There are no enemies to attack.");
		IOHelper::writeLine("");
	}
}
void ExprSMTLIBPrinter::generateOutput() {
  if (p == NULL || query == NULL || o == NULL) {
    std::cerr << "ExprSMTLIBPrinter::generateOutput() Can't print SMTLIBv2. "
                 "Output or query bad!" << std::endl;
    return;
  }

  if (humanReadable)
    printNotice();
  printOptions();
  printSetLogic();
  printArrayDeclarations();
  printConstraints();
  printQuery();
  printAction();
  printExit();
}
Beispiel #10
0
void ExprSMTLIBLetPrinter::generateOutput() {
  if (p == NULL || query == NULL || o == NULL) {
    std::cerr << "Can't print SMTLIBv2. Output or query bad!" << std::endl;
    return;
  }

  generateBindings();

  if (isHumanReadable())
    printNotice();
  printOptions();
  printSetLogic();
  printArrayDeclarations();
  printLetExpression();
  printAction();
  printExit();
}
Beispiel #11
0
void Opt::process(int argc, char* argv[]) {
	for(int i = 0; i < argc; i++) {
		argumentsInString.push_back(std::string(argv[i]));
	}

	std::map<std::string, Option*>::iterator iter;
	// TODO: map
	for(iter = this->argumentMap.begin(); iter != this->argumentMap.end(); iter++) {
		std::vector<std::string>::iterator argIter = std::find(argumentsInString.begin(), argumentsInString.end(), iter->first);
		if(argIter != argumentsInString.end()) {
			try{
				processValueByType(iter, argIter);
			} catch(StandardError* exception) {
				std::cerr << exception->message << std::endl;
				printOptions();
			}
		}
	}
}
Beispiel #12
0
int main() {

    int input;

    do {
        printOptions();
        scanf("%d", &input);
        switch(input) {
        case 1:
            inputGrade();
        case 2:
            printGrade();
        case 3:
            break;
        }

    } while(input != 3);

    return 0;


}
int main(int argc,char *argv[]) {
    int c;
    std::string outFileName = "";
    std::vector<std::string> years;
    std::string inYears = "";
    std::string srsValue = "free";
    /*____________________________Parse Command Line___________________________*/
    while ((c = getopt(argc, argv, "y:o:s:h")) != -1) {
        switch (c) {
            case 'y':
                inYears.assign(optarg);
                boost::split(years, inYears, boost::is_any_of(","));
                break;
            case 'o':
                outFileName.assign(optarg);
                break;
            case 's':
                srsValue.assign(optarg);
                break;
            case 'h':
                printOptions();
                return 0;
            default:
                // not an option
                break;
        }
    }

    //ensure years and outYear are set
    if (years.empty()) {
        std::cout << "You must set the input years using the -y switch and a comma-separated list of years" <<
        std::endl;
        printOptions();
        return 0;
    }
    if (outFileName == ""){
        std::cout << "You must set the output file name using the -o switch" << std::endl;
        printOptions();
        return 0;
    }

    char *homePath, path[256];
    homePath = getenv("HOME");

    //read in the necessary constants
    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_standard_deviations.d", homePath);
    ConstantStandardDeviations *stdDevs = ConstantStandardDeviations::Instance();
    stdDevs->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/season_info.d", homePath);
    ConstantSeasonInfo *seasonInfo = ConstantSeasonInfo::Instance();
    seasonInfo->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_functions.d", homePath);
    ConstantWAverageFunctions *functions = ConstantWAverageFunctions::Instance();
    functions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/team_neutral_ratios.d", homePath);
    ConstantTeamNeutralRatios *ratios = ConstantTeamNeutralRatios::Instance();
    ratios->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/srs_additions.d", homePath);
    ConstantSRSadditions *additions = ConstantSRSadditions::Instance();
    additions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/game_function_weights.%s.d", homePath,srsValue.c_str());
    ConstantGameFunction *gameFunction = ConstantGameFunction::Instance();
    gameFunction->initialize(path);

    //read in the game and waverage info
    for (std::string &year : years) {
        sprintf(path, "%s/cpp/NCAA_C/teams/%s/", homePath, year.c_str());
        std::cout << "Reading in games and waverages for " << year << std::endl;
        readTeamsFromDir(path);
        readTeamsFromDir(path, "waverages");
    }

    std::unordered_map<std::string, Team *> teams = Team::getTeams();
    std::unordered_map<std::string, TeamGame *> games;
    Team *opp;
    TeamWAverage *wa1, *wa2;

    TFile file(("rootFiles/"+outFileName).c_str(),"RECREATE");

    std::unordered_map<int, TH1F*> hists_gameScore_wins, hists_gameScore_losses;
    for (int year = 2007; year <= 2016; year++) {
        sprintf(path,"hist_gameScore_wins_%d",year);
        hists_gameScore_wins.emplace(year, new TH1F(path,"",200,-3,3));
        sprintf(path,"hist_gameScore_losses_%d",year);
        hists_gameScore_losses.emplace(year, new TH1F(path,"",200,-3,3));
    }

    for (auto &team : teams) {
        games = team.second->getGamesByDate();
        for (auto &game : games) {
            if (team.first < game.second->getOpp()) continue; //look at each game only once
            opp = Team::findTeam(game.second->getOpp());
            if (!opp) continue;
            if (game.second->getDate() >= seasonInfo->get(team.second->getYear(), "tournament start")) continue;
            if (game.second->getDate().month().as_number() == 11) continue;

            bool win = game.second->getWin() == 1;
            int gameYear = team.second->getYear();

            wa1 = team.second->WAverageOnDate(game.second->getDate());
            wa2 = opp->WAverageOnDate(game.second->getDate());

            std::string loc = game.second->getLoc();
            std::string oppLoc = game.second->getOppLoc();

            std::unordered_map<int, double> gameScoreByYear;

            switch (gameYear){
                case 2005:
                    for (int y = 2007; y <= 2010; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2006:
                    for (int y = 2007; y <= 2011; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2007:
                    for (int y = 2008; y <= 2012; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2008:
                    for (int y = 2009; y <= 2013; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2009:
                    for (int y = 2010; y <= 2014; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2010:
                    for (int y = 2011; y <= 2015; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2011:
                    for (int y = 2012; y <= 2016; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2012:
                    for (int y = 2013; y <= 2016; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2013:
                    for (int y = 2014; y <= 2016; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2014:
                    for (int y = 2015; y <= 2016; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
                case 2015:
                    for (int y = 2016; y <= 2016; y++)
                        gameScoreByYear.emplace(y, gameFunction->predictGame(wa1,wa2,y,loc,oppLoc));
                    break;
            }
            if (win){
                for (int y = 2007; y <= 2016; y++){
                    if (gameScoreByYear.find(y) == gameScoreByYear.end()) continue;
                    hists_gameScore_wins[y]->Fill(gameScoreByYear[y]);
                    hists_gameScore_losses[y]->Fill(-gameScoreByYear[y]);
                }
            }
            else{
                for (int y = 2007; y <= 2016; y++){
                    if (gameScoreByYear.find(y) == gameScoreByYear.end()) continue;
                    hists_gameScore_wins[y]->Fill(-gameScoreByYear[y]);
                    hists_gameScore_losses[y]->Fill(gameScoreByYear[y]);
                }
            }
        }
    }

    TF1 *fnWins = new TF1("fnWins","gaus");
    TF1 *fnLosses = new TF1("fnLosses","gaus");

    std::unordered_map<int, TH1F*> hists_probs;
    std::unordered_map<int, TH1F*> hists_probs_err;

    for (int y = 2007; y <= 2016; y++){
        if (hists_gameScore_wins[y]->Integral() == 0) continue;
        hists_gameScore_wins[y]->Fit(fnWins,"q");
        hists_gameScore_losses[y]->Fit(fnLosses,"q");

        sprintf(path,"probs_by_year_%d",y);
        hists_probs.emplace(y, new TH1F(path,"",1600,-3,3));
        sprintf(path,"probs_err_by_year_%d",y);
        hists_probs_err.emplace(y, new TH1F(path,"",1600,-3,3));

        for (int i = 1; i < 1600; i++){
            double w = fnWins->Eval(-3+i*6/1600.0);
            double l = fnLosses->Eval(-3+i*6/1600.0);
            double p = 0;
            double e = 0;
            if (w != 0 && l != 0){
                p = w / (double)(w+l);
                e = sqrt(p*(1-p) / (w+l));
            }
            else if (w != 0 && l == 0){
                p = 1;
                e = 0.01;
            }
            else if (w == 0){
                p = 0;
                e = 0.01;
            }

            hists_probs[y]->SetBinContent(i,p);
            hists_probs_err[y]->SetBinContent(i,e);
        }
    }

    file.Write();
    file.Close();

    return 0;
}
Beispiel #14
0
int main(int argc, char **argv)
{	
	HashObjectPtr p;
	char * line = (char *)malloc(sizeof(char)*MAX_INPUT_LENGTH);

	printOptions();
	while (fgets(line, MAX_INPUT_LENGTH, stdin)!=NULL)
	{
		switch (line[0])
		{
			case 'c':
			if (table == NULL)
			{
				if ((table = createNewHashTable()) == NULL)
				{
					printOptions();
					break;
				}
				else
				{
					printf("\n\nSuccess. What would you like to do now?\n\n");
					printOptions();
				}
					
			}
			else 
			{
				FreeHashTable(table);
				if ((table = createNewHashTable()) == NULL)
				{
					printOptions();
					break;
				}
				else
				{
					printf("\n\nSuccess. What would you like to do now?\n\n");
					printOptions();
				}
			}
			break;
			case 'l':
				if (table == NULL)
				{
					printf("You need to first instantiate a hashtable, use the 'c' option\n\n");
					break;
				}
				else 
				{
					if ((p = wordSearch(table)) != NULL)
					{
						printf("\n\nSuccess. What would you like to do now?\n\n");
						printOptions();
					}
					else 
					{
						printOptions();
					}
				}

				break;
			case 'f':
				if (table == NULL)
				{
					printf("You need to first instantiate a hashtable, use the 'c' option\n\n");
					break;
				}
				if (uploadAndRunFile(table) != NULL)
				{
					printf("\n\nSuccess. What would you like to do now?\n\n");
					printOptions();
				}
				
				break;
			case 'p':
				if (table == NULL)
				{
					printf("You need to first instantiate a hashtable, use the 'c' option\n\n");
					break;
				}
				printf("\n\nPrinting Hash Table\n\n");
				PrintHash(table);
				printf("\n\nSuccess. What would you like to do now?\n\n");
				printOptions();
				break;
			case 'r':
				if (table == NULL)
				{
					printf("You need to first instantiate a hashtable, use the 'c' option\n\n");
					break;
				}
				removeThings();
				break;
			case 'q':
				FreeHashTable(table);
				free(line);
				printf("\n\nGoodbye\n\n");
				return 0;
			case 's':
				if (table == NULL)
				{
					printf("You need to first instantiate a hashtable, use the 'c' option\n\n");
					break;
				}

				break;
			default:
				printf("%s\n", "That is an unrecognized entry, please try again\n\n");
				printOptions();
				break;
		}
	}
	free(line);
	return 0;
}
Beispiel #15
0
int main(int argc,char *argv[]) {
    int c;
    bool writeOutput = false;
    std::vector<std::string> years;
    std::string inYears = "";
    bool useHistogramsFile = false;
    std::string srsValue = "free";
    std::string outFileName = "";
    double sigmas = 3;
    int nbins = 33;
    std::string predictionDay = "";
    std::string endRangeDay = "";
    /*____________________________Parse Command Line___________________________*/
    while ((c = getopt(argc, argv, "y:HS:o:s:n:d:D:h")) != -1) {
        switch (c) {
            case 'y':
                inYears.assign(optarg);
                boost::split(years, inYears, boost::is_any_of(","));
                break;
            case 's':
                srsValue.assign(optarg);
                break;
            case 'H':
                useHistogramsFile = true;
                break;
            case 'o':
                outFileName = optarg;
                break;
            case 'S':
                sigmas = atof(optarg);
                break;
            case 'n':
                nbins = atoi(optarg);
                break;
            case 'd':
                predictionDay.assign(optarg);
                break;
            case 'D':
                endRangeDay.assign(optarg);
                break;
            case 'h':
                printOptions();
                return 0;
            default:
                // not an option
                break;
        }
    }

    //ensure years and outYear are set
    if (years.empty()) {
        std::cout << "You must set the input years using the -y switch and a comma-separated list of years" <<
        std::endl;
        printOptions();
        return 0;
    }

    boost::gregorian::date predictionDate;
    if (predictionDay != "")
        predictionDate = boost::gregorian::date(boost::gregorian::from_string(predictionDay));

    boost::gregorian::date endRangeDate;
    if (endRangeDay != ""){
        endRangeDate = boost::gregorian::date(boost::gregorian::from_string(endRangeDay));
        if (predictionDay == ""){
            std::cout << "If you enter an end date, you must also specify a start date" << std::endl;
            return 0;
        }
    }

    char *homePath, path[256];
    homePath = getenv("HOME");

    //read in the necessary constants
    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_standard_deviations.d", homePath);
    ConstantStandardDeviations *stdDevs = ConstantStandardDeviations::Instance();
    stdDevs->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/season_info.d", homePath);
    ConstantSeasonInfo *seasonInfo = ConstantSeasonInfo::Instance();
    seasonInfo->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_functions.d", homePath);
    ConstantWAverageFunctions *functions = ConstantWAverageFunctions::Instance();
    functions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/team_neutral_ratios.d", homePath);
    ConstantTeamNeutralRatios *ratios = ConstantTeamNeutralRatios::Instance();
    ratios->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/srs_additions.d", homePath);
    ConstantSRSadditions *additions = ConstantSRSadditions::Instance();
    additions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/game_function_weights.%s.d", homePath,srsValue.c_str());
    ConstantGameFunction *gameFunction = ConstantGameFunction::Instance();
    gameFunction->initialize(path);

    //read in the game and waverage info
    for (std::string &year : years) {
        sprintf(path, "%s/cpp/NCAA_C/teams/%s/", homePath, year.c_str());
        std::cout << "Reading in games and waverages for " << year << std::endl;
        readTeamsFromDir(path);
        readTeamsFromDir(path, "waverages");
    }

    TFile *histsFile;
    std::unordered_map<int, TH1F*> probs_by_year, probs_err_by_year;
    if (useHistogramsFile){
        sprintf(path, "%s/cpp/NCAA_C/rootFiles/gameFunctionHistograms.%s.root", homePath, srsValue.c_str());
        histsFile = new TFile(path);

        for (int y = 2007; y <= 2016; y++){
            sprintf(path, "probs_by_year_%d", y);
            probs_by_year.emplace(y, (TH1F*)gROOT->FindObject(path));
            sprintf(path, "probs_err_by_year_%d", y);
            probs_err_by_year.emplace(y, (TH1F*)gROOT->FindObject(path));
        }
    }

    std::unordered_map<std::string, Team *> teams = Team::getTeams();
    std::unordered_map<std::string, TeamGame *> games;
    Team *opp;
    TeamWAverage *wa1, *wa2;

    int gameScoreWins = 0, gameScoreTotal = 0;
    int gameScoreWinsSpread = 0, gameScoreTotalSpread = 0;
    int vegasWinsSpread = 0, vegasTotalSpread = 0;
    int adjGameScoreWins = 0, adjGameScoreTotal = 0;
    int unadjustedSrsWins = 0, unadjustedSrsTotal = 0;
    int srsWins = 0, srsTotal = 0;
    int srsWinsSpread = 0, srsTotalSpread = 0;

    int srsGameScoreWins = 0, srsGameScoreTotal = 0;
    int srsGameScoreWinsSpread = 0, srsGameScoreTotalSpread = 0;

    TFile *outFile;
    if (outFileName != "") {
        sprintf(path, "%s/cpp/NCAA_C/rootFiles/%s",homePath,outFileName.c_str());
        outFile = new TFile(path, "RECREATE");
    }

    TH1F *h_wins = new TH1F("h_wins","",nbins,0,1);
    TH1F *h_total = new TH1F("h_total","",nbins,0,1);
    TH2F *spread_vs_spread = new TH2F("spread_vs_spread","",80,-20,20,80,-20,20);
    TH2F *myspread_vs_pct = new TH2F("myspread_vs_pct","",100,0,1,80,-20,20);
    TH2F *myPct_vs_VegasPct = new TH2F("myPct_vs_VegasPct","",nbins,0,1,nbins,0,1);

    for (auto &team : teams) {
        games = team.second->getGamesByDate();
        for (auto &game : games) {
            //look only at games within a certain range
            if (predictionDay != ""){
                if (endRangeDay == ""){
                    if (predictionDate != game.second->getDate()) continue;
                }
                else{
                    if (game.second->getDate() < predictionDate || game.second->getDate() > endRangeDate) continue;
                }
            }
            else{
                if (game.second->getDate() >= seasonInfo->get(team.second->getYear(), "tournament start")) continue;
                if (game.second->getDate().month().as_number() == 11) continue;
            }
            if (team.first < game.second->getOpp()) continue; //look at each game only once
            opp = Team::findTeam(game.second->getOpp());
            if (!opp) continue;

            TeamGame *oppgame = opp->GameOnDate(game.second->getDate(),team.second->getName());

            bool win = game.second->getWin() == 1;
            double spread = game.second->getSpread();
            double mySpread;

            wa1 = team.second->WAverageOnDate(game.second->getDate());
            wa2 = opp->WAverageOnDate(game.second->getDate());

            std::string loc = game.second->getLoc();
            std::string oppLoc = game.second->getOppLoc();

            double gameScore = gameFunction->predictGame(wa1,wa2,team.second->getYear(),loc,oppLoc);
            if (gameScore >= 0 && win) gameScoreWins++;
            if (gameScore < 0 && !win) gameScoreWins++;
            gameScoreTotal++;

            double gameScorePct = -1;
            double gameScorePct_err = -1;

            double unadjustedSrsVal = wa1->getSrs() - wa2->getSrs();
            if (win && unadjustedSrsVal >= 0) unadjustedSrsWins++;
            if (!win && unadjustedSrsVal < 0) unadjustedSrsWins++;
            unadjustedSrsTotal++;

            double srsVal = wa1->getSrs() - wa2->getSrs() + additions->get(team.second->getYear(),loc);
            if (win && srsVal >= 0) srsWins++;
            if (!win && srsVal < 0) srsWins++;
            srsTotal++;

            if (gameScore >= 0 && srsVal >= 0){
                if (win) srsGameScoreWins++;
                srsGameScoreTotal++;
            }
            if (gameScore < 0 && srsVal < 0){
                if (!win) srsGameScoreWins++;
                srsGameScoreTotal++;
            }

            if (useHistogramsFile){
                if (gameScore >= 3){
                    gameScorePct = 1;
                    gameScorePct_err = 1;
                }
                else if (gameScore <= -3){
                    gameScorePct = 0;
                    gameScorePct_err = 1;
                }
                else{
                    gameScorePct = probs_by_year[team.second->getYear()]->GetBinContent((gameScore+3)*1600/6.0);
                    gameScorePct_err = probs_err_by_year[team.second->getYear()]->GetBinContent((gameScore+3)*1600/6.0);
                }

                if (gameScorePct >= 0.5 && gameScorePct - sigmas*gameScorePct_err >= 0.5 && win) adjGameScoreWins++;
                if (gameScorePct < 0.5 && gameScorePct + sigmas*gameScorePct_err < 0.5 && !win) adjGameScoreWins++;
                if ((gameScorePct >= 0.5 && gameScorePct - sigmas*gameScorePct_err >= 0.5) ||
                    (gameScorePct < 0.5 && gameScorePct + sigmas*gameScorePct_err < 0.5)) adjGameScoreTotal++;

                if (win) h_wins->Fill(gameScorePct);
                h_total->Fill(gameScorePct);

                if (spread != 0 && spread == -1*oppgame->getSpread()){
                    mySpread = pctToSpread(gameScorePct);
                    myspread_vs_pct->Fill(gameScorePct,mySpread);
                    spread_vs_spread->Fill(spread, mySpread);
                    myPct_vs_VegasPct->Fill(spreadToPct(spread),gameScorePct);
                }
            }

            if (spread != -1*oppgame->getSpread()) continue; //if the spreads are somehow messed up

            if (spread != 0){
                gameScoreTotalSpread++;
                if (gameScore > 0 && win) gameScoreWinsSpread++;
                if (gameScore < 0 && !win) gameScoreWinsSpread++;

                srsTotalSpread++;
                if (win && srsVal >= 0) srsWinsSpread++;
                if (!win && srsVal < 0) srsWinsSpread++;

                if (gameScore >= 0 && srsVal >= 0){
                    if (win) srsGameScoreWinsSpread++;
                    srsGameScoreTotalSpread++;
                }
                if (gameScore < 0 && srsVal < 0){
                    if (!win) srsGameScoreWinsSpread++;
                    srsGameScoreTotalSpread++;
                }

                vegasTotalSpread++;
                if (spread < 0 && win) vegasWinsSpread++;
                if (spread > 0 && !win) vegasWinsSpread++;
            }
        }
    }

    std::cout << "All Games" << std::endl;
    std::cout << "gameScore:\t\t" << gameScoreWins << " / " << gameScoreTotal << " = " <<
    doubleFormatter(gameScoreWins / (double) gameScoreTotal, 3) << std::endl;

    if (useHistogramsFile) {
        std::cout << "Games above sigma:\t" << adjGameScoreWins << " / " << adjGameScoreTotal << " = " <<
        doubleFormatter(adjGameScoreWins / (double) adjGameScoreTotal, 3) << std::endl;
    }

    std::cout << "Unadjusted SRS:\t\t" << unadjustedSrsWins << " / " << unadjustedSrsTotal << " = " <<
    doubleFormatter(unadjustedSrsWins / (double) unadjustedSrsTotal, 3) << std::endl;

    std::cout << "Adjusted SRS:\t\t" << srsWins << " / " << srsTotal << " = " <<
    doubleFormatter(srsWins / (double) srsTotal, 3) << std::endl;

    std::cout << "SRS, GameScore agree :\t" << srsGameScoreWins << " / " << srsGameScoreTotal << " = " <<
    doubleFormatter(srsGameScoreWins / (double) srsGameScoreTotal, 3) << std::endl;

    std::cout << std::endl;

    std::cout << "Games with a spread" << std::endl;
    std::cout << "Vegas:\t\t\t" << vegasWinsSpread << " / " << vegasTotalSpread << " = " <<
    doubleFormatter(vegasWinsSpread / (double) vegasTotalSpread,3) << std::endl;

    std::cout << "gameScore:\t\t" << gameScoreWinsSpread << " / " << gameScoreTotalSpread << " = " <<
    doubleFormatter(gameScoreWinsSpread / (double) gameScoreTotalSpread, 3) << std::endl;

    std::cout << "SRS:\t\t\t" << srsWinsSpread << " / " << srsTotalSpread << " = " <<
    doubleFormatter(srsWinsSpread / (double) srsTotalSpread, 3) << std::endl;

    std::cout << "SRS, GameScore agree :\t" << srsGameScoreWinsSpread << " / " << srsGameScoreTotalSpread << " = " <<
    doubleFormatter(srsGameScoreWinsSpread / (double) srsGameScoreTotalSpread, 3) << std::endl;

    if (outFileName != "") {
        outFile->Write();
        outFile->Close();
    }

    return 0;
}
Beispiel #16
0
FILE* uploadAndRunFile()
{
	FILE *fp;
	char * input = (char*)malloc(sizeof(char)*MAX_INPUT_LENGTH);
	char * line = (char*)malloc(sizeof(char)*MAX_INPUT_LENGTH);
	char * token;
	HashObjectPtr extraJob;
	char delims[] =  ",.;:\"&!? -_\n\t\r@()#$%^*+={}[]|<>/~`";

	printf("%s\n", "Please enter the path to the file\n\n");
	fgets(input, MAX_INPUT_LENGTH, stdin);

	int j = 0;
	for (; j < strlen(input); j++)
	{
		if (input[j] == '\n')
		{
			input[j] = '\0';
			break;
		}
	}
	fp = fopen(input, "r+");

	if (fp != NULL)
	{
		while(!feof(fp))
		{
			fgets(line, MAX_INPUT_LENGTH, fp);
			if (strtok(line, delims) != NULL) 
			{
				token = strtok(line, delims);
				extraJob = createHashObject(token);
				HashInsert(table, extraJob);
				while (token != NULL) 
				{
				token = strtok(NULL, delims);
					if (token != NULL) 
					{
						token = strtok(NULL, delims);
						if (table->maxChainReached)
						{
							HashTablePtr oldTable = table;
							table = resizeHashTable(table);
							FreeHashTable(oldTable);
						}

							HashObjectPtr job = createHashObject(token);
							HashInsert(table, job);
					}


				}
			}
		}
		fclose(fp);
		free(input);
		free(line);
		return fp;
	}
	else
	{
		printf("%s\n", "That path was invalid, please try again\n\n");
		printOptions();
		free(input);
		free(line);
		return NULL;
	}

}
Beispiel #17
0
int main(int argc, char* argv[]) {

	struct myoptions Opt = initOptions();
	static struct option longOptions[] = {
      {"uppertriangular", no_argument, &Opt.uppertriangular, 1},
      {"bidirectional", no_argument, &Opt.bidirectional, 1},
      {"selfloops", required_argument, 0, 's'},
      {"duplicatededges", required_argument, 0, 'd'},
      {"inputformat", required_argument, 0, 'i'},
      {"outputformat", required_argument, 0, 'o'},
      {"inputheader", required_argument, 0, 'n'},
      {"outputheader", required_argument, 0, 'u'},
      {"inputedgeweights", required_argument, 0, 'e'},
      {"outputedgeweights", required_argument, 0, 'w'},
      {"edgeweighttype", required_argument, 0, 't'},
      {"r", required_argument, 0, 'r'},
      {"nvertices", required_argument, 0, 'v'},
      {"split", required_argument, 0, 'p'},
      {"help", no_argument, 0, 'h'}
    };

  while (1) {
    int optionIndex = 0;
    int currentOption = getopt_long(argc, (char *const*)argv, "h:s:d:i:o:n:u:e:w:t:v:r:p", longOptions, &optionIndex);
    if (currentOption == -1) {
      break;
    }
    int method = 3;
    switch (currentOption) {
    case 0:
      break;
    case 'h':
      printHelp(argv[0]);
      return(0);
    case 's':
      sscanf(optarg, "%i", &Opt.selfloops);
      break;
    case 'd':
      sscanf(optarg, "%i", &Opt.duplicatededges);
      break;
    case 'i':
      sscanf(optarg, "%i", &Opt.inputformat);
      break;
    case 'o':
      sscanf(optarg, "%i", &Opt.outputformat);
      break;
    case 'n':
      sscanf(optarg, "%i", &Opt.inputheader);
      break;
    case 'u':
      sscanf(optarg, "%i", &Opt.outputheader);
      break;
    case 'e':
      sscanf(optarg, "%i", &Opt.inputedgeweights);
      break;
    case 'w':
      sscanf(optarg, "%i", &Opt.outputedgeweights);
      break;
    case 't':
      sscanf(optarg, "%i", &Opt.edgeweighttype);
      break;
    case 'v':
      sscanf(optarg, "%i", &Opt.nvertices);
      break;
    case 'r':
      sscanf(optarg, "%i", &Opt.random_range);
      break;
    case 'p':
      sscanf(optarg, "%i", &Opt.nsplits);
      break;

    case '?':
      break;
    default:
      abort();
      break;
    }
  }

  if (optind != argc - 2) {
    printHelp(argv[0]);
    return(0);
	}

	int check = validateOptions(Opt);
	assert(check != 0);

  printOptions(Opt);

  const char* ifilename = argv[optind];
  const char* ofilename = argv[optind+1];

  switch(Opt.edgeweighttype)
  {
    case 0:
      process_graph<unsigned int>(ifilename, ofilename, Opt);
      break;
    case 1:
      process_graph<double>(ifilename, ofilename, Opt);
      break;
    default:
      printf("Invalid edge type: %d\n", Opt.edgeweighttype);
      exit(-1);
      break;
  }

  return 0;
}
Beispiel #18
0
int main (int argc, char *argv[])
{

  int dnsServerPort = SERVER_PORT;
  strcpy(hostFileName, HOSTS_FILE);

  int option = -1;
  int optionIndex = 0;

  //Pointers for the objects
  DNSDataBaseReader *dnsDBR;
  DNSResolver *dnsResolver;
  DNSPacketizator *dnsPacketizator;
  DNSServerSocket *dnsServerSocket;

  //Process the command options...
  while ((option = getopt_long (argc, argv, optString, longOptions, &optionIndex)) != -1)
  {
    switch (option)
    {
      case 'f':
        if (strlen(optarg) > 100)
        {
          printf("The file name %s is too long, takin the default value \'%s\'\n", optarg, hostFileName);
        }
        else
        {
          strcpy(hostFileName, optarg);
        }
        break;

      case 'p':
        //In god we trust!
        dnsServerPort = atoi(optarg);
        break;

     case 'h':
        printOptions();
        exit(-1);
    }
  }

  //Creating the objects
  cout << "Creating data base reader object...   " ;
  try 
  {
    dnsDBR = new DNSDataBaseReader (hostFileName);
  }
  catch (FileNotFoundException)
  {
    cout << "Fatal error: couldn't open file " << hostFileName << endl;
    cout << "Exit!" << endl; 
    exit(-1);
  }
  cout << "OK!" << endl;

  cout << "Creating resolver object...   " ;
  dnsResolver = new DNSResolver(dnsDBR);
  cout << "OK!" << endl;

  cout << "Creating packetizator object...   " ;
  dnsPacketizator = new DNSPacketizator(dnsResolver);
  cout << "OK!" << endl;

  cout << "Creating listening socket...   " ;
  //Create the listening UDP socket
  try
  {
    dnsServerSocket = new DNSServerSocket(dnsServerPort, dnsPacketizator);
  }
  catch (SocketException)
  {   
    cout << "Fatal error: couldn't listen on port " << dnsServerPort << endl;
    cout << "Do you have rights for doing it?" << endl; 
    cout << "Exit!" << endl; 
    exit(-1);
  }
  cout << "OK!" << endl;

   cout << "Listening for incoming petitions." << endl,
  //Wait for clients & process them  
  dnsServerSocket->listenSocket();

}
Beispiel #19
0
int main(int argc, char *argv[]) {
	if (argc < 2) {
		std::cerr << "USAGE: ./aixi agent.conf [--option1=value1 --option2=value2 ...] " << std::endl;
		std::cerr << "The first argument should indicate the location of the configuration file. Further arguments can either be specified in the config file or passed as command line option. Command line options are used over options specified in the file." << std::endl;
		return -1;
	}
    // Initialize random seed
    srand(time(NULL));

	// Load configuration options
	options_t options;

	// Default configuration values
	options["ct-depth"] = "16";
	options["agent-horizon"] = "3";
	options["exploration"] = "0";     // do not explore
	options["explore-decay"] = "1.0"; // exploration rate does not decay
    options["mc-timelimit"] = "500"; //number of mc simulations per search
    options["terminate-age"] = "10000";
    options["log"]  = "log";
    options["load-ct"] = "";
    options["write-ct"] = "";
    options["intermediate-ct"] = "1";

	// Read configuration options
	std::ifstream conf(argv[1]);
	if (!conf.is_open()) {
		std::cerr << "ERROR: Could not open file '" << argv[1] << "' now exiting" << std::endl;
		return -1;
	}
	processOptions(conf, options);
	conf.close();

    //parse command line options (overwrites values of config files)
    parseCmdOptions(argc, argv, options);

	// Set up logging
	std::string log_file = options["log"];
	verboseLog.open((log_file + ".log").c_str());
	compactLog.open((log_file + ".csv").c_str());

	// Print header to compactLog
	compactLog << "cycle, observation, reward, action, explored, explore_rate, total reward, average reward" << std::endl;

	// Set up the environment
	Environment *env;
	std::string environment_name = options["environment"];
	if (environment_name == "coin-flip") {
		env = new CoinFlip(options);
		options["agent-actions"] = "2";
		options["observation-bits"] = "1";
		options["reward-bits"] = "1";
	}
	else if (environment_name == "tiger") {
		env = new Tiger(options);
		options["agent-actions"] = "3";
		options["observation-bits"] = "2";
		options["reward-bits"] = "7";
	}
	else if (environment_name == "biased-rock-paper-scissor") {
		env = new BiasedRockPaperScissor(options);
		options["agent-actions"] = "3";
		options["observation-bits"] = "2";
		options["reward-bits"] = "2";
	}
	else if (environment_name == "kuhn-poker") {
		env = new KuhnPoker(options);
		options["agent-actions"] = "2";
		options["observation-bits"] = "4";
		options["reward-bits"] = "3";
	}
	else if (environment_name == "pacman") {
        env = new Pacman(options);
		options["agent-actions"] = "4";
		options["observation-bits"] = "16";
		options["reward-bits"] = "8";
	}
	else {
		std::cerr << "ERROR: unknown environment '" << environment_name << "'" << std::endl;
		return -1;
	}

    printOptions(options);

	// Set up the agent
	Agent ai(options);

	// If specified, load a pretrained context tree.
    if(options["load-ct"] != ""){
        std::ifstream ct(options["load-ct"].c_str());

        if(ct.is_open()){
            ai.loadCT(ct);
        }
        else{
            std::cerr << "WARNING: specified context tree file could not be loaded.\n";
        }
        ct.close();
    }  

	// Run the main agent/environment interaction loop
	mainLoop(ai, *env, options);

	verboseLog.close();
	compactLog.close();

	return 0;
}
int main(int argc, char const *argv[])
{
	int rc = -1;
	int x=0;
	ManagedDevice client;


	char *configFilePath = "./device.cfg";

	rc = initialize_configfile(&deviceClient, configFilePath);
	if(rc != SUCCESS){
		printf("initialize failed and returned rc = %d.\n Quitting..", rc);
		scanf("%d",&x);
		return 0;
	}

	rc = connectiotf_dm(&client);
	if(rc != SUCCESS){
		printf("Connection; failed and returned rc = %d.\n Quitting..", rc);
		scanf("%d",&x);
		return 0;
	}

	setCommandHandler_dm(&client, myCallback);
	setManagedHandler_dm(&client,managedCallBack );
	subscribeCommands_dm(&client);
	populateMgmtConfig(&client);
	int exit = 0;
	char reqId[40];
	while (!exit){
		printOptions();
		int val;
		scanf("%d",&val);
		switch (val) {
			case 1:
				printf("\n publish manage ..\n");
				publishManageEvent(&client,4000,1,1, reqId);
				printf("\n Manage Event Exited: %s",reqId);
				break;
			case 2:
				printf("\n publish unmanaged..\n");
				publishUnManageEvent(&client, reqId);
				printf("\nunmanaged Request Exit : %s",reqId);
				break;
			case 3:
				printf("\n publish addErrorCode ..\n");
				addErrorCode(&client, 121 , reqId);
				printf("\n addErrorCode Request Exit : %s",reqId);
				break;
			case 4:
				printf("\n publish clearErrorCodes ..\n");
				clearErrorCodes(&client,  reqId);
				printf("\n clearErrorCodes Request Exit :");// %s",reqId);
				break;
			case 5:
				printf("\n publish addLog ..\n");
				addLog(&client, "test","",1, reqId);
				printf("\n addLog Request Exit : %s",reqId);
				break;
			case 6:
				printf("\n publish clearLogs ..\n");
				clearLogs(&client,reqId);
				printf("\n clearLogs Request Exit : %s",reqId);
				break;
			case 7:
				printf("\n publish updateLocation ..\n");
				time_t t = time(NULL);
				char updatedDateTime[50];//"2016-03-01T07:07:56.323Z"
				strftime(updatedDateTime, sizeof(updatedDateTime), "%Y-%m-%dT%TZ", localtime(&t));
				updateLocation(&client, 77.5667,12.9667, 0,updatedDateTime, 0, reqId) ;
				printf("updateLocation Request Exit : %s",reqId);
				break;
			case 8:
				printf("\n publish Event To WIoTP ..\n");
				publishEventToIot(&client);
				break;
			default:
				disconnect_dm(&client);
				printf("\n Quitting!!\n");
				exit = 1;
				break;
		}
	}

	return 0;
}
Beispiel #21
0
/*! This is the main function and creates and links all the different
    classes.  First it reads in all the parameters from the command
    prompt (<program name> -help)and uses these values to create the
    classes. After all the classes are linked, the mainLoop in the
    Player class is called. */
int main( int argc, char * argv[] )
{
#ifdef WIN32
  HANDLE         listen, sense;
#else
  pthread_t      listen, sense;
#endif
  ServerSettings ss;
  PlayerSettings cs;

  // define variables for command options and initialize with default values
  char     strTeamName[MAX_TEAM_NAME_LENGTH] = "UvA_Trilearn";
  int      iPort                             = 6002;
  int      iMinLogLevel                      = 0 ;
  int      iMaxLogLevel                      = 0;
  char     strHost[128]                      = "localhost";
  double   dVersion                          = 14;
  int      iMode                             = 0;
  char     strFormations[128]                = "formations.conf";
  int      iNr                               = 0;
  int      iReconnect                        = -1;
  bool     bInfo                             = false;
  bool     bSuppliedLogFile                  = false;
  ofstream os;

  // read in all the command options and change the associated variables
  // assume every two values supplied at prompt, form a duo
  char * str;
  for( int i = 1 ; i < argc ; i = i + 2  )
  {
    // help is only option that does not have to have an argument
    if( i + 1 >= argc && strncmp( argv[i], "-help", 3 ) != 0 )
    {
      cout << "Need argument for option: " << argv[i] << endl;
      exit( 0 );
    }
    // read a command option
    if( argv[i][0] == '-' && strlen( argv[i] ) > 1)
    {
      switch( argv[i][1] )
      {
        case 'h':                                   // host server or help
          if( strlen( argv [i]) > 2 && argv[i][2] == 'e' )
          {
            printOptions( );
            exit(0);
          }
          else
            strcpy( strHost, argv[i+1] );
          break;
        case 'f':                                   // formations file
          strcpy( strFormations, argv[i+1] );
          break;
        case 'c':                                   // clientconf file
          if( cs.readValues( argv[i+1], ":" ) == false )
            cerr << "Error in reading client file: " << argv[i+1] << endl;
          break;
        case 'i':                                   // info 1 0
          str   = &argv[i+1][0];
          bInfo = (Parse::parseFirstInt( &str ) == 1 ) ? true : false ;
          break;
        case 'l':                                   // loglevel int[..int]
          str = &argv[i+1][0];
          iMinLogLevel = Parse::parseFirstInt( &str );
          while( iMinLogLevel != 0 )
          {
            if( *str == '.' ) // '.' indicates range of levels
            {
              iMaxLogLevel = Parse::parseFirstInt( &str );
              if( iMaxLogLevel == 0 ) iMaxLogLevel = iMinLogLevel;
              Log.addLogRange( iMinLogLevel, iMaxLogLevel );
            }
            else
              Log.addLogLevel( iMinLogLevel );
            iMinLogLevel = Parse::parseFirstInt( &str );
          }
          break;
        case 'm':                                   // mode int
          str = &argv[i+1][0];
          iMode = Parse::parseFirstInt( &str );
          break;
        case 'o':                                   // output file log info
          os.open( argv[i+1] );
          bSuppliedLogFile = true;
          break;
        case 'p':                                   // port
          str = &argv[i+1][0];
          iPort = Parse::parseFirstInt( &str );
          break;
        case 's':                                   // serverconf file
          if( ss.readValues( argv[i+1], ":" ) == false )
            cerr << "Error in reading server file: " << argv[i+1] << endl;
          break;
        case 't':                                   // teamname name
          strcpy( strTeamName, argv[i+1] );
          break;
        case 'v':                                   // version version
          str = &argv[i+1][0];
          dVersion = Parse::parseFirstDouble( &str );
          break;
        default:
          cerr << "(main) Unknown command option: " << argv[i] << endl;
      }
    }
  }


  if( bInfo == true )
  cout << "team         : "  << strTeamName    << endl <<
          "port         : "  << iPort          << endl <<
          "host         : "  << strHost        << endl <<
          "version      : "  << dVersion       << endl <<
          "min loglevel : "  << iMinLogLevel   << endl <<
          "max loglevel : "  << iMaxLogLevel   << endl <<
          "mode         : "  << iMode          << endl <<
          "playernr     : "  << iNr            << endl <<
          "reconnect    : "  << iReconnect     << endl ;

  if( bSuppliedLogFile == true )
    Log.setOutputStream( os );                   // initialize logger
  else
    Log.setOutputStream( cout );
  Log.restartTimer( );
  Formations fs( strFormations, (FormationT)cs.getInitialFormation(), iNr );
                                               // read formations file
  WorldModel wm( &ss, &cs, &fs );              // create worldmodel
  Connection c( strHost, iPort, MAX_MSG );     // make connection with server
  ActHandler a( &c, &wm, &ss );                // link actHandler and WM
  SenseHandler s( &c, &wm, &ss, &cs );         // link senseHandler with wm
  bool isTrainer = (iPort == ss.getCoachPort()) ? true : false;
  BasicCoach bp( &a, &wm, &ss, strTeamName, dVersion, isTrainer );
                                               // link acthandler and WM

#ifdef WIN32
  DWORD id1;
  sense = CreateThread(NULL, 0, &sense_callback, &s, 0, &id1);
  if (sense == NULL)
  {
      cerr << "create thread error" << endl;
      return false;
  }
#else
  pthread_create( &sense, NULL, sense_callback  , &s); // start listening
#endif

  if( iMode > 0 && iMode < 9 )       // only listen to sdtdin when not playing
#ifdef WIN32
  {
    DWORD id2;
    listen = CreateThread(NULL, 0, &stdin_callback, &bp, 0, &id2);
    if ( listen == NULL)
    {
        cerr << "create thread error" << endl;
        return false;
    }
  }
#else
    pthread_create( &listen, NULL, stdin_callback, &bp);
#endif
  
  if( iMode == 0 )
    bp.mainLoopNormal();

  c.disconnect();
  
  os.close();
}
Beispiel #22
0
int main(int argc,char *argv[]) {
    int c;
    std::vector<std::string> years;
    std::string inYears = "";
    int numIterations = 1;
    std::string outFileName = "";
    bool writeOutput = false;
    int outYear = 0;

    /*____________________________Parse Command Line___________________________*/
    while ((c = getopt(argc, argv, "y:Y:i:o:h")) != -1) {
        switch (c) {
            case 'y':
                inYears.assign(optarg);
                boost::split(years, inYears, boost::is_any_of(","));
                break;
            case 'Y':
                outYear = atoi(optarg);
                break;
            case 'i':
                numIterations = atoi(optarg);
                break;
            case 'o':
                outFileName.assign(optarg);
                writeOutput = true;
                break;
            case 'h':
                printOptions();
                return 0;
            default:
                // not an option
                break;
        }
    }

    //ensure years and outYear are set
    if (years.empty()) {
        std::cout << "You must set the input years using the -y switch and a comma-separated list of years" <<
        std::endl;
        printOptions();
        return 0;
    }
    if (outYear == 0) {
        std::cout << "You must set the output year using the -Y switch" << std::endl;
        printOptions();
        return 0;
    }

    char *homePath, path[256];
    homePath = getenv("HOME");

    //read in the necessary constants
    sprintf(path, "%s/cpp/NCAA_C/constants/season_info.d", homePath);
    ConstantSeasonInfo *seasonInfo = ConstantSeasonInfo::Instance();
    seasonInfo->initialize(path);

    //read in the game and waverage info
    for (std::string &year : years) {
        sprintf(path, "%s/cpp/NCAA_C/teams/%s/", homePath, year.c_str());
        std::cout << "Reading in games and waverages for " << year << std::endl;
        readTeamsFromDir(path);
        readTeamsFromDir(path, "waverages");
    }

    std::unordered_map<std::string, Team*> teams = Team::getTeams();
    std::unordered_map<std::string, TeamGame*> games;
    Team *opp;
    TeamWAverage *wa1, *wa2;
    int totalGames = 0;

    std::cout << "Processing Games" << std::endl;
    for (auto &team : teams) {
        games = team.second->getGamesByDate();
        for (auto &game : games) {
            if (team.first < game.second->getOpp()) continue; //look at each game only once
            opp = Team::findTeam(game.second->getOpp());
            if (!opp) continue;
            if (game.second->getDate() >= seasonInfo->get(team.second->getYear(), "tournament start")) continue;
            if (game.second->getDate().month().as_number() == 11) continue;

            totalGames++;

            wa1 = team.second->WAverageOnDate(game.second->getDate());
            wa2 = opp->WAverageOnDate(game.second->getDate());

            int loc = 0;
            if (game.second->getLoc() == "home") loc = 1;
            else if (game.second->getLoc() == "away") loc = -1;

            win.push_back(game.second->getWin());
            location.push_back(loc);
            srs.push_back((wa1->getSrs() - wa2->getSrs()));
        }
    }

    std::cout << "Total number of games to analyze: " << totalGames << std::endl;

    std::vector<double> temp_ary, temp_ary2;
    std::vector<double> fcn_min;
    std::vector< std::vector<double>*> params_ary;

    //random number generator, using Mersenne Twister method
    //the 0 means we use a unique seed each time
    TRandom3 rand(0);

    for (int i = 0; i < numIterations; i++){
        temp_ary = run_fit(rand.Rndm()*40 - 20);//random number between -20 and 20

        double temp_fcn_min = temp_ary.back();
        double temp_fcn_min2;

        int num_times_through = 0;
        for (int k = 0; k < 100; k++){
            num_times_through++;
            temp_ary2 = run_fit(temp_ary[0]);
            temp_fcn_min2 = temp_ary2.back();
            if (temp_fcn_min2 == temp_fcn_min && temp_ary == temp_ary2) break;

            temp_ary = temp_ary2;
            temp_fcn_min = temp_fcn_min2;
        }

        fcn_min.push_back(temp_fcn_min);
        params_ary.push_back(new std::vector<double>());
        for (int ii = 0; ii < temp_ary.size(); ii++)
            params_ary.back()->push_back(temp_ary[ii]);

        int indexOfMin = indexOfVectorMin(fcn_min);
        std::cout << "  " << i << "\t" << doubleFormatter(fcn_min.back(), 4) << "\t" <<
        doubleFormatter(fcn_min[indexOfMin], 4) << "\t" << indexOfMin << "\r";
        fflush(stdout);
    }

    int indexOfMin = indexOfVectorMin(fcn_min);
    std::cout << indexOfMin << "\t" << fcn_min[indexOfMin] << "\t" <<
            params_ary[indexOfMin]->at(0) << std::endl;

    if (writeOutput) {
        sprintf(path, "%s/cpp/NCAA_C/constants/%s", homePath, outFileName.c_str());
        std::ofstream outFile(path, std::ios::app);
        outFile << outYear << "," << doubleFormatter(params_ary[indexOfMin]->at(0), 2) << "," <<
                doubleFormatter(params_ary[indexOfMin]->at(1), 4) << std::endl;
        outFile.close();
    }

    return 0;
}
Beispiel #23
0
int main(int argc,char *argv[]) {
    int c;
    bool writeOutput = false;
    std::string outFileName = "";
    std::vector<std::string> years;
    std::string inYears = "";
    int numIterations = 1;
    int outYear = 0;
    bool useSeededValues = false;
    std::string seededLocation = "";
    bool zeroSRS = false;
    /*____________________________Parse Command Line___________________________*/
    while ((c = getopt(argc, argv, "y:Y:o:i:S:zh")) != -1) {
        switch (c) {
            case 'y':
                inYears.assign(optarg);
                boost::split(years, inYears, boost::is_any_of(","));
                break;
            case 'Y':
                outYear = atoi(optarg);
                break;
            case 'o':
                outFileName.assign(optarg);
                writeOutput = true;
                break;
            case 'i':
                numIterations = atoi(optarg);
                break;
            case 'S':
                useSeededValues = true;
                seededLocation.assign(optarg);
                break;
            case 'z':
                zeroSRS = true;
                break;
            case 'h':
                printOptions();
                return 0;
            default:
                // not an option
                break;
        }
    }

    //ensure years and outYear are set
    if (years.empty()) {
        std::cout << "You must set the input years using the -y switch and a comma-separated list of years" <<
        std::endl;
        printOptions();
        return 0;
    }
    if (outYear == 0) {
        std::cout << "You must set the output year using the -Y switch" << std::endl;
        printOptions();
        return 0;
    }

    char *homePath, path[256];
    homePath = getenv("HOME");

    //read in the necessary constants
    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_standard_deviations.d", homePath);
    ConstantStandardDeviations *stdDevs = ConstantStandardDeviations::Instance();
    stdDevs->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/season_info.d", homePath);
    ConstantSeasonInfo *seasonInfo = ConstantSeasonInfo::Instance();
    seasonInfo->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_functions.d", homePath);
    ConstantWAverageFunctions *functions = ConstantWAverageFunctions::Instance();
    functions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/team_neutral_ratios.d", homePath);
    ConstantTeamNeutralRatios *ratios = ConstantTeamNeutralRatios::Instance();
    ratios->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/srs_additions.d", homePath);
    ConstantSRSadditions *additions = ConstantSRSadditions::Instance();
    additions->initialize(path);

    //read in the game and waverage info
    for (std::string &year : years) {
        sprintf(path, "%s/cpp/NCAA_C/teams/%s/", homePath, year.c_str());
        std::cout << "Reading in games and waverages for " << year << std::endl;
        readTeamsFromDir(path);
        readTeamsFromDir(path, "waverages");
    }

    std::unordered_map<std::string, Team*> teams = Team::getTeams();
    std::unordered_map<std::string, TeamGame*> games;
    Team *opp;
    TeamWAverage *wa1, *wa2;
    int totalGames = 0;

    for (auto &team : teams) {
        games = team.second->getGamesByDate();
        for (auto &game : games) {
            if (team.first < game.second->getOpp()) continue; //look at each game only once
            opp = Team::findTeam(game.second->getOpp());
            if (!opp) continue;
            if (game.second->getDate() >= seasonInfo->get(team.second->getYear(), "tournament start")) continue;
            if (game.second->getDate().month().as_number() == 11) continue;

            totalGames++;

            wa1 = team.second->WAverageOnDate(game.second->getDate());
            wa2 = opp->WAverageOnDate(game.second->getDate());

            std::string loc = game.second->getLoc();
            std::string oppLoc = game.second->getOppLoc();

            std::unordered_map<std::string, double> predictions1 = functions->predictStats(wa1, wa2, outYear);
            std::unordered_map<std::string, double> predictions2 = functions->predictStats(wa2, wa1, outYear);

            win.push_back(game.second->getWin());
            oor.push_back((predictions1["oor.p"] * wa1->getValue("oor.p") / ratios->get(outYear,loc,"oor.p") -
                           predictions2["oor.p"] * wa2->getValue("oor.p") / ratios->get(outYear,oppLoc,"oor.p")) /
                          stdDevs->get(outYear,"oor.p"));

            oefg.push_back((predictions1["oefg.p"] * wa1->getValue("oefg.p") / ratios->get(outYear,loc,"oefg.p") -
                            predictions2["oefg.p"] * wa2->getValue("oefg.p") / ratios->get(outYear,oppLoc,"oefg.p")) /
                           stdDevs->get(outYear,"oefg.p"));

            oftmr.push_back((predictions1["oftmr.p"] * wa1->getValue("oftmr.p") / ratios->get(outYear,loc,"oftmr.p") -
                             predictions2["oftmr.p"] * wa2->getValue("oftmr.p") / ratios->get(outYear,oppLoc,"oftmr.p")) /
                            stdDevs->get(outYear,"oftmr.p"));

            //This guy is reversed because turnovers are bad.
            oto.push_back((-predictions1["oto.p"] * wa1->getValue("oto.p") / ratios->get(outYear,loc,"oto.p") +
                           predictions2["oto.p"] * wa2->getValue("oto.p") / ratios->get(outYear,oppLoc,"oto.p")) /
                          stdDevs->get(outYear,"oto.p"));

            srs.push_back((wa1->getSrs() - wa2->getSrs()) / stdDevs->get(outYear,"srs")); //removed additions
        }
    }

    std::cout << "Total number of games to analyze: " << totalGames << std::endl;

    std::vector<double> temp_ary, temp_ary2;
    std::vector<double> fcn_mins;
    std::vector< std::vector<double>*> params_ary;

    if (!useSeededValues) {
        //random number generator, using Mersenne Twister method
        //the 0 means we use a unique seed each time
        TRandom3 rand(0);

        for (int i = 0; i < numIterations; i++) {
            double randoms[5];
            rand.RndmArray(5, randoms);

            if (zeroSRS)
                temp_ary = run_fit(randoms[0], randoms[1], randoms[2], randoms[3], 0);
            else
                temp_ary = run_fit(randoms[0], randoms[1], randoms[2], randoms[3], randoms[4]);

            double temp_fcn_min = temp_ary.back();
            double temp_fcn_min2;

            double temp_norm = 0;
            int num_times_through = 0;
            for (int k = 0; k < 100; k++) {
                num_times_through++;
                temp_ary2 = run_fit(temp_ary[0], temp_ary[1], temp_ary[2], temp_ary[3], temp_ary[4]);
                temp_fcn_min2 = temp_ary2.back();
                if (temp_fcn_min2 == temp_fcn_min && temp_ary == temp_ary2) break;

                temp_ary = temp_ary2;
                temp_fcn_min = temp_fcn_min2;
            }

            fcn_mins.push_back(temp_fcn_min);
            params_ary.push_back(new std::vector<double>());
            for (int ii = 0; ii < temp_ary.size(); ii++)
                params_ary.back()->push_back(temp_ary[ii]);

            int indexOfMin = indexOfVectorMin(fcn_mins);
            std::cout << "  " << i << "\t" << doubleFormatter(fcn_mins.back(), 4) << "\t" <<
            doubleFormatter(fcn_mins[indexOfMin], 4) << "\t" << indexOfMin << "\r";
            fflush(stdout);
//            std::cout << "  \t\t" << i << "\t" << doubleFormatter(fcn_mins.back(), 4) << "\t" <<
//                  doubleFormatter(fcn_mins[indexOfMin], 4) << "\t" << indexOfMin << std::endl;
//            temp_norm = 0;
//            for (int ii = 0; ii < 5; ii++)
//                temp_norm += fabs(temp_ary[ii]);
//            for (int ii = 0; ii < 5; ii++){
//                std::cout << "  " << ii << "\t" << doubleFormatter(temp_ary[ii],4) << std::endl;
//            }
        }
    }
    else{
        sprintf(path, "%s/cpp/NCAA_C/%s", homePath, seededLocation.c_str());
        ConstantGameFunction *gameFunction = ConstantGameFunction::Instance();
        gameFunction->initialize(path);

        std::vector<int> keys = gameFunction->getKeys();
        for (int &year : keys){
            std::vector<double> initialValuesVec = gameFunction->getWeights(year);

            temp_ary = run_fit(initialValuesVec[0],initialValuesVec[1],initialValuesVec[2],
                               initialValuesVec[3],initialValuesVec[4]);

            double temp_fcn_min = temp_ary.back();
            double temp_fcn_min2;

            double temp_norm = 0;
            int num_times_through = 0;
            for (int k = 0; k < 100; k++) {
                num_times_through++;
                temp_ary2 = run_fit(temp_ary[0], temp_ary[1], temp_ary[2], temp_ary[3], temp_ary[4]);
                temp_fcn_min2 = temp_ary2.back();
                if (temp_fcn_min2 == temp_fcn_min && temp_ary == temp_ary2) break;

                temp_ary = temp_ary2;
                temp_fcn_min = temp_fcn_min2;
            }

            fcn_mins.push_back(temp_fcn_min);
            params_ary.push_back(new std::vector<double>());
            for (int ii = 0; ii < temp_ary.size(); ii++)
                params_ary.back()->push_back(temp_ary[ii]);

            int indexOfMin = indexOfVectorMin(fcn_mins);
            std::cout << "  " << year << "\t" << doubleFormatter(fcn_mins.back(), 4) << "\t" <<
            doubleFormatter(fcn_mins[indexOfMin], 4) << "\t" << indexOfMin << std::endl;
        }
    }

    std::cout << "\n\n\nFinal Results";
    int indexOfMin = indexOfVectorMin(fcn_mins);
    double norm = 0;
    for (int i = 0; i < 5; i++)
        norm += fabs(params_ary[indexOfMin]->at(i));

    std::cout << "Minimum = " << doubleFormatter(fcn_mins[indexOfMin],4) << std::endl;
    for (int i = 0; i < 5; i++)
        std::cout << i << "\t" << doubleFormatter(params_ary[indexOfMin]->at(i) / norm, 4) << std::endl;

    if (writeOutput) {
        sprintf(path, "%s/cpp/NCAA_C/constants/%s", homePath, outFileName.c_str());
        std::ofstream outFile(path, std::ios::app);
        outFile << outYear;
        for (int i = 0; i < 5; i++)
            outFile << "," << doubleFormatter(params_ary[indexOfMin]->at(i) / norm, 4);
        outFile << "," << doubleFormatter(params_ary[indexOfMin]->at(5), 4);
        outFile << std::endl;
        outFile.close();
    }

    return 0;
}
Beispiel #24
0
int main(int argc,char *argv[]){
    int c;
    int year = 2015, numIterations = 100;
    bool verbose = false, writeOutput = false;
    bool startFromOriginalSRS = false;
    /*____________________________Parse Command Line___________________________*/
    while((c = getopt(argc,argv,"y:vn:oOh")) != -1){
        switch(c){
            case 'y':
                year = atoi(optarg);
                break;
            case 'n':
                numIterations = atoi(optarg);
                break;
            case 'v':
                verbose = true;
                break;
            case 'o':
                writeOutput = true;
                break;
            case 'O':
                startFromOriginalSRS = true;
                break;
            case 'h':
                printOptions();
                return 0;
            default:
                // not an option
                break;
        }
    }

    if (year == 0){
        std::cout << "you must set the year" << std::endl;
        printOptions();
        return 0;
    }

    if (numIterations == 0){
        std::cout << "you must set the number of iterations" << std::endl;
        printOptions();
        return 0;
    }

    char *homePath, path[256];
    homePath = getenv("HOME");

    sprintf(path, "%s/cpp/NCAA_C/constants/season_info.d", homePath);
    ConstantSeasonInfo *seasonInfo = ConstantSeasonInfo::Instance();
    seasonInfo->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/teams/%i/", homePath, year);
    std::cout << "Reading in " << year << std::endl;
    readTeamsFromDir(path);
    readTeamsFromDir(path,"waverages");

    typedef std::unordered_map<std::string, double> teamHashType;
    typedef std::unordered_map<std::string, teamHashType *> dateHashType;
    typedef std::unordered_map<int, dateHashType *> srsHashType;
    typedef std::unordered_map<std::string, Team *> allTeamsHashType;

    srsHashType srsHash;
    srsHash.emplace(0,new dateHashType());
    allTeamsHashType allTeamsHash = Team::getTeams();

    sprintf(path,"%d north carolina",year);
    Team *genericTeam = Team::findTeam(path);
    std::unordered_map<std::string, TeamWAverage*> genericWAveragesUnordered = genericTeam->getWAveragesByDate();
    std::map<std::string, TeamWAverage*> genericWAverages(genericWAveragesUnordered.begin(),
                                                          genericWAveragesUnordered.end());
    for (auto &genericWAverage : genericWAverages){
        boost::gregorian::date day(boost::gregorian::from_string(genericWAverage.first));
        std::string date = genericWAverage.first;
        srsHash[0]->emplace(genericWAverage.first,new teamHashType());
        for (auto &team : allTeamsHash){
            if (startFromOriginalSRS)
                srsHash[0]->at(genericWAverage.first)->emplace(team.first, team.second->WAverageOnDate(day)->getOrigSRS());
            else
                srsHash[0]->at(genericWAverage.first)->emplace(team.first, team.second->WAverageOnDate(day)->getSrs());
        }

    }

    std::vector<double> srsSOS;
    for (int i = 1; i < numIterations; i++){
        srsHash.emplace(i, new dateHashType());
        for (auto &genericWAverage : genericWAverages){
            boost::gregorian::date day(boost::gregorian::from_string(genericWAverage.first));
            std::string date = genericWAverage.first;
            srsHash[i]->emplace(date, new teamHashType());
            for (auto &team : allTeamsHash){
                srsSOS = calcSRS(srsHash[i-1]->at(date),team.first,day);
                srsHash[i]->at(date)->emplace(team.first,srsSOS[0]);
            }
        }

        if (verbose) {
            //this will show the srs for 3 different teams (a generally good team, a generally
            //mediocre team, and a generally bad team, on four different dates throughout the
            //season, the first date SRS is calculated (14 days after the season starts),
            //then 50 days into the season, 100 days into the season, the day the
            //tournament starts, and the day the tournament ends.
            char team1[256], team2[256], team3[256];
            sprintf(team1, "%i north carolina", year);
            sprintf(team2, "%i bradley", year);
            sprintf(team3, "%i grambling state", year);
            std::string date1 = std::to_string(year-1)+"-12-01";
            std::string date2 = std::to_string(year)+"-01-01";
            std::string date3 = std::to_string(year)+"-02-14";
            std::string date4 = boost::gregorian::to_iso_extended_string(seasonInfo->get(year, "tournament start"));
            std::string date5 = boost::gregorian::to_iso_extended_string(seasonInfo->get(year, "tournament end"));
            std::cout << i <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date1)->at(team1), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date1)->at(team2), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date1)->at(team3), 3) <<
            "\t\t" << doubleFormatter(srsHash[i]->at(date2)->at(team1), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date2)->at(team2), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date2)->at(team3), 3) <<
            "\t\t" << doubleFormatter(srsHash[i]->at(date3)->at(team1), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date3)->at(team2), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date3)->at(team3), 3) <<
            "\t\t" << doubleFormatter(srsHash[i]->at(date4)->at(team1), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date4)->at(team2), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date4)->at(team3), 3) <<
            "\t\t" << doubleFormatter(srsHash[i]->at(date5)->at(team1), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date5)->at(team2), 3) <<
            "\t" <<   doubleFormatter(srsHash[i]->at(date5)->at(team3), 3) << std::endl;
        }
    }

    if (writeOutput) {
        TeamWAverage *wAverage;

        for (auto & team : allTeamsHash){
            //open up the file
            std::ofstream waveragesFile;
            sprintf(path, "%s/cpp/NCAA_C/teams/%i/teams.%s.waverages.d",
                    homePath, year, boost::replace_all_copy(team.first, " ", "_").c_str());
            waveragesFile.open(path);

            for (auto &genericWAverage : genericWAverages){
                boost::gregorian::date day(boost::gregorian::from_string(genericWAverage.first));
                std::string date = genericWAverage.first;
                srsSOS = calcSRS(srsHash[numIterations - 1]->at(date), team.first, day);

                wAverage = team.second->WAverageOnDate(day);

                //write in the file
                waveragesFile << team.first;
                waveragesFile << "," << day.year();
                waveragesFile << "," << day.month().as_number();
                waveragesFile << "," << day.day();
                waveragesFile << "," << wAverage->getOpts();
                waveragesFile << "," << wAverage->getOtwo()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getOtwo()->P(), 3);
                waveragesFile << "," << wAverage->getOthree()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getOthree()->P(), 3);
                waveragesFile << "," << wAverage->getOft()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getOft()->P(), 3);
                waveragesFile << "," << wAverage->getOor()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getOor()->P(), 3);
                waveragesFile << "," << wAverage->getOdr()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getOdr()->P(), 3);
                waveragesFile << "," << wAverage->getOto()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getOto()->P(), 3);
                waveragesFile << "," << wAverage->getDpts();
                waveragesFile << "," << wAverage->getDtwo()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getDtwo()->P(), 3);
                waveragesFile << "," << wAverage->getDthree()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getDthree()->P(), 3);
                waveragesFile << "," << wAverage->getDft()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getDft()->P(), 3);
                waveragesFile << "," << wAverage->getDor()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getDor()->P(), 3);
                waveragesFile << "," << wAverage->getDdr()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getDdr()->P(), 3);
                waveragesFile << "," << wAverage->getDto()->A();
                waveragesFile << "," << doubleFormatter(wAverage->getDto()->P(), 3);
                waveragesFile << "," << doubleFormatter(wAverage->getRpi(), 3);
                waveragesFile << "," << doubleFormatter(wAverage->getOrigSRS(), 3);
                waveragesFile << "," << doubleFormatter(srsSOS[0], 3);
                waveragesFile << "," << doubleFormatter(srsSOS[1], 3);
                waveragesFile << "," << wAverage->getNum_games() << std::endl;
            }

            //close the file
            waveragesFile.close();
        }
    }

    return 0;
}