Beispiel #1
0
    /*
     * This stores the node on the disk. If the offset passed is -1 node will be stored at the end of the file.
     * This indicated newly added node.
     */
    int storeNode(TreeNode *node, long long int offset) {
        if (offset == -1) {
            offset = fHandler->getSize();
        }
        Utils::copyBytes(node->myaddr, Utils::getBytesForInt(offset), NODE_OFFSET_SIZE);
        char *block = (char *) malloc(BLOCK_SIZE);
        int position = 0;
        Utils::copyBytes(&block[position], Utils::getBytesForInt(offset),
                         NODE_OFFSET_SIZE);
        position += NODE_OFFSET_SIZE;
        block[position] = node->flag;
        position += 1;
        Utils::copyBytes(&block[position], Utils::getBytesForInt(node->numkeys),
                         sizeof(node->numkeys));
        position += sizeof(node->numkeys);
        Utils::copyBytes(&block[position], (node->data), sizeof(node->data));
        position += sizeof(node->data);
        if(node->nextaddr){
			Utils::copyBytes(&(block[position]), (node->nextaddr), NODE_OFFSET_SIZE);
		}
        else Utils::copyBytes(&(block[position]), Utils::getBytesForInt(-1), NODE_OFFSET_SIZE);
        fHandler->writeBlock(offset, block);
        free(block);
        return 0;
    }
Beispiel #2
0
void MatrixGraph::displayMatrix(MatrixGraph& mg)
{
	IoHandler ioh;

	string fileName = ioh.getString("무방향 그래프가 저장된 파일명을 입력하시오.(종료는 quit) : ");
	if (fileName == "quit")
	{
		exit(1);
	}
	FileHandler fh;

	fh.loadMatrixGraph(fileName, mg);

	ioh.putString("입력된 그래프의 인접 행렬 표현");
	ioh.putNewLine();

	mg.printMatrix();
	ioh.putNewLine();

	mg.dfs();
	ioh.putNewLine();

	mg.bfs();
	ioh.putNewLine();
}
Beispiel #3
0
int main()
{
    sout << locker << "\n  Console Receiver Demo "
         << "\n =======================\n" << unlocker;

    try
    {
        EndPoint rep("127.0.0.1",8081);
        //EndPoint sep("127.0.0.1",2049);

        // MsgReceiver_Proc is your receiver's server message handling
        // FileReceiver_Proc is your receiver's server file handling
        Communicator rcvr(rep);
        MsgHandler<MsgReceiver_Proc> rMsgHandler;
        rMsgHandler.setCommunicator(&rcvr);
        rcvr.attachMsgHandler(&rMsgHandler);
        FileHandler<FileReceiver_Proc> rFileHandler;
        rFileHandler.setFileDestination(".\\debug");
        rFileHandler.setCommunicator(&rcvr);
        rcvr.attachFileHandler(&rFileHandler);
        rcvr.listen();

        sout << "\n\n  press key to exit:  ";
        sout.flush();
        _getche();
        sout << "\n\n";
        rcvr.disconnect();
    }
    catch(std::exception& ex)
    {
        sout << locker << "\n  " << ex.what() << "\n\n" << unlocker;
    }
}
Beispiel #4
0
int CacheManager::init() {
    assert(m_initialised == false);

    FileHandler *fh = System::instance()->getFileHandler();

    assert(fh != NULL);

    // Cache path name
    std::string c_path = fh->getUserDataPath() + CACHE_PATH;

    // Check if path exists
    if (!fh->exists(c_path)) {
        printf("Creating Cache Directory.\n");
        fh->mkdir(c_path);
    }

    // Load cache data file
    if (fh->exists(c_path + CACHE_FILE)) {
        if (!m_cache.readFromFile(c_path + CACHE_FILE)) {
            fprintf(stderr, "Error reading cache config file.\n");
        }
    }

    m_initialised = true;

    return 0;
}
void ProcessHandler::WriteProcessesInfoToFile(char* pFilename)
{
	std::vector<Process> processes = GetCurrentProcesses();
	FileHandler fh;
	fh.Open(pFilename, FileHandler::FILE_WRITE);
	std::vector<Process>::iterator iter = processes.begin();
	for (; iter != processes.end(); ++iter)
	{
		fh.Write(*iter);
	}
	fh.Close();
}
Beispiel #6
0
  ExitCodes main_(int, const char**) override
  {
    StringList in  = getStringList_("in");
    StringList out = getStringList_("out");
    bool inplace = getFlag_("i");

    // consistency checks
    if (out.empty() && !inplace)
    {
      writeLog_("Cannot write output files, as neither -out nor -i are given. Use either of them, but not both!");
      printUsage_();
      return ILLEGAL_PARAMETERS;
    }
    if (out.size() > 0 && inplace)
    {
      writeLog_("Two incompatible arguments given (-out and -i). Use either of them, but not both!");
      printUsage_();
      return ILLEGAL_PARAMETERS;
    }

    if (!inplace && out.size() != in.size())
    {
      writeLog_("Output and input file list length must be equal!");
      printUsage_();
      return ILLEGAL_PARAMETERS;
    }

    // do the conversion!
    FileHandler fh;
    for (Size i = 0; i < in.size(); ++i)
    {
      FileTypes::Type f_type = fh.getType(in[i]);
      if (f_type == FileTypes::INI) updateINI(in[i], inplace ? "" : out[i]);
      else if (f_type == FileTypes::TOPPAS) updateTOPPAS(in[i], inplace ? "" : out[i]);
    }

    for (Size i = 0; i < tmp_files_.size(); ++i)
    {
      // clean up
      File::remove(tmp_files_[i]);
    }


    if (failed_.size() > 0)
    {
      writeLog_("The following INI/TOPPAS files could not be updated:\n  " + ListUtils::concatenate(failed_, "\n  "));
      return INPUT_FILE_CORRUPT;
    }

    return EXECUTION_OK;

  }
Beispiel #7
0
/*
 * Create our database using the appropriate schema.
 */
