void UploadImpl::importButton() { QString file; file = QFileDialog::getOpenFileName(this, tr("Import Exercise Data"), "", tr("Comma separated files (*.csv *.txt);;Garmin FIT file (*.fit)")); if (!file.isEmpty()) { if ( QFileInfo(file.toLower()).suffix() == "fit") { // Garmin FIT file QFile fitFile(file); if (!fitFile.open(QIODevice::ReadOnly)) return; QByteArray blob = fitFile.readAll(); std::vector<uint8_t> fitData(blob.begin(), blob.end()); FIT fit; fit.parse (fitData, exdata); } else { // csv file ReadCSV(qPrintable(file), exdata); } if (exdata.size()) { fillList(); } } }
void PlotDataFitFunction::calculate() { if (!pData_) return; if (fittingValues_.column >= 0) { fitData(); } else { PlotFunction* newPlotData; newPlotData = new PlotFunction(); newPlotData->getPlotExpression().setExpressionName(expressionNameInput_.get()); newPlotData->setExpressionLength(static_cast<PlotFunction::ExpressionDescriptionLengthType>(expressionText_.getValue()), maxLength_.get(),selfDescription_.get()); PlotFunction* oldData; oldData = pDataOut_; pDataOut_ = newPlotData; setOutPortData(); if (getProcessorWidget()){ getProcessorWidget()->updateFromProcessor(); } oldData->getPlotExpression().deletePlotExpressionNodes(); delete oldData; } }
int main(int argc, char *argv[]) { int i,j,n; FILE *inputfile,*outputfile; // mwd parameters int k; // integration time int l = WINDOW_WIDTH; // l is fixed int m; // decay constant int min; int max; int chan; double fwhm; // FWHM = 2.35 * sigma double fwhm_min = 100000; // to keep track of the minimum FWHM int k_min; // to keep track of the k param for which fwhm is minimized int m_min; // to keep track of the m param for which fwhm is minimized int num_waveforms; int good_waveforms = 0; double p[NUM_PARAMS]; double *histData = NULL; double peakData[2*GAUSSIAN_PEAK_WIDTH+1]; int peak_centre, peak_start; double peak_amp; /* Read in waveform data from input file*/ if ((inputfile = fopen(argv[1],"r")) == NULL) { fprintf(stdout, "Input file does not exist.\n"); } else { // check if output file already exists if ((outputfile = fopen(argv[2],"wx")) == NULL) { fprintf(stdout, "Could not open output file or file already exists.\n"); } else { fclose(outputfile); // count the total number of waveforms in file char c; long total_waveforms; long lines; while ((c=getc(inputfile)) != EOF) { if (c=='\n') { lines++; } } total_waveforms = (long) (lines/NUM_SAMPLES*1.0 + 0.5); num_waveforms = MIN(MAX_WAVEFORMS, total_waveforms); for (k=K_MIN;k<=K_MAX;k+=K_STEP) { outputfile = fopen(argv[2],"a"); fprintf(outputfile, "\n"); for (m=M_MIN;m<=M_MAX;m+=M_STEP) { printf("k = %d, m = %d\n", k, m); good_waveforms = 0; fseek(inputfile, 0, SEEK_SET); for (i=0;i<num_waveforms;i++) { for (j=0;j<NUM_SAMPLES;j++) { fscanf(inputfile, "%f\n", &v[j]); } // filter waveform with MWD and evaluate pulse height differenceFilterFloat(l, v, y); deconvolutionFilterFloat(l, m, y, y); pulseHeights[i] = (int) (pulseHeightFloat(y, k) + 0.5); //plotLine(v, NUM_SAMPLES, 0); // plotLine(y, NUM_SAMPLES, 0); } /* Plot Energy Spectrum */ // Find minimum and maximum pulse heights max = 0; min = 100000; for (i=0;i<num_waveforms;i++) { if (pulseHeights[i] > max) { max = pulseHeights[i]; } } for (i=0;i<num_waveforms;i++) { if (pulseHeights[i] > 0 && pulseHeights[i] < min) { min = pulseHeights[i]; } } histData = (double*)calloc(max+1, sizeof(double)); for (i=0;i<num_waveforms;i++) { if (pulseHeights[i] > 0) { good_waveforms++; chan = pulseHeights[i]; histData[chan] += 1.0; } } plotHisto(histData, max, 0, 1500); /* Fit peak to find FWHM */ // we only want to fit the peak, not the whole spectrum // find the peak we want to fit peak_start = peakFind(histData, max, PEAK_NUM, 300, 50); peak_amp = 0; for (i=peak_start;i<peak_start+GAUSSIAN_PEAK_WIDTH+1;i++) { if (histData[i] > peak_amp) { peak_amp = histData[i]; peak_centre = i; } } free(histData); for (i=0;i<GAUSSIAN_PEAK_WIDTH*2+1;i++) { peakData[i] = histData[(peak_centre-GAUSSIAN_PEAK_WIDTH)+i]; } p[0] = peak_amp*5.5; p[1] = GAUSSIAN_PEAK_WIDTH; p[2] = 0.5; fitData(peakData, GAUSSIAN_PEAK_WIDTH*2+1, p, 0, 0); // calculate the fwhm from fit parameters and keep track of the minimum value if (2.35*p[2]<fwhm_min) { fwhm_min = 2.35*p[2]; k_min = k; m_min = m; } fprintf(outputfile, "%d\t%d\t%g\n", k, m, 2.35*p[2]*PEAK_ENERGY/(p[1]-GAUSSIAN_PEAK_WIDTH+peak_centre)); printf("Processed %d waveforms, %d counts in spectrum\n", num_waveforms, good_waveforms); } fclose(outputfile); } fclose(inputfile); //print summary to screen printf("Finished processing file %s\n", argv[1]); printf("Mminimum energy resolution: %g channels and %g keV at k = %d and m = %d\n", fwhm_min, fwhm_min*PEAK_ENERGY/(p[1]-GAUSSIAN_PEAK_WIDTH+peak_centre), k_min, m_min); } } return 0; }
void DataSection::addBytes(uint8_t* buf, size_t count) { (void)buf; fitData(count); assert(false); }
void DataSection::addByte(uint8_t byte) { fitData(); _data[_dataIndex++] = byte; }
/** Calculate a workspace that contains the result of the fit to the * transmission fraction that was calculated * @param raw [in] the workspace with the unfitted transmission ratio data * @param rebinParams [in] the parameters for rebinning * @param fitMethod [in] string can be Log, Linear, Poly2, Poly3, Poly4, Poly5, * Poly6 * @return a workspace that contains the evaluation of the fit * @throw runtime_error if the Linear or ExtractSpectrum algorithm fails during * execution */ API::MatrixWorkspace_sptr CalculateTransmission::fit(API::MatrixWorkspace_sptr raw, std::vector<double> rebinParams, const std::string fitMethod) { MatrixWorkspace_sptr output = this->extractSpectra(raw, std::vector<size_t>(1, 0)); Progress progress(this, m_done, 1.0, 4); progress.report("CalculateTransmission: Performing fit"); // these are calculated by the call to fit below double grad(0.0), offset(0.0); std::vector<double> coeficients; const bool logFit = (fitMethod == "Log"); if (logFit) { g_log.debug("Fitting to the logarithm of the transmission"); MantidVec &Y = output->dataY(0); MantidVec &E = output->dataE(0); double start = m_done; Progress prog2(this, start, m_done += 0.1, Y.size()); for (size_t i = 0; i < Y.size(); ++i) { // Take the log of each datapoint for fitting. Recalculate errors // remembering that d(log(a))/da = 1/a E[i] = std::abs(E[i] / Y[i]); Y[i] = std::log10(Y[i]); progress.report("Fitting to the logarithm of the transmission"); } // Now fit this to a straight line output = fitData(output, grad, offset); } // logFit true else if (fitMethod == "Linear") { // Linear fit g_log.debug("Fitting directly to the data (i.e. linearly)"); output = fitData(output, grad, offset); } else { // fitMethod Polynomial int order = getProperty("PolynomialOrder"); std::stringstream info; info << "Fitting the transmission to polynomial order=" << order; g_log.information(info.str()); output = fitPolynomial(output, order, coeficients); } progress.report("CalculateTransmission: Performing fit"); // if no rebin parameters were set the output workspace will have the same // binning as the input ones, otherwise rebin if (!rebinParams.empty()) { output = rebin(rebinParams, output); } progress.report("CalculateTransmission: Performing fit"); // if there was rebinnning or log fitting we need to recalculate the Ys, // otherwise we can just use the workspace kicked out by the fitData()'s call // to Linear if ((!rebinParams.empty()) || logFit) { const MantidVec &X = output->readX(0); MantidVec &Y = output->dataY(0); if (logFit) { // Need to transform back to 'unlogged' const double m(std::pow(10, grad)); const double factor(std::pow(10, offset)); MantidVec &E = output->dataE(0); for (size_t i = 0; i < Y.size(); ++i) { // the relationship between the grad and interspt of the log fit and the // un-logged value of Y contain this dependence on the X (bin center // values) Y[i] = factor * (std::pow(m, 0.5 * (X[i] + X[i + 1]))); E[i] = std::abs(E[i] * Y[i]); progress.report(); } } // end logFit else if (fitMethod == "Linear") { // the simpler linear situation for (size_t i = 0; i < Y.size(); ++i) { Y[i] = (grad * 0.5 * (X[i] + X[i + 1])) + offset; } } else { // the polynomial fit for (size_t i = 0; i < Y.size(); ++i) { double aux = 0; double x_v = 0.5 * (X[i] + X[i + 1]); for (int j = 0; j < static_cast<int>(coeficients.size()); ++j) { aux += coeficients[j] * std::pow(x_v, j); } Y[i] = aux; } } } progress.report("CalculateTransmission: Performing fit"); return output; }
int main(int argc,char *argv[]) { ////////////////////////////////////////////////////////////// //PROGRAM VARIBALES ////////////////////////////////////////////////////////////// char datafile[FSIZE]="",fitfile[FSIZE]=""; char fitfunc[FSIZE]="",inipars[FSIZE]=""; real2 params[MAXPARAMS]; int numcols=0,colx=0,coly=0,cole=0; int nfac=2; int i,ndata; ////////////////////////////////////////////////////////////// //INITIALIZE ////////////////////////////////////////////////////////////// TITLE(stdout,'*',"FIT DATA TO A GIVEN FUNCTION"); ////////////////////////////////////////////////////////////// //SET OPTIONS AND USAGE ////////////////////////////////////////////////////////////// SET_OPTIONS(":hvVf:F:u:p:n:x:y:e:N:"); SET_USAGE( "=======================================================================================\n" "Usage:\n\n" "\t./program -f <datafile> [-F <fitfile>] -u <fit_function> [-p <initial_params>]\n" "\t [-N <num_sampling_fitting_func>]\n" "\t -n <numcols> -x <colx> -y <coly> [-e <cole>]\n" "\n" "Fit the 2D data described by <colx> and <coly> with errors <cole> using fitting function\n" "<fit_function> as given by function file functions.hpp. The initial set of parameters\n" "<initial_params> should be provided as a list of comma separated real values.\n" "The result of the fit is stored in file <fitfile> where the fitted parameters, the \n" "chisquare and the p-value are stored in the header. <fitfile> is a two column file with\n" "the value of the fitted function at intermediate points (<num_sampling_fitting_func> x \n" "number of fitted points).\n" "=======================================================================================\n" ); ////////////////////////////////////////////////////////////// //READ OPTIONS ////////////////////////////////////////////////////////////// while(ITEROPTIONS){ switch(OPTION){ case 'f': strcpy(datafile,optarg); break; case 'F': strcpy(fitfile,optarg); break; case 'u': strcpy(fitfunc,optarg); break; case 'p': strcpy(inipars,optarg); break; case 'n': numcols=atoi(optarg); break; case 'N': nfac=atoi(optarg); break; case 'x': colx=atoi(optarg); break; case 'y': coly=atoi(optarg); break; case 'e': cole=atoi(optarg); break; //======================================== //COMMON //======================================== case 'v': VERBOSITY=1; break; case 'V': VERBOSITY=2; break; //DETECT ERRORS OPTION_ERRORS; } } ////////////////////////////////////////////////////////////// //VALIDATE OPTIONS ////////////////////////////////////////////////////////////// if(isBlank(datafile)){ fprintf(stderr,"Error: No datafile was provided\n"); PRINT_USAGE; EXIT; } if(!fileExists(datafile)){ fprintf(stderr,"Error: Datafile '%s' does not exist\n",datafile); PRINT_USAGE; EXIT; } if(isBlank(fitfile)){ sprintf(fitfile,"%s.fit",datafile); } if((ndata=countLines(datafile))==0){ fprintf(stderr,"Error: Datafile '%s' seems empty\n",datafile); PRINT_USAGE; EXIT; } if(numcols<1){ fprintf(stderr,"Error: The number of columns should be different from 0\n"); PRINT_USAGE; EXIT; } if(colx==0){ colx=1; } if(coly==0){ coly=2; } if(isBlank(fitfunc)){ fprintf(stderr,"Error: No fit function was provided\n"); PRINT_USAGE; EXIT; }else{ getFunction(fitfunc); } if(isBlank(inipars)){ for(i=0;i<FNpars;i++){ if(i==FNpars-1) strcat(inipars,"0.0"); else strcat(inipars,"0.0,"); } } splitString(inipars,",",params); ////////////////////////////////////////////////////////////// //REPORT INPUT INFORMATION ////////////////////////////////////////////////////////////// if(VERBOSE(1)){ fprintf(stdout,"Datafile: %s\n",datafile); fprintf(stdout,"Fitfile: %s\n",fitfile); fprintf(stdout,"Fit function: %s\n",fitfunc); fprintf(stdout,"Fit parameters: %s\n",inipars); fprintf(stdout,"Test call: %s(%+14.7e;%s) = %+14.7e\n", fitfunc,FXtest,inipars,FFunc(FXtest,params)); fprintf(stdout,"Number of columns: %d\n",numcols); fprintf(stdout,"Columns x,y: %d,%d\n",colx,coly); if(cole!=0) fprintf(stdout,"Column error: %d\n",cole); else fprintf(stdout,"Errors assumed 1\n"); fprintf(stdout,"Factor of over sampling: %d\n",nfac); } ////////////////////////////////////////////////////////////// //PROGRAM ////////////////////////////////////////////////////////////// //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //READING DATA //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf(stdout,"Reading %d data points from datafile '%s'...\n",ndata,datafile); real2 *X=readColumn(datafile,ndata,numcols,colx); real2 *Y=readColumn(datafile,ndata,numcols,coly); real2 *E; if(cole) E=readColumn(datafile,ndata,numcols,cole); else{ E=(real2*)calloc(ndata,sizeof(real2)); for(int i=0;i<ndata;i++) E[i]=1.0; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //FITTING DATA //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% real2 chis,pval; fprintf(stdout,"Fitting %d data points with function '%s'...\n", ndata,fitfunc); fitData(X,Y,E,ndata,FFunc,FNpars,params,chis,pval); fprintf(stdout,"Fit succesful:\n"); fprintf(stdout,"\tBest fit parameters: "); for(i=0;i<FNpars;i++) fprintf(stdout,"%+14.7e ",params[i]); fprintf(stdout,"\n"); fprintf(stdout,"\tChisquare: %+14.7e\n",chis); fprintf(stdout,"\tP-val (nu = %d): %+14.7e\n",ndata,pval); if(pval>0.05) fprintf(stdout,"\tData is compatible with fitting function\n"); else fprintf(stdout,"\tData cannot be fitted with function\n"); file fs=fileOpen(fitfile,"w"); //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //STORING //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf(stdout,"Storing fit results...\n",fitfile); fprintf(fs,"#Datafile: %s\n",datafile); fprintf(fs,"#TotCols,ColX,ColY,ColE: %d %d %d %d\n", numcols,colx,coly,cole); fprintf(fs,"#FitFunction: %s\n",fitfunc); fprintf(fs,"#Initial parameters: %s\n",inipars); fprintf(fs,"#NumberDataPoints: %d\n",ndata); fprintf(fs,"#FitParameters: "); for(i=0;i<FNpars;i++) fprintf(fs,"%+14.7e ",params[i]); fprintf(fs,"\n"); fprintf(fs,"#Chisquare: %+14.7e\n",chis); fprintf(fs,"#P-val: %+14.7e\n",pval); fprintf(fs,"%-14s %-14s\n","#1:X","2:Y"); //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //SAMPLING FUNCTION //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf(stdout,"Sampling fitting function...\n",fitfile); real2 x,y; real2 xini=X[0]; real2 dx=(X[ndata-1]-X[0])/(ndata*nfac); for(i=0;i<=ndata*nfac;i++){ x=xini+i*dx; y=FFunc(x,params); fprintf(fs,"%+14.7e %+14.7e\n",x,y); } fprintf(stdout,"Fitting result stored in %s...\n",fitfile); fclose(fs); return 0; }
void Clamp::customizeGUI(void) { QGridLayout *customlayout = DefaultGUIModel::getLayout(); customlayout->setColumnStretch(1,1); //overall GUI layout with a "horizontal box" copied from DefaultGUIModel QGroupBox *plotBox = new QGroupBox("FI Plot"); QHBoxLayout *plotBoxLayout = new QHBoxLayout; plotBox->setLayout(plotBoxLayout); QPushButton *clearButton = new QPushButton("&Clear"); QPushButton *linearfitButton = new QPushButton("Linear &Fit"); QPushButton *savePlotButton = new QPushButton("Screenshot"); QPushButton *printButton = new QPushButton("Print"); QPushButton *saveDataButton = new QPushButton("Save Data"); plotBoxLayout->addWidget(clearButton); plotBoxLayout->addWidget(linearfitButton); plotBoxLayout->addWidget(printButton); plotBoxLayout->addWidget(savePlotButton); plotBoxLayout->addWidget(saveDataButton); QLineEdit *eqnLine = new QLineEdit("Linear Equation"); eqnLine->setText("Y = c0 + c1 * X"); eqnLine->setFrame(false); splot = new ScatterPlot(this); // Connect buttons to functions QObject::connect(clearButton, SIGNAL(clicked()), splot, SLOT(clear())); QObject::connect(clearButton, SIGNAL(clicked()), this, SLOT(clearData())); QObject::connect(savePlotButton, SIGNAL(clicked()), this, SLOT(exportSVG())); QObject::connect(printButton, SIGNAL(clicked()), this, SLOT(print())); QObject::connect(saveDataButton, SIGNAL(clicked()), this, SLOT(saveFIData())); QObject::connect(linearfitButton, SIGNAL(clicked()), this, SLOT(fitData())); clearButton->setToolTip("Clear"); savePlotButton->setToolTip("Save screenshot"); saveDataButton->setToolTip("Save data"); linearfitButton->setToolTip("Perform linear least-squares regression"); printButton->setToolTip("Print plot"); plotBox->hide(); eqnLine->hide(); // splot->setMinimumSize(450, 270); splot->hide(); customlayout->addWidget(plotBox, 0, 1, 1, 1); customlayout->addWidget(eqnLine, 10, 1, 1, 1); customlayout->addWidget(splot, 1, 1, 3, 1); QGroupBox *modeBox = new QGroupBox("Clamp Mode"); QHBoxLayout *modeBoxLayout = new QHBoxLayout; modeBox->setLayout(modeBoxLayout); QButtonGroup *modeButtons = new QButtonGroup; modeButtons->setExclusive(true); QRadioButton *stepButton = new QRadioButton("Step"); modeBoxLayout->addWidget(stepButton); modeButtons->addButton(stepButton); stepButton->setEnabled(true); QRadioButton *rampButton = new QRadioButton("Ramp"); modeBoxLayout->addWidget(rampButton); modeButtons->addButton(rampButton); stepButton->setChecked(true); QObject::connect(modeButtons,SIGNAL(buttonClicked(int)),this,SLOT(updateClampMode(int))); stepButton->setToolTip("Set mode to current steps"); rampButton->setToolTip("Set mode to triangular current ramps"); customlayout->addWidget(modeBox, 0, 0); QHBoxLayout *optionBoxLayout = new QHBoxLayout; QGroupBox *optionBoxGroup = new QGroupBox; QCheckBox *randomCheckBox = new QCheckBox("Randomize"); optionBoxLayout->addWidget(randomCheckBox); QCheckBox *plotFICheckBox = new QCheckBox("Plot FI Curve"); optionBoxLayout->addWidget(plotFICheckBox); QObject::connect(randomCheckBox,SIGNAL(toggled(bool)),this,SLOT(togglerandom(bool))); QObject::connect(plotFICheckBox,SIGNAL(toggled(bool)),eqnLine,SLOT(setVisible(bool))); QObject::connect(plotFICheckBox,SIGNAL(toggled(bool)),splot,SLOT(setVisible(bool))); QObject::connect(plotFICheckBox,SIGNAL(toggled(bool)),plotBox,SLOT(setVisible(bool))); QObject::connect(plotFICheckBox,SIGNAL(toggled(bool)),this,SLOT(toggleFIplot(bool))); QObject::connect(plotFICheckBox,SIGNAL(toggled(bool)),this,SLOT(resizeMe())); randomCheckBox->setToolTip("Randomize input amplitudes within a cycle"); plotFICheckBox->setToolTip("Show/Hide FI plot area"); optionBoxGroup->setLayout(optionBoxLayout); customlayout->addWidget(optionBoxGroup, 3, 0); QObject::connect(DefaultGUIModel::pauseButton,SIGNAL(toggled(bool)),savePlotButton,SLOT(setEnabled(bool))); QObject::connect(DefaultGUIModel::pauseButton,SIGNAL(toggled(bool)),printButton,SLOT(setEnabled(bool))); QObject::connect(DefaultGUIModel::pauseButton,SIGNAL(toggled(bool)),saveDataButton,SLOT(setEnabled(bool))); QObject::connect(DefaultGUIModel::pauseButton,SIGNAL(toggled(bool)),linearfitButton,SLOT(setEnabled(bool))); QObject::connect(DefaultGUIModel::pauseButton,SIGNAL(toggled(bool)),DefaultGUIModel::modifyButton,SLOT(setEnabled(bool))); DefaultGUIModel::pauseButton->setToolTip("Start/Stop current clamp protocol"); DefaultGUIModel::modifyButton->setToolTip("Commit changes to parameter values"); DefaultGUIModel::unloadButton->setToolTip("Close module"); QObject::connect(this,SIGNAL(newDataPoint(double,double)),splot,SLOT(appendPoint(double,double))); QObject::connect(this,SIGNAL(setFIRange(double, double, double, double)),splot,SLOT(setAxes(double, double, double, double))); QObject::connect(this,SIGNAL(setPlotMode(bool)),plotFICheckBox,SLOT(setChecked(bool))); QObject::connect(this,SIGNAL(setStepMode(bool)),plotFICheckBox,SLOT(setEnabled(bool))); QObject::connect(this,SIGNAL(setStepMode(bool)),plotBox,SLOT(setEnabled(bool))); QObject::connect(this,SIGNAL(drawFit(double*, double*, int)),splot,SLOT(appendLine(double*, double*, int))); QObject::connect(this,SIGNAL(setEqnMsg(const QString &)), eqnLine,SLOT(setText(const QString &))); setLayout(customlayout); }