Esempio n. 1
0
int main()
{
  QString path = getenv("HOME");
  path += "/maskingdata";

  QFile datafile(path);
  datafile.open(IO_ReadOnly);

  QDataStream datastream(&datafile);

  //currently the QStrings at the beginning of the file
  //are just being read, not written to stdout
  QString str;
  for(int i = 0; i < 3; i++)
    datastream >> str;


  float val;
  int counter = 0;

  while( ! datastream.atEnd() )
    {
      counter++;
      datastream >> val;
      printf("%d:  %f \n", counter, val);
    }

  return 0;
}
Esempio n. 2
0
void ParticleGenerator::getFileInput(char* fileName, ParticleContainer* pc, Simulation *sim) {
	double m = 1;
	int num_cuboids = 0;

	std::ifstream input_file(fileName);
	string tmp_string;

	if (input_file.is_open()) {
		getline(input_file, tmp_string);
		LOG4CXX_DEBUG(iolog, "Read line: " << tmp_string);

		while (tmp_string.size() == 0 || tmp_string[0] == '#') {
			getline(input_file, tmp_string);
			LOG4CXX_DEBUG(iolog, "Read line: " << tmp_string);
		}

		istringstream numstream(tmp_string);
		numstream >> num_cuboids;
		LOG4CXX_DEBUG(iolog, "Reading " << num_cuboids << ".");
		getline(input_file, tmp_string);
		LOG4CXX_DEBUG(iolog, "Read line: " << tmp_string);

		for (int i = 0; i < num_cuboids; i++) {
			istringstream datastream(tmp_string);

			for (int j = 0; j < 3; j++) {
				datastream >> X[j];
			}
			for (int j = 0; j < 3; j++) {
				datastream >> V[j];
			}

			for (int j = 0; j < 3; j++) {
				datastream >> num[j];
			}
			if (datastream.eof()) {
				LOG4CXX_ERROR(iolog, "Error reading file: eof reached unexpectedly reading from line " << i);
				exit(-1);
			}

			datastream >> meanV;
			datastream >> M;
			datastream >> H;

			// create particles from cuboid data
			LOG4CXX_ERROR(particlelog, "Generating Cuboid...");
			createParticles(pc);

			getline(input_file, tmp_string);
		}
	} else {
Esempio n. 3
0
void CommentLoader::loadFile(const QString filename, const int pagecount) {
	this->pagecount = pagecount;
	notes = new QStringList[pagecount];
	datafile.setFileName(filename);
	if (datafile.exists()) {
		datafile.open(QIODevice::ReadOnly | QIODevice::Text);
		if (datafile.isOpen()) {
			QTextStream datastream(&datafile);
			int slide = 0;
			while (!datastream.atEnd()) {
				QString line = datastream.readLine();
				if (line.startsWith("slide ")) {
					QStringList params=line.split(" ");
					if (params.count() > 1) {
						slide = params[1].toInt() - 1;
					}
				}
				if (line.startsWith("comment {")) {
					line = datastream.readLine();
					while (!datastream.atEnd() && !line.startsWith("}")) {
						if (slide < pagecount) {
							notes[slide].append(line.trimmed());
						}
						line = datastream.readLine();
					}
				}
				if (line.startsWith("keys {")) {
					line = datastream.readLine();
					while (!datastream.atEnd() && !line.startsWith("}")) {
						keys.append(line.trimmed());
						line = datastream.readLine();
					}
				}
				if (line.startsWith("bookmarks {")) {
					line = datastream.readLine();
					while (!datastream.atEnd() && !line.startsWith("}")) {
						QStringList bmarks=line.split(" ");
						for (int i=0; i<bmarks.size(); i++) {
							bookmarks.append(bmarks[i].toInt() - 1);
						}
						line = datastream.readLine();
					}
				}
			}
		}
	}
}
Esempio n. 4
0
static BOOL DLL_CALLCONV
Validate(FreeImageIO *io, fi_handle handle) {
	LibRaw RawProcessor;
	BOOL bSuccess = TRUE;
	
	// wrap the input datastream
	LibRaw_freeimage_datastream datastream(io, handle);

	// open the datastream
	if(RawProcessor.open_datastream(&datastream) != LIBRAW_SUCCESS) {
		bSuccess = FALSE;	// LibRaw : failed to open input stream (unknown format)
	}

	// clean-up internal memory allocations
	RawProcessor.recycle();

	return bSuccess;
}
Esempio n. 5
0
        Value fetch( const Key& key )
        { try {
           FC_ASSERT( is_open(), "Database is not open!" );

           ldb::Slice key_slice( (char*)&key, sizeof(key) );
           std::string value;
           auto status = _db->Get( _read_options, key_slice, &value );
           if( status.IsNotFound() )
           {
             FC_THROW_EXCEPTION( fc::key_not_found_exception, "unable to find key ${key}", ("key",key) );
           }
           if( !status.ok() )
           {
               FC_THROW_EXCEPTION( level_pod_map_failure, "database error: ${msg}", ("msg", status.ToString() ) );
           }
           fc::datastream<const char*> datastream(value.c_str(), value.size());
           Value tmp;
           fc::raw::unpack(datastream, tmp);
           return tmp;
        } FC_RETHROW_EXCEPTIONS( warn, "error fetching key ${key}", ("key",key) ); }
Esempio n. 6
0
 Value fetch( const Key& key )
 {
   try {
      ldb::Slice key_slice( (char*)&key, sizeof(key) );
      std::string value;
      auto status = _db->Get( ldb::ReadOptions(), key_slice, &value );
      if( status.IsNotFound() )
      {
        FC_THROW_EXCEPTION( key_not_found_exception, "unable to find key ${key}", ("key",key) );
      }
      if( !status.ok() )
      {
          FC_THROW_EXCEPTION( exception, "database error: ${msg}", ("msg", status.ToString() ) );
      }
      fc::datastream<const char*> datastream(value.c_str(), value.size());
      Value tmp;
      fc::raw::unpack(datastream, tmp);
      return tmp;
   } FC_RETHROW_EXCEPTIONS( warn, "error fetching key ${key}", ("key",key) );
 }
void ARControlConnection::onNavdata(const ARControlFrame &frame)
{
    Q_D(ARControlConnection);

    // TODO: Should we do this, or should we allow application to decide
    // when/if an acknowledge occurs?
    // Construct acknowledge frame, if this incoming frame requires it.
    if(frame.type == ARControlConnection::AcknowledgeData)
    {
        QByteArray payload(1, 0x00);
        QDataStream datastream(&payload, QIODevice::WriteOnly);
        datastream.setByteOrder(QDataStream::LittleEndian);
        datastream << (quint8)frame.seq;
        sendFrame(ARControlConnection::Acknowledge, ARNET_C2D_NAVDATA_ACK_ID, payload.constData(), payload.size());
    }

    // Decode command header.
    quint8  project  = static_cast<quint8>(frame.payload[0]);
    quint8  klass    = static_cast<quint8>(frame.payload[1]);
    quint16 id       = qFromLittleEndian(static_cast<quint16>(frame.payload[2]));
    const char *data = frame.payload.data() + 4;

    // Resolve command meta-type information.
    ARCommandInfo *command = d->commands->find(project, klass, id);
    if(command == NULL)
    {
        WARNING_T(QString("Unrecognised command: %1 %2 %3")
                  .arg(project)
                  .arg(klass)
                  .arg(id));
        return;
    }

    // Use command codec to decode command parameters.
    QVariantMap params = d->codec->decode(command, data);
    DEBUG_T(QString("Decoded Command %1 %2 %3").arg(command->klass->project).arg(command->klass->name).arg(command->name));

    d->controller->onCommandReceived(*command, params);
}
void SimpleDataSet::read(int type){  
    openMysqlSession();
    
    this->dataSet.clear();
    
    ResultSet *resSet;
    PreparedStatement *prep_stmt;

    /* create a statement object */
    prep_stmt = con -> prepareStatement("SELECT * FROM `SimpleDataSet` WHERE `compression_rate`=? AND `num_clusters`=? AND `type`=?");
    prep_stmt->setInt(1, compressionRate);  
    prep_stmt->setInt(2, numClusters);      
    prep_stmt->setInt(3, type);      
    resSet = prep_stmt->executeQuery();

    while (resSet->next()) {       
        std::stringstream datastream(resSet->getString("sequence"));        
        //for each loop we save one sequence
        vector<int> sequence;
        while (!datastream.eof()) {
            int state;
            datastream >> state;
            sequence.push_back(state);
        }        
        SimpleData newSD;
        newSD.sequence=sequence;
        newSD.idAction=resSet->getInt("id_action");
        this->dataSet.push_back(newSD);
    }
    
    delete resSet;
    delete prep_stmt;
    
    closeMysqlSession();
    
    cout<<"SimpleData readad: "<<this->dataSet.size()<<" data, each sequence length:"<<this->dataSet[0].sequence.size()<<endl;
    
}
void Mesh_Binary_File_Writer::write_mesh(
    const Filename        & file,
    Mesh                  & mesh
)
{
    std::ofstream datastream((char*)file.string().c_str(), std::ios::binary);

    if (!datastream)
    {
        throw_exception(
            IO_Error("Mesh_Binary_File_Writer: cannot create "
                     "binary file: " + file.string()),
            WARNING_LEVEL, __FILE__, __LINE__);
    }
    
    // write header infos for the current mesh
    Vertex_Index vertex_count = mesh.vertex_count();
    Triangle_Index triangle_count = mesh.triangle_count();
    Triangle_Index triangle_strip_length = mesh.triangle_strip_length();
    datastream.write((char*)&vertex_count, sizeof(Vertex_Index));
    datastream.write((char*)&triangle_count, sizeof(Triangle_Index));
    datastream.write((char*)&triangle_strip_length, sizeof(Triangle_Index));
    
    // write the vertices data
    datastream.write((char*)mesh.vertices().pointer(),
                     vertex_count * 3 * sizeof(Micron));
    datastream.write((char*)mesh.vertex_sections().pointer(),
                     vertex_count * sizeof(Section_ID));
    datastream.write((char*)mesh.vertex_relative_distances().pointer(), 
                     vertex_count * sizeof(float));
    
    // write the triangles data
    datastream.write((char*)mesh.triangles().pointer(), 
                     triangle_count * 3 * sizeof(Vertex_Index));
    datastream.write((char*)mesh.triangle_strip().pointer(), 
                     triangle_strip_length * sizeof(Vertex_Index));
}
Esempio n. 10
0
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	FIBITMAP *dib = NULL;
	LibRaw RawProcessor;

	BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;

	try {
		// wrap the input datastream
		LibRaw_freeimage_datastream datastream(io, handle);

		// open the datastream
		if(RawProcessor.open_datastream(&datastream) != LIBRAW_SUCCESS) {
			throw "LibRaw : failed to open input stream (unknown format)";
		}

		if(header_only) {
			// header only mode
			dib = FreeImage_AllocateHeaderT(header_only, FIT_RGB16, RawProcessor.imgdata.sizes.width, RawProcessor.imgdata.sizes.height);
			// try to get JPEG embedded Exif metadata
			if(dib) {
				FIBITMAP *metadata_dib = libraw_LoadEmbeddedPreview(RawProcessor, FIF_LOAD_NOPIXELS);
				if(metadata_dib) {
					FreeImage_CloneMetadata(dib, metadata_dib);
					FreeImage_Unload(metadata_dib);
				}
			}
		}
		else if((flags & RAW_PREVIEW) == RAW_PREVIEW) {
			// try to get the embedded JPEG
			dib = libraw_LoadEmbeddedPreview(RawProcessor, 0);
			if(!dib) {
				// no JPEG preview: try to load as 8-bit/sample (i.e. RGB 24-bit)
				dib = libraw_LoadRawData(RawProcessor, 8);
			}
		} 
		else if((flags & RAW_DISPLAY) == RAW_DISPLAY) {
			// load raw data as 8-bit/sample (i.e. RGB 24-bit)
			dib = libraw_LoadRawData(RawProcessor, 8);
		} 
		else {
			// default: load raw data as linear 16-bit/sample (i.e. RGB 48-bit)
			dib = libraw_LoadRawData(RawProcessor, 16);
		}

		// save ICC profile if present
		if(NULL != RawProcessor.imgdata.color.profile) {
			FreeImage_CreateICCProfile(dib, RawProcessor.imgdata.color.profile, RawProcessor.imgdata.color.profile_length);
		}

		// try to get JPEG embedded Exif metadata
		if(dib && !((flags & RAW_PREVIEW) == RAW_PREVIEW) ) {
			FIBITMAP *metadata_dib = libraw_LoadEmbeddedPreview(RawProcessor, FIF_LOAD_NOPIXELS);
			if(metadata_dib) {
				FreeImage_CloneMetadata(dib, metadata_dib);
				FreeImage_Unload(metadata_dib);
			}
		}

		// clean-up internal memory allocations
		RawProcessor.recycle();

		return dib;

	} catch(const char *text) {
		if(dib) {
			FreeImage_Unload(dib);
		}
		RawProcessor.recycle();
		FreeImage_OutputMessageProc(s_format_id, text);
	}

	return NULL;
}
Esempio n. 11
0
  bool FastSearchFormat::ReadChemObject(OBConversion* pConv)
  {
    //Searches index file for structural matches
    //This function is called only once per search

    std::string auditMsg = "OpenBabel::Read fastsearch index ";
    std::string description(Description());
    auditMsg += description.substr(0,description.find('\n'));
    obErrorLog.ThrowError(__FUNCTION__,
                          auditMsg,
                          obAuditMsg);

    //Derive index name
    string indexname = pConv->GetInFilename();
    string::size_type pos=indexname.find_last_of('.');
    if(pos!=string::npos)
      {
        indexname.erase(pos);
        indexname += ".fs";
      }

    //Have to open input stream again because needs to be in binary mode
    ifstream ifs;
    stringstream errorMsg;
    if(!indexname.empty())
      ifs.open(indexname.c_str(),ios::binary);
    if(!ifs)
      {
        errorMsg << "Couldn't open " << indexname << endl;
        obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError);
        return false;
      }

    string datafilename = fs.ReadIndex(&ifs);
    if(datafilename.empty())
      {
        errorMsg << "Difficulty reading from index " << indexname << endl;
        obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError);
        return false;
      }

    vector<OBMol> patternMols;
    if(!ObtainTarget(pConv, patternMols, indexname))
      return false;

    bool exactmatch = pConv->IsOption("e",OBConversion::INOPTIONS)!=NULL;// -ae option

    //Open the datafile and put it in pConv
    //datafile name derived from index file probably won't have a file path
    //but indexname may. Derive a full datafile name
    string path;
    pos = indexname.find_last_of("/\\");
    if(pos==string::npos)
      path = datafilename;
    else
      path = indexname.substr(0,pos+1) + datafilename;

    ifstream datastream(path.c_str());
    if(!datastream)
      {
        errorMsg << "Difficulty opening " << path << endl;
        obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError);
        return false;
      }
    pConv->SetInStream(&datastream);

    //Input format is currently fs; set it appropriately
    if(!pConv->SetInAndOutFormats(pConv->FormatFromExt(datafilename.c_str()),pConv->GetOutFormat()))
      return false;

    // If target has dative bonds like -[N+](=O)[O-] convert it to the uncharged form
    // (-N(=O)=O and add uncharged form to vector of mols which are sent to
    // the -s (SMARTS)filter.
    // Also check whether the target has dative bonds in the uncharged form and supply
    // the charged form to the -s filter.
    // Together with the automatic conversion to the uncharged form when the fs index is made,
    // this ensures that both forms are found however they occur in the datafile or the taget.
    vector<OBBase*> extraSMARTSMols;
    vector<OBMol>extraUnchargedMols;
    for(unsigned i=0;i<patternMols.size();++i)
    {
      if(patternMols[i].ConvertDativeBonds())
        extraSMARTSMols.push_back(&patternMols[i]);
      else 
      {
        // If target has uncharged dative bonds, still use it for fastsearching,
        // but add the charged form for -s filter.
        extraUnchargedMols.push_back(patternMols[i]);
        if(extraUnchargedMols.back().MakeDativeBonds())
          extraSMARTSMols.push_back(&extraUnchargedMols.back());
      }
    }
    OBOp* sFilter = OBOp::FindType("s");
    if(sFilter)
      sFilter->ProcessVec(extraSMARTSMols);

    //Now do searching
    const char* p = pConv->IsOption("t",OBConversion::INOPTIONS);
    if(p)
      {
        //Do a similarity search
        multimap<double, unsigned int> SeekposMap;
        string txt=p;
        if(txt.find('.')==string::npos)
          {
            //Finds n molecules with largest Tanimoto
            int n = atoi(p);
            fs.FindSimilar(&patternMols[0], SeekposMap, n);
          }
        else
          {
            //Finds molecules with Tanimoto > MinTani
            double MaxTani = 1.1;
            size_t pos = txt.find(',');
            if( pos != string::npos ) {
              MaxTani = atof( txt.substr( pos + 1 ).c_str() );
            }
            double MinTani = atof( txt.substr( 0, pos ).c_str() );
            fs.FindSimilar(&patternMols[0], SeekposMap, MinTani, MaxTani);
          }

        //Don't want to filter through SMARTS filter
        pConv->RemoveOption("s", OBConversion::GENOPTIONS);
        //also because op names are case independent
        pConv->RemoveOption("S", OBConversion::GENOPTIONS);

        multimap<double, unsigned int>::reverse_iterator itr;
        for(itr=SeekposMap.rbegin();itr!=SeekposMap.rend();++itr)
          {
            datastream.seekg(itr->second);

            if(pConv->IsOption("a", OBConversion::INOPTIONS))
              {
                //Adds Tanimoto coeff to title
                //First remove any previous value
                pConv->RemoveOption("addtotitle", OBConversion::GENOPTIONS);
                stringstream ss;
                ss << " " << itr->first;
                pConv->AddOption("addtotitle",OBConversion::GENOPTIONS, ss.str().c_str());

              }
            pConv->SetOneObjectOnly();
            if(itr != --SeekposMap.rend())
              pConv->SetMoreFilesToCome();//so that not seen as last on output
            pConv->Convert(NULL,NULL);
          }
      }

    else
    {
      //Structure search
      int MaxCandidates = 4000;
      p = pConv->IsOption("l",OBConversion::INOPTIONS);
      if(p && atoi(p))
        MaxCandidates = atoi(p);

      vector<unsigned int> SeekPositions;

      if(exactmatch)
      {
        //Find mols where all fingerprint bits are the same as the target
        fs.FindMatch(&patternMols[0], SeekPositions, MaxCandidates);
        // ensure that SMARTS filter in transform.cpp looks only for an exact match
        // by setting an option with the number of heavy atoms in the pattern mol included.
        stringstream ss;
        ss << patternMols[0].NumHvyAtoms();
        pConv->AddOption("exactmatch", OBConversion::GENOPTIONS, ss.str().c_str());
      }

      else
      {
        //Do a substructure search for each target
        vector<OBMol>::iterator iter;
        for(iter=patternMols.begin();iter!=patternMols.end();++iter)
          fs.Find(&*iter, SeekPositions, MaxCandidates);
        clog << SeekPositions.size() << " candidates from fingerprint search phase" << endl;
      }

      vector<unsigned int>::iterator seekitr,
          begin = SeekPositions.begin(), end = SeekPositions.end();

      if(patternMols.size()>1)//only sort and eliminate duplicates if necessary
      {
        sort(begin, end);
        end = unique(begin, end); //removed duplicates are after new end
      }

      //Output the candidate molecules, filtering through s filter, unless it was not requested
      if(pConv->IsOption("n", OBConversion::INOPTIONS) )
        pConv->RemoveOption("s",OBConversion::GENOPTIONS);

      pConv->SetLast(false);
      for(seekitr=begin; seekitr!=end; ++seekitr)
      {
        datastream.seekg(*seekitr);
        if(!pConv->GetInFormat()->ReadChemObject(pConv))
          return false;
        pConv->SetFirstInput(false); //needed for OpSort
      }
    }
    return false;	//To finish
  }