bool DBHandler::dbCreateInstance()
{
    QMutexLocker locker(&dbMutex);

    int error = 0; // Number of SQL queries

    QSqlQuery query(db);

    if (db.isOpen())
    {
        qDebug() << "Creating Tables";

        QString address_book_create = "CREATE TABLE address_book (id INTEGER PRIMARY KEY, nym_id TEXT, nym_display_name TEXT)";
        // --------------------------------------------
        QString default_nym_create = "CREATE TABLE default_nym (default_id INTEGER PRIMARY KEY, nym TEXT)";
        QString default_server_create = "CREATE TABLE default_server (default_id INTEGER PRIMARY KEY, server TEXT)";
        QString default_asset_create = "CREATE TABLE default_asset (default_id INTEGER PRIMARY KEY, asset TEXT)";
        QString default_account_create = "CREATE TABLE default_account (default_id INTEGER PRIMARY KEY, account TEXT)";
        QString settings = "CREATE TABLE settings (setting TEXT PRIMARY KEY, parameter1 TEXT)";
        // --------------------------------------------
        QString create_contact = "CREATE TABLE contact(contact_id INTEGER PRIMARY KEY, contact_display_name TEXT)";
        QString create_nym     = "CREATE TABLE nym(nym_id TEXT PRIMARY KEY, contact_id INTEGER, nym_display_name)";
        QString create_server  = "CREATE TABLE nym_server(nym_id TEXT, server_id TEXT, PRIMARY KEY(nym_id, server_id))";
        QString create_account = "CREATE TABLE nym_account(account_id TEXT PRIMARY KEY, server_id TEXT, nym_id TEXT, asset_id TEXT, account_display_name TEXT)";
        // --------------------------------------------
        error += query.exec(address_book_create);
        error += query.exec(default_nym_create);
        error += query.exec(default_server_create);
        error += query.exec(default_asset_create);
        error += query.exec(default_account_create);
        error += query.exec(settings);
        // --------------------------------------------
        error += query.exec(create_contact);
        error += query.exec(create_nym);
        error += query.exec(create_server);
        error += query.exec(create_account);
        // ------------------------------------------
        if(error != 10)  //every querie passed?
        {
            qDebug() << "dbCreateInstance Error: " << dbConnectErrorStr + " " + dbCreationStr;
            FileHandler rm;
            db.close();

            rm.removeFile(QString(OTPaths::AppDataFolder().Get()) + dbFileNameStr);
//          rm.removeFile(QCoreApplication::applicationDirPath() + dbFileNameStr);
        }
        else
            qDebug() << "Database " + dbFileNameStr + " created.";
    }
    return error;
}
Beispiel #8
0
 void setFilePath(const std::string& filePath)
 {
     if(!m_filePath.empty())
         m_fileHandler.close();
     m_filePath = filePath;
     freeData();
     m_gotData = false;
     if(!filePath.empty()){
         m_fileHandler.open(filePath);
         if(m_fileHandler.isOpen()){
             allocData();
         }
     }
 }
Beispiel #9
0
static int
FileHandlerEventProc(
    Tcl_Event *evPtr,		/* Event to service. */
    int flags)			/* Flags that indicate what events to handle,
				 * such as TCL_FILE_EVENTS. */
{
    FileHandler *filePtr;
    FileHandlerEvent *fileEvPtr = (FileHandlerEvent *) evPtr;
    int mask;

    if (!(flags & TCL_FILE_EVENTS)) {
	return 0;
    }

    /*
     * Search through the file handlers to find the one whose handle matches
     * the event. We do this rather than keeping a pointer to the file handler
     * directly in the event, so that the handler can be deleted while the
     * event is queued without leaving a dangling pointer.
     */

    for (filePtr = notifier.firstFileHandlerPtr; filePtr != NULL;
	    filePtr = filePtr->nextPtr) {
	if (filePtr->fd != fileEvPtr->fd) {
	    continue;
	}

	/*
	 * The code is tricky for two reasons:
	 * 1. The file handler's desired events could have changed since the
	 *    time when the event was queued, so AND the ready mask with the
	 *    desired mask.
	 * 2. The file could have been closed and re-opened since the time
	 *    when the event was queued. This is why the ready mask is stored
	 *    in the file handler rather than the queued event: it will be
	 *    zeroed when a new file handler is created for the newly opened
	 *    file.
	 */

	mask = filePtr->readyMask & filePtr->mask;
	filePtr->readyMask = 0;
	if (mask != 0) {
	    filePtr->proc(filePtr->clientData, mask);
	}
	break;
    }
    return 1;
}
Beispiel #10
0
void CameraHandler::SwitchToReadMode() {
	delete m_camera;
	cout << "Please enter the directory name of your recorded video: ";
	char dirName[150];
	cin >> dirName;
	FileHandler* fileHandler = FileHandler::Init();
	const char* videoSuperDirectoryName = "Video";
	char fullPath[150];
	fileHandler->GetPath(videoSuperDirectoryName, dirName, fullPath);

	m_camera = new CameraFromFile(fullPath);
	if (!m_camera->IsInitialized()) {
		cout << "Failed initializing read from file." << endl;
		delete fileHandler;
		exit(1);
	}
	delete fileHandler;
}
/**
 * Load shader from file.
 */
void ShaderTransformation::loadShader(const char* file){
#ifdef _PC_
    if(shaderType == ShaderTransformation::st_Pixel)
        shader.loadFromFile(file, sf::Shader::Fragment);
    else if(shaderType == ShaderTransformation::st_Vertex)
        shader.loadFromFile(file, sf::Shader::Vertex);
    else{
        FileHandler handler;
        MemoryPool* fileData = handler.readFile(file);
        const char* vertexShader = (const char*)fileData->getBuffer();
        int i;
        while(vertexShader[i] != 0)
            i++;
        const char* pixelShader = vertexShader + i + 1;

        shader.loadFromMemory(vertexShader, pixelShader);
        delete fileData;
    }
#endif
}
Beispiel #12
0
 /*
  * Constructor to load already existing index
  */
 Index(char* indexName) {
     fHandler = new FileHandler(indexName, 'o');
     header = (char *) malloc(BLOCK_SIZE);
     fHandler->readBlock(0, header);
     Utils::copyBytes(rootAddress, header, NODE_OFFSET_SIZE);
     root = new TreeNode();
     loadNode(root, rootAddress);
     payloadlen = Utils::getIntForBytes(&header[NODE_OFFSET_SIZE]);
     keytype = Utils::getKeyTypeForBytes(
             &header[NODE_OFFSET_SIZE + sizeof(payloadlen)]);
 }
Beispiel #13
0
int main(){
        string filename = "topology.txt";
        string filename1 = "changes.txt";
        string filename2 = "messages.txt";
        FileHandler * h = new FileHandler();
        h->parse(filename,"TOPO_FILE");
        h->parse(filename1,"CHANGES_FILE");
        h->parse(filename2,"MESSAGES_FILE");
        int len = h->getNumInit();
        int * row_one = h->getGraph(0);
        printf("Number of rows: %d\n",len);
        printf("First row: %d %d %d\n",row_one[0],row_one[1],row_one[2]);
        printf("Changes file\n");
        printf("Number of changes: %d\n",h->getNumChanges());
        int * change_one = h->getChange(0);
        printf("First change: %d %d %d\n",change_one[0],change_one[1],change_one[2]);
        printf("Messages\n");
        printf("Number of messages: %d\n",h->getNumMessages());
        printf("First message: %s\n",h->getMessage(0).c_str());
        free(h);
}
Beispiel #14
0
    /*
	 * This is to handle first addition. First addition needs to update header of the file with nodes address
	 */
    int addFirstElement(byte *key, byte *payload) {
        root = new TreeNode();
        root->numkeys = 0;
        root->flag = 'c';
        root->addData(keytype, key, payloadlen, payload, 0);
        root->numkeys = 1;
        Utils::copyBytes(header, Utils::getBytesForInt((long long int) 1), NODE_OFFSET_SIZE);
        Utils::copyBytes(rootAddress, Utils::getBytesForInt((long long int) 1), NODE_OFFSET_SIZE);
        fHandler->writeBlock(0, header);
        storeNode(root, 1);
        return 0;
    }
Beispiel #15
0
 void
 allocData()
 {
     assert(m_fileHandler.isOpen());
     if(m_data.getData())
         return;
     policies::GetExtents< FileHandler > fileExtents(m_fileHandler);
     typename Data::IdxType extents;
     for(unsigned i=0; i<numDims; ++i)
         extents[i] = fileExtents[i];
     m_data.allocData(extents);
 }
