Ejemplo n.º 1
0
/*
 * Entry point - start the OneWire messaging server,
 * listening on a socket.
 */
int main (int argc, char **argv)
{
    ServerReturnCode returnCode = SERVER_ERR_GENERAL_FAILURE;
    UInt16 oneWireServerPort;

    setDebugPrintsOn();
    setProgressPrintsOn();

    if (argc == 2)
    {
        oneWireServerPort = atoi (argv[1]);
        printProgress ("OneWireServer listening on port %d.\n", oneWireServerPort);

        returnCode = runMessagingServer (oneWireServerPort);
        
        if (returnCode == SERVER_EXIT_NORMALLY)
        {
            printProgress ("OneWireServer exiting normally.\n");            
        }
        else
        {
            printProgress ("OneWireServer exiting with returnCode %d.\n", returnCode);                        
        }            
    }    
    else
    {
        printProgress ("Usage: %s portnumber\ne.g. %s 5234\n", argv[0], argv[0]);
    }
    
    return returnCode;
}
Ejemplo n.º 2
0
/**
 * Initializes the SMTP communications by sending the EHLO
 * If EHLO errors out, it will try the HELO command.
 *
 * Params
 * 	sd - Socket descriptor
 * 	domain - Your domain name.
 *
 * Return
 * 	- ERROR
 * 	- SUCCESS
 */
int
smtpInit(dsocket *sd, const char *domain)
{
	int retval;

	printProgress("Init connection...");
	retval = init(sd);
	if (retval == ERROR) {
		return retval;
	}

	printProgress("Greeting the SMTP server...");
	retval = ehlo(sd, domain);
	if (retval == ERROR) {
		/*
		 * Per RFC, if ehlo error's out, you can
		 * ignore the error, RSET and try a 
		 * regular helo.
		 */
		rset(sd);
		retval = helo(sd, domain);
	}

	return retval;
}
Ejemplo n.º 3
0
void ConsoleUpdater::onProgressChange(const ProgressInfo& info)
{
	bool progressPrinted = false;
	switch (info.type)
	{
	case ProgressInfo::FileDownload:
		if( info.mirrorDisplayName.empty() )
			break;

		// Download progress
    if (!_d->info.file.toString().empty()
        && info.file.toString() != _d->info.file.toString() )
		{
			// New file, finish the current download
      _d->info.progressFraction = 1.0f;
      _d->progressDone = false;
			progressPrinted = true;
      printProgress();

			// Add a line break when a new file starts
      Logger::warning( fmt::format( "\nDownloading from Mirror {}: {}", info.mirrorDisplayName, info.file.toString() ) );
		}
    else if (_d->info.file.toString().empty())
		{
			// First file
      Logger::warning( fmt::format( " Downloading from Mirror {}: {}", info.mirrorDisplayName, info.file.toString() ) );
		}

    _d->info = info;

		// Print the new info
		if( !progressPrinted )
      printProgress();

		// Add a new line if we're done here
    if( info.progressFraction >= 1 && !_d->progressDone)
		{
      _d->progressDone = true;
			Logger::warning( "\n" );
		}
		break;

	case ProgressInfo::FileOperation:

    _d->info = info;

		// Print the new info
    printProgress();

		// Add a new line if we're done here
		if (info.progressFraction >= 1)
		{
			Logger::warning( "\n");
		}
	break;

	default: break;
	};
}
Ejemplo n.º 4
0
bool QInstallPage::writeQString2File( const QString& the_string,
                                        const QString& fname ){
    QFile* the_file = new QFile( fname  );
    if ( ! the_file->open( QIODevice::WriteOnly ) ){
        printProgress( (QString)"Error opening file " + fname + " for writing \n" );
        printProgress( (QString)"Check that it exists or could be created ..." );
        return false;
    }
    QTextStream the_stream;
    the_stream.setDevice( the_file );
    the_stream << the_string;
    the_file->close();
    return true;
}
Ejemplo n.º 5
0
void XMLerLoadUrlThread::run()
{
	QNetworkRequest request(url);
	QNetworkReply* rep = mNetworkManager->get(request);
	connect(rep, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(printProgress(qint64, qint64)));
	disconnect(rep, SIGNAL(downloadProgress(qint64, qint64)));
}
Ejemplo n.º 6
0
int calcMD5(int file, int size, char* fname){
	unsigned char c[MD5_DIGEST_LENGTH];
	MD5_CTX mdContext;
	int delay = 0, bytes, i, written = 0;
	unsigned char data[DATA_BUF_SIZE];
	MD5_Init(&mdContext);
	while((bytes = read(file, data, DATA_BUF_SIZE)) != 0){
		written+=bytes;
		if(++delay > DELAY_LENGTH) {
			printProgress(MD5_TAG, written, size);
			delay = 0;
		}
		MD5_Update(&mdContext, data, bytes);
	}
	MD5_Final(c, &mdContext);
	printf("\n%s: ", MD5_TAG);
	for(i=0; i < MD5_DIGEST_LENGTH; i++) printf("%02x",c[i]);
	printf("\n");
	lseek(file, 0, SEEK_SET); //return to beginning of file
	
	//write to file
	char final[256] = MD5_TAG;
	strcat(final, fname);
	strcat (final, ".txt");
	FILE *fp = fopen(final, "w");
	if(fp){
		for(i=0; i < MD5_DIGEST_LENGTH; i++) fprintf(fp, "%02x",c[i]);
		fprintf(fp, "\t%s", fname);
	}
	fclose(fp);
	
	return 0;
}
Ejemplo n.º 7
0
int RecursiveSolver::guess(int index) {
	printProgress(count, _field);
	bool succes = false;
	for (int option : options[index]) {
		if (_field.get(index) >= option) { // We have tried this slot before
			continue;
		}
		if (_field.fit(index, option)) {
			_field.set(index, option);
			succes = true;
			break;
		}
	}
	map<int, vector<int>>::iterator it;
	it = options.find(index);
	if (succes) {
		if (_field.countEmpty(true) > 0) {
			// Find the the next empty slot in the vector
			//guess(std::next(it)->first);
			return RETURN_NEXT;
		} else {
			return RETURN_EXIT;
		}
	} else {
		_field.set(index, 0);
		// Find the the previous tried slot in the vector
		//guess(std::prev(it)->first);
		return RETURN_PREV;
	}
}
Ejemplo n.º 8
0
/**
 * Sends the QUIT\r\n signal to the smtp server.
 *
 * Params
 * 	sd - Socket Descriptor
 *
 * Return
 * 	- ERROR
 * 	- SUCCESS
 */
int
smtpQuit(dsocket *sd)
{
	int retval=0;
	printProgress("Sending QUIT...");
	retval = quit(sd);
	dsbDestroy(errorstr);
	return retval;
}
Ejemplo n.º 9
0
int
smtpInitAfterTLS(dsocket *sd, const char *domain)
{
	int retval;

	printProgress("Greeting the SMTP server...");
	retval = ehlo(sd, domain);

	return retval;
}
Ejemplo n.º 10
0
/**
 * Takes a timer structure and a pointer to the progress array.
 * it checks if the time since given structure was initiated has passed 500 ms
 * if so it passed the progress structure to the printprogress function
 * @param timer
 * @param progress
 */
void checkTimer(timeval &timer,int *progress){

    timeval time2;
    gettimeofday(&time2, NULL);
    long millis = (timer.tv_sec * 1000) + (timer.tv_usec / 1000);
    long millis2 = (time2.tv_sec * 1000) + (time2.tv_usec / 1000);
    long timeElapsed = millis2 - millis;
    
    if(timeElapsed>=500){
        printProgress(progress);
        resetTimer(timer);
    }
}
Ejemplo n.º 11
0
	void checkTimer(SYSTEMTIME &timer,int *progress){
		SYSTEMTIME time2;
		GetSystemTime(&time2);

		long millis = (timer.wHour*3600000)+(timer.wMinute*60000)+(timer.wSecond * 1000) + timer.wMilliseconds;
		long millis2 = (time2.wHour*3600000)+(time2.wMinute*60000)+(time2.wSecond * 1000) + time2.wMilliseconds;
		
		float timeElapsed = millis2-millis;
		if(timeElapsed>=500){
			printProgress(progress);
			resetTimer(timer);
		}

	}