Esempio n. 12
0
void ARControlConnection::onVideoData(const ARControlFrame &frame)
{
    TRACE
    Q_D(ARControlConnection);

    quint16 frameNumber = qFromLittleEndian(*((quint16*)(frame.payload.constData())));
    quint8  frameFlags = static_cast<quint8>(frame.payload[2]);
    quint8  fragmentNumber = static_cast<quint8>(frame.payload[3]);
    quint8  fragsPerFrame = static_cast<quint8>(frame.payload[4]);

    if(frameNumber != d->frameNumber)
    {
        if(frameFlags == 0x01)
        {
            DEBUG_T(QString("Video Key Frame Header [%1] (%2 %3 %4)")
                    .arg(QString(QByteArray().append(frame.payload.constData(), 5).toHex()))
                    .arg(frameNumber)
                    .arg(fragmentNumber)
                    .arg(fragsPerFrame));
        }
        else
        {
            DEBUG_T(QString("Video Frame Header (%2 %3 %4)")
                    .arg(frameNumber)
                    .arg(fragmentNumber)
                    .arg(fragsPerFrame));
        }

        if(fragsPerFrame < 64)
        {
            d->hiAck = 0xffffffffffffffff;
            d->loAck = 0xffffffffffffffff << fragsPerFrame;
        }
        else if(fragsPerFrame < 128)
        {
            d->hiAck = 0xffffffffffffffff << (fragsPerFrame - 64);
            d->loAck = 0ll;
        }
        else
        {
            d->hiAck = 0ll;
            d->loAck = 0ll;
        }

        d->frameNumber = frameNumber;
    }

    if(fragmentNumber < 64)
    {
        d->loAck |= (1ll << fragmentNumber);
    }
    else if(fragmentNumber < 128)
    {
        d->hiAck |= (1ll << (fragmentNumber - 64));
    }

    // Construct reply.
    QByteArray payload(2 + 8 + 8, 0x00);
    QDataStream datastream(&payload, QIODevice::WriteOnly);

    if(!d->sequenceIds.contains(ARNET_C2D_VIDEO_ACK_ID))
        d->sequenceIds.insert(ARNET_C2D_VIDEO_ACK_ID, 0x00);

    datastream.setByteOrder(QDataStream::LittleEndian);
    datastream
            << (quint16)frameNumber
            << (quint64)d->hiAck
            << (quint64)d->loAck;

    sendFrame(ARControlConnection::LowLatencyData, ARNET_C2D_VIDEO_ACK_ID, payload.constData(), payload.size());
}
Esempio n. 13
0
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	FIBITMAP *dib = NULL;
	LibRaw RawProcessor;

	BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;

	try {
		// wrap the input datastream
		LibRaw_freeimage_datastream datastream(io, handle);

		// set decoding parameters
		// the following parameters affect data reading
		// --------------------------------------------

		// (-w) Use camera white balance, if possible (otherwise, fallback to auto_wb)
		RawProcessor.imgdata.params.use_camera_wb = 1;
		// RAW data filtration mode during data unpacking and postprocessing
		RawProcessor.imgdata.params.filtering_mode = LIBRAW_FILTERING_AUTOMATIC;
		// (-h) outputs the image in 50% size
		RawProcessor.imgdata.params.half_size = ((flags & RAW_HALFSIZE) == RAW_HALFSIZE) ? 1 : 0;

		// open the datastream
		if(RawProcessor.open_datastream(&datastream) != LIBRAW_SUCCESS) {
			throw "LibRaw : failed to open input stream (unknown format)";
		}

		if(header_only) {
			// header only mode
			dib = FreeImage_AllocateHeaderT(header_only, FIT_RGB16, RawProcessor.imgdata.sizes.width, RawProcessor.imgdata.sizes.height);
			// try to get JPEG embedded Exif metadata
			if(dib) {
				FIBITMAP *metadata_dib = libraw_LoadEmbeddedPreview(RawProcessor, FIF_LOAD_NOPIXELS);
				if(metadata_dib) {
					FreeImage_CloneMetadata(dib, metadata_dib);
					FreeImage_Unload(metadata_dib);
				}
			}
		}
		else if((flags & RAW_PREVIEW) == RAW_PREVIEW) {
			// try to get the embedded JPEG
			dib = libraw_LoadEmbeddedPreview(RawProcessor, 0);
			if(!dib) {
				// no JPEG preview: try to load as 8-bit/sample (i.e. RGB 24-bit)
				dib = libraw_LoadRawData(RawProcessor, 8);
			}
		} 
		else if((flags & RAW_DISPLAY) == RAW_DISPLAY) {
			// load raw data as 8-bit/sample (i.e. RGB 24-bit)
			dib = libraw_LoadRawData(RawProcessor, 8);
		} 
		else {
			// default: load raw data as linear 16-bit/sample (i.e. RGB 48-bit)
			dib = libraw_LoadRawData(RawProcessor, 16);
		}

		// save ICC profile if present
		if(NULL != RawProcessor.imgdata.color.profile) {
			FreeImage_CreateICCProfile(dib, RawProcessor.imgdata.color.profile, RawProcessor.imgdata.color.profile_length);
		}

		// try to get JPEG embedded Exif metadata
		if(dib && !((flags & RAW_PREVIEW) == RAW_PREVIEW) ) {
			FIBITMAP *metadata_dib = libraw_LoadEmbeddedPreview(RawProcessor, FIF_LOAD_NOPIXELS);
			if(metadata_dib) {
				FreeImage_CloneMetadata(dib, metadata_dib);
				FreeImage_Unload(metadata_dib);
			}
		}

		// clean-up internal memory allocations
		RawProcessor.recycle();

		return dib;

	} catch(const char *text) {
		if(dib) {
			FreeImage_Unload(dib);
		}
		RawProcessor.recycle();
		FreeImage_OutputMessageProc(s_format_id, text);
	}

	return NULL;
}
Esempio n. 14
0
bool FastSearchFormat::ReadChemObject(OBConversion* pConv)
{
    //Searches index file for structural matches
    //This function is called only once per search

    std::string auditMsg = "OpenBabel::Read fastsearch index ";
    std::string description(Description());
    auditMsg += description.substr(0,description.find('\n'));
    obErrorLog.ThrowError(__FUNCTION__,
                          auditMsg,
                          obAuditMsg);

    //Derive index name
    string indexname = pConv->GetInFilename();
    string::size_type pos=indexname.find_last_of('.');
    if(pos!=string::npos)
    {
        indexname.erase(pos);
        indexname += ".fs";
    }

    //Have to open input stream again because needs to be in binary mode
    ifstream ifs;
    stringstream errorMsg;
    if(!indexname.empty())
        ifs.open(indexname.c_str(),ios::binary);
    if(!ifs)
    {
        errorMsg << "Couldn't open " << indexname << endl;
        obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError);
        return false;
    }

    string datafilename = fs.ReadIndex(&ifs);
    if(datafilename.empty())
    {
        errorMsg << "Difficulty reading from index " << indexname << endl;
        obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError);
        return false;
    }

    OBMol patternMol;
    bool doSubset = pConv->IsOption("s",OBConversion::INOPTIONS)!=NULL;// -as option
    bool exactmatch = pConv->IsOption("e",OBConversion::INOPTIONS)!=NULL;// -ae option
    if(!doSubset)
    {
        //Similarity or substructure
        if(!ObtainTarget(pConv, patternMol, indexname))
            return false;
    }

    //Open the datafile and put it in pConv
    //datafile name derived from index file probably won't have a file path
    //but indexname may. Derive a full datafile name
    string path;
    pos = indexname.find_last_of("/\\");
    if(pos==string::npos)
        path = datafilename;
    else
        path = indexname.substr(0,pos+1) + datafilename;

    ifstream datastream(path.c_str());
    if(!datastream)
    {
        errorMsg << "Difficulty opening " << path << endl;
        obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError);
        return false;
    }
    pConv->SetInStream(&datastream);

    //Input format is currently fs; set it appropriately
    if(!pConv->SetInAndOutFormats(pConv->FormatFromExt(datafilename.c_str()),pConv->GetOutFormat()))
        return false;
    pConv->AddOption("b",OBConversion::GENOPTIONS);


    //Now do searching
    const char* p = pConv->IsOption("t",OBConversion::INOPTIONS);
    if(p)
    {
        //Do a similarity search
        multimap<double, unsigned int> SeekposMap;
        string txt=p;
        if(txt.find('.')==string::npos)
        {
            //Finds n molecules with largest Tanimoto
            int n = atoi(p);
            fs.FindSimilar(&patternMol, SeekposMap, n);
        }
        else
        {
            //Finds molecules with Tanimoto > MinTani
            double MinTani = atof(txt.c_str());
//            if(doSubset)
//              fs.FindSubset(SeekposMap, MinTani);
//            else
            fs.FindSimilar(&patternMol, SeekposMap, MinTani);
        }

        //Don't want to filter through SMARTS filter
        pConv->RemoveOption("s", OBConversion::GENOPTIONS);

        multimap<double, unsigned int>::reverse_iterator itr;
        for(itr=SeekposMap.rbegin(); itr!=SeekposMap.rend(); ++itr)
        {
            datastream.seekg(itr->second);

            if(pConv->IsOption("a", OBConversion::INOPTIONS))
            {
                //Adds Tanimoto coeff to title
                //First remove any previous value
                pConv->RemoveOption("addtotitle", OBConversion::GENOPTIONS);
                stringstream ss;
                ss << " " << itr->first;
                pConv->AddOption("addtotitle",OBConversion::GENOPTIONS, ss.str().c_str());

            }
            pConv->SetOneObjectOnly();
            if(itr != --SeekposMap.rend())
                pConv->SetMoreFilesToCome();//so that not seen as last on output
            pConv->Convert(NULL,NULL);
        }
    }

    else
    {
        //Structure search
        int MaxCandidates = 4000;
        p = pConv->IsOption("l",OBConversion::INOPTIONS);
        if(p && atoi(p))
            MaxCandidates = atoi(p);

        vector<unsigned int> SeekPositions;
        if(exactmatch)
        {
            //Find mols where all fingerprint bits are the same as the target
            fs.FindMatch(&patternMol, SeekPositions, MaxCandidates);
            // ensure that SMARTS filter in transform.cpp looks only for an exact match
            // by setting an option with the number of heavy atoms in the pattern mol included.
            stringstream ss;
            ss << patternMol.NumHvyAtoms();
            pConv->AddOption("exactmatch", OBConversion::GENOPTIONS, ss.str().c_str());
        }

        else
        {
            //Do a substructure search
            fs.Find(&patternMol, SeekPositions, MaxCandidates);
            clog << SeekPositions.size() << " candidates from fingerprint search phase" << endl;
        }

        //Output the candidate molecules
        //filtering through s filter, unless the fingerprint type does not require it
        if(fs.GetFingerprint()->Flags() & OBFingerprint::FPT_UNIQUEBITS)
            pConv->RemoveOption("s",OBConversion::GENOPTIONS);

        vector<unsigned int>::iterator itr;
        for(itr=SeekPositions.begin(); itr!=SeekPositions.end(); itr++)
        {
            datastream.seekg(*itr);
            //	datastream.seekg(*itr - datastream.tellg(), ios_base::cur); //Avoid retrieving start

            //debugging kludge to output all candidates directly
            if(pConv->IsOption("c",OBConversion::GENOPTIONS))
            {
                string ln;
                getline(datastream,ln);
                datastream.seekg(*itr);
                *pConv->GetOutStream() << "** " << ln << endl;
            }
            pConv->SetOneObjectOnly();
            pConv->SetLast(itr+1 == SeekPositions.end());
            pConv->Convert(NULL,NULL);
        }
    }
    return false;	//To finish
}