示例#1
0
文件: plot.cpp 项目: skhal/bsm_mc
int main(int argc, char *argv[])
try
{
    // Test if sufficient number of arguments is specified.
    if (2 > argc)
        throw std::invalid_argument(string("usage: ") + argv[0] + " in.root [in.root]");

    Files inputs;

    // open specified input files to the List
    //
    cout << "Inputs" << endl;
    for( int i = 1; argc > i; ++i)
    {
        cout << " [+] " << argv[i] << endl;

        TFilePtr input;
        input.reset(new TFile(argv[i], "READ"));
        if (!input)
        {
            cerr << "Failed to open input: " << argv[i] << endl;

            continue;
        }

        string filename = argv[i];
        boost::to_lower(filename);
        inputs[filename] = input;
    }

    if (inputs.empty())
        cout << "nothing to be done" << endl;
    else
    {
        shared_ptr<TRint> app(new TRint("app", &argc, argv));

        // Process files
        //
        generatePlots(&inputs, "ZprimeKinematics");
        
        app->Run(true);
    }

    cleanup();

    return 0;
}
catch(const exception &error)
{
    cerr << error.what() << endl;

    cleanup();

    return 1;
}
示例#2
0
BOOL ExtractExe( LPCTSTR szExeFilename, LPCTSTR szDestPath, Files &files )
{
	LPCTSTR szFolder = szDestPath;

	LPCTSTR p1=NULL, p2=NULL;
	p1 = _tcsrchr(szExeFilename, _T('/'));
	p2 = _tcsrchr(szExeFilename, _T('\\'));
	if(p1 && p2)
		p1 = max(p1, p2);
	else if(p2)
		p1 = p2;
	if(!p1)
		return FALSE;
	
	CString strParam;
	INT nState = 0;
	if(_tcsstr(p1, _T("2003")))
		nState = 1;
	else if(_tcsstr(p1, _T("2007")))
		nState = 2;
	else
	{
		// 根据文件的属性来获取是否Office  : office-kb981715-fullfile-x86-glb.exe
		CString strFileDescription;
		if( GetPEFileDescription(szExeFilename, strFileDescription) )
		{
			strFileDescription.MakeLower();
			if(_tcsstr(strFileDescription, _T("office"))!=NULL)
			{
				if(_tcsstr(strFileDescription, _T("2003")))
					nState = 1;
				else if(_tcsstr(strFileDescription, _T("2007")))
					nState = 2;
			}
		}
	}
	
	if(nState==1)
		strParam.Format(_T("/Q /C /T:\"%s\""), szDestPath);
	else if(nState==2)
		strParam.Format(_T("/q /extract:\"%s\""), szDestPath);
	else
		return FALSE;

	DWORD dwExitCode = 0;
	if(!ExecuteFile(szExeFilename, strParam, dwExitCode))
		return FALSE;

	RPathHelper_GetMSPFile rp(files);
	RecursePath(szFolder, rp);
	return !files.empty();
}
        bool getDicomFilesInDirectory(const std::string& path, Files& files) const
        {
            osgDB::DirectoryContents contents = osgDB::getDirectoryContents(path);

            std::sort(contents.begin(), contents.end());

            for(osgDB::DirectoryContents::iterator itr = contents.begin();
                itr != contents.end();
                ++itr)
            {
                std::string localFile = path + "/" + *itr;
                info()<<"contents = "<<localFile<<std::endl;
                if (acceptsExtension(osgDB::getLowerCaseFileExtension(localFile)) &&
                    osgDB::fileType(localFile) == osgDB::REGULAR_FILE)
                {
                    files.push_back(localFile);
                }
            }
            
            return !files.empty();
        }