Beispiel #16
0
int main()
{
	FileHandler* fh = FileHandler::GetInstance();
	vector<Passenger*> passengers;
	fh->ReadPassengers(passengers);

	cout << "FIFO simulation start" << endl;
	Simulator* simulator = Simulator::GetInstance();
	Strategy* strategy = new FIFO();
	vector<Passenger*> servedPassengers = simulator->Simulate(strategy, passengers);
	simulator->GetEverageTicketingWaitingTime(servedPassengers);
	fh->WritePassengers(servedPassengers, "result1.txt");

	cout << "\nLTFO simulation start" << endl;
	fh->ReadPassengers(passengers);
	strategy = new LTFO();
	servedPassengers = simulator->Simulate(strategy, passengers);
	simulator->GetEverageTicketingWaitingTime(servedPassengers);
	fh->WritePassengers(servedPassengers, "result2.txt");

	return 0;
}
Beispiel #17
0
CameraHandler::CameraHandler()
{
	inputData_depth = new CAMERA_DEPTH_TYPE[m_params.m_width*m_params.m_height];
	inputData_rgb = new CAMERA_RGB_TYPE[m_params.m_width*m_params.m_height];
	
	if(isFromCamera) {
		char path[200] = {0};
		FileHandler* fileHandler = FileHandler::Init();
		fileHandler->GetPath("Video", "realTrial", path); // TODO: What is this real trial? You may want to get it from the user.

		// TODO: THE SOFTKINETIC CONSTRUCTOR MUST CHECK THAT IT CAN READ FROM THE SERVER.
		// OTHERWISE IT SHOULD RETURN FALSE.
		
		if (FALSE
		#ifdef BUILD_SOFTKINETIC
		    || (m_camera = new SoftKineticCamera()) && m_camera->IsInitialized() 
		#endif
		#ifdef BUILD_GIPCAM
		    || (m_camera = new GIPCam()) && m_camera->IsInitialized()
		#endif
		#ifdef BUILD_PRIMESENSE
		    || (m_camera = new PrimesenseCamera()) && m_camera->IsInitialized()
		#endif
		#ifdef BUILD_FROMFILE
		    || (m_camera = new CameraFromFile(path)) && m_camera->IsInitialized()
		#endif
		)
		{
			m_params = *(m_camera->GetParameters());
		}
		else {
			cout << "No camera found!" << endl;
			exit(1); // TODO CHANGE
		}
	}
}
Beispiel #18
0
    /*
     * This loads the node.We are using an in memory structure for node.Following function generates the node from the block read.
     */
    int loadNode(TreeNode *here, char *offset) {
        int position = 0;
        char *block = (char *) malloc(BLOCK_SIZE);

        fHandler->readBlock(Utils::getIntForBytes(offset), block);
        Utils::copyBytes(here->myaddr, offset, NODE_OFFSET_SIZE);
        position += NODE_OFFSET_SIZE;

        here->flag = block[position];
        position += 1;
        here->numkeys = Utils::getIntForBytes(&(block[position]));
        position += sizeof(here->numkeys);
        Utils::copyBytes(here->data, &(block[position]), sizeof(here->data));
		position += sizeof(here->data);
		//printf("%d %d\n",Utils::getIntForBytes(&block[position]),position);
		if(Utils::getIntForBytes(&block[position]) != -1){
			here->nextaddr = (char *) malloc(NODE_OFFSET_SIZE);
			Utils::copyBytes(here->nextaddr, &(block[position]), NODE_OFFSET_SIZE);
		}
        free(block);
        return 0;
    }
Beispiel #19
0
bool RADCompute::write(FileHandler &f, map<int, vector<vector<double> > > &linear_hist){
	
	if(!f.is_open()) return false;
	string err_msg = "";
	bool aborted = false;
	for(map<int, vector<vector<double> > >::iterator i = linear_hist.begin(); i != linear_hist.end(); ++i){
		int class_label = i->first;
		for(vector<vector<double> >::iterator j = i->second.begin(); j != i->second.end(); ++j){
			int inst_idx = 0;
			string inst_str = "";
			for(vector<double>::iterator e = j->begin(); e != j->end(); ++e){
				char buff[100];
				sprintf(buff,"%d:%5.7f ",++inst_idx,*e);
				inst_str += buff;
				
			}
			char *buff;
			buff = (char *)malloc(sizeof(char)*(inst_str.size()+100));
			sprintf(buff,"%d %s\n",class_label,inst_str.c_str());
			inst_str = string(buff);
			delete []buff;
			bool worked = f << inst_str;
			if(!worked){
			 	aborted = true;
				err_msg += "Failed to write: " + inst_str + " : to the file\n";
				break;
			}
		}
		if(aborted) break;
	}

	if(aborted){
		cerr << err_msg << endl;
	}
	return !aborted;
}
void
TFileHandler::isFileExist () {
  FileHandler fh;
  QVERIFY (fh.isFileExist (tFilename) == true);
}
Beispiel #21
0
 const ExtentsVec&
 getExtents() const
 {
     assert(m_fileHandler.isOpen());
     return m_data.getExtents();
 }
