Esempio n. 1
0
//**********MAIN**************************************************************************
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        cout << argv[0] << " cfg file " << "[run]" << endl; 
        return -1;
    }

    //---memory consumption tracking---
    float cpu[2]{0}, mem[2]={0}, vsz[2]={0}, rss[2]={0};

    //---load options---    
    CfgManager opts;
    opts.ParseConfigFile(argv[1]);

    //-----input setup-----    
    if(argc > 2)
    {
        vector<string> run(1, argv[2]);
        opts.SetOpt("h4reco.run", run);
    }
    string outSuffix = opts.GetOpt<string>("h4reco.outNameSuffix");
    string run = opts.GetOpt<string>("h4reco.run");
    TChain* inTree = new TChain("H4tree");
    ReadInputFiles(opts, inTree);
    H4Tree h4Tree(inTree);

    //-----output setup-----
    uint64 index=stoul(run)*1e9;
    TFile* outROOT = new TFile("ntuples/"+outSuffix+TString(run)+".root", "RECREATE");
    outROOT->cd();
    RecoTree mainTree(&index);

    //---Get plugin sequence---
    PluginLoader<PluginBase>* loader;
    vector<PluginLoader<PluginBase>* > pluginLoaders;    
    map<string, PluginBase*> pluginMap;
    vector<PluginBase*> pluginSequence;
    vector<string> pluginList = opts.GetOpt<vector<string> >("h4reco.pluginList");    
    //---plugin creation
    pluginLoaders.reserve(pluginList.size());
    for(auto& plugin : pluginList)
    {
        cout << ">>> Loading plugin <" << plugin << ">" << endl;
        //---create loader 
        loader = new PluginLoader<PluginBase>(opts.GetOpt<string>(plugin+".pluginType"));
        pluginLoaders.push_back(loader);
        pluginLoaders.back()->Create();
        //---get instance and put it in the plugin sequence   
        PluginBase* newPlugin = pluginLoaders.back()->CreateInstance();
        if(newPlugin)
        {
            pluginSequence.push_back(newPlugin);
            pluginSequence.back()->SetInstanceName(plugin);
            pluginMap[plugin] = pluginSequence.back();
        }
        else
        {
            cout << ">>> ERROR: plugin type " << opts.GetOpt<string>(plugin+".pluginType") << " is not defined." << endl;
            return 0;
        }
    }

    //---begin
    for(auto& plugin : pluginSequence)
    {
        plugin->Begin(opts, &index);
        for(auto& shared : plugin->GetSharedData("", "TTree", true))
        {
            TTree* tree = (TTree*)shared.obj;
            tree->SetMaxVirtualSize(10000);
            tree->SetDirectory(outROOT);
        }
    }
            
    //---events loop
    int maxEvents=opts.GetOpt<int>("h4reco.maxEvents");
    cout << ">>> Processing H4DAQ run #" << run << " <<<" << endl;
    while(h4Tree.NextEntry() && (index-stoul(run)*1e9<maxEvents || maxEvents==-1))
    {
        if(index % 1000 == 0)
        {
            cout << ">>>Processed events: " << index-stoul(run)*1e9 << "/"
                 << (maxEvents<0 ? h4Tree.GetEntries() : min((int)h4Tree.GetEntries(), maxEvents))
                 << endl;
            TrackProcess(cpu, mem, vsz, rss);
        }

        //---call ProcessEvent for each plugin
        for(auto& plugin : pluginSequence)
            plugin->ProcessEvent(h4Tree, pluginMap, opts);

        //---fill the main tree with info variables and increase event counter
        mainTree.time_stamp = h4Tree.evtTimeStart;
        mainTree.run = h4Tree.runNumber;
        mainTree.spill = h4Tree.spillNumber;
        mainTree.event = h4Tree.evtNumber;
        mainTree.Fill();
        ++index;
    }

    //---end
    for(auto& plugin : pluginSequence)
    {
        //---call endjob for each plugin
        plugin->End(opts);
        //---get permanent data from each plugin and store them in the out file
        for(auto& shared : plugin->GetSharedData())
        {
            if(shared.obj->IsA()->GetName() == string("TTree"))
            {
                TTree* currentTree = (TTree*)shared.obj;
                outROOT->cd();
                currentTree->BuildIndex("index");
                currentTree->Write(currentTree->GetName(), TObject::kOverwrite);
                mainTree.AddFriend(currentTree->GetName());
            }
            else
            {
                outROOT->cd();
                shared.obj->Write(shared.tag.c_str(), TObject::kOverwrite);
            }
        }
    }
    
    //---close
    mainTree.Write();
    opts.Write("cfg");
    outROOT->Close();
    for(auto& loader : pluginLoaders)
        loader->Destroy();

    //---info
    TrackProcess(cpu, mem, vsz, rss);

    exit(0);
}    
int main (int argc,const char **argv) {

	int argvStep;
	unsigned int currentNode;
	unsigned int currentCore;

	Processor *processor;
	PState ps(0);

	bool autoRecall=false;
	int autoRecallTimer=60;
	
	CfgManager *cfgInstance;
	int errorLine;
	
	Scaler *scaler;

	int rv;
	int parsed = 0;
	int parsed_set = 0;

	printf ("TurionPowerControl %s (%s) %s\n", _VERSION, _SOURCE_VERSION, _TARGET_OS);
	printf ("Turion Power States Optimization and Control - by blackshard\n\n");

	if (argc<2) {
		printUsage(argv[0]);

		return 0;
	}

	if (initializeCore() == false) {
		return -1;
	}

	processor=getSupportedProcessor ();
	if (processor==NULL) {
		printf ("No supported processor detected, sorry.\n");
		return -2;
	}
	
	//Initializes currentNode and currentCore
	currentNode=processor->ALL_NODES;
	currentCore=processor->ALL_CORES;

	//Initializes the scaler based on the processor found in the system
	scaler=new Scaler (processor);
	
	for (argvStep = 1; ; argvStep++) {

		if (argvStep == argc) {
			if (!autoRecall)
				break;
			//Autorecall feature set argvStep back to 1 when it reaches end
			printf("Autorecall activated. Timeout: %d seconds\n", autoRecallTimer);
			Sleep(autoRecallTimer * 1000);
			printf("Autorecalling...\n");
			argvStep = 1;
		}

		//Reinitializes the processor object for active node and core in the system
		processor->setNode(currentNode);
		processor->setCore(currentCore);

		//printf ("Parsing argument %d %s\n",argvStep,argv[argvStep]);

		if (parsed_set) {
			printf("ERROR: -set can only be used exclusively\n");
			break;
		}
		parsed++;

		//List power states action
		if (strcmp(argv[argvStep], "-l") == 0) {

			processorStatus (processor);
			continue;
		}

		//Set the current operational node
		if (strcmp(argv[argvStep], "-node") == 0) {

			unsigned int thisNode;
			const char *arg = argv[argvStep + 1];

			if (arg == NULL) {
				printf("-node requires an argument\n");
				break;
			}
			if (strcmp(arg, "all") != 0) {
				if (requireUnsignedInteger(argc, argv, argvStep + 1, &thisNode)) {
					printf("ERROR: invalid -node -- %s\n", arg);
					break;
				}
				if (thisNode >= processor->getProcessorNodes()) {
					printf("ERROR: node must be in 0-%u range\n", processor->getProcessorNodes() - 1);
					break;
				}
				currentNode = thisNode;
			} else {
				currentNode = processor->ALL_NODES;
			}
			argvStep++;
			continue;
		}

		//Set the current operational core
		if (strcmp(argv[argvStep], "-core") == 0) {

			unsigned int thisCore;
			const char *arg = argv[argvStep + 1];

			if (arg == NULL) {
				printf("ERROR: -core requires an argument\n");
				break;
			}
			if (strcmp(arg, "all") != 0) {
				if (requireUnsignedInteger(argc, argv, argvStep + 1, &thisCore)) {
					printf("ERROR: invalid -core -- %s\n", arg);
					break;
				}
				if (thisCore >= processor->getProcessorCores()) {
					printf("ERROR: core must be in 0-%u range\n", processor->getProcessorCores() - 1);
					break;
				}
				currentCore = thisCore;
			} else {
				currentCore = processor->ALL_CORES;
			}
			argvStep++;
			continue;
		}

		rv = parseSingleSetSubcommand(processor, argc, argv, argvStep, 1, &ps);
		if (rv >= 0) {
			printf("\n");
			argvStep = rv - 1;
			continue;
		}
		if (rv == PARSE_WRONG_FORMAT) {
			break;
		}

		if (strcmp(argv[argvStep], "-nbvid") == 0) {
			unsigned int nbvid;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -nbvid requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &nbvid)) { 
				printf("ERROR: invalid NBVid -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (processor->getProcessorIdentifier() == PROCESSOR_10H_FAMILY) {
				processor->setNBVid (ps, nbvid);
				print_stat(processor, ps, "nbvid", nbvid, PRINT_STAT_FLAG_NODE | PRINT_STAT_FLAG_PSTATE);
				if (processor->getNBVid(ps) != nbvid)
					printf(" (actual: %d)", processor->getNBVid(ps));
				printf("\n\n");
			} else {
				processor->setNBVid (nbvid);
				print_stat(processor, ps, "nbvid", nbvid, PRINT_STAT_FLAG_NODE);
				if (processor->getNBVid() != nbvid)
					printf(" (actual: %d)", processor->getNBVid());
				printf("\n\n");
			}
			argvStep = argvStep + 1;
			continue;
		}

		if (strcmp(argv[argvStep], "-nbdid") == 0) {

			if (processor->getProcessorIdentifier() == PROCESSOR_10H_FAMILY) {
				unsigned int nbdid;

				if (argv[argvStep + 1] == NULL) {
					printf("ERROR: -nbdid requires an argument\n");
					break;
				}
				if (requireUnsignedInteger(argc, argv, argvStep + 1, &nbdid)) { 
					printf("ERROR: invalid NBDid -- %s\n", argv[argvStep + 1]);
					break;
				}
				processor->setNBDid (ps, nbdid);
				print_stat(processor, ps, "nbdid", nbdid, PRINT_STAT_FLAG_NODE | PRINT_STAT_FLAG_PSTATE);
				if (processor->getNBDid(ps) != nbdid)
					printf(" (actual: %d)", processor->getNBDid(ps));
				printf("\n\n");
				argvStep = argvStep + 1;
			} else {
				printf("ERROR: -nbdid is only supported on family 10h processors\n");
				break;
			}
			continue;
		}

		if (strcmp(argv[argvStep], "-nbfid") == 0) {

			unsigned int nbfid;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -nbfid requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &nbfid)) { 
				printf("ERROR: invalid NBFid -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setNBFid(nbfid);
			print_stat(processor, ps, "nbfid", nbfid, PRINT_STAT_FLAG_NODE);
			if (processor->getNBFid() != nbfid)
				printf(" (actual: %d)", processor->getNBFid());
			printf("\n\n");
			argvStep += 1;
			continue;
		}

		/*
		 * Following section will set a new frequency for selected pstate/core/node
		 */
		if (strcmp(argv[argvStep], "-nbfreq") == 0 || 
			strcmp(argv[argvStep], "-nbf") == 0 || 
			strcmp(argv[argvStep], "-nbfrequency") == 0) {

			unsigned int nbfrequency;

			if (argv[argvStep + 1] == NULL) {
				printf("ERROR: %s requires an argument\n", argv[argvStep]);
				return -1;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &nbfrequency)) {
				printf("ERROR: invalid nbfrequency -- %s\n", argv[argvStep + 1]);
				return -1;
			}
			if (processor->getProcessorIdentifier() == PROCESSOR_10H_FAMILY) {
				processor->setNBFrequency(ps, nbfrequency);
				print_stat(processor, ps, "nbfrequency", nbfrequency, PRINT_STAT_FLAG_NODE | PRINT_STAT_FLAG_PSTATE);
				if (processor->getNBFrequency(ps) != nbfrequency)
					printf(" (actual: %d)", processor->getNBFrequency(ps));
				printf("\n\n");
			} else {
				processor->setNBFrequency(nbfrequency);
				print_stat(processor, ps, "nbfrequency", nbfrequency, PRINT_STAT_FLAG_NODE);
				if (processor->getNBFrequency() != nbfrequency)
					printf(" (actual: %d)", processor->getNBFrequency());
				printf("\n\n");
			}
			argvStep++;
			continue;
		}

		//Enables a specified PState for current cores and current nodes
		if (strcmp(argv[argvStep], "-en") == 0) {

			unsigned int pstate;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -en requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &pstate)) { 
				printf("ERROR: -en: invalid P-state -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (pstate >= processor->getPowerStates()) {
				printf("ERROR: -en: P-state must be in 0-%u range\n", processor->getPowerStates() - 1);
				break;
			}
			processor->pStateEnable(pstate);
			argvStep++;
			continue;
		}

		//Disables a specified PState for current cores and current nodes
		if (strcmp(argv[argvStep], "-di") == 0) {

			unsigned int pstate;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -di requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &pstate)) { 
				printf("ERROR: -di: invalid P-state -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (pstate >= processor->getPowerStates()) {
				printf("ERROR: -di: P-state must be in 0-%u range\n", processor->getPowerStates() - 1);
				break;
			}
			processor->pStateDisable(pstate);
			argvStep++;
			continue;
		}

		//Set maximum PState for current nodes
		if (strcmp(argv[argvStep], "-psmax") == 0) {

			unsigned int pstate;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -psmax requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &pstate)) { 
				printf("ERROR: invalid P-state -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (pstate >= processor->getPowerStates()) {
				printf("ERROR: P-state must be in 0-%u range\n", processor->getPowerStates() - 1);
				break;
			}
			processor->setMaximumPState(pstate);
			argvStep++;
			continue;
		}

		//Force transition to a pstate for current cores and current nodes
		if (strcmp(argv[argvStep], "-fo") == 0) {

			unsigned int pstate;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -fo requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &pstate)) { 
				printf("ERROR: -fo: invalid P-state -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (pstate >= processor->getPowerStates() - processor->getBoostStates()) {
				printf("ERROR: -fo: P-state (software P-state) must be in 0-%u range\n", processor->getPowerStates() - processor->getBoostStates() - 1);
				break;
			}
			processor->forcePState(pstate);
			argvStep++;
			continue;
		}

		if (strcmp(argv[argvStep], "-bst") == 0) {

			unsigned int numBoostStates;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -bst requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &numBoostStates)) { 
				printf("ERROR: invalid numBoostStates -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setNumBoostStates(numBoostStates);
			argvStep++;
			continue;
		}

		//Show temperature table
		if (strcmp(argv[argvStep], "-temp") == 0) {

			processorTempStatus(processor);
			continue;
		}

		//Set vsSlamTime for current nodes
		if (strcmp(argv[argvStep], "-slamtime") == 0) {

			unsigned int slamtime;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -slamtime requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &slamtime)) { 
				printf("ERROR: invalid slamtime -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setSlamTime(slamtime);
			argvStep++;
			continue;
		}

		//Set vsAltVIDSlamTime for current nodes
		if (strcmp(argv[argvStep], "-altvidslamtime") == 0) {

			unsigned int altvidslamtime;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -altvidslamtime requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &altvidslamtime)) { 
				printf("ERROR: invalid altvidslamtime -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setAltVidSlamTime(altvidslamtime);
			argvStep++;
			continue;
		}

		//Set Ramp time for StepUpTime for current nodes
		if (strcmp(argv[argvStep], "-rampuptime") == 0) {

			unsigned int rampuptime;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -rampuptime requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &rampuptime)) { 
				printf("ERROR: invalid rampuptime -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setStepUpRampTime(rampuptime);
			argvStep++;
			continue;
		}

		//Set Ramp time for StepDownTime for current nodes
		if (strcmp(argv[argvStep], "-rampdowntime") == 0) {

			unsigned int rampdowntime;

			if (argv[argvStep + 1] == NULL) {
				printf ("ERROR: -rampdowntime requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &rampdowntime)) { 
				printf("ERROR: invalid rampdowntime -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setStepDownRampTime(rampdowntime);
			argvStep++;
			continue;
		}

		if (strcmp(argv[argvStep], "-gettdp") == 0) {

			processor->getTDP();
			continue;
		}

		//Show information about per-family specifications
		if (strcmp(argv[argvStep], "-spec") == 0) {

			processor->showFamilySpecs();
			continue;
		}

		//Show information about DRAM timing register
		if (strcmp(argv[argvStep], "-dram") == 0) {

			processor->showDramTimings();
			continue;
		}

		//Show information about HTC registers status
		if (strcmp(argv[argvStep], "-htc") == 0) {

			processor->showHTC();
			continue;
		}
		
		//Enables HTC Features for current nodes
		if (strcmp(argv[argvStep], "-htcenable") == 0) {

			processor->HTCEnable();
			continue;
		}

		//Disables HTC Features for current nodes
		if (strcmp(argv[argvStep], "-htcdisable") == 0) {

			processor->HTCDisable();
			continue;
		}

		//Set HTC temperature limit for current nodes
		if (strcmp(argv[argvStep], "-htctemplimit") == 0) {

			unsigned int htctemplimit;

			if (argv[argvStep + 1] == NULL) {
				printf("ERROR: -htctemplimit requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &htctemplimit)) { 
				printf("ERROR: invalid htctemplimit -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->HTCsetTempLimit(htctemplimit);
			argvStep++;
			continue;
		}

		//Set HTC hysteresis limit for current nodes
		if (strcmp(argv[argvStep], "-htchystlimit") == 0) {

			unsigned int htchystlimit;

			if (argv[argvStep + 1] == NULL) {
				printf("ERROR: -htchystlimit requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &htchystlimit)) { 
				printf("ERROR: invalid htchystlimit -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->HTCsetHystLimit(htchystlimit);
			argvStep++;
			continue;
		}

		//Set AltVID for current nodes
		if (strcmp(argv[argvStep], "-altvid") == 0) {

			unsigned int altvid;

			if (argv[argvStep + 1] == NULL) {
				printf("ERROR: -altvid requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &altvid)) { 
				printf("ERROR: invalid altvid -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->setAltVid(altvid);
			argvStep++;
			continue;
		}

		//Show information about Hypertransport registers
		if (strcmp(argv[argvStep], "-htstatus") == 0) {

			processor->showHTLink();
			continue;
		}

		//Set Hypertransport Link frequency for current nodes
		if (strcmp(argv[argvStep], "-htset") == 0) {

			unsigned int reg;
			unsigned int value;

			if ((argv[argvStep + 1] == NULL) || (argv[argvStep + 2] == NULL)) {
				printf("ERROR: -htset requires two arguments (register, value)\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &reg)) { 
				printf("ERROR: invalid register -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 2, &value)) { 
				printf("ERROR: invalid value -- %s\n", argv[argvStep + 2]);
				break;
			}
			processor->setHTLinkSpeed(reg, value);
			argvStep += 2;
			continue;
		}

		//Enables PSI_L bit for current nodes
		if (strcmp(argv[argvStep], "-psienable") == 0) {

			processor->setPsiEnabled (true);
			continue;
		}

		//Disables PSI_L bit for current nodes
		if (strcmp(argv[argvStep], "-psidisable") == 0) {

			processor->setPsiEnabled (false);
			continue;
		}

		//Set PSI_L bit threshold for current nodes
		if (strcmp(argv[argvStep], "-psithreshold") == 0) {

			unsigned int psithreshold;

			if (argv[argvStep + 1] == NULL) {
				printf("ERROR: -psithreshold requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &psithreshold)) { 
				printf("ERROR: invalid psithreshold -- %s\n", argv[argvStep + 1]);
				break;
			}
			if (processor->getPsiEnabled() == true) {
				printf("ERROR: PSI enabled; disable PSI before changing PSI threshold\n");
				break;
			}
			printf("WARNING: changing PSI threshold may cause permanent damage to your hardware!\n\n");
			processor->setPsiThreshold(psithreshold);
			argvStep++;
			continue;
		}

		//Set C1E enabled on current nodes and current cores
		if (strcmp(argv[argvStep], "-c1eenable") == 0) {

			processor->setC1EStatus(true);
			continue;
		}

		//Set C1E disabled on current nodes and current cores
		if (strcmp(argv[argvStep], "-c1edisable") == 0) {

			processor->setC1EStatus(false);
			continue;
		}

		//Set Boost state to enabled for supported processors
		if (strcmp(argv[argvStep], "-boostenable") == 0) {	

			processor->setBoost(true);
			continue;
		}

		//Set Boost state to disabled for supported processors
		if (strcmp(argv[argvStep], "-boostdisable") == 0) {

			processor->setBoost(false);
			continue;
		}

		//Goes in temperature monitoring
		if (strcmp(argv[argvStep], "-mtemp") == 0) {

			processorTempMonitoring(processor);
			continue;
		}

		//Goes into Check Mode and controls very fastly if a transition to a wrong pstate happens
		if (strcmp(argv[argvStep], "-CM") == 0) {

			processor->checkMode();
			continue;
		}

		//Allow cyclic parameter auto recall
		if (strcmp(argv[argvStep], "-autorecall") == 0) {

			if (autoRecall == false) {
				autoRecall = true;
				autoRecallTimer = 60;
			}
			continue;
		}

		//Get general info about Performance counters
		if (strcmp(argv[argvStep], "-pcgetinfo") == 0) {

			processor->perfCounterGetInfo();
			continue;
		}

		//Get Performance counter value about a specific performance counter
		if (strcmp(argv[argvStep], "-pcgetvalue") == 0) {

			unsigned int counter;

			if (argv[argvStep + 1] == NULL) {
				printf("ERROR: -pcgetvalue requires an argument\n");
				break;
			}
			if (requireUnsignedInteger(argc, argv, argvStep + 1, &counter)) { 
				printf("ERROR: invalid counter -- %s\n", argv[argvStep + 1]);
				break;
			}
			processor->perfCounterGetValue(counter);
			argvStep++;
			continue;
		}

		//Costantly monitors Performance counter value about a specific performance counter
		if (strcmp(argv[argvStep], "-pcmonitor") == 0) {
			printf("ERROR: -pcmonitor is currently not implemented\n");
			break;
		}

		//Handle -set switch. That is a user friendly way to set up a pstate or a pstate/core
		//with frequency value and voltage value.
		if (strcmp(argv[argvStep], "-set") == 0) {

			parsed_set++;
			
			if (parsed - parsed_set) {
				printf("ERROR: -set can only be used exclusively\n");
				break;
			}
			printf("WARNING: -set is deprecated and will be removed in future versions.\n");
			printf("          Please consider using standalone versions of your sub-commands.\n");
			printf("          Consult the documentation for details.\n\n");
			if ((argvStep = parseSetCommand(processor, argc, argv, argvStep + 1)) == PARSE_WRONG_FORMAT)
				break;

			printf ("*** -set parsing completed\n");
			argvStep--;
			continue;
		}

		//Costantly monitors CPU Usage 
		if (strcmp(argv[argvStep], "-perf-cpuusage") == 0) {

			processor->perfMonitorCPUUsage ();
			continue;
		}

		//Costantly monitors FPU Usage
		if (strcmp(argv[argvStep], "-perf-fpuusage") == 0) {

			processor->perfMonitorFPUUsage ();
			continue;
		}

		//Constantly monitors Data Cache Misaligned Accesses
		if (strcmp(argv[argvStep], "-perf-dcma") == 0) {

			processor->perfMonitorDCMA();
			continue;
		}



		//Open a configuration file
		if (strcmp(argv[argvStep], "-cfgfile") == 0) {

			cfgInstance=new CfgManager (processor, scaler);

			if (cfgInstance->openCfgFile ((char *)argv[argvStep+1])) {
				printf ("Error: invalid configuration file\n");
				free (cfgInstance);
				break;
			}

			errorLine=cfgInstance->parseCfgFile ();

			if (errorLine!=0) {
				printf ("Error: invalid configuration identifier at row %d\n",errorLine);
				free (cfgInstance);
				break;
			}

			free (cfgInstance); 

			argvStep++;
			continue;
		}

		if (strcmp(argv[argvStep], "-scaler") == 0) {

			printf ("Scaler is not active in this version.\n");
			scaler->beginScaling ();
			continue;
		}

		printf("ERROR: invalid argument -- %s\n", argv[argvStep]);
		break;
	}

	free (processor);

	deinitializeCore();

	if (argvStep == argc) {
		printf ("Done.\n");
		return 0;
	}
	return -1;
}
Esempio n. 3
0
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        cout << argv[0] << " cfg file " << "[run]" << endl; 
        return -1;
    }

    //---load options---
    CfgManager opts;
    //---defaults
    opts.ParseConfigFile("cfg/dumper_default.cfg");
    //---current
    opts.ParseConfigFile(argv[1]);
    cout << opts << endl;
    //---data opts
    string path=opts.GetOpt<string>("global", "path2data");
    string run=opts.GetOpt<string>("global", "run");
    if(argc > 2)
        run = argv[2];
    //---channels opts
    int maxEvents = opts.GetOpt<int>("global", "maxEvents");
    int nCh = opts.GetOpt<int>("global", "nCh");
    int nSamples = opts.GetOpt<int>("global", "nSamples");
    float tUnit = opts.GetOpt<float>("global", "tUnit");
    int* chPolarity = new int[nCh];
    TString* nameMCP = new TString[nCh];    
    for(int jCh=1; jCh<=nCh; ++jCh)
    {
        nameMCP[jCh-1] = opts.GetOpt<string>("global", string("Ch")+to_string(jCh));
        chPolarity[jCh-1] = opts.GetOpt<int>("global", string("Ch")+to_string(jCh), 1);
    }

    //---definitions---
    int iCh=-1, iEvent=-1;
    string ls_command;
    TekFilesManager sortedWaveList;
  
    //-----output setup-----
    TFile* outROOT = TFile::Open("ntuples/"+TString(run)+".root", "RECREATE");
    outROOT->cd();
    RecoTree outTree(nCh, nSamples, nameMCP);

    //-----read data + sort by date-----
    ls_command = string("ls "+path+run+" | grep 'txt' > tmp/"+run+".list");
    system(ls_command.c_str());
    ifstream waveList(string("tmp/"+run+".list").c_str(), ios::in);
    string file;    
    while(waveList >> file)
        sortedWaveList.PushBack(file);
        
    //---process WFs---
    map<uint32, vector<string> >::iterator evtFiles;
    while(iEvent<maxEvents || maxEvents==-1)
    {
        //---get next event files
        evtFiles = sortedWaveList.NextEvt();
        if(iEvent == -1)
            outTree.start_time = evtFiles->first;
        if(evtFiles == sortedWaveList.end())
            break;

        //---check input files
        if(evtFiles->second.size() != nCh)
            cout << "> Dumper --- WARNING: more than one event with the same time stamp" << endl;
        
        for(auto file : evtFiles->second)
        {
            ++iCh;
            file = path+run+"/"+file;
            cout << file << endl;

            //---read WFs
            WFClass WF(chPolarity[iCh], tUnit);
            ifstream inputFile(file.c_str(), ios::in);
            float sample_val=0;    
            int iSample=0;
            while(inputFile >> sample_val && iSample<nSamples)
            {
                WF.AddSample(sample_val*1000);
                ++iSample;
            }
            inputFile.close();
            //---compute reco variables
            WF.SetBaselineWindow(10, 90);
            WF.SetSignalWindow(200, nSamples);
            outTree.baseline[iCh] = WF.SubtractBaseline();
            outTree.amp_max[iCh] = WF.GetAmpMax();
            int time_AM = (int)WF.GetTimeCF(1);
            int time_I1 = time_AM-30;
            int time_I2 = time_AM+50;
            outTree.time[iCh] = WF.GetTimeCF(0.5);
            outTree.baseline[iCh] = WF.GetIntegral(100, 180);
            outTree.charge_tot[iCh] = WF.GetModIntegral(200, nSamples);
            if(time_I1 > 200 && time_I2 < nSamples)
                outTree.charge_sig[iCh] = WF.GetIntegral(time_I1, time_I2);
            else
                outTree.charge_sig[iCh] = -1000;
            //---WFs---
            vector<float>* analizedWF = WF.GetSamples();
            for(int jSample=0; jSample<analizedWF->size(); ++jSample)
            {
                outTree.WF_ch[jSample+iCh*nSamples] = iCh;
                outTree.WF_time[jSample+iCh*nSamples] = jSample*tUnit;
                outTree.WF_val[jSample+iCh*nSamples] = analizedWF->at(jSample);
            }
            //---fill the output tree
            if(iCh == nCh-1)
            {
                iEvent++;
                outTree.time_stamp = evtFiles->first-outTree.start_time;
                outTree.event_id = iEvent;
                outTree.Fill();
                //---reset
                iCh = -1;
            }
        }
    }
    waveList.close();
    
    outTree.Write();
    outROOT->Close();
}
//**********MAIN**************************************************************************
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        cout << argv[0] << " cfg file " << "[run]" << endl; 
        return -1;
    }

    gROOT->SetBatch(kTRUE);
    //---load options---
    CfgManager opts;
    opts.ParseConfigFile(argv[1]);

    //---data opts
    string path=opts.GetOpt<string>("global.path2data");
    string run=opts.GetOpt<string>("global.run");
    string outSuffix=opts.GetOpt<string>("global.outFileSuffix");
    if(argc > 2)
        run = argv[2];
    int maxEvents = opts.GetOpt<int>("global.maxEvents");
    //---channels opts
    int nCh = opts.GetOpt<int>("global.nCh");
    int nSamples = opts.GetOpt<int>("global.nSamples");
    float tUnit = opts.GetOpt<float>("global.tUnit");
    string refChannel = opts.GetOpt<string>("global.refChannel");
    vector<string> channelsNames = opts.GetOpt<vector<string> >("global.channelsNames");
    map<string, vector<float> > timeOpts;
    timeOpts[refChannel] = opts.GetOpt<vector<float> >(refChannel+".timeOpts");
    for(auto& channel : channelsNames)
         timeOpts[channel] = opts.GetOpt<vector<float> >(channel+".timeOpts");

    //---definitions---
    int iEvent=0;
  
    //-----output setup-----
    TString outF="ntuples/Templates_"+TString(outSuffix)+"_"+TString(run)+".root";
    TFile* outROOT = TFile::Open(outF, "RECREATE");
    outROOT->cd();
    map<string, TH2F*> templates;
    for(auto channel : channelsNames)
        templates[channel] = new TH2F(channel.c_str(), channel.c_str(),
				      16000, -40, 160, 1200, -0.1, 1.1);
  
    //-----input setup-----
    TChain* inTree = new TChain("H4tree");
    string ls_command;
    if(path.find("/eos/cms") != string::npos)
        ls_command = string("gfal-ls root://eoscms/"+path+run+" | grep 'root' > tmp/"+run+".list");
    else
        ls_command = string("ls "+path+run+" | grep 'root' > tmp/"+run+".list");
    system(ls_command.c_str());
    ifstream waveList(string("tmp/"+run+".list").c_str(), ios::in);
    string file;
    
    int nFiles=0;
    while(waveList >> file && (opts.GetOpt<int>("global.maxFiles")<0 || nFiles<opts.GetOpt<int>("global.maxFiles")) )
    {
      
        if(path.find("/eos/cms") != string::npos)
	  {
	    std::cout << "+++ Adding file " << ("root://eoscms/"+path+run+"/"+file).c_str() << std::endl;
            inTree->AddFile(("root://eoscms/"+path+run+"/"+file).c_str());
	  }
        else
	  {
	    std::cout << "+++ Adding file " << (path+run+"/"+file).c_str() << std::endl;
            inTree->AddFile((path+run+"/"+file).c_str());
	  }
	++nFiles;

    }
    H4Tree h4Tree(inTree);

    //---process WFs---
    long nentries=h4Tree.GetEntries();
    cout << ">>> Processing H4DAQ run #" << run << " events #" << nentries << " <<<" << endl;
    while(h4Tree.NextEntry() && (iEvent<maxEvents || maxEvents==-1))
    {        
        ++iEvent;
	if (iEvent%1000==0) std::cout << "Processing event " << iEvent << "/" << nentries << std::endl;
        //---setup output event 
        int outCh=0;
        bool badEvent=false;
        
        //---read the digitizer
        //---read time raference channel
        float refTime=0, refAmpl=0;
        WFClass WF(opts.GetOpt<int>(refChannel+".polarity"), tUnit);
        int digiGr = opts.GetOpt<int>(refChannel+".digiGroup");
        int digiCh = opts.GetOpt<int>(refChannel+".digiChannel");
        int offset = digiGr*9*nSamples + digiCh*nSamples;
        for(int iSample=offset; iSample<offset+nSamples; ++iSample)
        {
            //---H4DAQ bug: sometimes ADC value is out of bound.
            if(h4Tree.digiSampleValue[iSample] > 4096)
            {
                badEvent = true;
                break;
            }
            WF.AddSample(h4Tree.digiSampleValue[iSample]);
        }
        //---skip bad events
        if(badEvent)
            continue;
        WF.SetBaselineWindow(opts.GetOpt<int>(refChannel+".baselineWin", 0), 
                             opts.GetOpt<int>(refChannel+".baselineWin", 1));
        WF.SetSignalWindow(opts.GetOpt<int>(refChannel+".signalWin", 0), 
                           opts.GetOpt<int>(refChannel+".signalWin", 1));
        WFBaseline refBaseline=WF.SubtractBaseline();
        refAmpl = WF.GetInterpolatedAmpMax();            
        refTime = WF.GetTime(opts.GetOpt<string>(refChannel+".timeType"), timeOpts[refChannel]).first;
	//---you may want to use an offset, for example if you use the trigger time
	if(opts.OptExist(refChannel+".timeOffset"))refTime -= opts.GetOpt<float>(refChannel+".timeOffset");
        //---require reference channel to be good
        if(refTime/tUnit < opts.GetOpt<int>(refChannel+".signalWin", 0) ||
           refTime/tUnit > opts.GetOpt<int>(refChannel+".signalWin", 1) ||
	   refBaseline.rms > opts.GetOpt<float>(refChannel+".noiseThreshold") ||  refAmpl < opts.GetOpt<int>(refChannel+".amplitudeThreshold"))
	  continue;

        //---template channels
        for(auto& channel : channelsNames)
        {
            //---read WFs
            WFClass WF(opts.GetOpt<int>(channel+".polarity"), tUnit);
            int digiGr = opts.GetOpt<int>(channel+".digiGroup");
            int digiCh = opts.GetOpt<int>(channel+".digiChannel");
            int offset = digiGr*9*nSamples + digiCh*nSamples;
            for(int iSample=offset; iSample<offset+nSamples; ++iSample)
            {
                //---H4DAQ bug: sometimes ADC value is out of bound.
                if(h4Tree.digiSampleValue[iSample] > 4096)
                {
                    badEvent = true;
                    break;
                }
                WF.AddSample(h4Tree.digiSampleValue[iSample]);
            }
            //---skip bad events
            if(badEvent)
                continue;
            //---compute reco variables
            float channelTime=0, channelAmpl=0;            
            WF.SetBaselineWindow(opts.GetOpt<int>(channel+".baselineWin", 0), 
                                 opts.GetOpt<int>(channel+".baselineWin", 1));
            WF.SetSignalWindow(opts.GetOpt<int>(channel+".signalWin", 0), 
                               opts.GetOpt<int>(channel+".signalWin", 1));
            WFBaseline channelBaseline=WF.SubtractBaseline();
	    channelAmpl = WF.GetInterpolatedAmpMax(-1,-1,opts.GetOpt<int>(channel+".signalWin", 2));
            channelTime = WF.GetTime(opts.GetOpt<string>(channel+".timeType"), timeOpts[channel]).first;
            //---skip bad events or events with no signal
            if(channelTime/tUnit > opts.GetOpt<int>(channel+".signalWin", 0) &&
               channelTime/tUnit < opts.GetOpt<int>(channel+".signalWin", 1) &&
	       channelBaseline.rms < opts.GetOpt<float>(channel+".noiseThreshold") &&
               channelAmpl > opts.GetOpt<int>(channel+".amplitudeThreshold") &&
               channelAmpl < 4000)
            {                
                vector<float>* analizedWF = WF.GetSamples();
                for(int iSample=0; iSample<analizedWF->size(); ++iSample)
		  templates[channel]->Fill(iSample*tUnit-refTime, analizedWF->at(iSample)/channelAmpl);
	    }
        }
    }   


    cout << ">>> Writing output " << outF << " <<<" << endl;    

    outROOT->cd();

    for(auto& channel : channelsNames)
    {
      //      pair<TH1F, TH1F> dft = DFT_cut(getMeanProfile(templates[channel]), channel, 4);
      //      dft.first.Write();
      //      dft.second.Write();
      if (templates[channel]->GetEntries()>1024*10)
	{
	  TH1F* prof=getMeanProfile(templates[channel]);
	  templates[channel]->Write();
	  prof->Write();
	}
    }
    opts.Write("cfg");
    outROOT->Close();
}