diff --git a/CMake/BuildConfigurations/DiffusionAll.cmake b/CMake/BuildConfigurations/DiffusionAll.cmake index 424855e336..22fd3320ec 100644 --- a/CMake/BuildConfigurations/DiffusionAll.cmake +++ b/CMake/BuildConfigurations/DiffusionAll.cmake @@ -1,37 +1,39 @@ message(STATUS "Configuring MITK Diffusion with all Plugins") # Enable non-optional external dependencies set(MITK_USE_Vigra ON CACHE BOOL "MITK Use Vigra Library" FORCE) set(MITK_USE_HDF5 ON CACHE BOOL "MITK Use HDF5 Library" FORCE) set(MITK_USE_MatchPoint ON CACHE BOOL "" FORCE) set(MITK_USE_DCMTK ON CACHE BOOL "" FORCE) -#set(MITK_USE_DCMQI ON CACHE BOOL "" FORCE) +set(MITK_USE_DCMQI OFF CACHE BOOL "" FORCE) +set(MITK_USE_PCRE ON CACHE BOOL "" FORCE) +set(MITK_USE_SWIG ON CACHE BOOL "" FORCE) set(MITK_USE_Python ON CACHE BOOL "" FORCE) set(MITK_USE_BetData ON CACHE BOOL "" FORCE) # Disable all apps but MITK Diffusion set(MITK_BUILD_ALL_APPS OFF CACHE BOOL "Build all MITK applications" FORCE) set(MITK_BUILD_APP_CoreApp OFF CACHE BOOL "Build the MITK CoreApp" FORCE) set(MITK_BUILD_APP_Diffusion ON CACHE BOOL "Build MITK Diffusion" FORCE) # Activate Diffusion Mini Apps set(BUILD_DiffusionCoreCmdApps ON CACHE BOOL "Build commandline tools for diffusion" FORCE) set(BUILD_DiffusionFiberProcessingCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber processing" FORCE) set(BUILD_DiffusionFiberfoxCmdApps ON CACHE BOOL "Build commandline tools for diffusion data simulation (Fiberfox)" FORCE) set(BUILD_DiffusionMiscCmdApps ON CACHE BOOL "Build miscellaneous commandline tools for diffusion" FORCE) set(BUILD_DiffusionQuantificationCmdApps ON CACHE BOOL "Build commandline tools for diffusion quantification (IVIM, ADC, ...)" FORCE) set(BUILD_DiffusionTractographyCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography" FORCE) set(BUILD_DiffusionTractographyEvaluationCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography evaluation" FORCE) set(BUILD_DiffusionConnectomicsCmdApps ON CACHE BOOL "Build commandline tools for diffusion connectomics" FORCE) # Build neither all plugins nor examples set(MITK_BUILD_ALL_PLUGINS OFF CACHE BOOL "Build all MITK plugins" FORCE) set(MITK_BUILD_EXAMPLES OFF CACHE BOOL "Build the MITK examples" FORCE) set(BUILD_TESTING ON CACHE BOOL "Build the MITK tests" FORCE) # Activate in-application help generation set(MITK_DOXYGEN_GENERATE_QCH_FILES ON CACHE BOOL "Use doxygen to generate Qt compressed help files for MITK docs" FORCE) set(BLUEBERRY_USE_QT_HELP ON CACHE BOOL "Enable support for integrating bundle documentation into Qt Help" FORCE) # Disable console window set(MITK_SHOW_CONSOLE_WINDOW ON CACHE BOOL "Use this to enable or disable the console window when starting MITK GUI Applications" FORCE) diff --git a/CMake/BuildConfigurations/DiffusionRelease.cmake b/CMake/BuildConfigurations/DiffusionRelease.cmake index 15f61d065d..ef55857c2a 100644 --- a/CMake/BuildConfigurations/DiffusionRelease.cmake +++ b/CMake/BuildConfigurations/DiffusionRelease.cmake @@ -1,40 +1,42 @@ message(STATUS "Configuring MITK Diffusion Release Build") # Enable non-optional external dependencies set(MITK_USE_Vigra ON CACHE BOOL "MITK Use Vigra Library" FORCE) set(MITK_USE_HDF5 ON CACHE BOOL "MITK Use HDF5 Library" FORCE) set(MITK_USE_MatchPoint ON CACHE BOOL "" FORCE) set(MITK_USE_DCMTK ON CACHE BOOL "" FORCE) -set(MITK_USE_DCMQI ON CACHE BOOL "" FORCE) +set(MITK_USE_DCMQI OFF CACHE BOOL "" FORCE) +set(MITK_USE_PCRE ON CACHE BOOL "" FORCE) +set(MITK_USE_SWIG ON CACHE BOOL "" FORCE) set(MITK_USE_Python ON CACHE BOOL "" FORCE) set(MITK_USE_BetData ON CACHE BOOL "" FORCE) # Disable all apps but MITK Diffusion set(MITK_BUILD_ALL_APPS OFF CACHE BOOL "Build all MITK applications" FORCE) set(MITK_BUILD_APP_CoreApp OFF CACHE BOOL "Build the MITK CoreApp" FORCE) set(MITK_BUILD_APP_Workbench OFF CACHE BOOL "Build the MITK Workbench" FORCE) set(MITK_BUILD_APP_Diffusion ON CACHE BOOL "Build MITK Diffusion" FORCE) # Activate Diffusion Mini Apps -set(BUILD_DiffusionCoreCmdApps OFF CACHE BOOL "Build commandline tools for diffusion" FORCE) +set(BUILD_DiffusionCoreCmdApps ON CACHE BOOL "Build commandline tools for diffusion" FORCE) set(BUILD_DiffusionFiberProcessingCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber processing" FORCE) set(BUILD_DiffusionFiberfoxCmdApps ON CACHE BOOL "Build commandline tools for diffusion data simulation (Fiberfox)" FORCE) -set(BUILD_DiffusionMiscCmdApps OFF CACHE BOOL "Build miscellaneous commandline tools for diffusion" FORCE) +set(BUILD_DiffusionMiscCmdApps ON CACHE BOOL "Build miscellaneous commandline tools for diffusion" FORCE) set(BUILD_DiffusionQuantificationCmdApps OFF CACHE BOOL "Build commandline tools for diffusion quantification (IVIM, ADC, ...)" FORCE) set(BUILD_DiffusionTractographyCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography" FORCE) -set(BUILD_DiffusionTractographyEvaluationCmdApps OFF CACHE BOOL "Build commandline tools for diffusion fiber tractography evaluation" FORCE) +set(BUILD_DiffusionTractographyEvaluationCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography evaluation" FORCE) set(BUILD_DiffusionConnectomicsCmdApps ON CACHE BOOL "Build commandline tools for diffusion connectomics" FORCE) # Build neither all plugins nor examples set(MITK_BUILD_ALL_PLUGINS OFF CACHE BOOL "Build all MITK plugins" FORCE) set(MITK_BUILD_EXAMPLES OFF CACHE BOOL "Build the MITK examples" FORCE) set(BUILD_TESTING OFF CACHE BOOL "Build the MITK tests" FORCE) # Activate in-application help generation set(MITK_DOXYGEN_GENERATE_QCH_FILES ON CACHE BOOL "Use doxygen to generate Qt compressed help files for MITK docs" FORCE) set(BLUEBERRY_USE_QT_HELP ON CACHE BOOL "Enable support for integrating bundle documentation into Qt Help" FORCE) # Enable console window set(MITK_SHOW_CONSOLE_WINDOW ON CACHE BOOL "Use this to enable or disable the console window when starting MITK GUI Applications" FORCE) set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE) diff --git a/CMakeExternals/BetData.cmake b/CMakeExternals/BetData.cmake index 8771e56b40..f511435b0e 100644 --- a/CMakeExternals/BetData.cmake +++ b/CMakeExternals/BetData.cmake @@ -1,38 +1,37 @@ #----------------------------------------------------------------------------- # Brain Extraction Data #----------------------------------------------------------------------------- if(MITK_USE_BetData) # Sanity checks if(DEFINED BetData_DIR AND NOT EXISTS ${BetData_DIR}) message(FATAL_ERROR "BetData_DIR variable is defined but corresponds to non-existing directory") endif() set(proj BetData) set(proj_DEPENDENCIES) set(BetData_DEPENDS ${proj}) if(NOT DEFINED BetData_DIR) set(BetData_DIR ${ep_prefix}/src/${proj}/) ExternalProject_Add(${proj} - URL http://mitk.org/download/data/MITK-BET-20180706.tar.gz + URL http://mitk.org/download/data/MITK-BET-20180711.tar.gz UPDATE_COMMAND "" CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" -# INSTALL_COMMAND ${CMAKE_COMMAND} -E copy_directory ${BetData_DIR} ${ep_prefix}/bin/ DEPENDS ${proj_DEPENDENCIES} ) configure_file(${CMAKE_CURRENT_LIST_DIR}/${proj}.h.in ${CMAKE_BINARY_DIR}/${proj}.h) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/BetData.h.in b/CMakeExternals/BetData.h.in index ba3fe5867e..0287b03917 100644 --- a/CMakeExternals/BetData.h.in +++ b/CMakeExternals/BetData.h.in @@ -1,30 +1,31 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BetData_h #define BetData_h -#define BetData_DIR "@BetData_DIR@" +//#define BetData_DIR "@BetData_DIR@" namespace mitk { namespace bet { -std::vector< std::string > search_dirs = {"/","/bin/","/BetData/","/bin/BetData/"}; +std::vector< std::string > relative_search_dirs = {"/","/bin/","/BetData/","/bin/BetData/"}; +std::vector< std::string > absolute_search_dirs = {"@BetData_DIR@"}; } } #endif diff --git a/Modules/Python/autoload/PythonService/mitkPythonService.cpp b/Modules/Python/autoload/PythonService/mitkPythonService.cpp index 2bc412b143..5ae320d5e1 100644 --- a/Modules/Python/autoload/PythonService/mitkPythonService.cpp +++ b/Modules/Python/autoload/PythonService/mitkPythonService.cpp @@ -1,955 +1,966 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPythonService.h" #include #include #include #include #include #include "PythonPath.h" #include #include #include #include #include #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include #include #ifndef WIN32 #include #endif const QString mitk::PythonService::m_TmpDataFileName("temp_mitk_data_file"); #ifdef USE_MITK_BUILTIN_PYTHON static char* pHome = nullptr; #endif mitk::PythonService::PythonService() : m_ItkWrappingAvailable( true ), m_OpenCVWrappingAvailable( true ), m_VtkWrappingAvailable( true ), m_ErrorOccured( false ) { { MITK_DEBUG << "will init python if necessary"; } bool pythonInitialized = static_cast( Py_IsInitialized() ); //m_PythonManager.isPythonInitialized() ); { MITK_DEBUG << "pythonInitialized " << pythonInitialized; MITK_DEBUG << "m_PythonManager.isPythonInitialized() " << m_PythonManager.isPythonInitialized(); } // due to strange static var behaviour on windows Py_IsInitialized() returns correct value while // m_PythonManager.isPythonInitialized() does not because it has been constructed and destructed again if( !m_PythonManager.isPythonInitialized() ) { try { //TODO a better way to do this #ifndef WIN32 dlerror(); if(dlopen(PYTHON_LIBRARY, RTLD_NOW | RTLD_GLOBAL) == 0 ) { mitkThrow() << "Python runtime could not be loaded: " << dlerror(); } #endif std::string programPath = mitk::IOUtil::GetProgramPath(); QDir programmDir( QString( programPath.c_str() ).append("/Python") ); QString pythonCommand; // TODO: Check this in the modernization branch with an installer // Set the pythonpath variable depending if // we have an installer or development environment if ( programmDir.exists() ) { // runtime directory used in installers pythonCommand.append( QString("import site, sys\n") ); pythonCommand.append( QString("sys.path.append('')\n") ); pythonCommand.append( QString("sys.path.append('%1')\n").arg(programPath.c_str()) ); pythonCommand.append( QString("sys.path.append('%1/Python')").arg(programPath.c_str()) ); // development } else { pythonCommand.append( QString("import site, sys\n") ); pythonCommand.append( QString("sys.path.append('')\n") ); pythonCommand.append( QString("sys.path.append('%1')\n").arg(EXTERNAL_DIST_PACKAGES) ); pythonCommand.append( QString("\nsite.addsitedir('%1')").arg(EXTERNAL_SITE_PACKAGES) ); } if( pythonInitialized ) m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut|PythonQt::PythonAlreadyInitialized); else m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut); // set python home if own runtime is used #ifdef USE_MITK_BUILTIN_PYTHON QString pythonHome; if ( programmDir.exists() ) pythonHome.append(QString("%1/Python").arg(programPath.c_str())); else pythonHome.append(PYTHONHOME); if(pHome) delete[] pHome; pHome = new char[pythonHome.toStdString().length() + 1]; strcpy(pHome,pythonHome.toStdString().c_str()); Py_SetPythonHome(pHome); MITK_DEBUG("PythonService") << "PythonHome: " << pHome; #endif MITK_DEBUG("PythonService") << "initalizing python"; m_PythonManager.initialize(); #ifdef USE_MITK_BUILTIN_PYTHON PyObject* dict = PyDict_New(); // Import builtin modules if (PyDict_GetItemString(dict, "__builtins__") == nullptr) { PyObject* builtinMod = PyImport_ImportModule("__builtin__"); if (builtinMod == nullptr || PyDict_SetItemString(dict, "__builtins__", builtinMod) != 0) { Py_DECREF(dict); Py_XDECREF(dict); return; } Py_DECREF(builtinMod); } #endif MITK_DEBUG("PythonService")<< "Python Search paths: " << Py_GetPath(); MITK_DEBUG("PythonService") << "python initalized"; //MITK_DEBUG("PythonService") << "registering python paths" << PYTHONPATH_COMMAND; m_PythonManager.executeString( pythonCommand, ctkAbstractPythonManager::FileInput ); } catch (...) { MITK_DEBUG("PythonService") << "exception initalizing python"; } } } mitk::PythonService::~PythonService() { MITK_DEBUG("mitk::PythonService") << "destructing PythonService"; #ifdef USE_MITK_BUILTIN_PYTHON if(pHome) delete[] pHome; #endif } std::string mitk::PythonService::Execute(const std::string &stdpythonCommand, int commandType) { QString pythonCommand = QString::fromStdString(stdpythonCommand); { MITK_DEBUG("mitk::PythonService") << "pythonCommand = " << pythonCommand.toStdString(); MITK_DEBUG("mitk::PythonService") << "commandType = " << commandType; } QVariant result; bool commandIssued = true; if(commandType == IPythonService::SINGLE_LINE_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::SingleInput ); else if(commandType == IPythonService::MULTI_LINE_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::FileInput ); else if(commandType == IPythonService::EVAL_COMMAND ) result = m_PythonManager.executeString(pythonCommand, ctkAbstractPythonManager::EvalInput ); else commandIssued = false; if(commandIssued) { this->NotifyObserver(pythonCommand.toStdString()); m_ErrorOccured = PythonQt::self()->hadError(); } return result.toString().toStdString(); } void mitk::PythonService::ExecuteScript( const std::string& pythonScript ) { std::ifstream t(pythonScript.c_str()); std::string str((std::istreambuf_iterator(t)), std::istreambuf_iterator()); + t.close(); m_PythonManager.executeString(QString::fromStdString(str)); } std::vector mitk::PythonService::GetVariableStack() const { std::vector list; PyObject* dict = PyImport_GetModuleDict(); PyObject* object = PyDict_GetItemString(dict, "__main__"); PyObject* dirMain = PyObject_Dir(object); PyObject* tempObject = 0; //PyObject* strTempObject = 0; if(dirMain) { std::string name, attrValue, attrType; for(int i = 0; iob_type->tp_name; - //disabled due to strange errors, see T24085 - //strTempObject = PyObject_Repr(tempObject); - //if(strTempObject && ( PyUnicode_Check(strTempObject) || PyString_Check(strTempObject) ) ) - // attrValue = PyString_AsString(strTempObject); - //else - // attrValue = ""; + if(tempObject && ( PyUnicode_Check(tempObject) || PyString_Check(tempObject) ) ) + attrValue = PyString_AsString(tempObject); + else + attrValue = ""; mitk::PythonVariable var; var.m_Name = name; - //var.m_Value = attrValue; + var.m_Value = attrValue; var.m_Type = attrType; list.push_back(var); } } return list; } +std::string mitk::PythonService::GetVariable(const std::string& name) const +{ + std::vector allVars = this->GetVariableStack(); + for(unsigned int i = 0; i< allVars.size(); i++) + { + if( allVars.at(i).m_Name == name ) + return allVars.at(i).m_Value; + } + + return ""; +} + bool mitk::PythonService::DoesVariableExist(const std::string& name) const { bool varExists = false; std::vector allVars = this->GetVariableStack(); for(unsigned int i = 0; i< allVars.size(); i++) { if( allVars.at(i).m_Name == name ) { varExists = true; break; } } return varExists; } void mitk::PythonService::AddPythonCommandObserver(mitk::PythonCommandObserver *observer) { if(!m_Observer.contains(observer)) m_Observer.append(observer); } void mitk::PythonService::RemovePythonCommandObserver(mitk::PythonCommandObserver *observer) { m_Observer.removeOne(observer); } void mitk::PythonService::NotifyObserver(const std::string &command) { MITK_DEBUG("mitk::PythonService") << "number of observer " << m_Observer.size(); for( int i=0; i< m_Observer.size(); ++i ) { m_Observer.at(i)->CommandExecuted(command); } } QString mitk::PythonService::GetTempDataFileName(const std::string& ext) const { QString tmpFolder = QDir::tempPath(); QString fileName = tmpFolder + QDir::separator() + m_TmpDataFileName + QString::fromStdString(ext); return fileName; } bool mitk::PythonService::CopyToPythonAsSimpleItkImage(mitk::Image *image, const std::string &stdvarName) { QString varName = QString::fromStdString( stdvarName ); QString command; unsigned int* imgDim = image->GetDimensions(); int npy_nd = 1; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionary PyObject *pyDict = PyModule_GetDict(pyMod); const mitk::Vector3D spacing = image->GetGeometry()->GetSpacing(); const mitk::Point3D origin = image->GetGeometry()->GetOrigin(); mitk::PixelType pixelType = image->GetPixelType(); itk::ImageIOBase::IOPixelType ioPixelType = image->GetPixelType().GetPixelType(); PyObject* npyArray = nullptr; mitk::ImageReadAccessor racc(image); void* array = (void*) racc.GetData(); mitk::Vector3D xDirection; mitk::Vector3D yDirection; mitk::Vector3D zDirection; const vnl_matrix_fixed &transform = image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::Vector3D s = image->GetGeometry()->GetSpacing(); // ToDo: Check if this is a collumn or row vector from the matrix. // right now it works but not sure for rotated geometries mitk::FillVector3D(xDirection, transform[0][0]/s[0], transform[0][1]/s[1], transform[0][2]/s[2]); mitk::FillVector3D(yDirection, transform[1][0]/s[0], transform[1][1]/s[1], transform[1][2]/s[2]); mitk::FillVector3D(zDirection, transform[2][0]/s[0], transform[2][1]/s[1], transform[2][2]/s[2]); // save the total number of elements here (since the numpy array is one dimensional) npy_intp* npy_dims = new npy_intp[1]; npy_dims[0] = imgDim[0]; /** * Build a string in the format [1024,1028,1] * to describe the dimensionality. This is needed for simple itk * to know the dimensions of the image */ QString dimensionString; dimensionString.append(QString("[")); dimensionString.append(QString::number(imgDim[0])); for (unsigned i = 1; i < 3; ++i) // always three because otherwise the 3d-geometry gets destroyed // (relevant for backtransformation of simple itk image to mitk. { dimensionString.append(QString(",")); dimensionString.append(QString::number(imgDim[i])); npy_dims[0] *= imgDim[i]; } dimensionString.append("]"); // the next line is necessary for vectorimages npy_dims[0] *= pixelType.GetNumberOfComponents(); // default pixeltype: unsigned short NPY_TYPES npy_type = NPY_USHORT; std::string sitk_type = "sitkUInt8"; if( ioPixelType == itk::ImageIOBase::SCALAR ) { if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; sitk_type = "sitkFloat64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; sitk_type = "sitkFloat32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; sitk_type = "sitkInt16"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; sitk_type = "sitkInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; sitk_type = "sitkInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; sitk_type = "sitkInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; sitk_type = "sitkUInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; sitk_type = "sitkUInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; sitk_type = "sitkUInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; sitk_type = "sitkUInt16"; } } else if ( ioPixelType == itk::ImageIOBase::VECTOR || ioPixelType == itk::ImageIOBase::RGB || ioPixelType == itk::ImageIOBase::RGBA ) { if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; sitk_type = "sitkVectorFloat64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; sitk_type = "sitkVectorFloat32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; sitk_type = "sitkVectorInt16"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; sitk_type = "sitkVectorInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; sitk_type = "sitkVectorInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; sitk_type = "sitkVectorInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; sitk_type = "sitkVectorUInt8"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; sitk_type = "sitkVectorUInt32"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; sitk_type = "sitkVectorUInt64"; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; sitk_type = "sitkVectorUInt16"; } } else { MITK_WARN << "not a recognized pixeltype"; return false; } // creating numpy array import_array1 (true); npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); // add temp array it to the python dictionary to access it in python code const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") .arg(varName).toStdString().c_str(), npyArray ); // sanity check if ( status != 0 ) return false; command.append( QString("%1 = sitk.Image(%2,sitk.%3,%4)\n").arg(varName) .arg(dimensionString) .arg(QString(sitk_type.c_str())).arg(QString::number(pixelType.GetNumberOfComponents())) ); command.append( QString("%1.SetSpacing([%2,%3,%4])\n").arg(varName) .arg(QString::number(spacing[0])) .arg(QString::number(spacing[1])) .arg(QString::number(spacing[2])) ); command.append( QString("%1.SetOrigin([%2,%3,%4])\n").arg(varName) .arg(QString::number(origin[0])) .arg(QString::number(origin[1])) .arg(QString::number(origin[2])) ); command.append( QString("%1.SetDirection([%2,%3,%4,%5,%6,%7,%8,%9,%10])\n").arg(varName) .arg(QString::number(xDirection[0])) .arg(QString::number(xDirection[1])) .arg(QString::number(xDirection[2])) .arg(QString::number(yDirection[0])) .arg(QString::number(yDirection[1])) .arg(QString::number(yDirection[2])) .arg(QString::number(zDirection[0])) .arg(QString::number(zDirection[1])) .arg(QString::number(zDirection[2])) ); // directly access the cpp api from the lib command.append( QString("_SimpleITK._SetImageFromArray(%1_numpy_array,%1)\n").arg(varName) ); command.append( QString("del %1_numpy_array").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; } mitk::PixelType DeterminePixelType(const std::string& pythonPixeltype, int nrComponents, int dimensions) { typedef itk::RGBPixel< unsigned char > UCRGBPixelType; typedef itk::RGBPixel< unsigned short > USRGBPixelType; typedef itk::RGBPixel< float > FloatRGBPixelType; typedef itk::RGBPixel< double > DoubleRGBPixelType; typedef itk::Image< UCRGBPixelType > UCRGBImageType; typedef itk::Image< USRGBPixelType > USRGBImageType; typedef itk::Image< FloatRGBPixelType > FloatRGBImageType; typedef itk::Image< DoubleRGBPixelType > DoubleRGBImageType; typedef itk::RGBAPixel< unsigned char > UCRGBAPixelType; typedef itk::RGBAPixel< unsigned short > USRGBAPixelType; typedef itk::RGBAPixel< float > FloatRGBAPixelType; typedef itk::RGBAPixel< double > DoubleRGBAPixelType; typedef itk::Image< UCRGBAPixelType > UCRGBAImageType; typedef itk::Image< USRGBAPixelType > USRGBAImageType; typedef itk::Image< FloatRGBAPixelType > FloatRGBAImageType; typedef itk::Image< DoubleRGBAPixelType > DoubleRGBAImageType; mitk::PixelType pixelType = mitk::MakePixelType(nrComponents); if (nrComponents == 1) { if( pythonPixeltype.compare("float64") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("float32") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("int16") == 0) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("int8") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("int32") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("int64") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("uint8") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("uint32") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("uint64") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else if( pythonPixeltype.compare("uint16") == 0 ) { pixelType = mitk::MakePixelType(nrComponents); } else { mitkThrow()<< "unknown scalar PixelType"; } } else if(nrComponents == 3 && dimensions == 2) { if( pythonPixeltype.compare("float64") == 0 ) { pixelType = mitk::MakePixelType(); } else if( pythonPixeltype.compare("float32") == 0 ) { pixelType = mitk::MakePixelType(); } else if( pythonPixeltype.compare("uint8") == 0 ) { pixelType = mitk::MakePixelType(); } else if( pythonPixeltype.compare("uint16") == 0 ) { pixelType = mitk::MakePixelType(); } } else if( (nrComponents == 4) && dimensions == 2 ) { if( pythonPixeltype.compare("float64") == 0 ) { pixelType = mitk::MakePixelType(); } else if( pythonPixeltype.compare("float32") == 0 ) { pixelType = mitk::MakePixelType(); } else if( pythonPixeltype.compare("uint8") == 0 ) { pixelType = mitk::MakePixelType(); } else if( pythonPixeltype.compare("uint16") == 0 ) { pixelType = mitk::MakePixelType(); } } else { if( pythonPixeltype.compare("float64") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("float32") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("int16") == 0) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("int8") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("int32") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("int64") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("uint8") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("uint16") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("uint32") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else if( pythonPixeltype.compare("uint64") == 0 ) { pixelType = mitk::MakePixelType >(nrComponents); } else { mitkThrow()<< "unknown vectorial PixelType"; } } return pixelType; } mitk::Image::Pointer mitk::PythonService::CopySimpleItkImageFromPython(const std::string &stdvarName) { double*ds = nullptr; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionarry PyObject *pyDict = PyModule_GetDict(pyMod); mitk::Image::Pointer mitkImage = mitk::Image::New(); mitk::Vector3D spacing; mitk::Point3D origin; QString command; QString varName = QString::fromStdString( stdvarName ); command.append( QString("%1_numpy_array = sitk.GetArrayFromImage(%1)\n").arg(varName) ); command.append( QString("%1_spacing = numpy.asarray(%1.GetSpacing())\n").arg(varName) ); command.append( QString("%1_origin = numpy.asarray(%1.GetOrigin())\n").arg(varName) ); command.append( QString("%1_dtype = %1_numpy_array.dtype.name\n").arg(varName) ); command.append( QString("%1_direction = numpy.asarray(%1.GetDirection())\n").arg(varName) ); command.append( QString("%1_nrComponents = numpy.asarray(%1.GetNumberOfComponentsPerPixel())\n").arg(varName)); command.append( QString("%1_dtype = %1_numpy_array.dtype.name\n").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); PyObject* py_dtype = PyDict_GetItemString(pyDict,QString("%1_dtype").arg(varName).toStdString().c_str() ); std::string dtype = PyString_AsString(py_dtype); PyArrayObject* py_data = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_numpy_array").arg(varName).toStdString().c_str() ); PyArrayObject* py_spacing = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_spacing").arg(varName).toStdString().c_str() ); PyArrayObject* py_origin = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_origin").arg(varName).toStdString().c_str() ); PyArrayObject* py_direction = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_direction").arg(varName).toStdString().c_str() ); PyArrayObject* py_nrComponents = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_nrComponents").arg(varName).toStdString().c_str() ); unsigned int nr_Components = *(reinterpret_cast(PyArray_DATA(py_nrComponents))); unsigned int nr_dimensions = PyArray_NDIM(py_data); if (nr_Components > 1) // for VectorImages the last dimension in the numpy array are the vector components. { --nr_dimensions; } mitk::PixelType pixelType = DeterminePixelType(dtype, nr_Components, nr_dimensions); unsigned int* dimensions = new unsigned int[nr_dimensions]; // fill backwards , nd data saves dimensions in opposite direction for( unsigned i = 0; i < nr_dimensions; ++i ) { dimensions[i] = PyArray_DIMS(py_data)[nr_dimensions - 1 - i]; } mitkImage->Initialize(pixelType, nr_dimensions, dimensions); mitkImage->SetChannel(PyArray_DATA(py_data)); ds = reinterpret_cast(PyArray_DATA(py_spacing)); spacing[0] = ds[0]; spacing[1] = ds[1]; spacing[2] = ds[2]; mitkImage->GetGeometry()->SetSpacing(spacing); ds = reinterpret_cast(PyArray_DATA(py_origin)); origin[0] = ds[0]; origin[1] = ds[1]; origin[2] = ds[2]; mitkImage->GetGeometry()->SetOrigin(origin); itk::Matrix py_transform; ds = reinterpret_cast(PyArray_DATA(py_direction)); py_transform[0][0] = ds[0]; py_transform[0][1] = ds[1]; py_transform[0][2] = ds[2]; py_transform[1][0] = ds[3]; py_transform[1][1] = ds[4]; py_transform[1][2] = ds[5]; py_transform[2][0] = ds[6]; py_transform[2][1] = ds[7]; py_transform[2][2] = ds[8]; mitk::AffineTransform3D::Pointer affineTransform = mitkImage->GetGeometry()->GetIndexToWorldTransform(); itk::Matrix transform = py_transform * affineTransform->GetMatrix(); affineTransform->SetMatrix(transform); mitkImage->GetGeometry()->SetIndexToWorldTransform(affineTransform); // mitk::AffineTransform3D::New(); //mitkImage->GetGeometry()->SetIndexToWorldTransform(); // cleanup command.clear(); command.append( QString("del %1_numpy_array\n").arg(varName) ); command.append( QString("del %1_dtype\n").arg(varName) ); command.append( QString("del %1_spacing\n").arg(varName) ); command.append( QString("del %1_origin\n").arg(varName) ); command.append( QString("del %1_direction\n").arg(varName) ); command.append( QString("del %1_nrComponents\n").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); delete[] dimensions; return mitkImage; } bool mitk::PythonService::CopyToPythonAsCvImage( mitk::Image* image, const std::string& stdvarName ) { QString varName = QString::fromStdString( stdvarName ); QString command; unsigned int* imgDim = image->GetDimensions(); int npy_nd = 1; // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionary PyObject *pyDict = PyModule_GetDict(pyMod); mitk::PixelType pixelType = image->GetPixelType(); PyObject* npyArray = nullptr; mitk::ImageReadAccessor racc(image); void* array = (void*) racc.GetData(); // save the total number of elements here (since the numpy array is one dimensional) npy_intp* npy_dims = new npy_intp[1]; npy_dims[0] = imgDim[0]; /** * Build a string in the format [1024,1028,1] * to describe the dimensionality. This is needed for simple itk * to know the dimensions of the image */ QString dimensionString; dimensionString.append(QString("[")); dimensionString.append(QString::number(imgDim[0])); // ToDo: check if we need this for (unsigned i = 1; i < 3; ++i) // always three because otherwise the 3d-geometry gets destroyed // (relevant for backtransformation of simple itk image to mitk. { dimensionString.append(QString(",")); dimensionString.append(QString::number(imgDim[i])); npy_dims[0] *= imgDim[i]; } dimensionString.append("]"); // the next line is necessary for vectorimages npy_dims[0] *= pixelType.GetNumberOfComponents(); // default pixeltype: unsigned short NPY_TYPES npy_type = NPY_USHORT; if( pixelType.GetComponentType() == itk::ImageIOBase::DOUBLE ) { npy_type = NPY_DOUBLE; } else if( pixelType.GetComponentType() == itk::ImageIOBase::FLOAT ) { npy_type = NPY_FLOAT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::SHORT) { npy_type = NPY_SHORT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::CHAR ) { npy_type = NPY_BYTE; } else if( pixelType.GetComponentType() == itk::ImageIOBase::INT ) { npy_type = NPY_INT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::LONG ) { npy_type = NPY_LONG; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UCHAR ) { npy_type = NPY_UBYTE; } else if( pixelType.GetComponentType() == itk::ImageIOBase::UINT ) { npy_type = NPY_UINT; } else if( pixelType.GetComponentType() == itk::ImageIOBase::ULONG ) { npy_type = NPY_LONG; } else if( pixelType.GetComponentType() == itk::ImageIOBase::USHORT ) { npy_type = NPY_USHORT; } else { MITK_WARN << "not a recognized pixeltype"; return false; } // creating numpy array import_array1 (true); npyArray = PyArray_SimpleNewFromData(npy_nd,npy_dims,npy_type,array); // add temp array it to the python dictionary to access it in python code const int status = PyDict_SetItemString( pyDict,QString("%1_numpy_array") .arg(varName).toStdString().c_str(), npyArray ); // sanity check if ( status != 0 ) return false; command.append( QString("import numpy as np\n")); //command.append( QString("if '%1' in globals():\n").arg(varName)); //command.append( QString(" del %1\n").arg(varName)); command.append( QString("%1_array_tmp=%1_numpy_array.copy()\n").arg(varName)); command.append( QString("%1_array_tmp=%1_array_tmp.reshape(%2,%3,%4)\n").arg( varName, QString::number(imgDim[1]), QString::number(imgDim[0]), QString::number(pixelType.GetNumberOfComponents()))); command.append( QString("%1 = %1_array_tmp[:,...,::-1]\n").arg(varName)); command.append( QString("del %1_numpy_array\n").arg(varName) ); command.append( QString("del %1_array_tmp").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute( command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; } mitk::Image::Pointer mitk::PythonService::CopyCvImageFromPython( const std::string& stdvarName ) { // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionarry PyObject *pyDict = PyModule_GetDict(pyMod); mitk::Image::Pointer mitkImage = mitk::Image::New(); QString command; QString varName = QString::fromStdString( stdvarName ); command.append( QString("import numpy as np\n")); command.append( QString("%1_dtype=%1.dtype.name\n").arg(varName) ); command.append( QString("%1_shape=np.asarray(%1.shape)\n").arg(varName) ); command.append( QString("%1_np_array=%1[:,...,::-1]\n").arg(varName)); command.append( QString("%1_np_array=np.reshape(%1_np_array,%1.shape[0] * %1.shape[1] * %1.shape[2])").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); PyObject* py_dtype = PyDict_GetItemString(pyDict,QString("%1_dtype").arg(varName).toStdString().c_str() ); std::string dtype = PyString_AsString(py_dtype); PyArrayObject* py_data = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_np_array").arg(varName).toStdString().c_str() ); PyArrayObject* shape = (PyArrayObject*) PyDict_GetItemString(pyDict,QString("%1_shape").arg(varName).toStdString().c_str() ); size_t* d = reinterpret_cast(PyArray_DATA(shape)); unsigned int dimensions[3]; dimensions[0] = d[1]; dimensions[1] = d[0]; dimensions[2] = d[2]; unsigned int nr_dimensions = 2; // get number of components unsigned int nr_Components = (unsigned int) d[2]; mitk::PixelType pixelType = DeterminePixelType(dtype, nr_Components, nr_dimensions); mitkImage->Initialize(pixelType, nr_dimensions, dimensions); //mitkImage->SetChannel(py_data->data); { mitk::ImageWriteAccessor ra(mitkImage); char* data = (char*)(ra.GetData()); memcpy(data, PyArray_DATA(py_data), dimensions[0] * dimensions[1] * pixelType.GetSize()); } command.clear(); command.append( QString("del %1_shape\n").arg(varName) ); command.append( QString("del %1_dtype\n").arg(varName) ); command.append( QString("del %1_np_array").arg(varName)); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return mitkImage; } ctkAbstractPythonManager *mitk::PythonService::GetPythonManager() { return &m_PythonManager; } mitk::Surface::Pointer mitk::PythonService::CopyVtkPolyDataFromPython( const std::string& stdvarName ) { // access python module PyObject *pyMod = PyImport_AddModule((char*)"__main__"); // global dictionarry PyObject *pyDict = PyModule_GetDict(pyMod); // python memory address PyObject *pyAddr = nullptr; // cpp address size_t addr = 0; mitk::Surface::Pointer surface = mitk::Surface::New(); QString command; QString varName = QString::fromStdString( stdvarName ); command.append( QString("%1_addr_str = %1.GetAddressAsString(\"vtkPolyData\")\n").arg(varName) ); // remove 0x from the address command.append( QString("%1_addr = int(%1_addr_str[5:],16)").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); // get address of the object pyAddr = PyDict_GetItemString(pyDict,QString("%1_addr").arg(varName).toStdString().c_str()); // convert to long addr = PyInt_AsLong(pyAddr); MITK_DEBUG << "Python object address: " << addr; // get the object vtkPolyData* poly = (vtkPolyData*)((void*)addr); surface->SetVtkPolyData(poly); // delete helper variables from python stack command = ""; command.append( QString("del %1_addr_str\n").arg(varName) ); command.append( QString("del %1_addr").arg(varName) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return surface; } bool mitk::PythonService::CopyToPythonAsVtkPolyData( mitk::Surface* surface, const std::string& stdvarName ) { QString varName = QString::fromStdString( stdvarName ); std::ostringstream oss; std::string addr = ""; QString command; QString address; oss << (void*) ( surface->GetVtkPolyData() ); // get the address addr = oss.str(); // remove "0x" address = QString::fromStdString(addr.substr(2)); command.append( QString("%1 = vtk.vtkPolyData(\"%2\")\n").arg(varName).arg(address) ); MITK_DEBUG("PythonService") << "Issuing python command " << command.toStdString(); this->Execute(command.toStdString(), IPythonService::MULTI_LINE_COMMAND ); return true; } bool mitk::PythonService::IsSimpleItkPythonWrappingAvailable() { this->Execute( "import SimpleITK as sitk\n", IPythonService::SINGLE_LINE_COMMAND ); // directly access cpp lib this->Execute( "import _SimpleITK\n", IPythonService::SINGLE_LINE_COMMAND ); m_ItkWrappingAvailable = !this->PythonErrorOccured(); // check for numpy this->Execute( "import numpy\n", IPythonService::SINGLE_LINE_COMMAND ); if ( this->PythonErrorOccured() ) MITK_ERROR << "Numpy not found."; m_ItkWrappingAvailable = !this->PythonErrorOccured(); return m_ItkWrappingAvailable; } bool mitk::PythonService::IsOpenCvPythonWrappingAvailable() { this->Execute( "import cv2\n", IPythonService::SINGLE_LINE_COMMAND ); m_OpenCVWrappingAvailable = !this->PythonErrorOccured(); return m_OpenCVWrappingAvailable; } bool mitk::PythonService::IsVtkPythonWrappingAvailable() { this->Execute( "import vtk", IPythonService::SINGLE_LINE_COMMAND ); //this->Execute( "print \"Using VTK version \" + vtk.vtkVersion.GetVTKVersion()\n", IPythonService::SINGLE_LINE_COMMAND ); m_VtkWrappingAvailable = !this->PythonErrorOccured(); return m_VtkWrappingAvailable; } bool mitk::PythonService::PythonErrorOccured() const { return m_ErrorOccured; } diff --git a/Modules/Python/autoload/PythonService/mitkPythonService.h b/Modules/Python/autoload/PythonService/mitkPythonService.h index d20bc44b16..6f8cc5c84f 100644 --- a/Modules/Python/autoload/PythonService/mitkPythonService.h +++ b/Modules/Python/autoload/PythonService/mitkPythonService.h @@ -1,104 +1,108 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPythonService_h #define mitkPythonService_h #include "mitkIPythonService.h" #include #include #include "mitkSurface.h" namespace mitk { /// /// implementation of the IPythonService using ctkabstractpythonmanager /// \see IPythonService class PythonService: public itk::LightObject, public mitk::IPythonService { public: /// /// instantiate python manager here PythonService(); /// /// empty implementation... ~PythonService(); /// /// \see IPythonService::Execute() std::string Execute( const std::string& pythonCommand, int commandType = SINGLE_LINE_COMMAND ); /// /// \see IPythonService::ExecuteScript() void ExecuteScript(const std::string &pathToPythonScript); /// /// \see IPythonService::PythonErrorOccured() bool PythonErrorOccured() const; /// /// \see IPythonService::GetVariableStack() std::vector GetVariableStack() const; /// /// \see IPythonService::DoesVariableExist() bool DoesVariableExist(const std::string& name) const; /// + /// \see IPythonService::GetVariable() + std::string GetVariable(const std::string& name) const; + /// /// \see IPythonService::AddPythonCommandObserver() void AddPythonCommandObserver( PythonCommandObserver* observer ); /// /// \see IPythonService::RemovePythonCommandObserver() void RemovePythonCommandObserver( PythonCommandObserver* observer ); /// /// \see IPythonService::NotifyObserver() void NotifyObserver( const std::string& command ); /// /// \see IPythonService::IsItkPythonWrappingAvailable() bool IsSimpleItkPythonWrappingAvailable(); /// /// \see IPythonService::CopyToPythonAsItkImage() bool CopyToPythonAsSimpleItkImage( mitk::Image* image, const std::string& varName ); /// /// \see IPythonService::CopyItkImageFromPython() mitk::Image::Pointer CopySimpleItkImageFromPython( const std::string& varName ); /// /// \see IPythonService::IsOpenCvPythonWrappingAvailable() bool IsOpenCvPythonWrappingAvailable(); /// /// \see IPythonService::CopyToPythonAsCvImage() bool CopyToPythonAsCvImage( mitk::Image* image, const std::string& varName ); /// /// \see IPythonService::CopyCvImageFromPython() mitk::Image::Pointer CopyCvImageFromPython( const std::string& varName ); /// /// \see IPythonService::IsVtkPythonWrappingAvailable() bool IsVtkPythonWrappingAvailable(); /// /// \see IPythonService::CopyToPythonAsVtkPolyData() bool CopyToPythonAsVtkPolyData( mitk::Surface* surface, const std::string& varName ); /// /// \see IPythonService::CopyVtkPolyDataFromPython() mitk::Surface::Pointer CopyVtkPolyDataFromPython( const std::string& varName ); /// /// \return the ctk abstract python manager instance ctkAbstractPythonManager* GetPythonManager(); + protected: QString GetTempDataFileName(const std::string &ext) const; private: QList m_Observer; ctkAbstractPythonManager m_PythonManager; static const QString m_TmpDataFileName; bool m_ItkWrappingAvailable; bool m_OpenCVWrappingAvailable; bool m_VtkWrappingAvailable; bool m_ErrorOccured; }; } #endif diff --git a/Modules/Python/mitkIPythonService.h b/Modules/Python/mitkIPythonService.h index 7e6b72ce3b..d074ff31a6 100644 --- a/Modules/Python/mitkIPythonService.h +++ b/Modules/Python/mitkIPythonService.h @@ -1,150 +1,153 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkIPythonService_h #define mitkIPythonService_h // mitk #include #include "mitkImage.h" //for microservices #include #include "mitkSurface.h" #include class ctkAbstractPythonManager; namespace mitk { /// /// describes a python variable (data container) /// \see IPythonService::GetVariableStack() /// struct PythonVariable { std::string m_Name; std::string m_Type; std::string m_Value; }; /// /// a PythonCommandObserver gets informed as soon as a python command was issued /// \see IPythonService::AddPythonCommandObserver() /// class PythonCommandObserver { public: virtual void CommandExecuted(const std::string& pythonCommand) = 0; }; /// /// The central service for issuing Python Code /// The class also enables to transfer mitk images to python as itk::Image and vice versa /// \see IPythonService::GetVariableStack() /// class MITKPYTHON_EXPORT IPythonService { public: /// /// Constant representing a single line command /// \see IPythonService::Execute() static const int SINGLE_LINE_COMMAND = 0; /// /// Constant representing a command in which the commands are seperated by new lines, i.e. "\\n" /// \see IPythonService::Execute() static const int MULTI_LINE_COMMAND = 1; /// /// Constant representing a single line command x which is run as "eval(x)" /// \see IPythonService::Execute() static const int EVAL_COMMAND = 2; /// /// Executes a python command. /// \return A variant containing the return value as string of the python code (if any) virtual std::string Execute( const std::string& pythonCommand, int commandType = SINGLE_LINE_COMMAND ) = 0; /// /// Executes a python script. virtual void ExecuteScript( const std::string& pathToPythonScript ) = 0; /// /// \return true if the last call to Execute...() resulted in an error, false otherwise virtual bool PythonErrorOccured() const = 0; /// /// \return The list of variables in the __main__ namespace virtual std::vector GetVariableStack() const = 0; /// /// \return true if a variable with this name is defined in the __main__ namespace, false otherwise virtual bool DoesVariableExist(const std::string& name) const = 0; /// + /// \return value of variable with this name as string, empty string if variable does not exist + virtual std::string GetVariable(const std::string& name) const = 0; + /// /// adds a command observer which is informed after a command was issued with "Execute" virtual void AddPythonCommandObserver( PythonCommandObserver* observer ) = 0; /// /// removes a specific command observer virtual void RemovePythonCommandObserver( PythonCommandObserver* observer ) = 0; /// /// notify all observer. this should only be used if it can be garantueed that the /// current python interpreter instance got another command from anywhere else /// the the Execute() method of this service, e.g. the shell widget uses this function /// since it does not use Execute() virtual void NotifyObserver( const std::string& command ) = 0; /// /// \return true, if itk wrapping is available, false otherwise virtual bool IsSimpleItkPythonWrappingAvailable() = 0; /// /// copies an mitk image as itk image into the python interpreter process /// the image will be available as "varName" in python if everythin worked /// \return true if image was copied, else false virtual bool CopyToPythonAsSimpleItkImage( mitk::Image* image, const std::string& varName ) = 0; /// /// copies an itk image from the python process that is named "varName" /// \return the image or 0 if copying was not possible virtual mitk::Image::Pointer CopySimpleItkImageFromPython( const std::string& varName ) = 0; /// /// \return true, if OpenCv wrapping is available, false otherwise virtual bool IsOpenCvPythonWrappingAvailable() = 0; /// /// \see CopyToPythonAsItkImage() virtual bool CopyToPythonAsCvImage( mitk::Image* image, const std::string& varName ) = 0; /// /// \see CopyCvImageFromPython() virtual mitk::Image::Pointer CopyCvImageFromPython( const std::string& varName ) = 0; /// /// \return true, if vtk wrapping is available, false otherwise virtual bool IsVtkPythonWrappingAvailable() = 0; /// /// \see CopyToPythonAsItkImage() virtual bool CopyToPythonAsVtkPolyData( mitk::Surface* surface, const std::string& varName ) = 0; /// /// \see CopyCvImageFromPython() virtual mitk::Surface::Pointer CopyVtkPolyDataFromPython( const std::string& varName ) = 0; /// \return the ctk abstract python manager instance virtual ctkAbstractPythonManager* GetPythonManager() = 0; /// /// nothing to do here virtual ~IPythonService(); // leer in mitkIPythonService.cpp implementieren // force us module loading by linking static std::string ForceLoadModule(); }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IPythonService, "org.mitk.services.IPythonService") #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging.python/resources/dipy_reconstructions.py b/Plugins/org.mitk.gui.qt.diffusionimaging.python/resources/dipy_reconstructions.py index 9650f27c34..7008312528 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging.python/resources/dipy_reconstructions.py +++ b/Plugins/org.mitk.gui.qt.diffusionimaging.python/resources/dipy_reconstructions.py @@ -1,378 +1,390 @@ -import dipy.direction.peaks as dpp -from dipy.reconst.shore import ShoreModel -from dipy.reconst.shm import CsaOdfModel -import dipy.reconst.sfm as sfm -from dipy.reconst.csdeconv import auto_response, ConstrainedSphericalDeconvModel -from dipy.core import sphere -import numpy as np -from dipy.core.gradients import gradient_table -import SimpleITK as sitk +error_string = None +del error_string +try: + import dipy.direction.peaks as dpp + from dipy.reconst.shore import ShoreModel + from dipy.reconst.shm import CsaOdfModel, OpdtModel, SphHarmModel + import dipy.reconst.sfm as sfm + from dipy.reconst.csdeconv import auto_response, ConstrainedSphericalDeconvModel + from dipy.core import sphere + import numpy as np + from dipy.core.gradients import gradient_table + import SimpleITK as sitk -def get_mitk_sphere(): - """ Return MITK compliant dipy Sphere object. - MITK stores ODFs as 252 values spherically sampled from the continuous ODF. - The sampling directions are generate by a 5-fold subdivisions of an icosahedron. - """ - xyz = np.array([ - 0.9756767549555488, 0.9977154378498742, 0.9738192119472443, - 0.8915721200771204, 0.7646073555341725, 0.6231965669156312, - 0.9817040172417226, 0.9870396762453547, 0.9325589150767597, - 0.8173592116492303, 0.6708930871960926, 0.9399233672993689, - 0.9144882783890762, 0.8267930935417315, 0.6931818659696647, - 0.8407280774774689, 0.782394344826989, 0.6762337155773353, - 0.7005607434301688, 0.6228579759074076, 0.5505632701289798, - 0.4375940376503738, 0.3153040621970065, 0.1569517536476641, - -0.01984099037382634, -0.1857690950088067, -0.3200730131503601, - 0.5232435944036425, 0.3889403678268736, 0.2135250052622625, - 0.02420694871807206, -0.1448539951504302, 0.5971534158422009, - 0.4482053228282282, 0.2597018771197477, 0.06677517278138323, - 0.6404616222418184, 0.4782876117785159, 0.2868761951248767, - 0.6459894362878276, 0.4789651252338281, 0.3200724178002418, - 0.4973180497018747, 0.6793811951363423, 0.8323587928990375, - 0.9308933612987835, 0.4036036036586492, 0.5984781165037405, - 0.7817280923310203, 0.9140795130247613, 0.4809905907165384, - 0.6759621154318279, 0.8390728924802671, 0.5347729120192694, - 0.7094340284155564, 0.5560356639783846, 0.2502538949373057, - 0.3171352000240629, 0.3793963897789465, 0.4231100429674418, - 0.4410301813437042, 0.4357529867703999, 0.5208717223808415, - 0.5850086433327374, 0.611055499882272, 0.6009463532173235, - 0.6305067000562991, 0.7188806066405239, 0.7654898954879897, - 0.7616477696596397, 0.7997756996573342, 0.8700831379830764, - 0.8872031228985237, 0.9155019734809123, 0.9568003701205341, - -0.4375932291383153, -0.3153035222278598, -0.1569515927579475, - 0.0198407706589918, 0.1857686171195431, -0.2644927501381796, - -0.1064219080255857, 0.07849995612144045, 0.2583107784678281, - -0.04938676750055992, 0.1358448755096817, 0.3243479900672576, - 0.1811879481039926, 0.3692668145365748, 0.3890115016151001, - -0.6231952788307174, -0.4943551945928708, -0.319458133528771, - -0.1156489798772063, 0.08328895892415776, -0.4789641985801549, - -0.3127252940830145, -0.1059392282183739, 0.1077444781964869, - 0.2912280153186658, -0.2868758523956744, -0.08856892011805101, - 0.1287405357080231, 0.3245517154572714, -0.06677541204276306, - 0.1413542883070481, 0.3408430926744944, 0.1448534358763926, - 0.3374016489097037, -0.2502532651867688, -0.3171345072414974, - -0.3793956104585266, -0.4231091882680272, -0.4410293135613324, - -0.09929959410007272, -0.1535127609134815, -0.2052877394623771, - -0.2436963810571767, 0.08175409117371149, 0.04056025153798869, - -0.006048944565669369, 0.2686152102237028, 0.2319923070602857, - 0.430309819720559, -0.975676581463901, -0.9977153903038788, - -0.9738191090293654, -0.8915716840571059, -0.7646064477130079, - -0.9568001079664734, -0.9598482725023617, -0.9044523389503778, - -0.7901672201648241, -0.6459882395962464, -0.8872027729137049, - -0.8582754834679532, -0.7705800268610806, -0.6404605781008121, - -0.7616472974254324, -0.7008201753656432, -0.5971525097007422, - -0.6009457148226922, -0.5232427588825813, 0.4943566966479628, - 0.3194596781650836, 0.1156503154178581, -0.0832879858164388, - 0.5222841738261358, 0.3225497922064885, 0.1018140973507329, - 0.5217885230992481, 0.3044789836562512, 0.4873191346491355, - -0.4973183240635209, -0.6793811856410323, -0.8323586364840968, - -0.9308931819742911, -0.3374020539278631, -0.5261951664998159, - -0.7070125356849136, -0.8417962075837926, -0.9155017573317124, - -0.3408433114184408, -0.5265312606271311, -0.6896418460594331, - -0.7997755164970677, -0.3245517106425898, -0.4925847482169691, - -0.6305065080228541, -0.2912277152063287, -0.4357526334612896, - 0.7901679726328494, 0.9044526665335126, 0.9598484396937114, - 0.7705806468939737, 0.858275831469383, 0.7008207681995118, - -0.4036039458806759, -0.2583110138480089, -0.0784999126587471, - 0.1064223584250461, 0.264493571710179, -0.4809907334514471, - -0.3243480295764106, -0.1358446002697818, 0.04938746901646566, - -0.5347730026038946, -0.3692667658371347, -0.1811875286592425, - -0.5560358190148772, -0.3890114324926668, -0.5505634949474449, - 0.8417963565884857, 0.7070125813068046, 0.5261950179989611, - 0.6896418985458221, 0.5265311900255359, 0.4925848265160583, - 0.2436972866599269, 0.2052886581368649, 0.153513629451971, - 0.09930039009433847, 0.006049691633511915, -0.04055950638179381, - -0.08175337578691833, -0.2319919155781195, -0.2686148310916902, - -0.430309819678344, -0.02420720081803753, -0.2135248270679241, - -0.3889397838050994, -0.2597016312374675, -0.4482046405142344, - -0.4782867918076852, -0.1018130528605821, -0.322548598821141, - -0.5222830294256716, -0.6708921376896406, -0.304478224282928, - -0.5217878437313506, -0.6931813485878851, -0.4873188675145023, - -0.6762335873429084, -0.6228580878699612, -0.6110548409057, - -0.5850080622199078, -0.5208712693637837, -0.7654894328832393, - -0.7188802647693375, -0.8700828159137221, -0.8173587433845655, - -0.9325588839421305, -0.9870397834787261, -0.9817039872478999, - -0.8267930492778305, -0.9144884914916022, -0.9399235077793813, - -0.7823945479956939, -0.8407283372889187, -0.7005610213599369, - -0.1077438933887955, 0.1059400956623477, 0.3127262866621893, - -0.1287403742204129, 0.08856921814263634, -0.1413545191115968, - -0.9140794058749131, -0.7817279594934516, -0.5984781448346268, - -0.8390728949381593, -0.6759620794963979, -0.709434131000089, - -0.1778161375899129, -0.06053925384414331, 0.07929679392711581, - 0.222673458561735, 0.3458247516791153, 0.4366423972091846, - 0.01030826616734189, 0.1591522280204451, 0.3173816763430465, - 0.4549463955350546, 0.5521270265729551, 0.2292788658415479, - 0.3973400932411465, 0.5502139834879405, 0.6594089221868847, - 0.4476465561008348, 0.6096570464011057, 0.7343998566036512, - 0.629214796874201, 0.7646693979379596, 0.7580253719184178, - -0.5980610514568761, -0.5101530988159087, -0.382225667160838, - -0.2244621267538426, -0.06301328229424107, 0.07805400320688782, - -0.4311039309963852, -0.3079662136138592, -0.1501157132113724, - 0.01750888497279251, 0.1650825345160538, -0.2148810450151756, - -0.06090095222676627, 0.1073128739652992, 0.2584097661066967, - 0.02655484252908358, 0.1901297170957776, 0.3420822257932489, - 0.2531835106264871, 0.4022303494272352, -0.07805410188638827, - -0.1080255529483224, -0.1376217050758367, -0.1609000070073124, - -0.1740018618448228, 0.09827676798573926, 0.083291898217249, - 0.06127443921955168, 0.03526739273256396, 0.2991139104294396, - 0.2941068360088736, 0.2692865316145088, 0.4942032775296958, - 0.4857723178878524, 0.6512069539966677, -0.9161616153729886, - -0.9396953110011561, -0.9204280785344878, -0.8462030522374957, - -0.7293237120999879, -0.8470541513588044, -0.8482966176587544, - -0.7977006542517769, -0.6951661565374421, -0.566558592627622, - -0.7243096319272092, -0.6931460376496088, -0.6140043047773551, - -0.5016343691560573, -0.5520254073275178, -0.4928644880867128, - -0.403575153350467, -0.3587591578566765, -0.2886351685087218, - 0.5980613131647216, 0.5101532951859686, 0.382225843595672, - 0.2244622808787926, 0.06301334452030186, 0.6944632949786616, - 0.5955168212825119, 0.4473425940100297, 0.2700417838303327, - 0.7724043956082883, 0.6553545192922715, 0.4871408620353512, - 0.8097301284690857, 0.6725220182496192, 0.8002534097038426, - -0.4366431953633789, -0.5869882376922511, -0.7332080507197046, - -0.8450980113065225, -0.9041113586460733, -0.4022310083998925, - -0.554596445154436, -0.6925605687496104, -0.7854318984598006, - -0.8250621271173465, -0.3420827953668352, -0.4840440064641756, - -0.6033456975789954, -0.6777531805937266, -0.2584102557043402, - -0.3819753792546441, -0.4821906665520286, -0.1650828712784331, - -0.270790845781693, 0.9161619708326184, 0.9396956424389374, - 0.9204283182965946, 0.8462032095340455, 0.7293238793541417, - 0.9749588444840027, 0.9879501207294071, 0.942053498973333, - 0.8348196077814718, 0.9950795014807369, 0.9818515654328379, - 0.9027098746674149, 0.9581801446138297, 0.9118246030313639, - 0.8703772282258925, 0.1778171059718252, 0.06053992567271226, - -0.07929659020903117, -0.2226737578340799, -0.345825401239635, - 0.2886360377097776, 0.1672516508448342, 0.02000533874392893, - -0.1285435155191929, -0.2531843553864728, 0.403575906447316, - 0.2774342678683828, 0.1245598363284875, -0.02655554762561945, - 0.5016349858535857, 0.3695530582277636, 0.2148806720954671, - 0.5665590425344393, 0.431103930292903, 0.5869876102086139, - 0.7332077514676827, 0.845098078457225, 0.9041116580482536, - 0.7182616282077119, 0.8617334421407644, 0.9490975365686583, - 0.8223898048944452, 0.9416915744235097, 0.8729720010540123, - 0.1080256414522809, 0.1376220280275969, 0.1609005865750696, - 0.1740026689030255, 0.2707904196202965, 0.3196768235430837, - 0.3552546724685221, 0.3677018240803483, 0.3587598208776521, - 0.4821901792282771, 0.5389508449256169, 0.5637713635689835, - 0.5520258363563475, 0.6777529577987501, 0.7231337276202411, - 0.724309982145211, 0.8250622687013296, 0.8470545173149734, - 0.1285429999155006, -0.02000532948058562, -0.1672511147059996, - -0.1245600244829796, -0.2774338902981233, -0.3695528631494325, - -0.09827641615811868, -0.2700412859530667, -0.4473420975374328, - -0.5955164071695848, -0.6944629164413806, -0.2991130971968019, - -0.4871400501186961, -0.6553538941234454, -0.7724039524031648, - -0.4942022299541438, -0.6725212074710563, -0.8097296395344389, - -0.6512059956089504, -0.8002528392148971, -0.7580246814516085, - -0.3677014077761052, -0.3552545716101517, -0.3196770257819652, - -0.5637712030900536, -0.5389510214534028, -0.7231336172569296, - -0.8348194119106425, -0.9420533966954356, -0.9879499956150448, - -0.9749586635216289, -0.9027097279159257, -0.9818515951566739, - -0.9950795477220543, -0.9118244750171576, -0.9581802235578871, - -0.8703770126934449, -0.0175091339170676, 0.1501155140512474, - 0.3079660822386824, -0.1073133727582037, 0.06090046334304851, - -0.1901304002696938, -0.9490974969653682, -0.8617336589899791, - -0.7182621005240754, -0.5521276321758419, -0.941691783045487, - -0.8223901593137167, -0.6594093292610237, -0.872972144171723, - -0.7343999908188845, -0.7646691446910742, 0.6951665021597787, - 0.7977009700656229, 0.8482969664746548, 0.6140047811934269, - 0.6931464276818936, 0.4928650597255946, -0.4549467775084718, - -0.3173815862988101, -0.1591515620353438, -0.01030716362341688, - -0.5502140363721867, -0.3973395475484636, -0.2292777334167206, - -0.609656670182737, -0.4476455277450017, -0.6292139442700462, - 0.7854319364049284, 0.6925603649758249, 0.5545959620739339, - 0.6033453603619342, 0.4840435291285519, 0.3819748711371402, - -0.03526641653115874, -0.06127364342066123, -0.0832913202753871, - -0.2692854573778917, -0.2941058574917593, -0.4857712605383084, - -0.1282040992012934, 0.02998172476739921, 0.2130449739264662, - 0.394354771181159, 0.5438573645627299, 0.6488215902264565, - -0.1901340637026595, -0.02057293935230464, 0.1720544722828635, - 0.3534794142829396, 0.4950335464190314, -0.252933321812349, - -0.07636778766011496, 0.1169519253626288, 0.2909961752861106, - -0.304612640171253, -0.1271903099934383, 0.0580070042064605, - -0.3366056805211806, -0.1653138037361849, -0.3496821715684524, - 0.6714420577705413, 0.8002044514563711, 0.9106424580428781, - 0.9742808059046055, 0.9805708386415104, 0.9441720387917811, - 0.7350956003099328, 0.8682639008659977, 0.9653353535299492, - 0.9995536316680411, 0.9755844796257857, 0.7728091190204586, - 0.8918537226509272, 0.9597077065970592, 0.9637247890765801, - 0.767530944505584, 0.857374860312736, 0.8948082473172733, - 0.7201359303293944, 0.7802583897718675, -0.9441722324566724, - -0.8608166107545396, -0.7207644955095487, -0.5303678229575245, - -0.3211867088850157, -0.9096404828216634, -0.7967975927156801, - -0.620601831095295, -0.4039985827676406, -0.8241231220089414, - -0.6757043639889994, -0.4726959329165278, -0.6854057579633669, - -0.5106159168102177, -0.5164821811548767, -0.3130828685601688, - -0.128054626578418, 0.09418349997750548, 0.3239109228229815, - 0.523048087763098, -0.3043330399192493, -0.09531787499064681, - 0.146419102006115, 0.3786227553496849, 0.5638039035645359, - -0.2789925774668332, -0.05252850546893189, 0.1924160430438771, - 0.4101897544477446, -0.2358533016570041, -0.006318969895916147, - 0.2236016867495729, -0.1820659309330632, 0.03496843200875603, - -0.6714423515894649, -0.8002045390283683, -0.9106424117173109, - -0.9742807748705438, -0.9805709251787237, -0.6691519386893557, - -0.79626257796142, -0.8909109722488041, -0.9275521423149625, - -0.6332080201962388, -0.7430051304270751, -0.8108589038018792, - -0.5581290590099237, -0.6413705283620924, -0.4563600901355626, - -0.648822290296783, -0.6411378559950974, -0.600293640880965, - -0.5219527418637842, -0.4191009430775375, -0.7802586188950914, - -0.7711197529973893, -0.713538182957094, -0.6094980396194888, - -0.4842093859996422, -0.8948081394501657, -0.8705497953564927, - -0.7870195954857328, -0.6597854273844109, -0.9637246412193355, - -0.9132982945459158, -0.8070428410352181, -0.975584505681221, - -0.9015722073987464, 0.3130823317650696, 0.1280539101236855, - -0.09418429615654819, -0.3239116283455282, -0.523048586255087, - 0.1989845274738189, -0.01970764286946627, -0.2653151882168217, - -0.4936479477555078, 0.05597369301027853, -0.1852629737758222, - -0.4302072668465533, -0.09867461327158224, -0.3387557568094476, - -0.2393260112020272, 0.1282040764044601, -0.0299819504088954, - -0.2130455201840074, -0.3943555879655132, -0.5438582278251758, - -0.03496843048443223, -0.2252069693946209, -0.4261053308619027, - -0.5992598174372795, -0.720136706807033, -0.2236017161594696, - -0.4317330442416767, -0.6250530132529536, -0.7675317913865697, - -0.4101898771205939, -0.6101488498350025, -0.7728099228904255, - -0.5638041319099237, -0.7350961954485662, 0.6411372723067146, - 0.6002931843810706, 0.5219523372221417, 0.4191004905746099, - 0.4596949806286311, 0.3916338931244087, 0.2980734064957148, - 0.226741584116328, 0.1432114770939381, -0.02097489882147943, - 0.8608164411414747, 0.7207644427956729, 0.5303678926086439, - 0.3211867913977836, 0.9015721838250796, 0.7879881821713033, - 0.6114960278478284, 0.3951892122332402, 0.1820657113417612, - 0.8070430398170311, 0.6574928275930984, 0.4544842943197335, - 0.2358529185889448, 0.6597856586149884, 0.4841878538357612, - 0.2789921022280572, 0.4842093252521232, 0.3043325272261384, - 0.5992589358516202, 0.4261046359672609, 0.2252066549797059, - 0.6250522113657903, 0.4317325950511361, 0.6101482870567641, - 0.9096403689902206, 0.9275522217134882, 0.8909112253661301, - 0.796262827475376, 0.6691520068054228, 0.8241233338640371, - 0.810859375773786, 0.7430057321681839, 0.6332085061147845, - 0.6854064426268304, 0.6413714065577412, 0.5581299045184589, - 0.5164832226272315, 0.4563611494403301, 0.3496833143594963, - -0.3951892821849063, -0.6114960336943951, -0.787988199289983, - -0.4544844137443082, -0.657492739431111, -0.484187939006181, - 0.4936478319326018, 0.2653148405479006, 0.01970714938077021, - -0.1989850169013517, 0.4302075642722875, 0.1852629793843341, - -0.0559739158243807, 0.3387563694841473, 0.09867487876932232, - 0.2393267951217032, -0.999553621201999, -0.9653354239158236, - -0.8682642090770526, -0.9597077173597477, -0.8918540989344099, - -0.8573751662344773, -0.2980738893651726, -0.3916343988495664, - -0.4596955428592778, -0.4950341577852201, -0.1432117197792371, - -0.2267418620329016, -0.2909964852939082, 0.02097514873862574, - -0.05800679989935065, 0.1653145532988453, -0.3786231842883476, - -0.1464197032303796, 0.09531724619007391, -0.1924163631703616, - 0.05252803743712917, 0.006318730357784829, -0.3534800054422614, - -0.1720548071373146, 0.02057294660420643, 0.190134278339324, - -0.1169519894866824, 0.07636807502743861, 0.2529338262925594, - 0.1271908635410245, 0.3046134343217798, 0.3366066958443542, - 0.6094980941008995, 0.7135382519498201, 0.7711196978950583, - 0.7870198804193677, 0.8705500304441893, 0.9132984713369965, - 0.403998910419839, 0.62060207699311, 0.7967976318501995, - 0.4726965405256068, 0.6757048258462731, 0.5106167801856609]) + def get_mitk_sphere(): + """ Return MITK compliant dipy Sphere object. + MITK stores ODFs as 252 values spherically sampled from the continuous ODF. + The sampling directions are generate by a 5-fold subdivisions of an icosahedron. + """ + xyz = np.array([ + 0.9756767549555488, 0.9977154378498742, 0.9738192119472443, + 0.8915721200771204, 0.7646073555341725, 0.6231965669156312, + 0.9817040172417226, 0.9870396762453547, 0.9325589150767597, + 0.8173592116492303, 0.6708930871960926, 0.9399233672993689, + 0.9144882783890762, 0.8267930935417315, 0.6931818659696647, + 0.8407280774774689, 0.782394344826989, 0.6762337155773353, + 0.7005607434301688, 0.6228579759074076, 0.5505632701289798, + 0.4375940376503738, 0.3153040621970065, 0.1569517536476641, + -0.01984099037382634, -0.1857690950088067, -0.3200730131503601, + 0.5232435944036425, 0.3889403678268736, 0.2135250052622625, + 0.02420694871807206, -0.1448539951504302, 0.5971534158422009, + 0.4482053228282282, 0.2597018771197477, 0.06677517278138323, + 0.6404616222418184, 0.4782876117785159, 0.2868761951248767, + 0.6459894362878276, 0.4789651252338281, 0.3200724178002418, + 0.4973180497018747, 0.6793811951363423, 0.8323587928990375, + 0.9308933612987835, 0.4036036036586492, 0.5984781165037405, + 0.7817280923310203, 0.9140795130247613, 0.4809905907165384, + 0.6759621154318279, 0.8390728924802671, 0.5347729120192694, + 0.7094340284155564, 0.5560356639783846, 0.2502538949373057, + 0.3171352000240629, 0.3793963897789465, 0.4231100429674418, + 0.4410301813437042, 0.4357529867703999, 0.5208717223808415, + 0.5850086433327374, 0.611055499882272, 0.6009463532173235, + 0.6305067000562991, 0.7188806066405239, 0.7654898954879897, + 0.7616477696596397, 0.7997756996573342, 0.8700831379830764, + 0.8872031228985237, 0.9155019734809123, 0.9568003701205341, + -0.4375932291383153, -0.3153035222278598, -0.1569515927579475, + 0.0198407706589918, 0.1857686171195431, -0.2644927501381796, + -0.1064219080255857, 0.07849995612144045, 0.2583107784678281, + -0.04938676750055992, 0.1358448755096817, 0.3243479900672576, + 0.1811879481039926, 0.3692668145365748, 0.3890115016151001, + -0.6231952788307174, -0.4943551945928708, -0.319458133528771, + -0.1156489798772063, 0.08328895892415776, -0.4789641985801549, + -0.3127252940830145, -0.1059392282183739, 0.1077444781964869, + 0.2912280153186658, -0.2868758523956744, -0.08856892011805101, + 0.1287405357080231, 0.3245517154572714, -0.06677541204276306, + 0.1413542883070481, 0.3408430926744944, 0.1448534358763926, + 0.3374016489097037, -0.2502532651867688, -0.3171345072414974, + -0.3793956104585266, -0.4231091882680272, -0.4410293135613324, + -0.09929959410007272, -0.1535127609134815, -0.2052877394623771, + -0.2436963810571767, 0.08175409117371149, 0.04056025153798869, + -0.006048944565669369, 0.2686152102237028, 0.2319923070602857, + 0.430309819720559, -0.975676581463901, -0.9977153903038788, + -0.9738191090293654, -0.8915716840571059, -0.7646064477130079, + -0.9568001079664734, -0.9598482725023617, -0.9044523389503778, + -0.7901672201648241, -0.6459882395962464, -0.8872027729137049, + -0.8582754834679532, -0.7705800268610806, -0.6404605781008121, + -0.7616472974254324, -0.7008201753656432, -0.5971525097007422, + -0.6009457148226922, -0.5232427588825813, 0.4943566966479628, + 0.3194596781650836, 0.1156503154178581, -0.0832879858164388, + 0.5222841738261358, 0.3225497922064885, 0.1018140973507329, + 0.5217885230992481, 0.3044789836562512, 0.4873191346491355, + -0.4973183240635209, -0.6793811856410323, -0.8323586364840968, + -0.9308931819742911, -0.3374020539278631, -0.5261951664998159, + -0.7070125356849136, -0.8417962075837926, -0.9155017573317124, + -0.3408433114184408, -0.5265312606271311, -0.6896418460594331, + -0.7997755164970677, -0.3245517106425898, -0.4925847482169691, + -0.6305065080228541, -0.2912277152063287, -0.4357526334612896, + 0.7901679726328494, 0.9044526665335126, 0.9598484396937114, + 0.7705806468939737, 0.858275831469383, 0.7008207681995118, + -0.4036039458806759, -0.2583110138480089, -0.0784999126587471, + 0.1064223584250461, 0.264493571710179, -0.4809907334514471, + -0.3243480295764106, -0.1358446002697818, 0.04938746901646566, + -0.5347730026038946, -0.3692667658371347, -0.1811875286592425, + -0.5560358190148772, -0.3890114324926668, -0.5505634949474449, + 0.8417963565884857, 0.7070125813068046, 0.5261950179989611, + 0.6896418985458221, 0.5265311900255359, 0.4925848265160583, + 0.2436972866599269, 0.2052886581368649, 0.153513629451971, + 0.09930039009433847, 0.006049691633511915, -0.04055950638179381, + -0.08175337578691833, -0.2319919155781195, -0.2686148310916902, + -0.430309819678344, -0.02420720081803753, -0.2135248270679241, + -0.3889397838050994, -0.2597016312374675, -0.4482046405142344, + -0.4782867918076852, -0.1018130528605821, -0.322548598821141, + -0.5222830294256716, -0.6708921376896406, -0.304478224282928, + -0.5217878437313506, -0.6931813485878851, -0.4873188675145023, + -0.6762335873429084, -0.6228580878699612, -0.6110548409057, + -0.5850080622199078, -0.5208712693637837, -0.7654894328832393, + -0.7188802647693375, -0.8700828159137221, -0.8173587433845655, + -0.9325588839421305, -0.9870397834787261, -0.9817039872478999, + -0.8267930492778305, -0.9144884914916022, -0.9399235077793813, + -0.7823945479956939, -0.8407283372889187, -0.7005610213599369, + -0.1077438933887955, 0.1059400956623477, 0.3127262866621893, + -0.1287403742204129, 0.08856921814263634, -0.1413545191115968, + -0.9140794058749131, -0.7817279594934516, -0.5984781448346268, + -0.8390728949381593, -0.6759620794963979, -0.709434131000089, + -0.1778161375899129, -0.06053925384414331, 0.07929679392711581, + 0.222673458561735, 0.3458247516791153, 0.4366423972091846, + 0.01030826616734189, 0.1591522280204451, 0.3173816763430465, + 0.4549463955350546, 0.5521270265729551, 0.2292788658415479, + 0.3973400932411465, 0.5502139834879405, 0.6594089221868847, + 0.4476465561008348, 0.6096570464011057, 0.7343998566036512, + 0.629214796874201, 0.7646693979379596, 0.7580253719184178, + -0.5980610514568761, -0.5101530988159087, -0.382225667160838, + -0.2244621267538426, -0.06301328229424107, 0.07805400320688782, + -0.4311039309963852, -0.3079662136138592, -0.1501157132113724, + 0.01750888497279251, 0.1650825345160538, -0.2148810450151756, + -0.06090095222676627, 0.1073128739652992, 0.2584097661066967, + 0.02655484252908358, 0.1901297170957776, 0.3420822257932489, + 0.2531835106264871, 0.4022303494272352, -0.07805410188638827, + -0.1080255529483224, -0.1376217050758367, -0.1609000070073124, + -0.1740018618448228, 0.09827676798573926, 0.083291898217249, + 0.06127443921955168, 0.03526739273256396, 0.2991139104294396, + 0.2941068360088736, 0.2692865316145088, 0.4942032775296958, + 0.4857723178878524, 0.6512069539966677, -0.9161616153729886, + -0.9396953110011561, -0.9204280785344878, -0.8462030522374957, + -0.7293237120999879, -0.8470541513588044, -0.8482966176587544, + -0.7977006542517769, -0.6951661565374421, -0.566558592627622, + -0.7243096319272092, -0.6931460376496088, -0.6140043047773551, + -0.5016343691560573, -0.5520254073275178, -0.4928644880867128, + -0.403575153350467, -0.3587591578566765, -0.2886351685087218, + 0.5980613131647216, 0.5101532951859686, 0.382225843595672, + 0.2244622808787926, 0.06301334452030186, 0.6944632949786616, + 0.5955168212825119, 0.4473425940100297, 0.2700417838303327, + 0.7724043956082883, 0.6553545192922715, 0.4871408620353512, + 0.8097301284690857, 0.6725220182496192, 0.8002534097038426, + -0.4366431953633789, -0.5869882376922511, -0.7332080507197046, + -0.8450980113065225, -0.9041113586460733, -0.4022310083998925, + -0.554596445154436, -0.6925605687496104, -0.7854318984598006, + -0.8250621271173465, -0.3420827953668352, -0.4840440064641756, + -0.6033456975789954, -0.6777531805937266, -0.2584102557043402, + -0.3819753792546441, -0.4821906665520286, -0.1650828712784331, + -0.270790845781693, 0.9161619708326184, 0.9396956424389374, + 0.9204283182965946, 0.8462032095340455, 0.7293238793541417, + 0.9749588444840027, 0.9879501207294071, 0.942053498973333, + 0.8348196077814718, 0.9950795014807369, 0.9818515654328379, + 0.9027098746674149, 0.9581801446138297, 0.9118246030313639, + 0.8703772282258925, 0.1778171059718252, 0.06053992567271226, + -0.07929659020903117, -0.2226737578340799, -0.345825401239635, + 0.2886360377097776, 0.1672516508448342, 0.02000533874392893, + -0.1285435155191929, -0.2531843553864728, 0.403575906447316, + 0.2774342678683828, 0.1245598363284875, -0.02655554762561945, + 0.5016349858535857, 0.3695530582277636, 0.2148806720954671, + 0.5665590425344393, 0.431103930292903, 0.5869876102086139, + 0.7332077514676827, 0.845098078457225, 0.9041116580482536, + 0.7182616282077119, 0.8617334421407644, 0.9490975365686583, + 0.8223898048944452, 0.9416915744235097, 0.8729720010540123, + 0.1080256414522809, 0.1376220280275969, 0.1609005865750696, + 0.1740026689030255, 0.2707904196202965, 0.3196768235430837, + 0.3552546724685221, 0.3677018240803483, 0.3587598208776521, + 0.4821901792282771, 0.5389508449256169, 0.5637713635689835, + 0.5520258363563475, 0.6777529577987501, 0.7231337276202411, + 0.724309982145211, 0.8250622687013296, 0.8470545173149734, + 0.1285429999155006, -0.02000532948058562, -0.1672511147059996, + -0.1245600244829796, -0.2774338902981233, -0.3695528631494325, + -0.09827641615811868, -0.2700412859530667, -0.4473420975374328, + -0.5955164071695848, -0.6944629164413806, -0.2991130971968019, + -0.4871400501186961, -0.6553538941234454, -0.7724039524031648, + -0.4942022299541438, -0.6725212074710563, -0.8097296395344389, + -0.6512059956089504, -0.8002528392148971, -0.7580246814516085, + -0.3677014077761052, -0.3552545716101517, -0.3196770257819652, + -0.5637712030900536, -0.5389510214534028, -0.7231336172569296, + -0.8348194119106425, -0.9420533966954356, -0.9879499956150448, + -0.9749586635216289, -0.9027097279159257, -0.9818515951566739, + -0.9950795477220543, -0.9118244750171576, -0.9581802235578871, + -0.8703770126934449, -0.0175091339170676, 0.1501155140512474, + 0.3079660822386824, -0.1073133727582037, 0.06090046334304851, + -0.1901304002696938, -0.9490974969653682, -0.8617336589899791, + -0.7182621005240754, -0.5521276321758419, -0.941691783045487, + -0.8223901593137167, -0.6594093292610237, -0.872972144171723, + -0.7343999908188845, -0.7646691446910742, 0.6951665021597787, + 0.7977009700656229, 0.8482969664746548, 0.6140047811934269, + 0.6931464276818936, 0.4928650597255946, -0.4549467775084718, + -0.3173815862988101, -0.1591515620353438, -0.01030716362341688, + -0.5502140363721867, -0.3973395475484636, -0.2292777334167206, + -0.609656670182737, -0.4476455277450017, -0.6292139442700462, + 0.7854319364049284, 0.6925603649758249, 0.5545959620739339, + 0.6033453603619342, 0.4840435291285519, 0.3819748711371402, + -0.03526641653115874, -0.06127364342066123, -0.0832913202753871, + -0.2692854573778917, -0.2941058574917593, -0.4857712605383084, + -0.1282040992012934, 0.02998172476739921, 0.2130449739264662, + 0.394354771181159, 0.5438573645627299, 0.6488215902264565, + -0.1901340637026595, -0.02057293935230464, 0.1720544722828635, + 0.3534794142829396, 0.4950335464190314, -0.252933321812349, + -0.07636778766011496, 0.1169519253626288, 0.2909961752861106, + -0.304612640171253, -0.1271903099934383, 0.0580070042064605, + -0.3366056805211806, -0.1653138037361849, -0.3496821715684524, + 0.6714420577705413, 0.8002044514563711, 0.9106424580428781, + 0.9742808059046055, 0.9805708386415104, 0.9441720387917811, + 0.7350956003099328, 0.8682639008659977, 0.9653353535299492, + 0.9995536316680411, 0.9755844796257857, 0.7728091190204586, + 0.8918537226509272, 0.9597077065970592, 0.9637247890765801, + 0.767530944505584, 0.857374860312736, 0.8948082473172733, + 0.7201359303293944, 0.7802583897718675, -0.9441722324566724, + -0.8608166107545396, -0.7207644955095487, -0.5303678229575245, + -0.3211867088850157, -0.9096404828216634, -0.7967975927156801, + -0.620601831095295, -0.4039985827676406, -0.8241231220089414, + -0.6757043639889994, -0.4726959329165278, -0.6854057579633669, + -0.5106159168102177, -0.5164821811548767, -0.3130828685601688, + -0.128054626578418, 0.09418349997750548, 0.3239109228229815, + 0.523048087763098, -0.3043330399192493, -0.09531787499064681, + 0.146419102006115, 0.3786227553496849, 0.5638039035645359, + -0.2789925774668332, -0.05252850546893189, 0.1924160430438771, + 0.4101897544477446, -0.2358533016570041, -0.006318969895916147, + 0.2236016867495729, -0.1820659309330632, 0.03496843200875603, + -0.6714423515894649, -0.8002045390283683, -0.9106424117173109, + -0.9742807748705438, -0.9805709251787237, -0.6691519386893557, + -0.79626257796142, -0.8909109722488041, -0.9275521423149625, + -0.6332080201962388, -0.7430051304270751, -0.8108589038018792, + -0.5581290590099237, -0.6413705283620924, -0.4563600901355626, + -0.648822290296783, -0.6411378559950974, -0.600293640880965, + -0.5219527418637842, -0.4191009430775375, -0.7802586188950914, + -0.7711197529973893, -0.713538182957094, -0.6094980396194888, + -0.4842093859996422, -0.8948081394501657, -0.8705497953564927, + -0.7870195954857328, -0.6597854273844109, -0.9637246412193355, + -0.9132982945459158, -0.8070428410352181, -0.975584505681221, + -0.9015722073987464, 0.3130823317650696, 0.1280539101236855, + -0.09418429615654819, -0.3239116283455282, -0.523048586255087, + 0.1989845274738189, -0.01970764286946627, -0.2653151882168217, + -0.4936479477555078, 0.05597369301027853, -0.1852629737758222, + -0.4302072668465533, -0.09867461327158224, -0.3387557568094476, + -0.2393260112020272, 0.1282040764044601, -0.0299819504088954, + -0.2130455201840074, -0.3943555879655132, -0.5438582278251758, + -0.03496843048443223, -0.2252069693946209, -0.4261053308619027, + -0.5992598174372795, -0.720136706807033, -0.2236017161594696, + -0.4317330442416767, -0.6250530132529536, -0.7675317913865697, + -0.4101898771205939, -0.6101488498350025, -0.7728099228904255, + -0.5638041319099237, -0.7350961954485662, 0.6411372723067146, + 0.6002931843810706, 0.5219523372221417, 0.4191004905746099, + 0.4596949806286311, 0.3916338931244087, 0.2980734064957148, + 0.226741584116328, 0.1432114770939381, -0.02097489882147943, + 0.8608164411414747, 0.7207644427956729, 0.5303678926086439, + 0.3211867913977836, 0.9015721838250796, 0.7879881821713033, + 0.6114960278478284, 0.3951892122332402, 0.1820657113417612, + 0.8070430398170311, 0.6574928275930984, 0.4544842943197335, + 0.2358529185889448, 0.6597856586149884, 0.4841878538357612, + 0.2789921022280572, 0.4842093252521232, 0.3043325272261384, + 0.5992589358516202, 0.4261046359672609, 0.2252066549797059, + 0.6250522113657903, 0.4317325950511361, 0.6101482870567641, + 0.9096403689902206, 0.9275522217134882, 0.8909112253661301, + 0.796262827475376, 0.6691520068054228, 0.8241233338640371, + 0.810859375773786, 0.7430057321681839, 0.6332085061147845, + 0.6854064426268304, 0.6413714065577412, 0.5581299045184589, + 0.5164832226272315, 0.4563611494403301, 0.3496833143594963, + -0.3951892821849063, -0.6114960336943951, -0.787988199289983, + -0.4544844137443082, -0.657492739431111, -0.484187939006181, + 0.4936478319326018, 0.2653148405479006, 0.01970714938077021, + -0.1989850169013517, 0.4302075642722875, 0.1852629793843341, + -0.0559739158243807, 0.3387563694841473, 0.09867487876932232, + 0.2393267951217032, -0.999553621201999, -0.9653354239158236, + -0.8682642090770526, -0.9597077173597477, -0.8918540989344099, + -0.8573751662344773, -0.2980738893651726, -0.3916343988495664, + -0.4596955428592778, -0.4950341577852201, -0.1432117197792371, + -0.2267418620329016, -0.2909964852939082, 0.02097514873862574, + -0.05800679989935065, 0.1653145532988453, -0.3786231842883476, + -0.1464197032303796, 0.09531724619007391, -0.1924163631703616, + 0.05252803743712917, 0.006318730357784829, -0.3534800054422614, + -0.1720548071373146, 0.02057294660420643, 0.190134278339324, + -0.1169519894866824, 0.07636807502743861, 0.2529338262925594, + 0.1271908635410245, 0.3046134343217798, 0.3366066958443542, + 0.6094980941008995, 0.7135382519498201, 0.7711196978950583, + 0.7870198804193677, 0.8705500304441893, 0.9132984713369965, + 0.403998910419839, 0.62060207699311, 0.7967976318501995, + 0.4726965405256068, 0.6757048258462731, 0.5106167801856609]) - n = int(xyz.shape[0] / 3) - x = xyz[:n] - y = xyz[n:2 * n] - z = xyz[2 * n:] + n = int(xyz.shape[0] / 3) + x = xyz[:n] + y = xyz[n:2 * n] + z = xyz[2 * n:] - for i in range(n): - v = np.array([x[i], y[i], z[i]]) - norm = np.linalg.norm(v) - if norm > 0: - v /= norm - x[i] = v[0] - y[i] = v[1] - z[i] = v[2] + for i in range(n): + v = np.array([x[i], y[i], z[i]]) + norm = np.linalg.norm(v) + if norm > 0: + v /= norm + x[i] = v[0] + y[i] = v[1] + z[i] = v[2] - s = sphere.Sphere(x=x, y=y, z=z) - return s + s = sphere.Sphere(x=x, y=y, z=z) + return s -def fit_data(data, bvals, bvecs, model_type='3D-SHORE', calculate_peak_image=False): - """ Fits the defined model to the input dMRI and returns an MITK compliant ODF image. - """ + def fit_data(data, bvals, bvecs, model_type='3D-SHORE', calculate_peak_image=False): + """ Fits the defined model to the input dMRI and returns an MITK compliant ODF image. + """ - # create dipy Sphere - sphere = get_mitk_sphere() - odf = None - model = None - gtab = gradient_table(bvals, bvecs) + # create dipy Sphere + sphere = get_mitk_sphere() + odf = None + model = None + gtab = gradient_table(bvals, bvecs) - # fit selected model - if model_type == '3D-SHORE': - print('Fitting 3D-SHORE') - radial_order = 6 - zeta = 700 - lambdaN = 1e-8 - lambdaL = 1e-8 - model = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL) - asmfit = model.fit(data) - odf = asmfit.odf(sphere) - elif model_type == 'CSA-QBALL': - print('Fitting CSA-QBALL') - model = CsaOdfModel(gtab, 4) - odf = model.fit(data).odf(sphere) - odf = np.clip(odf, 0, np.max(odf, -1)[..., None]) - elif model_type == 'SFM': - print('Fitting SFM') - response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7) - model = sfm.SparseFascicleModel(gtab, sphere=sphere, - l1_ratio=0.5, alpha=0.001, - response=response[0]) - odf = model.fit(data).odf(sphere) - elif model_type == 'CSD': - print('Fitting CSD') - response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7) - model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=6) - odf = model.fit(data).odf(sphere) - else: - raise ValueError('Model type not supported. Available models: 3D-SHORE, CSA-QBALL, SFM, CSD') + # fit selected model + if model_type == '3D-SHORE': + print('Fitting 3D-SHORE') + print("radial_order: ", radial_order) + print("zeta: ", zeta) + print("lambdaN: ", lambdaN) + print("lambdaL: ", lambdaL) + model = ShoreModel(gtab, radial_order=radial_order, zeta=zeta, lambdaN=lambdaN, lambdaL=lambdaL) + asmfit = model.fit(data) + odf = asmfit.odf(sphere) + elif model_type == 'CSA-QBALL': + print('Fitting CSA-QBALL') + print("sh_order: ", sh_order) + print("smooth: ", smooth) + model = CsaOdfModel(gtab=gtab, sh_order=sh_order, smooth=smooth) + odf = model.fit(data).odf(sphere) + odf = np.clip(odf, 0, np.max(odf, -1)[..., None]) + elif model_type == 'SFM': + print('Fitting SFM') + print("fa_thr: ", fa_thr) + response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=fa_thr) + model = sfm.SparseFascicleModel(gtab, sphere=sphere, + l1_ratio=0.5, alpha=0.001, + response=response[0]) + odf = model.fit(data).odf(sphere) + elif model_type == 'CSD': + print('Fitting CSD') + print("sh_order: ", sh_order) + print("fa_thr: ", fa_thr) + response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=fa_thr) + model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=sh_order) + odf = model.fit(data).odf(sphere) + elif model_type == 'Opdt': + print('Orientation Probability Density Transform') + print("sh_order: ", sh_order) + print("smooth: ", smooth) + model = OpdtModel(gtab=gtab, sh_order=sh_order, smooth=smooth) + odf = model.fit(data).odf(sphere) + else: + raise ValueError('Model type not supported. Available models: 3D-SHORE, CSA-QBALL, SFM, CSD, Opdt') - print('Preparing ODF image') - # swap axes to obtain MITK compliant format. - # odf = odf.swapaxes(3, 2) - # odf = odf.swapaxes(2, 1) - # odf = odf.swapaxes(1, 0) + print('Preparing ODF image') + odf_image = sitk.Image([data.shape[2], data.shape[1], data.shape[0]], sitk.sitkVectorFloat32, len(sphere.vertices)) + for x in range(data.shape[2]): + for y in range(data.shape[1]): + for z in range(data.shape[0]): + odf_image.SetPixel(x, y, z, odf[z, y, x, :]) - odf_image = sitk.Image([data.shape[2], data.shape[1], data.shape[0]], sitk.sitkVectorFloat32, len(sphere.vertices)) - for x in range(data.shape[2]): - for y in range(data.shape[1]): - for z in range(data.shape[0]): - odf_image.SetPixel(x,y,z, odf[z,y,x,:]) + # if not calculate_peak_image: + return odf_image, None - # if not calculate_peak_image: - return odf_image, None + # # calculate peak image + # sf_peaks = dpp.peaks_from_model(model, + # data, + # sphere, + # relative_peak_threshold=.4, + # min_separation_angle=15, + # return_sh=False, npeaks=5, parallel=True) + # + # # reshape to be MITK/MRtrix compliant + # s = sf_peaks.peak_dirs.shape + # peaks = sf_peaks.peak_dirs.reshape((s[0], s[1], s[2], s[3] * s[4]), order='C') + # + # # scale peaks + # for x in range(s[0]): + # for y in range(s[1]): + # for z in range(s[2]): + # for i in range(3): + # peaks[x, y, z, i * 3] *= sf_peaks.peak_values[x, y, z, i] + # peaks[x, y, z, i * 3 + 1] *= sf_peaks.peak_values[x, y, z, i] + # peaks[x, y, z, i * 3 + 2] *= sf_peaks.peak_values[x, y, z, i] + # + # peaks = peaks.astype('float32') + # return odf_image, peaks - # # calculate peak image - # sf_peaks = dpp.peaks_from_model(model, - # data, - # sphere, - # relative_peak_threshold=.4, - # min_separation_angle=15, - # return_sh=False, npeaks=5, parallel=True) - # - # # reshape to be MITK/MRtrix compliant - # s = sf_peaks.peak_dirs.shape - # peaks = sf_peaks.peak_dirs.reshape((s[0], s[1], s[2], s[3] * s[4]), order='C') - # - # # scale peaks - # for x in range(s[0]): - # for y in range(s[1]): - # for z in range(s[2]): - # for i in range(3): - # peaks[x, y, z, i * 3] *= sf_peaks.peak_values[x, y, z, i] - # peaks[x, y, z, i * 3 + 1] *= sf_peaks.peak_values[x, y, z, i] - # peaks[x, y, z, i * 3 + 2] *= sf_peaks.peak_values[x, y, z, i] - # - # peaks = peaks.astype('float32') - # return odf_image, peaks + print('DIPY Reconstructions') + data = sitk.GetArrayFromImage(in_image) + bvals = np.array(bvals) + bvecs = np.array(bvecs) -print('DIPY Reconstructions') -data = sitk.GetArrayFromImage(in_image) -bvals = np.array(bvals) -bvecs = np.array(bvecs) + odf_image, peaks = fit_data(data=data, bvals=bvals, bvecs=bvecs, model_type=model_type, calculate_peak_image=calculate_peak_image) -odf_image, peaks = fit_data(data=data, bvals=bvals, bvecs=bvecs, model_type=model_type, calculate_peak_image=calculate_peak_image) - -odf_image.SetOrigin(in_image.GetOrigin()) -odf_image.SetSpacing(in_image.GetSpacing()) -odf_image.SetDirection(in_image.GetDirection()) + odf_image.SetOrigin(in_image.GetOrigin()) + odf_image.SetSpacing(in_image.GetSpacing()) + odf_image.SetDirection(in_image.GetDirection()) +except Exception as e: + error_string = str(e) + print(error_string) diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp index 70d1c9140b..58b03e509d 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkBrainExtractionView.cpp @@ -1,224 +1,250 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //misc #define _USE_MATH_DEFINES #include // Blueberry #include #include // Qmitk #include "QmitkBrainExtractionView.h" // MITK #include // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #define _USE_MATH_DEFINES #include typedef itksys::SystemTools ist; const std::string QmitkBrainExtractionView::VIEW_ID = "org.mitk.views.brainextraction"; QmitkBrainExtractionView::QmitkBrainExtractionView() : QmitkAbstractView() , m_Controls( 0 ) , m_DiffusionImage( nullptr ) { } // Destructor QmitkBrainExtractionView::~QmitkBrainExtractionView() { } void QmitkBrainExtractionView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkBrainExtractionViewControls; m_Controls->setupUi( parent ); connect( m_Controls->m_ImageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateGUI()) ); connect( m_Controls->m_StartButton, SIGNAL(clicked()), this, SLOT(StartBrainExtraction()) ); this->m_Parent = parent; m_Controls->m_ImageBox->SetDataStorage(this->GetDataStorage()); mitk::NodePredicateDimension::Pointer dimPred = mitk::NodePredicateDimension::New(3); mitk::TNodePredicateDataType::Pointer isImagePredicate = mitk::TNodePredicateDataType::New(); m_Controls->m_ImageBox->SetPredicate(isImagePredicate); UpdateGUI(); } } void QmitkBrainExtractionView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& ) { } void QmitkBrainExtractionView::UpdateGUI() { if (m_Controls->m_ImageBox->GetSelectedNode().IsNotNull()) m_Controls->m_StartButton->setEnabled(true); else m_Controls->m_StartButton->setEnabled(false); } void QmitkBrainExtractionView::SetFocus() { UpdateGUI(); m_Controls->m_StartButton->setFocus(); } std::string QmitkBrainExtractionView::GetPythonFile(std::string filename) { std::string out = ""; - std::string bet_dir = std::string(BetData_DIR); - - if ( ist::FileExists(bet_dir + filename) ) - out = bet_dir + filename; - else - { - for (auto dir : mitk::bet::search_dirs) - if ( ist::FileExists( ist::GetCurrentWorkingDirectory() + dir + filename) ) - { - out = ist::GetCurrentWorkingDirectory() + dir + filename; - break; - } - } + for (auto dir : mitk::bet::relative_search_dirs) + if ( ist::FileExists( ist::GetCurrentWorkingDirectory() + dir + filename) ) + { + out = ist::GetCurrentWorkingDirectory() + dir + filename; + return out; + } + for (auto dir : mitk::bet::absolute_search_dirs) + if ( ist::FileExists( dir + filename) ) + { + out = dir + filename; + return out; + } return out; } void QmitkBrainExtractionView::StartBrainExtraction() { mitk::DataNode::Pointer node = m_Controls->m_ImageBox->GetSelectedNode(); mitk::Image::Pointer mitk_image = dynamic_cast(node->GetData()); bool missing_file = false; std::string missing_file_string = ""; if ( GetPythonFile("run_mitk.py").empty() ) { missing_file_string += "Brain extraction script file missing: run_mitk.py\n\n"; missing_file = true; } if ( GetPythonFile("model_final.model").empty() ) { missing_file_string += "Brain extraction model file missing: model_final.model\n\n"; missing_file = true; } if ( GetPythonFile("basic_config_just_like_braintumor.py").empty() ) { missing_file_string += "Config file missing: basic_config_just_like_braintumor.py\n\n"; missing_file = true; } if (missing_file) { QMessageBox::warning(nullptr, "Error", (missing_file_string).c_str(), QMessageBox::Ok); return; } try { us::ModuleContext* context = us::GetModuleContext(); us::ServiceReference m_PythonServiceRef = context->GetServiceReference(); mitk::IPythonService* m_PythonService = dynamic_cast ( context->GetService(m_PythonServiceRef) ); mitk::IPythonService::ForceLoadModule(); - std::string pythonpath = std::string(BetData_DIR); - for (auto dir : mitk::bet::search_dirs) - pythonpath += "','" + ist::GetCurrentWorkingDirectory() + dir; - + // load essential modules m_PythonService->Execute("import SimpleITK as sitk"); m_PythonService->Execute("import SimpleITK._SimpleITK as _SimpleITK"); m_PythonService->Execute("import numpy"); - m_PythonService->CopyToPythonAsSimpleItkImage( mitk_image, "in_image"); + + // extend python search path + std::string pythonpath = ""; + for (auto dir : mitk::bet::relative_search_dirs) + pythonpath += "','" + ist::GetCurrentWorkingDirectory() + dir; + for (auto dir : mitk::bet::absolute_search_dirs) + pythonpath += "','" + dir; m_PythonService->Execute("paths=['"+pythonpath+"']"); + + // set input files (model and config) m_PythonService->Execute("model_file=\""+GetPythonFile("model_final.model")+"\""); m_PythonService->Execute("config_file=\""+GetPythonFile("basic_config_just_like_braintumor.py")+"\""); + + // copy input image to python + m_PythonService->CopyToPythonAsSimpleItkImage( mitk_image, "in_image"); + + // run segmentation script m_PythonService->ExecuteScript( GetPythonFile("run_mitk.py") ); + // clean up after running script (better way than deleting individual variables?) + if(m_PythonService->DoesVariableExist("in_image")) + m_PythonService->Execute("del in_image"); + + // check for errors + if(!m_PythonService->GetVariable("error_string").empty()) { - mitk::Image::Pointer image = m_PythonService->CopySimpleItkImageFromPython("brain_mask"); - mitk::DataNode::Pointer corrected_node = mitk::DataNode::New(); - corrected_node->SetData( image ); - QString name(node->GetName().c_str()); - name += "_BrainMask"; - corrected_node->SetName(name.toStdString()); - GetDataStorage()->Add(corrected_node, node); + QMessageBox::warning(nullptr, "Error", QString(m_PythonService->GetVariable("error_string").c_str()), QMessageBox::Ok); + return; } - { - mitk::Image::Pointer image = m_PythonService->CopySimpleItkImageFromPython("brain_extracted"); + // get output images and add to datastorage + std::string output_variables = m_PythonService->GetVariable("output_variables"); + std::vector outputs; + boost::split(outputs, output_variables, boost::is_any_of(",")); + + std::string output_types = m_PythonService->GetVariable("output_types"); + std::vector types; + boost::split(types, output_types, boost::is_any_of(",")); - if(mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(mitk_image)) + for (unsigned int i=0; iDoesVariableExist(outputs.at(i))) { - mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, image, true); - mitk::DiffusionPropertyHelper::InitializeImage(image); + mitk::Image::Pointer image = m_PythonService->CopySimpleItkImageFromPython(outputs.at(i)); + + if(types.at(i)=="input" && mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(mitk_image)) + { + mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, image, true); + mitk::DiffusionPropertyHelper::InitializeImage(image); + } + + mitk::DataNode::Pointer corrected_node = mitk::DataNode::New(); + corrected_node->SetData( image ); + std::string name = node->GetName(); + name += "_"; + name += outputs.at(i); + corrected_node->SetName(name); + GetDataStorage()->Add(corrected_node, node); + m_PythonService->Execute("del " + outputs.at(i)); + + mitk::RenderingManager::GetInstance()->InitializeViews( corrected_node->GetData()->GetTimeGeometry(), + mitk::RenderingManager::REQUEST_UPDATE_ALL, + true); } - - mitk::DataNode::Pointer corrected_node = mitk::DataNode::New(); - corrected_node->SetData( image ); - QString name(node->GetName().c_str()); - name += "_SkullStripped"; - corrected_node->SetName(name.toStdString()); - GetDataStorage()->Add(corrected_node, node); - - mitk::RenderingManager::GetInstance()->InitializeViews( corrected_node->GetData()->GetTimeGeometry(), - mitk::RenderingManager::REQUEST_UPDATE_ALL, - true); } } catch(...) { QMessageBox::warning(nullptr, "Error", "File could not be processed.\nIs pytorch installed on your system?\nDoes your script use the correct input and output variable names (in: in_image & model, out: brain_mask & brain_extracted)?", QMessageBox::Ok); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsView.cpp index 1f1d91f809..93cacc770b 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsView.cpp @@ -1,195 +1,260 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkDipyReconstructionsView.h" #include #include #include #include #include #include #include #include #include #include const std::string QmitkDipyReconstructionsView::VIEW_ID = "org.mitk.views.dipyreconstruction"; QmitkDipyReconstructionsView::QmitkDipyReconstructionsView() : QmitkAbstractView() , m_Controls( 0 ) { } // Destructor QmitkDipyReconstructionsView::~QmitkDipyReconstructionsView() { } void QmitkDipyReconstructionsView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkDipyReconstructionsViewControls; m_Controls->setupUi( parent ); connect( m_Controls->m_ImageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateGUI()) ); connect( m_Controls->m_StartButton, SIGNAL(clicked()), this, SLOT(StartFit()) ); + connect( m_Controls->m_ModelBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateGUI()) ); this->m_Parent = parent; m_Controls->m_ImageBox->SetDataStorage(this->GetDataStorage()); mitk::NodePredicateIsDWI::Pointer isDwi = mitk::NodePredicateIsDWI::New(); m_Controls->m_ImageBox->SetPredicate( isDwi ); UpdateGUI(); } } void QmitkDipyReconstructionsView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& ) { } void QmitkDipyReconstructionsView::UpdateGUI() { if (m_Controls->m_ImageBox->GetSelectedNode().IsNotNull()) m_Controls->m_StartButton->setEnabled(true); else m_Controls->m_StartButton->setEnabled(false); + + m_Controls->m_ShoreBox->setVisible(false); + m_Controls->m_SfmBox->setVisible(false); + m_Controls->m_CsdBox->setVisible(false); + m_Controls->m_CsaBox->setVisible(false); + m_Controls->m_OpdtBox->setVisible(false); + switch(m_Controls->m_ModelBox->currentIndex()) + { + case 0: + { + m_Controls->m_ShoreBox->setVisible(true); + break; + } + case 1: + { + m_Controls->m_SfmBox->setVisible(true); + break; + } + case 2: + { + m_Controls->m_CsdBox->setVisible(true); + break; + } + case 3: + { + m_Controls->m_CsaBox->setVisible(true); + break; + } + case 4: + { + m_Controls->m_OpdtBox->setVisible(true); + break; + } + } } void QmitkDipyReconstructionsView::SetFocus() { UpdateGUI(); m_Controls->m_StartButton->setFocus(); } void QmitkDipyReconstructionsView::StartFit() { mitk::DataNode::Pointer node = m_Controls->m_ImageBox->GetSelectedNode(); mitk::Image::Pointer input_image = dynamic_cast(node->GetData()); - try + // get python script as string + QString data; + QString fileName(":/QmitkDiffusionImaging/dipy_reconstructions.py"); + QFile file(fileName); + if(!file.open(QIODevice::ReadOnly)) { + qDebug()<<"filenot opened"<Size(); ++i) - { - bvals += boost::lexical_cast(bvaluevector.at(i)); - if (bvaluevector.at(i)==0) - b0_count++; - auto g = gcont->GetElement(i); - - if (g.two_norm()>0.000001) - g /= g.two_norm(); - bvecs += "[" + boost::lexical_cast(g[0]) + "," + boost::lexical_cast(g[1]) + "," + boost::lexical_cast(g[2]) + "]"; - - if (iSize()-1) - { - bvals += ", "; - bvecs += ", "; - } - } - bvals += "]"; - bvecs += "]"; - if (b0_count==0) - { - QMessageBox::warning(nullptr, "Error", "No b=0 volume found. Do your b-values need rounding? Use the Preprocessing View for rounding b-values,", QMessageBox::Ok); - return; - } + qDebug()<<"file opened"<Size(); ++i) + { + bvals += boost::lexical_cast(bvaluevector.at(i)); + if (bvaluevector.at(i)==0) + b0_count++; + auto g = gcont->GetElement(i); - us::ModuleContext* context = us::GetModuleContext(); - us::ServiceReference m_PythonServiceRef = context->GetServiceReference(); - mitk::IPythonService* m_PythonService = dynamic_cast ( context->GetService(m_PythonServiceRef) ); - mitk::IPythonService::ForceLoadModule(); + if (g.two_norm()>0.000001) + g /= g.two_norm(); + bvecs += "[" + boost::lexical_cast(g[0]) + "," + boost::lexical_cast(g[1]) + "," + boost::lexical_cast(g[2]) + "]"; - m_PythonService->Execute("import SimpleITK as sitk"); - m_PythonService->Execute("import SimpleITK._SimpleITK as _SimpleITK"); - m_PythonService->Execute("import numpy"); - m_PythonService->CopyToPythonAsSimpleItkImage( input_image, "in_image"); - std::string model = "3D-SHORE"; - switch(m_Controls->m_ModelBox->currentIndex()) + if (iSize()-1) { - case 0: - model = "3D-SHORE"; - break; - case 1: - model = "SFM"; - break; - case 2: - model = "CSD"; - break; - case 3: - model = "CSA-QBALL"; - break; + bvals += ", "; + bvecs += ", "; } - m_PythonService->Execute("model_type='"+model+"'"); - m_PythonService->Execute("calculate_peak_image=False"); - m_PythonService->Execute("data=False"); - m_PythonService->Execute("bvals=" + bvals); - m_PythonService->Execute("bvecs=" + bvecs); - m_PythonService->Execute(data.toStdString(), mitk::IPythonService::MULTI_LINE_COMMAND); + } + bvals += "]"; + bvecs += "]"; + if (b0_count==0) + { + QMessageBox::warning(nullptr, "Error", "No b=0 volume found. Do your b-values need rounding? Use the Preprocessing View for rounding b-values,", QMessageBox::Ok); + return; + } - { - mitk::OdfImage::ItkOdfImageType::Pointer itkImg = mitk::OdfImage::ItkOdfImageType::New(); - mitk::Image::Pointer out_image = m_PythonService->CopySimpleItkImageFromPython("odf_image"); - mitk::CastToItkImage(out_image, itkImg); + us::ModuleContext* context = us::GetModuleContext(); + us::ServiceReference m_PythonServiceRef = context->GetServiceReference(); + mitk::IPythonService* m_PythonService = dynamic_cast ( context->GetService(m_PythonServiceRef) ); + mitk::IPythonService::ForceLoadModule(); - mitk::OdfImage::Pointer image = mitk::OdfImage::New(); - image->InitializeByItk( itkImg.GetPointer() ); - image->SetVolume( itkImg->GetBufferPointer() ); + m_PythonService->Execute("import SimpleITK as sitk"); + m_PythonService->Execute("import SimpleITK._SimpleITK as _SimpleITK"); + m_PythonService->Execute("import numpy"); + m_PythonService->CopyToPythonAsSimpleItkImage( input_image, "in_image"); + std::string model = "3D-SHORE"; + switch(m_Controls->m_ModelBox->currentIndex()) + { + case 0: + { + model = "3D-SHORE"; + m_PythonService->Execute("radial_order=" + boost::lexical_cast(m_Controls->m_RadialOrder->value())); + m_PythonService->Execute("zeta=" + boost::lexical_cast(m_Controls->m_Zeta->value())); + m_PythonService->Execute("lambdaN=" + m_Controls->m_LambdaN->text().toStdString()); + m_PythonService->Execute("lambdaL=" + m_Controls->m_LambdaL->text().toStdString()); + break; + } + case 1: + { + model = "SFM"; + m_PythonService->Execute("fa_thr=" + boost::lexical_cast(m_Controls->m_FaThresholdSfm->value())); + break; + } + case 2: + { + model = "CSD"; + m_PythonService->Execute("sh_order=" + boost::lexical_cast(m_Controls->m_ShOrderCsd->value())); + m_PythonService->Execute("fa_thr=" + boost::lexical_cast(m_Controls->m_FaThresholdCsd->value())); + break; + } + case 3: + { + model = "CSA-QBALL"; + m_PythonService->Execute("sh_order=" + boost::lexical_cast(m_Controls->m_ShOrderCsa->value())); + m_PythonService->Execute("smooth=" + boost::lexical_cast(m_Controls->m_LambdaCsa->value())); + break; + } + case 4: + { + model = "Opdt"; + m_PythonService->Execute("sh_order=" + boost::lexical_cast(m_Controls->m_ShOrderOpdt->value())); + m_PythonService->Execute("smooth=" + boost::lexical_cast(m_Controls->m_LambdaOpdt->value())); + break; + } + } + m_PythonService->Execute("model_type='"+model+"'"); + m_PythonService->Execute("calculate_peak_image=False"); + m_PythonService->Execute("data=False"); + m_PythonService->Execute("bvals=" + bvals); + m_PythonService->Execute("bvecs=" + bvecs); + m_PythonService->Execute(data.toStdString(), mitk::IPythonService::MULTI_LINE_COMMAND); - mitk::DataNode::Pointer odfs = mitk::DataNode::New(); - odfs->SetData( image ); - QString name(node->GetName().c_str()); - odfs->SetName(name.toStdString() + "_" + model); - GetDataStorage()->Add(odfs, node); - } + // clean up after running script (better way than deleting individual variables?) + if(m_PythonService->DoesVariableExist("in_image")) + m_PythonService->Execute("del in_image"); + + // check for errors + if(!m_PythonService->GetVariable("error_string").empty()) + { + QMessageBox::warning(nullptr, "Error", QString(m_PythonService->GetVariable("error_string").c_str()), QMessageBox::Ok); + return; } - catch(...) + + if (m_PythonService->DoesVariableExist("odf_image")) { - QMessageBox::warning(nullptr, "Error", "File could not be processed.\nIs pytorch installed on your system?\nDoes your script use the correct input and output variable names (in: in_image & model, out: brain_mask & brain_extracted)?", QMessageBox::Ok); + mitk::OdfImage::ItkOdfImageType::Pointer itkImg = mitk::OdfImage::ItkOdfImageType::New(); + + mitk::Image::Pointer out_image = m_PythonService->CopySimpleItkImageFromPython("odf_image"); + mitk::CastToItkImage(out_image, itkImg); + + mitk::OdfImage::Pointer image = mitk::OdfImage::New(); + image->InitializeByItk( itkImg.GetPointer() ); + image->SetVolume( itkImg->GetBufferPointer() ); + + mitk::DataNode::Pointer odfs = mitk::DataNode::New(); + odfs->SetData( image ); + QString name(node->GetName().c_str()); + odfs->SetName(name.toStdString() + "_" + model); + GetDataStorage()->Add(odfs, node); + m_PythonService->Execute("del odf_image"); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsViewControls.ui b/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsViewControls.ui index 8d485d3edc..70b1251024 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsViewControls.ui +++ b/Plugins/org.mitk.gui.qt.diffusionimaging.python/src/internal/QmitkDipyReconstructionsViewControls.ui @@ -1,128 +1,551 @@ QmitkDipyReconstructionsViewControls 0 0 435 - 744 + 803 Form QCommandLinkButton:disabled { border: none; } QGroupBox { background-color: transparent; } - - - - false - - - - - - Start Reconstruction - - - - + + 25 + + Qt::Vertical 20 40 + + + + Constrained Spherical Deconvolution Parameters + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + SH Order: + + + + + + + QFrame::NoFrame + + + QFrame::Raised + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + 2 + + + 100 + + + 2 + + + 6 + + + + + + + FA Threshold: + + + + + + + 3 + + + 1.000000000000000 + + + 0.100000000000000 + + + 0.700000000000000 + + + + + + + + + + Sparse Fascicle Model Parameters + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + FA Threshold: + + + + + + + 3 + + + 1.000000000000000 + + + 0.100000000000000 + + + 0.700000000000000 + + + + + + + + + + 3D-SHORE Parameters + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + 2 + + + 100 + + + 2 + + + 6 + + + + + + + Zeta: + + + + + + + Radial Order: + + + + + + + LambdaN: + + + + + + + LambdaL: + + + + + + + 9999 + + + 700 + + + + + + + 1e-8 + + + + + + + 1e-8 + + + + + + QFrame::NoFrame QFrame::Raised 0 0 0 0 Input Image: Model: 3D-SHORE Sparse Fascicle Model Constrained Spherical Deconvolution CSA-QBALL + + + Orientation Probability Density Transform + + + + + + + + + + + CSA-QBALL Parameters + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + QFrame::NoFrame + + + QFrame::Raised + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + 2 + + + 100 + + + 2 + + + 6 + + + + + + + Lambda: + + + + + + + SH Order: + + + + + + + 4 + + + 1.000000000000000 + + + 0.001000000000000 + + + 0.006000000000000 + + + + + + + + + + false + + + + + + Start Reconstruction + + + + + + + Orientation Probability Density Transform Parameters + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + QFrame::NoFrame + + + QFrame::Raised + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + 2 + + + 100 + + + 2 + + + 6 + + + + + + + Lambda: + + + + + + + SH Order: + + + + + + + 4 + + + 1.000000000000000 + + + 0.001000000000000 + + + 0.006000000000000 + QmitkDataStorageComboBox QComboBox -
QmitkDataStorageComboBox.h
+
QmitkDataStorageComboBox.h