Ejemplo n.º 12
0
QString QInstallPage::readFile2QString( const QString& fname,
                                          const QString& err ){
    QFile* the_file = new QFile( fname  );
    if ( ! the_file->open( QIODevice::ReadOnly  ) ){
        printProgress( err );
        return QString::null;
    }
    QTextStream the_stream;
    the_stream.setDevice( the_file );
    QString the_string = the_stream.readAll();
//     the_stream.unsetDevice();
    the_file->close();
    return the_string;
}
Ejemplo n.º 13
0
void ClassifierApplication::showNextSubStep(int subStep)
{
    mutex->lock();
    mSubStep = subStep;
    int progress = 0;
    if (mSubStepCount != 0)
        progress = int(10 * mSubStep / mSubStepCount);

    if (mCurrentSubProgress < progress)
    {
        mCurrentSubProgress = progress;
        printProgress();
    }
    mutex->unlock();
}
Ejemplo n.º 14
0
int FrameCapture::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: finished(); break;
        case 1: printProgress((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 2: saveResult((*reinterpret_cast< bool(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 3;
    }
    return _id;
}
Ejemplo n.º 15
0
Launcher::Launcher(int numImages, int numThreads, QString workerCommand, QStringList args) : runningProcs(0),
    timer(this),workCmd(workerCommand),procCount(1),workArgs(args)
{
    if(numThreads > numImages)
        numThreads = numImages;// more threads than images are useless!

    int iPerThread = numImages / numThreads; //we roud down here as we use ints

    for(int i = 0; i < (numThreads - 1); i++){
        startProcess(i*iPerThread, iPerThread);
    }
    startProcess((numThreads -1)*iPerThread, numImages - (numThreads -1)*iPerThread);

    connect(&timer,SIGNAL(timeout()),this,SLOT(printProgress()));
    timer.setInterval(100);
    timer.start();
}
Ejemplo n.º 16
0
void Scene::render()
{
  vec2 pixel;
  Ray r;
  Color c;
  printProgressHeader();
  int count = 0;

  while (getSample(&pixel)) {
	r = cam->generateRay(pixel);
	c = rt->trace(r, scene->getMaxDepth());
	film->put(pixel, c);
	count++;
	printProgress(count);
  }
  
  cout << endl;
  film->writeToFile(outputPath);
}
Ejemplo n.º 17
0
/* genera tutte le chiavi wpa possibili per ssid-series-macAddr specificati */
int generateKeys(unsigned long int ssid, unsigned long int series, unsigned char *macAddr)
{ 
	int i;
	
    for(serial = userOptions.startSerial; serial < userOptions.endSerial; serial++) /* per ogni serial... */
    {
    
    	if(cycle % PRINT_RATE == 0)
        {
            printProgress();
        }
        
        sprintf(seriesXserial, "%05dX%07d", series, serial); /* crea la stringa serie-X-seriale */
            
        /* calcola l'hash SHA256(fixedPadding + serie-X-seriale + MAC) */
        sha256_starts(shaCtx); 
        sha256_update(shaCtx, fixedPadding, sizeof(fixedPadding));
        sha256_update(shaCtx, seriesXserial, SERIESXSERIAL_SIZE);
        sha256_update(shaCtx, macAddr, MAC_SIZE);
        sha256_finish(shaCtx, hash);
            
        /* converte l'hash in caratteri ASCII */
        for(i = 0; i < WPA_SIZE; i++) wpa[i] = charset[hash[i]];

        if(userOptions.opMode == FINDKEY) /* stiamo cercando una chiave particolare */
        {
            if(isWpaCorrect() == TRUE)
            {
                return KEYFOUND;
            }
        }
        else if(userOptions.opMode == GENFILE) /* stiamo generando il dizionario */
        {
            if(writeWpaToBuffer() == FAILURE)
            {
                lastErr = FILE_ERR;
                return FAILURE;
            }
        }
        cycle++;
    }
    return SUCCESS;
}
Ejemplo n.º 18
0
Message* Parser::parseMessage(uint64_t& reference, uint64_t& match) {
	char test = '\0';
	if (!binaryData.get(test)) return NULL;
	binaryData.get(test);
	uint32_t size = test - '\0';
	binaryData.read(buffer, size);
	printProgress(size + 2);
	switch (*buffer) {
	case 'R':
		return buildSD(buffer);
		break;
	case 'A':
	case 'F':
		return buildAO(buffer, reference);
		break;
	case 'E':
		return buildOE(buffer, reference, match);
		break;
	case 'C':
		return buildOEWP(buffer, reference, match);
		break;
	case 'D':
		return buildOD(buffer, reference);
		break;
	case 'U':
		return buildOR(buffer, reference);
		break;
	case 'P':
	case 'Q':
		return buildT(buffer, match);
		break;
	case 'B':
		return buildBT(buffer, match);
		break;
	default: {
		//cout << "skipping non-relevant message, type: " << *buffer << endl; 
		return new Message('\0');
	}
	}
}
Ejemplo n.º 19
0
/**
 * Let's the SMTP server know it's the end of the data stream.
 *
 * Params
 * 	sd - Socket descriptor
 *
 * Return
 * 	- ERROR
 * 	- SUCCESS
 */
int 
smtpEndData(dsocket *sd)
{
	int retval=ERROR;
	dstrbuf *rbuf = DSB_NEW;

	printProgress("Ending Data...");
	if (writeResponse(sd, "\r\n.\r\n") != ERROR) {
		retval = readResponse(sd, rbuf);
		if (retval != 250) {
			if (retval != ERROR) {
				smtpSetErr(rbuf->str);
				retval = ERROR;
			}
		}
	} else {
		smtpSetErr("Lost Connection with SMTP server: smtpEndData()");
		retval = ERROR;
	}

	dsbDestroy(rbuf);
	return retval;
}
Ejemplo n.º 20
0
int
smtpStartTls(dsocket *sd)
{
        int retval=SUCCESS;
#ifdef HAVE_LIBSSL
        dstrbuf *sb=DSB_NEW;

	printProgress("Starting TLS Communications...");
        if (writeResponse(sd, "STARTTLS\r\n") < 0) {
                smtpSetErr("Lost connection to SMTP Server");
                retval = ERROR;
                goto end;
        }

#ifdef DEBUG_SMTP
	printf("--> STARTTLS\n");
	fflush(stdout);
#endif

        retval = readResponse(sd, sb);
        if (retval != 220) {
                smtpSetErr(sb->str);
                retval = ERROR;
        }

#ifdef DEBUG_SMTP
	printf("<-- %s\n", sb->str);
	fflush(stdout);
#endif

end:
        dsbDestroy(sb);
#else
	sd = sd;
#endif
        return retval;
}
Ejemplo n.º 21
0
int VCS_SOLVE::vcs_setMolesLinProg()
{
    size_t ik, irxn;
    double test = -1.0E-10;

    if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) {
        plogf("   --- call setInitialMoles\n");
    }

    double dg_rt;
    int idir;
    double nu;
    double delta_xi, dxi_min = 1.0e10;
    bool redo = true;
    int retn;
    int iter = 0;
    bool abundancesOK = true;
    bool usedZeroedSpecies;
    vector_fp sm(m_numElemConstraints*m_numElemConstraints, 0.0);
    vector_fp ss(m_numElemConstraints, 0.0);
    vector_fp sa(m_numElemConstraints, 0.0);
    vector_fp wx(m_numElemConstraints, 0.0);
    vector_fp aw(m_numSpeciesTot, 0.0);

    for (ik = 0; ik < m_numSpeciesTot; ik++) {
        if (m_speciesUnknownType[ik] != VCS_SPECIES_INTERFACIALVOLTAGE) {
            m_molNumSpecies_old[ik] = max(0.0, m_molNumSpecies_old[ik]);
        }
    }

    if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) {
        printProgress(m_speciesName, m_molNumSpecies_old, m_SSfeSpecies);
    }

    while (redo) {
        if (!vcs_elabcheck(0)) {
            if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) {
                plogf(" --- seMolesLinProg  Mole numbers failing element abundances\n");
                plogf(" --- seMolesLinProg  Call vcs_elcorr to attempt fix\n");
            }
            retn = vcs_elcorr(&sm[0], &wx[0]);
            if (retn >= 2) {
                abundancesOK = false;
            } else {
                abundancesOK = true;
            }
        } else {
            abundancesOK = true;
        }
        /*
         *  Now find the optimized basis that spans the stoichiometric
         *  coefficient matrix, based on the current composition, m_molNumSpecies_old[]
         *  We also calculate sc[][], the reaction matrix.
         */
        retn = vcs_basopt(false, &aw[0], &sa[0], &sm[0], &ss[0],
                          test, &usedZeroedSpecies);
        if (retn != VCS_SUCCESS) {
            return retn;
        }

        if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) {
            plogf("iteration %d\n", iter);
        }
        redo = false;
        iter++;
        if (iter > 15) {
            break;
        }

        // loop over all reactions
        for (irxn = 0; irxn < m_numRxnTot; irxn++) {
            // dg_rt is the Delta_G / RT value for the reaction
            ik = m_numComponents + irxn;
            dg_rt = m_SSfeSpecies[ik];
            dxi_min = 1.0e10;
            const double* sc_irxn = m_stoichCoeffRxnMatrix.ptrColumn(irxn);
            for (size_t jcomp = 0; jcomp < m_numElemConstraints; jcomp++) {
                dg_rt += m_SSfeSpecies[jcomp] * sc_irxn[jcomp];
            }
            // fwd or rev direction.
            //  idir > 0 implies increasing the current species
            //  idir < 0 implies decreasing the current species
            idir = (dg_rt < 0.0 ? 1 : -1);
            if (idir < 0) {
                dxi_min = m_molNumSpecies_old[ik];
            }

            for (size_t jcomp = 0; jcomp < m_numComponents; jcomp++) {
                nu = sc_irxn[jcomp];
                // set max change in progress variable by
                // non-negativity requirement
                if (nu*idir < 0) {
                    delta_xi = fabs(m_molNumSpecies_old[jcomp]/nu);
                    // if a component has nearly zero moles, redo
                    // with a new set of components
                    if (!redo && delta_xi < 1.0e-10 && (m_molNumSpecies_old[ik] >= 1.0E-10)) {
                        if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) {
                            plogf("   --- Component too small: %s\n", m_speciesName[jcomp]);
                        }
                        redo = true;
                    }
                    dxi_min = std::min(dxi_min, delta_xi);
                }
            }

            // step the composition by dxi_min, check against zero, since
            // we are zeroing components and species on every step.
            // Redo the iteration, if a component went from positive to zero on this step.
            double dsLocal = idir*dxi_min;
            m_molNumSpecies_old[ik] += dsLocal;
            m_molNumSpecies_old[ik] = max(0.0, m_molNumSpecies_old[ik]);
            for (size_t jcomp = 0; jcomp < m_numComponents; jcomp++) {
                bool full = false;
                if (m_molNumSpecies_old[jcomp] > 1.0E-15) {
                    full = true;
                }
                m_molNumSpecies_old[jcomp] += sc_irxn[jcomp] * dsLocal;
                m_molNumSpecies_old[jcomp] = max(0.0, m_molNumSpecies_old[jcomp]);
                if (full && m_molNumSpecies_old[jcomp] < 1.0E-60) {
                    redo = true;
                }
            }
        }

        if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) {
            printProgress(m_speciesName, m_molNumSpecies_old, m_SSfeSpecies);
        }
    }

    if (DEBUG_MODE_ENABLED && m_debug_print_lvl == 1) {
        printProgress(m_speciesName, m_molNumSpecies_old, m_SSfeSpecies);
        plogf("   --- setInitialMoles end\n");
    }
    retn = 0;
    if (!abundancesOK) {
        retn = -1;
    } else if (iter > 15) {
        retn = 1;
    }
    return retn;
}
Ejemplo n.º 22
0
int uncompress(FILE *input, FILE *output) {
    printProgress(1,0.00);
    return 0;
}
Ejemplo n.º 23
0
void getXsecExtended(const TString mc_input, int debugMode=0, bool useFEWZ=true, int fineGrid=0)
{
  // check whether it is a calculation
  if (mc_input.Contains("_DebugRun_")) {
    std::cout << "getXsec: _DebugRun_ detected. Terminating the script\n";
    return;
  }

  if (debugMode==1) std::cout << "\n\n\tDEBUG MODE is ON\n\n";
  if (debugMode==-1) std::cout << "\n\n\tPLOT ONLY MODE is ON\n\n";
  std::cout << "DYTools::analysisTag=" << DYTools::analysisTag << "\n";

  if (DYTools::study2D && fineGrid) {
    std::cout << "fineGrid=1 is allowed only for study2D=0\n";
    return;
  }

  // normal calculation

  gBenchmark->Start("getXsec");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  //Bool_t doSave  = false;    // save plots?
  TString format = "png";   // output file format
  MCInputFileMgr_t inpMgr;
  TString fineGridStr;
  if (fineGrid==1) fineGridStr="fineGrid_";
  else if (fineGrid==2) fineGridStr="summer2011Grid_";
  else if (fineGrid==3) fineGridStr="summer2011specGrid_";
  
  Double_t massLow  = DYTools::massBinLimits[0];
  Double_t massHigh = DYTools::massBinLimits[DYTools::nMassBins];

  // fine grid: 0, 1, 2, ..., (fineGrid_1GeVstop-1), fineGrid_1GeVstop, fineGrid_1GeVstop+fineGridLargerStep, fineGrid_1GeVstop+2*fineGridLargerStep, ..., 1500
  //
  double fineGrid_1GeVstop=200.;
  double fineGrid_LargerStep=20.;

  int locMassBinCount=DYTools::nMassBins;
  double *massRangeEdges=NULL;
  if (!fineGrid) {
    massRangeEdges=new double[locMassBinCount+1];
    for (int i=0; i<=DYTools::nMassBins; ++i) {
      massRangeEdges[i]=DYTools::massBinLimits[i];
    }
  }
  else if (fineGrid==1) {
    // 1GeV grid
    locMassBinCount=int(fineGrid_1GeVstop-massLow+1e-3);
    std::cout << "1GeV grid size=" << locMassBinCount << "\n";
    // fineGrid_LargerStep
    double upperRange= (massHigh-fineGrid_1GeVstop);
    double upperCount= upperRange/fineGrid_LargerStep + 1e-3;
    if (upperCount - trunc(upperCount) > 1e-3) {
      std::cout << "(upperCount -1e-3)=" << (upperCount -1e-3) << "\n";
      std::cout << "should be integer value\n";
      return;
    }
    locMassBinCount += int(upperCount);
    std::cout << "mass grid[" << locMassBinCount << "]\n";

    massRangeEdges=new double[locMassBinCount+1];
    double m=massLow, dm=1;
    int count=0;
    while (m<=massHigh) {
      massRangeEdges[count]=m;
      if (1) {
	if (m<massHigh) std::cout << "count=" << count << ", massRange=" << m << " .. " << (m+dm) << "\n";
	else std::cout << "last edge=" << m << "\n";
      }
      count++;
      m+=dm;
      if (m==fineGrid_1GeVstop) dm=fineGrid_LargerStep;
    }
  }
  else if (fineGrid==2) {
    const int nMassBinTh=518;
    Double_t mxl = 14.0;
    locMassBinCount=nMassBinTh;
    massRangeEdges=new double[nMassBinTh+1];

    for(int iTh=0; iTh<=nMassBinTh; iTh++){
      // mass limits
      if     ( iTh >=   0 && iTh <  11 ) {mxl += 1.0;}
      else if( iTh >=  11 && iTh <  18 ) {mxl += 5.0;}
      else if( iTh >=  18 && iTh < 118 ) {mxl += 1.0;}
      else if( iTh >= 118 && iTh < 340 ) {mxl += 2.0;}
      else if( iTh >= 340 && iTh < nMassBinTh)   {mxl += 5.0; }
      else if( iTh == nMassBinTh)                {mxl = 1500; }
      massRangeEdges[iTh]=mxl;
    }
  }
  else if (fineGrid==3) {
    const int nMassBinTh=518;
    Double_t mxl = 14.0;
    locMassBinCount=nMassBinTh;
    massRangeEdges=new double[nMassBinTh+1];

    int iTh_new=0, tmpCounter=0;
    for(int iTh=0; iTh<=nMassBinTh; iTh++, iTh_new++){
      // mass limits
      if     ( iTh >=   0 && iTh <  11 ) {mxl += 1.0;}
      else if( iTh >=  11 && iTh <  18 ) {mxl += 5.0;}
      else if( iTh >=  18 && iTh < 118 ) {mxl += 1.0;}
      else if( iTh >= 118 && iTh < 340 ) {
	if (iTh>=139) {
	  std::cout << "iTh=" << iTh << ", current mxl=" << mxl << " +2\n";
	  if (iTh==139) tmpCounter=10;
	  tmpCounter--;
	  if (tmpCounter>0) iTh_new--;
	  else if (tmpCounter==0) {
	    tmpCounter=10;
	    std::cout << "iTh=" << iTh << ", iTh_new=" << iTh_new << ", current mxl=" << mxl << " +10\n";
	  }
	}
	mxl += 2.0;
      }
      else if( iTh >= 340 && iTh < nMassBinTh)   {
	std::cout << "iTh=" << iTh << ", current mxl=" << mxl << " +5\n";
	if (iTh<342) iTh_new--;
	else {
	  if ((iTh-342)%4>0) iTh_new--;
	  else std::cout << "iTh=" << iTh << ", iTh_new=" << iTh_new << ", current mxl=" << mxl << " +10\n";
	}
	mxl += 5.0; 
      }
      else if( iTh == nMassBinTh)                {mxl = 1500; }
      massRangeEdges[iTh_new]=mxl;
    }
    massRangeEdges[iTh_new-2]=1500.;
    std::cout << "iTh_new=" << iTh_new << "\n";
    locMassBinCount=iTh_new-2;
  }

  TVectorD massGrid(locMassBinCount+1);
  for (int i=0; i<=locMassBinCount; ++i) massGrid[i]=massRangeEdges[i];
  TH1F hMassIdx("h_massIdx","h_massIdx",locMassBinCount-1,massRangeEdges);
  //delete massRangeEdges;

  if (0) {
    printHisto(&hMassIdx);
    if (0) {
      for (int i=0; i<int(massHigh); ++i) {
	double m=i+0.5;
	std::cout << "i=" << i << ", m=" << m << ", idx=" << (hMassIdx.FindBin(m)-1) << "\n";
      }
    }
    return;
  }

  //std::cout << "massHigh=" << massHigh << "\n";
  //std::cout << "locMassBinCount=" << locMassBinCount << "\n";

  if (!inpMgr.Load(mc_input)) {
    return;
  }
  
  //--------------------------------------------------------------------------------------------------------------
  // Main code 
  //==============================================================================================================
  
  //  
  // Set up histograms
  //

  //vector<TH1D*> hZMassv;
  
  Double_t   nZv = 0;

  TMatrixD nEvents (locMassBinCount,DYTools::nYBinsMax);    // number of weigthed events
  TMatrixD nEventsDET (locMassBinCount,DYTools::nYBinsMax); // number of weighted events in the detector acceptance
  TMatrixD nEventsDETrecoPostIdx (locMassBinCount,DYTools::nYBinsMax);    // number of weigthed events
  TMatrixD w2Events (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD w2EventsDET (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD w2EventsDETrecoPostIdx (locMassBinCount,DYTools::nYBinsMax);
  Double_t nZpeak=0, w2Zpeak=0;
  double nZpeakDET=0, w2ZpeakDET=0;
  double nZpeakDETrecoPostIdx=0, w2ZpeakDETrecoPostIdx=0;

  nEvents = 0;
  w2Events = 0;
  nEventsDET = 0;
  w2EventsDET  = 0;
  nEventsDETrecoPostIdx = 0;
  w2EventsDETrecoPostIdx  = 0;

  //char hname[100];
  //for(UInt_t ifile = 0; ifile<fnamev.size(); ifile++) {
  //  sprintf(hname,"hZMass_%i",ifile); hZMassv.push_back(new TH1F(hname,"",500,0,500)); hZMassv[ifile]->Sumw2();
  //}

  // 
  // Read weights from a file
  //
  const bool useFewzWeights = useFEWZ;
  const bool cutZPT100 = true;
  FEWZ_t fewz(useFewzWeights,cutZPT100);
  if (useFewzWeights && !fewz.isInitialized()) {
    std::cout << "failed to prepare FEWZ correction\n";
    throw 2;
  }

  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
    
  // Data structures to store info from TTrees
  mithep::TGenInfo *gen  = new mithep::TGenInfo();

  // loop over samples  
  double lumi0=0;
  if (debugMode!=-1) {
  for(UInt_t ifile=0; ifile<inpMgr.fileNames().size(); ifile++) {
  
    // Read input file
    cout << "Processing " << inpMgr.fileName(ifile) << "..." << endl;
    infile = new TFile(inpMgr.fileName(ifile));
    assert(infile);

    // Get the TTrees
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);

    // Find weight for events for this file
    // The first file in the list comes with weight 1,
    // all subsequent ones are normalized to xsection and luminosity
    double lumi  = eventTree->GetEntries()/inpMgr.xsec(ifile);
    if (ifile==0) lumi0=lumi;
    double scale = lumi0/lumi;
    std::cout << "       -> sample weight is " << scale << endl;

    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Gen",&gen);
    TBranch *genBr = eventTree->GetBranch("Gen");
 
    // loop over events    
    nZv += scale * eventTree->GetEntries();

    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
      if (debugMode && (ientry>100000)) break;

      genBr->GetEntry(ientry);
      if (ientry%1000000==0) printProgress("ientry=",ientry,eventTree->GetEntriesFast());

      double massPreFsr = gen->vmass;   // pre-FSR
      double yPreFsr = gen->vy;    // pre-FSR
      double massPostFsr = gen->mass;   // post-FSR
      double yPostFsr = gen->y;    // post-FSR

      if ((massPreFsr < massLow) || (massPreFsr > massHigh)) continue;
      if ((fabs(yPreFsr) < DYTools::yRangeMin) || 
	  (fabs(yPreFsr) > DYTools::yRangeMax)) continue;

      int ibinMassPreFsr=-1, ibinYPreFsr=-1;
      int ibinMassPostFsr=-1, ibinYPostFsr=-1;

      if (!fineGrid) {
	ibinMassPreFsr = DYTools::findMassBin(massPreFsr);
	ibinMassPostFsr= DYTools::findMassBin(massPostFsr);
	ibinYPreFsr = DYTools::findAbsYBin(ibinMassPreFsr, yPreFsr);
	ibinYPostFsr= DYTools::findAbsYBin(ibinMassPostFsr, yPostFsr);
      }
      else {
	ibinMassPreFsr=hMassIdx.FindBin(massPreFsr)-1;
	ibinMassPostFsr=hMassIdx.FindBin(massPostFsr)-1;
	ibinYPreFsr=0;
	ibinYPostFsr=0;
	//printf("massPreFsr=%8.4lf, idx=%3d;  massPostFsr=%8.4lf, idx=%3d\n", massPreFsr,ibinMassPreFsr, massPostFsr,ibinMassPostFsr);
      }

      // We are only interested in the events, reconstructed with 
      // good mass and rapidity 
      if (ibinMassPreFsr==-1 || 
	  ibinMassPreFsr>=locMassBinCount || 
	  ibinYPreFsr==-1) {
	printf(".. skipping mass=%6.4lf, y=%6.4lf. ibinMass=%d, ibinY=%d\n",massPreFsr,yPreFsr,ibinMassPreFsr,ibinYPreFsr);
	continue;
      }

      // Find FEWZ-powheg reweighting factor 
      // that depends on pre-FSR Z/gamma* rapidity, pt, and mass
      double fewz_weight = 1.0;

      if(useFewzWeights) {
	fewz_weight=fewz.getWeight(gen->vmass,gen->vpt,gen->vy);
      }

      //std::cout << "weight=scale*gen->weight*fewz: " << scale << " * " << gen->weight << " * " << fewz_weight << "\n";
      double fullWeight = scale * gen->weight * fewz_weight;
      nEvents(ibinMassPreFsr,ibinYPreFsr) += fullWeight;
      w2Events(ibinMassPreFsr,ibinYPreFsr) += fullWeight*fullWeight;

      // Pre-FSR cross section
      if( DYTools::goodEtPair(gen->vpt_1, gen->vpt_2) &&
	  DYTools::goodEtaPair(gen->veta_1, gen->veta_2) ) {
	nEventsDET(ibinMassPreFsr,ibinYPreFsr) += fullWeight;
	w2EventsDET(ibinMassPreFsr,ibinYPreFsr) += fullWeight*fullWeight;
      }

      // Post-FSR cross section
      if(  (ibinMassPostFsr!=-1) && (ibinYPostFsr!=-1) &&
	   DYTools::goodEtPair(gen->pt_1, gen->pt_2) &&
	   DYTools::goodEtaPair(gen->eta_1, gen->eta_2) ) {
	nEventsDETrecoPostIdx(ibinMassPostFsr,ibinYPostFsr) += fullWeight;
	w2EventsDETrecoPostIdx(ibinMassPostFsr,ibinYPostFsr) += fullWeight*fullWeight;
      }
    }
    delete infile;
    infile=0, eventTree=0;
  }
  delete gen;

  // Determine Z-peak event count
  for (int i=0; i<locMassBinCount; i++) {
    int isZpeak=0;
    // bin idx is (i+1)
    if ((hMassIdx.GetBinLowEdge(i+1)>=60-1e-3) 
	&& (hMassIdx.GetBinLowEdge(i+1+1)<=120+1e-3)) isZpeak=1;
    if (isZpeak) {
      int yiMax=(fineGrid) ? 1:DYTools::nYBins[i];
      for (int yi=0; yi<yiMax; ++yi) {
	nZpeak += nEvents(i,yi);
	w2Zpeak += w2Events(i,yi);
	nZpeakDET += nEventsDET(i,yi);
	w2ZpeakDET += w2EventsDET(i,yi);
	nZpeakDETrecoPostIdx += nEventsDETrecoPostIdx(i,yi);
	w2ZpeakDETrecoPostIdx += w2EventsDETrecoPostIdx(i,yi);
      }
    }
  }
  std::cout << "\n";
  std::cout << "nZpeak=" << nZpeak << ", w2Zpeak=" << w2Zpeak << "\n";
  std::cout << "nZpeakDET=" << nZpeakDET << ", w2ZpeakDET=" << w2ZpeakDET << "\n";
  std::cout << "nZpeakDETrecoPostIdx=" << nZpeakDETrecoPostIdx << ", w2ZpeakDETrecoPostIdx=" << w2ZpeakDETrecoPostIdx << "\n";
  std::cout << "\n";


  if (nZpeak==0) {
    std::cout << "no events in the Z-peak region\n";
    return ;
  }
  } // if (debugMode!=-1)


  // Containers of the normalized event counts
  TMatrixD nEventsNorm (locMassBinCount,DYTools::nYBinsMax);    // number of weigthed events, normalized to Z-peak
  TMatrixD nEventsDETNorm (locMassBinCount,DYTools::nYBinsMax); // number of weighted events in the detector acceptance, normalized to Z-peak
  TMatrixD nEventsDETrecoPostIdxNorm (locMassBinCount,DYTools::nYBinsMax); // number of weighted events in the detector acceptance, normalized to Z-peak
  TMatrixD nEventsNormErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETNormErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETrecoPostIdxNormErr (locMassBinCount,DYTools::nYBinsMax);

  TMatrixD nEventsErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETrecoPostIdxErr (locMassBinCount,DYTools::nYBinsMax);

  nEventsNorm=0;
  nEventsDETNorm=0;
  nEventsDETrecoPostIdxNorm=0;
  nEventsNormErr=0;
  nEventsDETNormErr=0;
  nEventsDETrecoPostIdxNormErr=0;

  nEventsErr=0;
  nEventsDETErr=0;

  if (debugMode!=-1) {
  for(int i=0; i<locMassBinCount; i++) {
    int yiMax=(fineGrid) ? 1:DYTools::nYBins[i];
    for (int j=0; j<yiMax; j++) {
      nEventsErr(i,j)=sqrt(w2Events(i,j));
      nEventsDETErr(i,j)=sqrt(w2EventsDET(i,j));
      nEventsDETrecoPostIdxErr(i,j)=sqrt(w2EventsDETrecoPostIdx(i,j));

      nEventsNorm(i,j) = nEvents(i,j)/nZpeak;
      nEventsNormErr(i,j) = 
	getErrorOnRatio(nEvents(i,j),nEventsErr(i,j),
			nZpeak, sqrt(w2Zpeak));

      nEventsDETNorm(i,j) = nEventsDET(i,j)/nZpeakDET;
      nEventsDETNormErr(i,j) =
	getErrorOnRatio(nEventsDET(i,j),nEventsDETErr(i,j),
			nZpeakDET, sqrt(w2ZpeakDET));

      nEventsDETrecoPostIdxNorm(i,j) = nEventsDETrecoPostIdx(i,j)/nZpeakDETrecoPostIdx;
      nEventsDETrecoPostIdxNormErr(i,j) =
	getErrorOnRatio(nEventsDETrecoPostIdx(i,j),nEventsDETrecoPostIdxErr(i,j),
			nZpeakDETrecoPostIdx, sqrt(w2ZpeakDETrecoPostIdx));
    }
  }
  }



  TString outFile= TString("../root_files/xSecThExt_");
  //outFile.Append("2MCfiles_");
  if (!useFewzWeights) outFile.Append("noFEWZ_");
  if (fineGridStr.Length()) outFile.Append(fineGridStr);
  if (debugMode==1) outFile.Append("debug_");
  outFile.Append( DYTools::analysisTag + TString("_tmp.root") );


  TVectorD rapidityGrid(massGrid.GetNoElements()-1);
  rapidityGrid=1;

  if (debugMode!=-1) {
    TFile thFile(outFile,"recreate");
    massGrid.Write("massBinEdges");
    if (fineGrid) rapidityGrid.Write("rapidityBinCount");
    nEvents.Write("nGenEvents");
    nEventsErr.Write("nGenEventsErr");
    nEventsDET.Write("nGenEventsDET");
    nEventsDETErr.Write("nGenEventsDETErr");
    nEventsDETrecoPostIdx.Write("nGenEventsDETrecoPostIdx");
    nEventsDETrecoPostIdxErr.Write("nGenEventsDETRecoPostIdxErr");
    nEventsNorm.Write("nGenEventsNorm");
    nEventsNormErr.Write("nGenEventsNormErr");
    nEventsDETNorm.Write("nGenEventsDETNorm");
    nEventsDETNormErr.Write("nGenEventsDETNormErr");
    nEventsDETrecoPostIdxNorm.Write("nGenEventsDETrecoPostIdxNorm");
    nEventsDETrecoPostIdxNormErr.Write("nGenEventsDETrecoPostIdxNormErr");
    TVectorD zPeakInfo(6);
    zPeakInfo(0)=nZpeak; zPeakInfo(1)=sqrt(w2Zpeak);
    zPeakInfo(2)=nZpeakDET; zPeakInfo(3)=sqrt(w2ZpeakDET);
    zPeakInfo(4)=nZpeakDETrecoPostIdx; zPeakInfo(5)=sqrt(w2ZpeakDETrecoPostIdx);
    zPeakInfo.Write("zPeakCountAndErr");
    thFile.Close();
    std::cout << "file <" << outFile << "> created\n";
  }
  else {
    TFile thFile(outFile);
    nEvents.Read("nGenEvents");
    nEventsErr.Read("nGenEventsErr");
    nEventsDET.Read("nGenEventsDET");
    nEventsDETErr.Read("nGenEventsDETErr");
    nEventsDETrecoPostIdx.Read("nGenEventsDETrecoPostIdx");
    nEventsDETrecoPostIdxErr.Read("nGenEventsDETRecoPostIdxErr");
    nEventsNorm.Read("nGenEventsNorm");
    nEventsNormErr.Read("nGenEventsNormErr");
    nEventsDETNorm.Read("nGenEventsDETNorm");
    nEventsDETNormErr.Read("nGenEventsDETNormErr");
    nEventsDETrecoPostIdxNorm.Read("nGenEventsDETrecoPostIdxNorm");
    nEventsDETrecoPostIdxNormErr.Read("nGenEventsDETrecoPostIdxNormErr");
    TVectorD zPeakInfo(6);
    zPeakInfo.Read("zPeakCountAndErr");
    thFile.Close();
    
    nZpeak=zPeakInfo[0]; w2Zpeak=SQR(zPeakInfo[1]);
    nZpeakDET=zPeakInfo[2]; w2ZpeakDET=SQR(zPeakInfo[3]);
    nZpeakDETrecoPostIdx=zPeakInfo[4]; w2ZpeakDETrecoPostIdx=SQR(zPeakInfo[5]);
    std::cout << "file <" << outFile << "> loaded\n";
  }

  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  CPlot::sOutDir="plots" + DYTools::analysisTag;

  TString fileNamePlots=outFile;
  fileNamePlots.ReplaceAll("_tmp.root","_plots_tmp.root");
  TFile *filePlots=new TFile(fileNamePlots,"recreate");
  if (!filePlots) {
    std::cout << "failed to create file <" << fileNamePlots << ">\n";
    throw 2;
  }
  // string buffers
  //char ylabel[50];   // y-axis label


  if (DYTools::study2D) {
    TString c2Dname="canvXsectTh_2D";
    if (useFewzWeights) c2Dname.Append("_FEWZ");
    TCanvas *c2D = MakeCanvas(c2Dname,c2Dname,600,600+300*DYTools::study2D);
    std::vector<TH1F*> hXsecV;
    std::vector<CPlot*> cpV;
    hXsecV.reserve(DYTools::nMassBins);
    cpV.reserve(DYTools::nMassBins);
    for (int iM=0; iM<DYTools::nMassBins; ++iM) {
      double massMin=DYTools::massBinLimits[iM];
      double massMax=DYTools::massBinLimits[iM+1];
      CPlot *cp=new CPlot(Form("cpMass%2.0lf_%2.0lf",massMin,massMax),
			  "","|Y|","counts");
      cpV.push_back(cp);
      hXsecV.push_back( plotXsec2D("xsec",iM,nEvents,nEventsErr,cp,kBlack,1) );
    }
    c2D->Divide(2,3);
    for (int ipad=1; ipad<=6; ++ipad) {
      cpV[ipad]->Draw(c2D,false,"png",ipad);
    }
    c2D->Update();
    SaveCanvas(c2D,c2Dname);
  }

  {
    TString canvName=TString("canvXsectTh_") + fineGridStr + TString("1D");
    if (useFewzWeights) canvName.Append("_FEWZ");
    TCanvas *c1D = MakeCanvas(canvName,canvName,600,600);
    CPlot *cp=new CPlot("cplot_1D","","M_{ee} (GeV)","counts");
    TH1F *hXsec= plotXsec1D("xsec1D",nEvents,nEventsErr,cp,kBlue, fineGrid);
    hXsec->SetDirectory(0);
    cp->SetLogx();
    cp->Draw(c1D,false,"png");
    c1D->Update();
    SaveCanvas(c1D,canvName);
  }
	
  {
    TString canvName=TString("canvXsectThNorm_") + fineGridStr + TString("1D");
    if (useFewzWeights) canvName.Append("_FEWZ");
    TCanvas *c1D = MakeCanvas(canvName,canvName,600,600);
    CPlot *cp=new CPlot("cplotNorm_1D","","M_{ee} (GeV)","normalized counts");
    TH1F *hXsec= plotXsec1D("xsec1D",nEventsNorm,nEventsNormErr,cp,kBlue, fineGrid);
    hXsec->SetDirectory(0);
    cp->SetLogx();
    cp->Draw(c1D,false,"png");
    c1D->Update();
    SaveCanvas(c1D,canvName);
  }
	
  /* 

 // Z mass
  sprintf(ylabel,"a.u. / %.1f GeV/c^{2}",hZMassv[0]->GetBinWidth(1));
  CPlot plotZMass1("zmass1","","m(Z) [GeV/c^{2}]",ylabel);
  for(UInt_t i=0; i<fnamev.size(); i++) { 
    plotZMass1.AddHist1D(hZMassv[i],labelv[i],"hist",colorv[i],linev[i]); 
  }
  plotZMass1.SetLogy();
  plotZMass1.Draw(c);
  SaveCanvas(c, "zmass1");

  PlotMatrixVariousBinning(accv, "acceptance", "LEGO2",filePlots);
  filePlots->Close();
  if (DYTools::study2D==0)
    Plot1D(accv,accErrv,"acceptance1D","acceptance");
  //delete filePlots;
  
  */
  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //==============================================================================================================

  if (!fineGrid) {
    const int printSystErr=0;
    TMatrixD zeroErr=nEventsErr; zeroErr=0;
    printYields("nGenEvents", nEvents,nEventsErr,zeroErr, printSystErr);
    printYields("nGenEventsDET", nEventsDET,nEventsDETErr,zeroErr, printSystErr);
    printYields("nGenEventsDETrecoPostIdx",nEventsDETrecoPostIdx,nEventsDETrecoPostIdxErr, zeroErr,printSystErr);
  }

  gBenchmark->Show("getXsec");
}
Ejemplo n.º 24
0
/*
 * Main solver routine.
 */