int main( int argc, char ** argv ) {

    std::string *filename = NULL;
    int times = 0, cost = 0, innerTimes = 0;
    bool mazeValid = false;
    FileHandler *file = NULL;
    Maze *maze = new Maze( ROWS, COLS );
    GeneticAlgorithm *algorithm = new GeneticAlgorithm( maze );
    Search *search = new Search( maze );
    Agent *agent = new Agent( maze );

    if( argc == 2 ) {
        filename = new std::string( argv[1] );
    } else {
        filename = new std::string( "maze.txt" );
    }

    algorithm->setMinIterations( MIN_ITERATIONS );
    algorithm->setMutationRate( MUTATION_RATE );
    algorithm->setCrossOverRate( CROSS_OVER_RATE );

    maze->setRandomRate( RANDOM_RATE );
    maze->generateFirstPopulation();

    do {
        times++;
        algorithm->run();

        mazeValid = maze->searchDoors();
        // Se ele nao tem portas suficientes para testar
        // Executa o A.G denovo
        if( ! mazeValid ) {
            continue;
        }

        while( ( mazeValid = maze->selectDoors( MIN_COST, MAX_COST ) ) ) {

            // Se a menor distancia entre a entrada e saida for maior
            // que o MAX_COST, entao nao ha caminho valido
            if( ! maze->validDistance( MIN_COST, MAX_COST ) ) {
                continue;
            }

            cost = search->hasSolution( true ); // Usa o algoritmo A*, mais rapido a convergencia...
            if( cost >= MIN_COST && cost <= MAX_COST ) {
                break;
            }
            innerTimes++;
        }
        if( times % 10 == 0 ) {
            std::cout << times << ": " << DataNode::ctor << ", " << DataNode::dtor << std::endl;
        }

    } while( ! mazeValid );

    agent->run();

    try {
        file = new FileHandler( filename->c_str() );
        file->printMaze( maze );
        std::cout << "Maze dump in " << *filename << std::endl;
    } catch( int e ) {
        std::cout << file->getErrorMessage();
    }

    delete agent;
    delete search;
    delete maze;
    delete filename;
    delete algorithm;
    delete file;

    return 0;
}
Beispiel #23
0
    /*
     * This inserts pointers into node.May result in node split which is also handled.This results in recursive call to add pointers
     * to the parents up the tree till root
     */
    int insertIntoParent(byte left[NODE_OFFSET_SIZE], byte key[],
                         byte right[NODE_OFFSET_SIZE], byte parentOffset[NODE_OFFSET_SIZE],
                         int height, char accessPath[][NODE_OFFSET_SIZE]) {
        if (strncmp(rootAddress, left, NODE_OFFSET_SIZE) == 0) {
            TreeNode *newRoot = new TreeNode();
            newRoot->numkeys = 1;
            newRoot->flag = 'n';
            Utils::copyBytes(newRoot->data, key, keylen(&keytype));
            Utils::copyBytes(&(newRoot->data[DATA_SIZE - NODE_OFFSET_SIZE]),
                             left, NODE_OFFSET_SIZE);
            Utils::copyBytes(&(newRoot->data[DATA_SIZE - NODE_OFFSET_SIZE * 2]),
                             right, NODE_OFFSET_SIZE);
            root = newRoot;
            storeNode(newRoot, -1);
            Utils::copyBytes(rootAddress, root->myaddr, NODE_OFFSET_SIZE);

            byte *block = (byte *) malloc(BLOCK_SIZE);

            fHandler->readBlock(0, block);
            Utils::copyBytes(block, rootAddress, NODE_OFFSET_SIZE);
            fHandler->writeBlock(0, block);
            free(block);
            return 0;
        }

        TreeNode *parent = new TreeNode();
        loadNode(parent, parentOffset);
        int i;
        char nodekey[keylen(&keytype)];
        for (i = 0; i < parent->numkeys; i++) {
            parent->getKey(keytype, nodekey, i);
            int isLesser = compare(nodekey, key, keytype);
            if (isLesser > 0) {
                break;
            }
        }
        if (splitNecessary(parent->numkeys + 1, parent->flag) != 1) {
            parent->addData(keytype, key, NODE_OFFSET_SIZE, right, i);
            parent->numkeys = parent->numkeys + 1;
            storeNode(parent, Utils::getIntForBytes(parent->myaddr));

        } else {
            TreeNode *newNonLeaf = new TreeNode();
            int numPointers = parent->numkeys;
            if (parent->flag != 'c')
                numPointers++;
            int tempSpaceSize = DATA_SIZE + payloadlen + keylen(&keytype);
            char *tempSpace = (char *) calloc(tempSpaceSize, sizeof(char));
            Utils::copyBytes(tempSpace, parent->data,
                             (parent->numkeys) * keylen(&keytype));
            Utils::copyBytes(
                    &tempSpace[tempSpaceSize - (numPointers) * NODE_OFFSET_SIZE],
                    &(parent->data[DATA_SIZE - (numPointers) * NODE_OFFSET_SIZE]),
                    (numPointers) * NODE_OFFSET_SIZE);
            for (int j = parent->numkeys - 1; j >= (i); j--) {
                Utils::copyBytes(&(tempSpace[(j + 1) * keylen(&keytype)]),
                                 &(tempSpace[j * keylen(&keytype)]), keylen(&keytype));
            }
            strncpy(&(tempSpace[(i) * keylen(&keytype)]), key,
                    keylen(&keytype));
            int pointerPosition = i;
            if (parent->flag != 'c')
                pointerPosition++;
            for (int j = (tempSpaceSize - numPointers * NODE_OFFSET_SIZE);
                 j < (tempSpaceSize - pointerPosition * NODE_OFFSET_SIZE);
                 j += NODE_OFFSET_SIZE) {
                Utils::copyBytes(&(tempSpace[j - NODE_OFFSET_SIZE]),
                                 &(tempSpace[j]), NODE_OFFSET_SIZE);
            }
            strncpy(
                    &(tempSpace[tempSpaceSize
                                - (pointerPosition + 1) * NODE_OFFSET_SIZE]), right,
                    NODE_OFFSET_SIZE);

            parent->numkeys = parent->numkeys + 1;
            int n_by_two = (parent->numkeys) / 2;
            int k = 0;
            for (int i = 0; i < n_by_two; i++) {
                Utils::copyBytes(&(parent->data[(i) * keylen(&keytype)]),
                                 &(tempSpace[(i * keylen(&keytype))]), keylen(&keytype));
                Utils::copyBytes(
                        &(parent->data[DATA_SIZE - ((i + 1)) * NODE_OFFSET_SIZE]),
                        &(tempSpace[tempSpaceSize - ((i + 1) * NODE_OFFSET_SIZE)]),
                        NODE_OFFSET_SIZE);
                k = i + 1;
            }
            if (parent->flag != 'c')
                Utils::copyBytes(
                        &(parent->data[DATA_SIZE - ((k + 1)) * NODE_OFFSET_SIZE]),
                        &(tempSpace[tempSpaceSize - ((k + 1) * NODE_OFFSET_SIZE)]),
                        NODE_OFFSET_SIZE);
            for (int i = n_by_two + 1; i < parent->numkeys; i++) {
                Utils::copyBytes(
                        &(newNonLeaf->data[(i - (n_by_two + 1))
                                           * keylen(&keytype)]),
                        &(tempSpace[(i * keylen(&keytype))]), keylen(&keytype));
                Utils::copyBytes(
                        &(newNonLeaf->data[DATA_SIZE
                                           - ((i + 1) - (n_by_two + 1)) * NODE_OFFSET_SIZE]),
                        &(tempSpace[tempSpaceSize - ((i + 1) * NODE_OFFSET_SIZE)]),
                        NODE_OFFSET_SIZE);
                k = i + 1;
            }
            if (parent->flag != 'c')
                Utils::copyBytes(
                        &(newNonLeaf->data[DATA_SIZE
                                           - ((k + 1) - (n_by_two + 1)) * NODE_OFFSET_SIZE]),
                        &(tempSpace[tempSpaceSize - ((k + 1) * NODE_OFFSET_SIZE)]),
                        NODE_OFFSET_SIZE);
            newNonLeaf->flag = 'n';
            newNonLeaf->numkeys = parent->numkeys - n_by_two - 1;
            parent->numkeys = n_by_two;

            TreeNode* grandParent = new TreeNode();
            for (int i = 0; i < height; i++) {
                if (strncmp(accessPath[i], (parent->myaddr), NODE_OFFSET_SIZE)
                    == 0) if (i != 0)
                    loadNode(grandParent, accessPath[i - 1]);
            }

            char nextKey[keylen(&keytype)];

            Utils::copyBytes(nextKey,
                             &(tempSpace[(n_by_two * keylen(&keytype))]),
                             keylen(&keytype));
            storeNode(newNonLeaf, -1);
            storeNode(parent, Utils::getIntForBytes(parent->myaddr));

            char left[NODE_OFFSET_SIZE];
            Utils::copyBytes(left, parent->myaddr, NODE_OFFSET_SIZE);
            char right[NODE_OFFSET_SIZE];
            Utils::copyBytes(right, newNonLeaf->myaddr, NODE_OFFSET_SIZE);
            char parentAdd[NODE_OFFSET_SIZE];
            Utils::copyBytes(parentAdd, grandParent->myaddr, NODE_OFFSET_SIZE);
            if (parent != root)
                delete (parent);
            delete (newNonLeaf);
            delete (grandParent);
            insertIntoParent(left, nextKey, right, parentAdd, height,
                             accessPath);
        }
        return 0;
    }