示例#4
0
void DumpFiles( const Files& files, BOOL bOnlyFileName )
{
	if(files.empty())
	{
		_tprintf(_T("Empty Files\r\n"));
	}
	else
	{
		int i=0; 
		for(Files::const_iterator it=files.begin(); it!=files.end(); ++it)
		{
			++i;
			LPCTSTR szFile = *it;
			if(bOnlyFileName)
			{
				LPCTSTR szName = _tcsrchr(szFile, _T('\\'));
				if(szName)
					szFile = ++szName;
			}
			_tprintf(_T("%d/%d %s\r\n"), i, files.size(), szFile);
		}
	}
}
        virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            notice()<<"Reading DICOM file "<<file<<" using DCMTK"<<std::endl;

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
            
            std::string fileName = file;
            if (ext=="dicom")
            {
                fileName = osgDB::getNameLessExtension(file);
            }

            fileName = osgDB::findDataFile( fileName, options );
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            Files files;
            
            osgDB::FileType fileType = osgDB::fileType(fileName);
            if (fileType==osgDB::DIRECTORY)
            {
                getDicomFilesInDirectory(fileName, files);
            }
            else
            {
#if 1
                files.push_back(fileName);
#else                            
                if (!getDicomFilesInDirectory(osgDB::getFilePath(fileName), files))
                {
                    files.push_back(fileName);
                }
#endif            
            }

            if (files.empty())
            {
                return ReadResult::FILE_NOT_FOUND;
            }

            osg::ref_ptr<osg::RefMatrix> matrix = new osg::RefMatrix;
            osg::ref_ptr<osg::Image> image;
            unsigned int imageNum = 0;
            EP_Representation pixelRep = EPR_Uint8;
            int numPlanes = 0;
            GLenum pixelFormat = 0;
            GLenum dataType = 0;
            unsigned int pixelSize = 0;
            
            typedef std::list<FileInfo> FileInfoList;
            FileInfoList fileInfoList;

            typedef std::map<double, FileInfo> DistanceFileInfoMap;
            typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
            OrientationFileInfoMap orientationFileInfoMap;
            
            unsigned int totalNumSlices = 0;

            for(Files::iterator itr = files.begin();
                itr != files.end();
                ++itr)
            {
                DcmFileFormat fileformat;
                OFCondition status = fileformat.loadFile((*itr).c_str());
                if(!status.good()) return ReadResult::ERROR_IN_READING_FILE;
                
                FileInfo fileInfo;
                fileInfo.filename = *itr;

                double pixelSize_y = 1.0;
                double pixelSize_x = 1.0;
                double sliceThickness = 1.0;
                double imagePositionPatient[3] = {0, 0, 0};
                double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 };
                Uint16 numOfSlices = 1;
                
                double value = 0.0;
                if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,0).good())
                {
                    pixelSize_y = value;
                    fileInfo.matrix(1,1) = pixelSize_y;
                }

                if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,1).good())
                {
                    pixelSize_x = value;
                    fileInfo.matrix(0,0) = pixelSize_x;
                }

                // Get slice thickness
                if (fileformat.getDataset()->findAndGetFloat64(DCM_SliceThickness, value).good())
                {
                    sliceThickness = value;
                    notice()<<"sliceThickness = "<<sliceThickness<<std::endl;
                    fileInfo.sliceThickness = sliceThickness;
                }
    
                notice()<<"tagExistsWithValue(DCM_NumberOfFrames)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfFrames)<<std::endl;
                notice()<<"tagExistsWithValue(DCM_NumberOfSlices)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfSlices)<<std::endl;

                Uint32 numFrames;
                if (fileformat.getDataset()->findAndGetUint32(DCM_NumberOfFrames, numFrames).good())
                {
                    fileInfo.numSlices = numFrames;
                    notice()<<"Read number of frames = "<<numFrames<<std::endl;
                }

                
                OFString numFramesStr;
                if (fileformat.getDataset()->findAndGetOFString(DCM_NumberOfFrames, numFramesStr).good())
                {
                    fileInfo.numSlices = atoi(numFramesStr.c_str());
                    notice()<<"Read number of frames = "<<numFramesStr<<std::endl;
                }

                if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfFrames, numOfSlices).good())
                {
                    fileInfo.numSlices = numOfSlices;
                    notice()<<"Read number of frames = "<<numOfSlices<<std::endl;
                }
                
                if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfSlices, numOfSlices).good())
                {
                    fileInfo.numSlices = numOfSlices;
                    notice()<<"Read number of slices = "<<numOfSlices<<std::endl;
                }



                // patient position
                for(int i=0; i<3; ++i)
                {
                    if (fileformat.getDataset()->findAndGetFloat64(DCM_ImagePositionPatient, imagePositionPatient[i],i).good())
                    {
                        notice()<<"Read DCM_ImagePositionPatient["<<i<<"], "<<imagePositionPatient[i]<<std::endl;
                    }
                    else
                    {
                        notice()<<"Have not read DCM_ImagePositionPatient["<<i<<"]"<<std::endl;
                    }
                }
                //notice()<<"imagePositionPatient[2]="<<imagePositionPatient[2]<<std::endl;
                
                fileInfo.matrix.setTrans(imagePositionPatient[0],imagePositionPatient[1],imagePositionPatient[2]);

                for(int i=0; i<6; ++i)
                {
                    double value = 0.0;
                    if (fileformat.getDataset()->findAndGetFloat64(DCM_ImageOrientationPatient, value,i).good())
                    {
                        imageOrientationPatient[i] = value;
                        notice()<<"Read imageOrientationPatient["<<i<<"], "<<imageOrientationPatient[i]<<std::endl;
                    }
                    else
                    {
                        notice()<<"Have not read imageOrientationPatient["<<i<<"]"<<std::endl;
                    }
                }

                osg::Vec3d dirX(imageOrientationPatient[0],imageOrientationPatient[1],imageOrientationPatient[2]);
                osg::Vec3d dirY(imageOrientationPatient[3],imageOrientationPatient[4],imageOrientationPatient[5]);
                osg::Vec3d dirZ = dirX ^ dirY;
                dirZ.normalize();
                
                dirX *= pixelSize_x;
                dirY *= pixelSize_y;
                
                fileInfo.matrix(0,0) = dirX[0];
                fileInfo.matrix(1,0) = dirX[1];
                fileInfo.matrix(2,0) = dirX[2];
                
                fileInfo.matrix(0,1) = dirY[0];
                fileInfo.matrix(1,1) = dirY[1];
                fileInfo.matrix(2,1) = dirY[2];
                
                fileInfo.matrix(0,2) = dirZ[0];
                fileInfo.matrix(1,2) = dirZ[1];
                fileInfo.matrix(2,2) = dirZ[2];
                
                fileInfo.distance = dirZ * (osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix);

                notice()<<"dirX = "<<dirX<<std::endl;
                notice()<<"dirY = "<<dirY<<std::endl;
                notice()<<"dirZ = "<<dirZ<<std::endl;
                notice()<<"matrix = "<<fileInfo.matrix<<std::endl;
                notice()<<"pos = "<<osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix<<std::endl;
                notice()<<"dist = "<<fileInfo.distance<<std::endl;
                notice()<<std::endl;

                (orientationFileInfoMap[dirZ])[fileInfo.distance] = fileInfo;

                totalNumSlices += fileInfo.numSlices;

            }

            if (orientationFileInfoMap.empty()) return 0;
            
            typedef std::map<double, FileInfo> DistanceFileInfoMap;
            typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
            for(OrientationFileInfoMap::iterator itr = orientationFileInfoMap.begin();
                itr != orientationFileInfoMap.end();
                ++itr)
            {
                notice()<<"Orientation = "<<itr->first<<std::endl;
                DistanceFileInfoMap& dfim = itr->second;
                for(DistanceFileInfoMap::iterator ditr = dfim.begin();
                    ditr != dfim.end();
                    ++ditr)
                {
                    FileInfo& fileInfo = ditr->second;
                    notice()<<"   d = "<<fileInfo.distance<<" "<<fileInfo.filename<<std::endl;
                }
            }
            

            DistanceFileInfoMap& dfim = orientationFileInfoMap.begin()->second;
            if (dfim.empty()) return 0;

            double totalDistance = 0.0;
            if (dfim.size()>1)
            {
                totalDistance = fabs(dfim.rbegin()->first - dfim.begin()->first);
            }
            else
            {
                totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices);
            }
            
            notice()<<"Total Distance including ends "<<totalDistance<<std::endl;

            double averageThickness = totalNumSlices<=1 ? 1.0 : totalDistance / double(totalNumSlices-1);
            
            notice()<<"Average thickness "<<averageThickness<<std::endl;

            for(DistanceFileInfoMap::iterator ditr = dfim.begin();
                ditr != dfim.end();
                ++ditr)
            {
                FileInfo& fileInfo = ditr->second;
                
                std::auto_ptr<DicomImage> dcmImage(new DicomImage(fileInfo.filename.c_str()));
                if (dcmImage.get())
                {
                    if (dcmImage->getStatus()==EIS_Normal)
                    {

                        // get the pixel data
                        const DiPixel* pixelData = dcmImage->getInterData();
                        if(!pixelData) 
                        {
                            warning()<<"Error: no data in DicomImage object."<<std::endl;
                            return ReadResult::ERROR_IN_READING_FILE;
                        }
                        
                        osg::ref_ptr<osg::Image> imageAdapter = new osg::Image;
                        
                        EP_Representation curr_pixelRep;
                        int curr_numPlanes;
                        GLenum curr_pixelFormat;
                        GLenum curr_dataType;
                        unsigned int curr_pixelSize;

                        // create the new image
                        convertPixelTypes(pixelData,
                                          curr_pixelRep, curr_numPlanes, 
                                          curr_dataType, curr_pixelFormat, curr_pixelSize);

                        imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(),
                                              curr_pixelFormat,
                                              curr_pixelFormat,
                                              curr_dataType,
                                              (unsigned char*)(pixelData->getData()),
                                              osg::Image::NO_DELETE);
                        if (!image)
                        {
                            pixelRep = curr_pixelRep;
                            numPlanes = curr_numPlanes;
                            dataType = curr_dataType;
                            pixelFormat = curr_pixelFormat;
                            pixelSize = curr_pixelSize;

                            (*matrix)(0,0) = fileInfo.matrix(0,0);
                            (*matrix)(1,0) = fileInfo.matrix(1,0);
                            (*matrix)(2,0) = fileInfo.matrix(2,0);
                            (*matrix)(0,1) = fileInfo.matrix(0,1);
                            (*matrix)(1,1) = fileInfo.matrix(1,1);
                            (*matrix)(2,1) = fileInfo.matrix(2,1);
                            (*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness;
                            (*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness;
                            (*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness;
                            

                            
                            image = new osg::Image;
                            image->setUserData(matrix.get());
                            image->setFileName(fileName.c_str());
                            image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, 
                                                 pixelFormat, dataType);
                                                 
                                                 
                            matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));

                            notice()<<"Image dimensions = "<<image->s()<<", "<<image->t()<<", "<<image->r()<<" pixelFormat=0x"<<std::hex<<pixelFormat<<" dataType=0x"<<std::hex<<dataType<<std::dec<<std::endl;
                        }
                        else if (pixelData->getPlanes()>numPlanes ||
                                 pixelData->getRepresentation()>pixelRep)
                        {
                            notice()<<"Need to reallocated "<<image->s()<<", "<<image->t()<<", "<<image->r()<<std::endl;
                            
                            // record the previous image settings to use when we copy back the content.
                            osg::ref_ptr<osg::Image> previous_image = image;

                            // create the new image
                            convertPixelTypes(pixelData,
                                              pixelRep, numPlanes, 
                                              dataType, pixelFormat, pixelSize);
                                              
                            image = new osg::Image;
                            image->setUserData(previous_image->getUserData());
                            image->setFileName(fileName.c_str());
                            image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, 
                                                 pixelFormat, dataType);
                                                 
                            osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum,
                                           image.get(), 0, 0, 0,                                                 
                                           false);
                            
                        }
                        
                        osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(), 
                                       image.get(), 0, 0, imageNum,
                                       false);
                                             
                        imageNum += dcmImage->getFrameCount();
                    }
                    else
                    {
                        warning()<<"Error in reading dicom file "<<fileName.c_str()<<", error = "<<DicomImage::getString(dcmImage->getStatus())<<std::endl;
                    }
                }
            }
            
            if (!image)
            {
                return ReadResult::ERROR_IN_READING_FILE;
            }

            notice()<<"Spacing = "<<*matrix<<std::endl;
            
            return image.get();
        }
    void load()
    {
        //osg::notify(osg::NOTICE)<<"void load(Object)"<<std::endl;
        Files filesA;
        Files filesB;

        readMasterFile(filesB);
        // osg::notify(osg::NOTICE)<<"First read "<<filesA.size()<<std::endl;

        // itererate until the master file is stable
        do
        {
            OpenThreads::Thread::microSleep(100000);

            filesB.swap(filesA);
            filesB.clear();
            readMasterFile(filesB);

            // osg::notify(osg::NOTICE)<<"second read "<<filesB.size()<<std::endl;

        } while (filesA!=filesB);

        Files files;
        files.swap(filesB);

        // osg::notify(osg::NOTICE)<<"Now equal "<<files.size()<<std::endl;


        Files newFiles;
        Files removedFiles;

        // find out which files are new, and which ones have been removed.
        {
            OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

            for(Files::iterator fitr = files.begin();
                fitr != files.end();
                ++fitr)
            {
                if (_existingFilenameNodeMap.count(*fitr)==0) newFiles.insert(*fitr);
            }

            for(FilenameNodeMap::iterator litr = _existingFilenameNodeMap.begin();
                litr != _existingFilenameNodeMap.end();
                ++litr)
            {
                if (files.count(litr->first)==0)
                {
                    removedFiles.insert(litr->first);
                }
            }
        }

#if 0
        if (!newFiles.empty() || !removedFiles.empty())
        {
            osg::notify(osg::NOTICE)<<std::endl<<std::endl<<"void operator () files.size()="<<files.size()<<std::endl;
        }
#endif

        // first load the new files.
        FilenameNodeMap nodesToAdd;
        if (!newFiles.empty())
        {

            typedef std::vector< osg::ref_ptr<osg::GraphicsThread> > GraphicsThreads;
            GraphicsThreads threads;

            for(unsigned int i=0; i<= osg::GraphicsContext::getMaxContextID(); ++i)
            {
                osg::GraphicsContext* gc = osg::GraphicsContext::getCompileContext(i);
                osg::GraphicsThread* gt = gc ? gc->getGraphicsThread() : 0;
                if (gt) threads.push_back(gt);
            }

            if (_operationQueue.valid())
            {
                // osg::notify(osg::NOTICE)<<"Using OperationQueue"<<std::endl;

                _endOfLoadBlock = new osg::RefBlockCount(newFiles.size());

                _endOfLoadBlock->reset();

                typedef std::list< osg::ref_ptr<LoadAndCompileOperation> > LoadAndCompileList;
                LoadAndCompileList loadAndCompileList;

                for(Files::iterator nitr = newFiles.begin();
                    nitr != newFiles.end();
                    ++nitr)
                {
                    // osg::notify(osg::NOTICE)<<"Adding LoadAndCompileOperation "<<*nitr<<std::endl;

                    osg::ref_ptr<LoadAndCompileOperation> loadAndCompile = new LoadAndCompileOperation( *nitr, _incrementalCompileOperation.get(), _endOfLoadBlock.get() );
                    loadAndCompileList.push_back(loadAndCompile);
                    _operationQueue->add( loadAndCompile.get() );
                }

#if 1
                osg::ref_ptr<osg::Operation> operation;
                while ((operation=_operationQueue->getNextOperation()).valid())
                {
                    // osg::notify(osg::NOTICE)<<"Local running of operation"<<std::endl;
                    (*operation)(0);
                }
#endif
                // osg::notify(osg::NOTICE)<<"Waiting for completion of LoadAndCompile operations"<<std::endl;
                _endOfLoadBlock->block();
                // osg::notify(osg::NOTICE)<<"done ... Waiting for completion of LoadAndCompile operations"<<std::endl;

                for(LoadAndCompileList::iterator litr = loadAndCompileList.begin();
                    litr != loadAndCompileList.end();
                    ++litr)
                {
                    if ((*litr)->_loadedModel.valid())
                    {
                        nodesToAdd[(*litr)->_filename] = (*litr)->_loadedModel;
                    }
                }

            }

            else
            {

                _endOfLoadBlock = new osg::RefBlockCount(newFiles.size());

                _endOfLoadBlock->reset();

                for(Files::iterator nitr = newFiles.begin();
                    nitr != newFiles.end();
                    ++nitr)
                {
                    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFile(*nitr);

                    if (loadedModel.get())
                    {
                        nodesToAdd[*nitr] = loadedModel;

                        if (_incrementalCompileOperation.valid())
                        {
                            osg::ref_ptr<osgUtil::IncrementalCompileOperation::CompileSet> compileSet =
                                new osgUtil::IncrementalCompileOperation::CompileSet(loadedModel.get());

                            compileSet->_compileCompletedCallback = new ReleaseBlockOnCompileCompleted(_endOfLoadBlock.get());

                            _incrementalCompileOperation->add(compileSet.get());
                        }
                        else
                        {
                            _endOfLoadBlock->completed();
                        }
                    }
                    else
                    {
                        _endOfLoadBlock->completed();
                    }
                }

                _endOfLoadBlock->block();

            }

        }

        bool requiresBlock = false;

        // pass the locally peppared data to MasterOperations shared data
        // so that updated thread can merge these changes with the main scene
        // graph.  This merge is carried out via the update(..) method.
        if (!removedFiles.empty() || !nodesToAdd.empty())
        {
            OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
            _nodesToRemove.swap(removedFiles);
            _nodesToAdd.swap(nodesToAdd);
            requiresBlock = true;
        }

        // now block so we don't try to load anything till the new data has been merged
        // otherwise _existingFilenameNodeMap will get out of sync.
        if (requiresBlock)
        {
            _updatesMergedBlock.block();
        }
        else
        {
            OpenThreads::Thread::YieldCurrentThread();
        }

    }