idxint ECOS_solve(pwork* w)
{
	idxint i, initcode, KKT_FACTOR_RETURN_CODE;
	pfloat dtau_denom, dtauaff, dkapaff, sigma, dtau, dkap, bkap, pres_prev;
	idxint exitcode = ECOS_FATAL;
#if PROFILING > 0
	timer tsolve;
#endif
#if PROFILING > 1
    timer tfactor, tkktsolve;
#endif
    
#if PROFILING > 0
    /* start timer */
    tic(&tsolve);
#endif
	
	/* Initialize solver */
    initcode = init(w);
	if( initcode == ECOS_FATAL ){
#if PRINTLEVEL > 0
        if( w->stgs->verbose ) PRINTTEXT("\nFatal error during initialization, aborting.");
#endif
        return ECOS_FATAL;
    }
    
    
    
	/* MAIN INTERIOR POINT LOOP ---------------------------------------------------------------------- */
	for( w->info->iter = 0; w->info->iter <= w->stgs->maxit; w->info->iter++ ){
        
		/* Compute residuals */
		computeResiduals(w);
        
		/* Update statistics */
		updateStatistics(w);

#if PRINTLEVEL > 1
		/* Print info */
		if( w->stgs->verbose ) printProgress(w->info);
#endif		
        
        
        /* SAFEGUARD: Backtrack to old iterate if the update was bad such that the primal residual PRES has
         *            increased by a factor of SAFEGUARD.
         * If the safeguard is activated, the solver quits with the flag ECOS_NUMERICS.
         */
        if( w->info->iter > 0 && w->info->pres > SAFEGUARD*pres_prev ){
#if PRINTLEVEL > 1
            if( w->stgs->verbose ) PRINTTEXT("\nNUMERICAL PROBLEMS, recovering iterate %d and stopping.\n", (int)w->info->iter-1);
#endif
            /* Backtrack */
            for( i=0; i < w->n; i++ ){ w->x[i] -= w->info->step * w->KKT->dx2[i]; }
            for( i=0; i < w->p; i++ ){ w->y[i] -= w->info->step * w->KKT->dy2[i]; }
            for( i=0; i < w->m; i++ ){ w->z[i] -= w->info->step * w->KKT->dz2[i]; }
            for( i=0; i < w->m; i++ ){ w->s[i] -= w->info->step * w->dsaff[i]; }
            w->kap -= w->info->step * dkap;
            w->tau -= w->info->step * dtau;
            exitcode = ECOS_NUMERICS;
            computeResiduals(w);
            updateStatistics(w);
            break;
        }
        pres_prev = w->info->pres;
        

		/* Check termination criteria and exit if necessary */
		/* Optimal? */
		if( ( ( -w->cx > 0 ) || ( -w->by - w->hz > 0) ) &&
            w->info->pres < w->stgs->feastol && w->info->dres < w->stgs->feastol &&
			( w->info->gap < w->stgs->abstol || w->info->relgap < w->stgs->reltol ) ){
#if PRINTLEVEL > 0
			if( w->stgs->verbose ) PRINTTEXT("\nOPTIMAL (within feastol=%3.1e, reltol=%3.1e, abstol=%3.1e).", w->stgs->feastol, w->stgs->reltol, w->stgs->abstol);
#endif
	        exitcode = ECOS_OPTIMAL;
			break;
		}            
		/* Primal infeasible? */
		else if( ((w->info->pinfres != NAN) && (w->info->pinfres < w->stgs->feastol)) ||
                 ((w->tau < w->stgs->feastol) && (w->kap < w->stgs->feastol && w->info->pinfres < w->stgs->feastol)) ){
#if PRINTLEVEL > 0
			if( w->stgs->verbose ) PRINTTEXT("\nPRIMAL INFEASIBLE (within feastol=%3.1e, reltol=%3.1e, abstol=%3.1e).", w->stgs->feastol, w->stgs->reltol, w->stgs->abstol);
#endif
			w->info->pinf = 1;
			w->info->dinf = 0;
			exitcode = ECOS_PINF;
			break;
		}        
		/* Dual infeasible? */
		else if( (w->info->dinfres != NAN) && (w->info->dinfres < w->stgs->feastol) ){
#if PRINTLEVEL > 0
			if( w->stgs->verbose ) PRINTTEXT("\nUNBOUNDED (within feastol=%3.1e, reltol=%3.1e, abstol=%3.1e).", w->stgs->feastol, w->stgs->reltol, w->stgs->abstol);
#endif
			w->info->pinf = 0;  
			w->info->dinf = 1;        
			exitcode = ECOS_DINF;
			break;
		}   
		/* Did the line search c**k up? (zero step length) */
		else if( w->info->iter > 0 && w->info->step == STEPMIN*GAMMA ){
#if PRINTLEVEL > 0
			if( w->stgs->verbose ) PRINTTEXT("\nNo further progress possible (- numerics?), exiting.");
#endif
			exitcode = ECOS_NUMERICS;
			break;
		}
		/* MAXIT reached? */
		else if( w->info->iter == w->stgs->maxit ){
#if PRINTLEVEL > 0
			if( w->stgs->verbose ) PRINTTEXT("\nMaximum number of iterations reached, exiting.");
#endif
			exitcode = ECOS_MAXIT;
			break;
		}


		/* Compute scalings */
		if( updateScalings(w->C, w->s, w->z, w->lambda) == OUTSIDE_CONE ){
#if PRINTLEVEL > 0
            if( w->stgs->verbose ) PRINTTEXT("\nSlacks or multipliers leaving the positive orthant (- numerics ?), exiting.\n");
#endif
            return ECOS_OUTCONE;
        }
        
		/* Update KKT matrix with scalings */
		kkt_update(w->KKT->PKPt, w->KKT->PK, w->C);
        
#if DEBUG > 0
        dumpSparseMatrix(w->KKT->PKPt,"PKPt_updated.txt");
#endif
        /* factor KKT matrix */
#if PROFILING > 1
		tic(&tfactor);
        KKT_FACTOR_RETURN_CODE = kkt_factor(w->KKT, w->stgs->eps, w->stgs->delta, &w->info->tfactor_t1, &w->info->tfactor_t2);
        w->info->tfactor += toc(&tfactor);
#else
        KKT_FACTOR_RETURN_CODE = kkt_factor(w->KKT, w->stgs->eps, w->stgs->delta);
#endif

		/* Solve for RHS1, which is used later also in combined direction */
#if PROFILING > 1
		tic(&tkktsolve);
#endif
		w->info->nitref1 = kkt_solve(w->KKT, w->A, w->G, w->KKT->RHS1, w->KKT->dx1, w->KKT->dy1, w->KKT->dz1, w->n, w->p, w->m, w->C, 0, w->stgs->nitref);
#if PROFILING > 1
		w->info->tkktsolve += toc(&tkktsolve);
#endif
  
		/* AFFINE SEARCH DIRECTION (predictor, need dsaff and dzaff only) */
		RHS_affine(w);
#if PROFILING > 1
		tic(&tkktsolve);
#endif
		w->info->nitref2 = kkt_solve(w->KKT, w->A, w->G, w->KKT->RHS2, w->KKT->dx2, w->KKT->dy2, w->KKT->dz2, w->n, w->p, w->m, w->C, 0, w->stgs->nitref);
#if PROFILING > 1
		w->info->tkktsolve += toc(&tkktsolve);
#endif
        
		/* dtau_denom = kap/tau - (c'*x1 + by1 + h'*z1); */
		dtau_denom = w->kap/w->tau - ddot(w->n, w->c, w->KKT->dx1) - ddot(w->p, w->b, w->KKT->dy1) - ddot(w->m, w->h, w->KKT->dz1);
		
        /* dtauaff = (dt + c'*x2 + by2 + h'*z2) / dtau_denom; */
		dtauaff = (w->rt - w->kap + ddot(w->n, w->c, w->KKT->dx2) + ddot(w->p, w->b, w->KKT->dy2) + ddot(w->m, w->h, w->KKT->dz2)) / dtau_denom;
        
		/* dzaff = dz2 + dtau_aff*dz1 */
		for( i=0; i<w->m; i++ ){ w->W_times_dzaff[i] = w->KKT->dz2[i] + dtauaff*w->KKT->dz1[i]; } 
		scale(w->W_times_dzaff, w->C, w->W_times_dzaff);

		/* W\dsaff = -W*dzaff -lambda; */		
		for( i=0; i<w->m; i++ ){ w->dsaff_by_W[i] = -w->W_times_dzaff[i] - w->lambda[i]; }
		
		/* dkapaff = -(bkap + kap*dtauaff)/tau; bkap = kap*tau*/
		dkapaff = -w->kap - w->kap/w->tau*dtauaff;
        
        /* Line search on W\dsaff and W*dzaff */
		w->info->step_aff = lineSearch(w->lambda, w->dsaff_by_W, w->W_times_dzaff, w->tau, dtauaff, w->kap, dkapaff, w->C, w->KKT);
        
		/* Centering parameter */
        sigma = 1.0 - w->info->step_aff;
        sigma = sigma*sigma*sigma;
        if( sigma > SIGMAMAX ) sigma = SIGMAMAX;
        if( sigma < SIGMAMIN ) sigma = SIGMAMIN;
        w->info->sigma = sigma;
        
		
		/* COMBINED SEARCH DIRECTION */
		RHS_combined(w);
#if PROFILING > 1
		tic(&tkktsolve);
#endif
		w->info->nitref3 = kkt_solve(w->KKT, w->A, w->G, w->KKT->RHS2, w->KKT->dx2, w->KKT->dy2, w->KKT->dz2, w->n, w->p, w->m, w->C, 0, w->stgs->nitref);
#if PROFILING > 1
		w->info->tkktsolve += toc(&tkktsolve);
#endif
        
  		/* bkap = kap*tau + dkapaff*dtauaff - sigma*info.mu; */
		bkap = w->kap*w->tau + dkapaff*dtauaff - sigma*w->info->mu;

		/* dtau = ((1-sigma)*rt - bkap/tau + c'*x2 + by2 + h'*z2) / dtau_denom; */		
		dtau = ((1-sigma)*w->rt - bkap/w->tau + ddot(w->n, w->c, w->KKT->dx2) + ddot(w->p, w->b, w->KKT->dy2) + ddot(w->m, w->h, w->KKT->dz2)) / dtau_denom;
      	
		/* dx = x2 + dtau*x1;     dy = y2 + dtau*y1;       dz = z2 + dtau*z1; */
		for( i=0; i < w->n; i++ ){ w->KKT->dx2[i] += dtau*w->KKT->dx1[i]; }
		for( i=0; i < w->p; i++ ){ w->KKT->dy2[i] += dtau*w->KKT->dy1[i]; }
		for( i=0; i < w->m; i++ ){ w->KKT->dz2[i] += dtau*w->KKT->dz1[i]; }

		/*  ds_by_W = -(lambda \ bs + conelp_timesW(scaling,dz,dims)); */
		/* note that ath this point w->dsaff_by_W holds already (lambda \ ds) */
		scale(w->KKT->dz2, w->C, w->W_times_dzaff);
		for( i=0; i < w->m; i++ ){ w->dsaff_by_W[i] = -(w->dsaff_by_W[i] + w->W_times_dzaff[i]); }

		/* dkap = -(bkap + kap*dtau)/tau; */
		dkap = -(bkap + w->kap*dtau)/w->tau;

		/* Line search on combined direction */
		w->info->step = lineSearch(w->lambda, w->dsaff_by_W, w->W_times_dzaff, w->tau, dtau, w->kap, dkap, w->C, w->KKT) * w->stgs->gamma;
		
		/* ds = W*ds_by_W */
		scale(w->dsaff_by_W, w->C, w->dsaff);

		/* Update variables */
		for( i=0; i < w->n; i++ ){ w->x[i] += w->info->step * w->KKT->dx2[i]; }
		for( i=0; i < w->p; i++ ){ w->y[i] += w->info->step * w->KKT->dy2[i]; }
		for( i=0; i < w->m; i++ ){ w->z[i] += w->info->step * w->KKT->dz2[i]; }
		for( i=0; i < w->m; i++ ){ w->s[i] += w->info->step * w->dsaff[i]; }
		w->kap += w->info->step * dkap;
		w->tau += w->info->step * dtau;
	}

	/* scale variables back */    
	backscale(w);

	/* stop timer */
#if PROFILING > 0
	w->info->tsolve = toc(&tsolve);
#endif

#if PRINTLEVEL > 0
#if PROFILING > 0
	if( w->stgs->verbose ) PRINTTEXT("\nRuntime: %f seconds.", w->info->tsetup + w->info->tsolve);
#endif
	if( w->stgs->verbose ) PRINTTEXT("\n\n");
#endif

	return exitcode;
}
Ejemplo n.º 25
0
/*!
 *   This is done by running
 *   each reaction as far forward or backward as possible, subject
 *   to the constraint that all mole numbers remain
 *   non-negative. Reactions for which \f$ \Delta \mu^0 \f$ are
 *   positive are run in reverse, and ones for which it is negative
 *   are run in the forward direction. The end result is equivalent
 *   to solving the linear programming problem of minimizing the
 *   linear Gibbs function subject to the element and
 *   non-negativity constraints.
 */