Beispiel #24
0
void Find(const char* root, FileHandler& f, const char** ignoredFiles)
{
	if (!root)
		return;

	// Fix slashes
	char goodRoot[128];
	strcpy(goodRoot, root);
#if defined PX_WINDOWS || defined PX_X360
	for (char* p = goodRoot; *p; ++p)
	{
		if ('/' == *p)
			*p = '\\';
	}
#endif

	physx::DirEntry dentry;
	if (!physx::DirEntry::GetFirstEntry(goodRoot, dentry))
	{
		PX_ALWAYS_ASSERT();
		return;
	}

	for (; !dentry.isDone(); dentry.next())
	{
		const char* filename = dentry.getName();

		if (!filename || 0 == strcmp(".", filename) || 0 == strcmp("..", filename))
			continue;

		bool doSkip = false;
		for (size_t i = 0; ignoredFiles && ignoredFiles[i]; ++i)
		{
			if (0 == strcmp(filename, ignoredFiles[i]))
			{
				doSkip = true;
				break;
			}
		}

		if (doSkip)
			continue;

		char tmp[128];
		physx::string::sprintf_s(tmp, sizeof(tmp), "%s/%s", goodRoot, filename);

#if defined PX_WINDOWS || defined PX_X360
	for (char* p = tmp; *p; ++p)
	{
		if ('/' == *p)
			*p = '\\';
	}
#endif

		if (dentry.isDirectory())
		{
			Find(tmp, f, ignoredFiles);
			continue;
		}

		f.handle(tmp);
	}
}
void
TFileHandler::removeFile () {
  FileHandler fh;
  QVERIFY (fh.removeFile(tFilename) == true);
}
Beispiel #26
0
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/RichPeak1D.h>

START_TEST(FileHandler, "$Id$")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace OpenMS;
using namespace std;

