FrameTimeManager::Timing FrameTimeManager::GetFrameTiming(unsigned frameIndex) { Timing frameTiming = LocklessTiming.GetState(); if (frameTiming.ThisFrameTime != 0.0) { // If timing hasn't been initialized, starting based on "now" is the best guess. frameTiming.InitTimingFromInputs(frameTiming.Inputs, RenderInfo.Shutter.Type, ovr_GetTimeInSeconds(), frameIndex); } else if (frameIndex > frameTiming.FrameIndex) { unsigned frameDelta = frameIndex - frameTiming.FrameIndex; double thisFrameTime = frameTiming.NextFrameTime + double(frameDelta-1) * frameTiming.Inputs.FrameDelta; // Don't run away too far into the future beyond rendering. OVR_ASSERT(frameDelta < 6); frameTiming.InitTimingFromInputs(frameTiming.Inputs, RenderInfo.Shutter.Type, thisFrameTime, frameIndex); } return frameTiming; }
void arch_dump_summary(struct arch_t *arch, FILE *f) { Emu *emu = arch->emu; Timing *timing = arch->timing; /* If no instruction was run for this architecture, skip * statistics summary. */ if (!emu->instructions) return; /* Architecture-specific emulation statistics */ assert(emu->DumpSummary); emu->DumpSummary(emu, f); /* Timing simulation statistics */ if (arch->sim_kind == arch_sim_kind_detailed) { /* Architecture-specific */ assert(timing->DumpSummary); timing->DumpSummary(timing, f); } /* End */ fprintf(f, "\n"); }
void arch_run(int *num_emu_active_ptr, int *num_timing_active_ptr) { struct arch_t *arch; long long cycle; int run; int i; Emu *emu; Timing *timing; /* Reset active emulation and timing simulation counters */ *num_emu_active_ptr = 0; *num_timing_active_ptr = 0; /* Run one iteration for all architectures */ for (i = 0; i < arch_list_count; i++) { /* Get architecture */ arch = arch_list[i]; if (arch->sim_kind == arch_sim_kind_functional) { /* Emulation iteration */ emu = arch->emu; assert(emu && emu->Run); arch->active = emu->Run(emu); /* Increase number of active emulations if the architecture * actually performed a useful emulation iteration. */ *num_emu_active_ptr += arch->active; } else { /* Check whether the architecture should actually run an * iteration. If it is working at a slower frequency than * the main simulation loop, we must skip this call. */ timing = arch->timing; assert(timing); assert(timing->frequency_domain); cycle = esim_domain_cycle(timing->frequency_domain); run = cycle != arch->last_timing_cycle; /* Timing simulation iteration */ if (run) { /* Do it... */ arch->active = timing->Run(timing); /* ... but only update the last timing * simulation cycle if there was an effective * execution of the iteration loop. Otherwise, * there is a deadlock: 'esim_time' will not * advance (no call to 'esim_process_events') * because no architecture ran, and no * architecture will run because 'esim_time' * did not advance. */ if (arch->active) arch->last_timing_cycle = cycle; } /* Increase number of active timing simulations if the * architecture actually performance a useful iteration. */ *num_timing_active_ptr += arch->active; } } }
Timing CSSTimingData::convertToTiming(size_t index) const { Timing timing; timing.startDelay = getRepeated(m_delayList, index); timing.iterationDuration = getRepeated(m_durationList, index); timing.timingFunction = getRepeated(m_timingFunctionList, index); timing.assertValid(); return timing; }
// TODO: we might want to use multiple buffers at the same time void Measurement::WriteDataBin(FILE *f, int channel) { Timing t; long size_written; int i, j; const unsigned int length_datachunk = 1000000; char data_8bit[1000000]; // std::vector<char>data_8bit(1000); std::cerr << "Write binary data for channel " << (char)('A'+channel) << " ... "; t.Start(); // TODO: test if file exists if(channel < 0 || channel >= GetNumberOfChannels()) { throw "You can only write data for channels 0 - (N-1)."; } else { if(GetChannel(channel)->IsEnabled()) { /* size_written = fwrite(data[channel], sizeof(short), GetLengthFetched(), f); // make sure the data is written fflush(f); if(size_written < GetLengthFetched()) { FILE_LOG(logERROR) << "Measurement::WriteDataBin didn't manage to write to file."; }*/ // TODO: if only 8 bits int length_fetched = GetLengthFetched(); // int length_datachunk = data_8bit.size(); for(i=0; i<length_fetched; i+=length_datachunk) { if(GetSeries() == PICO_6000) { for(j=0; j<length_datachunk && i+j<length_fetched; j++) { data_8bit[j] = data[channel][i+j] >> 8; } size_written = fwrite(data_8bit, sizeof(char), j, f); } else { // TODO: test!!! size_written = fwrite(data[channel]+1, sizeof(data[0][0]), j, f); } fflush(f); if(size_written < j) { FILE_LOG(logERROR) << "Measurement::WriteDataBin didn't manage to write to file."; } } // size_written = fwrite(data[channel], sizeof(short), GetLengthFetched(), f); // make sure the data is written // fflush(f); // if(size_written < GetLengthFetched()) { // FILE_LOG(logERROR) << "Measurement::WriteDataBin didn't manage to write to file."; // } } else {
Timing TimingInput::convert(const Dictionary& timingInputDictionary) { Timing result; // FIXME: This method needs to be refactored to handle invalid // null, NaN, Infinity values better. // See: http://www.w3.org/TR/WebIDL/#es-double double startDelay = Timing::defaults().startDelay; timingInputDictionary.get("delay", startDelay); setStartDelay(result, startDelay); double endDelay = Timing::defaults().endDelay; timingInputDictionary.get("endDelay", endDelay); setEndDelay(result, endDelay); String fillMode; timingInputDictionary.get("fill", fillMode); setFillMode(result, fillMode); double iterationStart = Timing::defaults().iterationStart; timingInputDictionary.get("iterationStart", iterationStart); setIterationStart(result, iterationStart); double iterationCount = Timing::defaults().iterationCount; timingInputDictionary.get("iterations", iterationCount); setIterationCount(result, iterationCount); double iterationDuration = 0; if (timingInputDictionary.get("duration", iterationDuration)) { setIterationDuration(result, iterationDuration); } double playbackRate = Timing::defaults().playbackRate; timingInputDictionary.get("playbackRate", playbackRate); setPlaybackRate(result, playbackRate); String direction; timingInputDictionary.get("direction", direction); setPlaybackDirection(result, direction); String timingFunctionString; timingInputDictionary.get("easing", timingFunctionString); setTimingFunction(result, timingFunctionString); result.assertValid(); return result; }
//Formats a given input string such that it follows the iEta, iPhi, iSlice naming convention //Will take text written in quotes without requiring a variable string AnalyzeResponseUniformity::getNameByIndex(int iEta, int iPhi, int iSlice, const std::string & strInputPrefix, const std::string & strInputName){ //Variable Declaration string ret_Name = ""; if (iSlice > -1) { ret_Name = strInputPrefix + "_iEta" + getString(iEta) + "iPhi" + getString(iPhi) + "Slice" + getString(iSlice) + "_" + strInputName; } else if (iPhi > -1){ //Case: Specific (iEta,iPhi) sector ret_Name = strInputPrefix + "_iEta" + getString(iEta) + "iPhi" + getString(iPhi) + "_" + strInputName; } //End Case: Specific (iEta,iPhi) sector else{ //Case: iEta Sector, sum over sector's iPhi ret_Name = strInputPrefix + "_iEta" + getString(iEta) + "_" + strInputName; } //End Case: iEta Sector, sum over sector's iPhi return ret_Name; } //End AnalyzeResponseUniformity::getNameByIndex()
bool CompositorAnimationsImpl::convertTimingForCompositor(const Timing& timing, double timeOffset, CompositorTiming& out, double playerPlaybackRate) { timing.assertValid(); // FIXME: Compositor does not know anything about endDelay. if (timing.endDelay != 0) return false; if (std::isnan(timing.iterationDuration) || !timing.iterationCount || !timing.iterationDuration) return false; if (!std::isfinite(timing.iterationCount)) { out.adjustedIterationCount = -1; } else { out.adjustedIterationCount = timing.iterationCount; } out.scaledDuration = timing.iterationDuration; out.direction = timing.direction; // Compositor's time offset is positive for seeking into the animation. out.scaledTimeOffset = -timing.startDelay / playerPlaybackRate + timeOffset; out.playbackRate = timing.playbackRate * playerPlaybackRate; out.fillMode = timing.fillMode == Timing::FillModeAuto ? Timing::FillModeNone : timing.fillMode; out.iterationStart = timing.iterationStart; out.assertValid(); return true; }
void arch_dump(struct arch_t *arch, FILE *f) { double time_in_sec; int i; Emu *emu; Timing *timing; /* Get objects */ emu = arch->emu; timing = arch->timing; /* Nothing to print if architecture was not active */ if (!emu->instructions) return; /* Header */ for (i = 0; i < 80; i++) fprintf(f, "="); fprintf(f, "\nArchitecture '%s'\n", arch->name); for (i = 0; i < 80; i++) fprintf(f, "="); fprintf(f, "\n\n"); /* Emulator */ time_in_sec = (double) m2s_timer_get_value(emu->timer) / 1.0e6; fprintf(f, "SimKind = %s\n", str_map_value(&arch_sim_kind_map, arch->sim_kind)); fprintf(f, "Time = %.2f\n", time_in_sec); fprintf(f, "Instructions = %lld\n", emu->instructions); fprintf(f, "\n"); assert(emu->DumpSummary); emu->DumpSummary(emu, f); /* Continue with timing simulator only it active */ if (arch->sim_kind == arch_sim_kind_functional) return; /* Timing simulator */ fprintf(f, "Cycles = %lld\n", timing->cycle); fprintf(f, "\n"); assert(timing->DumpSummary); timing->DumpSummary(timing, f); }
void setInputMatrixToAlgebraDefault(float_tt* dst, size_t numVal) { Timing timer; memset(dst, 0, sizeof(float_tt) * numVal); // empty cells are implicit zeros for sparse matrices enum dummy {DBG_DENSE_ALGEBRA_WITH_NAN_FILL=0}; // won't be correct if empty cells present if(DBG_DENSE_ALGEBRA_WITH_NAN_FILL) { valsSet(dst, ::nan(""), numVal); // any non-signalling nan will do LOG4CXX_WARN(SCALAPACKPHYSICAL_HPP_logger, "@@@@@@@@@@@@@ WARNING: prefill matrix memory with NaN for debug"); } LOG4CXX_DEBUG(SCALAPACKPHYSICAL_HPP_logger, "setInputMatrixToAlgebraDefault took " << timer.stop()); }
void SolveTheBGIP(BGIP_sharedPtr bgip) { // Specify the solution method. // (See above and in BGIP_SolverType.h) BGIP_SolverType::BGIP_Solver_t method = BGIP_SolverType::AM; try { Timing timer; timer.Start( SoftPrint(method) ); BayesianGameIdenticalPayoffSolver * bgip_solver = NewBGIPSolver(bgip, method); cout << "running " << SoftPrint(method) << "..."<<endl; cout << "...value is " << bgip_solver->Solve() << endl; timer.Stop( SoftPrint(method) ); delete bgip_solver; } catch(E& e) { e.Print(); } }
bool CompositorAnimationsImpl::convertTimingForCompositor(const Timing& timing, CompositorTiming& out) { timing.assertValid(); // All fill modes are supported (the calling code handles them). // FIXME: Support non-zero iteration start. if (timing.iterationStart) return false; // FIXME: Compositor only supports positive, integer iteration counts. // Zero iterations could be converted, but silly. if ((std::floor(timing.iterationCount) != timing.iterationCount) || timing.iterationCount <= 0) return false; if (std::isnan(timing.iterationDuration) || !timing.iterationDuration) return false; // FIXME: Support other playback rates if (timing.playbackRate != 1) return false; // All directions are supported. // Now attempt an actual conversion out.scaledDuration = timing.iterationDuration; ASSERT(out.scaledDuration > 0); double scaledStartDelay = timing.startDelay; if (scaledStartDelay > 0 && scaledStartDelay > out.scaledDuration * timing.iterationCount) return false; out.reverse = (timing.direction == Timing::PlaybackDirectionReverse || timing.direction == Timing::PlaybackDirectionAlternateReverse); out.alternate = (timing.direction == Timing::PlaybackDirectionAlternate || timing.direction == Timing::PlaybackDirectionAlternateReverse); if (!std::isfinite(timing.iterationCount)) { out.adjustedIterationCount = -1; } else { out.adjustedIterationCount = std::floor(timing.iterationCount); ASSERT(out.adjustedIterationCount > 0); } // Compositor's time offset is positive for seeking into the animation. out.scaledTimeOffset = -scaledStartDelay; return true; }
int main(){ Timing timer; #ifdef _DEBUG int size = 4;{ #else for(int size=1; size>0; size*=2){ #endif std::cout << "size: " << size << '\n'; const int times = 10; Matrix a, b; a.resize(size); b.resize(size); a.randomize(); b.randomize(); timer.setDivisor(times); timer.start(); for(int i=0; i<times; i++){ Matrix c = MatrixMultiplication::recursive(a, b); #ifdef _DEBUG c.print(); #endif } timer.end(); timer.reportCPUtime(); timer.start(); for(int i=0; i<times; i++){ Matrix c = MatrixMultiplication::strassen(a, b); #ifdef _DEBUG c.print(); #endif } timer.end(); timer.reportCPUtime(); } return system("pause"); }
float AnalyzeResponseUniformity::getFitBoundary(std::string &strInputExp, std::shared_ptr<TH1F> hInput, TSpectrum &specInput){ //Variable Declaration map<string, float> map_key2Val; //Search the input expression for each of the supported keywords //Store these Keywords with their values for (int i=0; i < vec_strSupportedKeywords.size(); ++i) { //Loop Through Supported Keywords if ( strInputExp.find( vec_strSupportedKeywords[i] ) != std::string::npos ) { //Case: Keyword Found! map_key2Val[vec_strSupportedKeywords[i]] = getValByKeyword( vec_strSupportedKeywords[i], hInput, specInput ); } //End Case: Keyword Found! } //End Loop Through Supported Keywords //Check if map_key2Val has any entries, if so user requested complex expression; parse! //If map_key2Val is empty, user has a numeric input; convert to float! if (map_key2Val.size() > 0) { //Case: Complex Expression! //Setup the expression parser symbol_table_t symbol_table; //Stores the variables in expression and maps them to C++ objects expression_t expression; //Stores the actual expression & the symbol table parser_t parser; //Parses the information for evaluation //Load all found keywords into the symbol table for (auto iterMap = map_key2Val.begin(); iterMap != map_key2Val.end(); ++iterMap) { symbol_table.add_variable( (*iterMap).first, (*iterMap).second); } //Give the expression the variables it should have expression.register_symbol_table(symbol_table); //Compile the parsing parser.compile(strInputExp, expression); //Return value to the user return expression.value(); } //End Case: Complex Expression! else{ //Case: Numeric Input return stofSafe( strInputExp ); } //End Case: Numeric Input } //End AnalyzeResponseUniformity::getFitBoundary()
int main() { /******************************* [ signal ] ******************************/ Type a = 0; Type b = Ls-1; Vector<Type> t = linspace(a,b,Ls) / Type(Fs); Vector<Type> s = sin( Type(400*PI) * pow(t,Type(2.0)) ); /******************************** [ widow ] ******************************/ a = 0; b = Type(Lg-1); Type u = (Lg-1)/Type(2); Type r = Lg/Type(8); t = linspace(a,b,Lg); Vector<Type> g = gauss(t,u,r); g = g/norm(g); /********************************* [ WFT ] *******************************/ Type runtime = 0; Timing cnt; cout << "Taking windowed Fourier transform." << endl; cnt.start(); Matrix< complex<Type> > coefs = wft( s, g ); cnt.stop(); runtime = cnt.read(); cout << "The running time = " << runtime << " (ms)" << endl << endl; /******************************** [ IWFT ] *******************************/ cout << "Taking inverse windowed Fourier transform." << endl; cnt.start(); Vector<Type> x = iwft( coefs, g ); cnt.stop(); runtime = cnt.read(); cout << "The running time = " << runtime << " (ms)" << endl << endl; cout << "The relative error is : " << "norm(s-x) / norm(s) = " << norm(s-x)/norm(s) << endl << endl; return 0; }
void setOutputMatrixToAlgebraDefault(float_tt* dst, size_t numVal, log4cxx::LoggerPtr logger) { Timing timer; valsSet(dst, ::nan(""), numVal); // ScaLAPACK algorithm should provide all entries in matrix LOG4CXX_DEBUG(SCALAPACKPHYSICAL_HPP_logger, "setOutputMatrixToAlgebraDefault took " << timer.stop()); }
int main(int argc, char** argv) { Timing t; int i; // TODO: debug should be enabled with a command-line option // FILELog::ReportingLevel() = FILELog::FromString("DEBUG4"); // FILELog::ReportingLevel() = FILELog::FromString("DEBUG1"); FILELog::ReportingLevel() = FILELog::FromString("INFO"); FILE_LOG(logDEBUG4) << "starting"; t.Start(); try { Picoscope6000 *pico = new Picoscope6000(); Measurement *meas = new Measurement(pico); Channel *ch[4]; meas->SetTimebaseInPs(400); meas->EnableChannels(true,false,false,false); for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { ch[i] = meas->GetChannel(i); FILE_LOG(logDEBUG4) << "main - Channel " << (char)('A'+i) << " has index " << ch[i]->GetIndex(); } Args x; x.parse_options(argc, argv, meas); if(x.IsJustHelp()) { return 0; } if(x.GetFilename() == NULL) { // TODO: maybe we want to use just text file throw("You have to provide some filename using '--name <filename>'.\n"); } // meas->SetTimebaseInPs(10000); // TODO: fixme for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { ch[i]->SetVoltage(x.GetVoltage()); } // a->SetVoltage(U_100mV); // a[0]->SetVoltage(x.GetVoltage()); // meas->SetLength(GIGA(1)); meas->SetLength(x.GetLength()); if(x.GetNTraces() > 1) { meas->SetNTraces(x.GetNTraces()); // TODO: fix trigger FILE_LOG(logDEBUG4) << "main - checking for triggered events"; if(x.IsTriggered()) { for(i=0; i<PICOSCOPE_N_CHANNELS && !(ch[i]->IsEnabled()); i++); FILE_LOG(logDEBUG4) << "main - will trigger on channel " << (char)('A'+i); meas->SetTrigger(x.GetTrigger(ch[i])); } meas->AllocateMemoryRapidBlock(MEGA(50)); } else { meas->AllocateMemoryBlock(MEGA(50)); } // std::cerr << "test w5\n"; // it only makes sense to measure if we decided to use some positive number of samples if(x.GetLength()>0) { FILE *f = NULL; FILE *fb[4] = {NULL,NULL,NULL,NULL}, *ft[4] = {NULL,NULL,NULL,NULL}; struct tm *current; time_t now; time(&now); current = localtime(&now); for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { if(ch[i]->IsEnabled()) { if(x.IsTextOutput()) { ft[i] = fopen(x.GetFilenameText(i), "wt"); if(ft[i] == NULL) { throw("Unable to open text file.\n"); // TODO: write filename } } if(x.IsBinaryOutput()) { fb[i] = fopen(x.GetFilenameBinary(i), "wb"); if(fb[i] == NULL) { throw("Unable to open binary file.\n"); // TODO: write filename } } } } /************************************************************/ double tmp_dbl; short tmp_short; pico->Open(); meas->InitializeSignalGenerator(); meas->RunBlock(); /* metadata */ f = fopen(x.GetFilenameMeta(), "wt"); if(f == NULL) { throw("Unable to open file with metadata.\n"); } fprintf(f, "command: "); for(i=0; i<argc; i++) { fprintf(f, " %s", argv[i]); } fprintf(f, "\n"); fprintf(f, "timestamp: %d-%02d-%02d %02d:%02d:%02d\n\n", current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour, current->tm_min, current->tm_sec); fprintf(f, "channels: "); for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { if(ch[i]->IsEnabled()) { fprintf(f, "%c", 'A'+i); } } fprintf(f, "\n"); fprintf(f, "length: %ld\n", x.GetLength()); fprintf(f, "samples: %ld\n", x.GetNTraces()); // fprintf(f, "unit_x: %.1lf ns | %.1lf ns\n", meas->GetTimebaseInNs(), meas->GetReportedTimebaseInNs()); tmp_dbl = meas->GetTimebaseInNs(); fprintf(f, "unit_x: %.1lf ns\n", tmp_dbl); fprintf(f, "range_x: %.1lf ns\n", x.GetLength()*tmp_dbl); tmp_dbl = x.GetVoltageDouble(); fprintf(f, "unit_y: %.10le V\n", tmp_dbl*3.0757874015748e-5); // 1/(127*256) actually, but this might have to be fixed for series 4000 fprintf(f, "range_y: %g V\n", tmp_dbl); if(x.GetNTraces() > 1) { if(x.IsTriggered()) { fprintf(f, "trigger_ch: %c\n", (char)(meas->GetTrigger()->GetChannel()->GetIndex()+'A')); // fprintf(f, "trigger_xfrac: %g\n", meas->GetTrigger()->GetXFraction()); // fprintf(f, "trigger_yfrac: %g\n", meas->GetTrigger()->GetYFraction()); fprintf(f, "trigger_dx: %d (%g %% of %ld)\n", meas->GetLengthBeforeTrigger(), meas->GetLengthBeforeTrigger()*100.0/x.GetLength(), x.GetLength()); tmp_short = meas->GetTrigger()->GetThreshold(); tmp_dbl = meas->GetTrigger()->GetYFraction(); fprintf(f, "trigger_dy: %g V (%d)\n", meas->GetTrigger()->GetThresholdInVolts() /*tmp_dbl*x.GetVoltageDouble()*/, tmp_short); } } // fprintf(f, "unit_x: %.1lf ns | %.1lf ns\n", meas->GetTimebaseInNs(), meas->GetReportedTimebaseInNs()); fprintf(f, "out_bin: %s\n", x.IsBinaryOutput() ? "yes" : "no"); fprintf(f, "out_dat: %s\n", x.IsTextOutput() ? "yes" : "no"); // triggered (TODO: we could also ask for a single triggered event) if(x.GetNTraces() > 1) { unsigned int run=0; for(run=0; run<x.GetNRepeats() && !_kbhit(); run++) { //FILE_LOG(logINFO) << "Running experiment nr. " << run+1; if(run>0) { cerr << "\nRepeat #" << run+1 << endl; meas->RunBlock(); } while(meas->GetNextDataBulk() > 0) { for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { if(ch[i]->IsEnabled()) { if(x.IsTextOutput()) { meas->WriteDataTxt(ft[i], i); // zero for channel A } if(x.IsBinaryOutput()) { meas->WriteDataBin(fb[i], i); // zero for channel A } } } } } if(run>1) { fprintf(f, "repeats: %u\n", run); } // tmp_dbl = meas->GetRatePerSecond(); // fprintf(f, "\nrate: \n"); // if(fabs(tmp_dbl) > 1e6) { // fprintf(f, "%.3f MS/s\n", tmp_dbl*1e-6); // } else if(fabs(tmp_dbl) > 1e3) { // fprintf(f, "%.3f kS/s\n", tmp_dbl*1e-3); // } else { // fprintf(f, "%f S/s\n", tmp_dbl); // } } else { unsigned int run=0; for(run=0; run<x.GetNRepeats() && !_kbhit(); run++) { if(run>0) { cerr << "\nRepeat #" << run+1 << endl; meas->RunBlock(); } while(meas->GetNextData() > 0) { for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { if(ch[i]->IsEnabled()) { if(x.IsTextOutput()) { meas->WriteDataTxt(ft[i], i); // zero for channel A } if(x.IsBinaryOutput()) { meas->WriteDataBin(fb[i], i); // zero for channel A } } } } } if(run>1) { fprintf(f, "repeats: %u\n", run); } } fclose(f); for(i=0; i<PICOSCOPE_N_CHANNELS; i++) { if(ft[i] != NULL) { fclose(ft[i]); } if(fb[i] != NULL) { fclose(fb[i]); } } // apparently this doesn't work for some weird reason // meas->RunBlock(); meas->GetNextData(); // meas->RunBlock(); meas->GetNextData(); // meas->RunBlock(); meas->GetNextData(); // meas->RunBlock(); meas->GetNextData(); pico->Close(); t.Stop(); cerr << "Timing: " << t.GetSecondsDouble() << "s\n"; } delete pico; pico = NULL; delete meas; meas = NULL; } catch(Picoscope::PicoscopeException& ex) { cerr << "Some picoscope exception:" << endl << "Error number " << ex.GetErrorNumber() << ": " << ex.GetErrorMessage() << endl << '(' << ex.GetVerboseErrorMessage() << ')' << endl; try { // pico.Close(); } catch(...) {} } catch(Picoscope::PicoscopeUserException& ex) { cerr << "Some exception:" << endl << ex.GetErrorMessage() << endl; // catch any exceptions } catch(const char* s) { cerr << "Some exception has occurred:\n" << s << endl; } catch (std::bad_alloc& ba) { std::cerr << "Exception: bad_alloc: " << ba.what() << endl; } catch (const std::exception &exc) { // catch anything thrown within try block that derives from std::exception std::cerr << "Exception: " << exc.what() << endl; } catch(...) { cerr << "Some exception has occurred" << endl; } return 0; }
int main(int argc, char **argv) { DecPOMDPDiscreteInterface* decpomdp; try { ArgumentHandlers::Arguments args; argp_parse (&ArgumentHandlers::theArgpStruc, argc, argv, 0, 0, &args); Timing times; times.Start("Parsing"); //DecPOMDPDiscreteInterface* decpomdp = GetDecPOMDPDiscreteInterfaceFromArgs(args); TransitionObservationIndependentMADPDiscrete *toi=0; if((toi=dynamic_cast<TransitionObservationIndependentMADPDiscrete*>(decpomdp)) && args.qheur==eQMDP && !args.cache_flat_models /* otherwise * GetDecPOMDPDiscreteInterfaceFromArgs * already caches the flat * models */) { // we don't need a centralized obs model toi->CreateCentralizedSparseTransitionModel(); } times.Stop("Parsing"); if(!args.dryrun) directories::MADPCreateResultsDir("GMAA",*decpomdp); size_t horizon; if(args.infiniteHorizon) horizon=MAXHORIZON; else horizon=args.horizon; times.Start("Overall"); PlanningUnitMADPDiscreteParameters params; #if 0 // Caching doesn't seem worth the trouble if we're computing // just one thing (not to mention the memory savings) if(Qheur==eQMDP) // don't need any of this for solving the MDP params.SetComputeAll(false); else { params.SetComputeAll(true); params.SetUseSparseJointBeliefs(true); } #else params.SetComputeAll(false); if(args.sparse) params.SetUseSparseJointBeliefs(true); #endif times.Start("PlanningUnit"); NullPlanner np(params,horizon,decpomdp); times.Stop("PlanningUnit"); struct timeval tvStart, tvEnd; gettimeofday (&tvStart, NULL); QFunctionJAOHInterface* q=0; for(int restartI = 0; restartI < args.nrRestarts; restartI++) { // with hybrid heuristics already some computation is done // before Compute(), so start timing now times.Start("ComputeQ"); q = GetQheuristicFromArgs(&np, args); q->Compute(); times.Stop("ComputeQ"); // we want to keep the last q computed if(restartI<(args.nrRestarts-1)) delete q; } gettimeofday (&tvEnd, NULL); clock_t wallclockTime = static_cast<clock_t>(((tvEnd.tv_sec - tvStart.tv_sec) + static_cast<double>(tvEnd.tv_usec-tvStart.tv_usec)/1e6) * sysconf(_SC_CLK_TCK)); cout << "Wallclock: from " << tvStart.tv_sec << "." << tvStart.tv_usec << " until " << tvEnd.tv_sec << "." << tvEnd.tv_usec << " which took " << wallclockTime << " clock ticks" << endl; times.AddEvent("WallclockTime", wallclockTime); if(!args.dryrun) { times.Start("Save"); q->Save(); times.Stop("Save"); if(args.verbose >= 0) cout << "Q saved to " << q->GetCacheFilename() << endl; } times.Stop("Overall"); if(args.verbose >= 0) times.PrintSummary(); if(!args.dryrun) { stringstream ss; ss << directories::MADPGetResultsDir("GMAA",*decpomdp) << "/calculateQheuristic" << q->SoftPrintBrief() << "_h" << horizon; if(decpomdp->GetDiscount()!=1) ss << "_g" << decpomdp->GetDiscount(); ss << "_Timings"; times.Save(ss.str()); if(args.verbose >= 0) cout << "Timings saved to " << ss.str() << endl; } if(horizon!=MAXHORIZON) { double Vjb0=-DBL_MAX; for(Index a=0;a!=np.GetNrJointActions();++a) Vjb0=max(q->GetQ(Globals::INITIAL_JAOHI,a),Vjb0); cout << "Value of jaohI 0 = " << Vjb0 << endl; } delete q; } catch(E& e){ e.Print(); } cout << "cleanup..." << endl; delete decpomdp; }
int main() { /******************************* [ signal ] ******************************/ Vector<double> t = linspace( 0.0, (Ls-1)/fs, Ls ); Vector<double> st = sin( 200*PI*pow(t,2.0) ); st = st-mean(st); /******************************** [ CWT ] ********************************/ Matrix< complex<double> > coefs; CWT<double> wavelet("morlet"); wavelet.setScales( fs, fs/Ls, fs/2 ); Timing cnt; double runtime = 0.0; cout << "Taking continuous wavelet transform(Morlet)." << endl; cnt.start(); coefs = wavelet.cwtC(st); cnt.stop(); runtime = cnt.read(); cout << "The running time = " << runtime << " (ms)" << endl << endl; /******************************** [ ICWT ] *******************************/ cout << "Taking inverse continuous wavelet transform." << endl; cnt.start(); Vector<double> xt = wavelet.icwtC(coefs); cnt.stop(); runtime = cnt.read(); cout << "The running time = " << runtime << " (ms)" << endl << endl; cout << "The relative error is : " << endl; cout << "norm(st-xt) / norm(st) = " << norm(st-xt)/norm(st) << endl; cout << endl << endl; /******************************* [ signal ] ******************************/ Vector<float> tf = linspace( float(0.0), (Ls-1)/float(fs), Ls ); Vector<float> stf = sin( float(200*PI) * pow(tf,float(2.0) ) ); stf = stf-mean(stf); /******************************** [ CWT ] ********************************/ CWT<float> waveletf("mexiHat"); waveletf.setScales( float(fs), float(fs/Ls), float(fs/2), float(0.25) ); runtime = 0.0; cout << "Taking continuous wavelet transform(Mexican Hat)." << endl; cnt.start(); Matrix<float> coefsf = waveletf.cwtR(stf); cnt.stop(); runtime = cnt.read(); cout << "The running time = " << runtime << " (ms)" << endl << endl; /******************************** [ ICWT ] *******************************/ cout << "Taking inverse continuous wavelet transform." << endl; cnt.start(); Vector<float> xtf = waveletf.icwtR(coefsf); cnt.stop(); runtime = cnt.read(); cout << "The running time = " << runtime << " (ms)" << endl << endl; cout << "The relative error is : " << endl; cout << "norm(st-xt) / norm(st) = " << norm(stf-xtf)/norm(stf) << endl << endl; return 0; }
//Opens a text file set by the user and loads the requested parameters void ParameterLoaderAnaysis::loadAnalysisParameters(string & strInputSetupFile, AnalysisSetupUniformity &aSetupUniformity){ //Variable Declaration bool bExitSuccess = false; pair<string,string> pair_strParam; //Input file is setup in <Field, Value> pairs; not used here yet but placeholder string strLine = ""; //Line taken from the input file //string strHeading = ""; //For storing detector heading vector<string> vec_strList; //For storing char separated input; not used here yet but placeholder //Open the Data File //------------------------------------------------------ if (bVerboseMode_IO) { //Case: User Requested Verbose Error Messages - I/O printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParameters", ("trying to open and read: " + strInputSetupFile).c_str() ); } //End Case: User Requested Verbose Error Messages - I/O ifstream fStream( strInputSetupFile.c_str() ); //Check to See if Data File Opened Successfully //------------------------------------------------------ if (!fStream.is_open() && bVerboseMode_IO) { perror( ("Uniformity::ParameterLoaderAnaysis::loadAnalysisParameters(): error while opening file: " + strInputSetupFile).c_str() ); printStreamStatus(fStream); } ////Loop Over data Input File //------------------------------------------------------ //Read the file via std::getline(). Obey good coding practice rules: // -first the I/O operation, then error check, then data processing // -failbit and badbit prevent data processing, eofbit does not //See: http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror/ while ( getlineNoSpaces(fStream, strLine) ) { //Reset exit flag used in string manipulation bExitSuccess = false; //Does the user want to comment out this line? if ( 0 == strLine.compare(0,1,"#") ) continue; //Debugging cout<<"strLine = " << strLine.c_str() << endl; //Identify Section Headers if ( 0 == strLine.compare(strSecEnd_Analysis) ) { //Case: Reached End of File //Debugging cout<<"Found End of Analysis Section"<<endl; break; } //End Case: Reached End of File else if ( 0 == strLine.compare(strSecBegin_Analysis) ) { //Case: Analysis Header //Filler for now; intentionally empty } //End Case: Analysis Header else if ( 0 == strLine.compare(strSecBegin_Timing) ) { //Case: Timing Parameters //Debugging cout<<"Found Start of Timing Section"<<endl; loadAnalysisParametersTiming(fStream, aSetupUniformity); } //End Case: Timing Parameters else if ( 0 == strLine.compare(strSecBegin_Uniformity) ) { //Case: Uniformity Parameters //Debugging cout<<"Found Start of Uniformity Section"<<endl; loadAnalysisParametersUniformity(fStream, aSetupUniformity); } //End Case: Uniformity Parameters else { //Case: Unsorted Parameters //Filler for now; intentionally empty but may return to it later } //End Case: Unsorted Parameters } //End Loop Over Input File //Check to see if we had problems while reading the file if (fStream.bad() && bVerboseMode_IO) { perror( ("Uniformity::ParameterLoaderAnaysis::loadAnalysisParameters(): error while reading file: " + strInputSetupFile).c_str() ); printStreamStatus(fStream); } return; } //End ParameterLoaderAnaysis::loadAnalysisParameters()
int main(int argc, char* argv[]) { char* myString; int* suffixArray; int stringLength; int i; ifstream inFile; inFile.open(argv[1]); Timing timehere; if (strcmp(argv[1], "test.dat") != 0) { timehere.markbeg(); if (strstr(argv[1], ".fas")[0] == '.') { read_fasta(inFile, myString, stringLength); } else { read_input(inFile, myString, stringLength); } timehere.markend(); inFile.close(); cout << "finish read " << stringLength << " characters."<< endl; timehere.outtime(); } else { read_input(inFile, myString, stringLength); inFile.close(); cout << "finish read " << stringLength << " characters."<< endl; } timehere.markbeg(); suffixArray = LinearSuffixSort(myString, stringLength); timehere.markend(); timehere.outtime("finish suffix sort,"); if (strcmp(argv[1], "test.dat") == 0) { int result; bool pass = true; ifstream resultF; resultF.open("result.test.dat"); cout << "Testing the Suffix Array" << endl; for (i = 0; i < stringLength; i++) { resultF >> result; if (result != suffixArray[i]) { pass = false; } } if (pass == false) { cout << endl; cout << "***************" << endl; cout << "test has failed" << endl; cout << "***************" << endl; } else { cout << endl; cout << "******************" << endl; cout << "test is successful" << endl; cout << "******************" << endl; } }
void ParameterLoaderAnaysis::loadAnalysisParametersHistograms(ifstream &inputFileStream, HistoSetup &hSetup){ //Variable Declaration bool bExitSuccess; pair<string,string> pair_strParam; string strLine; vector<string> vec_strList; //Loop through the section while ( getlineNoSpaces(inputFileStream, strLine) ) { bExitSuccess = false; //Debugging //cout<<"loadAnalysisParametersHistograms (Base Level); strLine = " << strLine << endl; //Does the user want to comment out this line? if ( 0 == strLine.compare(0,1,"#") ) continue; //Has this section ended? if ( 0 == strLine.compare(strSecEnd_Uniformity_Hiso) ) break; //Get Parameter Pairing pair_strParam = Timing::getParsedLine(strLine, bExitSuccess); //transform field name to upper case transform(pair_strParam.first.begin(),pair_strParam.first.end(),pair_strParam.first.begin(),toupper); //Parse pair if (bExitSuccess) { //Case: Parameter Fetched Successfully if( 0 == pair_strParam.first.compare("HISTO_BINRANGE") ){ //Get comma separated list vec_strList = Timing::getCharSeparatedList(pair_strParam.second,','); //Debugging //for(int i=0; i<vec_strList.size(); ++i){ // cout<<"vec_strList["<<i<<"] = " << vec_strList[i] << endl; //} if (vec_strList.size() >= 2) { //Case: at least 2 numbers //Fetch hSetup.fHisto_xLower = Timing::stofSafe(pair_strParam.first, vec_strList[0]); hSetup.fHisto_xUpper = Timing::stofSafe(pair_strParam.first, vec_strList[1]); //Reset to ensure they are both correctly lower & upper values hSetup.fHisto_xLower = std::min(hSetup.fHisto_xLower, hSetup.fHisto_xUpper); hSetup.fHisto_xUpper = std::max(hSetup.fHisto_xLower, hSetup.fHisto_xUpper); //Tell the user they entered more than what was expected if (vec_strList.size() > 2) { //Case: 3 or more numbers printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ( "Sorry you entered 3 or more numbers for " + pair_strParam.first + "\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", "\tI have only used the first two and ignored the rest:\n" ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ("\t" + getString( hSetup.fHisto_xLower ) ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ("\t" + getString( hSetup.fHisto_xUpper ) ).c_str() ); } //End Case: 3 or more numbers } //End Case: at least 2 numbers else{ //Case: Not enough numbers if (vec_strList.size() == 1) { //Case: only 1 number entered hSetup.fHisto_xUpper = Timing::stofSafe(pair_strParam.first, vec_strList[0]); } //End Case: only 1 number entered //Reset to ensure they are both correctly lower & upper values hSetup.fHisto_xLower = std::min(hSetup.fHisto_xLower, hSetup.fHisto_xUpper); hSetup.fHisto_xUpper = std::max(hSetup.fHisto_xLower, hSetup.fHisto_xUpper); //Output to User printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ( "Sorry I was expecting a comma separated list of 2 numbers for: " + pair_strParam.first + "\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", "\tRight now I have set:\n" ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ("\t" + getString( hSetup.fHisto_xLower ) ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ("\t" + getString( hSetup.fHisto_xUpper ) ).c_str() ); } //End Case: Not enough numbers } //End Case: Assign Histo Bin Range /*else if( 0 == pair_strParam.first.compare("HISTO_NAME") ) { hSetup.strHisto_Name = pair_strParam.second; }*/ else if( 0 == pair_strParam.first.compare("HISTO_NUMBINS") ){ hSetup.iHisto_nBins = Timing::stoiSafe(pair_strParam.first, pair_strParam.second); } else if( 0 == pair_strParam.first.compare("HISTO_XTITLE") ){ hSetup.strHisto_Title_X = pair_strParam.second; } else if( 0 == pair_strParam.first.compare("HISTO_YTITLE") ){ hSetup.strHisto_Title_Y = pair_strParam.second; } else if( 0 == pair_strParam.first.compare("PERFORM_FIT") ){ hSetup.bFit = convert2bool(pair_strParam.second, bExitSuccess); } else{ //Case: Parameter not recognized printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","Error!!! Parameter Not Recognized:\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms",( "\tField = " + pair_strParam.first + "\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms",( "\tValue = " + pair_strParam.second + "\n" ).c_str() ); } //End Case: Parameter not recognized } //End Case: Parameter Fetched Successfully else{ //Case: Parameter was NOT fetched Successfully printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","Error!!! I didn't parse parameter correctly\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms",("\tCurrent line: " + strLine).c_str() ); } //End Case: Parameter was NOT fetched Successfully } //End Loop through Section return; } //End ParameterLoaderAnalysis::loadAnalysisParametersHistograms() - Histogram specific
//Uniformity //Loads parameters defined in file read by inputFileStream and sets tehm to the aSetupUniformity //Note this should only be called within the Uniformity heading if the user has configured the file correctly void ParameterLoaderAnaysis::loadAnalysisParametersUniformity(ifstream &inputFileStream, AnalysisSetupUniformity &aSetupUniformity){ //Variable Declaration bool bExitSuccess = false; pair<string,string> pair_strParam; //Input file is setup in <Field, Value> pairs; not used here yet but placeholder //string strField = ""; //From input file we have <Field,Value> pairs string strLine = ""; //Line taken from the input file //string strHeading = ""; //For storing detector heading vector<string> vec_strList; //For storing char separated input; not used here yet but placeholder if (bVerboseMode_IO) { //Case: User Requested Verbose Error Messages - I/O printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity", "Found Uniformity Heading"); } //End Case: User Requested Verbose Error Messages - I/O while ( getlineNoSpaces(inputFileStream, strLine) ) { //Does the user want to comment out this line? if ( 0 == strLine.compare(0,1,"#") ) continue; //Do we reach the end of the section? if ( 0 == strLine.compare(strSecEnd_Uniformity ) ) break; //Should we be storing histogram/fit setup parameters? if ( 0 == strLine.compare(strSecBegin_Uniformity_Fit) ) { //Case: Fit Setup loadAnalysisParametersFits(inputFileStream, aSetupUniformity.histoSetup_clustADC); continue; //Tell it to move to the next loop iteration (e.g. line in file) } //End Case: Fit Setup else if( 0 == strLine.compare(strSecBegin_Uniformity_Histo) ){ //Case: Histo Setup loadAnalysisParametersHistograms(inputFileStream, aSetupUniformity); continue; //Tell it to move to the next loop iteration (e.g. line in file) } //End Case: Histo Setup //Debugging cout<<"strLine: = " << strLine.c_str() << endl; //Parse the line pair_strParam = getParsedLine(strLine,bExitSuccess); if (bExitSuccess) { //Case: Parameter Fetched Correctly //transform(pair_strParam.first.begin(), pair_strParam.second.end(),pair_strParam.first.begin(),toupper); string strTmp = pair_strParam.first; transform(strTmp.begin(), strTmp.end(), strTmp.begin(), toupper); pair_strParam.first = strTmp; //cout<<pair_strParam.first<<"\t"<<pair_strParam.second; if ( 0 == pair_strParam.first.compare("CUT_ADC_MIN") ) { aSetupUniformity.selClust.iCut_ADCNoise = stoiSafe(pair_strParam.first,pair_strParam.second); //cout<<"\t"<<aSetupUniformity.selClust.iCut_ADCNoise<<endl; } //End Case: Minimum ADC Value else if( 0 == pair_strParam.first.compare("CUT_CLUSTERMULTI_MIN") ){ //Case: Min Cluster Multiplicity aSetupUniformity.selClust.iCut_MultiMin = stoiSafe(pair_strParam.first,pair_strParam.second); } //End Case: Max Cluster Multiplicity else if( 0 == pair_strParam.first.compare("CUT_CLUSTERMULTI_MAX") ){ aSetupUniformity.selClust.iCut_MultiMax = stoiSafe(pair_strParam.first,pair_strParam.second); } //End Case: else if( 0 == pair_strParam.first.compare("CUT_CLUSTERSIZE_MIN") ) { aSetupUniformity.selClust.iCut_SizeMin = stoiSafe(pair_strParam.first,pair_strParam.second); //cout<<"\t"<<aSetupUniformity.selClust.iCut_SizeMin<<endl; } //End Case: Min Cluster Size else if( 0 == pair_strParam.first.compare("CUT_CLUSTERSIZE_MAX") ) { aSetupUniformity.selClust.iCut_SizeMax = stoiSafe(pair_strParam.first,pair_strParam.second); //cout<<"\t"<<aSetupUniformity.selClust.iCut_SizeMax<<endl; } //End Case: Max Cluster Size else if( 0 == pair_strParam.first.compare("CUT_CLUSTERTIME_MIN") ) { aSetupUniformity.selClust.iCut_TimeMin = stoiSafe(pair_strParam.first,pair_strParam.second); //cout<<"\t"<<aSetupUniformity.selClust.iCut_TimeMin<<endl; } //End Case: Min Cluster Time else if( 0 == pair_strParam.first.compare("CUT_CLUSTERTIME_MAX") ) { aSetupUniformity.selClust.iCut_TimeMax = stoiSafe(pair_strParam.first,pair_strParam.second); //cout<<"\t"<<aSetupUniformity.selClust.iCut_TimeMax<<endl; } //End Case: Max Cluster Time if( 0 == pair_strParam.first.compare("EVENT_FIRST") ){ //Case: ADC Spectrum Fit Equation aSetupUniformity.iEvt_First = stoiSafe(pair_strParam.second); } //End Case: ADC Spectrum Fit Equation else if( 0 == pair_strParam.first.compare("EVENT_TOTAL") ){ //Case: ADC Spectrum Fit Equation aSetupUniformity.iEvt_Total = stoiSafe(pair_strParam.second); } //End Case: ADC Spectrum Fit Equation else if( 0 == pair_strParam.first.compare("UNIFORMITY_GRANULARITY") ){ //Case: Uniformity Granularity aSetupUniformity.iUniformityGranularity = stoiSafe(pair_strParam.first,pair_strParam.second); } //End Case: Uniformity Granularity else if( 0 == pair_strParam.first.compare("UNIFORMITY_TOLERANCE") ){ //Case: Uniformity Granularity aSetupUniformity.fUniformityTolerance = stofSafe(pair_strParam.first,pair_strParam.second); } //End Case: Uniformity Granularity else{ //Case: Parameter Not Recognized printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity","Error!!! Parameter Not Recognizd:\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity",( "\tField = " + pair_strParam.first + "\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity",( "\tValue = " + pair_strParam.second + "\n" ).c_str() ); } //End Case: Parameter Not Recognized } //End Case: Parameter Fetched Correctly else{ //Case: Parameter Failed to fetch correctly printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity","Error!!! I didn't parse parameter correctly\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity",("\tCurrent line: " + strLine).c_str() ); } //End Case: Parameter Failed to fetch correctly } //End Loop through Uniformity Heading return; } //End ParameterLoaderAnaysis::loadAnalysisParametersUniformity()
void ParameterLoaderAnaysis::loadAnalysisParametersFits(ifstream & inputFileStream, HistoSetup &hSetup){ //Variable Declaration bool bExitSuccess = false; pair<string,string> pair_strParam; //Input file is setup in <Field, Value> pairs; not used here yet but placeholder string strLine = ""; //Line taken from the input file vector<string> vec_strList; //For storing char separated input; not used here yet but placeholder if (bVerboseMode_IO) { //Case: User Requested Verbose Error Messages - I/O printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersFits", "Found Fit Heading"); } //End Case: User Requested Verbose Error Messages - I/O while ( getlineNoSpaces(inputFileStream, strLine) ) { //Does the user want to comment out this line? if ( 0 == strLine.compare(0,1,"#") ) continue; //Do we reach the end of the section? if ( 0 == strLine.compare(strSecEnd_Uniformity_Fit ) ) break; //Debugging cout<<"strLine: = " << strLine.c_str() << endl; //Parse the line pair_strParam = getParsedLine(strLine,bExitSuccess); if (bExitSuccess) { //Case: Parameter Fetched Correctly //transform(pair_strParam.first.begin(), pair_strParam.second.end(),pair_strParam.first.begin(),toupper); string strTmp = pair_strParam.first; transform(strTmp.begin(), strTmp.end(), strTmp.begin(), toupper); pair_strParam.first = strTmp; //cout<<pair_strParam.first<<"\t"<<pair_strParam.second; if( 0 == pair_strParam.first.compare("FIT_FORMULA") ){ //Case: ADC Spectrum Fit Equation hSetup.strFit_Formula = pair_strParam.second; } //End Case: ADC Spectrum Fit Equation else if( 0 == pair_strParam.first.compare("FIT_OPTION") ){ //Case: ADC Spectrum Fit Equation hSetup.strFit_Option = pair_strParam.second; //Ensure that the result of the fit is returned in the TFitResultPtr by included the option "S" by default if (hSetup.strFit_Option.find("S") == std::string::npos ) { hSetup.strFit_Option = hSetup.strFit_Option + "S"; } } //End Case: ADC Spectrum Fit Equation else if( 0 == pair_strParam.first.compare("FIT_PARAM_IGUESS") ){ hSetup.vec_strFit_ParamIGuess = getCharSeparatedList(pair_strParam.second,','); } else if( 0 == pair_strParam.first.compare("FIT_PARAM_LIMIT_MAX") ){ hSetup.vec_strFit_ParamLimit_Max = getCharSeparatedList(pair_strParam.second, ','); } else if( 0 == pair_strParam.first.compare("FIT_PARAM_LIMIT_MIN") ){ hSetup.vec_strFit_ParamLimit_Min = getCharSeparatedList(pair_strParam.second, ','); } else if( 0 == pair_strParam.first.compare("FIT_PARAM_MAP") ){ hSetup.vec_strFit_ParamMeaning = Timing::getCharSeparatedList(pair_strParam.second,','); } else if( 0 == pair_strParam.first.compare("FIT_RANGE") ){ hSetup.vec_strFit_Range = getCharSeparatedList(pair_strParam.second, ','); } else{ //Case: Parameter Not Recognized printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersFits","Error!!! Parameter Not Recognizd:\n"); //printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersUniformity",( "\t(Field,Value) = (" + pair_strParam.first "," + pair_strParam.second + ")\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersFits",( "\tField = " + pair_strParam.first + "\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersFits",( "\tValue = " + pair_strParam.second + "\n" ).c_str() ); } //End Case: Parameter Not Recognized } //End Case: Parameter Fetched Correctly else{ //Case: Parameter Failed to fetch correctly printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersFits","Error!!! I didn't parse parameter correctly\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersFits",("\tCurrent line: " + strLine).c_str() ); } //End Case: Parameter Failed to fetch correctly } //End Loop through Fit Heading } //End ParameterLoaderAnaysis::loadAnalysisParametersFits
//Called when loading analysis parameters; relative to histograms //This is the top level method; this method calls loadAnalysisParametersHistograms(ifstream, Timing::HistoSetup) depending on which histogram is requested by the user void ParameterLoaderAnaysis::loadAnalysisParametersHistograms(ifstream & inputFileStream, AnalysisSetupUniformity &aSetupUniformity){ //Variable Declaration bool bExitSuccess = false; bool bSetup = false; pair<string,string> pair_strParam; //<Field, Value> string strName = ""; //What Histo Case should we create? string strLine = ""; string strTmp = ""; //Used for case insensitive comparison of strName //Loop through to find "Histo_Name" Should be the first one while ( getlineNoSpaces(inputFileStream, strLine) ) { //Loop through file to find "Histo_Name" //Debugging //cout<<"loadAnalysisParametersHistograms (Top Level); strLine = " << strLine << endl; //Does the user want to comment out this line? if ( 0 == strLine.compare(0,1,"#") ) continue; //Do we reach the end of the section? If so the user has configured the file incorrectly if ( 0 == strLine.compare(strSecEnd_Uniformity_Hiso) ) { //Section End Reached Prematurely printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","I have reached the END of a Histogram Heading\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","\tBut I Have NOT found the 'Histo_Name' field\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","\tYou have configured this heading incorrectly, the 'Histo_Name' field is expected to be the FIRST line after the Heading\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","\tThis object has been skipped, please cross-check\n"); //Exit the Loop to find "Detector_Name" break; } //End Case: Section End Reached Prematurely pair_strParam = getParsedLine(strLine,bExitSuccess); if (bExitSuccess) { //Case: Parameter Fetched Successfully transform(pair_strParam.first.begin(),pair_strParam.first.end(),pair_strParam.first.begin(),toupper); if ( 0 == pair_strParam.first.compare("HISTO_NAME") ) { //Case: Name found! //Store name locally & convert to upper case strName = pair_strParam.second; //Set the correct exit flag bSetup = true; //Exit the Loop to find "Detector_Name" break; } //End Case: Detector Name found! else{ //Case: Detector Name not found! printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","I am parsing a Histogram Heading\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","\tHowever I expected the 'Histo_Name' field to be the first line after the heading\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ( "\tThe current line I am parsing: " + strLine ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","\tHas been skipped and may lead to undefined behavior"); } //End Case: Name not found! }//End Case: Parameter Fetched Successfully else{ //Case: Parameter was NOT fetched Successfully printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms","Sorry I didn't parse parameter correctly\n"); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ( "\tCurrent line: " + strLine ).c_str() ); } //End Case: Parameter was NOT fetched Successfully } //Loop through file to find "Name" //Fetch the values for the map for the correct case if (bSetup) { //Case: Setup Correct strTmp = strName; transform(strTmp.begin(), strTmp.end(), strTmp.begin(), toupper); if (0 == strTmp.compare("CLUSTADC") ) { //Case: Cluster ADC's aSetupUniformity.histoSetup_clustADC.strHisto_Name = strName; loadAnalysisParametersHistograms(inputFileStream, aSetupUniformity.histoSetup_clustADC); } //End Case: Cluster ADC's else if (0 == strTmp.compare("CLUSTMULTI") ) { //Case: Cluster Multi aSetupUniformity.histoSetup_clustMulti.strHisto_Name = strName; loadAnalysisParametersHistograms(inputFileStream, aSetupUniformity.histoSetup_clustMulti); } //End Case: Cluster Multi else if (0 == strTmp.compare("CLUSTPOS") ) { //Case: Cluster Position aSetupUniformity.histoSetup_clustPos.strHisto_Name = strName; loadAnalysisParametersHistograms(inputFileStream, aSetupUniformity.histoSetup_clustPos); } //End Case: Cluster Position else if (0 == strTmp.compare("CLUSTSIZE") ) { //Case: Cluster Size aSetupUniformity.histoSetup_clustSize.strHisto_Name = strName; loadAnalysisParametersHistograms(inputFileStream, aSetupUniformity.histoSetup_clustSize); } //End Case: Cluster Size else if (0 == strTmp.compare("CLUSTTIME") ) { //Case: Cluster Time aSetupUniformity.histoSetup_clustTime.strHisto_Name = strName; loadAnalysisParametersHistograms(inputFileStream, aSetupUniformity.histoSetup_clustTime); } //End Case: Cluster Time else{ //Case: Undefined Behavior printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", ( "Histogram Type" + strName + " Not Recognized\n" ).c_str() ); printClassMethodMsg("ParameterLoaderAnaysis","loadAnalysisParametersHistograms", "\tI Only Support Case-Insenstive versions from this set {CLUSTADC, CLUSTMULTI, CLUSTPOS, CLUSTSIZE, CLUSTTIME}\n"); } //End Case: Undefined Behavior } //End Case: Setup Correct return; } //End ParameterLoaderAnaysis::loadAnalysisParametersHistograms() - Top Level
// Returns the default timing function. const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing, bool& isPaused) { if (animationData->isDelaySet()) timing.startDelay = animationData->delay(); if (animationData->isDurationSet()) { timing.iterationDuration = animationData->duration(); timing.hasIterationDuration = true; } if (animationData->isIterationCountSet()) { if (animationData->iterationCount() == CSSAnimationData::IterationCountInfinite) timing.iterationCount = std::numeric_limits<double>::infinity(); else timing.iterationCount = animationData->iterationCount(); } if (animationData->isFillModeSet()) { switch (animationData->fillMode()) { case AnimationFillModeForwards: timing.fillMode = Timing::FillModeForwards; break; case AnimationFillModeBackwards: timing.fillMode = Timing::FillModeBackwards; break; case AnimationFillModeBoth: timing.fillMode = Timing::FillModeBoth; break; case AnimationFillModeNone: timing.fillMode = Timing::FillModeNone; break; default: ASSERT_NOT_REACHED(); } } else { timing.fillMode = Timing::FillModeNone; } if (animationData->isDirectionSet()) { switch (animationData->direction()) { case CSSAnimationData::AnimationDirectionNormal: timing.direction = Timing::PlaybackDirectionNormal; break; case CSSAnimationData::AnimationDirectionAlternate: timing.direction = Timing::PlaybackDirectionAlternate; break; case CSSAnimationData::AnimationDirectionReverse: timing.direction = Timing::PlaybackDirectionReverse; break; case CSSAnimationData::AnimationDirectionAlternateReverse: timing.direction = Timing::PlaybackDirectionAlternateReverse; break; default: ASSERT_NOT_REACHED(); } } // For CSS, the constraints on the timing properties are tighter than in // the general case of the Web Animations model. timing.assertValid(); ASSERT(!timing.iterationStart); ASSERT(timing.playbackRate == 1); ASSERT(timing.iterationDuration >= 0 && std::isfinite(timing.iterationDuration)); isPaused = animationData->isPlayStateSet() && animationData->playState() == AnimPlayStatePaused; return animationData->isTimingFunctionSet() ? animationData->timingFunction() : CSSAnimationData::initialAnimationTimingFunction(); }
//Loops over all stored clusters in detMPGD and Book histograms for the full detector void AnalyzeResponseUniformity::fillHistos(){ //Variable Declaration //vector<Cluster> vec_clust; //Initialize Summary Histograms //hEta_v_SliceNum_Occupancy = std::make_shared<TH2F>( TH2F("hEta_v_SliceNum_Occupancy","",3. * aSetup.iUniformityGranularity, 1, 3. * aSetup.iUniformityGranularity + 1, detMPGD.map_sectorsEta.size(), 1, detMPGD.map_sectorsEta.size() + 1 ) ); //Loop Over Stored iEta Sectors for (auto iterEta = detMPGD.map_sectorsEta.begin(); iterEta != detMPGD.map_sectorsEta.end(); ++iterEta) { //Loop Over iEta Sectors //Grab Eta Sector width (for ClustPos Histo) aSetup.histoSetup_clustPos.fHisto_xLower = -0.5*(*iterEta).second.fWidth; aSetup.histoSetup_clustPos.fHisto_xUpper = 0.5*(*iterEta).second.fWidth; //Initialize iEta Histograms - 1D (*iterEta).second.hEta_ClustADC = make_shared<TH1F>(getHistogram((*iterEta).first, -1, aSetup.histoSetup_clustADC ) ); (*iterEta).second.hEta_ClustMulti = make_shared<TH1F>(getHistogram((*iterEta).first, -1, aSetup.histoSetup_clustMulti ) ); (*iterEta).second.hEta_ClustPos = make_shared<TH1F>(getHistogram((*iterEta).first, -1, aSetup.histoSetup_clustPos ) ); (*iterEta).second.hEta_ClustSize = make_shared<TH1F>(getHistogram((*iterEta).first, -1, aSetup.histoSetup_clustSize ) ); (*iterEta).second.hEta_ClustTime = make_shared<TH1F>(getHistogram((*iterEta).first, -1, aSetup.histoSetup_clustTime ) ); //Initialize iEta Histograms - 2D (*iterEta).second.hEta_ClustADC_v_ClustPos = make_shared<TH2F>( TH2F( ("hiEta" + getString( (*iterEta).first ) + "_ClustADC_v_ClustPos").c_str(),"Response Uniformity", 3. * aSetup.iUniformityGranularity,-0.5*(*iterEta).second.fWidth,0.5*(*iterEta).second.fWidth,300,0,15000) ); (*iterEta).second.hEta_ClustADC_v_ClustPos->Sumw2(); //Debugging //cout<<"(*iterEta).second.hEta_ClustADC->GetName() = " << (*iterEta).second.hEta_ClustADC->GetName() << endl; //Loop Over Stored iPhi Sectors for (auto iterPhi = (*iterEta).second.map_sectorsPhi.begin(); iterPhi != (*iterEta).second.map_sectorsPhi.end(); ++iterPhi) { //Loop Over iPhi Sectors //Initialize iPhi Histograms - 1D (*iterPhi).second.hPhi_ClustADC = make_shared<TH1F>(getHistogram( (*iterEta).first, (*iterPhi).first, aSetup.histoSetup_clustADC ) ); (*iterPhi).second.hPhi_ClustMulti = make_shared<TH1F>(getHistogram( (*iterEta).first, (*iterPhi).first, aSetup.histoSetup_clustMulti ) ); (*iterPhi).second.hPhi_ClustSize = make_shared<TH1F>(getHistogram( (*iterEta).first, (*iterPhi).first, aSetup.histoSetup_clustSize ) ); (*iterPhi).second.hPhi_ClustTime = make_shared<TH1F>(getHistogram( (*iterEta).first, (*iterPhi).first, aSetup.histoSetup_clustTime ) ); //Initialize iPhi Histograms - 2D (*iterPhi).second.hPhi_ClustADC_v_ClustPos = make_shared<TH2F>( TH2F( ("hiEta" + getString( (*iterEta).first ) + "iPhi" + getString( (*iterPhi).first ) + "_ClustADC_v_ClustPos").c_str(),"Response Uniformity", aSetup.iUniformityGranularity, (*iterPhi).second.fPos_Xlow, (*iterPhi).second.fPos_Xhigh,300,0,15000) ); (*iterPhi).second.hPhi_ClustADC_v_ClustPos->Sumw2(); //Loop Over Stored Clusters for (auto iterClust = (*iterPhi).second.vec_clusters.begin(); iterClust != (*iterPhi).second.vec_clusters.end(); ++iterClust) { //Loop Over Stored Clusters //Fill iEta Histograms (*iterEta).second.hEta_ClustADC->Fill( (*iterClust).fADC ); //(*iterEta).second.hEta_ClustMulti->Fill( (*iterClust). ); (*iterEta).second.hEta_ClustPos->Fill( (*iterClust).fPos_X ); (*iterEta).second.hEta_ClustSize->Fill( (*iterClust).iSize ); (*iterEta).second.hEta_ClustTime->Fill( (*iterClust).iTimeBin ); (*iterEta).second.hEta_ClustADC_v_ClustPos->Fill( (*iterClust).fPos_X, (*iterClust).fADC ); //Fill iPhi Histograms (*iterPhi).second.hPhi_ClustADC->Fill( (*iterClust).fADC ); //(*iterPhi).second.hPhi_ClustMulti (*iterPhi).second.hPhi_ClustSize->Fill( (*iterClust).iSize); (*iterPhi).second.hPhi_ClustTime->Fill( (*iterClust).iTimeBin); (*iterPhi).second.hPhi_ClustADC_v_ClustPos->Fill( (*iterClust).fPos_X, (*iterClust).fADC ); } //End Loop Over Stored Clusters //Slices //Now that all clusters have been analyzed we extract the slices for (int i=1; i<= aSetup.iUniformityGranularity; ++i) { //Loop Over Slices //Create the slice SectorSlice slice; //string strSliceName = "hiEta" + getString( (*iterEta).first ) + "iPhi" + getString( (*iterPhi).first ) + "Slice" + getString(i) + "_ClustADC"; //Grab ADC spectrum for this slice slice.hSlice_ClustADC = make_shared<TH1F>( *( (TH1F*) (*iterPhi).second.hPhi_ClustADC_v_ClustPos->ProjectionY( ("hiEta" + getString( (*iterEta).first ) + "iPhi" + getString( (*iterPhi).first ) + "Slice" + getString(i) + "_ClustADC").c_str(),i,i,"") ) ); //Store position information for this slice slice.fPos_Center = (*iterPhi).second.hPhi_ClustADC_v_ClustPos->GetXaxis()->GetBinCenter(i); slice.fWidth = (*iterPhi).second.hPhi_ClustADC_v_ClustPos->GetXaxis()->GetBinWidth(i); //Store the slice (*iterPhi).second.map_slices[i] = slice; } //End Loop Over Slices } //End Loop Over iPhi Sectors std::cout<<"(*iterEta).second.hEta_ClustADC->Integral() = " << (*iterEta).second.hEta_ClustADC->Integral() << std::endl; } //End Loop Over iEta Sectors } //End AnalyzeResponseUniformity::fillHistos() - Full Detector
//Stores booked histograms (for those histograms that are non-null) void AnalyzeResponseUniformity::storeHistos( string strOutputROOTFileName, std::string strOption ){ //Variable Declaration //std::shared_ptr<TFile> ptr_fileOutput; TFile * ptr_fileOutput = new TFile(strOutputROOTFileName.c_str(), strOption.c_str(),"",1); //Assign the TFile to the ptr_fileOutput //ptr_fileOutput = make_shared<TFile>(TFile(strOutputROOTFileName.c_str(), strOption.c_str(),"",1) ); //Check if File Failed to Open Correctly if ( !ptr_fileOutput->IsOpen() || ptr_fileOutput->IsZombie() ) { printClassMethodMsg("AnalyzeResponseUniformity","storeHistos","Error: File I/O"); printROOTFileStatus(ptr_fileOutput); printClassMethodMsg("AnalyzeResponseUniformity","storeHistos", "\tPlease cross check input file name, option, and the execution directory\n" ); printClassMethodMsg("AnalyzeResponseUniformity","storeHistos", "\tExiting; No Histograms have been stored!\n" ); return; } //End Check if File Failed to Open Correctly //Loop over ieta's //Create/Load file structure //Store ieta level histograms //Loop over iphi's within ieta's //Create/Load file structure //Store iphi level histograms //Loop over slices //Create/Load file structure //store slice level histograms //Close File //Loop Over Stored iEta Sectors for (auto iterEta = detMPGD.map_sectorsEta.begin(); iterEta != detMPGD.map_sectorsEta.end(); ++iterEta) { //Loop Over iEta Sectors //Get Directory //------------------------------------- //Check to see if the directory exists already TDirectory *dir_SectorEta = ptr_fileOutput->GetDirectory( ( "SectorEta" + getString( (*iterEta).first ) ).c_str(), false, "GetDirectory" ); //If the above pointer is null the directory does NOT exist, create it if (dir_SectorEta == nullptr) { //Case: Directory did not exist in file, CREATE dir_SectorEta = ptr_fileOutput->mkdir( ( "SectorEta" + getString( (*iterEta).first ) ).c_str() ); } //End Case: Directory did not exist in file, CREATE //Debugging cout<<"dir_SectorEta->GetName() = " << dir_SectorEta->GetName()<<endl; //Store Histograms - SectorEta Level //------------------------------------- dir_SectorEta->cd(); (*iterEta).second.hEta_ClustADC->Write(); (*iterEta).second.hEta_ClustPos->Write(); (*iterEta).second.hEta_ClustSize->Write(); (*iterEta).second.hEta_ClustTime->Write(); (*iterEta).second.hEta_ClustADC_v_ClustPos->Write(); //Loop Over Stored iPhi Sectors within this iEta Sector for (auto iterPhi = (*iterEta).second.map_sectorsPhi.begin(); iterPhi != (*iterEta).second.map_sectorsPhi.end(); ++iterPhi) { //Loop Over Stored iPhi Sectors //Get Directory //------------------------------------- //Check to see if the directory exists already TDirectory *dir_SectorPhi = dir_SectorEta->GetDirectory( ( "SectorPhi" + getString( (*iterPhi).first ) ).c_str(), false, "GetDirectory" ); //If the above pointer is null the directory does NOT exist, create it if (dir_SectorPhi == nullptr) { //Case: Directory did not exist in file, CREATE dir_SectorPhi = dir_SectorEta->mkdir( ( "SectorPhi" + getString( (*iterPhi).first ) ).c_str() ); } //End Case: Directory did not exist in file, CREATE //Debugging cout<<"dir_SectorPhi->GetName() = " << dir_SectorPhi->GetName()<<endl; //Store Histograms - SectorPhi Level //------------------------------------- dir_SectorPhi->cd(); (*iterPhi).second.hPhi_ClustADC->Write(); (*iterPhi).second.hPhi_ClustSize->Write(); (*iterPhi).second.hPhi_ClustTime->Write(); (*iterPhi).second.hPhi_ClustADC_v_ClustPos->Write(); //Loop through Slices //To be implemented //Slices //Now that all clusters have been analyzed we extract the slices for (auto iterSlice = (*iterPhi).second.map_slices.begin(); iterSlice != (*iterPhi).second.map_slices.end(); ++iterSlice ) { //Loop Over Slices //int iSliceCount = std::distance( (*iterPhi).second.map_slices.begin(), iterSlice ) + 1; //Get Directory //------------------------------------- //Check to see if the directory exists already TDirectory *dir_Slice = dir_SectorPhi->GetDirectory( ( "Slice" + getString( (*iterSlice).first ) ).c_str(), false, "GetDirectory" ); //If the above pointer is null the directory does NOT exist, create it if (dir_Slice == nullptr) { //Case: Directory did not exist in file, CREATE dir_Slice = dir_SectorPhi->mkdir( ( "Slice" + getString( (*iterSlice).first ) ).c_str() ); } //End Case: Directory did not exist in file, CREATE //Store Histograms - Slice Level //------------------------------------- dir_Slice->cd(); (*iterSlice).second.hSlice_ClustADC->Write(); } //End Loop Over Slices } //End Loop Over Stored iPhi Sectors } //End Loop Over Stored iEta Sectors //Close the ROOT file ptr_fileOutput->Close(); return; } //End storeHistos()
void AnalyzeResponseUniformity::storeFits( string strOutputROOTFileName, std::string strOption ){ //Variable Declaration TFile * ptr_fileOutput = new TFile(strOutputROOTFileName.c_str(), strOption.c_str(),"",1); //Check if File Failed to Open Correctly if ( !ptr_fileOutput->IsOpen() || ptr_fileOutput->IsZombie() ) { printClassMethodMsg("AnalyzeResponseUniformity","storeFits","Error: File I/O"); printROOTFileStatus(ptr_fileOutput); printClassMethodMsg("AnalyzeResponseUniformity","storeFits", "\tPlease cross check input file name, option, and the execution directory\n" ); printClassMethodMsg("AnalyzeResponseUniformity","storeFits", "\tExiting; No Fits have been stored!\n" ); return; } //End Check if File Failed to Open Correctly //Loop Over Stored iEta Sectors for (auto iterEta = detMPGD.map_sectorsEta.begin(); iterEta != detMPGD.map_sectorsEta.end(); ++iterEta) { //Loop Over iEta Sectors //Get Directory //------------------------------------- //Check to see if the directory exists already TDirectory *dir_SectorEta = ptr_fileOutput->GetDirectory( ( "SectorEta" + getString( (*iterEta).first ) ).c_str(), false, "GetDirectory" ); //If the above pointer is null the directory does NOT exist, create it if (dir_SectorEta == nullptr) { //Case: Directory did not exist in file, CREATE dir_SectorEta = ptr_fileOutput->mkdir( ( "SectorEta" + getString( (*iterEta).first ) ).c_str() ); } //End Case: Directory did not exist in file, CREATE //Debugging //cout<<"dir_SectorEta->GetName() = " << dir_SectorEta->GetName()<<endl; //Store Fits - SectorEta Level //------------------------------------- dir_SectorEta->cd(); (*iterEta).second.gEta_ClustADC_Fit_NormChi2->Write(); (*iterEta).second.gEta_ClustADC_Fit_PkPos->Write(); (*iterEta).second.gEta_ClustADC_Fit_Failures->Write(); (*iterEta).second.gEta_ClustADC_Spec_NumPks->Write(); (*iterEta).second.gEta_ClustADC_Spec_PkPos->Write(); //Loop Over Stored iPhi Sectors within this iEta Sector for (auto iterPhi = (*iterEta).second.map_sectorsPhi.begin(); iterPhi != (*iterEta).second.map_sectorsPhi.end(); ++iterPhi) { //Loop Over Stored iPhi Sectors //Get Directory //------------------------------------- //Check to see if the directory exists already TDirectory *dir_SectorPhi = dir_SectorEta->GetDirectory( ( "SectorPhi" + getString( (*iterPhi).first ) ).c_str(), false, "GetDirectory" ); //If the above pointer is null the directory does NOT exist, create it if (dir_SectorPhi == nullptr) { //Case: Directory did not exist in file, CREATE dir_SectorPhi = dir_SectorEta->mkdir( ( "SectorPhi" + getString( (*iterPhi).first ) ).c_str() ); } //End Case: Directory did not exist in file, CREATE //Debugging //cout<<"dir_SectorPhi->GetName() = " << dir_SectorPhi->GetName()<<endl; //Store Fits - SectorPhi Level //------------------------------------- dir_SectorPhi->cd(); //No Fits defined at this level - yet //Slices //Now that all clusters have been analyzed we extract the slices for (auto iterSlice = (*iterPhi).second.map_slices.begin(); iterSlice != (*iterPhi).second.map_slices.end(); ++iterSlice ) { //Loop Over Slices //int iSliceCount = std::distance( (*iterPhi).second.map_slices.begin(), iterSlice ); //Get Directory //------------------------------------- //Check to see if the directory exists already TDirectory *dir_Slice = dir_SectorPhi->GetDirectory( ( "Slice" + getString( (*iterSlice).first ) ).c_str(), false, "GetDirectory" ); //If the above pointer is null the directory does NOT exist, create it if (dir_Slice == nullptr) { //Case: Directory did not exist in file, CREATE dir_Slice = dir_SectorPhi->mkdir( ( "Slice" + getString( (*iterSlice).first ) ).c_str() ); } //End Case: Directory did not exist in file, CREATE //Store Fits - Slice Level //------------------------------------- dir_Slice->cd(); //(*iterSlice).second.pmrkSlice_ClustADC->Write( getNameByIndex( (*iterEta).first, (*iterPhi).first, (*iterSlice).first, "PeakMrk", "clustADC" ).c_str() ); (*iterSlice).second.fitSlice_ClustADC->Write(); } //End Loop Over Slices } //End Loop Over Stored iPhi Sectors } //End Loop Over Stored iEta Sectors //Close the ROOT file ptr_fileOutput->Close(); return; } //End storeHistos()
TF1 AnalyzeResponseUniformity::getFit(int iEta, int iPhi, int iSlice, HistoSetup & setupHisto, shared_ptr<TH1F> hInput, TSpectrum &specInput ){ //Variable Declaration float fLimit_Max = setupHisto.fHisto_xUpper, fLimit_Min = setupHisto.fHisto_xLower; vector<string>::const_iterator iterVec_IGuess; //Iterator to use for setting initial guess of fit vector<float> vec_fFitRange; for (auto iterRange = aSetup.histoSetup_clustADC.vec_strFit_Range.begin(); iterRange != aSetup.histoSetup_clustADC.vec_strFit_Range.end(); ++iterRange) { //Loop Over Fit Range vec_fFitRange.push_back( getFitBoundary( (*iterRange), hInput, specInput ) ); } //End Loop Over Fit Range if (vec_fFitRange.size() > 1) { fLimit_Min = (*std::min_element(vec_fFitRange.begin(), vec_fFitRange.end() ) ); fLimit_Max = (*std::max_element(vec_fFitRange.begin(), vec_fFitRange.end() ) ); } TF1 ret_Func( getNameByIndex(iEta, iPhi, iSlice, "fit", setupHisto.strHisto_Name).c_str(), setupHisto.strFit_Formula.c_str(), fLimit_Min, fLimit_Max); //Check to see if the number of parameters in the TF1 meets the expectation if ( ret_Func.GetNpar() < setupHisto.vec_strFit_ParamIGuess.size() || ret_Func.GetNpar() < setupHisto.vec_strFit_ParamLimit_Min.size() || ret_Func.GetNpar() < setupHisto.vec_strFit_ParamLimit_Max.size() ) { //Case: Set points for initial parameters do not meet expectations printClassMethodMsg("AnalyzeResponseUniformity","getFit","Error! Number of Parameters in Function Less Than Requested Initial Guess Parameters!"); printClassMethodMsg("AnalyzeResponseUniformity","getFit", ("\tNum Parameter: " + getString( ret_Func.GetNpar() ) ).c_str() ); printClassMethodMsg("AnalyzeResponseUniformity","getFit", ("\tNum Initial Guesses: " + getString( setupHisto.vec_strFit_ParamIGuess.size() ) ).c_str() ); printClassMethodMsg("AnalyzeResponseUniformity","getFit", ("\tNum Initial Guess Limits (Min): " + getString( setupHisto.vec_strFit_ParamLimit_Min.size() ) ).c_str() ); printClassMethodMsg("AnalyzeResponseUniformity","getFit", ("\tNum Initial Guess Limits (Max): " + getString( setupHisto.vec_strFit_ParamLimit_Max.size() ) ).c_str() ); printClassMethodMsg("AnalyzeResponseUniformity","getFit", "No Initial Parameters Have Been Set! Please Cross-Check Input Analysis Config File" ); return ret_Func; } //End Case: Set points for initial parameters do not meet expectations //Set Fit Parameters - Initial Value //------------------------------------------------------ //Keywords are AMPLITUDE, MEAN, PEAK, SIGMA for (int i=0; i<setupHisto.vec_strFit_ParamIGuess.size(); ++i) { //Loop over parameters - Initial Guess iterVec_IGuess = std::find(vec_strSupportedKeywords.begin(), vec_strSupportedKeywords.end(), setupHisto.vec_strFit_ParamIGuess[i]); if ( iterVec_IGuess == vec_strSupportedKeywords.end() ) { //Case: No Keyword Found; Try to set a Numeric Value ret_Func.SetParameter(i, stofSafe( setupHisto.vec_strFit_ParamIGuess[i] ) ); } //End Case: No Keyword Found; Try to set a Numeric Value else{ //Case: Keyword Found; Set Value based on Keyword ret_Func.SetParameter(i, getValByKeyword( (*iterVec_IGuess), hInput, specInput ) ); } //End Case: Keyword Found; Set Value based on Keyword } //End Loop over parameters - Initial Guess //Set Fit Parameters - Boundaries //------------------------------------------------------ if (setupHisto.vec_strFit_ParamLimit_Min.size() == setupHisto.vec_strFit_ParamLimit_Max.size() ) { //Check: Stored Parameter Limits Match //Here we use vec_strFit_ParamLimit_Min but we know it has the same number of parameters as vec_strFit_ParamLimit_Max //For each fit parameter, set the boundary for (int i=0; i<setupHisto.vec_strFit_ParamLimit_Min.size(); ++i) { //Loop over boundary parameters fLimit_Min = getFitBoundary(setupHisto.vec_strFit_ParamLimit_Min[i], hInput, specInput); fLimit_Max = getFitBoundary(setupHisto.vec_strFit_ParamLimit_Max[i], hInput, specInput); //cout<<"(fLimit_Min, fLimit_Max) = (" << fLimit_Min << ", " << fLimit_Max << ")\n"; (fLimit_Max > fLimit_Min) ? ret_Func.SetParLimits(i, fLimit_Min, fLimit_Max ) : ret_Func.SetParLimits(i, fLimit_Max, fLimit_Min ); } //End Loop over boundary parameters } //End Check: Stored Parameter Limits Match //Set Fit Parameters - Fixed? //------------------------------------------------------ //Placeholder; maybe we add functionality in the future //Set Other Fit Data Members //------------------------------------------------------ ret_Func.SetLineColor(kRed); ret_Func.SetLineWidth(3); //Delete Pointers //delete iterVec_IGuess; //Return fit //------------------------------------------------------ return ret_Func; } //End AnalyzeResponseUniformity::getFit()