int VCS_SOLVE::vcs_setMolesLinProg() {
  int ik, irxn;
  double test = -1.0E-10;

#ifdef DEBUG_MODE
    std::string pprefix(" --- seMolesLinProg ");
    if (m_debug_print_lvl >= 2) {
      plogf("   --- call setInitialMoles\n"); 
    }
#endif


  // m_mu are standard state chemical potentials
  //  Boolean on the end specifies standard chem potentials
  // m_mix->getValidChemPotentials(not_mu, DATA_PTR(m_mu), true);
  // -> This is already done coming into the routine.
  double dg_rt;

  int idir;
  double nu;
  double delta_xi, dxi_min = 1.0e10;
  bool redo = true;
  int jcomp;
  int retn;
  int iter = 0;
  bool abundancesOK = true;
  int usedZeroedSpecies;

  std::vector<double> sm(m_numElemConstraints*m_numElemConstraints, 0.0);
  std::vector<double> ss(m_numElemConstraints, 0.0);
  std::vector<double> sa(m_numElemConstraints, 0.0);
  std::vector<double> wx(m_numElemConstraints, 0.0);
  std::vector<double> aw(m_numSpeciesTot, 0.0);

  for (ik = 0; ik <  m_numSpeciesTot; ik++) {
    if (m_speciesUnknownType[ik] !=  VCS_SPECIES_INTERFACIALVOLTAGE) {
      m_molNumSpecies_old[ik] = MAX(0.0, m_molNumSpecies_old[ik]);
    }
  }

#ifdef DEBUG_MODE
  if (m_debug_print_lvl >= 2) {
    printProgress(m_speciesName, m_molNumSpecies_old, m_SSfeSpecies);
  }
#endif
  
  while (redo) {
 
    if (!vcs_elabcheck(0)) {
#ifdef DEBUG_MODE
      if (m_debug_print_lvl >= 2) {
	plogf("%s Mole numbers failing element abundances\n", pprefix.c_str());  
	plogf("%sCall vcs_elcorr to attempt fix\n",          pprefix.c_str());
      }
#endif
      retn = vcs_elcorr(VCS_DATA_PTR(sm), VCS_DATA_PTR(wx));
      if (retn >= 2) {
	abundancesOK = false;
      } else {
	abundancesOK = true;
      }
    } else {
      abundancesOK = true;
    }
    /*
     *  Now find the optimized basis that spans the stoichiometric
     *  coefficient matrix, based on the current composition, m_molNumSpecies_old[]
     *  We also calculate sc[][], the reaction matrix.
     */
    retn = vcs_basopt(FALSE, VCS_DATA_PTR(aw), VCS_DATA_PTR(sa),
			  VCS_DATA_PTR(sm), VCS_DATA_PTR(ss), 
			  test, &usedZeroedSpecies);
    if (retn != VCS_SUCCESS) return retn;

#ifdef DEBUG_MODE
    if (m_debug_print_lvl >= 2) {
      plogf("iteration %d\n", iter);  
    }
#endif
    redo = false;
    iter++;
    if (iter > 15) break;

    // loop over all reactions
    for (irxn = 0; irxn < m_numRxnTot; irxn++) {
	   
      // dg_rt is the Delta_G / RT value for the reaction
      ik = m_numComponents + irxn;
      dg_rt = m_SSfeSpecies[ik];
      dxi_min = 1.0e10;
      const double *sc_irxn = m_stoichCoeffRxnMatrix[irxn];
      for (jcomp = 0; jcomp < m_numElemConstraints; jcomp++) {
	dg_rt += m_SSfeSpecies[jcomp] * sc_irxn[jcomp];
      }
      // fwd or rev direction. 
      //  idir > 0 implies increasing the current species
      //  idir < 0  implies decreasing the current species
      idir = (dg_rt < 0.0 ? 1 : -1);
      if (idir < 0) {
	dxi_min = m_molNumSpecies_old[ik];
      }
	    
      for (jcomp = 0; jcomp < m_numComponents; jcomp++) {
	nu = sc_irxn[jcomp];
	      
	// set max change in progress variable by
	// non-negativity requirement
	if (nu*idir < 0) {
	  delta_xi = fabs(m_molNumSpecies_old[jcomp]/nu);
	  // if a component has nearly zero moles, redo
	  // with a new set of components
	  if (!redo) {
	    if (delta_xi < 1.0e-10 && (m_molNumSpecies_old[ik] >= 1.0E-10)) {
#ifdef DEBUG_MODE
	      if (m_debug_print_lvl >= 2) {
		plogf("   --- Component too small: %s\n", m_speciesName[jcomp].c_str()); 
	      }
#endif
	      redo = true;
	    }
	  }
	  if (delta_xi < dxi_min) dxi_min = delta_xi;
	}
      }
	    
      // step the composition by dxi_min, check against zero, since
      // we are zeroing components and species on every step.
      // Redo the iteration, if a component went from positive to zero on this step.
      double dsLocal = idir*dxi_min;
      m_molNumSpecies_old[ik] += dsLocal;
      m_molNumSpecies_old[ik] = MAX(0.0,  m_molNumSpecies_old[ik]);
      for (jcomp = 0; jcomp < m_numComponents; jcomp++) {
	bool full = false;
	if (m_molNumSpecies_old[jcomp] > 1.0E-15) {
	  full = true;
	}
	m_molNumSpecies_old[jcomp] += sc_irxn[jcomp] * dsLocal;
	m_molNumSpecies_old[jcomp] = MAX(0.0, m_molNumSpecies_old[jcomp]);
	if (full) {
	  if (m_molNumSpecies_old[jcomp] < 1.0E-60) {
	    redo = true;
	  }
	}
      }
    }

    // set the moles of the phase objects to match
    //  updateMixMoles();
    // Update the phase objects with the contents of the m_molNumSpecies_old vector
    // vcs_updateVP(0);
#ifdef DEBUG_MODE
    if (m_debug_print_lvl >= 2) {
      printProgress(m_speciesName, m_molNumSpecies_old, m_SSfeSpecies);
    }
#endif
  }

#ifdef DEBUG_MODE
  if (m_debug_print_lvl == 1) {
    printProgress(m_speciesName, m_molNumSpecies_old, m_SSfeSpecies);
    plogf("   --- setInitialMoles end\n"); 
  }
#endif
  retn = 0;
  if (!abundancesOK) {
    retn = -1;
  } else if (iter > 15) {
    retn = 1;
  }
  return retn;
}
Ejemplo n.º 26
0
//*--------------------------------------------------------------------------*//
//* MAIN                                                                MAIN *//
//*--------------------------------------------------------------------------*//
int main(int argc, char* argv[])
{  
   // Initialise random number generator
	srandom(time(NULL));
	clock_t t0 = clock();
   
   // Print header
   printHeader();
	
	// Read options
   Options uo = parseCommandLine(argc,argv);
   if(!uo.noHybrid)
   {
      if(uo.funcGroupVec[AROM] && uo.funcGroupVec[LIPO])
      {
         uo.funcGroupVec[HYBL] = true;
      }
      if(uo.funcGroupVec[HDON] && uo.funcGroupVec[HACC])
      {
         uo.funcGroupVec[HYBH] = true;
      }
   }
   std::cerr << uo.print() << std::endl;
   
   if (uo.version)
   {
		printHeader();
		exit(0);
	}
   
	if (uo.help)
   {
		printUsage();
		exit(0);
	}
	
	// Db file and pharmacophore out are mandatory elements
	if (uo.dbInpFile.empty())
   {
		mainErr("Missing database file. This is a required option (-d).");
	}
   
	if (uo.pharmOutFile.empty() && uo.molOutFile.empty() && uo.scoreOutFile.empty())
   {
		mainErr("No output file defined. So there is actually no use to compute anything at all.");
	}	
   
	if ((uo.pharmOutFile.empty() && uo.scoreOutFile.empty()) && !uo.molOutFile.empty())
   {
		mainErr("No file defined to write pharmacophore information.");
	}	
	
	if (uo.refInpFile.empty() && uo.pharmOutFile.empty() && uo.molOutFile.empty() && !uo.scoreOutFile.empty())
   {
		mainErr("Only score file requested when no reference is given. Unable to generate this output.");
	}	
  
	// Reference variables
   Pharmacophore refPharm;
   refPharm.clear();
   std::string refId;
   double refVolume(0.0);
   int refSize(0);
	int exclSize(0);
  
	// Database variables
   std::vector<Result*> resList;
   Pharmacophore dbPharm;
   std::string dbId;
   double dbVolume(0.0);
   int dbSize(0);
  
   //----------------------------------------------------------------------------
	//...(A).. Process the reference
   //----------------------------------------------------------------------------
  
	if (!uo.refInpFile.empty())
	{
      //-------------------------------------------------------
      //...(1).. get reference pharmacophore
      //-------------------------------------------------------
    
      if (uo.refInpType == UNKNOWN)
      {
         std::string ext(getExt(uo.refInpFile));
         if (ext == ".phar")
         {
            uo.refInpType = PHAR;
         }
         else 
         {
            uo.refInpType = MOL;
         }
      }
		
      if (uo.refInpType == MOL)
      {
         OpenBabel::OBMol m;
         OpenBabel::OBConversion* reader = new OpenBabel::OBConversion();
         reader->SetInFormat(reader->FormatFromExt(uo.refInpFile.c_str()));
         if (!reader->Read(&m, uo.refInpStream))
         {
            mainErr("Unable to read reference molecule");
         }
         calcPharm(&m, &refPharm, uo);
         refId = m.GetTitle();
         delete reader;
         reader = NULL;
      }
      else if (uo.refInpType == PHAR)
      {
         PharmacophoreReader* reader = new PharmacophoreReader();
         refPharm = reader->read(uo.refInpStream, refId);
         if (refPharm.empty())
         {
            mainErr("Error reading reference pharmacophore");
         }
         delete reader;
         reader = NULL;
      }
      else
      {
         mainErr("Unknown format of reference molecule.");
      }
		
      //-------------------------------------------------------
		//...(2).. process reference pharmacophore
      //-------------------------------------------------------
		
      if (uo.merge)
      {
         pharMerger.merge(refPharm);
      }
    
      refSize = refPharm.size();
      for (unsigned int i(0); i < refSize; ++i)
		{
         if (refPharm[i].func == EXCL)
         {
				// extract overlap with exclusion spheres
				for (unsigned int j(0); j < refPharm.size(); ++j)
            {
					if (refPharm[j].func != EXCL)
               {
						refVolume -= VolumeOverlap(refPharm[i], refPharm[j], !uo.noNormal);
					}
				}
				exclSize++;
			}
         else
         {
				// add point self-overlap
				refVolume += VolumeOverlap(refPharm[i], refPharm[i], !uo.noNormal);
			}
      }
      
      if(!uo.isQuiet)
      {
         std::cerr << "Reference pharmacophore " << refId << std::endl;
         std::cerr << "   number of points:            " << refSize - exclSize << std::endl;
			std::cerr << "   number of exclusion spheres: " << exclSize << std::endl;
         std::cerr << "   totalvolume:                 " << refVolume << std::endl;
      }
	}

   //----------------------------------------------------------------------------
	//...(B).. Process the database file
   //----------------------------------------------------------------------------

   // DB files
   if (uo.dbInpType == UNKNOWN)
   {
      std::string ext(getExt(uo.dbInpFile));
      if (ext==".phar")
      {
         uo.dbInpType = PHAR;
      }
      else
      {
         uo.dbInpType = MOL;
      }
   }
	
	// local storage of the rotation matrix
	SiMath::Matrix rotMat(3,3,0.0);

   unsigned int molCount(0);
   
   OpenBabel::OBConversion* molReader = NULL;
	PharmacophoreReader* pharmReader = NULL;
   
   if (uo.dbInpType == PHAR)
   {
      pharmReader = new PharmacophoreReader();
   }
   else if (uo.dbInpType == MOL)
   {
      molReader = new OpenBabel::OBConversion();
      molReader->SetInFormat(molReader->FormatFromExt(uo.dbInpFile.c_str()));
      molReader->SetInStream(uo.dbInpStream);
   }
   else
   {
      mainErr("Unknown format of db file.");
   }

   bool done(false);
   OpenBabel::OBMol m;
   while (!done)
   {	
      dbPharm.clear();
      m.Clear();

      if (uo.dbInpType == MOL)
      {
         if (!molReader->Read(&m))
         {
            done = true;
            break;
         }
         else
         {
            calcPharm(&m, &dbPharm, uo);
            dbId = m.GetTitle();
         }
      }
      else
      {
         if (uo.dbInpStream->eof())
         {
            done = true;
            break;
         }
         else
         {
            dbPharm = pharmReader->read(uo.dbInpStream, dbId);
         }
      }
      if (dbPharm.empty())
      {
         continue;
      }

      ++molCount;
      if (!uo.isQuiet )
      {
         if ((molCount % 10) == 0)
         {
            std::cerr << "." << std::flush;
         }
         if ((molCount % 500) == 0)
         {
            std::cerr << molCount << std::endl << std::flush;
         }
      }

			
      if (uo.merge)
      {
         pharMerger.merge(dbPharm);
      }
      
      if (uo.refInpFile.empty())
      {
         if (!(uo.isQuiet))
         {
            printProgress(molCount);
         } 
         if( !uo.pharmOutFile.empty())
         {
            uo.pharmOutWriter->write(dbPharm, uo.pharmOutStream, dbId);
         }
         continue;
      }

      //-------------------------------------------------------
      //...(1).. Alignment
      //-------------------------------------------------------
      
      dbSize = dbPharm.size();
      dbVolume = 0.0;
      for (unsigned int i(0); i < dbSize; ++i) 
      {
         if (dbPharm[i].func == EXCL)
         {
            continue;
         }
         dbVolume += VolumeOverlap(dbPharm[i], dbPharm[i], !uo.noNormal);
      }
			
      // Create a result structure
      Result res;
      res.refId           = refId;
      res.refVolume       = refVolume;
      res.dbId            = dbId;
      res.dbVolume        = dbVolume;
      res.overlapVolume   = 0.0;
      res.exclVolume      = 0.0;
      res.resMol          = m;
      res.resPharSize     = 0;
			
      if (uo.scoreOnly)
      {
         FunctionMapping funcMap(&refPharm, &dbPharm, uo.epsilon);
         PharmacophoreMap fMap = funcMap.getNextMap();
         double volBest(-9999.999);
         
         // loop over all reference points
         while (!fMap.empty())
         {
            double newVol(0.0);
            double exclVol(0.0);
            for (PharmacophoreMap::iterator itP = fMap.begin(); itP != fMap.end(); ++itP) 
            {
               if ((itP->first)->func == EXCL)
               {
                  exclVol += VolumeOverlap((itP->first), (itP->second), !uo.noNormal);					
               }
               else if (((itP->first)->func == (itP->second)->func ) || 
                       (((itP->first)->func == HYBH || 
                         (itP->first)->func == HDON || 
                         (itP->first)->func == HACC) 
                     && ((itP->second)->func == HDON || 
                         (itP->second)->func == HACC ||
                         (itP->second)->func == HYBH))
                     || (((itP->first)->func == HYBL || 
                          (itP->first)->func == AROM || 
                          (itP->first)->func == LIPO)
                      && ((itP->second)->func == AROM || 
                          (itP->second)->func == LIPO || 
                          (itP->second)->func == HYBL)))
               {
                  newVol += VolumeOverlap((itP->first),(itP->second), !uo.noNormal);
               }
            }
					
            if ((newVol - exclVol) > volBest)
            {
               res.resPhar.clear();
               res.resPharSize = 0;
               for (PharmacophoreMap::iterator itP = fMap.begin(); itP != fMap.end(); ++itP) 
               {
                  // add point to resulting pharmacophore
                  PharmacophorePoint p(itP->second);
                  (res.resPhar).push_back(p);
                  ++res.resPharSize;
               }						
               res.overlapVolume = newVol;
               res.exclVolume = exclVol;
               volBest = newVol - exclVol;
            }
            // get the next map
            fMap.clear();
            fMap = funcMap.getNextMap();
         }
      }
      else
      {
         FunctionMapping funcMap(&refPharm, &dbPharm, uo.epsilon);
         PharmacophoreMap fMap = funcMap.getNextMap();
         PharmacophoreMap bestMap;
				
         // default solution
         SolutionInfo best;
         best.volume = -999.9;
         
         // rotor is set to no rotation 
         best.rotor.resize(4);
         best.rotor = 0.0;
         best.rotor[0] = 1.0;
				
         double bestScore = -1000;
         int mapSize(fMap.size());
         int maxSize = mapSize - 3;
				
         while (!fMap.empty())
         {
            int msize = fMap.size();
            
            // add the exclusion spheres to the alignment procedure
            if (uo.withExclusion)
            {
               for (unsigned int i(0); i < refSize ; ++i)
               {
                  if (refPharm[i].func != EXCL)
                  {
                     continue;
                  }
                  for (unsigned int j(0); j < dbSize; ++j)
                  {
                     if (dbPharm[j].func == EXCL)
                     {
                        continue;
                     }
                     fMap.insert(std::make_pair(&(refPharm[i]), &(dbPharm[j])));
                  }
               }
            }
					
            // Only align if the expected score has any chance of being larger 
            // than best score so far
            if ((msize > maxSize)
            && (((double) msize / (refSize - exclSize + dbSize - msize)) > bestScore))
            {
               Alignment align(fMap);
               SolutionInfo r = align.align(!uo.noNormal);

               if (best.volume < r.volume)
               {
                  best = r;
                  bestScore = best.volume / (refVolume + dbVolume - best.volume);
                  bestMap = fMap;
                  mapSize = msize;
               }
            }
            else
            {
               // Level of mapping site to low
               break;
            }
	
            if (bestScore > 0.98)
            {
               break;
            }
					
            // Get the next map
            fMap.clear();
            fMap = funcMap.getNextMap();
         }
				
         // Transform the complete pharmacophore and the molecule towards the 
         // best alignment
         rotMat = quat2Rotation(best.rotor);
         positionPharmacophore(dbPharm, rotMat, best);
         positionMolecule(&res.resMol, rotMat, best);
				
         // Update result
         res.info = best;

         // Compute overlap volume between exlusion spheres and pharmacophore 
         // points
         for (int i(0); i < refSize; ++i) 
         {
            if (refPharm[i].func != EXCL)
            {
               continue;
            }
            for (int j(0); j < dbSize; ++j)
            {
               res.exclVolume += VolumeOverlap(refPharm[i], dbPharm[j], !uo.noNormal);
            }
         }
				
         // make copy of the best map and compute the volume overlap
         for (PharmacophoreMap::iterator itP = bestMap.begin(); itP != bestMap.end(); ++itP) 
         {
            if(((itP->first)->func == EXCL) || ((itP->second)->func == EXCL))
            { 
               continue; 
            }
					
            // compute overlap
            res.overlapVolume += VolumeOverlap(itP->first, itP->second, !uo.noNormal);
					
            // add point to resulting pharmacophore
				PharmacophorePoint p(itP->second);
            (res.resPhar).push_back(p);
            ++res.resPharSize;
         }
      }
			
      // update scores
      res.info.volume = res.overlapVolume - res.exclVolume;
      if (res.info.volume > 0.0)
      {
         res.tanimoto = res.info.volume / (res.refVolume + res.dbVolume - res.info.volume);
         res.tversky_ref = res.info.volume / res.refVolume;
         res.tversky_db = res.info.volume / res.dbVolume;
      }

      switch (uo.rankby) 
      {
         case TANIMOTO:
            res.rankbyScore = res.tanimoto;
            break;
         case TVERSKY_REF:
            res.rankbyScore = res.tversky_ref;
            break;
         case TVERSKY_DB:
            res.rankbyScore = res.tversky_db;
            break;
      }

      //-------------------------------------------------------
      //...(5).. Generate output
      //-------------------------------------------------------
      if (uo.cutOff != 0.0)
      {
         if (res.rankbyScore < uo.cutOff)
         {
            continue;
         }
      }

      if (uo.best != 0)
      {
         addBest(res, uo, resList);
      }
      else 
      { 
         if (!uo.molOutFile.empty())
         { 
            logOut(&res, uo);
         }
         if (!uo.pharmOutFile.empty())
         {
            logPharmacophores(&res, uo);
         }
         if (!uo.scoreOutFile.empty())
         {
            logScores(&res, uo);
         }
      }
   }

   if (molReader)
   {
      delete molReader;
      molReader = NULL;
   }
   if (pharmReader)
   {
      delete pharmReader;
      pharmReader = NULL;
   }
  
   //----------------------------------------------------------------------------
   //...(C).. Process best list (if defined)
   //----------------------------------------------------------------------------

   if (uo.best != 0)
   {
      std::vector<Result*>::iterator itR;
      for (itR = resList.begin(); itR != resList.end(); ++itR) 
      {
         Result* res(*itR);
         if (!uo.molOutFile.empty())
         {
            logOut(res, uo);
         }
         if (!uo.pharmOutFile.empty())
         {
            logPharmacophores(res, uo);
         }
         if (!uo.scoreOutFile.empty())
         {
            logScores(res, uo);
         }
         delete res;
      }
   }

   // done processing database
   if (!uo.isQuiet)
   {
      if (uo.refInpFile.empty())
      {
         std::cerr << std::endl;
         std::cerr << "Processed " << molCount << " molecules";
         double tt = (double)(clock() - t0 )/CLOCKS_PER_SEC;
         std::cerr << " in " << tt << " seconds (";
         std::cerr << molCount/tt << " molecules per second)." << std::endl;
      }
      else
      {
         std::cerr << std::endl;
         std::cerr << "Processed " << molCount << " molecules" << std::endl;
         double tt = (double)(clock() - t0 )/CLOCKS_PER_SEC;
         std::cerr << molCount << " alignments in " << tt << " seconds (";
         std::cerr << molCount/tt << " alignments per second)." << std::endl;
      }
   }
	
   exit(0);

}
Ejemplo n.º 27
0
/******************************************************************************
* Main function!
******************************************************************************/
int main(int argc, char **argv) {
  int res;
  char *file = NULL;
  micronucleus *my_device = NULL;

  // parse arguments
  int run = 0;
  int file_type = FILE_TYPE_INTEL_HEX;
  int arg_pointer = 1;
  char* usage = "usage: micronucleus [--run] [--dump-progress] [--type intel-hex|raw] [--no-ansi] [--timeout integer] filename";
  progress_step = 0;
  progress_total_steps = 5; // steps: waiting, connecting, parsing, erasing, writing, (running)?
  dump_progress = 0;
  timeout = 0; // no timeout by default
  //#if defined(WIN)
  //  use_ansi = 0;
  //#else
    use_ansi = 1;
  //#endif
  
  while (arg_pointer < argc) {
    if (strcmp(argv[arg_pointer], "--run") == 0) {
      run = 1;
      progress_total_steps += 1;
    } else if (strcmp(argv[arg_pointer], "--type") == 0) {
      arg_pointer += 1;
      if (strcmp(argv[arg_pointer], "intel-hex") == 0) {
        file_type = FILE_TYPE_INTEL_HEX;
      } else if (strcmp(argv[arg_pointer], "raw") == 0) {
        file_type = FILE_TYPE_RAW;
      } else {
        printf("Unknown File Type specified with --type option");
        return EXIT_FAILURE;
      }
    } else if (strcmp(argv[arg_pointer], "--help") == 0 || strcmp(argv[arg_pointer], "-h") == 0) {
      puts(usage);
      puts("");
      puts("  --type [intel-hex, raw]: Set upload file type to either intel hex or raw");
      puts("                           bytes (intel hex is default)");
      puts("          --dump-progress: Output progress data in computer-friendly form");
      puts("                           for driving GUIs");
      puts("                    --run: Ask bootloader to run the program when finished");
      puts("                           uploading provided program");
      //#ifndef WIN
      puts("                --no-ansi: Don't use ANSI in terminal output");
      //#endif
      puts("      --timeout [integer]: Timeout after waiting specified number of seconds");
      puts("                 filename: Path to intel hex or raw data file to upload,");
      puts("                           or \"-\" to read from stdin");
      return EXIT_SUCCESS;
    } else if (strcmp(argv[arg_pointer], "--dump-progress") == 0) {
      dump_progress = 1;
    } else if (strcmp(argv[arg_pointer], "--no-ansi") == 0) {
      use_ansi = 0;
    } else if (strcmp(argv[arg_pointer], "--timeout") == 0) {
      arg_pointer += 1;
      if (sscanf(argv[arg_pointer], "%d", &timeout) != 1) {
        printf("Did not understand --timeout value\n");
        return EXIT_FAILURE;
      }
    } else {
      file = argv[arg_pointer];
    }
    
    arg_pointer += 1;
  }
  
  if (argc < 2) {
    puts(usage);
    return EXIT_FAILURE;
  }
  
  setProgressData("waiting", 1);
  if (dump_progress) printProgress(0.5);
  printf("> Please plug in the device ... \n");
  printf("> Press CTRL+C to terminate the program.\n");
  
  
  time_t start_time, current_time;
  time(&start_time);
  
  while (my_device == NULL) {
    delay(100);
    my_device = micronucleus_connect();
    
    time(&current_time);
    if (timeout && start_time + timeout < current_time) {
      break;
    }
  }
  
  if (my_device == NULL) {
    printf("> Device search timed out\n");
    return EXIT_FAILURE;
  }
  
  printf("> Device is found!\n");
  
  // wait for CONNECT_WAIT milliseconds with progress output
  float wait = 0.0f;
  setProgressData("connecting", 2);
  while (wait < CONNECT_WAIT) {
    printProgress((wait / ((float) CONNECT_WAIT)) * 0.9f);
    wait += 50.0f;
    delay(50);
  }
  
  //my_device = micronucleus_connect();
  printProgress(1.0);
    
  // if (my_device->page_size == 64) {
  //   printf("> Device looks like ATtiny85!\n");
  // } else if (my_device->page_size == 32)  {
  //   printf("> Device looks like ATtiny45!\n");
  // } else {
  //   printf("> Unsupported device!\n");
  //   return EXIT_FAILURE;
  // }
  
  printf("> Available space for user application: %d bytes\n", my_device->flash_size);
  printf("> Suggested sleep time between sending pages: %ums\n", my_device->write_sleep);
  printf("> Whole page count: %d\n", my_device->pages);
  printf("> Erase function sleep duration: %dms\n", my_device->erase_sleep);
  
  setProgressData("parsing", 3);
  printProgress(0.0);
  memset(dataBuffer, 0xFF, sizeof(dataBuffer));
  
  int startAddress = 1, endAddress = 0;
  if (file_type == FILE_TYPE_INTEL_HEX) {
    if (parseIntelHex(file, dataBuffer, &startAddress, &endAddress)) {
      printf("> Error loading or parsing hex file.\n");
      return EXIT_FAILURE;
    }
  } else if (file_type == FILE_TYPE_RAW) {
    if (parseRaw(file, dataBuffer, &startAddress, &endAddress)) {
      printf("> Error loading raw file.\n");
      return EXIT_FAILURE;
    }
  }
  
  printProgress(1.0);

  if (startAddress >= endAddress) {
    printf("> No data in input file, exiting.\n");
    return EXIT_FAILURE;
  }
  
  if (endAddress > my_device->flash_size) {
    printf("> Program file is %d bytes too big for the bootloader!\n", endAddress - my_device->flash_size);
    return EXIT_FAILURE;
  }
  
  setProgressData("erasing", 4);
  printf("> Erasing the memory ...\n");
  res = micronucleus_eraseFlash(my_device, printProgress);
  
  if (res == 1) { // erase disconnection bug workaround
    printf(">> Eep! Connection to device lost during erase! Not to worry\n");
    printf(">> This happens on some computers - reconnecting...\n");
    my_device = NULL;
    
    delay(CONNECT_WAIT);
    
    int deciseconds_till_reconnect_notice = 50; // notice after 5 seconds
    while (my_device == NULL) {
      delay(100);
      my_device = micronucleus_connect();
      deciseconds_till_reconnect_notice -= 1;
      
      if (deciseconds_till_reconnect_notice == 0) {
        printf(">> (!) Automatic reconnection not working. Unplug and reconnect\n");
        printf("   device usb connector, or reset it some other way to continue.\n");
      }
    }
    
    printf(">> Reconnected! Continuing upload sequence...\n");
    
  } else if (res != 0) {
    printf(">> Abort mission! %d error has occured ...\n", res);
    printf(">> Please unplug the device and restart the program.\n");
    return EXIT_FAILURE;
  }
  printProgress(1.0);
  
  printf("> Starting to upload ...\n");
  setProgressData("writing", 5);
  res = micronucleus_writeFlash(my_device, endAddress, dataBuffer, printProgress);
  if (res != 0) {
    printf(">> Abort mission! An error has occured ...\n");
    printf(">> Please unplug the device and restart the program.\n");
    return EXIT_FAILURE;
  }
  
  if (run) {
    
    printf("> Starting the user app ...\n");
    setProgressData("running", 6);
    printProgress(0.0);
    
    res = micronucleus_startApp(my_device);
    
    if (res != 0) {
      printf(">> Abort mission! An error has occured ...\n");
      printf(">> Please unplug the device and restart the program. \n");
      return EXIT_FAILURE;
    }
    
    printProgress(1.0);
  }
  
  printf(">> Micronucleus done. Thank you!\n");
  
  return EXIT_SUCCESS;
}
Ejemplo n.º 28
0
void ProgressBar::finish() {
  done = toDo;
  printProgress();
  clear();
}
Ejemplo n.º 29
0
//---------------------------------------------------------------------
// ファイルの読み込みチェック(Win32APIバージョン)
//---------------------------------------------------------------------
bool readCheckOne(const kjm::_tstring& fname, DWORD bytesPerSector, bool fastMode) {
	bool result = true;

	_tcout << _T("残り(") << (--g_totalCount) << _T(") ") << fname << std::endl;

	DWORD openFlag = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN | (fastMode ? 0 : FILE_FLAG_NO_BUFFERING);
	HANDLE hFile = CreateFile(fname.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, openFlag, NULL);

	if (hFile != INVALID_HANDLE_VALUE) {

		// ファイルアクセスのバイト数をセクタサイズの整数倍に合わせる
		// バッファ アドレスをメモリ上でのディスクのセクタ境界に調整する
		char* buffer = new char[bytesPerSector * 2];
		char* p = (char *) ((DWORD) (buffer + bytesPerSector - 1) & ~(bytesPerSector - 1));

		__int64 li1 = kjm::file::getFileSize(hFile);
		__int64 li2 = 0;

		DWORD lastPrintTime = 0;
		DWORD dwStart = GetTickCount();
		while (true) {
			DWORD bytesRead;
			if (ReadFile(hFile, p, bytesPerSector, &bytesRead, NULL) == FALSE) {
				DWORD dwError = GetLastError();
				_tcerr << _T("[ng] read error ") << dwError << _T(": ") << kjm::util::formatMessageBySystem(dwError) << std::endl;
				result = false;
				break;
			}

			li2 += bytesRead;

			if ((GetTickCount() - lastPrintTime) > 500) {
				lastPrintTime = GetTickCount();

				// 500ms毎に進捗を出力する
				printProgress(li2, li1, lastPrintTime, dwStart);
				_tcout << _T("\r");
			}

			if (bytesRead != bytesPerSector) {
				lastPrintTime = GetTickCount();

				// 最後の結果出力
				printProgress(li2, li1, lastPrintTime, dwStart);
				_tcout << _T(" ... [ok]\n");
				break;
			}
		}

		delete[] buffer;

		CloseHandle(hFile);
	} else {
		DWORD dwError = GetLastError();
		_tcerr << _T("[ng] open error ") << dwError << _T(": ") << kjm::util::formatMessageBySystem(dwError) << std::endl;

		if (dwError == ERROR_SHARING_VIOLATION || dwError == ERROR_ACCESS_DENIED) {
			// 共有違反のときは、処理を継続させます。
		} else {
			result = false;
		}
	}

	return result;
}
Ejemplo n.º 30
0
/*
 * Entry point
 */