START_SECTION((static FileTypes::Type getTypeByFileName(const String &filename)))
FileHandler tmp;
TEST_EQUAL(tmp.getTypeByFileName("test.bla"), FileTypes::UNKNOWN)
TEST_EQUAL(tmp.getTypeByFileName("test.dta"), FileTypes::DTA)
TEST_EQUAL(tmp.getTypeByFileName("test.DTA2D"), FileTypes::DTA2D)
TEST_EQUAL(tmp.getTypeByFileName("test.MzData"), FileTypes::MZDATA)
TEST_EQUAL(tmp.getTypeByFileName("test.MZXML"), FileTypes::MZXML)
TEST_EQUAL(tmp.getTypeByFileName("test.featureXML"), FileTypes::FEATUREXML)
TEST_EQUAL(tmp.getTypeByFileName("test.idXML"), FileTypes::IDXML)
TEST_EQUAL(tmp.getTypeByFileName("test.consensusXML"), FileTypes::CONSENSUSXML)
TEST_EQUAL(tmp.getTypeByFileName("test.mGf"), FileTypes::MGF)
TEST_EQUAL(tmp.getTypeByFileName("test.ini"), FileTypes::INI)
TEST_EQUAL(tmp.getTypeByFileName("test.toPPas"), FileTypes::TOPPAS)
TEST_EQUAL(tmp.getTypeByFileName("test.TraFoXML"), FileTypes::TRANSFORMATIONXML)
TEST_EQUAL(tmp.getTypeByFileName("test.MzML"), FileTypes::MZML)
TEST_EQUAL(tmp.getTypeByFileName(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.bz2")), FileTypes::MZML)
TEST_EQUAL(tmp.getTypeByFileName(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.gz")), FileTypes::MZML)
Beispiel #27
0
  ExitCodes main_(int, const char**)
  {

    //-------------------------------------------------------------
    // parameter handling
    //-------------------------------------------------------------
    //file list
    StringList file_list = getStringList_("in");

    //file type
    FileHandler fh;
    FileTypes::Type force_type;
    if (getStringOption_("in_type").size() > 0)
    {
      force_type = FileTypes::nameToType(getStringOption_("in_type"));
    }
    else
    {
      force_type = fh.getType(file_list[0]);
    }

    //output file names and types
    String out_file = getStringOption_("out");

    //-------------------------------------------------------------
    // calculations
    //-------------------------------------------------------------

    bool annotate_file_origin =  getFlag_("annotate_file_origin");

    if (force_type == FileTypes::FEATUREXML)
    {
      FeatureMap<> out;
      for (Size i = 0; i < file_list.size(); ++i)
      {
        FeatureMap<> map;
        FeatureXMLFile fh;
        fh.load(file_list[i], map);

        if (annotate_file_origin)
        {
          for (FeatureMap<>::iterator it = map.begin(); it != map.end(); ++it)
          {
            it->setMetaValue("file_origin", DataValue(file_list[i]));
          }
        }
        out += map;
      }

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      addDataProcessing_(out, getProcessingInfo_(DataProcessing::FORMAT_CONVERSION));

      FeatureXMLFile f;
      f.store(out_file, out);

    }
    else if (force_type == FileTypes::CONSENSUSXML)
    {
      ConsensusMap out;
      ConsensusXMLFile fh;
      fh.load(file_list[0], out);
      //skip first file
      for (Size i = 1; i < file_list.size(); ++i)
      {
        ConsensusMap map;
        ConsensusXMLFile fh;
        fh.load(file_list[i], map);

        if (annotate_file_origin)
        {
          for (ConsensusMap::iterator it = map.begin(); it != map.end(); ++it)
          {
            it->setMetaValue("file_origin", DataValue(file_list[i]));
          }
        }
        out += map;
      }

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      addDataProcessing_(out, getProcessingInfo_(DataProcessing::FORMAT_CONVERSION));

      ConsensusXMLFile f;
      f.store(out_file, out);
    }
    else if (force_type == FileTypes::TRAML)
    {
      TargetedExperiment out;
      for (Size i = 0; i < file_list.size(); ++i)
      {
        TargetedExperiment map;
        TraMLFile fh;
        fh.load(file_list[i], map);
        out += map;
      }

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      Software software;
      software.setName("FileMerger");
      software.setVersion(VersionInfo::getVersion());
      out.addSoftware(software);

      TraMLFile f;
      f.store(out_file, out);
    }
    else
    {
      // we might want to combine different types, thus we only
      // query in_type (which applies to all files)
      // and not the suffix or content of a single file
      force_type = FileTypes::nameToType(getStringOption_("in_type"));

      //rt
      bool rt_auto_number = getFlag_("raw:rt_auto");
      bool rt_filename = getFlag_("raw:rt_filename");
      bool rt_custom = false;
      DoubleList custom_rts = getDoubleList_("raw:rt_custom");
      if (custom_rts.size() != 0)
      {
        rt_custom = true;
        if (custom_rts.size() != file_list.size())
        {
          writeLog_("Custom retention time list must have as many elements as there are input files!");
          printUsage_();
          return ILLEGAL_PARAMETERS;
        }
      }

      //ms level
      bool user_ms_level = getFlag_("raw:user_ms_level");

      MSExperiment<> out;
      out.reserve(file_list.size());
      UInt rt_auto = 0;
      UInt native_id = 0;
      std::vector<MSChromatogram<ChromatogramPeak> > all_chromatograms;
      for (Size i = 0; i < file_list.size(); ++i)
      {
        String filename = file_list[i];

        //load file
        MSExperiment<> in;
        fh.loadExperiment(filename, in, force_type, log_type_);
        if (in.empty() && in.getChromatograms().empty())
        {
          writeLog_(String("Warning: Empty file '") + filename + "'!");
          continue;
        }
        out.reserve(out.size() + in.size());

        //warn if custom RT and more than one scan in input file
        if (rt_custom && in.size() > 1)
        {
          writeLog_(String("Warning: More than one scan in file '") + filename + "'! All scans will have the same retention time!");
        }

        for (MSExperiment<>::const_iterator it2 = in.begin(); it2 != in.end(); ++it2)
        {
          //handle rt
          Real rt_final = it2->getRT();
          if (rt_auto_number)
          {
            rt_final = ++rt_auto;
          }
          else if (rt_custom)
          {
            rt_final = custom_rts[i];
          }
          else if (rt_filename)
          {
            if (!filename.hasSubstring("rt"))
            {
              writeLog_(String("Warning: cannot guess retention time from filename as it does not contain 'rt'"));
            }
            for (Size i = 0; i < filename.size(); ++i)
            {
              if (filename[i] == 'r' && ++i != filename.size() && filename[i] == 't' && ++i != filename.size() && isdigit(filename[i]))
              {
                String rt;
                while (i != filename.size() && (filename[i] == '.' || isdigit(filename[i])))
                {
                  rt += filename[i++];
                }
                if (rt.size() > 0)
                {
                  // remove dot from rt3892.98.dta
                  //                          ^
                  if (rt[rt.size() - 1] == '.')
                  {
                    // remove last character
                    rt.erase(rt.end() - 1);
                  }
                }
                try
                {
                  float tmp = rt.toFloat();
                  rt_final = tmp;
                }
                catch (Exception::ConversionError)
                {
                  writeLog_(String("Warning: cannot convert the found retention time in a value '" + rt + "'."));
                }
              }
            }
          }

          // none of the rt methods were successful
          if (rt_final == -1)
          {
            writeLog_(String("Warning: No valid retention time for output scan '") + rt_auto + "' from file '" + filename + "'");
          }

          out.addSpectrum(*it2);
          out.getSpectra().back().setRT(rt_final);
          out.getSpectra().back().setNativeID(native_id);

          if (user_ms_level)
          {
            out.getSpectra().back().setMSLevel((int)getIntOption_("raw:ms_level"));
          }
          ++native_id;
        }

        // if we had only one spectrum, we can annotate it directly, for more spectra, we just name the source file leaving the spectra unannotated (to avoid a long and redundant list of sourceFiles)
        if (in.size() == 1)
        {
          out.getSpectra().back().setSourceFile(in.getSourceFiles()[0]);
          in.getSourceFiles().clear();   // delete source file annotated from source file (its in the spectrum anyways)
        }
        // copy experimental settings from first file
        if (i == 0)
        {
          out.ExperimentalSettings::operator=(in);
        }
        else // otherwise append
        {
          out.getSourceFiles().insert(out.getSourceFiles().end(), in.getSourceFiles().begin(), in.getSourceFiles().end()); // could be emtpty if spectrum was annotated above, but that's ok then
        }

        // also add the chromatograms
        for (std::vector<MSChromatogram<ChromatogramPeak> >::const_iterator it2 = in.getChromatograms().begin(); it2 != in.getChromatograms().end(); ++it2)
        {
          all_chromatograms.push_back(*it2);
        }

      }
      // set the chromatograms
      out.setChromatograms(all_chromatograms);

      //-------------------------------------------------------------
      // writing output
      //-------------------------------------------------------------

      //annotate output with data processing info
      addDataProcessing_(out, getProcessingInfo_(DataProcessing::FORMAT_CONVERSION));

      MzMLFile f;
      f.setLogType(log_type_);
      f.store(out_file, out);

    }

    return EXECUTION_OK;
  }
Beispiel #28
0
int main() {

  stdOut << "\n  Testing WinTools ";
  stdOut << "\n ==================\n";

  SystemError se;
  stdOut << TEXT("\n  Last error code = ") << ::GetLastError();
  stdOut << TEXT("\n  Last error message = ") << se.GetLastMsg();
  stdOut << std::endl;

  std::cout << "\n  testing directory management ";
  std::cout << "\n ------------------------------";

  Directory dir;
  if(dir.DirectoryExists(TEXT("test")))
  {
    std::cout << "\n  Directory test exists";
    if(dir.RemoveDirectory(TEXT("test")))
      std::cout << "\n  successfully removed directory test";
  }
  else
  {
    if(dir.CreateDirectory(TEXT("test")))
      std::cout << "\n  successfully created directory test";
    else
      std::cout << "\n  Directory creation failed";
  }
  stdOut << TEXT("\n  Current directory is: ") << dir.GetCurrentDirectory();
  if(dir.SetCurrentDirectory(TEXT("./test")))
  {
    stdOut << TEXT("\n  changed to: ")  << dir.GetCurrentDirectory();
    dir.SetCurrentDirectory(TEXT(".."));
    stdOut << TEXT("\n  changed back to: ") << dir.GetCurrentDirectory();
  }
  std::cout << std::endl;

  std::vector<stdStr> files = Directory::GetFiles();
  std::cout << "\n  files in this directory are:";
  for(size_t i=0; i<files.size(); ++i)
    stdOut << TEXT("\n    ") << files[i];
  std::cout << std::endl;

  files = Directory::GetFiles(TEXT("*.h*"));
  std::cout << "\n  *.h* files in this directory are:";
  for(size_t i=0; i<files.size(); ++i)
    stdOut << TEXT("\n    ") << files[i];
  std::cout << std::endl;

  std::vector<stdStr> dirs = Directory::GetDirectories();
  std::cout << "\n  directories in this directory are:";
  for(size_t i=0; i<dirs.size(); ++i)
    stdOut << TEXT("\n    ") << dirs[i];
  std::cout << std::endl;

  std::cout << "\n  testing Path management ";
  std::cout << "\n -------------------------";

  stdStr paths[] = { TEXT("aFile"), TEXT("../../aFile"), TEXT("test/aFile"), TEXT("../../") };
  for(int i=0; i<4; ++i)
  {
    stdOut << TEXT("\n  fileSpec: ") << std::setw(12) << paths[i];
    stdOut << TEXT(", name: ") << Path::getName(paths[i]);
    stdOut << TEXT("\n  fileSpec: ") << std::setw(12) << paths[i];
    stdOut << TEXT(", path: ") << Path::getPath(paths[i]);
  }
  std::cout << std::endl;

  std::cout << "\n  testing error messages ";
  std::cout << "\n ------------------------";

  int err = GetLastError();
  std::cout << "\n  Last error code = " << err;

  try {
    se.ThrowString(TEXT("throw message"),Convert::ToStdStr(__FILE__),__LINE__);
  }
  catch(const stdStr &msg)
  { 
    stdOut << TEXT("\n  ") << msg; 
  }
  std::cout << "\n";

  std::cout << "\n  test writing to \"Program Files\" Folder ";
  std::cout << "\n ------------------------------------------";

  stdStr CurrDir = Path::getFullPath(TEXT("."));
  stdStr fileSpec = CurrDir + TEXT("*.*");

  if(Directory::SetCurrentDirectory(TEXT("C:/Program Files")))
  {
    std::cout << "\n  sucessfully set directory to \"C:\\Program Files\"";
    if(Directory::DirectoryExists(TEXT("foobar stuff")))
    {
      std::cout << "\n  \"C:\\Program Files\\foobar stuff\" exists";
      if(!Directory::CopyFiles(fileSpec,TEXT("C:\\Program Files\\foobar stuff")))
        std::cout << "\n  one or more file copy operations failed";
      else
        std::cout << "\n  all file copy operations succeeded";
    }
    else if(Directory::CreateDirectory(TEXT("foobar stuff")))
    {
      std::cout << "\n  successfully created \".\\foobar stuff\"";
      if(!Directory::CopyFiles(fileSpec,TEXT("C:\\Program Files\\foobar stuff")))
        std::cout << "\n  one or more file copy operations failed";
      else
        std::cout << "\n  all file copy operations succeeded";
    }
  }

  std::cout << "\n";
  std::cout << "\n  File file operations: ";
  std::cout << "\n ----------------------";

  stdStr path = TEXT("C:\\temp");
  if(!Directory::SetCurrentDirectory(path))
  {
    stdOut << TEXT("\n\n  invalid path ") << path << TEXT("\n\n");
    return 1;
  }
  std::vector<stdStr> file = Directory::GetFiles();

  // find a fairly large cpp file to read

  stdStr displayFile = TEXT("");
  fileInfo fi;
  size_t fileSize = 0;
  for(size_t i=0; i<file.size(); ++i)
  {
    stdOut << TEXT("\n  ") << file[i];
    if(TEXT("cpp") == Path::getExt(file[i]))
    {
      fi.firstFile(file[i]);
      if(fileSize < fi.size() && fi.size() < 50000)
      {
        fileSize = fi.size();
        displayFile = file[i];
      }
    }
  }

  if(displayFile == TEXT(""))
  {
    stdOut << TEXT("\n  no *.cpp files in ") << path.c_str() << TEXT("\n\n");
    return 1;
  }


  stdOut << "\n\n  Reading Blocks";
  stdOut << "\n ----------------\n";

  if(file.size() > 0)
  {
    FileHandler fh;
    fh.setReadPath(path);
    if(fh.openFileReader(displayFile))
    {
      stdOut << "\n  opening file " << displayFile << "\n\n";
      const size_t size = 1024;
      size_t bytesRead;
      byte_ buffer[size];
      do
      {
        bytesRead = fh.getBlock(buffer,size);
        stdOut << fh.blockToString(buffer,bytesRead);
      } while(bytesRead == size);
    }
    fh.closeFileReader();
  }

  stdOut << "\n\n  Writing Blocks";
  stdOut << "\n ----------------";

  if(file.size() > 0)
  {
    FileHandler fh;
    fh.setReadPath(path);
    fh.setWritePath(path);
    if(!fh.openFileReader(displayFile))
    {
      stdOut << "\n  open " << displayFile << " failed\n\n";
      return 1;
    }
    else
      stdOut << "\n  opening file " << displayFile << " for reading";
    if(fh.openFileWriter(TEXT("test.txt")))
    {
      std::cout << "\n  opening file " << "test.txt" << " for writing";
      const size_t size = 1024;
      size_t bytesRead;
      byte_ buffer[size];
      int count = 0;
      do
      {
        std::cout << "\n    writing block #" << ++count;
        bytesRead = fh.getBlock(buffer,size);
        fh.putBlock(buffer,bytesRead);
      } while(bytesRead == size);
    }
    std::cout << "\n  closing write file";
    fh.closeFileWriter();
    std::cout << "\n  closing read file";
    fh.closeFileReader();
    std::cout << "\n\n";
  }
}
  ExitCodes main_(int, const char**)
  {
    // parsing parameters
    String in(getStringOption_("in"));
    String feature_in(getStringOption_("feature_in"));
    String out(getStringOption_("out"));
    double precursor_mass_tolerance(getDoubleOption_("precursor_mass_tolerance"));

    // reading input
    FileHandler fh;
    FileTypes::Type in_type = fh.getType(in);

    PeakMap exp;
    fh.loadExperiment(in, exp, in_type, log_type_, false, false);
    exp.sortSpectra();

    FeatureMap feature_map;
    if (feature_in != "")
    {
      FeatureXMLFile().load(feature_in, feature_map);
    }

    // calculations
    FeatureFinderAlgorithmIsotopeWavelet iso_ff;
    Param ff_param(iso_ff.getParameters());
    ff_param.setValue("max_charge", getIntOption_("max_charge"));
    ff_param.setValue("intensity_threshold", getDoubleOption_("intensity_threshold"));
    iso_ff.setParameters(ff_param);

    FeatureFinder ff;
    ff.setLogType(ProgressLogger::NONE);

    PeakMap exp2 = exp;
    exp2.clear(false);
    for (PeakMap::ConstIterator it = exp.begin(); it != exp.end(); ++it)
    {
      if (it->size() != 0)
      {
        exp2.addSpectrum(*it);
      }
    }

    exp = exp2;
    exp.updateRanges();

    // TODO check MS2 and MS1 counts
    ProgressLogger progresslogger;
    progresslogger.setLogType(log_type_);
    progresslogger.startProgress(0, exp.size(), "Correcting precursor masses");
    for (PeakMap::Iterator it = exp.begin(); it != exp.end(); ++it)
    {
      progresslogger.setProgress(exp.end() - it);
      if (it->getMSLevel() != 2)
      {
        continue;
      }
      // find first MS1 scan of the MS/MS scan
      PeakMap::Iterator ms1_it = it;
      while (ms1_it != exp.begin() && ms1_it->getMSLevel() != 1)
      {
        --ms1_it;
      }
      if (ms1_it == exp.begin() && ms1_it->getMSLevel() != 1)
      {
        writeLog_("Did not find a MS1 scan to the MS/MS scan at RT=" + String(it->getRT()));
        continue;
      }
      if (ms1_it->size() == 0)
      {
        writeDebug_("No peaks in scan at RT=" + String(ms1_it->getRT()) + String(", skipping"), 1);
        continue;
      }

      PeakMap::Iterator ms2_it = ms1_it;
      ++ms2_it;

      while (ms2_it != exp.end() && ms2_it->getMSLevel() == 2)
      {
        // first: error checks
        if (ms2_it->getPrecursors().empty())
        {
          writeDebug_("Warning: found no precursors of spectrum RT=" + String(ms2_it->getRT()) + ", skipping it.", 1);
          ++ms2_it;
          continue;
        }
        else if (ms2_it->getPrecursors().size() > 1)
        {
          writeLog_("Warning: found more than one precursor of spectrum RT=" + String(ms2_it->getRT()) + ", using first one.");
        }

        Precursor prec = *ms2_it->getPrecursors().begin();
        double prec_pos = prec.getMZ();

        PeakMap new_exp;
        // now excise small region from the MS1 spec for the feature finder (isotope pattern must be covered...)
        PeakSpectrum zoom_spec;
        for (PeakSpectrum::ConstIterator pit = ms1_it->begin(); pit != ms1_it->end(); ++pit)
        {
          if (pit->getMZ() > prec_pos - 3 && pit->getMZ() < prec_pos + 3)
          {
            zoom_spec.push_back(*pit);
          }
        }
        new_exp.addSpectrum(zoom_spec);
        new_exp.updateRanges();
        FeatureMap features, seeds;
        ff.run("isotope_wavelet", new_exp, features, ff_param, seeds);
        if (features.empty())
        {
          writeDebug_("No features found for scan RT=" + String(ms1_it->getRT()), 1);
          ++ms2_it;
          continue;
        }

        double max_int(numeric_limits<double>::min());
        double min_dist(numeric_limits<double>::max());
        Size max_int_feat_idx(0);

        for (Size i = 0; i != features.size(); ++i)
        {
          if (fabs(features[i].getMZ() - prec_pos) < precursor_mass_tolerance &&
              features[i].getIntensity() > max_int)
          {
            max_int_feat_idx = i;
            max_int = features[i].getIntensity();
            min_dist = fabs(features[i].getMZ() - prec_pos);
          }
        }


        writeDebug_(" max_int=" + String(max_int) + " mz=" + String(features[max_int_feat_idx].getMZ()) + " charge=" + String(features[max_int_feat_idx].getCharge()), 5);
        if (min_dist < precursor_mass_tolerance)
        {
          prec.setMZ(features[max_int_feat_idx].getMZ());
          prec.setCharge(features[max_int_feat_idx].getCharge());
          vector<Precursor> precs;
          precs.push_back(prec);
          ms2_it->setPrecursors(precs);
          writeDebug_("Correcting precursor mass of spectrum RT=" + String(ms2_it->getRT()) + " from " + String(prec_pos) + " to " + String(prec.getMZ()) + " (z=" + String(prec.getCharge()) + ")", 1);
        }

        ++ms2_it;
      }
      it = --ms2_it;
    }
    progresslogger.endProgress();

    // writing output
    fh.storeExperiment(out, exp, log_type_);

    return EXECUTION_OK;
  }
Beispiel #30
0
  ExitCodes main_(int, const char**) override
  {
    vector<ProteinIdentification> protein_identifications;

    vector<PeptideIdentification> identifications;
    PeptideIdentification peptide_identification;
    DateTime date_time = DateTime::now();
    String date_time_string = date_time.get();
    peptide_identification.setIdentifier("In-silico_digestion" + date_time_string);

    ProteinIdentification protein_identification;

    protein_identifications.push_back(ProteinIdentification());
    //-------------------------------------------------------------
    // parsing parameters
    //-------------------------------------------------------------
    String inputfile_name = getStringOption_("in");
    String outputfile_name = getStringOption_("out");

    FASTAID FASTA_ID = getStringOption_("FASTA:ID") == "parent" ? PARENT : (getStringOption_("FASTA:ID") == "number" ? NUMBER : BOTH);
    bool keep_FASTA_desc = (getStringOption_("FASTA:description") == "keep");

    // output file type
    FileHandler fh;
    FileTypes::Type out_type = FileTypes::nameToType(getStringOption_("out_type"));

    if (out_type == FileTypes::UNKNOWN)
    {
      out_type = fh.getTypeByFileName(outputfile_name);
      writeDebug_(String("Output file type: ") + FileTypes::typeToName(out_type), 2);
    }

    if (out_type == FileTypes::UNKNOWN)
    {
      LOG_ERROR << ("Error: Could not determine output file type!") << std::endl;
      return PARSE_ERROR;
    }

    Size min_size = getIntOption_("min_length");
    Size max_size = getIntOption_("max_length");
    Size missed_cleavages = getIntOption_("missed_cleavages");


    bool has_FASTA_output = (out_type == FileTypes::FASTA);

    //-------------------------------------------------------------
    // reading input
    //-------------------------------------------------------------
    FASTAFile ff;
    ff.readStart(inputfile_name);
    if (has_FASTA_output) ff.writeStart(outputfile_name);

    //-------------------------------------------------------------
    // calculations
    //-------------------------------------------------------------

    // This should be updated if more cleavage enzymes are available
    ProteinIdentification::SearchParameters search_parameters;
    String enzyme = getStringOption_("enzyme");
    ProteaseDigestion digestor;
    digestor.setEnzyme(enzyme);
    digestor.setMissedCleavages(missed_cleavages);
    search_parameters.digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme(enzyme);

    PeptideHit temp_peptide_hit;
    PeptideEvidence temp_pe;

    protein_identifications[0].setSearchParameters(search_parameters);
    protein_identifications[0].setDateTime(date_time);
    protein_identifications[0].setSearchEngine("In-silico digestion");
    protein_identifications[0].setIdentifier("In-silico_digestion" + date_time_string);

    Size dropped_by_length(0); // stats for removing candidates
    Size fasta_out_count(0);

    FASTAFile::FASTAEntry fe;
    while (ff.readNext(fe))
    {
      if (!has_FASTA_output)
      {
        ProteinHit temp_protein_hit;
        temp_protein_hit.setSequence(fe.sequence);
        temp_protein_hit.setAccession(fe.identifier);
        protein_identifications[0].insertHit(temp_protein_hit);
        temp_pe.setProteinAccession(fe.identifier);
        temp_peptide_hit.setPeptideEvidences(vector<PeptideEvidence>(1, temp_pe));
      }

      vector<AASequence> current_digest;
      if (enzyme == "none")
      {
        current_digest.push_back(AASequence::fromString(fe.sequence));
      }
      else
      {
        dropped_by_length += digestor.digest(AASequence::fromString(fe.sequence), current_digest, min_size, max_size);
      }

      String id = fe.identifier;
      for (auto const& s : current_digest)
      {
        if (!has_FASTA_output)
        {
          temp_peptide_hit.setSequence(s);
          peptide_identification.insertHit(temp_peptide_hit);
          identifications.push_back(peptide_identification);
          peptide_identification.setHits(std::vector<PeptideHit>()); // clear
        }
        else // for FASTA file output
        {
          ++fasta_out_count;
          switch (FASTA_ID)
          {
            case PARENT: break;
            case NUMBER: id = String(fasta_out_count); break;
            case BOTH: id = fe.identifier + "_" + String(fasta_out_count); break;
          }
          ff.writeNext(FASTAFile::FASTAEntry(id, keep_FASTA_desc ? fe.description : "", s.toString()));
        }
      }
    }

    //-------------------------------------------------------------
    // writing output
    //-------------------------------------------------------------

    if (has_FASTA_output)
    {
      ff.writeEnd();
    }
    else
    {
      IdXMLFile().store(outputfile_name,
                        protein_identifications,
                        identifications);
    }

    Size pep_remaining_count = (has_FASTA_output ? fasta_out_count : identifications.size());
    LOG_INFO << "Statistics:\n"
             << "  file:                                    " << inputfile_name << "\n"
             << "  total #peptides after digestion:         " << pep_remaining_count + dropped_by_length << "\n"
             << "  removed #peptides (length restrictions): " << dropped_by_length << "\n"
             << "  remaining #peptides:                     " << pep_remaining_count << std::endl;

    return EXECUTION_OK;
  }