qavrg 0.0.28
qavrgacquisition.cpp
Go to the documentation of this file.
00001 #include "qavrgacquisition.h"
00002 
00003 #include <QTime>
00004 #include <QTimer>
00005 #include <QMetaObject>
00006 #include <QMetaProperty>
00007 #include <QList>
00008 #include <QtConcurrentRun>
00009 #include "AcqirisImport.h"
00010 #include "AcqirisD1Import.h"
00011 #include "qavrgapplication.h"
00012 #include "qavrgfillpattern.h"
00013 #include "qavrgfitter.h"
00014 #include "qavrgsettings.h"
00015 #include <math.h>
00016 #include <QMutexLocker>
00017 #include "qavrgacquisitionthread.h"
00018 #include <stdio.h>
00019 
00020 #define CHECK_STATUS(val) checkStatus(__LINE__,val)
00021 
00022 QavrgAcquisition::QavrgAcquisition(QavrgAcquisitionThread *acq, QavrgApplication *app, QObject *parent)
00023   : QavrgAcquisitionSimulated(acq, app, parent),
00024 //    m_Mutex(QMutex::Recursive),
00025     m_Application(app),
00026     m_AcquisitionThread(acq),
00027     m_NInstruments(0),
00028     m_InstrumentID(NULL),
00029     m_CardNChannels(NULL),
00030     m_TotalChannels(0),
00031     m_SaveFile(NULL)
00032 //    m_ParametersChanged(false)
00033 {
00034   m_InstrumentID = new ViSession[20];
00035   m_CardNChannels = new ViInt32[20];
00036 
00037   newSaveFile("saveddata",1);
00038 
00039   findDevices();
00040 
00041   connect(prop_FillPatternMode(), SIGNAL(valueChanged(int,int)), this, SLOT(fillPatternChanged()));
00042 }
00043 
00044 void QavrgAcquisition::initialize()
00045 {
00046   THREAD_CHECK;
00047 
00048 //  printf("Enter QavrgAcquisition::initialize(), nChannels = %d\n", get_NChannels());
00049 
00050   if (get_SimulationMode()) {
00051     emit noDeviceAvailable();
00052   }
00053 
00054 //  loadParameters();
00055   loadReferenceData();
00056   loadDarkData();
00057 
00058 //  printf("Leave QavrgAcquisition::initialize()\n");
00059 }
00060 
00061 QavrgAcquisition::~QavrgAcquisition()
00062 {
00063   for (int i=0; i<m_NInstruments; i++) {
00064     AcqrsD1_stopAcquisition(m_InstrumentID[i]);
00065   }
00066       
00067   Acqrs_closeAll();
00068 
00069   delete [] m_InstrumentID;
00070   delete [] m_CardNChannels;
00071 
00072   QavrgFitter *t;
00073 
00074   foreach(t, m_Fitters) {
00075     delete t;
00076   }
00077 
00078   if (m_SaveFile) {
00079     fclose(m_SaveFile);
00080   }
00081 }
00082 
00083 void QavrgAcquisition::timingResetDefaults()
00084 {
00085   reset_NChannels();
00086   reset_NSamples();
00087 }
00088 
00089 void QavrgAcquisition::triggerResetDefaults()
00090 {
00091   reset_TriggerLevel();
00092   reset_TriggerSlope();
00093   reset_TriggerSource();
00094 }
00095 
00096 int QavrgAcquisition::resultSize()
00097 {
00098   int maxsize = 0;
00099 
00100   int nchan = get_NChannels();
00101 
00102   for (int chan=0; chan<nchan; chan++) {
00103     QavrgFitter *t = fitter(chan);
00104 
00105     if (t) {
00106       int resultsize = t -> resultSize();
00107       if (resultsize > maxsize) {
00108         maxsize = resultsize;
00109       }
00110     }
00111   }
00112 
00113   return maxsize;
00114 }
00115 
00116 void QavrgAcquisition::fillPatternChanged()
00117 {
00118 //  printf("QavrgAcquisition::fillPatternChanged\n");
00119 
00120   QcepBoolVector patt;
00121   int bpo = get_BucketsPerOrbit();
00122   int nbunches;
00123 
00124   switch (get_FillPatternMode()) {
00125   case 0:   // Automatic mode
00126     if (m_Application -> fillPattern()) {
00127       patt = m_Application -> fillPattern() -> fillPattern();
00128     }
00129     break;
00130 
00131   case 1:   // 24 bunch mode
00132     patt.resize(bpo);
00133     for (int i=0; i<24; i++) {
00134       patt[i*bpo/24] = true;
00135     }
00136     break;
00137 
00138   case 2:   // Single bunch mode;
00139     patt.resize(bpo);
00140     patt[0] = 1;
00141     break;
00142 
00143   case 3:
00144     nbunches = get_CustomFilledBucketsPerOrbit();
00145     patt.resize(bpo);
00146     for (int i=0; i<nbunches; i++) {
00147       patt[i*bpo/nbunches] = true;
00148     }
00149     break;
00150 
00151   case 4:   // Custom fill mode
00152     patt = get_CustomFillPattern();
00153     break;
00154   }
00155 
00156   set_FillPattern(patt);
00157 }
00158 
00159 int QavrgAcquisition::acquireWait(double time)
00160 {
00161   if (m_Acquiring.tryLock()) {
00162     m_Acquiring.unlock();
00163 
00164 //    printf("Not acquiring\n");
00165 
00166     return AcquireDone;
00167   }
00168 
00169   QMutex mutex;
00170   QMutexLocker lock(&mutex);
00171 
00172   if (m_StatusWaiting.wait(&mutex, (int)(time*1000))) {
00173 //    printf("Waited for %g and succeeded\n", time);
00174     return AcquireDone;
00175   } else {
00176 //    printf("Waited for %g and timed out\n", time);
00177     return AcquireData/*get_Status()*/;
00178   }
00179 }
00180 
00181 void QavrgAcquisition::acquireCancel()
00182 {
00183 //  printf("Acquire cancel\n");
00184 //
00185   if (m_Acquiring.tryLock()) {
00186     m_Acquiring.unlock();
00187     return;
00188   } else {
00189 //    printf("Emit cancelled\n");
00190 
00191     emit acquisitionCancelled();
00192 
00193     m_AcquireCancel = 1;
00194   }
00195 }
00196 
00197 void QavrgAcquisition::acquireData()
00198 {
00199   THREAD_CHECK;
00200 //
00201 //  QMutexLocker  lock(&m_Acquiring);
00202 
00203 //  printf("QavrgAcquisition::acquireData()\n");
00204 
00205   QTime tm;
00206   tm.start();
00207   int cumultime=0;
00208 
00209 //  cumultime += tm.restart();
00210 //  emit printMessage(tr("acquireData: cumulative acquisition time %1 msec").arg(cumultime));
00211 
00212   setupAcquisition(AcquireData);
00213 
00214 //  cumultime += tm.restart();
00215 //  emit printMessage(tr("setup: cumulative acquisition time %1 msec").arg(cumultime));
00216 
00217   int nrep = get_NRepeats();
00218 
00219   for (int i=0; i<nrep; i++) {
00220     if (m_AcquireCancel) {
00221       m_AcquireCancel = 0;
00222       break;
00223     } else {
00224 //      cumultime += tm.restart();
00225 //      emit printMessage(tr("start: cumulative acquisition time %1 msec").arg(cumultime));
00226 
00227       startAcquisition(i, nrep);
00228 
00229 //      cumultime += tm.restart();
00230 //      emit printMessage(tr("wait: cumulative acquisition time %1 msec").arg(cumultime));
00231 
00232       waitAcquisition(i, nrep);
00233 
00234 //      cumultime += tm.restart();
00235 //      emit printMessage(tr("readout: cumulative acquisition time %1 msec").arg(cumultime));
00236 
00237       readoutAcquisition(i, nrep);
00238 
00239       emit acquisitionProgress((i+1)*100.0/nrep);
00240 
00241 //      cumultime += tm.restart();
00242 //      emit printMessage(tr("done: cumulative acquisition time %1 msec").arg(cumultime));
00243     }
00244   }
00245 
00246   releaseAcquisitionLock();
00247 
00248   set_Status(AcquireDone);
00249   emit acquisitionCompleted();
00250 
00251   cumultime += tm.restart();
00252   emit printMessage(tr("acquireData(): cumulative acquisition time %1 msec").arg(cumultime));
00253 }
00254 
00255 void QavrgAcquisition::acquireDark()
00256 {
00257   THREAD_CHECK;
00258 //
00259 //  QMutexLocker  lock(&m_Acquiring);
00260 
00261   setupAcquisition(AcquireDark);
00262 
00263   int nrep = get_DarkNRepeats();
00264 
00265   for (int i=0; i<nrep; i++) {
00266     if (m_AcquireCancel) {
00267       m_AcquireCancel = 0;
00268       break;
00269     } else {
00270       startAcquisition(i, nrep);
00271       waitAcquisition(i, nrep);
00272       readoutAcquisition(i, nrep);
00273 
00274       emit acquisitionProgress((i+1)*100.0/nrep);
00275     }
00276   }
00277 
00278   saveDarkData();
00279 
00280   releaseAcquisitionLock();
00281 
00282   set_Status(AcquireDone);
00283   emit acquisitionCompleted();
00284 }
00285 
00286 void QavrgAcquisition::acquireReference()
00287 {
00288   THREAD_CHECK;
00289 //
00290 //  QMutexLocker  lock(&m_Acquiring);
00291 
00292   setupAcquisition(AcquireReference);
00293 
00294   int nrep = get_ReferenceNRepeats();
00295 
00296   for (int i=0; i<nrep; i++) {
00297     if (m_AcquireCancel) {
00298       m_AcquireCancel = 0;
00299       break;
00300     } else {
00301       startAcquisition(i, nrep);
00302       waitAcquisition(i, nrep);
00303       readoutAcquisition(i, nrep);
00304 
00305       emit acquisitionProgress((i+1)*100.0/nrep);
00306     }
00307   }
00308 
00309   saveReferenceData();
00310 
00311   releaseAcquisitionLock();
00312 
00313   set_Status(AcquireDone);
00314   emit acquisitionCompleted();
00315 }
00316 
00317 void QavrgAcquisition::acquireOnce()
00318 {
00319   THREAD_CHECK;
00320 //
00321 //  QMutexLocker  lock(&m_Acquiring);
00322 
00323   setupAcquisition(AcquireOnce);
00324 
00325   startAcquisition(0,1);
00326   waitAcquisition(0,1);
00327   readoutAcquisition(0,1);
00328 
00329   emit acquisitionProgress(100);
00330 
00331   releaseAcquisitionLock();
00332 
00333   set_Status(AcquireDone);
00334   emit acquisitionCompleted();
00335 }
00336 
00337 void QavrgAcquisition::acquireScope()
00338 {
00339   THREAD_CHECK;
00340 //
00341 //  QMutexLocker  lock(&m_Acquiring);
00342 
00343   setupAcquisition(AcquireScope);
00344 
00345   for (int i=0; ; i++) {
00346 //    printf("m_AcquireCancel = %d\n", (int) m_AcquireCancel);
00347 //
00348     if (m_AcquireCancel) {
00349       m_AcquireCancel = 0;
00350       break;
00351     } else {
00352       configureAverager(AcquireScope);
00353 
00354       startAcquisition(0,1);
00355       waitAcquisition(0,1);
00356       readoutAcquisition(0,1);
00357 
00358       emit acquisitionProgress(-1);
00359     }
00360   }
00361 
00362   releaseAcquisitionLock();
00363 
00364   set_Status(AcquireDone);
00365   emit acquisitionCompleted();
00366 }
00367 
00368 int QavrgAcquisition::getAcquisitionLock()
00369 {
00370   if (m_Acquiring.tryLock()) {
00371 //    printf("Got acquisition lock\n");
00372     return 1;
00373   } else {
00374 //    printf("Failed to get acquisition lock\n");
00375     return 0;
00376   }
00377 }
00378 
00379 void QavrgAcquisition::releaseAcquisitionLock()
00380 {
00381 //  printf("Release acquisition lock\n");
00382 
00383   m_Acquiring.unlock();
00384 
00385   m_StatusWaiting.wakeAll();
00386 }
00387 
00388 bool QavrgAcquisition::checkStatus(int line, ViStatus status)
00389 {
00390   ViChar message[512];
00391 
00392   if (status == VI_SUCCESS/* || status == ACQIRIS_WARN_SETUP_ADAPTED*/) {
00393     return (status == VI_SUCCESS);
00394   } else {
00395     AcqrsD1_errorMessageEx(VI_NULL, status, message, sizeof(message));
00396 
00397     printf("%d: checkStatus(%lx) = %s\n", line, status, message);
00398 
00399     return false;
00400   }
00401 }
00402 
00403 void QavrgAcquisition::findDevices()
00404 {
00405   QMutexLocker lock(&m_AcquisitionMutex);
00406 
00407 //  printf("QavrgAcquisition::findDevices()\n");
00408 
00409   ViStatus status;
00410   ViChar options[] = "cal=0 dma=1";
00411 
00412   status = AcqrsD1_multiInstrAutoDefine(options, &m_NInstruments);
00413 
00414 //  printf("Status = %d, NInstruments = %ld\n", (int) status, m_NInstruments);
00415 
00416   if ((!CHECK_STATUS(status)) || (m_NInstruments <= 0)) {
00417     set_SimulationMode(true);
00418 
00419     m_TotalChannels = 4;
00420   }
00421 
00422 //  printf("Found %ld Acqiris Instruments\n", m_NInstruments);
00423 
00424   for (int i=0; i<m_NInstruments; i++) {
00425     char resourceName[20];
00426     sprintf(resourceName, "PCI::INSTR%d",i);
00427 
00428     status = AcqrsD1_InitWithOptions(resourceName, VI_FALSE, VI_FALSE,
00429                                      options, &m_InstrumentID[i]);
00430     CHECK_STATUS(status);
00431 
00432     status = AcqrsD1_getNbrChannels(m_InstrumentID[i], &m_CardNChannels[i]);
00433     CHECK_STATUS(status);
00434 
00435     printf("Instrument %d has %ld channels\n", i, m_CardNChannels[i]);
00436 
00437     CHECK_STATUS(AcqrsD1_configMode(m_InstrumentID[i], 2, 0, 0)); // 0 for dig, 2 for avg
00438 
00439     m_TotalChannels += m_CardNChannels[i];
00440   }
00441 
00442   setdef_NChannels(m_TotalChannels);
00443 
00444 //  printf("Starting fitter threads...\n");
00445 
00446   QMutexLocker lock2(&m_FittersMutex);
00447 
00448   m_Fitters.resize(m_TotalChannels);
00449 
00450   for (int i=0; i < m_TotalChannels; i++) {
00451     m_Fitters[i] = new QavrgFitter(this, i);
00452   }
00453 
00454 //  printf("Ready..\n");
00455 }
00456 
00457 void QavrgAcquisition::newSaveFile(QString f, int n)
00458 {
00459   printf("QavrgAcquisition::newSaveFile(%s,%d)\n", qPrintable(f), n);
00460 
00461   QFileInfo finfo(f);
00462   QDateTime dt = QDateTime::currentDateTime();
00463   QString datePath = dt.toString("yyyy/MM/dd/");
00464   QString filePath;
00465 
00466   if (finfo.isRelative()) {
00467     QDir od(get_OutputDirectory());
00468     filePath = od.absolutePath()+"/saveddata/"+datePath+f;
00469     od.mkpath(od.absolutePath()+"/saveddata/"+datePath);
00470     printf("filePath = %s\n", qPrintable(filePath));
00471   } else {
00472     filePath = f;
00473   }
00474 
00475   FILE* nf = fopen(qPrintable(filePath),"a+");
00476 
00477   if (nf) {
00478     QMutexLocker lock(&m_SaveFileMutex);
00479 
00480     if (m_SaveFile) {
00481       fclose(m_SaveFile);
00482       m_SaveFile = NULL;
00483     }
00484 
00485     m_SaveFile = nf;
00486     set_FileName(f);
00487     set_FilePath(filePath);
00488     set_ScanNumber(n);
00489 
00490     fprintf(m_SaveFile, "#F %s\n", qPrintable(f));
00491     fprintf(m_SaveFile, "#E %d\n", (int) ::time(NULL));
00492     fprintf(m_SaveFile, "#D %s\n", qPrintable(QDateTime::currentDateTime().toString()));
00493     fprintf(m_SaveFile, "\n");
00494     fflush(m_SaveFile);
00495   }
00496 }
00497 
00498 void QavrgAcquisition::closeSaveFile()
00499 {
00500   QMutexLocker lock(&m_SaveFileMutex);
00501 
00502   if (m_SaveFile) {
00503     fclose(m_SaveFile);
00504     m_SaveFile = NULL;
00505   }
00506 }
00507 
00508 void QavrgAcquisition::startNewScan(QcepStringVector header)
00509 {
00510   QMutexLocker lock(&m_SaveFileMutex);
00511 
00512   int n = get_ScanNumber();
00513   n++; set_ScanNumber(n);
00514 
00515   fprintf(m_SaveFile, "#S %d qavrgscan\n", n);
00516   fprintf(m_SaveFile, "#D %s\n", qPrintable(QDateTime::currentDateTime().toString()));
00517 
00518   int ncols = 0;
00519 
00520   for (int ch=0; ch < get_NChannels(); ch++) {
00521     QavrgFitter *f = fitter(ch);
00522 
00523     if (f) {
00524       ncols += /*3**/(f->resultSize());
00525     }
00526   }
00527 
00528   int nhdr  = header.size();
00529 
00530   fprintf(m_SaveFile, "#N %d\n", ncols+nhdr);
00531 
00532   for (int i=0; i<nhdr; i++) {
00533     if (i == 0) {
00534       fprintf(m_SaveFile, "#L %s", qPrintable(header[i]));
00535     } else {
00536       fprintf(m_SaveFile, "  %s", qPrintable(header[i]));
00537     }
00538   }
00539 
00540   for (int ch=0; ch < get_NChannels(); ch++) {
00541     QavrgFitter *f = fitter(ch);
00542 
00543     if (f) {
00544       int nbins = f->resultSize();
00545 
00546       for (int bin=0; bin < nbins; bin++) {
00547 //      for (int parm=0; parm<3; parm++) {
00548 //        fprintf(m_SaveFile, "  %s", qPrintable(resultHeader(ch, parm, bin)));
00549 //      }
00550         fprintf(m_SaveFile, "  %s", qPrintable(resultHeader(ch, QavrgFitter::PeakHeight, bin)));
00551       }
00552     }
00553   }
00554 
00555   fprintf(m_SaveFile, "\n");
00556   fflush(m_SaveFile);
00557 }
00558 
00559 void QavrgAcquisition::saveAcquisitionResult(QcepDoubleVector data)
00560 {
00561   QMutexLocker lock(&m_SaveFileMutex);
00562 
00563 //  printf("acquisition data ready\n");
00564 
00565   int nhdr = data.size();
00566 
00567   for (int i=0; i<nhdr; i++) {
00568     if (i == 0) {
00569       fprintf(m_SaveFile, "%g",   data[i]);
00570     } else {
00571       fprintf(m_SaveFile, " %g", data[i]);
00572     }
00573   }
00574 
00575   for (int ch=0; ch < get_NChannels(); ch++) {
00576     QavrgFitter *f = fitter(ch);
00577 
00578     if (f) {
00579       int nbins = f->resultSize();
00580 
00581       for (int bin=0; bin < nbins; bin++) {
00582 //      for (int parm=0; parm<3; parm++) {
00583 //        fprintf(m_SaveFile, " %g", readResult(ch, parm, bin));
00584 //      }
00585         fprintf(m_SaveFile, " %g", readResult(ch, QavrgFitter::PeakHeight, bin));
00586       }
00587     }
00588   }
00589 
00590   fprintf(m_SaveFile, "\n");
00591   fflush(m_SaveFile);
00592 }
00593 
00594 double QavrgAcquisition::readResultAverage(int chan, int parm, int start, int nbins)
00595 {
00596   QavrgFitter *f = fitter(chan);
00597 
00598   if (f) {
00599     return f->readResultAverage(parm,start,nbins);
00600   } else {
00601     return 0;
00602   }
00603 }
00604   
00605 double QavrgAcquisition::readResultBunchAverage(int chan, int parm, int bunch, int norbits)
00606 {
00607   QavrgFitter *f = fitter(chan);
00608 
00609   if (f) {
00610     return f->readResultBunchAverage(parm, bunch, norbits);
00611   } else {
00612     return 0;
00613   }
00614 }
00615 
00616 QVector<double> QavrgAcquisition::readResult(int chan, int parm, int start, int nbins)
00617 {
00618   QavrgFitter *f = fitter(chan);
00619 
00620   if (f) {
00621     return f->readResult(parm,start,nbins);
00622   } else {
00623     return QVector<double>();
00624   }
00625 }
00626 
00627 QVector<double> QavrgAcquisition::readResult(int chan, int parm)
00628 {
00629   QavrgFitter *f = fitter(chan);
00630 
00631   if (f) {
00632     return f->readResult(parm);
00633   } else {
00634     return QVector<double>();
00635   }
00636 }
00637 
00638 double QavrgAcquisition::readResult(int chan, int parm, int bin)
00639 {
00640   QavrgFitter *f = fitter(chan);
00641 
00642   if (f) {
00643     return f->readResult(parm,bin);
00644   } else {
00645     return 0;
00646   }
00647 }
00648 
00649 QString QavrgAcquisition::resultHeader(int chan, int /*parm*/, int bin)
00650 {
00651 //  const char * labels = "BSP";
00652   
00653   return tr("c%1o%2b%3").arg(chan).arg(orbitNumber(bin)).arg(bucketNumber(bin));
00654 }
00655 
00656 int QavrgAcquisition::orbitNumber(int n) const
00657 {
00658   int norb = get_FilledBucketsPerOrbit();
00659 
00660   if (norb) {
00661     return n/norb;
00662   } else {
00663     return n;
00664   }
00665 }
00666 
00667 int QavrgAcquisition::bucketNumber(int n) const
00668 {
00669   int norb = get_FilledBucketsPerOrbit();
00670 
00671   if (norb) {
00672     return n%norb;
00673   } else {
00674     return 0;
00675   }
00676 }
00677 
00678 
00679 void QavrgAcquisition::configureAverager(AcquisitionMode mode)
00680 {
00681   THREAD_CHECK;
00682 
00683   set_AcquisitionMode(mode);
00684 
00685   if (mode == AcquireScope) {
00686     set_AcquireIntegrationTime(get_ScopeIntegrationTime());
00687   } else {
00688     set_AcquireIntegrationTime(get_IntegrationTime());
00689   }
00690 
00691   if (get_SimulationMode()) {
00692     simulatedConfigureAverager(mode);
00693   } else {
00694     //    printf("configure averager (thread %p, this-thread() %p\n", QThread::currentThread(), thread());
00695 
00696     //   QMutexLocker lock(&m_Mutex);
00697 
00698     double sampInterval = 1.e-9, delayTime = 0.0;
00699     long trigCoupling = 0;
00700 
00701     long trigSlope = (get_TriggerSlope()==0 ? 1 : 0);
00702     double trigLevel = get_TriggerLevel()*1000;
00703 
00704     // ### Configuration parameters for averager ###
00705     long nbrSamples = get_NSamples();
00706     long nbrWaveForms = (long)(get_AcquireIntegrationTime()*get_LaserRepRate());
00707     long ditherRange = 0, trigResync = 1;
00708     long startDelay = 0, stopDelay = 0;
00709 
00710     for (int i=0, chan=0; i<m_NInstruments; i++) {
00711 
00712       // Configure timebase
00713       CHECK_STATUS(AcqrsD1_configHorizontal(m_InstrumentID[i], sampInterval, delayTime));
00714 
00715       switch (get_TriggerSource()) {
00716       case 0: // External trigger
00717         CHECK_STATUS(AcqrsD1_configTrigClass(m_InstrumentID[i], 0, 0x80000000, 0, 0, 0.0, 0.0));
00718         CHECK_STATUS(AcqrsD1_configTrigSource(m_InstrumentID[i], -1, trigCoupling, trigSlope, trigLevel, 0.0));
00719         break;
00720       case 1: // Channel 0 trigger
00721         CHECK_STATUS(AcqrsD1_configTrigClass(m_InstrumentID[i], 0, 0x00000001, 0, 0, 0.0, 0.0));
00722         CHECK_STATUS(AcqrsD1_configTrigSource(m_InstrumentID[i], 1, trigCoupling, trigSlope, trigLevel, 0.0));
00723         break;
00724       default:
00725         emit printMessage("Unknown trigger source");
00726         break;
00727       }
00728 
00729       ViInt32 temperature;
00730       CHECK_STATUS(AcqrsD1_getInstrumentInfo(m_InstrumentID[i], "Temperature", &temperature));
00731 
00732       emit printMessage(tr("card %1 temperature %2degC").arg(i).arg(temperature));
00733 
00734       for (long channel = 1; channel <= m_CardNChannels[i]; channel++, chan++) {
00735         double fullScale = fitter(chan) -> get_InputFullScale();
00736         double offset    = fitter(chan) -> get_InputOffset();
00737         long   bandwidth = fitter(chan) -> get_InputBandwidth();
00738         long   coupling  = fitter(chan) -> get_InputCoupling();
00739 
00740         //        printf("Chan %d : Full Scale %g, Offset %g, Bandwidth %d, Coupling %d\n", chan, fullScale, offset, bandwidth, coupling);
00741 
00742         // Configure vertical settings
00743         CHECK_STATUS(AcqrsD1_configVertical(m_InstrumentID[i], channel, fullScale, offset, coupling, bandwidth));
00744         // number of samples
00745         CHECK_STATUS(AcqrsD1_configAvgConfig(m_InstrumentID[i], channel, "NbrSamples", &nbrSamples));
00746         // number of waveforms
00747         CHECK_STATUS(AcqrsD1_configAvgConfig(m_InstrumentID[i], channel, "NbrWaveforms", &nbrWaveForms));
00748         // dithering range
00749         CHECK_STATUS(AcqrsD1_configAvgConfig(m_InstrumentID[i], channel, "DitherRange", &ditherRange));
00750         // trigger resync
00751         CHECK_STATUS(AcqrsD1_configAvgConfig(m_InstrumentID[i], channel, "TrigResync", &trigResync));
00752         // startDelay
00753         CHECK_STATUS(AcqrsD1_configAvgConfig(m_InstrumentID[i], channel, "StartDelay", &startDelay));
00754         // stopDelay
00755         CHECK_STATUS(AcqrsD1_configAvgConfig(m_InstrumentID[i], channel, "StopDelay", &stopDelay));
00756       }
00757     }
00758   }
00759 }
00760 
00761 void QavrgAcquisition::setupAcquisition(AcquisitionMode mode)
00762 {
00763   THREAD_CHECK;
00764 
00765   m_Acquiring.tryLock();
00766 
00767   set_Status(mode);
00768   emit acquisitionStarted();
00769   m_AcquireCancel = 0;
00770 
00771   configureAverager(mode);
00772 }
00773 
00774 void QavrgAcquisition::startAcquisition(int rep, int nrep)
00775 {
00776   THREAD_CHECK;
00777 
00778   m_Time.start();
00779 
00780   if (get_SimulationMode()) {
00781     simulatedStartAcquisition(rep, nrep);
00782   } else {
00783     // printf("start acquisition (thread %p, this-thread() %p\n", QThread::currentThread(), thread());
00784 
00785     if (rep == 0) {
00786       int nchan = get_NChannels();
00787       int nsamp = get_NSamples();
00788 
00789       m_Accumulator.resize(m_TotalChannels);
00790 
00791       for (int chan=0; chan<m_TotalChannels; chan++) {
00792         m_Accumulator[chan].resize(nsamp);
00793         m_Accumulator[chan].fill(0);
00794       }
00795 
00796       m_Buffer.resize(nsamp);
00797 //
00798 //      m_Futures.resize(nchan);
00799     }
00800 
00801     for (int i=0; i<m_NInstruments; i++) {
00802       CHECK_STATUS(AcqrsD1_acquire(m_InstrumentID[i]));
00803 
00804 //       if (get_TriggerSource() == 1) {
00805 //         printf("Attempt to force trigger\n");
00806 
00807 //         CHECK_STATUS(AcqrsD1_forceTrig(m_InstrumentID[i]));
00808 //       }
00809     }
00810   }
00811 }
00812 
00813 void QavrgAcquisition::waitAcquisition(int rep, int nrep)
00814 {
00815   THREAD_CHECK;
00816 
00817   if (get_SimulationMode()) {
00818     simulatedWaitAcquisition(rep, nrep);
00819   } else {
00820 //    printf("wait acquisition (thread %p, this-thread() %p\n", QThread::currentThread(), thread());
00821 
00822     unsigned int status = VI_SUCCESS;
00823 
00824     long waitTime = (long)((get_AcquireIntegrationTime()+5.0)*1000);
00825 
00826     for (int i=0; i<m_NInstruments; i++) {
00827       while (waitTime > 0) {
00828         status = AcqrsD1_waitForEndOfAcquisition(m_InstrumentID[i], 100);
00829 
00830 //      printf("QavrgAcquisition::waitAcquisition waitTime %ld, status %x, i %d\n", waitTime, status, i);
00831 
00832         waitTime -= 100;
00833         if (status == VI_SUCCESS || m_AcquireCancel) {
00834           break;
00835         }
00836       }
00837 
00838       waitTime = 2000;
00839 
00840       if (status == ACQIRIS_ERROR_ACQ_TIMEOUT) {
00841         CHECK_STATUS(AcqrsD1_stopAcquisition(m_InstrumentID[i]));
00842         emit printMessage("Acquisition timeout");
00843       }
00844     }
00845   }
00846 
00847   emit printMessage(tr("Acquisition took %1 msec").arg(m_Time.restart()));
00848 }
00849 
00850 void QavrgAcquisition::readoutAcquisition(int rep, int nrep)
00851 {
00852   THREAD_CHECK;
00853 
00854   if (get_SimulationMode()) {
00855     simulatedReadoutAcquisition(rep, nrep);
00856   } else {
00857     QTime timer;
00858 
00859     AqReadParameters       readParams;
00860     AqDataDescriptor       wfDesc;
00861     AqSegmentDescriptorAvg segDesc[1];
00862     int                    chan=0;
00863 
00864     int nsamples = get_NSamples();
00865 
00866     for (int i=0; i<m_NInstruments; i++) {
00867       timer.start();
00868 
00869       for (int ch=0; ch<m_CardNChannels[i]; ch++, chan++) {
00870         readParams.dataType           = ReadReal64;
00871         readParams.readMode           = ReadModeAvgW; // ReadModeStdW;
00872         readParams.nbrSegments        = 1;
00873         readParams.firstSampleInSeg   = 0;
00874         readParams.firstSegment       = 0;
00875         readParams.segmentOffset      = 0;
00876         readParams.segDescArraySize   = (long)sizeof(AqSegmentDescriptorAvg) * 1;
00877         readParams.nbrSamplesInSeg    = nsamples;
00878         readParams.dataArraySize      = sizeof(double)*nsamples;
00879         readParams.flags              = 0;
00880         readParams.reserved           = 0;
00881         readParams.reserved2          = 0.0;
00882         readParams.reserved3          = 0.0;
00883 
00884         CHECK_STATUS(AcqrsD1_readData(m_InstrumentID[i], ch+1, &readParams, m_Buffer.data(),
00885                                      &wfDesc, &segDesc));
00886 
00887 //        printf("rep = %d, nrepetitions = %d\n", rep, nrep);
00888 
00889         for (int i=0; i<nsamples; i++) {
00890           m_Accumulator[chan][i] += m_Buffer[i];
00891         }
00892       }
00893     }
00894 
00895     if (rep >= (nrep-1)) {
00896       switch (get_AcquisitionMode()) {
00897 
00898       case AcquireDone:
00899         printf("Invalid acquisition mode in QavrgAcquisition::readoutAcquisition\n");
00900         return;
00901 
00902       case AcquireData:
00903       case AcquireScope:
00904       case AcquireOnce:
00905         for (int chan=0; chan<m_TotalChannels; chan++) {
00906           fitter(chan) -> resize(nsamples);
00907           QMutexLocker lock(&m_AccumulatorMutex);
00908           QMutexLocker lock1(fitter(chan)->mutex());
00909 
00910           double *rawData = fitter(chan)->rawDataPtr();
00911           double *accum   = m_Accumulator[chan].data();
00912 
00913           for (int i = 0; i<nsamples; i++) {
00914             rawData[i] = accum[i]/nrep;
00915           }
00916         }
00917 
00918         if (get_AcquisitionMode() == AcquireScope) {
00919           incr_NQueuedResults();
00920 
00921           emit new_RawData();
00922         }
00923         break;
00924 
00925       case AcquireDark:
00926         for (int chan=0; chan<m_TotalChannels; chan++) {
00927           fitter(chan) -> resize(nsamples);
00928           QMutexLocker lock(&m_AccumulatorMutex);
00929           QMutexLocker lock1(fitter(chan)->mutex());
00930 
00931           double *darkData = fitter(chan)->darkDataPtr();
00932           double *accum   = m_Accumulator[chan].data();
00933 
00934           for (int i = 0; i<nsamples; i++) {
00935             darkData[i] = accum[i]/nrep;
00936           }
00937 
00938           fitter(chan) -> set_DarkAvailable(true);
00939         }
00940 
00941         incr_NQueuedResults();
00942 
00943         emit new_DarkData();
00944 
00945         break;
00946 
00947       case AcquireReference:
00948         for (int chan=0; chan<m_TotalChannels; chan++) {
00949           fitter(chan) -> resize(nsamples);
00950           QMutexLocker lock(&m_AccumulatorMutex);
00951           QMutexLocker lock1(fitter(chan)->mutex());
00952 
00953           double *refData = fitter(chan)->referenceDataPtr();
00954           double *accum   = m_Accumulator[chan].data();
00955 
00956           for (int i = 0; i<nsamples; i++) {
00957             refData[i] = accum[i]/nrep;
00958           }
00959 
00960           fitter(chan) -> set_ReferenceAvailable(true);
00961         }
00962 
00963         incr_NQueuedResults();
00964 
00965         emit new_ReferenceData();
00966 
00967         break;
00968       }
00969 
00970       if (get_AcquisitionMode() == AcquireData  || get_AcquisitionMode() == AcquireOnce) {
00971         QList< QFuture<void> > futures;
00972 
00973         for (int chan=0; chan<m_TotalChannels; chan++) {
00974           if (fitter(chan) -> get_ReferenceAvailable()) {
00975             //              printf("concurrent fitting, max Threads = %d\n", QThreadPool::globalInstance()->maxThreadCount());
00976             futures.append(QtConcurrent::run(fitter(chan), &QavrgFitter::performCalculation));
00977           }
00978         }
00979 
00980         foreach(QFuture<void> f, futures) {
00981           f.waitForFinished();
00982         }
00983 
00984         incr_NQueuedResults();
00985 
00986         emit new_FitData();  /* implies new_RawData(), also */
00987 
00988         emit new_FittingResults();
00989 
00990         emit printMessage(tr("Fitting complete after %1 msec").arg(m_Time.restart()));
00991       }
00992     }
00993   }
00994 }
00995 
00996 void QavrgAcquisition::saveData(QString fileName)
00997 {
00998   QFile outFile(fileName);
00999 
01000   if (outFile.open(QIODevice::Append)) {
01001     QTextStream out(&outFile);
01002 
01003     out << "#S 0 qavrg data\n";
01004     out << "#N " << 1+get_NChannels() << "\n";
01005     out << "#L n";
01006     for (int ch=0; ch<get_NChannels(); ch++) {
01007       out << "  chan" << ch;
01008     }
01009     out <<"\n";
01010 
01011     int nsamples = get_NSamples();
01012     int nchans   = get_NChannels();
01013 
01014     for (int i=0; i<nsamples; i++) {
01015       out << i;
01016 
01017       for (int ch=0; ch < nchans; ch++) {
01018         out  << "\t" << fitter(ch)->get_RawData(i);
01019       }
01020 
01021       out << "\n";
01022     }
01023   } else {
01024     emit warningMessage(tr("Unable to open output file %1").arg(fileName));
01025   }
01026 }
01027 
01028 void QavrgAcquisition::loadData(QString fileName)
01029 {
01030   emit warningMessage(tr("QavrgAcquisition::loadData has not been implemented"));
01031 }
01032 
01033 QcepSettingsSaverWPtr QavrgAcquisition::saver() const
01034 {
01035   return m_Application->saver();
01036 }