int main (int argc, char **argv)
{
    Bool   success = false;
    UInt16 remainingCapacity;
    pid_t  hwServerPID;
    
    setDebugPrintsOnToFile ("robooneremainingcapacitysync.log");
    setProgressPrintsOn();

    printProgress ("Synchronising remaining battery capacity values...\n");
    /* Spawn a child that will become the Hardware server. */
    hwServerPID = fork();
    if (hwServerPID == 0)
    {
        /* Start Hardware Server process on a given port */
        static char *argv1[] = {HARDWARE_SERVER_EXE, HARDWARE_SERVER_PORT_STRING, PNULL};
        
        execv (HARDWARE_SERVER_EXE, argv1);
        printDebug ("!!! Couldn't launch %s, err: %s. !!!\n", HARDWARE_SERVER_EXE, strerror (errno));
    }
    else
    {
        if (hwServerPID < 0)
        {
            printDebug ("!!! Couldn't fork to launch %s, err: %s. !!!\n", HARDWARE_SERVER_EXE, strerror (errno));
        }
        else
        {   /* Parent process */
            /* Wait for the server to start */
            usleep (HARDWARE_SERVER_START_DELAY_PI_US);
            /* Now setup the Hardware Server, batteries
             * only on this occasion. This will restore
             * the remaining battery capacity from
             * non-volatile storage if it is out of date,
             * which would be the case at power-on. */
            success = startHardwareServer (true);

            if (success)
            {
                /* Now do a remaining capacity reading to complete the sync back to
                 * non-volatile storage in case we are about to power off */
                if (hardwareServerSendReceive (HARDWARE_READ_RIO_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("Rio battery has %d mAh remaining.\n", remainingCapacity);
                }
                if (hardwareServerSendReceive (HARDWARE_READ_O1_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("O1 battery has %d mAh remaining.\n", remainingCapacity);
                }
                if (hardwareServerSendReceive (HARDWARE_READ_O2_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("O2 battery has %d mAh remaining.\n", remainingCapacity);
                }
                if (hardwareServerSendReceive (HARDWARE_READ_O3_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("O3 battery has %d mAh remaining.\n", remainingCapacity);
                }
            }

            /* Shut the Hardware Server down gracefully */
            stopHardwareServer();
            waitpid (hwServerPID, 0, 0); /* wait for Hardware Server process to exit */
        }
    }
    
    setDebugPrintsOff();

    if (success)
    {
        printProgress ("Synchronisation complete.\n");
    }
    else
    {
        printProgress ("\nSynchronisation failed!\n");
        exit (-1);
    }

    return success;
}