diff --git a/BlueBerry/CMake/berryCTKQtHelpDoxygen.conf.in b/BlueBerry/CMake/berryCTKQtHelpDoxygen.conf.in index 6b29f8d63e..ae54ff6e47 100644 --- a/BlueBerry/CMake/berryCTKQtHelpDoxygen.conf.in +++ b/BlueBerry/CMake/berryCTKQtHelpDoxygen.conf.in @@ -1,1802 +1,1805 @@ # Doxyfile 1.8.0 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = "@Plugin-Name@" # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = "@PLUGIN_DOXYGEN_OUTPUT_DIR@" # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = bundlemainpage{1}=\mainpage \ "isHtml=\if NO_SUCH_THING" \ - "isHtmlend=\endif" + "isHtmlend=\endif" \ + "imageMacro{3}=\image html \1 \2 \n \image latex \1 \2 width=\3cm" \ + "developersguidemainpage{1}=\page \1 " \ + "usersguidemainpage{1}=\page \1 " # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all # comments according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you # can mix doxygen, HTML, and XML commands with Markdown formatting. # Disable only in case of backward compatibilities issues. MARKDOWN_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES all members with package or internal scope will be included in the documentation. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = NO # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = NO # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = NO # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= NO # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = NO # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = "@PLUGIN_DOXYGEN_INPUT_DIR@" # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.dox # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = "@PLUGIN_DOXYGEN_INPUT_DIR@" # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = YES # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 3 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # style sheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = YES # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = @Plugin-SymbolicName@ # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = bundle # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = @PLUGIN_QHP_CUST_FILTER_NAME@ # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = @PLUGIN_QHP_CUST_FILTER_ATTRS@ # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = @PLUGIN_QHP_SECT_FILTER_ATTRS@ # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from http://www.mathjax.org before deployment. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = NO # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a PHP enabled web server instead of at the web client # using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server # based approach is that it scales better to large projects and allows # full text search. The disadvantages are that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. For each # tag file the location of the external documentation should be added. The # format of a tag file without this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths # or URLs. Note that each tag file must have a unique name (where the name does # NOT include the path). If a tag file is not located in the directory in which # doxygen is run, you must also specify the path to the tagfile here. TAGFILES = @PLUGIN_DOXYGEN_TAGFILES@ # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = "@PLUGIN_DOXYGEN_OUTPUT_DIR@/@PROJECT_NAME@.tag" # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 0 # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = FreeSans # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If the UML_LOOK tag is enabled, the fields and methods are shown inside # the class node. If there are many fields or methods and many nodes the # graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS # threshold limits the number of items for each type to make the size more # managable. Set this to 0 for no limit. Note that the threshold may be # exceeded by 50% before the limit is enforced. UML_LIMIT_NUM_FIELDS = 10 # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES diff --git a/CMake/MITKDashboardSetup.cmake b/CMake/MITKDashboardSetup.cmake index dcf4a81171..deeafef9aa 100644 --- a/CMake/MITKDashboardSetup.cmake +++ b/CMake/MITKDashboardSetup.cmake @@ -1,159 +1,170 @@ # This file is intended to be included at the end of a custom MITKDashboardScript.TEMPLATE.cmake file list(APPEND CTEST_NOTES_FILES "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") # # Automatically determined properties # set(MY_OPERATING_SYSTEM "${CMAKE_HOST_SYSTEM}") # Windows 7, Linux-2.6.32, Darwin... site_name(CTEST_SITE) -if(QT_BINARY_DIR) - set(QT_QMAKE_EXECUTABLE "${QT_BINARY_DIR}/qmake") -else() - set(QT_QMAKE_EXECUTABLE "qmake") +if(NOT DEFINED MITK_USE_QT) + set(MITK_USE_QT 1) endif() -execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} --version - OUTPUT_VARIABLE MY_QT_VERSION - RESULT_VARIABLE qmake_error) -if(qmake_error) - message(FATAL_ERROR "Error when executing ${QT_QMAKE_EXECUTABLE} --version\n${qmake_error}") -endif() +if(MITK_USE_QT) + if(QT_BINARY_DIR) + set(QT_QMAKE_EXECUTABLE "${QT_BINARY_DIR}/qmake") + else() + set(QT_QMAKE_EXECUTABLE "qmake") + endif() + + execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} --version + OUTPUT_VARIABLE MY_QT_VERSION + RESULT_VARIABLE qmake_error) + if(qmake_error) + message(FATAL_ERROR "Error when executing ${QT_QMAKE_EXECUTABLE} --version\n${qmake_error}") + endif() -string(REGEX REPLACE ".*Qt version ([0-9.]+) .*" "\\1" MY_QT_VERSION ${MY_QT_VERSION}) + string(REGEX REPLACE ".*Qt version ([0-9.]+) .*" "\\1" MY_QT_VERSION ${MY_QT_VERSION}) +endif() # # Project specific properties # if(NOT CTEST_BUILD_NAME) - set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM}-${MY_COMPILER}-Qt-${MY_QT_VERSION}-${CTEST_BUILD_CONFIGURATION}") + if(MITK_USE_QT) + set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM}-${MY_COMPILER}-Qt-${MY_QT_VERSION}-${CTEST_BUILD_CONFIGURATION}") + else() + set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM}-${MY_COMPILER}-${CTEST_BUILD_CONFIGURATION}") + endif() endif() set(PROJECT_BUILD_DIR "MITK-build") set(CTEST_PATH "$ENV{PATH}") if(WIN32) set(ANN_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ANN-build/${CTEST_BUILD_CONFIGURATION}") set(CPPUNIT_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/CppUnit-build/${CTEST_BUILD_CONFIGURATION}") set(GLUT_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/GLUT-build/${CTEST_BUILD_CONFIGURATION}") set(GLEW_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/GLEW-build/${CTEST_BUILD_CONFIGURATION}") set(TINYXML_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/tinyxml-build/${CTEST_BUILD_CONFIGURATION}") set(QWT_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Qwt-build/${CTEST_BUILD_CONFIGURATION}") set(QXT_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Qxt-build/${CTEST_BUILD_CONFIGURATION}") set(VTK_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/VTK-build/bin/${CTEST_BUILD_CONFIGURATION}") set(ACVD_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ACVD-build/bin/${CTEST_BUILD_CONFIGURATION}") set(ITK_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ITK-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BOOST_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Boost-install/lib") set(GDCM_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/GDCM-build/bin/${CTEST_BUILD_CONFIGURATION}") set(OPENCV_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/OpenCV-build/bin/${CTEST_BUILD_CONFIGURATION}") set(POCO_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/Poco-install/lib") set(SOFA_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/SOFA-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BLUEBERRY_OSGI_DIR "${CTEST_BINARY_DIRECTORY}/MITK-build/bin/BlueBerry/org.blueberry.osgi/bin/${CTEST_BUILD_CONFIGURATION}") set(CTEST_PATH "${CTEST_PATH};${CPPUNIT_BINARY_DIR};${QT_BINARY_DIR};${VTK_BINARY_DIR};${ANN_BINARY_DIR};${GLUT_BINARY_DIR};${GLEW_BINARY_DIR};${TINYXML_BINARY_DIR};${QWT_BINARY_DIR};${QXT_BINARY_DIR};${ACVD_BINARY_DIR};${ITK_BINARY_DIR};${BOOST_BINARY_DIR};${GDCM_BINARY_DIR};${OPENCV_BINARY_DIR};${POCO_BINARY_DIR};${SOFA_BINARY_DIR};${BLUEBERRY_OSGI_DIR}") endif() set(ENV{PATH} "${CTEST_PATH}") set(SUPERBUILD_TARGETS "") # If the dashscript doesn't define a GIT_REPOSITORY variable, let's define it here. if(NOT DEFINED GIT_REPOSITORY OR GIT_REPOSITORY STREQUAL "") set(GIT_REPOSITORY "http://git.mitk.org/MITK.git") endif() # # Display build info # message("Site name: ${CTEST_SITE}") message("Build name: ${CTEST_BUILD_NAME}") message("Script Mode: ${SCRIPT_MODE}") message("Coverage: ${WITH_COVERAGE}, MemCheck: ${WITH_MEMCHECK}") # # Set initial cache options # if(${CMAKE_VERSION} VERSION_GREATER "2.8.9") set(CTEST_USE_LAUNCHERS 1) set(ENV{CTEST_USE_LAUNCHERS_DEFAULT} 1) endif() # Remove this if block after all dartclients work if(DEFINED ADDITIONNAL_CMAKECACHE_OPTION) message(WARNING "Rename ADDITIONNAL to ADDITIONAL in your dartlclient script: ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") set(ADDITIONAL_CMAKECACHE_OPTION ${ADDITIONNAL_CMAKECACHE_OPTION}) endif() if(NOT DEFINED MITK_USE_ACVD) set(MITK_USE_ACVD 1) endif() if(NOT DEFINED MITK_USE_Boost) set(MITK_USE_Boost 1) endif() if(NOT DEFINED MITK_USE_OpenCV) set(MITK_USE_OpenCV 1) endif() if(NOT DEFINED MITK_USE_Poco) set(MITK_USE_Poco 1) endif() if(NOT DEFINED MITK_USE_SOFA) set(MITK_USE_SOFA 1) endif() if(NOT DEFINED MITK_BUILD_ALL_APPS) set(MITK_BUILD_ALL_APPS TRUE) endif() if(NOT DEFINED BLUEBERRY_BUILD_ALL_PLUGINS) set(BLUEBERRY_BUILD_ALL_PLUGINS TRUE) endif() if(NOT DEFINED MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS TRUE) endif() if(NOT DEFINED MITK_BUILD_EXAMPLES) set(MITK_BUILD_EXAMPLES TRUE) endif() if(NOT BUILD_DiffusionMiniApps) set(BUILD_DiffusionMiniApps TRUE) endif() set(INITIAL_CMAKECACHE_OPTIONS " BLUEBERRY_BUILD_ALL_PLUGINS:BOOL=${MITK_BUILD_ALL_PLUGINS} MITK_BUILD_ALL_PLUGINS:BOOL=${MITK_BUILD_ALL_PLUGINS} MITK_BUILD_ALL_APPS:BOOL=${MITK_BUILD_ALL_APPS} MITK_BUILD_EXAMPLES:BOOL=${MITK_BUILD_EXAMPLES} SUPERBUILD_EXCLUDE_MITKBUILD_TARGET:BOOL=TRUE MITK_USE_ACVD:BOOL=${MITK_USE_ACVD} MITK_USE_Boost:BOOL=${MITK_USE_Boost} MITK_USE_OpenCV:BOOL=${MITK_USE_OpenCV} MITK_USE_Poco:BOOL=${MITK_USE_Poco} MITK_USE_SOFA:BOOL=${MITK_USE_SOFA} +MITK_USE_QT:BOOL=${MITK_USE_QT} ${ADDITIONAL_CMAKECACHE_OPTION} ") # Write a cache file for populating the MITK initial cache (not the superbuild cache). # This can be used to provide variables which are not passed through the # superbuild process to the MITK configure step) if(MITK_INITIAL_CACHE) set(mitk_cache_file "${CTEST_SCRIPT_DIRECTORY}/mitk_initial_cache.txt") file(WRITE "${mitk_cache_file}" "${MITK_INITIAL_CACHE}") set(INITIAL_CMAKECACHE_OPTIONS "${INITIAL_CMAKECACHE_OPTIONS} MITK_INITIAL_CACHE_FILE:INTERNAL=${mitk_cache_file} ") endif() # # Download and include dashboard driver script # set(url "http://mitk.org/git/?p=MITK.git;a=blob_plain;f=CMake/MITKDashboardDriverScript.cmake;hb=${hb}") set(dest ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}.driver) downloadFile("${url}" "${dest}") include(${dest}) diff --git a/CMakeExternals/CTK.cmake b/CMakeExternals/CTK.cmake index be71afaa15..0cfc835d01 100644 --- a/CMakeExternals/CTK.cmake +++ b/CMakeExternals/CTK.cmake @@ -1,95 +1,95 @@ #----------------------------------------------------------------------------- # CTK #----------------------------------------------------------------------------- if(MITK_USE_CTK) # Sanity checks if(DEFINED CTK_DIR AND NOT EXISTS ${CTK_DIR}) message(FATAL_ERROR "CTK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj CTK) set(proj_DEPENDENCIES ) set(CTK_DEPENDS ${proj}) if(NOT DEFINED CTK_DIR) - set(revision_tag 4cfeaaf7) + set(revision_tag 1dd16ae7) #IF(${proj}_REVISION_TAG) # SET(revision_tag ${${proj}_REVISION_TAG}) #ENDIF() set(ctk_optional_cache_args ) if(MITK_USE_Python) list(APPEND ctk_optional_cache_args -DCTK_LIB_Scripting/Python/Widgets:BOOL=ON -DCTK_ENABLE_Python_Wrapping:BOOL=ON -DCTK_APP_ctkSimplePythonShell:BOOL=ON -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} ) else() list(APPEND ctk_optional_cache_args -DCTK_LIB_Scripting/Python/Widgets:BOOL=OFF -DCTK_ENABLE_Python_Wrapping:BOOL=OFF -DCTK_APP_ctkSimplePythonShell:BOOL=OFF ) endif() if(MITK_USE_DCMTK) list(APPEND ctk_optional_cache_args -DDCMTK_DIR:PATH=${DCMTK_DIR} ) list(APPEND proj_DEPENDENCIES DCMTK) else() list(APPEND ctk_optional_cache_args -DDCMTK_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/CTK_DCMTK_085525e6.tar.gz ) endif() FOREACH(type RUNTIME ARCHIVE LIBRARY) IF(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY) LIST(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY}) ENDIF() ENDFOREACH() ExternalProject_Add(${proj} SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj}-src BINARY_DIR ${proj}-build PREFIX ${proj}-cmake URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/CTK_${revision_tag}.tar.gz - URL_MD5 23889893185726547ad1273dc8b63a46 + URL_MD5 03438db5c9a8324deb45d82c8a27784c UPDATE_COMMAND "" INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${ctk_optional_cache_args} -DDESIRED_QT_VERSION:STRING=${DESIRED_QT_VERSION} -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DGit_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE} -DGIT_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE} -DCTK_LIB_CommandLineModules/Backend/LocalProcess:BOOL=ON -DCTK_LIB_CommandLineModules/Frontend/QtGui:BOOL=ON -DCTK_LIB_PluginFramework:BOOL=ON -DCTK_LIB_DICOM/Widgets:BOOL=ON -DCTK_LIB_XNAT/Core:BOOL=ON -DCTK_PLUGIN_org.commontk.eventadmin:BOOL=ON -DCTK_PLUGIN_org.commontk.configadmin:BOOL=ON -DCTK_USE_GIT_PROTOCOL:BOOL=OFF -DDCMTK_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/CTK_DCMTK_085525e6.tar.gz - -DqRestAPI_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/qRestAPI_0d46f8a6.tar.gz + -DqRestAPI_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/qRestAPI_5f3a03b1.tar.gz DEPENDS ${proj_DEPENDENCIES} ) set(CTK_DIR ${CMAKE_CURRENT_BINARY_DIR}/${proj}-build) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/Core/Code/DataManagement/mitkProportionalTimeGeometry.cpp b/Core/Code/DataManagement/mitkProportionalTimeGeometry.cpp index 93ca960056..6823e6bb8b 100644 --- a/Core/Code/DataManagement/mitkProportionalTimeGeometry.cpp +++ b/Core/Code/DataManagement/mitkProportionalTimeGeometry.cpp @@ -1,265 +1,275 @@ /*=================================================================== 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 #include mitk::ProportionalTimeGeometry::ProportionalTimeGeometry() : m_FirstTimePoint(0.0), m_StepDuration(1.0) { } mitk::ProportionalTimeGeometry::~ProportionalTimeGeometry() { } void mitk::ProportionalTimeGeometry::Initialize() { m_FirstTimePoint = 0.0; m_StepDuration = 1.0; m_GeometryVector.resize(1); } mitk::TimeStepType mitk::ProportionalTimeGeometry::CountTimeSteps () const { return static_cast(m_GeometryVector.size() ); } mitk::TimePointType mitk::ProportionalTimeGeometry::GetMinimumTimePoint () const { return m_FirstTimePoint; } mitk::TimePointType mitk::ProportionalTimeGeometry::GetMaximumTimePoint () const { TimePointType timePoint = m_FirstTimePoint + m_StepDuration * CountTimeSteps(); if (timePoint >std::numeric_limits().max()) timePoint = std::numeric_limits().max(); return timePoint; } mitk::TimeBounds mitk::ProportionalTimeGeometry::GetTimeBounds () const { TimeBounds bounds; bounds[0] = this->GetMinimumTimePoint(); bounds[1] = this->GetMaximumTimePoint(); return bounds; } mitk::TimePointType mitk::ProportionalTimeGeometry::GetMinimumTimePoint(TimeStepType step) const { TimePointType timePoint; if (step == 0) { timePoint = m_FirstTimePoint; } else { timePoint = m_FirstTimePoint + m_StepDuration * step; } if (timePoint >std::numeric_limits().max()) timePoint = std::numeric_limits().max(); return timePoint; } mitk::TimePointType mitk::ProportionalTimeGeometry::GetMaximumTimePoint(TimeStepType step) const { TimePointType timePoint = m_FirstTimePoint + m_StepDuration * (step + 1); if (timePoint >std::numeric_limits().max()) timePoint = std::numeric_limits().max(); return timePoint; } mitk::TimeBounds mitk::ProportionalTimeGeometry::GetTimeBounds(TimeStepType step) const { TimeBounds bounds; bounds[0] = this->GetMinimumTimePoint(step); bounds[1] = this->GetMaximumTimePoint(step); return bounds; } bool mitk::ProportionalTimeGeometry::IsValidTimePoint (TimePointType timePoint) const { return this->GetMinimumTimePoint() <= timePoint && timePoint < this->GetMaximumTimePoint(); } bool mitk::ProportionalTimeGeometry::IsValidTimeStep (TimeStepType timeStep) const { return timeStep < this->CountTimeSteps(); } mitk::TimePointType mitk::ProportionalTimeGeometry::TimeStepToTimePoint( TimeStepType timeStep) const { if (m_FirstTimePoint <= itk::NumericTraits::NonpositiveMin() || m_FirstTimePoint >= itk::NumericTraits::max() || m_StepDuration <= itk::NumericTraits::min() || m_StepDuration >= itk::NumericTraits::max()) { return static_cast(timeStep); } return m_FirstTimePoint + timeStep * m_StepDuration; } mitk::TimeStepType mitk::ProportionalTimeGeometry::TimePointToTimeStep( TimePointType timePoint) const { if (m_FirstTimePoint <= timePoint) return static_cast((timePoint -m_FirstTimePoint) / m_StepDuration); else return 0; } mitk::BaseGeometry::Pointer mitk::ProportionalTimeGeometry::GetGeometryForTimeStep( TimeStepType timeStep) const { if (IsValidTimeStep(timeStep)) { return dynamic_cast(m_GeometryVector[timeStep].GetPointer()); } else { return 0; } } mitk::BaseGeometry::Pointer mitk::ProportionalTimeGeometry::GetGeometryForTimePoint(TimePointType timePoint) const { if (this->IsValidTimePoint(timePoint)) { TimeStepType timeStep = this->TimePointToTimeStep(timePoint); return this->GetGeometryForTimeStep(timeStep); } else { return 0; } } mitk::BaseGeometry::Pointer mitk::ProportionalTimeGeometry::GetGeometryCloneForTimeStep( TimeStepType timeStep) const { if (timeStep > m_GeometryVector.size()) return 0; itk::LightObject::Pointer lopointer = m_GeometryVector[timeStep]->Clone(); return dynamic_cast(lopointer.GetPointer()); } bool mitk::ProportionalTimeGeometry::IsValid() const { bool isValid = true; isValid &= m_GeometryVector.size() > 0; isValid &= m_StepDuration > 0; return isValid; } void mitk::ProportionalTimeGeometry::ClearAllGeometries() { m_GeometryVector.clear(); } void mitk::ProportionalTimeGeometry::ReserveSpaceForGeometries(TimeStepType numberOfGeometries) { m_GeometryVector.reserve(numberOfGeometries); } void mitk::ProportionalTimeGeometry::Expand(mitk::TimeStepType size) { m_GeometryVector.reserve(size); - while (m_GeometryVector.size() < size) + if (m_GeometryVector.size() == 0) { - Geometry3D::Pointer geo3D = Geometry3D::New(); - m_GeometryVector.push_back(dynamic_cast(geo3D.GetPointer())); + while (m_GeometryVector.size() < size) + { + Geometry3D::Pointer geo3D = Geometry3D::New(); + m_GeometryVector.push_back(dynamic_cast(geo3D.GetPointer())); + } + } else + { + while (m_GeometryVector.size() < size) + { + BaseGeometry::Pointer clone = dynamic_cast(m_GeometryVector[0]->Clone().GetPointer()); + m_GeometryVector.push_back(clone); + } } } void mitk::ProportionalTimeGeometry::SetTimeStepGeometry(BaseGeometry* geometry, TimeStepType timeStep) { assert(timeStep<=m_GeometryVector.size()); if (timeStep == m_GeometryVector.size()) m_GeometryVector.push_back(geometry); m_GeometryVector[timeStep] = geometry; } itk::LightObject::Pointer mitk::ProportionalTimeGeometry::InternalClone() const { itk::LightObject::Pointer parent = Superclass::InternalClone(); ProportionalTimeGeometry::Pointer newTimeGeometry = dynamic_cast (parent.GetPointer()); newTimeGeometry->m_FirstTimePoint = this->m_FirstTimePoint; newTimeGeometry->m_StepDuration = this->m_StepDuration; newTimeGeometry->m_GeometryVector.clear(); newTimeGeometry->Expand(this->CountTimeSteps()); for (TimeStepType i =0; i < CountTimeSteps(); ++i) { itk::LightObject::Pointer lopointer=GetGeometryForTimeStep(i)->Clone(); BaseGeometry::Pointer tempGeometry = dynamic_cast(lopointer.GetPointer()); newTimeGeometry->SetTimeStepGeometry(tempGeometry.GetPointer(),i); } return parent; } void mitk::ProportionalTimeGeometry::Initialize (BaseGeometry* geometry, TimeStepType timeSteps) { timeSteps = (timeSteps > 0) ? timeSteps : 1; m_FirstTimePoint = 0.0; m_StepDuration = 1.0; if (timeSteps < 2) { m_FirstTimePoint = -std::numeric_limits::max(); m_StepDuration = std::numeric_limits().infinity(); } this->ReserveSpaceForGeometries(timeSteps); try{ for (TimeStepType currentStep = 0; currentStep < timeSteps; ++currentStep) { itk::LightObject::Pointer lopointer=geometry->Clone(); BaseGeometry::Pointer clonedGeometry = dynamic_cast(lopointer.GetPointer()); this->SetTimeStepGeometry(clonedGeometry.GetPointer(), currentStep); } } catch (...) { MITK_INFO << "Cloning of geometry produced an error!"; } Update(); } void mitk::ProportionalTimeGeometry::Initialize (TimeStepType timeSteps) { mitk::Geometry3D::Pointer geo3D = Geometry3D::New(); mitk::BaseGeometry::Pointer geometry = dynamic_cast(geo3D.GetPointer()); geometry->Initialize(); this->Initialize(geometry.GetPointer(), timeSteps); } void mitk::ProportionalTimeGeometry::PrintSelf(std::ostream& os, itk::Indent indent) const { os << indent << " TimeSteps: " << this->CountTimeSteps() << std::endl; os << indent << " FirstTimePoint: " << this->GetFirstTimePoint() << std::endl; os << indent << " StepDuration: " << this->GetStepDuration() << " ms" << std::endl; os << indent << " Time Bounds: " << this->GetTimeBounds()[0] << " - " << this->GetTimeBounds()[1] << std::endl; os << std::endl; os << indent << " GetGeometryForTimeStep(0): "; if(GetGeometryForTimeStep(0).IsNull()) os << "NULL" << std::endl; else GetGeometryForTimeStep(0)->Print(os, indent); } diff --git a/Core/Code/DataManagement/mitkProportionalTimeGeometry.h b/Core/Code/DataManagement/mitkProportionalTimeGeometry.h index 1fb7478c55..1302d95f75 100644 --- a/Core/Code/DataManagement/mitkProportionalTimeGeometry.h +++ b/Core/Code/DataManagement/mitkProportionalTimeGeometry.h @@ -1,225 +1,227 @@ /*=================================================================== 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 ProportionalTimeGeometry_h #define ProportionalTimeGeometry_h //MITK #include #include #include #include namespace mitk { /** * \brief Organizes geometries over proportional time steps * * For this TimeGeometry implementation it is assumed that * the durations of the time steps are equidistant, e.g. * the durations of the time steps in one ProportionalTimeGeometry * are the same. The geometries of the time steps are independent, * and not linked to each other. Since the timeBounds of the * geometries are different for each time step it is not possible * to set the same geometry to different time steps. Instead * copies should be used. * * \addtogroup geometry */ class MITK_CORE_EXPORT ProportionalTimeGeometry : public TimeGeometry { public: mitkClassMacro(ProportionalTimeGeometry, TimeGeometry); ProportionalTimeGeometry(); typedef ProportionalTimeGeometry self; itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * \brief Returns the number of time steps. * * Returns the number of time steps for which * geometries are saved. The number of time steps * is also the upper bound of the time steps. The * minimum time steps is always 0. */ virtual TimeStepType CountTimeSteps() const; /** * \brief Returns the first time point for which the object is valid. * * Returns the first valid time point for this geometry. If only one * time steps available it usually goes from -max to +max. The time point * is given in ms. */ virtual TimePointType GetMinimumTimePoint () const; /** * \brief Returns the last time point for which the object is valid * * Gives the last time point for which a valid geometrie is saved in * this time geometry. The time point is given in ms. */ virtual TimePointType GetMaximumTimePoint () const; /** * \brief Returns the first time point for which the object is valid. * * Returns the first valid time point for the given TimeStep. The time point * is given in ms. */ virtual TimePointType GetMinimumTimePoint(TimeStepType step) const; /** * \brief Returns the last time point for which the object is valid * * Gives the last time point for the Geometry specified by the given TimeStep. The time point is given in ms. */ virtual TimePointType GetMaximumTimePoint(TimeStepType step) const; /** * \brief Get the time bounds (in ms) */ virtual TimeBounds GetTimeBounds( ) const; /** * \brief Get the time bounds for the given TimeStep (in ms) */ virtual TimeBounds GetTimeBounds(TimeStepType step) const; /** * \brief Tests if a given time point is covered by this object * * Returns true if a geometry can be returned for the given time * point and falls if not. The time point must be given in ms. */ virtual bool IsValidTimePoint (TimePointType timePoint) const; /** * \brief Test for the given time step if a geometry is availible * * Returns true if a geometry is defined for the given time step. * Otherwise false is returned. * The time step is defined as positiv number. */ virtual bool IsValidTimeStep (TimeStepType timeStep) const; /** * \brief Converts a time step to a time point * * Converts a time step to a time point in a way that * the new time point indicates the same geometry as the time step. * If the original time steps does not point to a valid geometry, * a time point is calculated that also does not point to a valid * geometry, but no exception is raised. */ virtual TimePointType TimeStepToTimePoint (TimeStepType timeStep) const; /** * \brief Converts a time point to the corresponding time step * * Converts a time point to a time step in a way that * the new time step indicates the same geometry as the time point. * If a negativ invalid time point is given always time step 0 is * returned. If an positiv invalid time step is given an invalid * time step will be returned. */ virtual TimeStepType TimePointToTimeStep (TimePointType timePoint) const; /** * \brief Returns the geometry which corresponds to the given time step * * Returns a clone of the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. */ virtual BaseGeometry::Pointer GetGeometryCloneForTimeStep( TimeStepType timeStep) const; /** * \brief Returns the geometry which corresponds to the given time point * * Returns the geometry which defines the given time point. If * the given time point is invalid an null-pointer is returned. * * If the returned geometry is changed this will affect the saved * geometry. */ virtual BaseGeometry::Pointer GetGeometryForTimePoint ( TimePointType timePoint) const; /** * \brief Returns the geometry which corresponds to the given time step * * Returns the geometry which defines the given time step. If * the given time step is invalid an null-pointer is returned. * * If the returned geometry is changed this will affect the saved * geometry. */ virtual BaseGeometry::Pointer GetGeometryForTimeStep ( TimeStepType timeStep) const; /** * \brief Tests if all necessary informations are set and the object is valid */ virtual bool IsValid () const; /** * \brief Initilizes a new object with one time steps which contains an empty geometry. */ virtual void Initialize(); /** * \brief Expands the time geometry to the given number of time steps. * - * Initializes the new time steps with empty geometries. + * Initializes the new time steps with empty geometries if no timesteps + * in the geometry so far. Otherwise fills the new times steps with + * clones of the first time step. * Shrinking is not supported. */ virtual void Expand(TimeStepType size); /** * \brief Sets the geometry for the given time step * * This method does not afflict other time steps, since the geometry for * each time step is saved individually. */ virtual void SetTimeStepGeometry(BaseGeometry* geometry, TimeStepType timeStep); /** * \brief Makes a deep copy of the current object */ virtual itk::LightObject::Pointer InternalClone () const; itkGetConstMacro(FirstTimePoint, TimePointType); itkSetMacro(FirstTimePoint, TimePointType); itkGetConstMacro(StepDuration, TimePointType); itkSetMacro(StepDuration, TimePointType); // void SetGeometryForTimeStep(TimeStepType timeStep, BaseGeometry& geometry); void ClearAllGeometries (); // void AddGeometry(BaseGeometry geometry); void ReserveSpaceForGeometries (TimeStepType numberOfGeometries); /** * \brief Initializes the TimeGeometry with equally time Step geometries * * Saves a copy for each time step. */ void Initialize (BaseGeometry* geometry, TimeStepType timeSteps); /** * \brief Initialize the TimeGeometry with empty BaseGeometry */ void Initialize (TimeStepType timeSteps); virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; protected: virtual ~ProportionalTimeGeometry(); std::vector m_GeometryVector; TimePointType m_FirstTimePoint; TimePointType m_StepDuration; }; // end class ProportialTimeGeometry } // end namespace MITK #endif // ProportionalTimeGeometry_h diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.h b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.h index bba438c8c7..a0f98760b3 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.h +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.h @@ -1,79 +1,84 @@ /*=================================================================== 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 __itkBrainMaskExtractionImageFilter_h_ #define __itkBrainMaskExtractionImageFilter_h_ #include "itkImageToImageFilter.h" namespace itk{ /** \class BrainMaskExtractionImageFilter * \brief This class takes as input a T2-weighted image and computes a brainmask. * */ template< class TOutputImagePixelType > class BrainMaskExtractionImageFilter : public ImageToImageFilter< Image< unsigned short, 3 >, Image< TOutputImagePixelType, 3 > > { public: typedef BrainMaskExtractionImageFilter Self; typedef SmartPointer Pointer; typedef SmartPointer ConstPointer; typedef ImageToImageFilter< Image< unsigned short, 3 >, Image< TOutputImagePixelType, 3 > > Superclass; /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** Runtime information support. */ itkTypeMacro(BrainMaskExtractionImageFilter, ImageToImageFilter); typedef unsigned short InputPixelType; typedef TOutputImagePixelType OutputPixelType; typedef typename Superclass::InputImageType InputImageType; typedef typename Superclass::OutputImageType OutputImageType; typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + itkSetMacro( MaxNumIterations, int ) + itkGetMacro( MaxNumIterations, int ) + protected: BrainMaskExtractionImageFilter(); ~BrainMaskExtractionImageFilter() {}; void GenerateData(); bool CompareImages( typename OutputImageType::Pointer im1, typename OutputImageType::Pointer im2); int ComputeHistogram( typename InputImageType::Pointer image); void CopyImage( typename OutputImageType::Pointer target, typename OutputImageType::Pointer source); + + int m_MaxNumIterations; }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkBrainMaskExtractionImageFilter.txx" #endif #endif //__itkBrainMaskExtractionImageFilter_h_ diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.txx b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.txx index 8a3061d02d..e195403710 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.txx +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkBrainMaskExtractionImageFilter.txx @@ -1,443 +1,444 @@ /*=================================================================== 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. ===================================================================*/ /*=================================================================== This file is based heavily on a corresponding ITK filter. ===================================================================*/ #ifndef __itkBrainMaskExtractionImageFilter_txx #define __itkBrainMaskExtractionImageFilter_txx #include "itkBrainMaskExtractionImageFilter.h" #include #include #include #include #include #include #include #include #include #include namespace itk { template< class TOutputImagePixelType > BrainMaskExtractionImageFilter< TOutputImagePixelType > ::BrainMaskExtractionImageFilter() + : m_MaxNumIterations(itk::NumericTraits::max()) { // At least 1 inputs is necessary for a vector image. // For images added one at a time we need at least six this->SetNumberOfRequiredInputs( 1 ); } template< class TOutputImagePixelType > void BrainMaskExtractionImageFilter< TOutputImagePixelType > ::GenerateData() { // gaussian filter typename itk::RecursiveGaussianImageFilter::Pointer gaussian = itk::RecursiveGaussianImageFilter::New(); gaussian->SetInput( this->GetInput(0) ); gaussian->SetSigma( 1.0 ); try { gaussian->Update(); } catch( itk::ExceptionObject &e) { std::cerr << e; return; } // threshold the image typename itk::BinaryThresholdImageFilter::Pointer threshold = itk::BinaryThresholdImageFilter::New(); threshold->SetInput( gaussian->GetOutput() ); int seuil = static_cast( ComputeHistogram( gaussian->GetOutput() ) ); threshold->SetLowerThreshold( seuil ); std::cout << "Thresholding..." << std::flush; try { threshold->Update(); } catch( itk::ExceptionObject &e) { std::cerr << e; return; } std::cout << "Done." << std::endl; #ifdef DEBUG_ME { WriterType::Pointer writer = WriterType::New(); writer->SetInput( threshold->GetOutput() ); writer->SetFileName( "AfterThreshold.hdr" ); writer->Update(); } #endif // erode to remove background noise typedef itk::BinaryBallStructuringElement StructuralElementType; StructuralElementType ball; typename itk::BinaryErodeImageFilter::Pointer erode = itk::BinaryErodeImageFilter::New(); ball.SetRadius( 3 ); erode->SetInput( threshold->GetOutput() ); erode->SetKernel( ball ); std::cout << "Eroding..." << std::flush; try { erode->Update(); } catch( itk::ExceptionObject &e) { std::cerr << e; return; } std::cout << "Done." << std::endl; #ifdef DEBUG_ME { WriterType::Pointer writer = WriterType::New(); writer->SetInput( erode->GetOutput() ); writer->SetFileName( "AfterErode.hdr" ); writer->Update(); } #endif typedef BinaryCrossStructuringElement CrossType; typedef BinaryDilateImageFilter DilateFilterType; typedef AndImageFilter AndFilterType; typename OutputImageType::Pointer M0 = threshold->GetOutput(); typename OutputImageType::Pointer Mn = OutputImageType::New(); Mn->SetRegions( M0->GetLargestPossibleRegion() ); Mn->SetSpacing( M0->GetSpacing() ); Mn->SetOrigin( M0->GetOrigin() ); Mn->SetDirection( M0->GetDirection() ); Mn->Allocate(); typename OutputImageType::Pointer Mnplus1 = erode->GetOutput(); CrossType cross; cross.SetRadius( 1 ); //unsigned long rad[3]={3,3,3}; //ball2.SetRadius( rad ); std::cout << "Conditional reconstruction..." << std::flush; int iter = 0; do { std::cout << "Iteration: " << iter++ << std::endl; CopyImage( Mn, Mnplus1); typename DilateFilterType::Pointer dilater = DilateFilterType::New(); dilater->SetInput( Mn ); dilater->SetKernel( cross ); try { dilater->Update(); } catch( itk::ExceptionObject &e) { std::cerr << e; return; } typename AndFilterType::Pointer andfilter = AndFilterType::New(); andfilter->SetInput(0, M0); andfilter->SetInput(1, dilater->GetOutput() ); try { andfilter->Update(); } catch( itk::ExceptionObject &e) { std::cerr << e; return; } Mnplus1 = andfilter->GetOutput(); /* #ifdef DEBUG_ME { WriterType::Pointer writer = WriterType::New(); writer->SetInput( andfilter->GetOutput() ); char filename[512]; sprintf( filename, "CondReconstruction_iter_%d.hdr", iter); writer->SetFileName( filename ); writer->Update(); } #endif*/ - } while( !CompareImages( Mn, Mnplus1) ); + } while( !CompareImages( Mn, Mnplus1) && iter < m_MaxNumIterations ); std::cout << "Done." << std::endl; #ifdef DEBUG_ME { WriterType::Pointer writer = WriterType::New(); writer->SetInput( Mn ); writer->SetFileName( "AfterCondReconstruction.hdr" ); writer->Update(); } #endif // now fill the holes typename itk::VotingBinaryIterativeHoleFillingImageFilter< OutputImageType >::Pointer filler = itk::VotingBinaryIterativeHoleFillingImageFilter< OutputImageType >::New(); filler->SetInput( Mn ); filler->SetMaximumNumberOfIterations (1000); std::cout << "Filling the holes..." << std::flush; try { filler->Update(); } catch( itk::ExceptionObject &e) { std::cerr << e; return; } std::cout << "Done." << std::endl; typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetPrimaryOutput()); outputImage->SetSpacing( filler->GetOutput()->GetSpacing() ); // Set the image spacing outputImage->SetOrigin( filler->GetOutput()->GetOrigin() ); // Set the image origin outputImage->SetLargestPossibleRegion( filler->GetOutput()->GetLargestPossibleRegion()); outputImage->SetBufferedRegion( filler->GetOutput()->GetLargestPossibleRegion() ); outputImage->SetDirection( filler->GetOutput()->GetDirection() ); outputImage->Allocate(); itk::ImageRegionIterator itIn( filler->GetOutput(), filler->GetOutput()->GetLargestPossibleRegion() ); itk::ImageRegionIterator itOut( outputImage, outputImage->GetLargestPossibleRegion() ); while( !itIn.IsAtEnd() ) { itOut.Set(itIn.Get()); ++itIn; ++itOut; } } template< class TOutputImagePixelType > void BrainMaskExtractionImageFilter< TOutputImagePixelType > ::CopyImage( typename OutputImageType::Pointer target, typename OutputImageType::Pointer source) { itk::ImageRegionConstIterator itIn( source, source->GetLargestPossibleRegion() ); itk::ImageRegionIterator itOut( target, target->GetLargestPossibleRegion() ); while( !itOut.IsAtEnd() ) { itOut.Set( itIn.Get() ); ++itIn; ++itOut; } } template< class TOutputImagePixelType > bool BrainMaskExtractionImageFilter< TOutputImagePixelType > ::CompareImages( typename OutputImageType::Pointer im1, typename OutputImageType::Pointer im2) { itk::ImageRegionConstIterator itIn( im1, im1->GetLargestPossibleRegion() ); itk::ImageRegionConstIterator itOut( im2, im2->GetLargestPossibleRegion() ); while( !itOut.IsAtEnd() ) { if( itOut.Value() != itIn.Value() ) { return false; } ++itOut; ++itIn; } return true; } template< class TOutputImagePixelType > int BrainMaskExtractionImageFilter< TOutputImagePixelType > ::ComputeHistogram( typename InputImageType::Pointer image) { // IMPORTANT: IMAGE MUST BE UNSIGNED SHORT int N=65535; int* histogram = new int[N]; for( int i=0; i itIn( image, image->GetLargestPossibleRegion() ); long totVoxels = 0; int max = -1; int min = 9999999; while( !itIn.IsAtEnd() ) { histogram[ (int)(itIn.Value()) ]++; if( itIn.Value()>max ) { max = itIn.Value(); } if( itIn.Value()EPS ) for( seuil = min; seuil<=max; seuil++) { //seuil = newseuil; // compute the classes: double mean0 = 0.0; double mean1 = 0.0; //double std0 = 0.0; //double std1 = 0.0; double num0 = 0.0; double num1 = 0.0; for( int i=min; i 65535 || newseuil<0) { std::cerr << "Error: threshold is too low or high, exiting" << std::endl; return -1; }*/ double Vm = num0 * (mean0 - mean)*(mean0 - mean) + num1*(mean1 - mean)*(mean1 - mean); if( Vm > V ) { V = Vm; S = seuil; //std::cout << "New seuil: " << S << std::endl; //getchar(); } } delete [] histogram; std::cout << "Seuil: " << S << std::endl; return S; } } #endif // __itkBrainMaskExtractionImageFilter_txx diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkDwiNormilzationFilter.txx b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkDwiNormilzationFilter.txx index ad4364059e..4e1931df1f 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkDwiNormilzationFilter.txx +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkDwiNormilzationFilter.txx @@ -1,137 +1,139 @@ /*=================================================================== 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 __itkDwiNormilzationFilter_txx #define __itkDwiNormilzationFilter_txx #include #include #include #define _USE_MATH_DEFINES #include #include "itkImageRegionConstIterator.h" #include "itkImageRegionConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" namespace itk { template< class TInPixelType > DwiNormilzationFilter< TInPixelType>::DwiNormilzationFilter() :m_B0Index(-1) ,m_NewMax(1000) ,m_UseGlobalMax(false) { this->SetNumberOfRequiredInputs( 1 ); } template< class TInPixelType > void DwiNormilzationFilter< TInPixelType>::BeforeThreadedGenerateData() { m_B0Index = -1; typename InputImageType::Pointer inputImagePointer = static_cast< InputImageType * >( this->ProcessObject::GetInput(0) ); for (unsigned int i=0; iGetVectorLength(); i++) { GradientDirectionType g = m_GradientDirections->GetElement(i); if (g.magnitude()<0.001) m_B0Index = i; } if (m_B0Index==-1) itkExceptionMacro(<< "DwiNormilzationFilter: No b-Zero indecies found!"); m_GlobalMax = 0; if (m_UseGlobalMax) { typedef ImageRegionConstIterator< InputImageType > InputIteratorType; typename InputImageType::Pointer inputImagePointer = static_cast< InputImageType * >( this->ProcessObject::GetInput(0) ); InputIteratorType git( inputImagePointer, inputImagePointer->GetLargestPossibleRegion() ); git.GoToBegin(); while( !git.IsAtEnd() ) { if (git.Get()[m_B0Index]>m_GlobalMax) m_GlobalMax = git.Get()[m_B0Index]; ++git; } } } template< class TInPixelType > void DwiNormilzationFilter< TInPixelType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType ) { typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread); oit.GoToBegin(); typedef ImageRegionConstIterator< InputImageType > InputIteratorType; typename InputImageType::Pointer inputImagePointer = static_cast< InputImageType * >( this->ProcessObject::GetInput(0) ); typename OutputImageType::PixelType nullPix; nullPix.SetSize(inputImagePointer->GetVectorLength()); nullPix.Fill(0); InputIteratorType git( inputImagePointer, outputRegionForThread ); git.GoToBegin(); while( !git.IsAtEnd() ) { typename InputImageType::PixelType pix = git.Get(); + typename OutputImageType::PixelType outPix; + outPix.SetSize(inputImagePointer->GetVectorLength()); double S0 = pix[m_B0Index]; if (m_UseGlobalMax) S0 = m_GlobalMax; if (S0>0.1) { for (unsigned int i=0; iGetVectorLength(); i++) { double val = (double)pix[i]; if (val!=val || val<0) val = 0; else { val /= S0; val *= (double)m_NewMax; } - pix[i] = (TInPixelType)val; + outPix[i] = (TInPixelType)val; } - oit.Set(pix); + oit.Set(outPix); } else oit.Set(nullPix); ++oit; ++git; } std::cout << "One Thread finished calculation" << std::endl; } template< class TInPixelType > void DwiNormilzationFilter< TInPixelType> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); } } #endif // __itkDwiNormilzationFilter_txx diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.h b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.h index b6f1d5926b..2bbaf13288 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.h +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.h @@ -1,90 +1,138 @@ /*=================================================================== 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. ===================================================================*/ /*========================================================================= Program: Tensor ToolKit - TTK Module: $URL: svn://scm.gforge.inria.fr/svn/ttk/trunk/Algorithms/itkResampleDwiImageFilter.h $ Language: C++ Date: $Date: 2010-06-07 13:39:13 +0200 (Mo, 07 Jun 2010) $ Version: $Revision: 68 $ Copyright (c) INRIA 2010. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itk_ResampleDwiImageFilter_h_ #define _itk_ResampleDwiImageFilter_h_ #include #include #include namespace itk { /** * \brief Resample DWI channel by channel. */ template class ResampleDwiImageFilter : public ImageToImageFilter, itk::VectorImage > { public: + enum Interpolation { + Interpolate_NearestNeighbour, + Interpolate_Linear, + Interpolate_BSpline, + Interpolate_WindowedSinc + }; + typedef ResampleDwiImageFilter Self; typedef SmartPointer Pointer; typedef SmartPointer ConstPointer; typedef ImageToImageFilter< itk::VectorImage, itk::VectorImage > Superclass; - typedef itk::Vector< double, 3 > SamplingFactorType; + typedef itk::Vector< double, 3 > DoubleVectorType; typedef itk::VectorImage DwiImageType; typedef itk::Image DwiChannelType; /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** Runtime information support. */ itkTypeMacro(ResampleDwiImageFilter, ImageToImageFilter) - itkGetMacro(SamplingFactor, SamplingFactorType) - itkSetMacro(SamplingFactor, SamplingFactorType) + itkSetMacro( Interpolation, Interpolation ) + + void SetSamplingFactor(DoubleVectorType sampling) + { + m_NewSpacing = this->GetInput()->GetSpacing(); + m_NewSpacing[0] /= sampling[0]; + m_NewSpacing[1] /= sampling[1]; + m_NewSpacing[2] /= sampling[2]; + m_NewImageRegion = this->GetInput()->GetLargestPossibleRegion(); + m_NewImageRegion.SetSize(0, m_NewImageRegion.GetSize(0)*sampling[0]); + m_NewImageRegion.SetSize(1, m_NewImageRegion.GetSize(1)*sampling[1]); + m_NewImageRegion.SetSize(2, m_NewImageRegion.GetSize(2)*sampling[2]); + } + void SetNewSpacing(DoubleVectorType spacing) + { + DoubleVectorType oldSpacing = this->GetInput()->GetSpacing(); + DoubleVectorType sampling; + sampling[0] = oldSpacing[0]/spacing[0]; + sampling[1] = oldSpacing[1]/spacing[1]; + sampling[2] = oldSpacing[2]/spacing[2]; + + m_NewSpacing = spacing; + m_NewImageRegion = this->GetInput()->GetLargestPossibleRegion(); + m_NewImageRegion.SetSize(0, m_NewImageRegion.GetSize(0)*sampling[0]); + m_NewImageRegion.SetSize(1, m_NewImageRegion.GetSize(1)*sampling[1]); + m_NewImageRegion.SetSize(2, m_NewImageRegion.GetSize(2)*sampling[2]); + } + void SetNewImageSize(ImageRegion<3> region) + { + ImageRegion<3> oldRegion = this->GetInput()->GetLargestPossibleRegion(); + DoubleVectorType sampling; + sampling[0] = (double)region.GetSize(0)/oldRegion.GetSize(0); + sampling[1] = (double)region.GetSize(1)/oldRegion.GetSize(1); + sampling[2] = (double)region.GetSize(2)/oldRegion.GetSize(2); + + m_NewImageRegion = region; + m_NewSpacing = this->GetInput()->GetSpacing(); + m_NewSpacing[0] /= sampling[0]; + m_NewSpacing[1] /= sampling[1]; + m_NewSpacing[2] /= sampling[2]; + } protected: ResampleDwiImageFilter(); ~ResampleDwiImageFilter(){} void GenerateData(); - SamplingFactorType m_SamplingFactor; + DoubleVectorType m_NewSpacing; + ImageRegion<3> m_NewImageRegion; + Interpolation m_Interpolation; }; } // end of namespace #ifndef ITK_MANUAL_INSTANTIATION #include "itkResampleDwiImageFilter.txx" #endif #endif diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.txx b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.txx index ce511a34db..516c121104 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.txx +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkResampleDwiImageFilter.txx @@ -1,125 +1,166 @@ /*=================================================================== 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. ===================================================================*/ /*========================================================================= Program: Tensor ToolKit - TTK Module: $URL: svn://scm.gforge.inria.fr/svn/ttk/trunk/Algorithms/itkResampleDwiImageFilter.txx $ Language: C++ Date: $Date: 2010-06-07 13:39:13 +0200 (Mo, 07 Jun 2010) $ Version: $Revision: 68 $ Copyright (c) INRIA 2010. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itk_ResampleDwiImageFilter_txx_ #define _itk_ResampleDwiImageFilter_txx_ #endif #define _USE_MATH_DEFINES #include "itkResampleDwiImageFilter.h" #include #include #include #include #include +#include +#include namespace itk { template ResampleDwiImageFilter ::ResampleDwiImageFilter() + : m_Interpolation(Interpolate_Linear) { this->SetNumberOfRequiredInputs( 1 ); } template void ResampleDwiImageFilter ::GenerateData() { - // initialize output image - itk::Vector< double, 3 > spacing = this->GetInput()->GetSpacing(); - spacing[0] /= m_SamplingFactor[0]; - spacing[1] /= m_SamplingFactor[1]; - spacing[2] /= m_SamplingFactor[2]; - ImageRegion<3> region = this->GetInput()->GetLargestPossibleRegion(); - region.SetSize(0, region.GetSize(0)*m_SamplingFactor[0]); - region.SetSize(1, region.GetSize(1)*m_SamplingFactor[1]); - region.SetSize(2, region.GetSize(2)*m_SamplingFactor[2]); +// // initialize output image +// itk::Vector< double, 3 > spacing = this->GetInput()->GetSpacing(); +// spacing[0] /= m_SamplingFactor[0]; +// spacing[1] /= m_SamplingFactor[1]; +// spacing[2] /= m_SamplingFactor[2]; +// ImageRegion<3> region = this->GetInput()->GetLargestPossibleRegion(); +// region.SetSize(0, region.GetSize(0)*m_SamplingFactor[0]); +// region.SetSize(1, region.GetSize(1)*m_SamplingFactor[1]); +// region.SetSize(2, region.GetSize(2)*m_SamplingFactor[2]); + + itk::Point origin = this->GetInput()->GetOrigin(); + origin[0] -= this->GetInput()->GetSpacing()[0]/2; + origin[1] -= this->GetInput()->GetSpacing()[1]/2; + origin[2] -= this->GetInput()->GetSpacing()[2]/2; + + origin[0] += m_NewSpacing[0]/2; + origin[1] += m_NewSpacing[1]/2; + origin[2] += m_NewSpacing[2]/2; typename DwiImageType::Pointer outImage = DwiImageType::New(); - outImage->SetSpacing( spacing ); - outImage->SetOrigin( this->GetInput()->GetOrigin() ); + outImage->SetSpacing( m_NewSpacing ); + outImage->SetOrigin( origin ); outImage->SetDirection( this->GetInput()->GetDirection() ); - outImage->SetLargestPossibleRegion( region ); - outImage->SetBufferedRegion( region ); - outImage->SetRequestedRegion( region ); + outImage->SetLargestPossibleRegion( m_NewImageRegion ); + outImage->SetBufferedRegion( m_NewImageRegion ); + outImage->SetRequestedRegion( m_NewImageRegion ); outImage->SetVectorLength( this->GetInput()->GetVectorLength() ); outImage->Allocate(); - typename itk::NearestNeighborInterpolateImageFunction::Pointer interp = itk::NearestNeighborInterpolateImageFunction::New(); -// typename itk::BSplineInterpolateImageFunction::Pointer interp = itk::BSplineInterpolateImageFunction::New(); - typename itk::ResampleImageFilter::Pointer resampler = itk::ResampleImageFilter::New(); resampler->SetOutputParametersFromImage(outImage); - resampler->SetInterpolator(interp); - for (int i=0; iGetInput()->GetVectorLength(); i++) + switch (m_Interpolation) + { + case Interpolate_NearestNeighbour: + { + typename itk::NearestNeighborInterpolateImageFunction::Pointer interp = itk::NearestNeighborInterpolateImageFunction::New(); + resampler->SetInterpolator(interp); + break; + } + case Interpolate_Linear: + { + typename itk::LinearInterpolateImageFunction::Pointer interp = itk::LinearInterpolateImageFunction::New(); + resampler->SetInterpolator(interp); + break; + } + case Interpolate_BSpline: + { + typename itk::BSplineInterpolateImageFunction::Pointer interp = itk::BSplineInterpolateImageFunction::New(); + resampler->SetInterpolator(interp); + break; + } + case Interpolate_WindowedSinc: + { + typename itk::WindowedSincInterpolateImageFunction::Pointer interp = itk::WindowedSincInterpolateImageFunction::New(); + resampler->SetInterpolator(interp); + break; + } + default: + { + typename itk::LinearInterpolateImageFunction::Pointer interp = itk::LinearInterpolateImageFunction::New(); + resampler->SetInterpolator(interp); + } + } + + for (unsigned int i=0; iGetInput()->GetVectorLength(); i++) { typename DwiChannelType::Pointer channel = DwiChannelType::New(); channel->SetSpacing( this->GetInput()->GetSpacing() ); channel->SetOrigin( this->GetInput()->GetOrigin() ); channel->SetDirection( this->GetInput()->GetDirection() ); channel->SetLargestPossibleRegion( this->GetInput()->GetLargestPossibleRegion() ); channel->SetBufferedRegion( this->GetInput()->GetLargestPossibleRegion() ); channel->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() ); channel->Allocate(); ImageRegionIterator it(channel, channel->GetLargestPossibleRegion()); while(!it.IsAtEnd()) { typename DwiImageType::PixelType pix = this->GetInput()->GetPixel(it.GetIndex()); it.Set(pix[i]); ++it; } resampler->SetInput(channel); resampler->Update(); channel = resampler->GetOutput(); ImageRegionIterator it2(outImage, outImage->GetLargestPossibleRegion()); while(!it2.IsAtEnd()) { typename DwiImageType::PixelType pix = it2.Get(); pix[i] = channel->GetPixel(it2.GetIndex()); it2.Set(pix); ++it2; } } this->SetNthOutput(0, outImage); } } // end of namespace diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp b/Modules/DiffusionImaging/DiffusionCore/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp index c84f89dbbd..2992c57bd0 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp @@ -1,1256 +1,1274 @@ /*=================================================================== 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 "mitkPartialVolumeAnalysisHistogramCalculator.h" #include "mitkImageAccessByItk.h" #include "mitkExtractImageFilter.h" #include #include #include #include #include #include "itkResampleImageFilter.h" #include "itkGaussianInterpolateImageFunction.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "itkGaussianInterpolateImageFunction.h" #include "itkBSplineInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkImageMaskSpatialObject.h" #include "itkRegionOfInterestImageFilter.h" #include "itkListSample.h" +#include "mitkAbstractTransformGeometry.h" + #include #include namespace mitk { PartialVolumeAnalysisHistogramCalculator::PartialVolumeAnalysisHistogramCalculator() : m_MaskingMode( MASKING_MODE_NONE ), m_MaskingModeChanged( false ), m_NumberOfBins(256), m_UpsamplingFactor(1), m_GaussianSigma(0), m_ForceUpdate(false), m_PlanarFigureThickness(0) { m_EmptyHistogram = HistogramType::New(); m_EmptyHistogram->SetMeasurementVectorSize(1); HistogramType::SizeType histogramSize(1); histogramSize.Fill( 256 ); m_EmptyHistogram->Initialize( histogramSize ); m_EmptyStatistics.Reset(); } PartialVolumeAnalysisHistogramCalculator::~PartialVolumeAnalysisHistogramCalculator() { } void PartialVolumeAnalysisHistogramCalculator::SetImage( const mitk::Image *image ) { if ( m_Image != image ) { m_Image = image; this->Modified(); m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = true; } } void PartialVolumeAnalysisHistogramCalculator::AddAdditionalResamplingImage( const mitk::Image *image ) { m_AdditionalResamplingImages.push_back(image); this->Modified(); m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = true; } void PartialVolumeAnalysisHistogramCalculator::SetModified( ) { this->Modified(); m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = true; m_MaskedImageStatisticsTimeStamp.Modified(); m_MaskedImageStatisticsCalculationTriggerBool = true; m_PlanarFigureStatisticsTimeStamp.Modified(); m_PlanarFigureStatisticsCalculationTriggerBool = true; } void PartialVolumeAnalysisHistogramCalculator::SetImageMask( const mitk::Image *imageMask ) { if ( m_Image.IsNull() ) { itkExceptionMacro( << "Image needs to be set first!" ); } if ( m_Image->GetTimeSteps() != imageMask->GetTimeSteps() ) { itkExceptionMacro( << "Image and image mask need to have equal number of time steps!" ); } if ( m_ImageMask != imageMask ) { m_ImageMask = imageMask; this->Modified(); m_MaskedImageStatisticsTimeStamp.Modified(); m_MaskedImageStatisticsCalculationTriggerBool = true; } } void PartialVolumeAnalysisHistogramCalculator::SetPlanarFigure( const mitk::PlanarFigure *planarFigure ) { if ( m_Image.IsNull() ) { itkExceptionMacro( << "Image needs to be set first!" ); } if ( m_PlanarFigure != planarFigure ) { m_PlanarFigure = planarFigure; this->Modified(); m_PlanarFigureStatisticsTimeStamp.Modified(); m_PlanarFigureStatisticsCalculationTriggerBool = true; } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingMode( unsigned int mode ) { if ( m_MaskingMode != mode ) { m_MaskingMode = mode; m_MaskingModeChanged = true; this->Modified(); } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingModeToNone() { if ( m_MaskingMode != MASKING_MODE_NONE ) { m_MaskingMode = MASKING_MODE_NONE; m_MaskingModeChanged = true; this->Modified(); } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingModeToImage() { if ( m_MaskingMode != MASKING_MODE_IMAGE ) { m_MaskingMode = MASKING_MODE_IMAGE; m_MaskingModeChanged = true; this->Modified(); } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingModeToPlanarFigure() { if ( m_MaskingMode != MASKING_MODE_PLANARFIGURE ) { m_MaskingMode = MASKING_MODE_PLANARFIGURE; m_MaskingModeChanged = true; this->Modified(); } } bool PartialVolumeAnalysisHistogramCalculator::ComputeStatistics() { MITK_DEBUG << "ComputeStatistics() start"; if ( m_Image.IsNull() ) { itkExceptionMacro( << "Image not set!" ); } if ( m_Image->GetReferenceCount() == 1 ) { MITK_DEBUG << "No Stats calculated; no one else holds a reference on it"; return false; } // If a mask was set but we are the only ones to still hold a reference on // it, delete it. if ( m_ImageMask.IsNotNull() && (m_ImageMask->GetReferenceCount() == 1) ) { m_ImageMask = NULL; } // Check if statistics is already up-to-date unsigned long imageMTime = m_ImageStatisticsTimeStamp.GetMTime(); unsigned long maskedImageMTime = m_MaskedImageStatisticsTimeStamp.GetMTime(); unsigned long planarFigureMTime = m_PlanarFigureStatisticsTimeStamp.GetMTime(); bool imageStatisticsCalculationTrigger = m_ImageStatisticsCalculationTriggerBool; bool maskedImageStatisticsCalculationTrigger = m_MaskedImageStatisticsCalculationTriggerBool; bool planarFigureStatisticsCalculationTrigger = m_PlanarFigureStatisticsCalculationTriggerBool; if ( /*prevent calculation without mask*/!m_ForceUpdate &&( m_MaskingMode == MASKING_MODE_NONE || ( ((m_MaskingMode != MASKING_MODE_NONE) || (imageMTime > m_Image->GetMTime() && !imageStatisticsCalculationTrigger)) && ((m_MaskingMode != MASKING_MODE_IMAGE) || (m_ImageMask.IsNotNull() && maskedImageMTime > m_ImageMask->GetMTime() && !maskedImageStatisticsCalculationTrigger)) && ((m_MaskingMode != MASKING_MODE_PLANARFIGURE) || (m_PlanarFigure.IsNotNull() && planarFigureMTime > m_PlanarFigure->GetMTime() && !planarFigureStatisticsCalculationTrigger)) ) ) ) { MITK_DEBUG << "Returning, statistics already up to date!"; if ( m_MaskingModeChanged ) { m_MaskingModeChanged = false; return true; } else { return false; } } // Reset state changed flag m_MaskingModeChanged = false; // Depending on masking mode, extract and/or generate the required image // and mask data from the user input this->ExtractImageAndMask( ); Statistics *statistics; HistogramType::ConstPointer *histogram; switch ( m_MaskingMode ) { case MASKING_MODE_NONE: default: statistics = &m_ImageStatistics; histogram = &m_ImageHistogram; m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = false; break; case MASKING_MODE_IMAGE: statistics = &m_MaskedImageStatistics; histogram = &m_MaskedImageHistogram; m_MaskedImageStatisticsTimeStamp.Modified(); m_MaskedImageStatisticsCalculationTriggerBool = false; break; case MASKING_MODE_PLANARFIGURE: statistics = &m_PlanarFigureStatistics; histogram = &m_PlanarFigureHistogram; m_PlanarFigureStatisticsTimeStamp.Modified(); m_PlanarFigureStatisticsCalculationTriggerBool = false; break; } // Calculate statistics and histogram(s) if ( m_InternalImage->GetDimension() == 3 ) { if ( m_MaskingMode == MASKING_MODE_NONE ) { // Reset state changed flag AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateStatisticsUnmasked, 3, *statistics, histogram ); } else { AccessFixedDimensionByItk_3( m_InternalImage, InternalCalculateStatisticsMasked, 3, m_InternalImageMask3D.GetPointer(), *statistics, histogram ); } } else if ( m_InternalImage->GetDimension() == 2 ) { if ( m_MaskingMode == MASKING_MODE_NONE ) { AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateStatisticsUnmasked, 2, *statistics, histogram ); } else { AccessFixedDimensionByItk_3( m_InternalImage, InternalCalculateStatisticsMasked, 2, m_InternalImageMask2D.GetPointer(), *statistics, histogram ); } } else { MITK_ERROR << "ImageStatistics: Image dimension not supported!"; } // Release unused image smart pointers to free memory // m_InternalImage = mitk::Image::Pointer(); m_InternalImageMask3D = MaskImage3DType::Pointer(); m_InternalImageMask2D = MaskImage2DType::Pointer(); return true; } const PartialVolumeAnalysisHistogramCalculator::HistogramType * PartialVolumeAnalysisHistogramCalculator::GetHistogram( ) const { if ( m_Image.IsNull() ) { return NULL; } switch ( m_MaskingMode ) { case MASKING_MODE_NONE: default: return m_ImageHistogram; case MASKING_MODE_IMAGE: return m_MaskedImageHistogram; case MASKING_MODE_PLANARFIGURE: return m_PlanarFigureHistogram; } } const PartialVolumeAnalysisHistogramCalculator::Statistics & PartialVolumeAnalysisHistogramCalculator::GetStatistics( ) const { if ( m_Image.IsNull() ) { return m_EmptyStatistics; } switch ( m_MaskingMode ) { case MASKING_MODE_NONE: default: return m_ImageStatistics; case MASKING_MODE_IMAGE: return m_MaskedImageStatistics; case MASKING_MODE_PLANARFIGURE: return m_PlanarFigureStatistics; } } void PartialVolumeAnalysisHistogramCalculator::ExtractImageAndMask( ) { MITK_DEBUG << "ExtractImageAndMask( ) start"; if ( m_Image.IsNull() ) { throw std::runtime_error( "Error: image empty!" ); } mitk::Image *timeSliceImage = const_cast(m_Image.GetPointer());//imageTimeSelector->GetOutput(); switch ( m_MaskingMode ) { case MASKING_MODE_NONE: { m_InternalImage = timeSliceImage; int s = m_AdditionalResamplingImages.size(); m_InternalAdditionalResamplingImages.resize(s); for(int i=0; i(m_AdditionalResamplingImages[i].GetPointer()); } m_InternalImageMask2D = NULL; m_InternalImageMask3D = NULL; break; } case MASKING_MODE_IMAGE: { if ( m_ImageMask.IsNotNull() && (m_ImageMask->GetReferenceCount() > 1) ) { ImageTimeSelector::Pointer maskedImageTimeSelector = ImageTimeSelector::New(); maskedImageTimeSelector->SetInput( m_ImageMask ); maskedImageTimeSelector->SetTimeNr( 0 ); maskedImageTimeSelector->UpdateLargestPossibleRegion(); mitk::Image *timeSliceMaskedImage = maskedImageTimeSelector->GetOutput(); InternalMaskImage(timeSliceMaskedImage); if(m_UpsamplingFactor != 1) { InternalResampleImage(m_InternalImageMask3D); } AccessFixedDimensionByItk_1( timeSliceImage, InternalResampleImageFromMask, 3, -1 ); int s = m_AdditionalResamplingImages.size(); m_InternalAdditionalResamplingImages.resize(s); for(int i=0; iIsClosed() ) { throw std::runtime_error( "Masking not possible for non-closed figures" ); } const BaseGeometry *imageGeometry = timeSliceImage->GetUpdatedGeometry(); if ( imageGeometry == NULL ) { throw std::runtime_error( "Image geometry invalid!" ); } const PlaneGeometry *planarFigureGeometry2D = m_PlanarFigure->GetPlaneGeometry(); if ( planarFigureGeometry2D == NULL ) { throw std::runtime_error( "Planar-Figure not yet initialized!" ); } const PlaneGeometry *planarFigureGeometry = dynamic_cast< const PlaneGeometry * >( planarFigureGeometry2D ); - if ( planarFigureGeometry == NULL ) + const AbstractTransformGeometry *abstrTransfGeometry = + dynamic_cast< const AbstractTransformGeometry * >( planarFigureGeometry2D ); + + if ( !planarFigureGeometry || abstrTransfGeometry ) { - throw std::runtime_error( "Non-planar planar figures not supported!" ); + throw std::runtime_error( "Only PlaneGeometry supported." ); } + // unsigned int axis = 2; // unsigned int slice = 0; AccessFixedDimensionByItk_3( timeSliceImage, InternalReorientImagePlane, 3, timeSliceImage->GetGeometry(), m_PlanarFigure->GetGeometry(), -1 ); AccessFixedDimensionByItk_1( m_InternalImage, InternalCalculateMaskFromPlanarFigure, 3, 2 ); int s = m_AdditionalResamplingImages.size(); for(int i=0; iGetGeometry(), m_PlanarFigure->GetGeometry(), i ); AccessFixedDimensionByItk_1( m_InternalAdditionalResamplingImages[i], InternalCropAdditionalImage, 3, i ); } } } } bool PartialVolumeAnalysisHistogramCalculator::GetPrincipalAxis( const Geometry3D *geometry, Vector3D vector, unsigned int &axis ) { vector.Normalize(); for ( unsigned int i = 0; i < 3; ++i ) { Vector3D axisVector = geometry->GetAxisVector( i ); axisVector.Normalize(); if ( fabs( fabs( axisVector * vector ) - 1.0) < mitk::eps ) { axis = i; return true; } } return false; } void PartialVolumeAnalysisHistogramCalculator::InternalMaskImage( mitk::Image *image ) { typedef itk::ImageMaskSpatialObject<3> ImageMaskSpatialObject; typedef itk::Image< unsigned char, 3 > ImageType; typedef itk::ImageRegion<3> RegionType; typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(image); caster->Update(); ImageMaskSpatialObject::Pointer maskSO = ImageMaskSpatialObject::New(); maskSO->SetImage ( caster->GetOutput() ); m_InternalMask3D = maskSO->GetAxisAlignedBoundingBoxRegion(); // check if bounding box is empty, if so set it to 1,1,1 // to prevent empty mask image if (m_InternalMask3D.GetSize()[0] == 0 ) { m_InternalMask3D.SetSize(0,1); m_InternalMask3D.SetSize(1,1); m_InternalMask3D.SetSize(2,1); } MITK_DEBUG << "Bounding Box Region: " << m_InternalMask3D; typedef itk::RegionOfInterestImageFilter< ImageType, MaskImage3DType > ROIFilterType; ROIFilterType::Pointer roi = ROIFilterType::New(); roi->SetRegionOfInterest(m_InternalMask3D); roi->SetInput(caster->GetOutput()); roi->Update(); m_InternalImageMask3D = roi->GetOutput(); MITK_DEBUG << "Created m_InternalImageMask3D"; } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::BaseGeometry* , mitk::BaseGeometry* planegeo3D, int additionalIndex ) { MITK_DEBUG << "InternalReorientImagePlane() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< float, VImageDimension > FloatImageType; typedef itk::ResampleImageFilter ResamplerType; typename ResamplerType::Pointer resampler = ResamplerType::New(); mitk::PlaneGeometry* planegeo = dynamic_cast(planegeo3D); + if ( !planegeo ) + { + throw std::runtime_error( "Unexpected null pointer returned for pointer to PlaneGeometry." ); + } + else + { + mitk::AbstractTransformGeometry* abstrGeo = dynamic_cast(planegeo3D); + if ( abstrGeo ) + { + throw std::runtime_error( "Unexpected pointer to AbstractTransformGeometry returned." ); + } + } float upsamp = m_UpsamplingFactor; float gausssigma = m_GaussianSigma; // Spacing typename ResamplerType::SpacingType spacing = planegeo->GetSpacing(); spacing[0] = image->GetSpacing()[0] / upsamp; spacing[1] = image->GetSpacing()[1] / upsamp; spacing[2] = image->GetSpacing()[2]; if(m_PlanarFigureThickness) { spacing[2] = image->GetSpacing()[2] / upsamp; } resampler->SetOutputSpacing( spacing ); // Size typename ResamplerType::SizeType size; size[0] = planegeo->GetExtentInMM(0) / spacing[0]; size[1] = planegeo->GetExtentInMM(1) / spacing[1]; size[2] = 1+2*m_PlanarFigureThickness; // klaus add +2*m_PlanarFigureThickness MITK_DEBUG << "setting size2:="<SetSize( size ); // Origin typename mitk::Point3D orig = planegeo->GetOrigin(); typename mitk::Point3D corrorig; planegeo3D->WorldToIndex(orig,corrorig); corrorig[0] += 0.5/upsamp; corrorig[1] += 0.5/upsamp; if(m_PlanarFigureThickness) { float thickyyy = m_PlanarFigureThickness; thickyyy/=upsamp; corrorig[2] -= thickyyy; // klaus add -= (float)m_PlanarFigureThickness/upsamp statt += 0 } planegeo3D->IndexToWorld(corrorig,corrorig); resampler->SetOutputOrigin(corrorig ); // Direction typename ResamplerType::DirectionType direction; typename mitk::AffineTransform3D::MatrixType matrix = planegeo->GetIndexToWorldTransform()->GetMatrix(); for(int c=0; cSetOutputDirection( direction ); // Gaussian interpolation if(gausssigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = gausssigma * image->GetSpacing()[d]; } double alpha = 2.0; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typename GaussianInterpolatorType::Pointer interpolator = GaussianInterpolatorType::New(); interpolator->SetInputImage( image ); interpolator->SetParameters( sigma, alpha ); resampler->SetInterpolator( interpolator ); } else { // typedef typename itk::BSplineInterpolateImageFunction // InterpolatorType; typedef typename itk::LinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); } // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); MITK_DEBUG << "Resampling requested image plane ... "; resampler->Update(); MITK_DEBUG << " ... done"; if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( resampler->GetOutput() ); this->m_InternalImage->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } else { unsigned int myIndex = additionalIndex; this->m_InternalAdditionalResamplingImages.push_back(mitk::Image::New()); this->m_InternalAdditionalResamplingImages[myIndex]->InitializeByItk( resampler->GetOutput() ); this->m_InternalAdditionalResamplingImages[myIndex]->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalResampleImageFromMask( const itk::Image< TPixel, VImageDimension > *image, int additionalIndex ) { typedef itk::Image< TPixel, VImageDimension > ImageType; typename ImageType::Pointer outImage = ImageType::New(); outImage->SetSpacing( m_InternalImageMask3D->GetSpacing() ); // Set the image spacing outImage->SetOrigin( m_InternalImageMask3D->GetOrigin() ); // Set the image origin outImage->SetDirection( m_InternalImageMask3D->GetDirection() ); // Set the image direction outImage->SetRegions( m_InternalImageMask3D->GetLargestPossibleRegion() ); outImage->Allocate(); outImage->FillBuffer(0); typedef itk::InterpolateImageFunction BaseInterpType; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typedef itk::LinearInterpolateImageFunction LinearInterpolatorType; typename BaseInterpType::Pointer interpolator; if(m_GaussianSigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = m_GaussianSigma * image->GetSpacing()[d]; } double alpha = 2.0; interpolator = GaussianInterpolatorType::New(); dynamic_cast(interpolator.GetPointer())->SetParameters( sigma, alpha ); } else { interpolator = LinearInterpolatorType::New(); } interpolator->SetInputImage( image ); itk::ImageRegionConstIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itk::ImageRegionIterator itimage(outImage, outImage->GetLargestPossibleRegion()); itmask.GoToBegin(); itimage.GoToBegin(); itk::Point< double, 3 > point; itk::ContinuousIndex< double, 3 > index; while( !itmask.IsAtEnd() ) { if(itmask.Get() != 0) { outImage->TransformIndexToPhysicalPoint (itimage.GetIndex(), point); image->TransformPhysicalPointToContinuousIndex(point, index); itimage.Set(interpolator->EvaluateAtContinuousIndex(index)); } ++itmask; ++itimage; } if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( outImage.GetPointer() ); this->m_InternalImage->SetVolume( outImage->GetBufferPointer() ); } else { this->m_InternalAdditionalResamplingImages[additionalIndex] = mitk::Image::New(); this->m_InternalAdditionalResamplingImages[additionalIndex]->InitializeByItk( outImage.GetPointer() ); this->m_InternalAdditionalResamplingImages[additionalIndex]->SetVolume( outImage->GetBufferPointer() ); } } void PartialVolumeAnalysisHistogramCalculator::InternalResampleImage( const MaskImage3DType *image ) { typedef itk::ResampleImageFilter ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); // Size ResamplerType::SizeType size; size[0] = m_UpsamplingFactor * image->GetLargestPossibleRegion().GetSize()[0]; size[1] = m_UpsamplingFactor * image->GetLargestPossibleRegion().GetSize()[1]; size[2] = m_UpsamplingFactor * image->GetLargestPossibleRegion().GetSize()[2];; resampler->SetSize( size ); // Origin mitk::Point3D orig = image->GetOrigin(); resampler->SetOutputOrigin(orig ); // Spacing ResamplerType::SpacingType spacing; spacing[0] = image->GetSpacing()[0] / m_UpsamplingFactor; spacing[1] = image->GetSpacing()[1] / m_UpsamplingFactor; spacing[2] = image->GetSpacing()[2] / m_UpsamplingFactor; resampler->SetOutputSpacing( spacing ); resampler->SetOutputDirection( image->GetDirection() ); typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); resampler->Update(); m_InternalImageMask3D = resampler->GetOutput(); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCalculateStatisticsUnmasked( const itk::Image< TPixel, VImageDimension > *image, Statistics &statistics, typename HistogramType::ConstPointer *histogram ) { MITK_DEBUG << "InternalCalculateStatisticsUnmasked()"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< unsigned char, VImageDimension > MaskImageType; typedef typename ImageType::IndexType IndexType; // Progress listening... typedef itk::SimpleMemberCommand< PartialVolumeAnalysisHistogramCalculator > ITKCommandType; ITKCommandType::Pointer progressListener; progressListener = ITKCommandType::New(); progressListener->SetCallbackFunction( this, &PartialVolumeAnalysisHistogramCalculator::UnmaskedStatisticsProgressUpdate ); // Issue 100 artificial progress events since ScalarIMageToHistogramGenerator // does not (yet?) support progress reporting this->InvokeEvent( itk::StartEvent() ); for ( unsigned int i = 0; i < 100; ++i ) { this->UnmaskedStatisticsProgressUpdate(); } // Calculate statistics (separate filter) typedef itk::StatisticsImageFilter< ImageType > StatisticsFilterType; typename StatisticsFilterType::Pointer statisticsFilter = StatisticsFilterType::New(); statisticsFilter->SetInput( image ); unsigned long observerTag = statisticsFilter->AddObserver( itk::ProgressEvent(), progressListener ); statisticsFilter->Update(); statisticsFilter->RemoveObserver( observerTag ); this->InvokeEvent( itk::EndEvent() ); statistics.N = image->GetBufferedRegion().GetNumberOfPixels(); statistics.Min = statisticsFilter->GetMinimum(); statistics.Max = statisticsFilter->GetMaximum(); statistics.Mean = statisticsFilter->GetMean(); statistics.Median = 0.0; statistics.Sigma = statisticsFilter->GetSigma(); statistics.RMS = sqrt( statistics.Mean * statistics.Mean + statistics.Sigma * statistics.Sigma ); typename ImageType::Pointer inImage = const_cast(image); // Calculate histogram typedef itk::Statistics::ScalarImageToHistogramGenerator< ImageType > HistogramGeneratorType; typename HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New(); histogramGenerator->SetInput( inImage ); histogramGenerator->SetMarginalScale( 10 ); // Defines y-margin width of histogram histogramGenerator->SetNumberOfBins( m_NumberOfBins ); // CT range [-1024, +2048] --> bin size 4 values histogramGenerator->SetHistogramMin( statistics.Min ); histogramGenerator->SetHistogramMax( statistics.Max ); histogramGenerator->Compute(); *histogram = histogramGenerator->GetOutput(); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCalculateStatisticsMasked( const itk::Image< TPixel, VImageDimension > *image, itk::Image< unsigned char, VImageDimension > *maskImage, Statistics &, typename HistogramType::ConstPointer *histogram ) { MITK_DEBUG << "InternalCalculateStatisticsMasked() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< unsigned char, VImageDimension > MaskImageType; typedef typename ImageType::IndexType IndexType; // generate a list sample of angles at positions // where the fiber-prob is higher than .2*maxprob typedef TPixel MeasurementType; const unsigned int MeasurementVectorLength = 1; typedef itk::Vector< MeasurementType , MeasurementVectorLength > MeasurementVectorType; typedef itk::Statistics::ListSample< MeasurementVectorType > ListSampleType; typename ListSampleType::Pointer listSample = ListSampleType::New(); listSample->SetMeasurementVectorSize( MeasurementVectorLength ); itk::ImageRegionConstIterator itmask(maskImage, maskImage->GetLargestPossibleRegion()); itk::ImageRegionConstIterator itimage(image, image->GetLargestPossibleRegion()); itmask.GoToBegin(); itimage.GoToBegin(); while( !itmask.IsAtEnd() ) { if(itmask.Get() != 0) { // apend to list MeasurementVectorType mv; mv[0] = ( MeasurementType ) itimage.Get(); listSample->PushBack(mv); } ++itmask; ++itimage; } // generate a histogram from the list sample typedef double HistogramMeasurementType; typedef itk::Statistics::Histogram< HistogramMeasurementType, itk::Statistics::DenseFrequencyContainer2 > HistogramType; typedef itk::Statistics::SampleToHistogramFilter< ListSampleType, HistogramType > GeneratorType; typename GeneratorType::Pointer generator = GeneratorType::New(); typename GeneratorType::HistogramType::SizeType size(MeasurementVectorLength); size.Fill(m_NumberOfBins); generator->SetHistogramSize( size ); generator->SetInput( listSample ); generator->SetMarginalScale( 10.0 ); generator->Update(); *histogram = generator->GetOutput(); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCropAdditionalImage( itk::Image< TPixel, VImageDimension > *image, int additionalIndex ) { typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::RegionOfInterestImageFilter< ImageType, ImageType > ROIFilterType; typename ROIFilterType::Pointer roi = ROIFilterType::New(); roi->SetRegionOfInterest(m_CropRegion); roi->SetInput(image); roi->Update(); m_InternalAdditionalResamplingImages[additionalIndex] = mitk::Image::New(); m_InternalAdditionalResamplingImages[additionalIndex]->InitializeByItk(roi->GetOutput()); m_InternalAdditionalResamplingImages[additionalIndex]->SetVolume(roi->GetOutput()->GetBufferPointer()); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis ) { MITK_DEBUG << "InternalCalculateMaskFromPlanarFigure() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::CastImageFilter< ImageType, MaskImage3DType > CastFilterType; // Generate mask image as new image with same header as input image and // initialize with "1". MaskImage3DType::Pointer newMaskImage = MaskImage3DType::New(); newMaskImage->SetSpacing( image->GetSpacing() ); // Set the image spacing newMaskImage->SetOrigin( image->GetOrigin() ); // Set the image origin newMaskImage->SetDirection( image->GetDirection() ); // Set the image direction newMaskImage->SetRegions( image->GetLargestPossibleRegion() ); newMaskImage->Allocate(); newMaskImage->FillBuffer( 1 ); // Generate VTK polygon from (closed) PlanarFigure polyline // (The polyline points are shifted by -0.5 in z-direction to make sure // that the extrusion filter, which afterwards elevates all points by +0.5 // in z-direction, creates a 3D object which is cut by the the plane z=0) const mitk::PlaneGeometry *planarFigureGeometry2D = m_PlanarFigure->GetPlaneGeometry(); const typename PlanarFigure::PolyLineType planarFigurePolyline = m_PlanarFigure->GetPolyLine( 0 ); const mitk::BaseGeometry *imageGeometry3D = m_InternalImage->GetGeometry( 0 ); vtkPolyData *polyline = vtkPolyData::New(); polyline->Allocate( 1, 1 ); // Determine x- and y-dimensions depending on principal axis int i0, i1; switch ( axis ) { case 0: i0 = 1; i1 = 2; break; case 1: i0 = 0; i1 = 2; break; case 2: default: i0 = 0; i1 = 1; break; } // Create VTK polydata object of polyline contour bool outOfBounds = false; vtkPoints *points = vtkPoints::New(); typename PlanarFigure::PolyLineType::const_iterator it; for ( it = planarFigurePolyline.begin(); it != planarFigurePolyline.end(); ++it ) { Point3D point3D; // Convert 2D point back to the local index coordinates of the selected // image mitk::Point2D point2D = *it; planarFigureGeometry2D->WorldToIndex(point2D, point2D); point2D[0] -= 0.5/m_UpsamplingFactor; point2D[1] -= 0.5/m_UpsamplingFactor; planarFigureGeometry2D->IndexToWorld(point2D, point2D); planarFigureGeometry2D->Map( point2D, point3D ); // Polygons (partially) outside of the image bounds can not be processed // further due to a bug in vtkPolyDataToImageStencil if ( !imageGeometry3D->IsInside( point3D ) ) { outOfBounds = true; } imageGeometry3D->WorldToIndex( point3D, point3D ); point3D[i0] += 0.5; point3D[i1] += 0.5; // Add point to polyline array points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); } polyline->SetPoints( points ); points->Delete(); if ( outOfBounds ) { polyline->Delete(); throw std::runtime_error( "Figure at least partially outside of image bounds!" ); } std::size_t numberOfPoints = planarFigurePolyline.size(); vtkIdType *ptIds = new vtkIdType[numberOfPoints]; for ( std::size_t i = 0; i < numberOfPoints; ++i ) { ptIds[i] = i; } polyline->InsertNextCell( VTK_POLY_LINE, numberOfPoints, ptIds ); // Extrude the generated contour polygon vtkLinearExtrusionFilter *extrudeFilter = vtkLinearExtrusionFilter::New(); extrudeFilter->SetInputData( polyline ); extrudeFilter->SetScaleFactor( 1 ); extrudeFilter->SetExtrusionTypeToNormalExtrusion(); extrudeFilter->SetVector( 0.0, 0.0, 1.0 ); // Make a stencil from the extruded polygon vtkPolyDataToImageStencil *polyDataToImageStencil = vtkPolyDataToImageStencil::New(); polyDataToImageStencil->SetInputConnection( extrudeFilter->GetOutputPort() ); // Export from ITK to VTK (to use a VTK filter) typedef itk::VTKImageImport< MaskImage3DType > ImageImportType; typedef itk::VTKImageExport< MaskImage3DType > ImageExportType; typename ImageExportType::Pointer itkExporter = ImageExportType::New(); itkExporter->SetInput( newMaskImage ); vtkImageImport *vtkImporter = vtkImageImport::New(); this->ConnectPipelines( itkExporter, vtkImporter ); vtkImporter->Update(); // Apply the generated image stencil to the input image vtkImageStencil *imageStencilFilter = vtkImageStencil::New(); imageStencilFilter->SetInputData( vtkImporter->GetOutput() ); imageStencilFilter->SetStencilConnection(polyDataToImageStencil->GetOutputPort() ); imageStencilFilter->ReverseStencilOff(); imageStencilFilter->SetBackgroundValue( 0 ); imageStencilFilter->Update(); // Export from VTK back to ITK vtkImageExport *vtkExporter = vtkImageExport::New(); vtkExporter->SetInputData( imageStencilFilter->GetOutput() ); vtkExporter->Update(); typename ImageImportType::Pointer itkImporter = ImageImportType::New(); this->ConnectPipelines( vtkExporter, itkImporter ); itkImporter->Update(); // calculate cropping bounding box m_InternalImageMask3D = itkImporter->GetOutput(); m_InternalImageMask3D->SetDirection(image->GetDirection()); itk::ImageRegionIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itmask.GoToBegin(); while( !itmask.IsAtEnd() ) { if(itmask.Get() != 0) { typename ImageType::IndexType index = itmask.GetIndex(); for(unsigned int thick=0; thick<2*m_PlanarFigureThickness+1; thick++) { index[axis] = thick; m_InternalImageMask3D->SetPixel(index, itmask.Get()); } } ++itmask; } itmask.GoToBegin(); itk::ImageRegionIterator itimage(image, image->GetLargestPossibleRegion()); itimage.GoToBegin(); typename ImageType::SizeType lowersize; lowersize.Fill(std::numeric_limits::max()); typename ImageType::SizeType uppersize; uppersize.Fill(std::numeric_limits::min()); while( !itmask.IsAtEnd() ) { if(itmask.Get() == 0) { itimage.Set(0); } else { typename ImageType::IndexType index = itimage.GetIndex(); typename ImageType::SizeType signedindex; signedindex[0] = index[0]; signedindex[1] = index[1]; signedindex[2] = index[2]; lowersize[0] = signedindex[0] < lowersize[0] ? signedindex[0] : lowersize[0]; lowersize[1] = signedindex[1] < lowersize[1] ? signedindex[1] : lowersize[1]; lowersize[2] = signedindex[2] < lowersize[2] ? signedindex[2] : lowersize[2]; uppersize[0] = signedindex[0] > uppersize[0] ? signedindex[0] : uppersize[0]; uppersize[1] = signedindex[1] > uppersize[1] ? signedindex[1] : uppersize[1]; uppersize[2] = signedindex[2] > uppersize[2] ? signedindex[2] : uppersize[2]; } ++itmask; ++itimage; } typename ImageType::IndexType index; index[0] = lowersize[0]; index[1] = lowersize[1]; index[2] = lowersize[2]; typename ImageType::SizeType size; size[0] = uppersize[0] - lowersize[0] + 1; size[1] = uppersize[1] - lowersize[1] + 1; size[2] = uppersize[2] - lowersize[2] + 1; m_CropRegion = itk::ImageRegion<3>(index, size); // crop internal image typedef itk::RegionOfInterestImageFilter< ImageType, ImageType > ROIFilterType; typename ROIFilterType::Pointer roi = ROIFilterType::New(); roi->SetRegionOfInterest(m_CropRegion); roi->SetInput(image); roi->Update(); m_InternalImage = mitk::Image::New(); m_InternalImage->InitializeByItk(roi->GetOutput()); m_InternalImage->SetVolume(roi->GetOutput()->GetBufferPointer()); // crop internal mask typedef itk::RegionOfInterestImageFilter< MaskImage3DType, MaskImage3DType > ROIMaskFilterType; typename ROIMaskFilterType::Pointer roi2 = ROIMaskFilterType::New(); roi2->SetRegionOfInterest(m_CropRegion); roi2->SetInput(m_InternalImageMask3D); roi2->Update(); m_InternalImageMask3D = roi2->GetOutput(); // Clean up VTK objects polyline->Delete(); extrudeFilter->Delete(); polyDataToImageStencil->Delete(); vtkImporter->Delete(); imageStencilFilter->Delete(); //vtkExporter->Delete(); // TODO: crashes when outcommented; memory leak?? delete[] ptIds; } void PartialVolumeAnalysisHistogramCalculator::UnmaskedStatisticsProgressUpdate() { // Need to throw away every second progress event to reach a final count of // 100 since two consecutive filters are used in this case static int updateCounter = 0; if ( updateCounter++ % 2 == 0 ) { this->InvokeEvent( itk::ProgressEvent() ); } } void PartialVolumeAnalysisHistogramCalculator::MaskedStatisticsProgressUpdate() { this->InvokeEvent( itk::ProgressEvent() ); } } diff --git a/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkDiffusionImage.h b/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkDiffusionImage.h index ebabe569b5..0c3092e558 100644 --- a/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkDiffusionImage.h +++ b/Modules/DiffusionImaging/DiffusionCore/IODataStructures/DiffusionWeightedImages/mitkDiffusionImage.h @@ -1,217 +1,218 @@ /*=================================================================== 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 __mitkDiffusionImage__h #define __mitkDiffusionImage__h #include "mitkImage.h" #include "itkVectorImage.h" #include "itkVectorImageToImageAdaptor.h" +#include namespace mitk { /** * \brief this class encapsulates diffusion volumes (vectorimages not * yet supported by mitkImage) */ template< class TPixelType > class DiffusionImage : public Image { public: typedef typename itk::VectorImage ImageType; typedef vnl_vector_fixed< double, 3 > GradientDirectionType; typedef itk::VectorContainer< unsigned int,GradientDirectionType > GradientDirectionContainerType; typedef GradientDirectionContainerType::Pointer GradientDirectionContainerTypePointer; typedef vnl_matrix_fixed< double, 3, 3 > MeasurementFrameType; typedef std::vector< unsigned int > IndicesVector; + typedef itk::VectorImage< TPixelType, 3 > ItkDwiType; + typedef itk::ImageDuplicator< ItkDwiType > DwiDuplicatorType; /** * \brief The BValueMap contains seperated IndicesVectors for each b value (index for GradientDirectionContainer) * key := b value * value := indicesVector */ typedef std::map< unsigned int , IndicesVector > BValueMap; mitkClassMacro( DiffusionImage, Image ) itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * \brief Return the itkVectorImage as pointer */ typename ImageType::Pointer GetVectorImage(); /** * \brief Return the itkVectorImage as const pointer */ const typename ImageType::Pointer GetVectorImage() const; /** * \brief Set the itkVectorImage * * \param SmartPointer ofitk::VectorImage */ void SetVectorImage(typename ImageType::Pointer image ); /** * \brief Initialize the mitkImage (base-class) using the first b-zero value of the itkVectorImage * * \warning First set itkVectorImage, GradientDirectionContainer and the b value of the image. * Has to be called. */ void InitializeFromVectorImage(); /** * \brief Return the directions as GradientDirectionContainer const pointer * * \warning MeasurementFrame already applied */ GradientDirectionContainerType::Pointer GetDirections() const; /** * \brief Return the directions as GradientDirectionContainer const pointer * * \warning no MeasurmentFrame applied */ GradientDirectionContainerType::Pointer GetDirectionsWithoutMeasurementFrame() const; /** * \brief Set the original and current GradientDirectionContainer * \param GradientdirectionContainer as pointer * \warning Replace the original (m_OriginalDirections) and current (m_Directions) GradientDirectionContainer. * For the current directions the MeasurmentFrame is applied. Remove existing GradientDirectionContainer observer * of m_Directions and add a new observer to it (observer update the m_B_ValueMap if modifications occours on the container) */ void SetDirections( GradientDirectionContainerType::Pointer directions ); /** * \brief Set the original and current GradientDirectionContainer * \param std::vector > * \warning Replace the original (m_OriginalDirections) and current (m_Directions) GradientDirectionContainer. * For the current directions the MeasurmentFrame is applied. * Remove existing GradientDirectionContainer observer of m_Directions and add a new observer to it * (observer update the m_B_ValueMap if modifications occours on the container). * Calls the overloaded GradientDirectionContainer pointer version of the method. */ void SetDirections( const std::vector > & directions ); /** * \brief Return a copy of the MeasurmentFrame (m_MeasurementFrame) */ MeasurementFrameType GetMeasurementFrame() const; /** * \brief Set the MeasurementFrame * * \param Const reference of MeasurementFrameType */ void SetMeasurementFrame( const MeasurementFrameType & mFrame ); /** * \brief Return true if gradients of with diffrent b-values exist */ bool GetNumberOfBValues() const; /** * \brief Return a BValueMap (key: b value, Value: IndicesVector of the GradientDirectionContainer) */ const BValueMap & GetBValueMap() const; /** * \brief Return the reference b value * GradientsLength * referenceBValue encoding the true b value of the corresponding GradientDirection */ float GetReferenceBValue() const; /** * \brief Set the reference b value s */ void SetReferenceBValue( float val ); GradientDirectionContainerType::Pointer CalcAveragedDirectionSet(double precision, GradientDirectionContainerType::Pointer directions); void AverageRedundantGradients(double precision); void SetDisplayIndexForRendering(int displayIndex); - - protected: mitkCloneMacro(Self); DiffusionImage(); DiffusionImage(const DiffusionImage &); virtual ~DiffusionImage(); // Helper Methods bool AreAlike(GradientDirectionType g1, GradientDirectionType g2, double precision); float GetB_Value(unsigned int i); /** * \brief Apply the previouse set MeasurmentFrame to all gradients in the GradientsDirectionContainer (m_Directions) * * \warning first set the MeasurmentFrame */ void ApplyMeasurementFrame(); /** * \brief Update the BValueMap (m_B_ValueMap) using the current gradient directions (m_Directions) * * \warning Have to be called after each manipulation on the GradientDirectionContainer * !especially after manipulation of the m_Directions (GetDirections()) container via pointer access! */ void UpdateBValueMap(); typename ImageType::Pointer m_VectorImage; float m_B_Value; MeasurementFrameType m_MeasurementFrame; GradientDirectionContainerType::Pointer m_OriginalDirections; GradientDirectionContainerType::Pointer m_Directions; int m_DisplayIndex; BValueMap m_B_ValueMap; }; /** * @brief Equal A function comparing two images for beeing equal in meta- and imagedata * * @ingroup MITKTestingAPI * * Following aspects are tested for equality: * - mitk image equal test * - GradientDirectionContainer * - MeasurementFrame * - reference BValue * - BValueMap * - itkVectorImage * * @param rightHandSide An image to be compared * @param leftHandSide An image to be compared * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return true, if all subsequent comparisons are true, false otherwise */ template inline bool Equal(const mitk::DiffusionImage &leftHandSide, const mitk::DiffusionImage &rightHandSide, ScalarType eps, bool verbose ); } // namespace mitk #include "mitkDiffusionImage.txx" #endif /* __mitkDiffusionImage__h */ diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp index 3467b387aa..af5223aafd 100755 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp @@ -1,1013 +1,1258 @@ /*=================================================================== 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 "itkTractsToDWIImageFilter.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include +#include #include namespace itk { template< class PixelType > TractsToDWIImageFilter< PixelType >::TractsToDWIImageFilter() : m_FiberBundle(NULL) , m_StatusText("") , m_UseConstantRandSeed(false) , m_RandGen(itk::Statistics::MersenneTwisterRandomVariateGenerator::New()) + , m_NoAcquisitionSimulation(false) { m_RandGen->SetSeed(); } template< class PixelType > TractsToDWIImageFilter< PixelType >::~TractsToDWIImageFilter() { } template< class PixelType > TractsToDWIImageFilter< PixelType >::DoubleDwiType::Pointer TractsToDWIImageFilter< PixelType >::DoKspaceStuff( std::vector< DoubleDwiType::Pointer >& images ) { // create slice object ImageRegion<2> sliceRegion; sliceRegion.SetSize(0, m_UpsampledImageRegion.GetSize()[0]); sliceRegion.SetSize(1, m_UpsampledImageRegion.GetSize()[1]); Vector< double, 2 > sliceSpacing; sliceSpacing[0] = m_UpsampledSpacing[0]; sliceSpacing[1] = m_UpsampledSpacing[1]; // frequency map slice SliceType::Pointer fMapSlice = NULL; if (m_Parameters.m_FrequencyMap.IsNotNull()) { fMapSlice = SliceType::New(); ImageRegion<2> region; region.SetSize(0, m_UpsampledImageRegion.GetSize()[0]); region.SetSize(1, m_UpsampledImageRegion.GetSize()[1]); fMapSlice->SetLargestPossibleRegion( region ); fMapSlice->SetBufferedRegion( region ); fMapSlice->SetRequestedRegion( region ); fMapSlice->Allocate(); fMapSlice->FillBuffer(0.0); } DoubleDwiType::Pointer newImage = DoubleDwiType::New(); newImage->SetSpacing( m_Parameters.m_ImageSpacing ); newImage->SetOrigin( m_Parameters.m_ImageOrigin ); newImage->SetDirection( m_Parameters.m_ImageDirection ); newImage->SetLargestPossibleRegion( m_Parameters.m_ImageRegion ); newImage->SetBufferedRegion( m_Parameters.m_ImageRegion ); newImage->SetRequestedRegion( m_Parameters.m_ImageRegion ); newImage->SetVectorLength( images.at(0)->GetVectorLength() ); newImage->Allocate(); std::vector< unsigned int > spikeVolume; for (unsigned int i=0; iGetIntegerVariate()%images.at(0)->GetVectorLength()); std::sort (spikeVolume.begin(), spikeVolume.end()); std::reverse (spikeVolume.begin(), spikeVolume.end()); m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n"; m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*"; unsigned long lastTick = 0; boost::progress_display disp(2*images.at(0)->GetVectorLength()*images.at(0)->GetLargestPossibleRegion().GetSize(2)); for (unsigned int g=0; gGetVectorLength(); g++) { std::vector< unsigned int > spikeSlice; while (!spikeVolume.empty() && spikeVolume.back()==g) { spikeSlice.push_back(m_RandGen->GetIntegerVariate()%images.at(0)->GetLargestPossibleRegion().GetSize(2)); spikeVolume.pop_back(); } std::sort (spikeSlice.begin(), spikeSlice.end()); std::reverse (spikeSlice.begin(), spikeSlice.end()); for (unsigned int z=0; zGetLargestPossibleRegion().GetSize(2); z++) { std::vector< SliceType::Pointer > compartmentSlices; std::vector< double > t2Vector; for (unsigned int i=0; i* signalModel; if (iSetLargestPossibleRegion( sliceRegion ); slice->SetBufferedRegion( sliceRegion ); slice->SetRequestedRegion( sliceRegion ); slice->SetSpacing(sliceSpacing); slice->Allocate(); slice->FillBuffer(0.0); // extract slice from channel g for (unsigned int y=0; yGetLargestPossibleRegion().GetSize(1); y++) for (unsigned int x=0; xGetLargestPossibleRegion().GetSize(0); x++) { SliceType::IndexType index2D; index2D[0]=x; index2D[1]=y; DoubleDwiType::IndexType index3D; index3D[0]=x; index3D[1]=y; index3D[2]=z; slice->SetPixel(index2D, images.at(i)->GetPixel(index3D)[g]); if (fMapSlice.IsNotNull() && i==0) fMapSlice->SetPixel(index2D, m_Parameters.m_FrequencyMap->GetPixel(index3D)); } compartmentSlices.push_back(slice); t2Vector.push_back(signalModel->GetT2()); } if (this->GetAbortGenerateData()) return NULL; // create k-sapce (inverse fourier transform slices) itk::Size<2> outSize; outSize.SetElement(0, m_Parameters.m_ImageRegion.GetSize(0)); outSize.SetElement(1, m_Parameters.m_ImageRegion.GetSize(1)); itk::KspaceImageFilter< SliceType::PixelType >::Pointer idft = itk::KspaceImageFilter< SliceType::PixelType >::New(); idft->SetCompartmentImages(compartmentSlices); idft->SetT2(t2Vector); idft->SetUseConstantRandSeed(m_UseConstantRandSeed); idft->SetParameters(m_Parameters); idft->SetZ((double)z-(double)images.at(0)->GetLargestPossibleRegion().GetSize(2)/2.0); idft->SetDiffusionGradientDirection(m_Parameters.GetGradientDirection(g)); idft->SetFrequencyMapSlice(fMapSlice); idft->SetOutSize(outSize); int numSpikes = 0; while (!spikeSlice.empty() && spikeSlice.back()==z) { numSpikes++; spikeSlice.pop_back(); } idft->SetSpikesPerSlice(numSpikes); idft->Update(); ComplexSliceType::Pointer fSlice; fSlice = idft->GetOutput(); ++disp; unsigned long newTick = 50*disp.count()/disp.expected_count(); for (unsigned long tick = 0; tick<(newTick-lastTick); tick++) m_StatusText += "*"; lastTick = newTick; // fourier transform slice SliceType::Pointer newSlice; itk::DftImageFilter< SliceType::PixelType >::Pointer dft = itk::DftImageFilter< SliceType::PixelType >::New(); dft->SetInput(fSlice); dft->Update(); newSlice = dft->GetOutput(); // put slice back into channel g for (unsigned int y=0; yGetLargestPossibleRegion().GetSize(1); y++) for (unsigned int x=0; xGetLargestPossibleRegion().GetSize(0); x++) { DoubleDwiType::IndexType index3D; index3D[0]=x; index3D[1]=y; index3D[2]=z; SliceType::IndexType index2D; index2D[0]=x; index2D[1]=y; DoubleDwiType::PixelType pix3D = newImage->GetPixel(index3D); pix3D[g] = newSlice->GetPixel(index2D); newImage->SetPixel(index3D, pix3D); } ++disp; newTick = 50*disp.count()/disp.expected_count(); for (unsigned long tick = 0; tick<(newTick-lastTick); tick++) m_StatusText += "*"; lastTick = newTick; } } m_StatusText += "\n\n"; return newImage; } template< class PixelType > void TractsToDWIImageFilter< PixelType >::GenerateData() { m_TimeProbe.Start(); m_StatusText = "Starting simulation\n"; // check input data if (m_FiberBundle.IsNull()) itkExceptionMacro("Input fiber bundle is NULL!"); if (m_Parameters.m_NonFiberModelList.empty()) itkExceptionMacro("No diffusion model for non-fiber compartments defined!"); int baselineIndex = m_Parameters.GetFirstBaselineIndex(); if (baselineIndex<0) itkExceptionMacro("No baseline index found!"); if (m_UseConstantRandSeed) // always generate the same random numbers? m_RandGen->SetSeed(0); else m_RandGen->SetSeed(); // initialize output dwi image ImageRegion<3> croppedRegion = m_Parameters.m_ImageRegion; croppedRegion.SetSize(1, croppedRegion.GetSize(1)*m_Parameters.m_CroppingFactor); itk::Point shiftedOrigin = m_Parameters.m_ImageOrigin; shiftedOrigin[1] += (m_Parameters.m_ImageRegion.GetSize(1)-croppedRegion.GetSize(1))*m_Parameters.m_ImageSpacing[1]/2; typename OutputImageType::Pointer outImage = OutputImageType::New(); outImage->SetSpacing( m_Parameters.m_ImageSpacing ); outImage->SetOrigin( shiftedOrigin ); outImage->SetDirection( m_Parameters.m_ImageDirection ); outImage->SetLargestPossibleRegion( croppedRegion ); outImage->SetBufferedRegion( croppedRegion ); outImage->SetRequestedRegion( croppedRegion ); outImage->SetVectorLength( m_Parameters.GetNumVolumes() ); outImage->Allocate(); typename OutputImageType::PixelType temp; temp.SetSize(m_Parameters.GetNumVolumes()); temp.Fill(0.0); outImage->FillBuffer(temp); // ADJUST GEOMETRY FOR FURTHER PROCESSING // is input slize size a power of two? unsigned int x=m_Parameters.m_ImageRegion.GetSize(0); unsigned int y=m_Parameters.m_ImageRegion.GetSize(1); ItkDoubleImgType::SizeType pad; pad[0]=x%2; pad[1]=y%2; pad[2]=0; m_Parameters.m_ImageRegion.SetSize(0, x+pad[0]); m_Parameters.m_ImageRegion.SetSize(1, y+pad[1]); if (m_Parameters.m_FrequencyMap.IsNotNull() && (pad[0]>0 || pad[1]>0)) { itk::ConstantPadImageFilter::Pointer zeroPadder = itk::ConstantPadImageFilter::New(); zeroPadder->SetInput(m_Parameters.m_FrequencyMap); zeroPadder->SetConstant(0); zeroPadder->SetPadUpperBound(pad); zeroPadder->Update(); m_Parameters.m_FrequencyMap = zeroPadder->GetOutput(); } if (m_Parameters.m_MaskImage.IsNotNull() && (pad[0]>0 || pad[1]>0)) { itk::ConstantPadImageFilter::Pointer zeroPadder = itk::ConstantPadImageFilter::New(); zeroPadder->SetInput(m_Parameters.m_MaskImage); zeroPadder->SetConstant(0); zeroPadder->SetPadUpperBound(pad); zeroPadder->Update(); m_Parameters.m_MaskImage = zeroPadder->GetOutput(); } // Apply in-plane upsampling for Gibbs ringing artifact double upsampling = 1; if (m_Parameters.m_DoAddGibbsRinging) upsampling = 2; m_UpsampledSpacing = m_Parameters.m_ImageSpacing; m_UpsampledSpacing[0] /= upsampling; m_UpsampledSpacing[1] /= upsampling; m_UpsampledImageRegion = m_Parameters.m_ImageRegion; m_UpsampledImageRegion.SetSize(0, m_Parameters.m_ImageRegion.GetSize()[0]*upsampling); m_UpsampledImageRegion.SetSize(1, m_Parameters.m_ImageRegion.GetSize()[1]*upsampling); m_UpsampledOrigin = m_Parameters.m_ImageOrigin; m_UpsampledOrigin[0] -= m_Parameters.m_ImageSpacing[0]/2; m_UpsampledOrigin[0] += m_UpsampledSpacing[0]/2; m_UpsampledOrigin[1] -= m_Parameters.m_ImageSpacing[1]/2; m_UpsampledOrigin[1] += m_UpsampledSpacing[1]/2; m_UpsampledOrigin[2] -= m_Parameters.m_ImageSpacing[2]/2; m_UpsampledOrigin[2] += m_UpsampledSpacing[2]/2; // generate double images to store the individual compartment signals std::vector< DoubleDwiType::Pointer > compartments; for (unsigned int i=0; iSetSpacing( m_UpsampledSpacing ); doubleDwi->SetOrigin( m_UpsampledOrigin ); doubleDwi->SetDirection( m_Parameters.m_ImageDirection ); doubleDwi->SetLargestPossibleRegion( m_UpsampledImageRegion ); doubleDwi->SetBufferedRegion( m_UpsampledImageRegion ); doubleDwi->SetRequestedRegion( m_UpsampledImageRegion ); doubleDwi->SetVectorLength( m_Parameters.GetNumVolumes() ); doubleDwi->Allocate(); DoubleDwiType::PixelType pix; pix.SetSize(m_Parameters.GetNumVolumes()); pix.Fill(0.0); doubleDwi->FillBuffer(pix); compartments.push_back(doubleDwi); } // initialize output volume fraction images m_VolumeFractions.clear(); for (unsigned int i=0; iSetSpacing( m_UpsampledSpacing ); doubleImg->SetOrigin( m_UpsampledOrigin ); doubleImg->SetDirection( m_Parameters.m_ImageDirection ); doubleImg->SetLargestPossibleRegion( m_UpsampledImageRegion ); doubleImg->SetBufferedRegion( m_UpsampledImageRegion ); doubleImg->SetRequestedRegion( m_UpsampledImageRegion ); doubleImg->Allocate(); doubleImg->FillBuffer(0); m_VolumeFractions.push_back(doubleImg); } // get volume fraction images ItkDoubleImgType::Pointer sumImage = ItkDoubleImgType::New(); bool foundVolumeFractionImage = false; for (unsigned int i=0; iGetVolumeFractionImage().IsNotNull()) { foundVolumeFractionImage = true; itk::ConstantPadImageFilter::Pointer zeroPadder = itk::ConstantPadImageFilter::New(); zeroPadder->SetInput(m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()); zeroPadder->SetConstant(0); zeroPadder->SetPadUpperBound(pad); zeroPadder->Update(); m_Parameters.m_NonFiberModelList[i]->SetVolumeFractionImage(zeroPadder->GetOutput()); sumImage->SetSpacing( m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetSpacing() ); sumImage->SetOrigin( m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetOrigin() ); sumImage->SetDirection( m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetDirection() ); sumImage->SetLargestPossibleRegion( m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion() ); sumImage->SetBufferedRegion( m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion() ); sumImage->SetRequestedRegion( m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion() ); sumImage->Allocate(); sumImage->FillBuffer(0); break; } } if (!foundVolumeFractionImage) { sumImage->SetSpacing( m_UpsampledSpacing ); sumImage->SetOrigin( m_UpsampledOrigin ); sumImage->SetDirection( m_Parameters.m_ImageDirection ); sumImage->SetLargestPossibleRegion( m_UpsampledImageRegion ); sumImage->SetBufferedRegion( m_UpsampledImageRegion ); sumImage->SetRequestedRegion( m_UpsampledImageRegion ); sumImage->Allocate(); sumImage->FillBuffer(0.0); } for (unsigned int i=0; iGetVolumeFractionImage().IsNull()) { ItkDoubleImgType::Pointer doubleImg = ItkDoubleImgType::New(); doubleImg->SetSpacing( sumImage->GetSpacing() ); doubleImg->SetOrigin( sumImage->GetOrigin() ); doubleImg->SetDirection( sumImage->GetDirection() ); doubleImg->SetLargestPossibleRegion( sumImage->GetLargestPossibleRegion() ); doubleImg->SetBufferedRegion( sumImage->GetLargestPossibleRegion() ); doubleImg->SetRequestedRegion( sumImage->GetLargestPossibleRegion() ); doubleImg->Allocate(); doubleImg->FillBuffer(1.0/m_Parameters.m_NonFiberModelList.size()); m_Parameters.m_NonFiberModelList[i]->SetVolumeFractionImage(doubleImg); } ImageRegionIterator it(m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage(), m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion()); while(!it.IsAtEnd()) { sumImage->SetPixel(it.GetIndex(), sumImage->GetPixel(it.GetIndex())+it.Get()); ++it; } } for (unsigned int i=0; i it(m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage(), m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion()); while(!it.IsAtEnd()) { if (sumImage->GetPixel(it.GetIndex())>0) it.Set(it.Get()/sumImage->GetPixel(it.GetIndex())); ++it; } } // resample mask image and frequency map to fit upsampled geometry if (m_Parameters.m_DoAddGibbsRinging) { if (m_Parameters.m_MaskImage.IsNotNull()) { // rescale mask image (otherwise there are problems with the resampling) itk::RescaleIntensityImageFilter::Pointer rescaler = itk::RescaleIntensityImageFilter::New(); rescaler->SetInput(0,m_Parameters.m_MaskImage); rescaler->SetOutputMaximum(100); rescaler->SetOutputMinimum(0); rescaler->Update(); // resample mask image itk::ResampleImageFilter::Pointer resampler = itk::ResampleImageFilter::New(); resampler->SetInput(rescaler->GetOutput()); resampler->SetOutputParametersFromImage(m_Parameters.m_MaskImage); resampler->SetSize(m_UpsampledImageRegion.GetSize()); resampler->SetOutputSpacing(m_UpsampledSpacing); resampler->SetOutputOrigin(m_UpsampledOrigin); itk::NearestNeighborInterpolateImageFunction::Pointer nn_interpolator = itk::NearestNeighborInterpolateImageFunction::New(); resampler->SetInterpolator(nn_interpolator); resampler->Update(); m_Parameters.m_MaskImage = resampler->GetOutput(); itk::ImageFileWriter::Pointer w = itk::ImageFileWriter::New(); w->SetFileName("/local/mask_ups.nrrd"); w->SetInput(m_Parameters.m_MaskImage); w->Update(); } // resample frequency map if (m_Parameters.m_FrequencyMap.IsNotNull()) { itk::ResampleImageFilter::Pointer resampler = itk::ResampleImageFilter::New(); resampler->SetInput(m_Parameters.m_FrequencyMap); resampler->SetOutputParametersFromImage(m_Parameters.m_FrequencyMap); resampler->SetSize(m_UpsampledImageRegion.GetSize()); resampler->SetOutputSpacing(m_UpsampledSpacing); resampler->SetOutputOrigin(m_UpsampledOrigin); itk::NearestNeighborInterpolateImageFunction::Pointer nn_interpolator = itk::NearestNeighborInterpolateImageFunction::New(); resampler->SetInterpolator(nn_interpolator); resampler->Update(); m_Parameters.m_FrequencyMap = resampler->GetOutput(); } } // no input tissue mask is set -> create default bool maskImageSet = true; if (m_Parameters.m_MaskImage.IsNull()) { m_StatusText += "No tissue mask set\n"; MITK_INFO << "No tissue mask set"; m_Parameters.m_MaskImage = ItkUcharImgType::New(); m_Parameters.m_MaskImage->SetSpacing( m_UpsampledSpacing ); m_Parameters.m_MaskImage->SetOrigin( m_UpsampledOrigin ); m_Parameters.m_MaskImage->SetDirection( m_Parameters.m_ImageDirection ); m_Parameters.m_MaskImage->SetLargestPossibleRegion( m_UpsampledImageRegion ); m_Parameters.m_MaskImage->SetBufferedRegion( m_UpsampledImageRegion ); m_Parameters.m_MaskImage->SetRequestedRegion( m_UpsampledImageRegion ); m_Parameters.m_MaskImage->Allocate(); m_Parameters.m_MaskImage->FillBuffer(1); maskImageSet = false; } else { m_StatusText += "Using tissue mask\n"; MITK_INFO << "Using tissue mask"; } m_Parameters.m_ImageRegion = croppedRegion; x=m_Parameters.m_ImageRegion.GetSize(0); y=m_Parameters.m_ImageRegion.GetSize(1); if ( x%2 == 1 ) m_Parameters.m_ImageRegion.SetSize(0, x+1); if ( y%2 == 1 ) m_Parameters.m_ImageRegion.SetSize(1, y+1); // resample fiber bundle for sufficient voxel coverage m_StatusText += "\n"+this->GetTime()+" > Resampling fibers ...\n"; double segmentVolume = 0.0001; float minSpacing = 1; if(m_UpsampledSpacing[0]GetDeepCopy(); double volumeAccuracy = 10; fiberBundle->ResampleFibers(minSpacing/volumeAccuracy); double mmRadius = m_Parameters.m_AxonRadius/1000; if (mmRadius>0) segmentVolume = M_PI*mmRadius*mmRadius*minSpacing/volumeAccuracy; double maxVolume = 0; double voxelVolume = m_UpsampledSpacing[0]*m_UpsampledSpacing[1]*m_UpsampledSpacing[2]; ofstream logFile; if (m_Parameters.m_DoAddMotion) { std::string fileName = "fiberfox_motion_0.log"; std::string filePath = mitk::IOUtil::GetTempPath(); if (m_Parameters.m_OutputPath.size()>0) filePath = m_Parameters.m_OutputPath; int c = 1; while (itksys::SystemTools::FileExists((filePath+fileName).c_str())) { fileName = "fiberfox_motion_"; fileName += boost::lexical_cast(c); fileName += ".log"; c++; } logFile.open((filePath+fileName).c_str()); logFile << "0 rotation: 0,0,0; translation: 0,0,0\n"; if (m_Parameters.m_DoRandomizeMotion) { m_StatusText += "Adding random motion artifacts:\n"; m_StatusText += "Maximum rotation: +/-" + boost::lexical_cast(m_Parameters.m_Rotation) + "°\n"; m_StatusText += "Maximum translation: +/-" + boost::lexical_cast(m_Parameters.m_Translation) + "mm\n"; } else { m_StatusText += "Adding linear motion artifacts:\n"; m_StatusText += "Maximum rotation: " + boost::lexical_cast(m_Parameters.m_Rotation) + "°\n"; m_StatusText += "Maximum translation: " + boost::lexical_cast(m_Parameters.m_Translation) + "mm\n"; } m_StatusText += "Motion logfile: " + (filePath+fileName) + "\n"; MITK_INFO << "Adding motion artifacts"; MITK_INFO << "Maximum rotation: " << m_Parameters.m_Rotation; MITK_INFO << "Maxmimum translation: " << m_Parameters.m_Translation; } maxVolume = 0; m_StatusText += "\n"+this->GetTime()+" > Generating " + boost::lexical_cast(m_Parameters.m_FiberModelList.size()+m_Parameters.m_NonFiberModelList.size()) + "-compartment diffusion-weighted signal.\n"; int numFibers = m_FiberBundle->GetNumFibers(); boost::progress_display disp(numFibers*m_Parameters.GetNumVolumes()); // get transform for motion artifacts FiberBundleType fiberBundleTransformed = fiberBundle; VectorType rotation = m_Parameters.m_Rotation/m_Parameters.GetNumVolumes(); VectorType translation = m_Parameters.m_Translation/m_Parameters.GetNumVolumes(); // creat image to hold transformed mask (motion artifact) ItkUcharImgType::Pointer tempTissueMask = ItkUcharImgType::New(); itk::ImageDuplicator::Pointer duplicator = itk::ImageDuplicator::New(); duplicator->SetInputImage(m_Parameters.m_MaskImage); duplicator->Update(); tempTissueMask = duplicator->GetOutput(); // second upsampling needed for motion artifacts ImageRegion<3> upsampledImageRegion = m_UpsampledImageRegion; itk::Vector upsampledSpacing = m_UpsampledSpacing; upsampledSpacing[0] /= 4; upsampledSpacing[1] /= 4; upsampledSpacing[2] /= 4; upsampledImageRegion.SetSize(0, m_UpsampledImageRegion.GetSize()[0]*4); upsampledImageRegion.SetSize(1, m_UpsampledImageRegion.GetSize()[1]*4); upsampledImageRegion.SetSize(2, m_UpsampledImageRegion.GetSize()[2]*4); itk::Point upsampledOrigin = m_UpsampledOrigin; upsampledOrigin[0] -= m_UpsampledSpacing[0]/2; upsampledOrigin[0] += upsampledSpacing[0]/2; upsampledOrigin[1] -= m_UpsampledSpacing[1]/2; upsampledOrigin[1] += upsampledSpacing[1]/2; upsampledOrigin[2] -= m_UpsampledSpacing[2]/2; upsampledOrigin[2] += upsampledSpacing[2]/2; ItkUcharImgType::Pointer upsampledTissueMask = ItkUcharImgType::New(); itk::ResampleImageFilter::Pointer upsampler = itk::ResampleImageFilter::New(); upsampler->SetInput(m_Parameters.m_MaskImage); upsampler->SetOutputParametersFromImage(m_Parameters.m_MaskImage); upsampler->SetSize(upsampledImageRegion.GetSize()); upsampler->SetOutputSpacing(upsampledSpacing); upsampler->SetOutputOrigin(upsampledOrigin); itk::NearestNeighborInterpolateImageFunction::Pointer nn_interpolator = itk::NearestNeighborInterpolateImageFunction::New(); upsampler->SetInterpolator(nn_interpolator); upsampler->Update(); upsampledTissueMask = upsampler->GetOutput(); - m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n"; - m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*"; unsigned long lastTick = 0; - - for (unsigned int g=0; gGetFiberPolyData(); - ItkDoubleImgType::Pointer intraAxonalVolumeImage = ItkDoubleImgType::New(); - intraAxonalVolumeImage->SetSpacing( m_UpsampledSpacing ); - intraAxonalVolumeImage->SetOrigin( m_UpsampledOrigin ); - intraAxonalVolumeImage->SetDirection( m_Parameters.m_ImageDirection ); - intraAxonalVolumeImage->SetLargestPossibleRegion( m_UpsampledImageRegion ); - intraAxonalVolumeImage->SetBufferedRegion( m_UpsampledImageRegion ); - intraAxonalVolumeImage->SetRequestedRegion( m_UpsampledImageRegion ); - intraAxonalVolumeImage->Allocate(); - intraAxonalVolumeImage->FillBuffer(0); + m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n"; + m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*"; - // generate fiber signal (if there are any fiber models present) - if (!m_Parameters.m_FiberModelList.empty()) - for( int i=0; iGetCell(i); - int numPoints = cell->GetNumberOfPoints(); - vtkPoints* points = cell->GetPoints(); + for (unsigned int g=0; gSetSpacing( m_UpsampledSpacing ); + intraAxonalVolumeImage->SetOrigin( m_UpsampledOrigin ); + intraAxonalVolumeImage->SetDirection( m_Parameters.m_ImageDirection ); + intraAxonalVolumeImage->SetLargestPossibleRegion( m_UpsampledImageRegion ); + intraAxonalVolumeImage->SetBufferedRegion( m_UpsampledImageRegion ); + intraAxonalVolumeImage->SetRequestedRegion( m_UpsampledImageRegion ); + intraAxonalVolumeImage->Allocate(); + intraAxonalVolumeImage->FillBuffer(0); + + vtkPolyData* fiberPolyData = fiberBundleTransformed->GetFiberPolyData(); + + // generate fiber signal (if there are any fiber models present) + if (!m_Parameters.m_FiberModelList.empty()) + for( int i=0; iGetCell(i); + int numPoints = cell->GetNumberOfPoints(); + vtkPoints* points = cell->GetPoints(); - if (numPoints<2) - continue; + if (numPoints<2) + continue; - for( int j=0; jGetAbortGenerateData()) + for( int j=0; jGetTime()+" > Simulation aborted\n"; - return; - } + if (this->GetAbortGenerateData()) + { + m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n"; + return; + } - double* temp = points->GetPoint(j); - itk::Point vertex = GetItkPoint(temp); - itk::Vector v = GetItkVector(temp); + double* temp = points->GetPoint(j); + itk::Point vertex = GetItkPoint(temp); + itk::Vector v = GetItkVector(temp); - itk::Vector dir(3); - if (jGetPoint(j+1))-v; - else - dir = v-GetItkVector(points->GetPoint(j-1)); + itk::Vector dir(3); + if (jGetPoint(j+1))-v; + else + dir = v-GetItkVector(points->GetPoint(j-1)); - if (dir.GetSquaredNorm()<0.0001 || dir[0]!=dir[0] || dir[1]!=dir[1] || dir[2]!=dir[2]) - continue; + if (dir.GetSquaredNorm()<0.0001 || dir[0]!=dir[0] || dir[1]!=dir[1] || dir[2]!=dir[2]) + continue; - itk::Index<3> idx; - itk::ContinuousIndex contIndex; - tempTissueMask->TransformPhysicalPointToIndex(vertex, idx); - tempTissueMask->TransformPhysicalPointToContinuousIndex(vertex, contIndex); + itk::Index<3> idx; + itk::ContinuousIndex contIndex; + tempTissueMask->TransformPhysicalPointToIndex(vertex, idx); + tempTissueMask->TransformPhysicalPointToContinuousIndex(vertex, contIndex); - if (!tempTissueMask->GetLargestPossibleRegion().IsInside(idx) || tempTissueMask->GetPixel(idx)<=0) - continue; + if (!tempTissueMask->GetLargestPossibleRegion().IsInside(idx) || tempTissueMask->GetPixel(idx)<=0) + continue; - // generate signal for each fiber compartment - for (unsigned int k=0; kSetFiberDirection(dir); - DoubleDwiType::PixelType pix = compartments.at(k)->GetPixel(idx); - pix[g] += segmentVolume*m_Parameters.m_FiberModelList[k]->SimulateMeasurement(g); - compartments.at(k)->SetPixel(idx, pix); + // generate signal for each fiber compartment + for (unsigned int k=0; kSetFiberDirection(dir); + DoubleDwiType::PixelType pix = compartments.at(k)->GetPixel(idx); + pix[g] += segmentVolume*m_Parameters.m_FiberModelList[k]->SimulateMeasurement(g); + compartments.at(k)->SetPixel(idx, pix); + } + + // update fiber volume image + double vol = intraAxonalVolumeImage->GetPixel(idx) + segmentVolume; + intraAxonalVolumeImage->SetPixel(idx, vol); + if (g==0 && vol>maxVolume) + maxVolume = vol; } - // update fiber volume image - double vol = intraAxonalVolumeImage->GetPixel(idx) + segmentVolume; - intraAxonalVolumeImage->SetPixel(idx, vol); - if (g==0 && vol>maxVolume) - maxVolume = vol; + // progress report + ++disp; + unsigned long newTick = 50*disp.count()/disp.expected_count(); + for (unsigned int tick = 0; tick<(newTick-lastTick); tick++) + m_StatusText += "*"; + lastTick = newTick; } - // progress report - ++disp; - unsigned long newTick = 50*disp.count()/disp.expected_count(); - for (unsigned int tick = 0; tick<(newTick-lastTick); tick++) - m_StatusText += "*"; - lastTick = newTick; - } - - // generate non-fiber signal - ImageRegionIterator it3(tempTissueMask, tempTissueMask->GetLargestPossibleRegion()); - double fact = 1; - if (m_Parameters.m_AxonRadius<0.0001 || maxVolume>voxelVolume) - fact = voxelVolume/maxVolume; - while(!it3.IsAtEnd()) - { - if (it3.Get()>0) + // generate non-fiber signal + ImageRegionIterator it3(tempTissueMask, tempTissueMask->GetLargestPossibleRegion()); + double fact = 1; + if (m_Parameters.m_AxonRadius<0.0001 || maxVolume>voxelVolume) + fact = voxelVolume/maxVolume; + while(!it3.IsAtEnd()) { - DoubleDwiType::IndexType index = it3.GetIndex(); - - // get fiber volume fraction - double intraAxonalVolume = intraAxonalVolumeImage->GetPixel(index)*fact; - - for (unsigned int i=0; i0) { - DoubleDwiType::PixelType pix = compartments.at(i)->GetPixel(index); - pix[g] *= fact; - compartments.at(i)->SetPixel(index, pix); - } + DoubleDwiType::IndexType index = it3.GetIndex(); - if (intraAxonalVolume>0.0001 && m_Parameters.m_DoDisablePartialVolume) // only fiber in voxel - { - DoubleDwiType::PixelType pix = compartments.at(0)->GetPixel(index); - pix[g] *= voxelVolume/intraAxonalVolume; - compartments.at(0)->SetPixel(index, pix); - m_VolumeFractions.at(0)->SetPixel(index, 1); - for (unsigned int i=1; iGetPixel(index)*fact; + + for (unsigned int i=0; iGetPixel(index); - pix[g] = 0; + pix[g] *= fact; compartments.at(i)->SetPixel(index, pix); } - } - else - { - m_VolumeFractions.at(0)->SetPixel(index, intraAxonalVolume/voxelVolume); - - double extraAxonalVolume = voxelVolume-intraAxonalVolume; // non-fiber volume - double interAxonalVolume = 0; - if (m_Parameters.m_FiberModelList.size()>1) - interAxonalVolume = extraAxonalVolume * intraAxonalVolume/voxelVolume; // inter-axonal fraction of non fiber compartment scales linearly with f - double other = extraAxonalVolume - interAxonalVolume; // rest of compartment - double singleinter = interAxonalVolume/(m_Parameters.m_FiberModelList.size()-1); - // adjust non-fiber and intra-axonal signal - for (unsigned int i=1; i0.0001 && m_Parameters.m_DoDisablePartialVolume) // only fiber in voxel { - DoubleDwiType::PixelType pix = compartments.at(i)->GetPixel(index); - if (intraAxonalVolume>0) // remove scaling by intra-axonal volume from inter-axonal compartment - pix[g] /= intraAxonalVolume; - pix[g] *= singleinter; - compartments.at(i)->SetPixel(index, pix); - m_VolumeFractions.at(i)->SetPixel(index, singleinter/voxelVolume); + DoubleDwiType::PixelType pix = compartments.at(0)->GetPixel(index); + pix[g] *= voxelVolume/intraAxonalVolume; + compartments.at(0)->SetPixel(index, pix); + m_VolumeFractions.at(0)->SetPixel(index, 1); + for (unsigned int i=1; iGetPixel(index); + pix[g] = 0; + compartments.at(i)->SetPixel(index, pix); + } } - for (unsigned int i=0; i point; - tempTissueMask->TransformIndexToPhysicalPoint(index, point); + m_VolumeFractions.at(0)->SetPixel(index, intraAxonalVolume/voxelVolume); - if (m_Parameters.m_DoAddMotion) + double extraAxonalVolume = voxelVolume-intraAxonalVolume; // non-fiber volume + double interAxonalVolume = 0; + if (m_Parameters.m_FiberModelList.size()>1) + interAxonalVolume = extraAxonalVolume * intraAxonalVolume/voxelVolume; // inter-axonal fraction of non fiber compartment scales linearly with f + double other = extraAxonalVolume - interAxonalVolume; // rest of compartment + double singleinter = interAxonalVolume/(m_Parameters.m_FiberModelList.size()-1); + + // adjust non-fiber and intra-axonal signal + for (unsigned int i=1; i0) - point = fiberBundle->TransformPoint(point.GetVnlVector(), -rotation[0],-rotation[1],-rotation[2],-translation[0],-translation[1],-translation[2]); - else - point = fiberBundle->TransformPoint(point.GetVnlVector(), -rotation[0]*g,-rotation[1]*g,-rotation[2]*g,-translation[0]*g,-translation[1]*g,-translation[2]*g); + DoubleDwiType::PixelType pix = compartments.at(i)->GetPixel(index); + if (intraAxonalVolume>0) // remove scaling by intra-axonal volume from inter-axonal compartment + pix[g] /= intraAxonalVolume; + pix[g] *= singleinter; + compartments.at(i)->SetPixel(index, pix); + m_VolumeFractions.at(i)->SetPixel(index, singleinter/voxelVolume); } - - double weight = 1; - if (m_Parameters.m_NonFiberModelList.size()>1) + for (unsigned int i=0; iGetVolumeFractionImage()->TransformPhysicalPointToIndex(point, newIndex); - if (!m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion().IsInside(newIndex)) + itk::Point point; + tempTissueMask->TransformIndexToPhysicalPoint(index, point); + + if (m_Parameters.m_DoAddMotion) { - MITK_INFO << index; - MITK_INFO << point; - MITK_INFO << newIndex; + if (m_Parameters.m_DoRandomizeMotion && g>0) + point = fiberBundle->TransformPoint(point.GetVnlVector(), -rotation[0],-rotation[1],-rotation[2],-translation[0],-translation[1],-translation[2]); + else + point = fiberBundle->TransformPoint(point.GetVnlVector(), -rotation[0]*g,-rotation[1]*g,-rotation[2]*g,-translation[0]*g,-translation[1]*g,-translation[2]*g); + } - MITK_WARN << "Volume fraction image is too small for the chosen motion artifacts! Due to motion a volume fraction outside of the specified image volume is requested."; - continue; + double weight = 1; + if (m_Parameters.m_NonFiberModelList.size()>1) + { + DoubleDwiType::IndexType newIndex; + m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->TransformPhysicalPointToIndex(point, newIndex); + if (!m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetLargestPossibleRegion().IsInside(newIndex)) + { + MITK_WARN << "Volume fraction image is too small for the chosen motion artifacts! Due to motion a volume fraction outside of the specified image volume is requested."; + continue; + } + weight = m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetPixel(newIndex); } - weight = m_Parameters.m_NonFiberModelList[i]->GetVolumeFractionImage()->GetPixel(newIndex); + + DoubleDwiType::Pointer doubleDwi = compartments.at(i+m_Parameters.m_FiberModelList.size()); + DoubleDwiType::PixelType pix = doubleDwi->GetPixel(index); + + pix[g] += m_Parameters.m_NonFiberModelList[i]->SimulateMeasurement(g)*other*weight; + doubleDwi->SetPixel(index, pix); + m_VolumeFractions.at(i+m_Parameters.m_FiberModelList.size())->SetPixel(index, other/voxelVolume*weight); + } + } + } + ++it3; + } + + // move fibers + if (m_Parameters.m_DoAddMotion && gGetDeepCopy(); + rotation[0] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Rotation[0]*2)-m_Parameters.m_Rotation[0]; + rotation[1] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Rotation[1]*2)-m_Parameters.m_Rotation[1]; + rotation[2] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Rotation[2]*2)-m_Parameters.m_Rotation[2]; + translation[0] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Translation[0]*2)-m_Parameters.m_Translation[0]; + translation[1] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Translation[1]*2)-m_Parameters.m_Translation[1]; + translation[2] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Translation[2]*2)-m_Parameters.m_Translation[2]; + } + + // rotate mask image + if (maskImageSet) + { + ImageRegionIterator maskIt(upsampledTissueMask, upsampledTissueMask->GetLargestPossibleRegion()); + tempTissueMask->FillBuffer(0); + + while(!maskIt.IsAtEnd()) + { + if (maskIt.Get()<=0) + { + ++maskIt; + continue; } - DoubleDwiType::Pointer doubleDwi = compartments.at(i+m_Parameters.m_FiberModelList.size()); - DoubleDwiType::PixelType pix = doubleDwi->GetPixel(index); + DoubleDwiType::IndexType index = maskIt.GetIndex(); + itk::Point point; + upsampledTissueMask->TransformIndexToPhysicalPoint(index, point); + if (m_Parameters.m_DoRandomizeMotion) + point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]); + else + point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0]*(g+1),rotation[1]*(g+1),rotation[2]*(g+1),translation[0]*(g+1),translation[1]*(g+1),translation[2]*(g+1)); + + tempTissueMask->TransformPhysicalPointToIndex(point, index); + if (tempTissueMask->GetLargestPossibleRegion().IsInside(index)) + tempTissueMask->SetPixel(index,100); + ++maskIt; + } + } + + // rotate fibers + if (logFile.is_open()) + { + logFile << g+1 << " rotation: " << rotation[0] << "," << rotation[1] << "," << rotation[2] << ";"; + logFile << " translation: " << translation[0] << "," << translation[1] << "," << translation[2] << "\n"; + } + fiberBundleTransformed->TransformFibers(rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]); + } + } + } + else + { + m_NoAcquisitionSimulation = true; + m_Parameters.m_SignalScale = 1; + std::vector< RawShModel* > wm_models; + std::vector< RawShModel* > gm_models; - pix[g] += m_Parameters.m_NonFiberModelList[i]->SimulateMeasurement(g)*other*weight; - doubleDwi->SetPixel(index, pix); - m_VolumeFractions.at(i+m_Parameters.m_FiberModelList.size())->SetPixel(index, other/voxelVolume*weight); + if (m_InputDwi.IsNotNull()) + { + typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, double > TensorReconstructionImageFilterType; + TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); + filter->SetGradientImage( m_InputDwi->GetDirections(), m_InputDwi->GetVectorImage() ); + filter->SetBValue(m_InputDwi->GetReferenceBValue()); + filter->Update(); + itk::Image< itk::DiffusionTensor3D< double >, 3 >::Pointer tensorImage = filter->GetOutput(); + + const int shOrder = 4; + const int NumCoeffs = (shOrder*shOrder + shOrder + 2)/2 + shOrder; + typedef itk::AnalyticalDiffusionQballReconstructionImageFilter QballFilterType; + typename QballFilterType::Pointer qballfilter = QballFilterType::New(); + qballfilter->SetGradientImage( m_InputDwi->GetDirections(), m_InputDwi->GetVectorImage() ); + qballfilter->SetBValue(m_InputDwi->GetReferenceBValue()); + qballfilter->SetLambda(0.006); + qballfilter->SetNormalizationMethod(QballFilterType::QBAR_RAW_SIGNAL); + qballfilter->Update(); + QballFilterType::CoefficientImageType::Pointer itkFeatureImage = qballfilter->GetCoefficientImage(); + + int b0Index; + for (unsigned int i=0; iGetDirectionsWithoutMeasurementFrame()->Size(); i++) + if ( m_InputDwi->GetDirectionsWithoutMeasurementFrame()->GetElement(i).magnitude()<0.001 ) + { + b0Index = i; + break; + } + + m_StatusText += "Sampling signal kernels.\n"; + ImageRegionIterator< itk::Image< itk::DiffusionTensor3D< double >, 3 > > it(tensorImage, tensorImage->GetLargestPossibleRegion()); + while(!it.IsAtEnd()) + { + bool valid = true; + for (int i=0; iGetNumberOfChannels(); i++) + { + if (m_InputDwi->GetVectorImage()->GetPixel(it.GetIndex())[i]<=0 || m_InputDwi->GetVectorImage()->GetPixel(it.GetIndex())[i]>m_InputDwi->GetVectorImage()->GetPixel(it.GetIndex())[b0Index]) + valid = false; + } + if (valid && tempTissueMask->GetPixel(it.GetIndex())>0) + { + itk::DiffusionTensor3D< double > tensor = it.Get(); + double FA = tensor.GetFractionalAnisotropy(); + if (FA>0.7 && FA<0.9) + { + RawShModel* model = new RawShModel(); + model->SetGradientList( m_Parameters.GetGradientDirections() ); + itk::Vector< float, NumCoeffs > itkv = itkFeatureImage->GetPixel(it.GetIndex()); + vnl_vector_fixed< double, NumCoeffs > coeffs; + for (unsigned int c=0; cSetB0Signal( m_InputDwi->GetVectorImage()->GetPixel(it.GetIndex())[b0Index] ); + if (!model->SetShCoefficients( coeffs )) + { + ++it; + continue; + } + wm_models.push_back(model); + MITK_INFO << "WM KERNEL: " << it.GetIndex(); + } + else if (FA>0.0 && FA<0.15) + { + RawShModel* model = new RawShModel(); + model->SetGradientList( m_Parameters.GetGradientDirections() ); + itk::Vector< float, NumCoeffs > itkv = itkFeatureImage->GetPixel(it.GetIndex()); + vnl_vector_fixed< double, NumCoeffs > coeffs; + for (unsigned int c=0; cSetB0Signal( m_InputDwi->GetVectorImage()->GetPixel(it.GetIndex())[b0Index] ); + if (!model->SetShCoefficients( coeffs )) + { + ++it; + continue; + } + gm_models.push_back(model); + MITK_INFO << "GM/CSF KERNEL: " << it.GetIndex(); } + + if (wm_models.size()>=100 && gm_models.size()>=100) + break; } + ++it; } - ++it3; + MITK_INFO << "Using pool of " << wm_models.size() << " WM and " << gm_models.size() << " GM/CSF kernels"; } - // move fibers - if (m_Parameters.m_DoAddMotion && gSetSpacing( m_UpsampledSpacing ); + numDirectionsImage->SetOrigin( m_UpsampledOrigin ); + numDirectionsImage->SetDirection( m_Parameters.m_ImageDirection ); + numDirectionsImage->SetLargestPossibleRegion( m_UpsampledImageRegion ); + numDirectionsImage->SetBufferedRegion( m_UpsampledImageRegion ); + numDirectionsImage->SetRequestedRegion( m_UpsampledImageRegion ); + numDirectionsImage->Allocate(); + numDirectionsImage->FillBuffer(0); + + ItkDoubleImgType::Pointer intraAxonalVolumeImage = ItkDoubleImgType::New(); + intraAxonalVolumeImage->SetSpacing( m_UpsampledSpacing ); + intraAxonalVolumeImage->SetOrigin( m_UpsampledOrigin ); + intraAxonalVolumeImage->SetDirection( m_Parameters.m_ImageDirection ); + intraAxonalVolumeImage->SetLargestPossibleRegion( m_UpsampledImageRegion ); + intraAxonalVolumeImage->SetBufferedRegion( m_UpsampledImageRegion ); + intraAxonalVolumeImage->SetRequestedRegion( m_UpsampledImageRegion ); + intraAxonalVolumeImage->Allocate(); + intraAxonalVolumeImage->FillBuffer(0); + + m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n"; + m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*"; + boost::progress_display disp(tempTissueMask->GetLargestPossibleRegion().GetNumberOfPixels()); + ImageRegionIterator it(tempTissueMask, tempTissueMask->GetLargestPossibleRegion()); + while(!it.IsAtEnd()) { - if (m_Parameters.m_DoRandomizeMotion) + ++disp; + + unsigned long newTick = 50*disp.count()/disp.expected_count(); + for (unsigned int tick = 0; tick<(newTick-lastTick); tick++) + m_StatusText += "*"; + lastTick = newTick; + + if (this->GetAbortGenerateData()) { - fiberBundleTransformed = fiberBundle->GetDeepCopy(); - rotation[0] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Rotation[0]*2)-m_Parameters.m_Rotation[0]; - rotation[1] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Rotation[1]*2)-m_Parameters.m_Rotation[1]; - rotation[2] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Rotation[2]*2)-m_Parameters.m_Rotation[2]; - translation[0] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Translation[0]*2)-m_Parameters.m_Translation[0]; - translation[1] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Translation[1]*2)-m_Parameters.m_Translation[1]; - translation[2] = m_RandGen->GetVariateWithClosedRange(m_Parameters.m_Translation[2]*2)-m_Parameters.m_Translation[2]; + m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n"; + return; } - // rotate mask image - if (maskImageSet) + if (it.Get()>0) { - ImageRegionIterator maskIt(upsampledTissueMask, upsampledTissueMask->GetLargestPossibleRegion()); - tempTissueMask->FillBuffer(0); + int numFibs = m_RandGen->GetIntegerVariate(2)+1; + DoubleDwiType::PixelType pix = compartments.at(0)->GetPixel(it.GetIndex()); - while(!maskIt.IsAtEnd()) + std::vector< itk::Vector > directions; + for (int i=0; iGetIntegerVariate(wm_models.size()-1); + itk::Vector fib; + fib[0] = m_RandGen->GetVariateWithClosedRange(2)-1.0; + fib[1] = m_RandGen->GetVariateWithClosedRange(2)-1.0; + fib[2] = m_RandGen->GetVariateWithClosedRange(2)-1.0; + fib.Normalize(); + + double min = 0; + for (unsigned int d=0; dmin) + min = angle; + } + if (min<0.7) + { + wm_models.at(modelIndex)->SetFiberDirection(fib); + pix += wm_models.at(modelIndex)->SimulateMeasurement()/numFibs; + directions.push_back(fib); } - - DoubleDwiType::IndexType index = maskIt.GetIndex(); - itk::Point point; - upsampledTissueMask->TransformIndexToPhysicalPoint(index, point); - if (m_Parameters.m_DoRandomizeMotion) - point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]); else - point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0]*(g+1),rotation[1]*(g+1),rotation[2]*(g+1),translation[0]*(g+1),translation[1]*(g+1),translation[2]*(g+1)); - - tempTissueMask->TransformPhysicalPointToIndex(point, index); - if (tempTissueMask->GetLargestPossibleRegion().IsInside(index)) - tempTissueMask->SetPixel(index,100); - ++maskIt; + i--; } + compartments.at(0)->SetPixel(it.GetIndex(), pix); + numDirectionsImage->SetPixel(it.GetIndex(), numFibs); + // int numDirs = 0; + // double volume = m_RandGen->GetVariateWithClosedRange(voxelVolume); + // int numFibs = m_RandGen->GetIntegerVariate(2)+1; + // std::vector< double > fractions; + // double sum = 0; + // for (int i=0; iGetVariateWithClosedRange(1)); + // sum += fractions.at(i); + // } + + // std::vector< itk::Vector > directions; + // for (int i=0; i0) + // fractions[i] /= sum; + + // itk::Vector dir; + // dir[0] = m_RandGen->GetVariateWithClosedRange(2)-1.0; + // dir[1] = m_RandGen->GetVariateWithClosedRange(2)-1.0; + // dir[2] = m_RandGen->GetVariateWithClosedRange(2)-1.0; + // dir.Normalize(); + + // if (fractions.at(i)*numFibs > 0.3 && volume/voxelVolume>0.01) + // { + // numDirs += 1; + // for (unsigned int d=0; dSetFiberDirection(dir); + // DoubleDwiType::PixelType pix = compartments.at(k)->GetPixel(it2.GetIndex()); + // pix += volume*fractions.at(i)*m_Parameters.m_FiberModelList[k]->SimulateMeasurement(); + // compartments.at(k)->SetPixel(it2.GetIndex(), pix); + // } + // } + + // intraAxonalVolumeImage->SetPixel(it2.GetIndex(), volume); + // if (volume>maxVolume) + // maxVolume = volume; + + // // for (unsigned int i=0; iTransformFibers(rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]); + ++it; + itk::ImageFileWriter< ItkUcharImgType >::Pointer wr = itk::ImageFileWriter< ItkUcharImgType >::New(); + wr->SetInput(numDirectionsImage); + wr->SetFileName(mitk::IOUtil::GetTempPath()+"/NumDirections.nrrd"); + wr->Update(); } } + if (logFile.is_open()) { logFile << "DONE"; logFile.close(); } m_StatusText += "\n\n"; if (this->GetAbortGenerateData()) { m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n"; return; } // do k-space stuff DoubleDwiType::Pointer doubleOutImage; - if (m_Parameters.m_Spikes>0 || m_Parameters.m_FrequencyMap.IsNotNull() || m_Parameters.m_KspaceLineOffset>0 || m_Parameters.m_DoSimulateRelaxation || m_Parameters.m_EddyStrength>0 || m_Parameters.m_DoAddGibbsRinging || m_Parameters.m_CroppingFactor<1.0) + if ( !m_NoAcquisitionSimulation && (m_Parameters.m_Spikes>0 || m_Parameters.m_FrequencyMap.IsNotNull() || m_Parameters.m_KspaceLineOffset>0 || m_Parameters.m_DoSimulateRelaxation || m_Parameters.m_EddyStrength>0 || m_Parameters.m_DoAddGibbsRinging || m_Parameters.m_CroppingFactor<1.0) ) { m_StatusText += this->GetTime()+" > Adjusting complex signal\n"; MITK_INFO << "Adjusting complex signal:"; if (m_Parameters.m_DoSimulateRelaxation) m_StatusText += "Simulating signal relaxation\n"; if (m_Parameters.m_FrequencyMap.IsNotNull()) m_StatusText += "Simulating distortions\n"; if (m_Parameters.m_DoAddGibbsRinging) m_StatusText += "Simulating ringing artifacts\n"; if (m_Parameters.m_EddyStrength>0) m_StatusText += "Simulating eddy currents\n"; if (m_Parameters.m_Spikes>0) m_StatusText += "Simulating spikes\n"; if (m_Parameters.m_CroppingFactor<1.0) m_StatusText += "Simulating aliasing artifacts\n"; if (m_Parameters.m_KspaceLineOffset>0) m_StatusText += "Simulating ghosts\n"; doubleOutImage = DoKspaceStuff(compartments); m_Parameters.m_SignalScale = 1; } else { m_StatusText += this->GetTime()+" > Summing compartments\n"; MITK_INFO << "Summing compartments"; doubleOutImage = compartments.at(0); for (unsigned int i=1; i::Pointer adder = itk::AddImageFilter< DoubleDwiType, DoubleDwiType, DoubleDwiType>::New(); adder->SetInput1(doubleOutImage); adder->SetInput2(compartments.at(i)); adder->Update(); doubleOutImage = adder->GetOutput(); } } if (this->GetAbortGenerateData()) { m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n"; return; } m_StatusText += this->GetTime()+" > Finalizing image\n"; MITK_INFO << "Finalizing image"; if (m_Parameters.m_SignalScale>1) m_StatusText += " Scaling signal\n"; if (m_Parameters.m_NoiseModel!=NULL) m_StatusText += " Adding noise\n"; unsigned int window = 0; unsigned int min = itk::NumericTraits::max(); ImageRegionIterator it4 (outImage, outImage->GetLargestPossibleRegion()); DoubleDwiType::PixelType signal; signal.SetSize(m_Parameters.GetNumVolumes()); boost::progress_display disp2(outImage->GetLargestPossibleRegion().GetNumberOfPixels()); m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n"; m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*"; lastTick = 0; while(!it4.IsAtEnd()) { if (this->GetAbortGenerateData()) { m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n"; return; } ++disp2; unsigned long newTick = 50*disp2.count()/disp2.expected_count(); for (unsigned long tick = 0; tick<(newTick-lastTick); tick++) m_StatusText += "*"; lastTick = newTick; typename OutputImageType::IndexType index = it4.GetIndex(); signal = doubleOutImage->GetPixel(index)*m_Parameters.m_SignalScale; if (m_Parameters.m_NoiseModel!=NULL) { DoubleDwiType::PixelType accu = signal; accu.Fill(0.0); for (unsigned int i=0; iAddNoise(temp); accu += temp; } signal = accu/m_Parameters.m_Repetitions; } for (unsigned int i=0; i0) signal[i] = floor(signal[i]+0.5); else signal[i] = ceil(signal[i]-0.5); if (!m_Parameters.IsBaselineIndex(i) && signal[i]>window) window = signal[i]; if (!m_Parameters.IsBaselineIndex(i) && signal[i]SetNthOutput(0, outImage); m_StatusText += "\n\n"; m_StatusText += "Finished simulation\n"; m_StatusText += "Simulation time: "+GetTime(); m_TimeProbe.Stop(); } template< class PixelType > itk::Point TractsToDWIImageFilter< PixelType >::GetItkPoint(double point[3]) { itk::Point itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; return itkPoint; } template< class PixelType > itk::Vector TractsToDWIImageFilter< PixelType >::GetItkVector(double point[3]) { itk::Vector itkVector; itkVector[0] = point[0]; itkVector[1] = point[1]; itkVector[2] = point[2]; return itkVector; } template< class PixelType > vnl_vector_fixed TractsToDWIImageFilter< PixelType >::GetVnlVector(double point[3]) { vnl_vector_fixed vnlVector; vnlVector[0] = point[0]; vnlVector[1] = point[1]; vnlVector[2] = point[2]; return vnlVector; } template< class PixelType > vnl_vector_fixed TractsToDWIImageFilter< PixelType >::GetVnlVector(Vector& vector) { vnl_vector_fixed vnlVector; vnlVector[0] = vector[0]; vnlVector[1] = vector[1]; vnlVector[2] = vector[2]; return vnlVector; } template< class PixelType > double TractsToDWIImageFilter< PixelType >::RoundToNearest(double num) { return (num > 0.0) ? floor(num + 0.5) : ceil(num - 0.5); } template< class PixelType > std::string TractsToDWIImageFilter< PixelType >::GetTime() { m_TimeProbe.Stop(); unsigned long total = RoundToNearest(m_TimeProbe.GetTotal()); unsigned long hours = total/3600; unsigned long minutes = (total%3600)/60; unsigned long seconds = total%60; std::string out = ""; out.append(boost::lexical_cast(hours)); out.append(":"); out.append(boost::lexical_cast(minutes)); out.append(":"); out.append(boost::lexical_cast(seconds)); m_TimeProbe.Start(); return out; } } diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.h b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.h index 6e28e8d25d..cf7303c01c 100755 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.h +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.h @@ -1,106 +1,112 @@ /*=================================================================== 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 __itkTractsToDWIImageFilter_h__ #define __itkTractsToDWIImageFilter_h__ #include #include #include #include #include #include +#include +#include +#include namespace itk { /** * \brief Generates artificial diffusion weighted image volume from the input fiberbundle using a generic multicompartment model. * See "Fiberfox: Facilitating the creation of realistic white matter software phantoms" (DOI: 10.1002/mrm.25045) for details. */ template< class PixelType > class TractsToDWIImageFilter : public ImageSource< itk::VectorImage< PixelType, 3 > > { public: typedef TractsToDWIImageFilter Self; typedef ImageSource< itk::VectorImage< PixelType, 3 > > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef typename Superclass::OutputImageType OutputImageType; typedef itk::Image ItkDoubleImgType; typedef itk::Image ItkUcharImgType; typedef mitk::FiberBundleX::Pointer FiberBundleType; typedef itk::VectorImage< double, 3 > DoubleDwiType; typedef itk::Matrix MatrixType; typedef itk::Image< double, 2 > SliceType; typedef itk::VnlForwardFFTImageFilter::OutputImageType ComplexSliceType; typedef itk::Vector< double,3> VectorType; itkFactorylessNewMacro(Self) itkCloneMacro(Self) itkTypeMacro( TractsToDWIImageFilter, ImageSource ) /** Input */ itkSetMacro( FiberBundle, FiberBundleType ) ///< Input fiber bundle itkSetMacro( UseConstantRandSeed, bool ) ///< Seed for random generator. + itkSetMacro( InputDwi, mitk::DiffusionImage::Pointer ) void SetParameters( FiberfoxParameters param ) ///< Simulation parameters. { m_Parameters = param; } /** Output */ FiberfoxParameters GetParameters(){ return m_Parameters; } std::vector< ItkDoubleImgType::Pointer > GetVolumeFractions() ///< one double image for each compartment containing the corresponding volume fraction per voxel { return m_VolumeFractions; } mitk::LevelWindow GetLevelWindow(){ return m_LevelWindow; } itkGetMacro( StatusText, std::string ) void GenerateData(); protected: TractsToDWIImageFilter(); virtual ~TractsToDWIImageFilter(); itk::Point GetItkPoint(double point[3]); itk::Vector GetItkVector(double point[3]); vnl_vector_fixed GetVnlVector(double point[3]); vnl_vector_fixed GetVnlVector(Vector< float, 3 >& vector); double RoundToNearest(double num); std::string GetTime(); /** Transform generated image compartment by compartment, channel by channel and slice by slice using DFT and add k-space artifacts. */ DoubleDwiType::Pointer DoKspaceStuff(std::vector< DoubleDwiType::Pointer >& images); mitk::FiberfoxParameters m_Parameters; itk::Vector m_UpsampledSpacing; itk::Point m_UpsampledOrigin; ImageRegion<3> m_UpsampledImageRegion; FiberBundleType m_FiberBundle; mitk::LevelWindow m_LevelWindow; std::vector< ItkDoubleImgType::Pointer > m_VolumeFractions; std::string m_StatusText; itk::TimeProbe m_TimeProbe; bool m_UseConstantRandSeed; + mitk::DiffusionImage::Pointer m_InputDwi; + bool m_NoAcquisitionSimulation; itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer m_RandGen; }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkTractsToDWIImageFilter.cpp" #endif #endif diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp index b431eff166..ef8b897311 100644 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp @@ -1,832 +1,835 @@ #include "itkTractsToVectorImageFilter.h" // VTK #include #include #include // ITK #include #include // misc #define _USE_MATH_DEFINES #include #include namespace itk{ static bool CompareVectorLengths(const vnl_vector_fixed< double, 3 >& v1, const vnl_vector_fixed< double, 3 >& v2) { return (v1.magnitude()>v2.magnitude()); } template< class PixelType > TractsToVectorImageFilter< PixelType >::TractsToVectorImageFilter(): m_AngularThreshold(0.7), m_Epsilon(0.999), m_MaskImage(NULL), m_NormalizeVectors(false), m_UseWorkingCopy(true), m_UseTrilinearInterpolation(false), m_MaxNumDirections(3), m_Thres(0.5), m_NumDirectionsImage(NULL) { this->SetNumberOfRequiredOutputs(1); } template< class PixelType > TractsToVectorImageFilter< PixelType >::~TractsToVectorImageFilter() { } template< class PixelType > vnl_vector_fixed TractsToVectorImageFilter< PixelType >::GetVnlVector(double point[]) { vnl_vector_fixed vnlVector; vnlVector[0] = point[0]; vnlVector[1] = point[1]; vnlVector[2] = point[2]; return vnlVector; } template< class PixelType > itk::Point TractsToVectorImageFilter< PixelType >::GetItkPoint(double point[]) { itk::Point itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; return itkPoint; } template< class PixelType > void TractsToVectorImageFilter< PixelType >::GenerateData() { mitk::BaseGeometry::Pointer geometry = m_FiberBundle->GetGeometry(); // calculate new image parameters itk::Vector spacing; itk::Point origin; itk::Matrix direction; ImageRegion<3> imageRegion; if (!m_MaskImage.IsNull()) { spacing = m_MaskImage->GetSpacing(); imageRegion = m_MaskImage->GetLargestPossibleRegion(); origin = m_MaskImage->GetOrigin(); direction = m_MaskImage->GetDirection(); } else { spacing = geometry->GetSpacing(); origin = geometry->GetOrigin(); mitk::BaseGeometry::BoundsArrayType bounds = geometry->GetBounds(); origin[0] += bounds.GetElement(0); origin[1] += bounds.GetElement(2); origin[2] += bounds.GetElement(4); for (int i=0; i<3; i++) for (int j=0; j<3; j++) direction[j][i] = geometry->GetMatrixColumn(i)[j]; imageRegion.SetSize(0, geometry->GetExtent(0)); imageRegion.SetSize(1, geometry->GetExtent(1)); imageRegion.SetSize(2, geometry->GetExtent(2)); m_MaskImage = ItkUcharImgType::New(); m_MaskImage->SetSpacing( spacing ); m_MaskImage->SetOrigin( origin ); m_MaskImage->SetDirection( direction ); m_MaskImage->SetRegions( imageRegion ); m_MaskImage->Allocate(); m_MaskImage->FillBuffer(1); } OutputImageType::RegionType::SizeType outImageSize = imageRegion.GetSize(); m_OutImageSpacing = m_MaskImage->GetSpacing(); m_ClusteredDirectionsContainer = ContainerType::New(); // initialize crossings image m_CrossingsImage = ItkUcharImgType::New(); m_CrossingsImage->SetSpacing( spacing ); m_CrossingsImage->SetOrigin( origin ); m_CrossingsImage->SetDirection( direction ); m_CrossingsImage->SetRegions( imageRegion ); m_CrossingsImage->Allocate(); m_CrossingsImage->FillBuffer(0); // initialize num directions image m_NumDirectionsImage = ItkUcharImgType::New(); m_NumDirectionsImage->SetSpacing( spacing ); m_NumDirectionsImage->SetOrigin( origin ); m_NumDirectionsImage->SetDirection( direction ); m_NumDirectionsImage->SetRegions( imageRegion ); m_NumDirectionsImage->Allocate(); m_NumDirectionsImage->FillBuffer(0); // resample fiber bundle double minSpacing = 1; if(m_OutImageSpacing[0]GetDeepCopy(); // resample fiber bundle for sufficient voxel coverage m_FiberBundle->ResampleFibers(minSpacing/3); // iterate over all fibers vtkSmartPointer fiberPolyData = m_FiberBundle->GetFiberPolyData(); vtkSmartPointer vLines = fiberPolyData->GetLines(); vLines->InitTraversal(); int numFibers = m_FiberBundle->GetNumFibers(); itk::TimeProbe clock; m_DirectionsContainer = ContainerType::New(); if (m_UseTrilinearInterpolation) MITK_INFO << "Generating directions from tractogram (trilinear interpolation)"; else MITK_INFO << "Generating directions from tractogram"; boost::progress_display disp(numFibers); for( int i=0; iGetNextCell ( numPoints, points ); if (numPoints<2) continue; itk::Index<3> index; index.Fill(0); itk::ContinuousIndex contIndex; vnl_vector_fixed dir, wDir; itk::Point worldPos; vnl_vector v; for( int j=0; jGetPoint(points[j]); worldPos = GetItkPoint(temp); v = GetVnlVector(temp); dir = GetVnlVector(fiberPolyData->GetPoint(points[j+1]))-v; dir.normalize(); m_MaskImage->TransformPhysicalPointToIndex(worldPos, index); m_MaskImage->TransformPhysicalPointToContinuousIndex(worldPos, contIndex); if (m_MaskImage->GetPixel(index)==0) continue; if (!m_UseTrilinearInterpolation) { if (index[0] < 0 || (unsigned long)index[0] >= outImageSize[0]) continue; if (index[1] < 0 || (unsigned long)index[1] >= outImageSize[1]) continue; if (index[2] < 0 || (unsigned long)index[2] >= outImageSize[2]) continue; unsigned int idx = index[0] + outImageSize[0]*(index[1] + outImageSize[1]*index[2]); DirectionContainerType::Pointer dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, dir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), dir); } else { dirCont->InsertElement(0, dir); m_DirectionsContainer->InsertElement(idx, dirCont); } continue; } double frac_x = contIndex[0] - index[0]; double frac_y = contIndex[1] - index[1]; double frac_z = contIndex[2] - index[2]; if (frac_x<0) { index[0] -= 1; frac_x += 1; } if (frac_y<0) { index[1] -= 1; frac_y += 1; } if (frac_z<0) { index[2] -= 1; frac_z += 1; } frac_x = 1-frac_x; frac_y = 1-frac_y; frac_z = 1-frac_z; // int coordinates inside image? if (index[0] < 0 || (unsigned long)index[0] >= outImageSize[0]-1) continue; if (index[1] < 0 || (unsigned long)index[1] >= outImageSize[1]-1) continue; if (index[2] < 0 || (unsigned long)index[2] >= outImageSize[2]-1) continue; DirectionContainerType::Pointer dirCont; int idx; wDir = dir; double weight = ( frac_x)*( frac_y)*( frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0] + outImageSize[0]*(index[1] + outImageSize[1]*index[2] ); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = ( frac_x)*(1-frac_y)*( frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0] + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2] ); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = ( frac_x)*( frac_y)*(1-frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0] + outImageSize[0]*(index[1] + outImageSize[1]*index[2]+outImageSize[1]); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = ( frac_x)*(1-frac_y)*(1-frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0] + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2]+outImageSize[1]); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = (1-frac_x)*( frac_y)*( frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0]+1 + outImageSize[0]*(index[1] + outImageSize[1]*index[2] ); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = (1-frac_x)*( frac_y)*(1-frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0]+1 + outImageSize[0]*(index[1] + outImageSize[1]*index[2]+outImageSize[1]); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = (1-frac_x)*(1-frac_y)*( frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0]+1 + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2] ); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } wDir = dir; weight = (1-frac_x)*(1-frac_y)*(1-frac_z); if (weight>m_Thres) { wDir *= weight; idx = index[0]+1 + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2]+outImageSize[1]); dirCont = DirectionContainerType::New(); if (m_DirectionsContainer->IndexExists(idx)) { dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull()) { dirCont = DirectionContainerType::New(); dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } else dirCont->InsertElement(dirCont->Size(), wDir); } else { dirCont->InsertElement(0, wDir); m_DirectionsContainer->InsertElement(idx, dirCont); } } } clock.Stop(); } vtkSmartPointer m_VtkCellArray = vtkSmartPointer::New(); vtkSmartPointer m_VtkPoints = vtkSmartPointer::New(); itk::ImageRegionIterator dirIt(m_NumDirectionsImage, m_NumDirectionsImage->GetLargestPossibleRegion()); itk::ImageRegionIterator crossIt(m_CrossingsImage, m_CrossingsImage->GetLargestPossibleRegion()); m_DirectionImageContainer = DirectionImageContainerType::New(); unsigned int maxNumDirections = 0; MITK_INFO << "Clustering directions"; boost::progress_display disp2(outImageSize[0]*outImageSize[1]*outImageSize[2]); for(crossIt.GoToBegin(); !crossIt.IsAtEnd(); ++crossIt) { ++disp2; OutputImageType::IndexType index = crossIt.GetIndex(); int idx = index[0]+(index[1]+index[2]*outImageSize[1])*outImageSize[0]; if (!m_DirectionsContainer->IndexExists(idx)) { ++dirIt; continue; } DirectionContainerType::Pointer dirCont = m_DirectionsContainer->GetElement(idx); if (dirCont.IsNull() || index[0] < 0 || (unsigned long)index[0] >= outImageSize[0] || index[1] < 0 || (unsigned long)index[1] >= outImageSize[1] || index[2] < 0 || (unsigned long)index[2] >= outImageSize[2]) { ++dirIt; continue; } std::vector< DirectionType > directions; for (unsigned int i=0; iSize(); i++) if (dirCont->ElementAt(i).magnitude()>0.0001) directions.push_back(dirCont->ElementAt(i)); if (!directions.empty()) directions = FastClustering(directions); std::sort( directions.begin(), directions.end(), CompareVectorLengths ); if ( directions.size() > maxNumDirections ) { for (unsigned int i=maxNumDirections; i(directions.size(), m_MaxNumDirections); i++) { ItkDirectionImageType::Pointer directionImage = ItkDirectionImageType::New(); directionImage->SetSpacing( spacing ); directionImage->SetOrigin( origin ); directionImage->SetDirection( direction ); directionImage->SetRegions( imageRegion ); directionImage->Allocate(); Vector< float, 3 > nullVec; nullVec.Fill(0.0); directionImage->FillBuffer(nullVec); m_DirectionImageContainer->InsertElement(i, directionImage); } maxNumDirections = std::min(directions.size(), m_MaxNumDirections); } unsigned int numDir = directions.size(); if (numDir>m_MaxNumDirections) numDir = m_MaxNumDirections; for (unsigned int i=0; i container = vtkSmartPointer::New(); itk::ContinuousIndex center; center[0] = index[0]; center[1] = index[1]; center[2] = index[2]; itk::Point worldCenter; m_MaskImage->TransformContinuousIndexToPhysicalPoint( center, worldCenter ); DirectionType dir = directions.at(i); + if (dir.magnitude()<0.4) + continue; + // set direction image pixel ItkDirectionImageType::Pointer directionImage = m_DirectionImageContainer->GetElement(i); Vector< float, 3 > pixel; pixel.SetElement(0, dir[0]); pixel.SetElement(1, dir[1]); pixel.SetElement(2, dir[2]); directionImage->SetPixel(index, pixel); // add direction to vector field (with spacing compensation) itk::Point worldStart; worldStart[0] = worldCenter[0]-dir[0]/2*minSpacing; worldStart[1] = worldCenter[1]-dir[1]/2*minSpacing; worldStart[2] = worldCenter[2]-dir[2]/2*minSpacing; vtkIdType id = m_VtkPoints->InsertNextPoint(worldStart.GetDataPointer()); container->GetPointIds()->InsertNextId(id); itk::Point worldEnd; worldEnd[0] = worldCenter[0]+dir[0]/2*minSpacing; worldEnd[1] = worldCenter[1]+dir[1]/2*minSpacing; worldEnd[2] = worldCenter[2]+dir[2]/2*minSpacing; id = m_VtkPoints->InsertNextPoint(worldEnd.GetDataPointer()); container->GetPointIds()->InsertNextId(id); m_VtkCellArray->InsertNextCell(container); } dirIt.Set(numDir); ++dirIt; } vtkSmartPointer directionsPolyData = vtkSmartPointer::New(); directionsPolyData->SetPoints(m_VtkPoints); directionsPolyData->SetLines(m_VtkCellArray); m_OutputFiberBundle = mitk::FiberBundleX::New(directionsPolyData); } template< class PixelType > std::vector< vnl_vector_fixed< double, 3 > > TractsToVectorImageFilter< PixelType >::FastClustering(std::vector< vnl_vector_fixed< double, 3 > >& inDirs) { std::vector< vnl_vector_fixed< double, 3 > > outDirs; if (inDirs.empty()) return outDirs; vnl_vector_fixed< double, 3 > oldMean, currentMean, workingMean; std::vector< vnl_vector_fixed< double, 3 > > normalizedDirs; std::vector< int > touched; for (unsigned int i=0; i0.0001) { counter = 0; oldMean = currentMean; workingMean = oldMean; workingMean.normalize(); currentMean.fill(0.0); for (unsigned int i=0; i=m_AngularThreshold) { currentMean += inDirs[i]; touched[i] = 1; counter++; } else if (-angle>=m_AngularThreshold) { currentMean -= inDirs[i]; touched[i] = 1; counter++; } } } // found stable mean if (counter>0) { currentMean /= counter; double mag = currentMean.magnitude(); if (mag>0) { if (mag>max) max = mag; outDirs.push_back(currentMean); } } // find next unused seed free = false; for (unsigned int i=0; i0) for (unsigned int i=0; i std::vector< vnl_vector_fixed< double, 3 > > TractsToVectorImageFilter< PixelType >::Clustering(std::vector< vnl_vector_fixed< double, 3 > >& inDirs) { std::vector< vnl_vector_fixed< double, 3 > > outDirs; if (inDirs.empty()) return outDirs; vnl_vector_fixed< double, 3 > oldMean, currentMean, workingMean; std::vector< vnl_vector_fixed< double, 3 > > normalizedDirs; std::vector< int > touched; for (std::size_t i=0; i0.0001) { counter = 0; oldMean = currentMean; workingMean = oldMean; workingMean.normalize(); currentMean.fill(0.0); for (std::size_t i=0; i=m_AngularThreshold) { currentMean += inDirs[i]; counter++; } else if (-angle>=m_AngularThreshold) { currentMean -= inDirs[i]; counter++; } } } // found stable mean if (counter>0) { bool add = true; vnl_vector_fixed< double, 3 > normMean = currentMean; normMean.normalize(); for (std::size_t i=0; i dir = outDirs[i]; dir.normalize(); if ((normMean-dir).magnitude()<=0.0001) { add = false; break; } } currentMean /= counter; if (add) { double mag = currentMean.magnitude(); if (mag>0) { if (mag>max) max = mag; outDirs.push_back(currentMean); } } } } if (m_NormalizeVectors) for (std::size_t i=0; i0) for (std::size_t i=0; i TractsToVectorImageFilter< PixelType >::DirectionContainerType::Pointer TractsToVectorImageFilter< PixelType >::MeanShiftClustering(DirectionContainerType::Pointer dirCont) { DirectionContainerType::Pointer container = DirectionContainerType::New(); double max = 0; for (DirectionContainerType::ConstIterator it = dirCont->Begin(); it!=dirCont->End(); ++it) { vnl_vector_fixed mean = ClusterStep(dirCont, it.Value()); if (mean.is_zero()) continue; bool addMean = true; for (DirectionContainerType::ConstIterator it2 = container->Begin(); it2!=container->End(); ++it2) { vnl_vector_fixed dir = it2.Value(); double angle = fabs(dot_product(mean, dir)/(mean.magnitude()*dir.magnitude())); if (angle>=m_Epsilon) { addMean = false; break; } } if (addMean) { if (m_NormalizeVectors) mean.normalize(); else if (mean.magnitude()>max) max = mean.magnitude(); container->InsertElement(container->Size(), mean); } } // max normalize voxel directions if (max>0 && !m_NormalizeVectors) for (std::size_t i=0; iSize(); i++) container->ElementAt(i) /= max; if (container->Size()Size()) return MeanShiftClustering(container); else return container; } template< class PixelType > vnl_vector_fixed TractsToVectorImageFilter< PixelType >::ClusterStep(DirectionContainerType::Pointer dirCont, vnl_vector_fixed currentMean) { vnl_vector_fixed newMean; newMean.fill(0); for (DirectionContainerType::ConstIterator it = dirCont->Begin(); it!=dirCont->End(); ++it) { vnl_vector_fixed dir = it.Value(); double angle = dot_product(currentMean, dir)/(currentMean.magnitude()*dir.magnitude()); if (angle>=m_AngularThreshold) newMean += dir; else if (-angle>=m_AngularThreshold) newMean -= dir; } if (fabs(dot_product(currentMean, newMean)/(currentMean.magnitude()*newMean.magnitude()))>=m_Epsilon || newMean.is_zero()) return newMean; else return ClusterStep(dirCont, newMean); } } diff --git a/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt b/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt index 726d43d1c4..4176a0c4bc 100644 --- a/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt +++ b/Modules/DiffusionImaging/FiberTracking/CMakeLists.txt @@ -1,54 +1,54 @@ set(_module_deps MitkDiffusionCore MitkGraphAlgorithms) mitk_check_module_dependencies( MODULES ${_module_deps} MISSING_DEPENDENCIES_VAR _missing_deps ) if(NOT _missing_deps) set(lut_url http://mitk.org/download/data/FibertrackingLUT.tar.gz) set(lut_tarball ${CMAKE_CURRENT_BINARY_DIR}/FibertrackingLUT.tar.gz) message("Downloading FiberTracking LUT ${lut_url}...") file(DOWNLOAD ${lut_url} ${lut_tarball} EXPECTED_MD5 38ecb6d4a826c9ebb0f4965eb9aeee44 TIMEOUT 20 STATUS status SHOW_PROGRESS ) list(GET status 0 status_code) list(GET status 1 status_msg) if(NOT status_code EQUAL 0) message(SEND_ERROR "${status_msg} (error code ${status_code})") else() message("done.") endif() file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Resources) message("Unpacking FiberTracking LUT tarball...") execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzf ../FibertrackingLUT.tar.gz WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Resources RESULT_VARIABLE result ERROR_VARIABLE err_msg) if(result) message(SEND_ERROR "Unpacking FibertrackingLUT.tar.gz failed: ${err_msg}") else() message("done.") endif() endif() MITK_CREATE_MODULE( SUBPROJECTS MITK-DTI INCLUDE_DIRS Algorithms Algorithms/GibbsTracking Algorithms/StochasticTracking IODataStructures IODataStructures/FiberBundleX IODataStructures/PlanarFigureComposite Interactions SignalModels Rendering ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${_module_deps} - PACKAGE_DEPENDS ITK|ITKFFT + PACKAGE_DEPENDS ITK|ITKFFT ITK|ITKDiffusionTensorImage #WARNINGS_AS_ERRORS ) if(MODULE_IS_ENABLED) add_subdirectory(Testing) endif() diff --git a/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkRawShModel.cpp b/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkRawShModel.cpp new file mode 100644 index 0000000000..f9ae2e518a --- /dev/null +++ b/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkRawShModel.cpp @@ -0,0 +1,215 @@ +/*=================================================================== + +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 +#include +#include +#include +#include +#include + +using namespace mitk; +using namespace boost::math; + +template< class ScalarType > +RawShModel< ScalarType >::RawShModel() + : m_ShOrder(0) +{ + +} + +template< class ScalarType > +RawShModel< ScalarType >::~RawShModel() +{ + +} + +// convert cartesian to spherical coordinates +template< class ScalarType > +void RawShModel< ScalarType >::Cart2Sph() +{ + GradientListType tempDirs = m_RotatedGradientList; + m_SphCoords.set_size(tempDirs.size(), 2); + m_SphCoords.fill(0.0); + + for (unsigned int i=0; i 0.0001 ) + { + tempDirs[i].Normalize(); + m_SphCoords(i,0) = acos(tempDirs[i][2]); // theta + m_SphCoords(i,1) = atan2(tempDirs[i][1], tempDirs[i][0]); // phi + } + } +} + +template< class ScalarType > +void RawShModel< ScalarType >::SetFiberDirection(GradientType fiberDirection) +{ + this->m_FiberDirection = fiberDirection; + this->m_FiberDirection.Normalize(); + + GradientType unit; unit.Fill(0.0); unit[0] = 1; + GradientType axis = itk::CrossProduct(this->m_FiberDirection, m_PrototypeMaxDirection); + axis.Normalize(); + + vnl_quaternion rotation(axis.GetVnlVector(), acos(dot_product(this->m_FiberDirection.GetVnlVector(), m_PrototypeMaxDirection.GetVnlVector()))); + rotation.normalize(); + + m_RotatedGradientList.clear(); + for (unsigned int i=0; im_GradientList.size(); i++) + { + GradientType dir = this->m_GradientList.at(i); + dir.Normalize(); + vnl_vector_fixed< double, 3 > vnlDir = rotation.rotate(dir.GetVnlVector()); + dir[0] = vnlDir[0]; dir[1] = vnlDir[1]; dir[2] = vnlDir[2]; + dir.Normalize(); + m_RotatedGradientList.push_back(dir); + } + + Cart2Sph(); +} + +template< class ScalarType > +bool RawShModel< ScalarType >::SetShCoefficients(vnl_vector< double > shCoefficients) +{ + m_ShCoefficients = shCoefficients; + m_ShOrder = 2; + while ( (m_ShOrder*m_ShOrder + m_ShOrder + 2)/2 + m_ShOrder <= m_ShCoefficients.size() ) + m_ShOrder += 2; + m_ShOrder -= 2; + + itk::OrientationDistributionFunction odf; + m_RotatedGradientList.clear(); + for (unsigned int i=0; i::max(); + for (unsigned int i=0; im_B0Signal || signal[i]<0) + { + MITK_INFO << "Corrupted signal value detected. Kernel rejected."; + return false; + } + if (signal[i] +ScalarType RawShModel< ScalarType >::SimulateMeasurement(unsigned int dir) +{ + ScalarType signal = 0; + + if (dir>=m_RotatedGradientList.size()) + return signal; + + int j, m; double mag, plm; + vnl_vector< double > shBasis; + shBasis.set_size(m_ShCoefficients.size()); + shBasis.fill(0.0); + + if (m_RotatedGradientList[dir].GetNorm()>0.001) + { + j=0; + for (int l=0; l<=m_ShOrder; l=l+2) + for (m=-l; m<=l; m++) + { + plm = legendre_p(l,abs(m),cos(m_SphCoords(dir,0))); + mag = sqrt((double)(2*l+1)/(4.0*M_PI)*factorial(l-abs(m))/factorial(l+abs(m)))*plm; + + if (m<0) + shBasis[j] = sqrt(2.0)*mag*cos(fabs((double)m)*m_SphCoords(dir,1)); + else if (m==0) + shBasis[j] = mag; + else + shBasis[j] = pow(-1.0, m)*sqrt(2.0)*mag*sin(m*m_SphCoords(dir,1)); + + j++; + } + } + + for (unsigned int i=0; i +typename RawShModel< ScalarType >::PixelType RawShModel< ScalarType >::SimulateMeasurement() +{ + PixelType signal; + signal.SetSize(m_RotatedGradientList.size()); + + int M = m_RotatedGradientList.size(); + int j, m; double mag, plm; + + vnl_matrix< double > shBasis; + shBasis.set_size(M, m_ShCoefficients.size()); + shBasis.fill(0.0); + + for (int p=0; p0.001) + { + j=0; + for (int l=0; l<=m_ShOrder; l=l+2) + for (m=-l; m<=l; m++) + { + plm = legendre_p(l,abs(m),cos(m_SphCoords(p,0))); + mag = sqrt((double)(2*l+1)/(4.0*M_PI)*factorial(l-abs(m))/factorial(l+abs(m)))*plm; + + if (m<0) + shBasis(p,j) = sqrt(2.0)*mag*cos(fabs((double)m)*m_SphCoords(p,1)); + else if (m==0) + shBasis(p,j) = mag; + else + shBasis(p,j) = pow(-1.0, m)*sqrt(2.0)*mag*sin(m*m_SphCoords(p,1)); + + j++; + } + + + double val = 0; + for (unsigned int cidx=0; cidxm_B0Signal || val<0) +// { +// MITK_INFO << "SIGNALGEN ERROR: " << val; +// val = 0; +// } + } + else + signal[p] = m_B0Signal; + } + + return signal; +} diff --git a/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkRawShModel.h b/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkRawShModel.h new file mode 100644 index 0000000000..a1d4e0c202 --- /dev/null +++ b/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkRawShModel.h @@ -0,0 +1,68 @@ +/*=================================================================== + +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 _MITK_RawShModel_H +#define _MITK_RawShModel_H + +#include + +namespace mitk { + +/** + * \brief The spherical harmonic representation of a prototype diffusion weighted MR signal is used to obtain the direction dependent signal. + * + */ + +template< class ScalarType > +class RawShModel : public DiffusionSignalModel< ScalarType > +{ +public: + + RawShModel(); + ~RawShModel(); + + typedef typename DiffusionSignalModel< ScalarType >::PixelType PixelType; + typedef typename DiffusionSignalModel< ScalarType >::GradientType GradientType; + typedef typename DiffusionSignalModel< ScalarType >::GradientListType GradientListType; + typedef itk::Matrix< double, 3, 3 > MatrixType; + + /** Actual signal generation **/ + PixelType SimulateMeasurement(); + ScalarType SimulateMeasurement(unsigned int dir); + + void SetGradientList(GradientListType gradientList) { this->m_GradientList = gradientList; Cart2Sph(); } + bool SetShCoefficients(vnl_vector< double > shCoefficients); + void SetFiberDirection(GradientType fiberDirection); + void SetB0Signal(ScalarType signal){ m_B0Signal = signal; } + +protected: + + void Cart2Sph(); + + vnl_vector< double > m_ShCoefficients; + GradientType m_PrototypeMaxDirection; + vnl_matrix m_SphCoords; + int m_ShOrder; + GradientListType m_RotatedGradientList; + ScalarType m_B0Signal; +}; + +} + +#include "mitkRawShModel.cpp" + +#endif + diff --git a/Modules/DiffusionImaging/FiberTracking/files.cmake b/Modules/DiffusionImaging/FiberTracking/files.cmake index 05776f0ff2..c0f05f474b 100644 --- a/Modules/DiffusionImaging/FiberTracking/files.cmake +++ b/Modules/DiffusionImaging/FiberTracking/files.cmake @@ -1,78 +1,79 @@ set(CPP_FILES ## IO datastructures IODataStructures/FiberBundleX/mitkFiberBundleX.cpp IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.cpp IODataStructures/FiberBundleX/mitkTrackvis.cpp IODataStructures/PlanarFigureComposite/mitkPlanarFigureComposite.cpp # Interactions Interactions/mitkFiberBundleInteractor.cpp # Tractography Algorithms/GibbsTracking/mitkParticleGrid.cpp Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.cpp Algorithms/GibbsTracking/mitkEnergyComputer.cpp Algorithms/GibbsTracking/mitkGibbsEnergyComputer.cpp Algorithms/GibbsTracking/mitkFiberBuilder.cpp Algorithms/GibbsTracking/mitkSphereInterpolator.cpp ) set(H_FILES # DataStructures -> FiberBundleX IODataStructures/FiberBundleX/mitkFiberBundleX.h IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h IODataStructures/FiberBundleX/mitkFiberBundleXReader.h IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h IODataStructures/FiberBundleX/mitkTrackvis.h IODataStructures/mitkFiberfoxParameters.h # Algorithms Algorithms/itkTractDensityImageFilter.h Algorithms/itkTractsToFiberEndingsImageFilter.h Algorithms/itkTractsToRgbaImageFilter.h Algorithms/itkElectrostaticRepulsionDiffusionGradientReductionFilter.h Algorithms/itkFibersFromPlanarFiguresFilter.h Algorithms/itkTractsToDWIImageFilter.h Algorithms/itkTractsToVectorImageFilter.h Algorithms/itkKspaceImageFilter.h Algorithms/itkDftImageFilter.h Algorithms/itkAddArtifactsToDwiImageFilter.h Algorithms/itkFieldmapGeneratorFilter.h Algorithms/itkEvaluateDirectionImagesFilter.h Algorithms/itkEvaluateTractogramDirectionsFilter.h # (old) Tractography Algorithms/itkGibbsTrackingFilter.h Algorithms/itkStochasticTractographyFilter.h Algorithms/itkStreamlineTrackingFilter.h Algorithms/GibbsTracking/mitkParticle.h Algorithms/GibbsTracking/mitkParticleGrid.h Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.h Algorithms/GibbsTracking/mitkSimpSamp.h Algorithms/GibbsTracking/mitkEnergyComputer.h Algorithms/GibbsTracking/mitkGibbsEnergyComputer.h Algorithms/GibbsTracking/mitkSphereInterpolator.h Algorithms/GibbsTracking/mitkFiberBuilder.h # Signal Models SignalModels/mitkDiffusionSignalModel.h SignalModels/mitkTensorModel.h SignalModels/mitkBallModel.h SignalModels/mitkDotModel.h SignalModels/mitkAstroStickModel.h SignalModels/mitkStickModel.h + SignalModels/mitkRawShModel.h SignalModels/mitkDiffusionNoiseModel.h SignalModels/mitkRicianNoiseModel.h SignalModels/mitkChiSquareNoiseModel.h ) set(RESOURCE_FILES # Binary directory resources FiberTrackingLUTBaryCoords.bin FiberTrackingLUTIndices.bin # Shaders Shaders/mitkShaderFiberClipping.xml ) diff --git a/Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp b/Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp index c6c0c2a327..914d9df06f 100755 --- a/Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp +++ b/Modules/DiffusionImaging/MiniApps/FiberDirectionExtraction.cpp @@ -1,163 +1,163 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include #include #include #include "ctkCommandLineParser.h" #include #include #include #include #include #include #include #define _USE_MATH_DEFINES #include int FiberDirectionExtraction(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input tractogram (.fib, vtk ascii file format)", us::Any(), false); parser.addArgument("out", "o", ctkCommandLineParser::String, "output root", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "mask image"); parser.addArgument("athresh", "a", ctkCommandLineParser::Float, "angular threshold in degrees. closer fiber directions are regarded as one direction and clustered together.", 25, true); parser.addArgument("verbose", "v", ctkCommandLineParser::Bool, "output optional and intermediate calculation results"); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; string fibFile = us::any_cast(parsedArgs["input"]); string maskImage(""); if (parsedArgs.count("mask")) maskImage = us::any_cast(parsedArgs["mask"]); float angularThreshold = 25; if (parsedArgs.count("athresh")) angularThreshold = us::any_cast(parsedArgs["athresh"]); string outRoot = us::any_cast(parsedArgs["out"]); bool verbose = false; if (parsedArgs.count("verbose")) verbose = us::any_cast(parsedArgs["verbose"]); try { typedef itk::Image ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< unsigned int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); // load/create mask image ItkUcharImgType::Pointer itkMaskImage = NULL; if (maskImage.compare("")!=0) { MITK_INFO << "Using mask image"; itkMaskImage = ItkUcharImgType::New(); mitk::Image::Pointer mitkMaskImage = dynamic_cast(mitk::IOUtil::LoadDataNode(maskImage)->GetData()); mitk::CastToItkImage(mitkMaskImage, itkMaskImage); } // extract directions from fiber bundle itk::TractsToVectorImageFilter::Pointer fOdfFilter = itk::TractsToVectorImageFilter::New(); fOdfFilter->SetFiberBundle(inputTractogram); fOdfFilter->SetMaskImage(itkMaskImage); fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180)); - fOdfFilter->SetNormalizeVectors(true); + fOdfFilter->SetNormalizeVectors(false); fOdfFilter->SetUseWorkingCopy(false); fOdfFilter->Update(); ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer(); // write direction images for (unsigned int i=0; iSize(); i++) { itk::TractsToVectorImageFilter::ItkDirectionImageType::Pointer itkImg = directionImageContainer->GetElement(i); typedef itk::ImageFileWriter< itk::TractsToVectorImageFilter::ItkDirectionImageType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_DIRECTION_"); outfilename.append(boost::lexical_cast(i)); outfilename.append(".nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(itkImg); writer->Update(); } if (verbose) { // write vector field mitk::FiberBundleX::Pointer directions = fOdfFilter->GetOutputFiberBundle(); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(directions.GetPointer()) ) { string outfilename = outRoot; outfilename.append("_VECTOR_FIELD.fib"); (*it)->SetFileName( outfilename.c_str() ); (*it)->DoWrite( directions.GetPointer() ); } } // write num direction image { ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage(); typedef itk::ImageFileWriter< ItkUcharImgType > WriterType; WriterType::Pointer writer = WriterType::New(); string outfilename = outRoot; outfilename.append("_NUM_DIRECTIONS.nrrd"); MITK_INFO << "writing " << outfilename; writer->SetFileName(outfilename.c_str()); writer->SetInput(numDirImage); writer->Update(); } } MITK_INFO << "DONE"; } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } RegisterDiffusionMiniApp(FiberDirectionExtraction); diff --git a/Modules/Ext/Algorithms/mitkPointSetToCurvedGeometryFilter.cpp b/Modules/Ext/Algorithms/mitkPointSetToCurvedGeometryFilter.cpp index 5b0941bdf6..77c36f225c 100644 --- a/Modules/Ext/Algorithms/mitkPointSetToCurvedGeometryFilter.cpp +++ b/Modules/Ext/Algorithms/mitkPointSetToCurvedGeometryFilter.cpp @@ -1,165 +1,178 @@ /*=================================================================== 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 "mitkPointSetToCurvedGeometryFilter.h" #include "mitkThinPlateSplineCurvedGeometry.h" #include "mitkPlaneGeometry.h" #include "mitkImage.h" #include "mitkDataNode.h" #include "mitkGeometryData.h" #include "mitkPlaneGeometryData.h" #include "mitkProperties.h" #include "itkMesh.h" #include "itkPointSet.h" mitk::PointSetToCurvedGeometryFilter::PointSetToCurvedGeometryFilter() { m_ProjectionMode = YZPlane; m_PCAPlaneCalculator = mitk::PlaneFit::New(); m_ImageToBeMapped = NULL; m_Sigma = 1000; mitk::PlaneGeometryData::Pointer output = static_cast ( this->MakeOutput ( 0 ).GetPointer() ); output->Initialize(); Superclass::SetNumberOfRequiredOutputs ( 1 ); Superclass::SetNthOutput ( 0, output.GetPointer() ); } mitk::PointSetToCurvedGeometryFilter::~PointSetToCurvedGeometryFilter() {} void mitk::PointSetToCurvedGeometryFilter::GenerateOutputInformation() { mitk::PointSet::ConstPointer input = this->GetInput(); mitk::PlaneGeometryData::Pointer output = dynamic_cast ( this->GetOutput() ); if ( input.IsNull() ) itkGenericExceptionMacro ( "Input point set is NULL!" ); if ( input->GetTimeGeometry()->CountTimeSteps() != 1 ) itkWarningMacro ( "More than one time step is not yet supported!" ); if ( output.IsNull() ) itkGenericExceptionMacro ( "Output is NULL!" ); if ( m_ImageToBeMapped.IsNull() ) itkGenericExceptionMacro ( "Image to be mapped is NULL!" ); bool update = false; if ( output->GetGeometry() == NULL || output->GetPlaneGeometry() == NULL || output->GetTimeGeometry() == NULL ) update = true; if ( ( ! update ) && ( output->GetTimeGeometry()->CountTimeSteps() != input->GetTimeGeometry()->CountTimeSteps() ) ) update = true; if ( update ) { mitk::ThinPlateSplineCurvedGeometry::Pointer curvedGeometry = mitk::ThinPlateSplineCurvedGeometry::New(); output->SetGeometry(curvedGeometry); } } void mitk::PointSetToCurvedGeometryFilter::GenerateData() { mitk::PointSet::ConstPointer input = this->GetInput(); mitk::GeometryData::Pointer output = this->GetOutput(); // // check preconditions // if ( input.IsNull() ) itkGenericExceptionMacro ( "Input point set is NULL!" ); if ( output.IsNull() ) itkGenericExceptionMacro ( "output geometry data is NULL!" ); if ( output->GetTimeGeometry() == NULL ) itkGenericExceptionMacro ( "Output time sliced geometry is NULL!" ); if ( output->GetTimeGeometry()->GetGeometryForTimeStep ( 0 ).IsNull() ) itkGenericExceptionMacro ( "Output geometry3d is NULL!" ); mitk::ThinPlateSplineCurvedGeometry::Pointer curvedGeometry = dynamic_cast ( output->GetTimeGeometry()->GetGeometryForTimeStep( 0 ).GetPointer() ); if ( curvedGeometry.IsNull() ) itkGenericExceptionMacro ( "Output geometry3d is not an instance of mitk::ThinPlateSPlineCurvedGeometry!" ); if ( m_ImageToBeMapped.IsNull() ) itkGenericExceptionMacro ( "Image to be mapped is NULL!" ); // // initialize members if needed // if ( m_XYPlane.IsNull() || m_XZPlane.IsNull() || m_YZPlane.IsNull() ) { m_ImageToBeMapped->UpdateOutputInformation(); const mitk::BaseGeometry* imageGeometry = m_ImageToBeMapped->GetUpdatedGeometry(); imageGeometry = m_ImageToBeMapped->GetUpdatedGeometry(); m_XYPlane = mitk::PlaneGeometry::New(); m_XZPlane = mitk::PlaneGeometry::New(); m_YZPlane = mitk::PlaneGeometry::New(); m_XYPlane->InitializeStandardPlane ( imageGeometry, mitk::PlaneGeometry::Axial ); m_YZPlane->InitializeStandardPlane ( imageGeometry, mitk::PlaneGeometry::Sagittal ); m_XZPlane->InitializeStandardPlane ( imageGeometry, mitk::PlaneGeometry::Frontal ); } if ( m_PlaneLandmarkProjector.IsNull() ) { m_PlaneLandmarkProjector = mitk::PlaneLandmarkProjector::New(); m_SphereLandmarkProjector = mitk::SphereLandmarkProjector::New(); } // // set up geometry according to the current settings // if ( m_ProjectionMode == Sphere ) { curvedGeometry->SetLandmarkProjector ( m_SphereLandmarkProjector ); } else { if ( m_ProjectionMode == XYPlane ) m_PlaneLandmarkProjector->SetProjectionPlane ( m_XYPlane ); else if ( m_ProjectionMode == XZPlane ) m_PlaneLandmarkProjector->SetProjectionPlane ( m_XZPlane ); else if ( m_ProjectionMode == YZPlane ) m_PlaneLandmarkProjector->SetProjectionPlane ( m_YZPlane ); else if ( m_ProjectionMode == PCAPlane ) { itkExceptionMacro ( "PCAPlane not yet implemented!" ); m_PCAPlaneCalculator->SetInput ( input ); m_PCAPlaneCalculator->Update(); - m_PlaneLandmarkProjector->SetProjectionPlane ( dynamic_cast ( m_PCAPlaneCalculator->GetOutput() ) ); + + const PlaneGeometry *planarFigureGeometry = + dynamic_cast< const PlaneGeometry * >( m_PCAPlaneCalculator->GetOutput() ); + const AbstractTransformGeometry *abstrTransfGeometry = + dynamic_cast< const AbstractTransformGeometry * >( m_PCAPlaneCalculator->GetOutput() ); + + if ( !planarFigureGeometry || abstrTransfGeometry ) + { + m_PlaneLandmarkProjector->SetProjectionPlane ( NULL ); + } + else + { + m_PlaneLandmarkProjector->SetProjectionPlane ( planarFigureGeometry ); + } } else itkExceptionMacro ( "Unknown projection mode" ); curvedGeometry->SetLandmarkProjector ( m_PlaneLandmarkProjector ); } //curvedGeometry->SetReferenceGeometry( m_ImageToBeMapped->GetGeometry() ); curvedGeometry->SetTargetLandmarks ( input->GetPointSet ( 0 )->GetPoints() ); curvedGeometry->SetSigma ( m_Sigma ); curvedGeometry->ComputeGeometry(); curvedGeometry->SetOversampling ( 1.0 ); } void mitk::PointSetToCurvedGeometryFilter::SetDefaultCurvedGeometryProperties ( mitk::DataNode* node ) { if ( node == NULL ) { itkGenericOutputMacro ( "Warning: node is NULL!" ); return; } node->SetIntProperty ( "xresolution", 50 ); node->SetIntProperty ( "yresolution", 50 ); node->SetProperty ( "name", mitk::StringProperty::New ( "Curved Plane" ) ); // exclude extent of this plane when calculating DataStorage bounding box node->SetProperty ( "includeInBoundingBox", mitk::BoolProperty::New ( false ) ); } diff --git a/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.cpp b/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.cpp index 1d6c97c287..2fb6db6714 100644 --- a/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.cpp +++ b/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.cpp @@ -1,85 +1,141 @@ /*=================================================================== 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 "mitkUSTelemedImageSource.h" #include "mitkUSTelemedSDKHeader.h" #include "MITKUSTelemedScanConverterPlugin.h" #include "mitkImageReadAccessor.h" mitk::USTelemedImageSource::USTelemedImageSource( ) : m_Image(mitk::Image::New()), m_ImageMutex(itk::FastMutexLock::New()), m_Plugin(0), - m_PluginCallback(0) + m_PluginCallback(0), + m_UsgDataView(0), + m_ImageProperties(0), + m_DepthProperties(0), + m_upDateCounter(0) { } mitk::USTelemedImageSource::~USTelemedImageSource( ) { SAFE_RELEASE(m_PluginCallback); SAFE_RELEASE(m_Plugin); + SAFE_RELEASE(m_ImageProperties); + SAFE_RELEASE(m_DepthProperties); } void mitk::USTelemedImageSource::GetNextRawImage( mitk::Image::Pointer& image) { if ( image.IsNull() ) { image = mitk::Image::New(); } + + //if depth changed: update geometry, but 20 frames after the change because it takes this time until geometry adapts + if (m_upDateCounter==20 && m_Image->IsInitialized()) + { + UpdateImageGeometry(); + m_upDateCounter++; + } + if (m_OldDepth != m_DepthProperties->Current) + { + m_upDateCounter=0; + m_OldDepth = m_DepthProperties->GetCurrent(); + } + if (m_upDateCounter<20) m_upDateCounter++; + + //now update image if ( m_Image->IsInitialized() ) { m_ImageMutex->Lock(); // copy contents of the given image into the member variable image->Initialize(m_Image->GetPixelType(), m_Image->GetDimension(), m_Image->GetDimensions()); mitk::ImageReadAccessor inputReadAccessor(m_Image, m_Image->GetSliceData(0,0,0)); image->SetSlice(inputReadAccessor.GetData()); + image->SetGeometry(m_Image->GetGeometry()); m_ImageMutex->Unlock(); } + +} + +void mitk::USTelemedImageSource::UpdateImageGeometry() +{ + Usgfw2Lib::tagPixelsOrigin origin = Usgfw2Lib::tagPixelsOrigin(); + Usgfw2Lib::tagImageResolution resolutionInMeters; + m_ImageProperties->GetResolution(&resolutionInMeters,0); + + mitk::Vector3D spacing; + spacing[0] = ((double)1 / resolutionInMeters.nXPelsPerUnit) * 1000; //conversion: meters to millimeters + spacing[1] = ((double)1 / resolutionInMeters.nXPelsPerUnit) * 1000; //conversion: meters to millimeters + spacing[2] = 1; + + m_ImageMutex->Lock(); + if(m_Image.IsNotNull() && (m_Image->GetGeometry()!=NULL)) + { + m_Image->GetGeometry()->SetSpacing(spacing); + m_Image->GetGeometry()->Modified(); + } + else + {MITK_WARN << "image or geometry was NULL, can't adapt geometry";} + m_ImageMutex->Unlock(); + + MITK_DEBUG << "UpdateImageGeometry called!"; + MITK_DEBUG << "depth: " << m_DepthProperties->GetCurrent(); + MITK_DEBUG << "new spacing: " << spacing; } bool mitk::USTelemedImageSource::CreateAndConnectConverterPlugin(Usgfw2Lib::IUsgDataView* usgDataView, Usgfw2Lib::tagScanMode scanMode) { IUnknown* tmp_obj = NULL; // create control object from Telemed API mitk::telemed::CreateUsgControl( usgDataView, Usgfw2Lib::IID_IUsgScanConverterPlugin, scanMode, 0, (void**)&tmp_obj ); if ( ! tmp_obj ) { MITK_ERROR("USImageSource")("USTelemedImageSource") << "Could not create scan converter plugin."; return false; } // create the callback object for the scan conversion if ( ! m_PluginCallback ) { m_PluginCallback = new USTelemedScanConverterPlugin(); // current image buffer should be copied to m_Image at every callback m_PluginCallback->SetOutputImage(m_Image.GetPointer(), m_ImageMutex); } else { // make sure that the scan converter plugin is not set // to the plugin callback any longer m_PluginCallback->SetScanConverterPlugin(0); } // now the ScanConverterPlugin can be created and set as plugin SAFE_RELEASE(m_Plugin); m_Plugin = (Usgfw2Lib::IUsgScanConverterPlugin*)tmp_obj; m_PluginCallback->SetScanConverterPlugin(m_Plugin); + //last: create some connections which are needed inside this class for communication with the telemed device + m_UsgDataView = usgDataView; + + // create telemed controls + if (!m_DepthProperties) {CREATE_TelemedControl(m_DepthProperties, m_UsgDataView, Usgfw2Lib::IID_IUsgDepth, Usgfw2Lib::IUsgDepth, Usgfw2Lib::SCAN_MODE_B);} + if (!m_ImageProperties) {CREATE_TelemedControl(m_ImageProperties, m_UsgDataView, Usgfw2Lib::IID_IUsgImageProperties, Usgfw2Lib::IUsgImageProperties, Usgfw2Lib::SCAN_MODE_B);} + return true; } \ No newline at end of file diff --git a/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.h b/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.h index e6f9dde4f0..2961df65d0 100644 --- a/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.h +++ b/Modules/US/USHardwareTelemed/mitkUSTelemedImageSource.h @@ -1,67 +1,83 @@ /*=================================================================== 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 MITKUSTelemedImageSource_H_HEADER_INCLUDED_ #define MITKUSTelemedImageSource_H_HEADER_INCLUDED_ #include "mitkUSImageSource.h" #include "mitkUSTelemedSDKHeader.h" #include "mitkUSTelemedScanConverterPlugin.h" #include "itkFastMutexLock.h" namespace mitk { /** * \brief Implementation of mitk::USImageSource for Telemed API devices. * The method mitk::USImageSource::GetNextRawImage() is implemented for * getting images from the Telemed API. * * A method for connecting this ImageSource to the Telemed API is * implemented (mitk::USTelemedImageSource::CreateAndConnectConverterPlugin()). * This method is available for being used by mitk::USTelemedDevice. */ class USTelemedImageSource : public USImageSource { public: mitkClassMacro(USTelemedImageSource, USImageSource); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * Implementation of the superclass method. Returns the pointer * to the mitk::Image filled by Telemed API callback. */ virtual void GetNextRawImage( mitk::Image::Pointer& ); + /** + * Updates the geometry of the current image from the API. + * Is used internally when a new image is initialized, but + * also needs to be called if, e.g., the zoom factor is changed. + */ + void UpdateImageGeometry(); + /** * \brief Connect this object to the Telemed API. * This method is for being used by mitk::USTelemedDevice. */ bool CreateAndConnectConverterPlugin( Usgfw2Lib::IUsgDataView*, Usgfw2Lib::tagScanMode ); protected: USTelemedImageSource( ); virtual ~USTelemedImageSource( ); Usgfw2Lib::IUsgScanConverterPlugin* m_Plugin; USTelemedScanConverterPlugin* m_PluginCallback; + Usgfw2Lib::IUsgDataView* m_UsgDataView; // main SDK object for comminucating with the Telemed API + + //API objects for communication, used to get the right geometry + Usgfw2Lib::IUsgImageProperties* m_ImageProperties; + Usgfw2Lib::IUsgDepth* m_DepthProperties; + double m_OldDepth; + int m_upDateCounter; + + mitk::Image::Pointer m_Image; itk::FastMutexLock::Pointer m_ImageMutex; }; } // namespace mitk #endif // MITKUSTelemedImageSource_H diff --git a/Modules/US/USModel/mitkUSDevice.cpp b/Modules/US/USModel/mitkUSDevice.cpp index a5ef150a61..1bfca80e85 100644 --- a/Modules/US/USModel/mitkUSDevice.cpp +++ b/Modules/US/USModel/mitkUSDevice.cpp @@ -1,559 +1,561 @@ /*=================================================================== 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 "mitkUSDevice.h" #include "mitkImageReadAccessor.h" // US Control Interfaces #include "mitkUSControlInterfaceProbes.h" #include "mitkUSControlInterfaceBMode.h" #include "mitkUSControlInterfaceDoppler.h" // Microservices #include #include #include #include mitk::USDevice::PropertyKeys mitk::USDevice::GetPropertyKeys() { static mitk::USDevice::PropertyKeys propertyKeys; return propertyKeys; } mitk::USDevice::USImageCropArea mitk::USDevice::GetCropArea() { MITK_INFO << "Return Crop Area L:" << m_CropArea.cropLeft << " R:" << m_CropArea.cropRight << " T:" << m_CropArea.cropTop << " B:" << m_CropArea.cropBottom; return m_CropArea; } mitk::USDevice::USDevice(std::string manufacturer, std::string model) : mitk::ImageSource(), m_IsFreezed(false), m_DeviceState(State_NoState), m_Manufacturer(manufacturer), m_Name(model), m_SpawnAcquireThread(true), m_MultiThreader(itk::MultiThreader::New()), m_ImageMutex(itk::FastMutexLock::New()), m_ThreadID(-1), m_UnregisteringStarted(false) { USImageCropArea empty; empty.cropBottom = 0; empty.cropTop = 0; empty.cropLeft = 0; empty.cropRight = 0; this->m_CropArea = empty; //set number of outputs this->SetNumberOfIndexedOutputs(1); //create a new output mitk::Image::Pointer newOutput = mitk::Image::New(); this->SetNthOutput(0,newOutput); } mitk::USDevice::USDevice(mitk::USImageMetadata::Pointer metadata) : mitk::ImageSource(), m_IsFreezed(false), m_DeviceState(State_NoState), m_SpawnAcquireThread(true), m_MultiThreader(itk::MultiThreader::New()), m_ImageMutex(itk::FastMutexLock::New()), m_ThreadID(-1), m_UnregisteringStarted(false) { m_Manufacturer = metadata->GetDeviceManufacturer(); m_Name = metadata->GetDeviceModel(); m_Comment = metadata->GetDeviceComment(); USImageCropArea empty; empty.cropBottom = 0; empty.cropTop = 0; empty.cropLeft = 0; empty.cropRight = 0; this->m_CropArea = empty; //set number of outputs this->SetNumberOfIndexedOutputs(1); //create a new output mitk::Image::Pointer newOutput = mitk::Image::New(); this->SetNthOutput(0,newOutput); } mitk::USDevice::~USDevice() { if (m_ThreadID >= 0) { m_MultiThreader->TerminateThread(m_ThreadID); } // make sure that the us device is not registered at the micro service // anymore after it is destructed this->UnregisterOnService(); } mitk::USAbstractControlInterface::Pointer mitk::USDevice::GetControlInterfaceCustom() { MITK_INFO << "Custom control interface does not exist for this object."; return 0; } mitk::USControlInterfaceBMode::Pointer mitk::USDevice::GetControlInterfaceBMode() { MITK_INFO << "Control interface BMode does not exist for this object."; return 0; } mitk::USControlInterfaceProbes::Pointer mitk::USDevice::GetControlInterfaceProbes() { MITK_INFO << "Control interface Probes does not exist for this object."; return 0; } mitk::USControlInterfaceDoppler::Pointer mitk::USDevice::GetControlInterfaceDoppler() { MITK_INFO << "Control interface Doppler does not exist for this object."; return 0; } void mitk::USDevice::SetManufacturer(std::string manufacturer) { m_Manufacturer = manufacturer; if ( m_DeviceState >= State_Initialized ) { this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_MANUFACTURER, manufacturer); } } void mitk::USDevice::SetName(std::string name) { m_Name = name; if ( m_DeviceState >= State_Initialized ) { this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_NAME, name); } } void mitk::USDevice::SetComment(std::string comment) { m_Comment = comment; if ( m_DeviceState >= State_Initialized ) { this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_COMMENT, comment); } } us::ServiceProperties mitk::USDevice::ConstructServiceProperties() { mitk::USDevice::PropertyKeys propertyKeys = mitk::USDevice::GetPropertyKeys(); us::ServiceProperties props; props[propertyKeys.US_PROPKEY_ISCONNECTED] = this->GetIsConnected() ? "true" : "false"; props[propertyKeys.US_PROPKEY_ISACTIVE] = this->GetIsActive() ? "true" : "false"; props[propertyKeys.US_PROPKEY_LABEL] = this->GetServicePropertyLabel(); // get identifier of selected probe if there is one selected mitk::USControlInterfaceProbes::Pointer probesControls = this->GetControlInterfaceProbes(); if (probesControls.IsNotNull() && probesControls->GetIsActive()) { mitk::USProbe::Pointer probe = probesControls->GetSelectedProbe(); if (probe.IsNotNull()) { props[propertyKeys.US_PROPKEY_PROBES_SELECTED] = probe->GetName(); } } props[ propertyKeys.US_PROPKEY_CLASS ] = GetDeviceClass(); props[ propertyKeys.US_PROPKEY_MANUFACTURER ] = m_Manufacturer; props[ propertyKeys.US_PROPKEY_NAME ] = m_Name; props[ propertyKeys.US_PROPKEY_COMMENT ] = m_Comment; m_ServiceProperties = props; return props; } void mitk::USDevice::UnregisterOnService() { // unregister on micro service if ( m_ServiceRegistration && ! m_UnregisteringStarted) { // make sure that unregister is not started a second // time due to a callback during unregister for example m_UnregisteringStarted = true; m_ServiceRegistration.Unregister(); m_ServiceRegistration = 0; } } bool mitk::USDevice::Initialize() { if (! this->OnInitialization() ) { return false; } m_DeviceState = State_Initialized; // Get Context and Module us::ModuleContext* context = us::GetModuleContext(); us::ServiceProperties props = this->ConstructServiceProperties(); m_ServiceRegistration = context->RegisterService(this, props); return true; } bool mitk::USDevice::Connect() { if ( this->GetIsConnected() ) { MITK_INFO("mitkUSDevice") << "Tried to connect an ultrasound device that was already connected. Ignoring call..."; return true; } if ( ! this->GetIsInitialized() ) { MITK_ERROR("mitkUSDevice") << "Cannot connect device if it is not in initialized state."; return false; } // Prepare connection, fail if this fails. if ( ! this->OnConnection() ) { return false; } // Update state m_DeviceState = State_Connected; this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISCONNECTED, true); return true; } void mitk::USDevice::ConnectAsynchron() { this->m_MultiThreader->SpawnThread(this->ConnectThread, this); } bool mitk::USDevice::Disconnect() { if ( ! GetIsConnected()) { MITK_WARN << "Tried to disconnect an ultrasound device that was not connected. Ignoring call..."; return false; } // Prepare connection, fail if this fails. if (! this->OnDisconnection()) return false; // Update state m_DeviceState = State_Initialized; this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISCONNECTED, false); return true; } bool mitk::USDevice::Activate() { if (! this->GetIsConnected()) { MITK_INFO("mitkUSDevice") << "Cannot activate device if it is not in connected state."; return true; } if ( OnActivation() ) { m_DeviceState = State_Activated; m_FreezeBarrier = itk::ConditionVariable::New(); // spawn thread for aquire images if us device is active if (m_SpawnAcquireThread) { this->m_ThreadID = this->m_MultiThreader->SpawnThread(this->Acquire, this); } this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE, true); this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL, this->GetServicePropertyLabel()); // initialize the b mode control properties of the micro service mitk::USControlInterfaceBMode::Pointer bmodeControls = this->GetControlInterfaceBMode(); if ( bmodeControls.IsNotNull() ) { bmodeControls->Initialize(); } } return m_DeviceState == State_Activated; } void mitk::USDevice::Deactivate() { if ( ! this->GetIsActive() ) { MITK_WARN("mitkUSDevice") << "Cannot deactivate a device which is not activae."; return; } if ( ! OnDeactivation() ) { return; } m_DeviceState = State_Connected; this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE, false); this->UpdateServiceProperty(mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL, this->GetServicePropertyLabel()); } void mitk::USDevice::SetIsFreezed(bool freeze) { if ( ! this->GetIsActive() ) { MITK_WARN("mitkUSDevice") << "Cannot freeze or unfreeze if device is not active."; return; } this->OnFreeze(freeze); if ( freeze ) { m_IsFreezed = true; } else { m_IsFreezed = false; // wake up the image acquisition thread m_FreezeBarrier->Signal(); } } bool mitk::USDevice::GetIsFreezed() { if ( ! this->GetIsActive() ) { MITK_WARN("mitkUSDevice")("mitkUSTelemedDevice") << "Cannot get freeze state if the hardware interface is not ready. Returning false..."; return false; } return m_IsFreezed; } void mitk::USDevice::PushFilter(AbstractOpenCVImageFilter::Pointer filter) { mitk::USImageSource::Pointer imageSource = this->GetUSImageSource(); if ( imageSource.IsNull() ) { MITK_ERROR << "ImageSource must not be null when pushing a filter."; mitkThrow() << "ImageSource must not be null when pushing a filter."; } imageSource->PushFilter(filter); } void mitk::USDevice::PushFilterIfNotPushedBefore(AbstractOpenCVImageFilter::Pointer filter) { mitk::USImageSource::Pointer imageSource = this->GetUSImageSource(); if ( imageSource.IsNull() ) { MITK_ERROR << "ImageSource must not be null when pushing a filter."; mitkThrow() << "ImageSource must not be null when pushing a filter."; } if ( ! imageSource->GetIsFilterInThePipeline(filter) ) { imageSource->PushFilter(filter); } } bool mitk::USDevice::RemoveFilter(AbstractOpenCVImageFilter::Pointer filter) { mitk::USImageSource::Pointer imageSource = this->GetUSImageSource(); if ( imageSource.IsNull() ) { MITK_ERROR << "ImageSource must not be null when pushing a filter."; mitkThrow() << "ImageSource must not be null when removing a filter."; } return imageSource->RemoveFilter(filter); } void mitk::USDevice::UpdateServiceProperty(std::string key, std::string value) { m_ServiceProperties[ key ] = value; m_ServiceRegistration.SetProperties(m_ServiceProperties); // send event to notify listeners about the changed property m_PropertyChangedMessage(key, value); } void mitk::USDevice::UpdateServiceProperty(std::string key, double value) { std::stringstream stream; stream << value; this->UpdateServiceProperty(key, stream.str()); } void mitk::USDevice::UpdateServiceProperty(std::string key, bool value) { this->UpdateServiceProperty(key, value ? std::string("true") : std::string("false")); } /** mitk::Image* mitk::USDevice::GetOutput() { if (this->GetNumberOfOutputs() < 1) return NULL; return static_cast(this->ProcessObject::GetPrimaryOutput()); } mitk::Image* mitk::USDevice::GetOutput(unsigned int idx) { if (this->GetNumberOfOutputs() < 1) return NULL; return static_cast(this->ProcessObject::GetOutput(idx)); } void mitk::USDevice::GraftOutput(itk::DataObject *graft) { this->GraftNthOutput(0, graft); } void mitk::USDevice::GraftNthOutput(unsigned int idx, itk::DataObject *graft) { if ( idx >= this->GetNumberOfOutputs() ) { itkExceptionMacro(<<"Requested to graft output " << idx << " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); } if ( !graft ) { itkExceptionMacro(<<"Requested to graft output with a NULL pointer object" ); } itk::DataObject* output = this->GetOutput(idx); if ( !output ) { itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); } // Call Graft on USImage to copy member data output->Graft( graft ); } */ void mitk::USDevice::GrabImage() { mitk::Image::Pointer image = this->GetUSImageSource()->GetNextImage(); m_ImageMutex->Lock(); this->SetImage(image); m_ImageMutex->Unlock(); + //if (image.IsNotNull() && (image->GetGeometry()!=NULL)){ + // MITK_INFO << "Spacing: " << image->GetGeometry()->GetSpacing();} } //########### GETTER & SETTER ##################// bool mitk::USDevice::GetIsInitialized() { return m_DeviceState == State_Initialized; } bool mitk::USDevice::GetIsActive() { return m_DeviceState == State_Activated; } bool mitk::USDevice::GetIsConnected() { return m_DeviceState == State_Connected; } std::string mitk::USDevice::GetDeviceManufacturer(){ return m_Manufacturer; } std::string mitk::USDevice::GetDeviceModel(){ return m_Name; } std::string mitk::USDevice::GetDeviceComment(){ return m_Comment; } void mitk::USDevice::GenerateData() { m_ImageMutex->Lock(); if ( m_Image.IsNull() || ! m_Image->IsInitialized() ) { m_ImageMutex->Unlock(); return; } mitk::Image::Pointer output = this->GetOutput(); if ( ! output->IsInitialized() || output->GetDimension(0) != m_Image->GetDimension(0) || output->GetDimension(1) != m_Image->GetDimension(1) ) { output->Initialize(m_Image->GetPixelType(), m_Image->GetDimension(), m_Image->GetDimensions()); } mitk::ImageReadAccessor inputReadAccessor(m_Image, m_Image->GetSliceData(0,0,0)); output->SetSlice(inputReadAccessor.GetData()); - + output->SetGeometry(m_Image->GetGeometry()); m_ImageMutex->Unlock(); }; std::string mitk::USDevice::GetServicePropertyLabel() { std::string isActive; if (this->GetIsActive()) { isActive = " (Active)"; } else { isActive = " (Inactive)"; } // e.g.: Zonare MyLab5 (Active) return m_Manufacturer + " " + m_Name + isActive; } ITK_THREAD_RETURN_TYPE mitk::USDevice::Acquire(void* pInfoStruct) { /* extract this pointer from Thread Info structure */ struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct; mitk::USDevice* device = (mitk::USDevice*) pInfo->UserData; while (device->GetIsActive()) { // lock this thread when ultrasound device is freezed if ( device->m_IsFreezed ) { itk::SimpleMutexLock* mutex = &(device->m_FreezeMutex); mutex->Lock(); if (device->m_FreezeBarrier.IsNotNull()) { device->m_FreezeBarrier->Wait(mutex); } } device->GrabImage(); } return ITK_THREAD_RETURN_VALUE; } ITK_THREAD_RETURN_TYPE mitk::USDevice::ConnectThread(void* pInfoStruct) { /* extract this pointer from Thread Info structure */ struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct; mitk::USDevice* device = (mitk::USDevice*) pInfo->UserData; device->Connect(); return ITK_THREAD_RETURN_VALUE; } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp index 75dbc0bfd7..6f1a6b01c2 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp @@ -1,220 +1,262 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 "CommandLineModulesPreferencesPage.h" #include "CommandLineModulesViewConstants.h" #include +#include #include #include #include #include #include #include #include #include #include #include #include "QmitkDirectoryListWidget.h" #include "QmitkFileListWidget.h" //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::CommandLineModulesPreferencesPage() : m_MainControl(0) +, m_DebugOutput(0) +, m_ShowAdvancedWidgets(0) , m_OutputDirectory(0) , m_TemporaryDirectory(0) , m_ModulesDirectories(0) , m_ModulesFiles(0) +, m_GridLayoutForLoadCheckboxes(0) , m_LoadFromHomeDir(0) , m_LoadFromHomeDirCliModules(0) , m_LoadFromCurrentDir(0) , m_LoadFromCurrentDirCliModules(0) , m_LoadFromApplicationDir(0) , m_LoadFromApplicationDirCliModules(0) , m_LoadFromAutoLoadPathDir(0) , m_ValidationMode(0) , m_MaximumNumberProcesses(0) , m_CLIPreferencesNode(0) { } //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::~CommandLineModulesPreferencesPage() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::CreateQtControl(QWidget* parent) { berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); std::string id = "/" + CommandLineModulesViewConstants::VIEW_ID; m_CLIPreferencesNode = prefService->GetSystemPreferences()->Node(id); m_MainControl = new QWidget(parent); m_TemporaryDirectory = new ctkDirectoryButton(m_MainControl); m_TemporaryDirectory->setCaption("Select a directory for temporary files ... "); m_OutputDirectory = new ctkDirectoryButton(m_MainControl); m_OutputDirectory->setCaption("Select a default directory for output files ... "); m_ModulesDirectories = new QmitkDirectoryListWidget(m_MainControl); m_ModulesDirectories->m_Label->setText("Select directories to scan:"); m_ModulesFiles = new QmitkFileListWidget(m_MainControl); m_ModulesFiles->m_Label->setText("Select additional executables:"); + m_DebugOutput = new QCheckBox(m_MainControl); + m_DebugOutput->setToolTip("Output debugging information to the console."); + + m_ShowAdvancedWidgets = new QCheckBox(m_MainControl); + m_ShowAdvancedWidgets->setToolTip("If selected, additional widgets appear\nin front-end for advanced users."); m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl); + m_LoadFromAutoLoadPathDir->setText("CTK_MODULE_LOAD_PATH"); + m_LoadFromAutoLoadPathDir->setToolTip("Scan the directory specified by\nthe environment variable CTK_MODULE_LOAD_PATH."); + m_LoadFromAutoLoadPathDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDir = new QCheckBox(m_MainControl); + m_LoadFromApplicationDir->setText("install dir"); + m_LoadFromApplicationDir->setToolTip("Scan the directory where\nthe application is installed."); + m_LoadFromApplicationDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDirCliModules = new QCheckBox(m_MainControl); + m_LoadFromApplicationDirCliModules->setText("install dir/cli-modules"); + m_LoadFromApplicationDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the installation directory."); + m_LoadFromApplicationDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDir = new QCheckBox(m_MainControl); + m_LoadFromHomeDir->setText("home dir"); + m_LoadFromHomeDir->setToolTip("Scan the users home directory."); + m_LoadFromHomeDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDirCliModules = new QCheckBox(m_MainControl); + m_LoadFromHomeDirCliModules->setText("home dir/cli-modules"); + m_LoadFromHomeDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the users home directory."); + m_LoadFromHomeDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDir = new QCheckBox(m_MainControl); + m_LoadFromCurrentDir->setText("current dir"); + m_LoadFromCurrentDir->setToolTip("Scan the current working directory\nfrom where the application was launched."); + m_LoadFromCurrentDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDirCliModules = new QCheckBox(m_MainControl); + m_LoadFromCurrentDirCliModules->setText("current dir/cli-modules"); + m_LoadFromCurrentDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the current working directory \n from where the application was launched."); + m_LoadFromCurrentDirCliModules->setLayoutDirection(Qt::RightToLeft); + + m_GridLayoutForLoadCheckboxes = new QGridLayout; + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDir, 0, 0); + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDirCliModules, 0, 1); + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDir, 1, 0); + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDirCliModules, 1, 1); + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDir, 2, 0); + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDirCliModules, 2, 1); + m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromAutoLoadPathDir, 3, 1); m_ValidationMode = new QComboBox(m_MainControl); m_ValidationMode->addItem("strict", ctkCmdLineModuleManager::STRICT_VALIDATION); m_ValidationMode->addItem("none", ctkCmdLineModuleManager::SKIP_VALIDATION); m_ValidationMode->addItem("weak", ctkCmdLineModuleManager::WEAK_VALIDATION); m_ValidationMode->setCurrentIndex(0); m_MaximumNumberProcesses = new QSpinBox(m_MainControl); m_MaximumNumberProcesses->setMinimum(1); m_MaximumNumberProcesses->setMaximum(1000000); + m_XmlTimeoutInSeconds = new QSpinBox(m_MainControl); + m_XmlTimeoutInSeconds->setMinimum(1); + m_XmlTimeoutInSeconds->setMaximum(3600); QFormLayout *formLayout = new QFormLayout; formLayout->addRow("show debug output:", m_DebugOutput); + formLayout->addRow("show advanced widgets:", m_ShowAdvancedWidgets); + formLayout->addRow("XML time-out (secs):", m_XmlTimeoutInSeconds); formLayout->addRow("XML validation mode:", m_ValidationMode); formLayout->addRow("max. concurrent processes:", m_MaximumNumberProcesses); - formLayout->addRow("scan home directory:", m_LoadFromHomeDir); - formLayout->addRow("scan home directory/cli-modules:", m_LoadFromHomeDirCliModules); - formLayout->addRow("scan current directory:", m_LoadFromCurrentDir); - formLayout->addRow("scan current directory/cli-modules:", m_LoadFromCurrentDirCliModules); - formLayout->addRow("scan installation directory:", m_LoadFromApplicationDir); - formLayout->addRow("scan installation directory/cli-modules:", m_LoadFromApplicationDirCliModules); - formLayout->addRow("scan CTK_MODULE_LOAD_PATH:", m_LoadFromAutoLoadPathDir); + formLayout->addRow("scan:", m_GridLayoutForLoadCheckboxes); formLayout->addRow("additional module directories:", m_ModulesDirectories); formLayout->addRow("additional modules:", m_ModulesFiles); formLayout->addRow("temporary directory:", m_TemporaryDirectory); formLayout->addRow("default output directory:", m_OutputDirectory); m_MainControl->setLayout(formLayout); this->Update(); } //----------------------------------------------------------------------------- QWidget* CommandLineModulesPreferencesPage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- std::string CommandLineModulesPreferencesPage::ConvertToStdString(const QStringList& list) { std::string output; for (int i = 0; i < list.count(); i++) { QString path = list[i] + ";"; output += path.toStdString(); } return output; } //----------------------------------------------------------------------------- bool CommandLineModulesPreferencesPage::PerformOk() { m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory().toStdString()); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory().toStdString()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); + m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, m_ShowAdvancedWidgets->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, m_LoadFromApplicationDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, m_LoadFromHomeDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, m_LoadFromCurrentDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); std::string paths = this->ConvertToStdString(m_ModulesDirectories->directories()); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, paths); std::string modules = this->ConvertToStdString(m_ModulesFiles->files()); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, modules); int currentValidationMode = m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 0); if (currentValidationMode != m_ValidationMode->currentIndex()) { QMessageBox msgBox; msgBox.setText("Changing the XML validation mode will require a restart of the application."); msgBox.exec(); } m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, m_ValidationMode->currentIndex()); + m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, m_XmlTimeoutInSeconds->value()); m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::MAX_CONCURRENT, m_MaximumNumberProcesses->value()); return true; } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::PerformCancel() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Update() { QString fallbackTmpDir = QDir::tempPath(); m_TemporaryDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir.toStdString()))); QString fallbackOutputDir = QDir::homePath(); m_OutputDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir.toStdString()))); + m_ShowAdvancedWidgets->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); m_DebugOutput->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false)); m_LoadFromApplicationDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false)); m_LoadFromApplicationDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true)); m_LoadFromHomeDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false)); m_LoadFromHomeDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false)); m_LoadFromCurrentDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false)); m_LoadFromCurrentDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false)); m_LoadFromAutoLoadPathDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); QString paths = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); QStringList directoryList = paths.split(";", QString::SkipEmptyParts); m_ModulesDirectories->setDirectories(directoryList); QString files = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); QStringList fileList = files.split(";", QString::SkipEmptyParts); m_ModulesFiles->setFiles(fileList); m_ValidationMode->setCurrentIndex(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 0)); + m_XmlTimeoutInSeconds->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30)); // 30 secs = QProcess default timeout m_MaximumNumberProcesses->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4)); } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h index e5a0171ded..3bd0888cf9 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.h @@ -1,107 +1,111 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 COMMANDLINEMODULESPREFERENCESPAGE_H #define COMMANDLINEMODULESPREFERENCESPAGE_H #include "berryIQtPreferencePage.h" #include "berryIPreferences.h" #include class QWidget; +class QGridLayout; class QCheckBox; class QComboBox; class QSpinBox; class QmitkDirectoryListWidget; class QmitkFileListWidget; class ctkDirectoryButton; /** * \class CommandLineModulesPreferencesPage * \brief Preference page for CommandLineModulesView * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ class CommandLineModulesPreferencesPage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: CommandLineModulesPreferencesPage(); ~CommandLineModulesPreferencesPage(); /** * \brief Called by framework to initialise this preference page, but currently does nothing. * \param workbench The workbench. */ void Init(berry::IWorkbench::Pointer workbench); /** * \brief Called by framework to create the GUI, and connect signals and slots. * \param widget The Qt widget that acts as parent to all GUI components, as this class itself is not derived from QWidget. */ void CreateQtControl(QWidget* widget); /** * \brief Required by framework to get hold of the GUI. * \return QWidget* the top most QWidget for the GUI. */ QWidget* GetQtControl() const; /** * \see IPreferencePage::PerformOk */ virtual bool PerformOk(); /** * \see IPreferencePage::PerformCancel */ virtual void PerformCancel(); /** * \see IPreferencePage::Update */ virtual void Update(); public slots: protected: QWidget *m_MainControl; QCheckBox *m_DebugOutput; + QCheckBox *m_ShowAdvancedWidgets; ctkDirectoryButton *m_OutputDirectory; ctkDirectoryButton *m_TemporaryDirectory; QmitkDirectoryListWidget *m_ModulesDirectories; QmitkFileListWidget *m_ModulesFiles; + QGridLayout *m_GridLayoutForLoadCheckboxes; QCheckBox *m_LoadFromHomeDir; QCheckBox *m_LoadFromHomeDirCliModules; QCheckBox *m_LoadFromCurrentDir; QCheckBox *m_LoadFromCurrentDirCliModules; QCheckBox *m_LoadFromApplicationDir; QCheckBox *m_LoadFromApplicationDirCliModules; QCheckBox *m_LoadFromAutoLoadPathDir; QComboBox *m_ValidationMode; + QSpinBox *m_XmlTimeoutInSeconds; QSpinBox *m_MaximumNumberProcesses; berry::IPreferences::Pointer m_CLIPreferencesNode; private: std::string ConvertToStdString(const QStringList& list); }; #endif // COMMANDLINEMODULESPREFERENCESPAGE_H diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp index a0d3e07209..96598270de 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp @@ -1,473 +1,553 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 #include // Qmitk #include "CommandLineModulesView.h" #include "CommandLineModulesViewConstants.h" #include "CommandLineModulesViewControls.h" #include "CommandLineModulesPreferencesPage.h" #include "QmitkCmdLineModuleFactoryGui.h" #include "QmitkCmdLineModuleGui.h" #include "QmitkCmdLineModuleProgressWidget.h" // Qt #include #include #include #include #include #include #include +#include // CTK #include #include #include #include #include #include #include #include +#include +#include //----------------------------------------------------------------------------- CommandLineModulesView::CommandLineModulesView() : m_Controls(NULL) , m_Parent(NULL) , m_Layout(NULL) , m_ModuleManager(NULL) , m_ModuleBackend(NULL) , m_DirectoryWatcher(NULL) , m_TemporaryDirectoryName("") , m_MaximumConcurrentProcesses(4) , m_CurrentlyRunningProcesses(0) , m_DebugOutput(false) +, m_XmlTimeoutSeconds(30) // 30 seconds = QProcess default timeout. { } //----------------------------------------------------------------------------- CommandLineModulesView::~CommandLineModulesView() { if (m_ModuleManager != NULL) { delete m_ModuleManager; } if (m_ModuleBackend != NULL) { delete m_ModuleBackend; } if (m_DirectoryWatcher != NULL) { delete m_DirectoryWatcher; } if (m_Layout != NULL) { delete m_Layout; } for (int i = 0; i < m_ListOfModules.size(); i++) { delete m_ListOfModules[i]; } } //----------------------------------------------------------------------------- void CommandLineModulesView::SetFocus() { this->m_Controls->m_ComboBox->setFocus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::CreateQtPartControl( QWidget *parent ) { m_Parent = parent; if (!m_Controls) { // We create CommandLineModulesViewControls, which derives from the Qt generated class. m_Controls = new CommandLineModulesViewControls(parent); // Create a layout to contain a display of QmitkCmdLineModuleProgressWidget. m_Layout = new QVBoxLayout(m_Controls->m_RunningWidgets); m_Layout->setContentsMargins(0,0,0,0); m_Layout->setSpacing(0); // This must be done independent of other preferences, as we need it before // we create the ctkCmdLineModuleManager to initialise the Cache. this->RetrieveAndStoreTemporaryDirectoryPreferenceValues(); this->RetrieveAndStoreValidationMode(); // Start to create the command line module infrastructure. m_ModuleBackend = new ctkCmdLineModuleBackendLocalProcess(); m_ModuleManager = new ctkCmdLineModuleManager(m_ValidationMode, m_TemporaryDirectoryName); // Set the main object, the ctkCmdLineModuleManager onto all the objects that need it. m_Controls->m_ComboBox->SetManager(m_ModuleManager); m_DirectoryWatcher = new ctkCmdLineModuleDirectoryWatcher(m_ModuleManager); + connect(this->m_DirectoryWatcher, SIGNAL(errorDetected(QString)), this, SLOT(OnDirectoryWatcherErrorsDetected(QString))); m_ModuleManager->registerBackend(m_ModuleBackend); // Setup the remaining preferences. this->RetrieveAndStorePreferenceValues(); // Connect signals to slots after we have set up GUI. connect(this->m_Controls->m_RunButton, SIGNAL(pressed()), this, SLOT(OnRunButtonPressed())); connect(this->m_Controls->m_RestoreDefaults, SIGNAL(pressed()), this, SLOT(OnRestoreButtonPressed())); connect(this->m_Controls->m_ComboBox, SIGNAL(actionChanged(QAction*)), this, SLOT(OnActionChanged(QAction*))); connect(this->m_Controls->m_TabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(OnTabCloseRequested(int))); + connect(this->m_Controls->m_ClearXMLCache, SIGNAL(pressed()), this, SLOT(OnClearCache())); + connect(this->m_Controls->m_ReloadModules, SIGNAL(pressed()), this, SLOT(OnReloadModules())); this->UpdateRunButtonEnabledStatus(); } } //----------------------------------------------------------------------------- berry::IBerryPreferences::Pointer CommandLineModulesView::RetrievePreferences() { berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry() .GetServiceById(berry::IPreferencesService::ID); assert( prefService ); std::string id = "/" + CommandLineModulesViewConstants::VIEW_ID; berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node(id)) .Cast(); assert( prefs ); return prefs; } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStoreTemporaryDirectoryPreferenceValues() { berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); QString fallbackTmpDir = QDir::tempPath(); m_TemporaryDirectoryName = QString::fromStdString( prefs->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir.toStdString())); } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStoreValidationMode() { berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); int value = prefs->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 0); if (value == 0) { m_ValidationMode = ctkCmdLineModuleManager::STRICT_VALIDATION; } else if (value == 1) { m_ValidationMode = ctkCmdLineModuleManager::SKIP_VALIDATION; } else { m_ValidationMode = ctkCmdLineModuleManager::WEAK_VALIDATION; } } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStorePreferenceValues() { berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); QString fallbackHomeDir = QDir::homePath(); m_OutputDirectoryName = QString::fromStdString( prefs->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackHomeDir.toStdString())); m_MaximumConcurrentProcesses = prefs->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4); + m_XmlTimeoutSeconds = prefs->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30); + m_ModuleManager->setTimeOutForXMLRetrieval(m_XmlTimeoutSeconds * 1000); // preference is in seconds, underlying CTK library in milliseconds. + // Get the flag for debug output, useful when parsing all the XML. m_DebugOutput = prefs->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false); m_DirectoryWatcher->setDebug(m_DebugOutput); + // Show/Hide the advanced widgets + this->m_Controls->SetAdvancedWidgetsVisible(prefs->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); + bool loadApplicationDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false); bool loadApplicationDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true); bool loadHomeDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false); bool loadHomeDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false); bool loadCurrentDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false); bool loadCurrentDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false); bool loadAutoLoadDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false); // Get some default application paths. // Here we can use the preferences to set up the builder, ctkCmdLineModuleDefaultPathBuilder builder; if (loadApplicationDir) builder.addApplicationDir(); if (loadApplicationDirCliModules) builder.addApplicationDir("cli-modules"); if (loadHomeDir) builder.addHomeDir(); if (loadHomeDirCliModules) builder.addHomeDir("cli-modules"); if (loadCurrentDir) builder.addCurrentDir(); if (loadCurrentDirCliModules) builder.addCurrentDir("cli-modules"); if (loadAutoLoadDir) builder.addCtkModuleLoadPath(); // and then we ask the builder to set up the paths. QStringList defaultPaths = builder.getDirectoryList(); // We get additional directory paths from preferences. QString pathString = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); QStringList additionalPaths = pathString.split(";", QString::SkipEmptyParts); // Combine the sets of directory paths. QStringList totalPaths; totalPaths << defaultPaths; totalPaths << additionalPaths; QString additionalModulesString = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); QStringList additionalModules = additionalModulesString.split(";", QString::SkipEmptyParts); // OnPreferencesChanged can be called for each preference in a dialog box, so // when you hit "OK", it is called repeatedly, whereas we want to only call these only once. - if (this->m_DirectoryWatcher->directories() != totalPaths) + if (m_DirectoryPaths != totalPaths) { + m_DirectoryPaths = totalPaths; m_DirectoryWatcher->setDirectories(totalPaths); } - if (this->m_DirectoryWatcher->additionalModules() != additionalModules) + if (m_ModulePaths != additionalModules) { + m_ModulePaths = additionalModules; m_DirectoryWatcher->setAdditionalModules(additionalModules); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnPreferencesChanged(const berry::IBerryPreferences* /*prefs*/) { this->RetrieveAndStoreTemporaryDirectoryPreferenceValues(); this->RetrieveAndStoreValidationMode(); this->RetrieveAndStorePreferenceValues(); } //----------------------------------------------------------------------------- ctkCmdLineModuleReference CommandLineModulesView::GetReferenceByFullName(QString fullName) { ctkCmdLineModuleReference result; QList references = this->m_ModuleManager->moduleReferences(); ctkCmdLineModuleReference ref; foreach(ref, references) { QString name = ref.description().categoryDotTitle(); if (name == fullName) { result = ref; } } return result; } //----------------------------------------------------------------------------- void CommandLineModulesView::OnActionChanged(QAction* action) { QString fullName = action->objectName(); ctkCmdLineModuleReference ref = this->GetReferenceByFullName(fullName); // ref should never be invalid, as the menu was generated from each ctkCmdLineModuleReference. // But just to be sure ... if invalid, don't do anything. if (ref) { // Check if we already have the reference. int tabIndex = -1; for (int i = 0; i < m_ListOfModules.size(); i++) { ctkCmdLineModuleReference tabsReference = m_ListOfModules[i]->moduleReference(); if (ref.location() == tabsReference.location()) { tabIndex = i; break; } } // i.e. we found a matching tab, so just switch to it. if (tabIndex != -1) { m_Controls->m_TabWidget->setCurrentIndex(tabIndex); } else // i.e. we did not find a matching tab { // In this case, we need to create a new tab, and give // it a GUI for the user to setup the parameters with. QmitkCmdLineModuleFactoryGui factory(this->GetDataStorage()); ctkCmdLineModuleFrontend *frontEnd = factory.create(ref); QmitkCmdLineModuleGui *theGui = dynamic_cast(frontEnd); // Add to list and tab wigdget m_ListOfModules.push_back(frontEnd); int tabIndex = m_Controls->m_TabWidget->addTab(theGui->getGui(), ref.description().title()); m_Controls->m_TabWidget->setTabToolTip(tabIndex, ref.description().title() + ":" + ref.xmlValidationErrorString()); // Here lies a small caveat. // // The XML may specify a default output file name. // However, this will probably have no file path, so we should probably add one. // Otherwise you will likely be trying to write in the application installation folder // eg. C:/Program Files (Windows) or /Applications/ (Mac) // // Also, we may find that 3rd party apps crash when they can't write. // So lets plan for the worst and hope for the best :-) QString parameterName; QList parameters; parameters = frontEnd->parameters("image", ctkCmdLineModuleFrontend::Output); parameters << frontEnd->parameters("file", ctkCmdLineModuleFrontend::Output); parameters << frontEnd->parameters("geometry", ctkCmdLineModuleFrontend::Output); foreach (ctkCmdLineModuleParameter parameter, parameters) { parameterName = parameter.name(); QString outputFileName = frontEnd->value(parameterName, ctkCmdLineModuleFrontend::DisplayRole).toString(); QFileInfo outputFileInfo(outputFileName); if (outputFileInfo.absoluteFilePath() != outputFileName) { QDir defaultOutputDir(m_OutputDirectoryName); QFileInfo replacementFileInfo(defaultOutputDir, outputFileName); frontEnd->setValue(parameterName, replacementFileInfo.absoluteFilePath(), ctkCmdLineModuleFrontend::DisplayRole); } } } } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnTabCloseRequested(int tabNumber) { ctkCmdLineModuleFrontend *frontEnd = m_ListOfModules[tabNumber]; m_Controls->m_TabWidget->removeTab(tabNumber); m_ListOfModules.removeAt(tabNumber); delete frontEnd; } //----------------------------------------------------------------------------- void CommandLineModulesView::AskUserToSelectAModule() const { QMessageBox msgBox; msgBox.setText("Please select a module!"); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnRestoreButtonPressed() { int tabNumber = m_Controls->m_TabWidget->currentIndex(); if (tabNumber >= 0) { ctkCmdLineModuleFrontend *frontEnd = m_ListOfModules[tabNumber]; frontEnd->resetValues(); } else { this->AskUserToSelectAModule(); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnRunButtonPressed() { int tabNumber = m_Controls->m_TabWidget->currentIndex(); if (tabNumber >= 0) { // 1. Create a new QmitkCmdLineModuleProgressWidget to represent the running widget. QmitkCmdLineModuleProgressWidget *widget = new QmitkCmdLineModuleProgressWidget(m_Controls->m_RunningWidgets); widget->SetDataStorage(this->GetDataStorage()); widget->SetManager(m_ModuleManager); widget->SetTemporaryDirectory(m_TemporaryDirectoryName); widget->SetOutputDirectory(m_OutputDirectoryName); // 2. Create a new front end. QmitkCmdLineModuleFactoryGui factory(this->GetDataStorage()); ctkCmdLineModuleFrontend *frontEndOnCurrentTab = m_ListOfModules[tabNumber]; QmitkCmdLineModuleGui *frontEndGuiOnCurrentTab = dynamic_cast(frontEndOnCurrentTab); ctkCmdLineModuleReference currentTabFrontendReferences = frontEndGuiOnCurrentTab->moduleReference(); ctkCmdLineModuleFrontend *newFrontEnd = factory.create(currentTabFrontendReferences); QmitkCmdLineModuleGui *newFrontEndGui = dynamic_cast(newFrontEnd); widget->SetFrontend(newFrontEndGui); m_Layout->insertWidget(0, widget); // 3. Copy parameters. This MUST come after widget->SetFrontEnd newFrontEndGui->copyParameters(*frontEndGuiOnCurrentTab); newFrontEndGui->setParameterContainerEnabled(false); // 4. Connect widget signals to here, to count how many jobs running. connect(widget, SIGNAL(started()), this, SLOT(OnJobStarted())); connect(widget, SIGNAL(finished()), this, SLOT(OnJobFinished())); // 5. GO. widget->Run(); } else { this->AskUserToSelectAModule(); } } //----------------------------------------------------------------------------- void CommandLineModulesView::UpdateRunButtonEnabledStatus() { if (m_CurrentlyRunningProcesses >= m_MaximumConcurrentProcesses) { m_Controls->m_RunButton->setEnabled(false); } else { m_Controls->m_RunButton->setEnabled(true); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnJobStarted() { m_CurrentlyRunningProcesses++; this->UpdateRunButtonEnabledStatus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnJobFinished() { m_CurrentlyRunningProcesses--; this->UpdateRunButtonEnabledStatus(); } + + +//----------------------------------------------------------------------------- +void CommandLineModulesView::OnDirectoryWatcherErrorsDetected(const QString& errorMsg) +{ + ctkCmdLineModuleUtils::messageBoxForModuleRegistration(errorMsg); +} + + +//----------------------------------------------------------------------------- +void CommandLineModulesView::OnClearCache() +{ + if (this->m_DebugOutput) + { + qDebug() << "CommandLineModulesView::OnClearCache(): starting"; + } + + m_ModuleManager->clearCache(); + + if (this->m_DebugOutput) + { + qDebug() << "CommandLineModulesView::OnClearCache(): finishing"; + } +} + + +//----------------------------------------------------------------------------- +void CommandLineModulesView::OnReloadModules() +{ + QList urls; + + QList moduleRefs = m_ModuleManager->moduleReferences(); + foreach (ctkCmdLineModuleReference ref, moduleRefs) + { + urls.push_back(ref.location()); + } + + if (this->m_DebugOutput) + { + qDebug() << "CommandLineModulesView::OnReloadModules(): unloading:" << urls; + } + + foreach (ctkCmdLineModuleReference ref, moduleRefs) + { + m_ModuleManager->unregisterModule(ref); + } + + if (this->m_DebugOutput) + { + qDebug() << "CommandLineModulesView::OnReloadModules(): reloading."; + } + + QList refResults = QtConcurrent::blockingMapped(urls, + ctkCmdLineModuleConcurrentRegister(m_ModuleManager, m_DebugOutput)); + + if (this->m_DebugOutput) + { + qDebug() << "CommandLineModulesView::OnReloadModules(): finished."; + } + + QString errorMessages = ctkCmdLineModuleUtils::errorMessagesFromModuleRegistration(refResults, + m_ModuleManager->validationMode()); + ctkCmdLineModuleUtils::messageBoxForModuleRegistration(errorMessages); +} + diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h index e42b2b5ed2..a626d0abb7 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.h @@ -1,225 +1,255 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 CommandLineModulesView_h #define CommandLineModulesView_h #include #include #include #include #include #include #include class ctkCmdLineModuleBackendLocalProcess; class ctkCmdLineModuleDirectoryWatcher; class CommandLineModulesViewControls; class QmitkCmdLineModuleProgressWidget; class QAction; class QVBoxLayout; namespace berry { struct IBerryPreferences; } /*! * \class CommandLineModulesView * \brief Provides basic GUI interface to the CTK command line modules. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal * \sa QmitkAbstractView */ class CommandLineModulesView : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: CommandLineModulesView(); virtual ~CommandLineModulesView(); /** * \brief Main method, called by framework to create the GUI at the right time. * \param parent The parent QWidget, as this class itself is not a QWidget subclass. */ virtual void CreateQtPartControl(QWidget *parent); /** * \brief Called by the framework to indicate that the preferences have changed. * \param prefs not used, as we call RetrievePreferenceValues(). */ void OnPreferencesChanged(const berry::IBerryPreferences* prefs); protected Q_SLOTS: /** * \brief Called when the ctkMenuComboBox has the menu selection changed, * and causes the corresponding GUI to be displayed. */ void OnActionChanged(QAction*); /** * \brief Slot that is called when the restore defaults button is pressed, * to reset the current GUI form to the default values, if the XML specifies defaults. */ void OnRestoreButtonPressed(); /** * \brief Slot that is called when the Run button is pressed to run the current module. */ void OnRunButtonPressed(); + /** + * \brief Alerts the user of any errors comming out of the directory watcher. + */ + void OnDirectoryWatcherErrorsDetected(const QString&); + protected: /** * \brief Called by framework to set the focus on the right widget * when this view has focus, so currently, thats the ctkMenuCombo box. */ virtual void SetFocus(); private slots: /** * \brief Called when the user clicks to close a tab, and removes the front end from m_ListOfModules */ void OnTabCloseRequested(int tabNumber); /** * \brief Called from QmitkCmdLineModuleProgressWidget to indicate a job has started. */ void OnJobStarted(); /** * \brief Called from QmitkCmdLineModuleProgressWidget to indicate a job has finished. */ void OnJobFinished(); + /** + * \brief Called when the user hits the 'clear XML cache' button. + */ + void OnClearCache(); + + /** + * \brief Called when the user hits the 'reload modules' button. + */ + void OnReloadModules(); + private: /** * \brief Called on startup and by OnPreferencesChanged to load all * preferences except the temporary folder into member variables. */ void RetrieveAndStorePreferenceValues(); /** * \brief Called on startup and by OnPreferencesChanged to load the temporary folder * preference into member variable m_TemporaryDirectoryName. */ void RetrieveAndStoreTemporaryDirectoryPreferenceValues(); /** * \brief Called on startup and by OnPreferencesChanged to set the validation mode, but will require a restart. */ void RetrieveAndStoreValidationMode(); /** * \brief Called to get hold of the actual preferences node. */ berry::IBerryPreferences::Pointer RetrievePreferences(); /** * \brief Search all modules for the one matching the given identifier. * \param fullName The "fullName" is the . from the XML. * \return ctkCmdLineModuleReference the reference corresponding to the fullName, or an invalid reference if non found. */ ctkCmdLineModuleReference GetReferenceByFullName(QString fullName); /** * \brief Raises a message box asking the user to select a module first. */ void AskUserToSelectAModule() const; /** * \brief Enables or Disables the Run Button. */ void UpdateRunButtonEnabledStatus(); /** * \brief The GUI controls contain a reset and run button, and a QWidget container, and the GUI component * for each command line module is added to the QWidget dynamically at run time. */ CommandLineModulesViewControls *m_Controls; /** * \brief We store the parent, passed in via CommandLineModulesView::CreateQtPartControl, * as this class itself is not a QWidget. */ QWidget *m_Parent; /** * \brief We keep a local layout, and arrange a display of QmitkCmdLineModuleProgressWidget, * where each QmitkCmdLineModuleProgressWidget represents a single running job. */ QVBoxLayout *m_Layout; /** * \brief The manager is responsible for loading and instantiating command line modules. */ ctkCmdLineModuleManager *m_ModuleManager; /** * \brief We are using a back-end that runs locally installed command line programs. */ ctkCmdLineModuleBackendLocalProcess *m_ModuleBackend; /** * \brief The ctkCmdLineModuleDirectoryWatcher maintains the list of directories * we are using to load modules, to provide automatic updates. */ ctkCmdLineModuleDirectoryWatcher *m_DirectoryWatcher; /** * \brief We store a temporary folder name, accessible via user preferences. */ QString m_TemporaryDirectoryName; /** * \brief We store an output folder name, accessible via user preferences for when * the file specified in a default output path is not within a writable directory. */ QString m_OutputDirectoryName; + /** + * \brief Cache the list of directory paths locally to avoid repeatedly trying to update Directory Watcher. + */ + QStringList m_DirectoryPaths; + + /** + * \brief Cache the list of module/executable paths locally to avoid repeatedly trying to update Directory Watcher. + */ + QStringList m_ModulePaths; + /** * \brief We store the validation mode, accessisble via user preferences. */ ctkCmdLineModuleManager::ValidationMode m_ValidationMode; /** * \brief We store the maximum number of concurrent processes, and disable the run button accordingly. */ int m_MaximumConcurrentProcesses; /** * \brief Counts the number of currently running processes. */ int m_CurrentlyRunningProcesses; /** * \brief Member variable, taken from preference page. */ bool m_DebugOutput; + /** + * \brief Member variable, taken from preferences page. + */ + int m_XmlTimeoutSeconds; + /** * \brief We keep a list of front ends to match the m_TabWidget. */ QList<ctkCmdLineModuleFrontend*> m_ListOfModules; }; #endif // CommandLineModulesView_h diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp index cf09729d0d..784083245c 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp @@ -1,32 +1,34 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 "CommandLineModulesViewConstants.h" const std::string CommandLineModulesViewConstants::VIEW_ID = "org.mitk.gui.qt.cmdlinemodules"; const std::string CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME = "temporary directory"; const std::string CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME = "output directory"; const std::string CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME = "module directories"; const std::string CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME = "module files"; const std::string CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME = "debug output"; const std::string CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR = "load from application dir"; const std::string CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR = "load from home dir"; const std::string CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR = "load from current dir"; const std::string CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR = "load from auto-load dir"; const std::string CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES = "load from application dir/cli-modules"; const std::string CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES = "load from home dir/cli-modules"; const std::string CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES = "load from current dir/cli-modules"; const std::string CommandLineModulesViewConstants::XML_VALIDATION_MODE = "xml validation mode"; +const std::string CommandLineModulesViewConstants::XML_TIMEOUT_SECS = "xml time-out"; const std::string CommandLineModulesViewConstants::MAX_CONCURRENT = "max concurrent processes"; +const std::string CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME = "show advanced widgets"; diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h index 33173679f0..2e2595b05f 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h @@ -1,115 +1,125 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 CommandLineModulesViewConstants_h #define CommandLineModulesViewConstants_h #include <QString> #include <string> /** * \class CommandLineModulesViewConstants * \brief Structure to define a namespace for constants used privately within this view. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ struct CommandLineModulesViewConstants { /** * \brief The name of the preferences node containing the temporary directory. */ static const std::string TEMPORARY_DIRECTORY_NODE_NAME; /** * \brief The name of the preferences node containing the output directory. */ static const std::string OUTPUT_DIRECTORY_NODE_NAME; /** * \brief The name of the preferences node containing the list of directories to scan. */ static const std::string MODULE_DIRECTORIES_NODE_NAME; /** * \brief The name of the preferences node containing the additional files to add to the module list. */ static const std::string MODULE_FILES_NODE_NAME; /** * \brief The name of the preferences node containing whether we are producing debug output. */ static const std::string DEBUG_OUTPUT_NODE_NAME; + /** + * \brief The name of the preferences node containing whether we are displaying advanced widgets. + */ + static const std::string SHOW_ADVANCED_WIDGETS_NAME; + /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the application directory. */ static const std::string LOAD_FROM_APPLICATION_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the "application directory/cli-modules". */ static const std::string LOAD_FROM_APPLICATION_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the users home directory. */ static const std::string LOAD_FROM_HOME_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the users "home directory/cli-modules". */ static const std::string LOAD_FROM_HOME_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the applications current working directory. */ static const std::string LOAD_FROM_CURRENT_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the applications "current working directory/cli-modules". */ static const std::string LOAD_FROM_CURRENT_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the directory specified in CTK_MODULE_LOAD_PATH. */ static const std::string LOAD_FROM_AUTO_LOAD_DIR; /** * \brief The name of the preferences node containing the validation mode. */ static const std::string XML_VALIDATION_MODE; + /** + * \brief The name of the preferences node containing the timeout in seconds for XML retrieval. + */ + static const std::string XML_TIMEOUT_SECS; + /** * \brief The name of the preferences node containing the maximum number of concurrent processes. */ static const std::string MAX_CONCURRENT; /** * \brief The View ID = org.mitk.gui.qt.cmdlinemodules, and should match that in plugin.xml. */ static const std::string VIEW_ID; }; #endif // CommandLineModulesViewConstants_h diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.cpp index ab5b38717d..3055c4d660 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.cpp @@ -1,36 +1,45 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 "CommandLineModulesViewControls.h" #include <QIcon> #include <QSize> #include <QHBoxLayout> //----------------------------------------------------------------------------- CommandLineModulesViewControls::CommandLineModulesViewControls(QWidget *parent) { this->setupUi(parent); this->m_ChooseLabel->setVisible(false); this->m_ComboBox->setToolTip("Choose a command line module"); this->m_RunButton->setIcon(QIcon(":/CommandLineModulesResources/run.png")); this->m_RestoreDefaults->setIcon(QIcon(":/CommandLineModulesResources/undo.png")); } //----------------------------------------------------------------------------- CommandLineModulesViewControls::~CommandLineModulesViewControls() { } + + +//----------------------------------------------------------------------------- +void CommandLineModulesViewControls::SetAdvancedWidgetsVisible(const bool& isVisible) +{ + this->m_ClearXMLCache->setVisible(isVisible); + this->m_ReloadModules->setVisible(isVisible); +} + diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.h index c3fa6227a7..549c09f2ad 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.h @@ -1,45 +1,47 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). 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 CommandLineModulesViewControls_h #define CommandLineModulesViewControls_h #include "ui_CommandLineModulesViewControls.h" class QHBoxLayout; /** * \class CommandLineModulesViewControls * \brief Class derived from Ui_CommandLineModulesViewControls to provide access to GUI widgets. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ class CommandLineModulesViewControls : public QWidget, public Ui_CommandLineModulesViewControls { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: CommandLineModulesViewControls(QWidget *parent = 0); virtual ~CommandLineModulesViewControls(); + void SetAdvancedWidgetsVisible(const bool& isVisible); + protected: private: }; #endif // CommandLineModulesViewControls_h diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.ui b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.ui index 7d34e94cfd..aaf96fcc0f 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.ui +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewControls.ui @@ -1,139 +1,172 @@ <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CommandLineModulesViewControls</class> <widget class="QWidget" name="CommandLineModulesViewControls"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>678</width> <height>582</height> </rect> </property> <property name="minimumSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="windowTitle"> <string>QmitkTemplate</string> </property> - <layout class="QVBoxLayout" name="verticalLayout"> + <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> - <layout class="QHBoxLayout" name="m_HorizontalLayout"> + <layout class="QVBoxLayout" name="verticalLayout"> <item> - <widget class="QLabel" name="m_ChooseLabel"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="toolTip"> - <string/> - </property> - <property name="text"> - <string>choose:</string> - </property> - </widget> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QLabel" name="m_ChooseLabel"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string/> + </property> + <property name="text"> + <string>choose:</string> + </property> + </widget> + </item> + <item> + <widget class="QmitkCmdLineModuleMenuComboBox" name="m_ComboBox" native="true"/> + </item> + <item> + <widget class="QPushButton" name="m_RestoreDefaults"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string>restore default parameters</string> + </property> + <property name="text"> + <string/> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="m_RunButton"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="toolTip"> + <string>run the command line module</string> + </property> + <property name="text"> + <string/> + </property> + </widget> + </item> + <item> + <spacer name="m_HorizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> </item> <item> - <widget class="QmitkCmdLineModuleMenuComboBox" name="m_ComboBox" native="true"/> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QPushButton" name="m_ClearXMLCache"> + <property name="text"> + <string>clear XML cache</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="m_ReloadModules"> + <property name="text"> + <string>reload modules</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> </item> <item> - <widget class="QPushButton" name="m_RestoreDefaults"> + <widget class="QWidget" name="m_RunningWidgets" native="true"> <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="toolTip"> - <string>restore default parameters</string> - </property> - <property name="text"> - <string/> - </property> </widget> </item> <item> - <widget class="QPushButton" name="m_RunButton"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> + <widget class="QTabWidget" name="m_TabWidget"> + <property name="currentIndex"> + <number>-1</number> </property> - <property name="toolTip"> - <string>run the command line module</string> - </property> - <property name="text"> - <string/> + <property name="tabsClosable"> + <bool>true</bool> </property> </widget> </item> <item> - <spacer name="m_HorizontalSpacer"> + <spacer name="verticalSpacer"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Vertical</enum> </property> <property name="sizeHint" stdset="0"> <size> - <width>40</width> - <height>20</height> + <width>20</width> + <height>250</height> </size> </property> </spacer> </item> </layout> </item> - <item> - <widget class="QTabWidget" name="m_TabWidget"> - <property name="currentIndex"> - <number>-1</number> - </property> - <property name="tabsClosable"> - <bool>true</bool> - </property> - </widget> - </item> - <item> - <widget class="QWidget" name="m_RunningWidgets" native="true"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - </widget> - </item> - <item> - <spacer name="verticalSpacer"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>250</height> - </size> - </property> - </spacer> - </item> </layout> </widget> <layoutdefault spacing="6" margin="11"/> <customwidgets> <customwidget> <class>QmitkCmdLineModuleMenuComboBox</class> <extends>QWidget</extends> <header>QmitkCmdLineModuleMenuComboBox.h</header> <container>1</container> </customwidget> </customwidgets> - <resources> - <include location="../../resources/CommandLineModulesResources.qrc"/> - </resources> + <resources/> <connections/> </ui> diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp index 7323e6bd1f..a6d8075ce2 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp @@ -1,2344 +1,2349 @@ /*=================================================================== 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 <math.h> // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "QmitkFiberfoxView.h" // MITK #include <mitkImage.h> #include <mitkDiffusionImage.h> #include <mitkImageToItk.h> #include <mitkImageCast.h> #include <mitkProperties.h> #include <mitkPlanarFigureInteractor.h> #include <mitkDataStorage.h> #include <itkFibersFromPlanarFiguresFilter.h> #include <itkTractsToDWIImageFilter.h> #include <mitkTensorImage.h> #include <mitkILinkedRenderWindowPart.h> #include <mitkGlobalInteraction.h> #include <mitkImageToItk.h> #include <mitkImageCast.h> #include <mitkImageGenerator.h> #include <mitkNodePredicateDataType.h> #include <itkScalableAffineTransform.h> #include <mitkLevelWindowProperty.h> #include <mitkNodePredicateOr.h> #include <mitkNodePredicateAnd.h> #include <mitkNodePredicateNot.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/foreach.hpp> #include <QFileDialog> #include <QMessageBox> #include "usModuleRegistry.h" #include <mitkChiSquareNoiseModel.h> #include <itksys/SystemTools.hxx> #include <mitkIOUtil.h> #include <QScrollBar> #include <itkInvertIntensityImageFilter.h> #include <QDialogButtonBox> #define _USE_MATH_DEFINES #include <math.h> QmitkFiberfoxWorker::QmitkFiberfoxWorker(QmitkFiberfoxView* view) : m_View(view) { } void QmitkFiberfoxWorker::run() { try{ switch (m_FilterType) { case 0: m_View->m_TractsToDwiFilter->Update(); break; case 1: m_View->m_ArtifactsToDwiFilter->Update(); break; } } catch( ... ) { } m_View->m_Thread.quit(); } const std::string QmitkFiberfoxView::VIEW_ID = "org.mitk.views.fiberfoxview"; QmitkFiberfoxView::QmitkFiberfoxView() : QmitkAbstractView() , m_Controls( 0 ) , m_SelectedImage( NULL ) , m_Worker(this) , m_ThreadIsRunning(false) { m_Worker.moveToThread(&m_Thread); connect(&m_Thread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_Thread, SIGNAL(started()), &m_Worker, SLOT(run())); connect(&m_Thread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_Thread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_SimulationTimer = new QTimer(this); } void QmitkFiberfoxView::KillThread() { MITK_INFO << "Aborting DWI simulation."; switch (m_Worker.m_FilterType) { case 0: m_TractsToDwiFilter->SetAbortGenerateData(true); break; case 1: m_ArtifactsToDwiFilter->SetAbortGenerateData(true); break; } m_Controls->m_AbortSimulationButton->setEnabled(false); m_Controls->m_AbortSimulationButton->setText("Aborting simulation ..."); } void QmitkFiberfoxView::BeforeThread() { m_SimulationTime = QTime::currentTime(); m_SimulationTimer->start(100); m_Controls->m_AbortSimulationButton->setVisible(true); m_Controls->m_GenerateImageButton->setVisible(false); m_Controls->m_SimulationStatusText->setVisible(true); m_ThreadIsRunning = true; } void QmitkFiberfoxView::AfterThread() { UpdateSimulationStatus(); m_SimulationTimer->stop(); m_Controls->m_AbortSimulationButton->setVisible(false); m_Controls->m_AbortSimulationButton->setEnabled(true); m_Controls->m_AbortSimulationButton->setText("Abort simulation"); m_Controls->m_GenerateImageButton->setVisible(true); m_ThreadIsRunning = false; QString statusText; FiberfoxParameters<double> parameters; mitk::DiffusionImage<short>::Pointer mitkImage = mitk::DiffusionImage<short>::New(); switch (m_Worker.m_FilterType) { case 0: { statusText = QString(m_TractsToDwiFilter->GetStatusText().c_str()); if (m_TractsToDwiFilter->GetAbortGenerateData()) { MITK_INFO << "Simulation aborted."; return; } parameters = m_TractsToDwiFilter->GetParameters(); mitkImage->SetVectorImage( m_TractsToDwiFilter->GetOutput() ); mitkImage->SetReferenceBValue(parameters.m_Bvalue); mitkImage->SetDirections(parameters.GetGradientDirections()); mitkImage->InitializeFromVectorImage(); parameters.m_ResultNode->SetData( mitkImage ); parameters.m_ResultNode->SetName(parameters.m_ParentNode->GetName() +"_D"+QString::number(parameters.m_ImageRegion.GetSize(0)).toStdString() +"-"+QString::number(parameters.m_ImageRegion.GetSize(1)).toStdString() +"-"+QString::number(parameters.m_ImageRegion.GetSize(2)).toStdString() +"_S"+QString::number(parameters.m_ImageSpacing[0]).toStdString() +"-"+QString::number(parameters.m_ImageSpacing[1]).toStdString() +"-"+QString::number(parameters.m_ImageSpacing[2]).toStdString() +"_b"+QString::number(parameters.m_Bvalue).toStdString() +"_"+parameters.m_SignalModelString +parameters.m_ArtifactModelString); GetDataStorage()->Add(parameters.m_ResultNode, parameters.m_ParentNode); parameters.m_ResultNode->SetProperty( "levelwindow", mitk::LevelWindowProperty::New(m_TractsToDwiFilter->GetLevelWindow()) ); if (m_Controls->m_VolumeFractionsBox->isChecked()) { std::vector< itk::TractsToDWIImageFilter< short >::ItkDoubleImgType::Pointer > volumeFractions = m_TractsToDwiFilter->GetVolumeFractions(); for (unsigned int k=0; k<volumeFractions.size(); k++) { mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(volumeFractions.at(k).GetPointer()); image->SetVolume(volumeFractions.at(k)->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName(parameters.m_ParentNode->GetName()+"_CompartmentVolume-"+QString::number(k).toStdString()); GetDataStorage()->Add(node, parameters.m_ParentNode); } } m_TractsToDwiFilter = NULL; break; } case 1: { statusText = QString(m_ArtifactsToDwiFilter->GetStatusText().c_str()); if (m_ArtifactsToDwiFilter->GetAbortGenerateData()) { MITK_INFO << "Simulation aborted."; return; } parameters = m_ArtifactsToDwiFilter->GetParameters().CopyParameters<double>(); mitk::DiffusionImage<short>::Pointer diffImg = dynamic_cast<mitk::DiffusionImage<short>*>(parameters.m_ParentNode->GetData()); mitkImage = mitk::DiffusionImage<short>::New(); mitkImage->SetVectorImage( m_ArtifactsToDwiFilter->GetOutput() ); mitkImage->SetReferenceBValue(diffImg->GetReferenceBValue()); mitkImage->SetDirections(diffImg->GetDirections()); mitkImage->InitializeFromVectorImage(); parameters.m_ResultNode->SetData( mitkImage ); parameters.m_ResultNode->SetName(parameters.m_ParentNode->GetName()+parameters.m_ArtifactModelString); GetDataStorage()->Add(parameters.m_ResultNode, parameters.m_ParentNode); m_ArtifactsToDwiFilter = NULL; break; } } mitk::BaseData::Pointer basedata = parameters.m_ResultNode->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if (!parameters.m_OutputPath.empty()) { try{ QString outputFileName(parameters.m_OutputPath.c_str()); outputFileName += parameters.m_ResultNode->GetName().c_str(); outputFileName.replace(QString("."), QString("_")); outputFileName += ".dwi"; QString status("Saving output image to "); status += outputFileName; m_Controls->m_SimulationStatusText->append(status); mitk::IOUtil::SaveBaseData(mitkImage, outputFileName.toStdString()); m_Controls->m_SimulationStatusText->append("File saved successfully."); } catch (itk::ExceptionObject &e) { QString status("Exception during DWI writing: "); status += e.GetDescription(); m_Controls->m_SimulationStatusText->append(status); } catch (...) { m_Controls->m_SimulationStatusText->append("Unknown exception during DWI writing!"); } } parameters.m_FrequencyMap = NULL; } void QmitkFiberfoxView::UpdateSimulationStatus() { QString statusText; switch (m_Worker.m_FilterType) { case 0: statusText = QString(m_TractsToDwiFilter->GetStatusText().c_str()); break; case 1: statusText = QString(m_ArtifactsToDwiFilter->GetStatusText().c_str()); break; } if (QString::compare(m_SimulationStatusText,statusText)!=0) { m_Controls->m_SimulationStatusText->clear(); statusText = "<pre>"+statusText+"</pre>"; m_Controls->m_SimulationStatusText->setText(statusText); QScrollBar *vScrollBar = m_Controls->m_SimulationStatusText->verticalScrollBar(); vScrollBar->triggerAction(QScrollBar::SliderToMaximum); } } // Destructor QmitkFiberfoxView::~QmitkFiberfoxView() { delete m_SimulationTimer; } void QmitkFiberfoxView::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::QmitkFiberfoxViewControls; m_Controls->setupUi( parent ); m_Controls->m_StickWidget1->setVisible(true); m_Controls->m_StickWidget2->setVisible(false); m_Controls->m_ZeppelinWidget1->setVisible(false); m_Controls->m_ZeppelinWidget2->setVisible(false); m_Controls->m_TensorWidget1->setVisible(false); m_Controls->m_TensorWidget2->setVisible(false); m_Controls->m_BallWidget1->setVisible(true); m_Controls->m_BallWidget2->setVisible(false); m_Controls->m_AstrosticksWidget1->setVisible(false); m_Controls->m_AstrosticksWidget2->setVisible(false); m_Controls->m_DotWidget1->setVisible(false); m_Controls->m_DotWidget2->setVisible(false); m_Controls->m_Comp4FractionFrame->setVisible(false); m_Controls->m_DiffusionPropsMessage->setVisible(false); m_Controls->m_GeometryMessage->setVisible(false); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(false); m_Controls->m_AdvancedFiberOptionsFrame->setVisible(false); m_Controls->m_VarianceBox->setVisible(false); m_Controls->m_NoiseFrame->setVisible(false); m_Controls->m_GhostFrame->setVisible(false); m_Controls->m_DistortionsFrame->setVisible(false); m_Controls->m_EddyFrame->setVisible(false); m_Controls->m_SpikeFrame->setVisible(false); m_Controls->m_AliasingFrame->setVisible(false); m_Controls->m_MotionArtifactFrame->setVisible(false); m_ParameterFile = QDir::currentPath()+"/param.ffp"; m_Controls->m_AbortSimulationButton->setVisible(false); m_Controls->m_SimulationStatusText->setVisible(false); m_Controls->m_FrequencyMapBox->SetDataStorage(this->GetDataStorage()); mitk::TNodePredicateDataType<mitk::Image>::Pointer isMitkImage = mitk::TNodePredicateDataType<mitk::Image>::New(); mitk::NodePredicateDataType::Pointer isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); mitk::NodePredicateDataType::Pointer isDti = mitk::NodePredicateDataType::New("TensorImage"); mitk::NodePredicateDataType::Pointer isQbi = mitk::NodePredicateDataType::New("QBallImage"); mitk::NodePredicateOr::Pointer isDiffusionImage = mitk::NodePredicateOr::New(isDwi, isDti); isDiffusionImage = mitk::NodePredicateOr::New(isDiffusionImage, isQbi); mitk::NodePredicateNot::Pointer noDiffusionImage = mitk::NodePredicateNot::New(isDiffusionImage); mitk::NodePredicateAnd::Pointer finalPredicate = mitk::NodePredicateAnd::New(isMitkImage, noDiffusionImage); m_Controls->m_FrequencyMapBox->SetPredicate(finalPredicate); m_Controls->m_Comp4VolumeFraction->SetDataStorage(this->GetDataStorage()); m_Controls->m_Comp4VolumeFraction->SetPredicate(finalPredicate); connect( m_SimulationTimer, SIGNAL(timeout()), this, SLOT(UpdateSimulationStatus()) ); connect((QObject*) m_Controls->m_AbortSimulationButton, SIGNAL(clicked()), (QObject*) this, SLOT(KillThread())); connect((QObject*) m_Controls->m_GenerateImageButton, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateImage())); connect((QObject*) m_Controls->m_GenerateFibersButton, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateFibers())); connect((QObject*) m_Controls->m_CircleButton, SIGNAL(clicked()), (QObject*) this, SLOT(OnDrawROI())); connect((QObject*) m_Controls->m_FlipButton, SIGNAL(clicked()), (QObject*) this, SLOT(OnFlipButton())); connect((QObject*) m_Controls->m_JoinBundlesButton, SIGNAL(clicked()), (QObject*) this, SLOT(JoinBundles())); connect((QObject*) m_Controls->m_VarianceBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnVarianceChanged(double))); connect((QObject*) m_Controls->m_DistributionBox, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(OnDistributionChanged(int))); connect((QObject*) m_Controls->m_FiberDensityBox, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(OnFiberDensityChanged(int))); connect((QObject*) m_Controls->m_FiberSamplingBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnFiberSamplingChanged(double))); connect((QObject*) m_Controls->m_TensionBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnTensionChanged(double))); connect((QObject*) m_Controls->m_ContinuityBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnContinuityChanged(double))); connect((QObject*) m_Controls->m_BiasBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnBiasChanged(double))); connect((QObject*) m_Controls->m_AddNoise, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddNoise(int))); connect((QObject*) m_Controls->m_AddGhosts, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddGhosts(int))); connect((QObject*) m_Controls->m_AddDistortions, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddDistortions(int))); connect((QObject*) m_Controls->m_AddEddy, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddEddy(int))); connect((QObject*) m_Controls->m_AddSpikes, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddSpikes(int))); connect((QObject*) m_Controls->m_AddAliasing, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddAliasing(int))); connect((QObject*) m_Controls->m_AddMotion, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddMotion(int))); connect((QObject*) m_Controls->m_ConstantRadiusBox, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnConstantRadius(int))); connect((QObject*) m_Controls->m_CopyBundlesButton, SIGNAL(clicked()), (QObject*) this, SLOT(CopyBundles())); connect((QObject*) m_Controls->m_TransformBundlesButton, SIGNAL(clicked()), (QObject*) this, SLOT(ApplyTransform())); connect((QObject*) m_Controls->m_AlignOnGrid, SIGNAL(clicked()), (QObject*) this, SLOT(AlignOnGrid())); connect((QObject*) m_Controls->m_Compartment1Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp1ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment2Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp2ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment3Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp3ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment4Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp4ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_AdvancedOptionsBox, SIGNAL( stateChanged(int)), (QObject*) this, SLOT(ShowAdvancedOptions(int))); connect((QObject*) m_Controls->m_AdvancedOptionsBox_2, SIGNAL( stateChanged(int)), (QObject*) this, SLOT(ShowAdvancedOptions(int))); connect((QObject*) m_Controls->m_SaveParametersButton, SIGNAL(clicked()), (QObject*) this, SLOT(SaveParameters())); connect((QObject*) m_Controls->m_LoadParametersButton, SIGNAL(clicked()), (QObject*) this, SLOT(LoadParameters())); connect((QObject*) m_Controls->m_OutputPathButton, SIGNAL(clicked()), (QObject*) this, SLOT(SetOutputPath())); } } template< class ScalarType > FiberfoxParameters< ScalarType > QmitkFiberfoxView::UpdateImageParameters() { FiberfoxParameters< ScalarType > parameters; parameters.m_OutputPath = ""; string outputPath = m_Controls->m_SavePathEdit->text().toStdString(); if (outputPath.compare("-")!=0) { parameters.m_OutputPath = outputPath; parameters.m_OutputPath += "/"; } if (m_MaskImageNode.IsNotNull()) { mitk::Image::Pointer mitkMaskImage = dynamic_cast<mitk::Image*>(m_MaskImageNode->GetData()); mitk::CastToItkImage<ItkUcharImgType>(mitkMaskImage, parameters.m_MaskImage); itk::ImageDuplicator<ItkUcharImgType>::Pointer duplicator = itk::ImageDuplicator<ItkUcharImgType>::New(); duplicator->SetInputImage(parameters.m_MaskImage); duplicator->Update(); parameters.m_MaskImage = duplicator->GetOutput(); } if (m_SelectedDWI.IsNotNull()) // use parameters of selected DWI { mitk::DiffusionImage<short>::Pointer dwi = dynamic_cast<mitk::DiffusionImage<short>*>(m_SelectedDWI->GetData()); parameters.m_ImageRegion = dwi->GetVectorImage()->GetLargestPossibleRegion(); parameters.m_ImageSpacing = dwi->GetVectorImage()->GetSpacing(); parameters.m_ImageOrigin = dwi->GetVectorImage()->GetOrigin(); parameters.m_ImageDirection = dwi->GetVectorImage()->GetDirection(); parameters.m_Bvalue = dwi->GetReferenceBValue(); parameters.SetGradienDirections(dwi->GetDirections()); } else if (m_SelectedImage.IsNotNull()) // use geometry of selected image { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(m_SelectedImage->GetData()); itk::Image< float, 3 >::Pointer itkImg = itk::Image< float, 3 >::New(); CastToItkImage< itk::Image< float, 3 > >(img, itkImg); parameters.m_ImageRegion = itkImg->GetLargestPossibleRegion(); parameters.m_ImageSpacing = itkImg->GetSpacing(); parameters.m_ImageOrigin = itkImg->GetOrigin(); parameters.m_ImageDirection = itkImg->GetDirection(); parameters.SetNumWeightedGradients(m_Controls->m_NumGradientsBox->value()); parameters.m_Bvalue = m_Controls->m_BvalueBox->value(); } else // use GUI parameters { parameters.m_ImageRegion.SetSize(0, m_Controls->m_SizeX->value()); parameters.m_ImageRegion.SetSize(1, m_Controls->m_SizeY->value()); parameters.m_ImageRegion.SetSize(2, m_Controls->m_SizeZ->value()); parameters.m_ImageSpacing[0] = m_Controls->m_SpacingX->value(); parameters.m_ImageSpacing[1] = m_Controls->m_SpacingY->value(); parameters.m_ImageSpacing[2] = m_Controls->m_SpacingZ->value(); parameters.m_ImageOrigin[0] = parameters.m_ImageSpacing[0]/2; parameters.m_ImageOrigin[1] = parameters.m_ImageSpacing[1]/2; parameters.m_ImageOrigin[2] = parameters.m_ImageSpacing[2]/2; parameters.m_ImageDirection.SetIdentity(); parameters.SetNumWeightedGradients(m_Controls->m_NumGradientsBox->value()); parameters.m_Bvalue = m_Controls->m_BvalueBox->value(); parameters.GenerateGradientHalfShell(); } // signal relaxation parameters.m_DoSimulateRelaxation = m_Controls->m_RelaxationBox->isChecked(); if (parameters.m_DoSimulateRelaxation && m_SelectedBundles.size()>0 ) parameters.m_ArtifactModelString += "_RELAX"; // N/2 ghosts if (m_Controls->m_AddGhosts->isChecked()) { parameters.m_ArtifactModelString += "_GHOST"; parameters.m_KspaceLineOffset = m_Controls->m_kOffsetBox->value(); parameters.m_ResultNode->AddProperty("Fiberfox.Ghost", DoubleProperty::New(parameters.m_KspaceLineOffset)); } else parameters.m_KspaceLineOffset = 0; // Aliasing if (m_Controls->m_AddAliasing->isChecked()) { parameters.m_ArtifactModelString += "_ALIASING"; parameters.m_CroppingFactor = (100-m_Controls->m_WrapBox->value())/100; parameters.m_ResultNode->AddProperty("Fiberfox.Aliasing", DoubleProperty::New(m_Controls->m_WrapBox->value())); } // Motion parameters.m_DoAddMotion = m_Controls->m_AddMotion->isChecked(); parameters.m_DoRandomizeMotion = m_Controls->m_RandomMotion->isChecked(); parameters.m_Translation[0] = m_Controls->m_MaxTranslationBoxX->value(); parameters.m_Translation[1] = m_Controls->m_MaxTranslationBoxY->value(); parameters.m_Translation[2] = m_Controls->m_MaxTranslationBoxZ->value(); parameters.m_Rotation[0] = m_Controls->m_MaxRotationBoxX->value(); parameters.m_Rotation[1] = m_Controls->m_MaxRotationBoxY->value(); parameters.m_Rotation[2] = m_Controls->m_MaxRotationBoxZ->value(); if ( m_Controls->m_AddMotion->isChecked() && m_SelectedBundles.size()>0 ) { parameters.m_ArtifactModelString += "_MOTION"; parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Random", BoolProperty::New(parameters.m_DoRandomizeMotion)); parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Translation-x", DoubleProperty::New(parameters.m_Translation[0])); parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Translation-y", DoubleProperty::New(parameters.m_Translation[1])); parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Translation-z", DoubleProperty::New(parameters.m_Translation[2])); parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Rotation-x", DoubleProperty::New(parameters.m_Rotation[0])); parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Rotation-y", DoubleProperty::New(parameters.m_Rotation[1])); parameters.m_ResultNode->AddProperty("Fiberfox.Motion.Rotation-z", DoubleProperty::New(parameters.m_Rotation[2])); } // other imaging parameters parameters.m_tLine = m_Controls->m_LineReadoutTimeBox->value(); parameters.m_tInhom = m_Controls->m_T2starBox->value(); parameters.m_tEcho = m_Controls->m_TEbox->value(); parameters.m_Repetitions = m_Controls->m_RepetitionsBox->value(); parameters.m_DoDisablePartialVolume = m_Controls->m_EnforcePureFiberVoxelsBox->isChecked(); parameters.m_AxonRadius = m_Controls->m_FiberRadius->value(); parameters.m_SignalScale = m_Controls->m_SignalScaleBox->value(); if (m_Controls->m_AddSpikes->isChecked()) { parameters.m_Spikes = m_Controls->m_SpikeNumBox->value(); parameters.m_SpikeAmplitude = m_Controls->m_SpikeScaleBox->value(); parameters.m_ArtifactModelString += "_SPIKES"; parameters.m_ResultNode->AddProperty("Fiberfox.Spikes.Number", IntProperty::New(parameters.m_Spikes)); parameters.m_ResultNode->AddProperty("Fiberfox.Spikes.Amplitude", DoubleProperty::New(parameters.m_SpikeAmplitude)); } // adjust echo time if needed if ( parameters.m_tEcho < parameters.m_ImageRegion.GetSize(1)*parameters.m_tLine ) { this->m_Controls->m_TEbox->setValue( parameters.m_ImageRegion.GetSize(1)*parameters.m_tLine ); parameters.m_tEcho = m_Controls->m_TEbox->value(); QMessageBox::information( NULL, "Warning", "Echo time is too short! Time not sufficient to read slice. Automaticall adjusted to "+QString::number(parameters.m_tEcho)+" ms"); } // rician noise if (m_Controls->m_AddNoise->isChecked()) { double noiseVariance = m_Controls->m_NoiseLevel->value(); { switch (m_Controls->m_NoiseDistributionBox->currentIndex()) { case 0: { parameters.m_NoiseModel = new mitk::RicianNoiseModel<ScalarType>(); parameters.m_ArtifactModelString += "_RICIAN-"; parameters.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Rician")); break; } case 1: { parameters.m_NoiseModel = new mitk::ChiSquareNoiseModel<ScalarType>(); parameters.m_ArtifactModelString += "_CHISQUARED-"; parameters.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Chi-squared")); break; } default: { parameters.m_NoiseModel = new mitk::RicianNoiseModel<ScalarType>(); parameters.m_ArtifactModelString += "_RICIAN-"; parameters.m_ResultNode->AddProperty("Fiberfox.Noise-Distribution", StringProperty::New("Rician")); } } } parameters.m_NoiseModel->SetNoiseVariance(noiseVariance); parameters.m_ArtifactModelString += QString::number(noiseVariance).toStdString(); parameters.m_ResultNode->AddProperty("Fiberfox.Noise-Variance", DoubleProperty::New(noiseVariance)); } // gibbs ringing parameters.m_DoAddGibbsRinging = m_Controls->m_AddGibbsRinging->isChecked(); if (m_Controls->m_AddGibbsRinging->isChecked()) { parameters.m_ResultNode->AddProperty("Fiberfox.Ringing", BoolProperty::New(true)); parameters.m_ArtifactModelString += "_RINGING"; } // adjusting line readout time to the adapted image size needed for the DFT unsigned int y = parameters.m_ImageRegion.GetSize(1); y += y%2; if ( y>parameters.m_ImageRegion.GetSize(1) ) parameters.m_tLine *= (double)parameters.m_ImageRegion.GetSize(1)/y; // add distortions if (m_Controls->m_AddDistortions->isChecked() && m_Controls->m_FrequencyMapBox->GetSelectedNode().IsNotNull()) { mitk::DataNode::Pointer fMapNode = m_Controls->m_FrequencyMapBox->GetSelectedNode(); mitk::Image* img = dynamic_cast<mitk::Image*>(fMapNode->GetData()); ItkDoubleImgType::Pointer itkImg = ItkDoubleImgType::New(); CastToItkImage< ItkDoubleImgType >(img, itkImg); if (parameters.m_ImageRegion.GetSize(0)==itkImg->GetLargestPossibleRegion().GetSize(0) && parameters.m_ImageRegion.GetSize(1)==itkImg->GetLargestPossibleRegion().GetSize(1) && parameters.m_ImageRegion.GetSize(2)==itkImg->GetLargestPossibleRegion().GetSize(2)) { itk::ImageDuplicator<ItkDoubleImgType>::Pointer duplicator = itk::ImageDuplicator<ItkDoubleImgType>::New(); duplicator->SetInputImage(itkImg); duplicator->Update(); parameters.m_FrequencyMap = duplicator->GetOutput(); parameters.m_ArtifactModelString += "_DISTORTED"; parameters.m_ResultNode->AddProperty("Fiberfox.Distortions", BoolProperty::New(true)); } } parameters.m_EddyStrength = 0; if (m_Controls->m_AddEddy->isChecked()) { parameters.m_EddyStrength = m_Controls->m_EddyGradientStrength->value(); parameters.m_ArtifactModelString += "_EDDY"; parameters.m_ResultNode->AddProperty("Fiberfox.Eddy-strength", DoubleProperty::New(parameters.m_EddyStrength)); } // signal models // compartment 1 switch (m_Controls->m_Compartment1Box->currentIndex()) { case 0: m_StickModel1.SetGradientList(parameters.GetGradientDirections()); m_StickModel1.SetBvalue(parameters.m_Bvalue); m_StickModel1.SetDiffusivity(m_Controls->m_StickWidget1->GetD()); m_StickModel1.SetT2(m_Controls->m_StickWidget1->GetT2()); parameters.m_FiberModelList.push_back(&m_StickModel1); parameters.m_SignalModelString += "Stick"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Stick") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.D", DoubleProperty::New(m_Controls->m_StickWidget1->GetD()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(m_StickModel1.GetT2()) ); break; case 1: m_ZeppelinModel1.SetGradientList(parameters.GetGradientDirections()); m_ZeppelinModel1.SetBvalue(parameters.m_Bvalue); m_ZeppelinModel1.SetDiffusivity1(m_Controls->m_ZeppelinWidget1->GetD1()); m_ZeppelinModel1.SetDiffusivity2(m_Controls->m_ZeppelinWidget1->GetD2()); m_ZeppelinModel1.SetDiffusivity3(m_Controls->m_ZeppelinWidget1->GetD2()); m_ZeppelinModel1.SetT2(m_Controls->m_ZeppelinWidget1->GetT2()); parameters.m_FiberModelList.push_back(&m_ZeppelinModel1); parameters.m_SignalModelString += "Zeppelin"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Zeppelin") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.D1", DoubleProperty::New(m_Controls->m_ZeppelinWidget1->GetD1()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.D2", DoubleProperty::New(m_Controls->m_ZeppelinWidget1->GetD2()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(m_ZeppelinModel1.GetT2()) ); break; case 2: m_TensorModel1.SetGradientList(parameters.GetGradientDirections()); m_TensorModel1.SetBvalue(parameters.m_Bvalue); m_TensorModel1.SetDiffusivity1(m_Controls->m_TensorWidget1->GetD1()); m_TensorModel1.SetDiffusivity2(m_Controls->m_TensorWidget1->GetD2()); m_TensorModel1.SetDiffusivity3(m_Controls->m_TensorWidget1->GetD3()); m_TensorModel1.SetT2(m_Controls->m_TensorWidget1->GetT2()); parameters.m_FiberModelList.push_back(&m_TensorModel1); parameters.m_SignalModelString += "Tensor"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Tensor") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.D1", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD1()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.D2", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD2()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.D3", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD3()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(m_ZeppelinModel1.GetT2()) ); break; } // compartment 2 switch (m_Controls->m_Compartment2Box->currentIndex()) { case 0: break; case 1: m_StickModel2.SetGradientList(parameters.GetGradientDirections()); m_StickModel2.SetBvalue(parameters.m_Bvalue); m_StickModel2.SetDiffusivity(m_Controls->m_StickWidget2->GetD()); m_StickModel2.SetT2(m_Controls->m_StickWidget2->GetT2()); parameters.m_FiberModelList.push_back(&m_StickModel2); parameters.m_SignalModelString += "Stick"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Stick") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.D", DoubleProperty::New(m_Controls->m_StickWidget2->GetD()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(m_StickModel2.GetT2()) ); break; case 2: m_ZeppelinModel2.SetGradientList(parameters.GetGradientDirections()); m_ZeppelinModel2.SetBvalue(parameters.m_Bvalue); m_ZeppelinModel2.SetDiffusivity1(m_Controls->m_ZeppelinWidget2->GetD1()); m_ZeppelinModel2.SetDiffusivity2(m_Controls->m_ZeppelinWidget2->GetD2()); m_ZeppelinModel2.SetDiffusivity3(m_Controls->m_ZeppelinWidget2->GetD2()); m_ZeppelinModel2.SetT2(m_Controls->m_ZeppelinWidget2->GetT2()); parameters.m_FiberModelList.push_back(&m_ZeppelinModel2); parameters.m_SignalModelString += "Zeppelin"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Zeppelin") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.D1", DoubleProperty::New(m_Controls->m_ZeppelinWidget2->GetD1()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.D2", DoubleProperty::New(m_Controls->m_ZeppelinWidget2->GetD2()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(m_ZeppelinModel2.GetT2()) ); break; case 3: m_TensorModel2.SetGradientList(parameters.GetGradientDirections()); m_TensorModel2.SetBvalue(parameters.m_Bvalue); m_TensorModel2.SetDiffusivity1(m_Controls->m_TensorWidget2->GetD1()); m_TensorModel2.SetDiffusivity2(m_Controls->m_TensorWidget2->GetD2()); m_TensorModel2.SetDiffusivity3(m_Controls->m_TensorWidget2->GetD3()); m_TensorModel2.SetT2(m_Controls->m_TensorWidget2->GetT2()); parameters.m_FiberModelList.push_back(&m_TensorModel2); parameters.m_SignalModelString += "Tensor"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Tensor") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.D1", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD1()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.D2", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD2()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.D3", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD3()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(m_ZeppelinModel2.GetT2()) ); break; } // compartment 3 switch (m_Controls->m_Compartment3Box->currentIndex()) { case 0: m_BallModel1.SetGradientList(parameters.GetGradientDirections()); m_BallModel1.SetBvalue(parameters.m_Bvalue); m_BallModel1.SetDiffusivity(m_Controls->m_BallWidget1->GetD()); m_BallModel1.SetT2(m_Controls->m_BallWidget1->GetT2()); parameters.m_NonFiberModelList.push_back(&m_BallModel1); parameters.m_SignalModelString += "Ball"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Ball") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.D", DoubleProperty::New(m_Controls->m_BallWidget1->GetD()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(m_BallModel1.GetT2()) ); break; case 1: m_AstrosticksModel1.SetGradientList(parameters.GetGradientDirections()); m_AstrosticksModel1.SetBvalue(parameters.m_Bvalue); m_AstrosticksModel1.SetDiffusivity(m_Controls->m_AstrosticksWidget1->GetD()); m_AstrosticksModel1.SetT2(m_Controls->m_AstrosticksWidget1->GetT2()); m_AstrosticksModel1.SetRandomizeSticks(m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()); parameters.m_NonFiberModelList.push_back(&m_AstrosticksModel1); parameters.m_SignalModelString += "Astrosticks"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Astrosticks") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.D", DoubleProperty::New(m_Controls->m_AstrosticksWidget1->GetD()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(m_AstrosticksModel1.GetT2()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.RandomSticks", BoolProperty::New(m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()) ); break; case 2: m_DotModel1.SetGradientList(parameters.GetGradientDirections()); m_DotModel1.SetT2(m_Controls->m_DotWidget1->GetT2()); parameters.m_NonFiberModelList.push_back(&m_DotModel1); parameters.m_SignalModelString += "Dot"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Dot") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(m_DotModel1.GetT2()) ); break; } // compartment 4 switch (m_Controls->m_Compartment4Box->currentIndex()) { case 0: break; case 1: { m_BallModel2.SetGradientList(parameters.GetGradientDirections()); m_BallModel2.SetBvalue(parameters.m_Bvalue); m_BallModel2.SetDiffusivity(m_Controls->m_BallWidget2->GetD()); m_BallModel2.SetT2(m_Controls->m_BallWidget2->GetT2()); mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp4VolumeFraction->GetSelectedNode(); if (volumeNode.IsNull()) { MITK_WARN << "No volume fraction image selected! Second extra-axonal compartment has been disabled."; break; } mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); ItkDoubleImgType::Pointer itkImg = ItkDoubleImgType::New(); CastToItkImage< ItkDoubleImgType >(img, itkImg); double max = img->GetScalarValueMax(); double min = img->GetScalarValueMin(); if (max>1 || min<0) // are volume fractions between 0 and 1? { itk::RescaleIntensityImageFilter<ItkDoubleImgType,ItkDoubleImgType>::Pointer rescaler = itk::RescaleIntensityImageFilter<ItkDoubleImgType,ItkDoubleImgType>::New(); rescaler->SetInput(0, itkImg); rescaler->SetOutputMaximum(1); rescaler->SetOutputMinimum(0); rescaler->Update(); itkImg = rescaler->GetOutput(); } m_BallModel2.SetVolumeFractionImage(itkImg); parameters.m_NonFiberModelList.push_back(&m_BallModel2); parameters.m_SignalModelString += "Ball"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Ball") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.D", DoubleProperty::New(m_Controls->m_BallWidget2->GetD()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(m_BallModel2.GetT2()) ); itk::InvertIntensityImageFilter< ItkDoubleImgType, ItkDoubleImgType >::Pointer inverter = itk::InvertIntensityImageFilter< ItkDoubleImgType, ItkDoubleImgType >::New(); inverter->SetMaximum(1.0); inverter->SetInput(itkImg); inverter->Update(); parameters.m_NonFiberModelList.at(parameters.m_NonFiberModelList.size()-2)->SetVolumeFractionImage(inverter->GetOutput()); break; } case 2: { m_AstrosticksModel2.SetGradientList(parameters.GetGradientDirections()); m_AstrosticksModel2.SetBvalue(parameters.m_Bvalue); m_AstrosticksModel2.SetDiffusivity(m_Controls->m_AstrosticksWidget2->GetD()); m_AstrosticksModel2.SetT2(m_Controls->m_AstrosticksWidget2->GetT2()); m_AstrosticksModel2.SetRandomizeSticks(m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()); mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp4VolumeFraction->GetSelectedNode(); if (volumeNode.IsNull()) { MITK_WARN << "No volume fraction image selected! Second extra-axonal compartment has been disabled."; break; } mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); ItkDoubleImgType::Pointer itkImg = ItkDoubleImgType::New(); CastToItkImage< ItkDoubleImgType >(img, itkImg); double max = img->GetScalarValueMax(); double min = img->GetScalarValueMin(); if (max>1 || min<0) // are volume fractions between 0 and 1? { itk::RescaleIntensityImageFilter<ItkDoubleImgType,ItkDoubleImgType>::Pointer rescaler = itk::RescaleIntensityImageFilter<ItkDoubleImgType,ItkDoubleImgType>::New(); rescaler->SetInput(0, itkImg); rescaler->SetOutputMaximum(1); rescaler->SetOutputMinimum(0); rescaler->Update(); itkImg = rescaler->GetOutput(); } m_AstrosticksModel2.SetVolumeFractionImage(itkImg); parameters.m_NonFiberModelList.push_back(&m_AstrosticksModel2); parameters.m_SignalModelString += "Astrosticks"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Astrosticks") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.D", DoubleProperty::New(m_Controls->m_AstrosticksWidget2->GetD()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(m_AstrosticksModel2.GetT2()) ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.RandomSticks", BoolProperty::New(m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()) ); itk::InvertIntensityImageFilter< ItkDoubleImgType, ItkDoubleImgType >::Pointer inverter = itk::InvertIntensityImageFilter< ItkDoubleImgType, ItkDoubleImgType >::New(); inverter->SetMaximum( 1.0 ); inverter->SetInput(itkImg); inverter->Update(); parameters.m_NonFiberModelList.at(parameters.m_NonFiberModelList.size()-2)->SetVolumeFractionImage(inverter->GetOutput()); break; } case 3: { m_DotModel2.SetGradientList(parameters.GetGradientDirections()); m_DotModel2.SetT2(m_Controls->m_DotWidget2->GetT2()); mitk::DataNode::Pointer volumeNode = m_Controls->m_Comp4VolumeFraction->GetSelectedNode(); if (volumeNode.IsNull()) { MITK_WARN << "No volume fraction image selected! Second extra-axonal compartment has been disabled."; break; } mitk::Image* img = dynamic_cast<mitk::Image*>(volumeNode->GetData()); ItkDoubleImgType::Pointer itkImg = ItkDoubleImgType::New(); CastToItkImage< ItkDoubleImgType >(img, itkImg); double max = img->GetScalarValueMax(); double min = img->GetScalarValueMin(); if (max>1 || min<0) // are volume fractions between 0 and 1? { itk::RescaleIntensityImageFilter<ItkDoubleImgType,ItkDoubleImgType>::Pointer rescaler = itk::RescaleIntensityImageFilter<ItkDoubleImgType,ItkDoubleImgType>::New(); rescaler->SetInput(0, itkImg); rescaler->SetOutputMaximum(1); rescaler->SetOutputMinimum(0); rescaler->Update(); itkImg = rescaler->GetOutput(); } m_DotModel2.SetVolumeFractionImage(itkImg); parameters.m_NonFiberModelList.push_back(&m_DotModel2); parameters.m_SignalModelString += "Dot"; parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Dot") ); parameters.m_ResultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(m_DotModel2.GetT2()) ); itk::InvertIntensityImageFilter< ItkDoubleImgType, ItkDoubleImgType >::Pointer inverter = itk::InvertIntensityImageFilter< ItkDoubleImgType, ItkDoubleImgType >::New(); inverter->SetMaximum( 1.0 ); inverter->SetInput(itkImg); inverter->Update(); parameters.m_NonFiberModelList.at(parameters.m_NonFiberModelList.size()-2)->SetVolumeFractionImage(inverter->GetOutput()); break; } } parameters.m_ResultNode->AddProperty("Fiberfox.SignalScale", IntProperty::New(parameters.m_SignalScale)); parameters.m_ResultNode->AddProperty("Fiberfox.FiberRadius", IntProperty::New(parameters.m_AxonRadius)); parameters.m_ResultNode->AddProperty("Fiberfox.Tinhom", DoubleProperty::New(parameters.m_tInhom)); parameters.m_ResultNode->AddProperty("Fiberfox.Tline", DoubleProperty::New(parameters.m_tLine)); parameters.m_ResultNode->AddProperty("Fiberfox.TE", DoubleProperty::New(parameters.m_tEcho)); parameters.m_ResultNode->AddProperty("Fiberfox.Repetitions", IntProperty::New(parameters.m_Repetitions)); parameters.m_ResultNode->AddProperty("Fiberfox.b-value", DoubleProperty::New(parameters.m_Bvalue)); parameters.m_ResultNode->AddProperty("Fiberfox.NoPartialVolume", BoolProperty::New(parameters.m_DoDisablePartialVolume)); parameters.m_ResultNode->AddProperty("Fiberfox.Relaxation", BoolProperty::New(parameters.m_DoSimulateRelaxation)); parameters.m_ResultNode->AddProperty("binary", BoolProperty::New(false)); return parameters; } void QmitkFiberfoxView::SaveParameters() { FiberfoxParameters<double> ffParamaters = UpdateImageParameters<double>(); QString filename = QFileDialog::getSaveFileName( 0, tr("Save Parameters"), m_ParameterFile, tr("Fiberfox Parameters (*.ffp)") ); if(filename.isEmpty() || filename.isNull()) return; if(!filename.endsWith(".ffp")) filename += ".ffp"; m_ParameterFile = filename; boost::property_tree::ptree parameters; // fiber generation parameters parameters.put("fiberfox.fibers.realtime", m_Controls->m_RealTimeFibers->isChecked()); parameters.put("fiberfox.fibers.showadvanced", m_Controls->m_AdvancedOptionsBox->isChecked()); parameters.put("fiberfox.fibers.distribution", m_Controls->m_DistributionBox->currentIndex()); parameters.put("fiberfox.fibers.variance", m_Controls->m_VarianceBox->value()); parameters.put("fiberfox.fibers.density", m_Controls->m_FiberDensityBox->value()); parameters.put("fiberfox.fibers.spline.sampling", m_Controls->m_FiberSamplingBox->value()); parameters.put("fiberfox.fibers.spline.tension", m_Controls->m_TensionBox->value()); parameters.put("fiberfox.fibers.spline.continuity", m_Controls->m_ContinuityBox->value()); parameters.put("fiberfox.fibers.spline.bias", m_Controls->m_BiasBox->value()); parameters.put("fiberfox.fibers.constantradius", m_Controls->m_ConstantRadiusBox->isChecked()); parameters.put("fiberfox.fibers.rotation.x", m_Controls->m_XrotBox->value()); parameters.put("fiberfox.fibers.rotation.y", m_Controls->m_YrotBox->value()); parameters.put("fiberfox.fibers.rotation.z", m_Controls->m_ZrotBox->value()); parameters.put("fiberfox.fibers.translation.x", m_Controls->m_XtransBox->value()); parameters.put("fiberfox.fibers.translation.y", m_Controls->m_YtransBox->value()); parameters.put("fiberfox.fibers.translation.z", m_Controls->m_ZtransBox->value()); parameters.put("fiberfox.fibers.scale.x", m_Controls->m_XscaleBox->value()); parameters.put("fiberfox.fibers.scale.y", m_Controls->m_YscaleBox->value()); parameters.put("fiberfox.fibers.scale.z", m_Controls->m_ZscaleBox->value()); parameters.put("fiberfox.fibers.includeFiducials", m_Controls->m_IncludeFiducials->isChecked()); parameters.put("fiberfox.fibers.includeFiducials", m_Controls->m_IncludeFiducials->isChecked()); // image generation parameters parameters.put("fiberfox.image.basic.size.x", ffParamaters.m_ImageRegion.GetSize(0)); parameters.put("fiberfox.image.basic.size.y", ffParamaters.m_ImageRegion.GetSize(1)); parameters.put("fiberfox.image.basic.size.z", ffParamaters.m_ImageRegion.GetSize(2)); parameters.put("fiberfox.image.basic.spacing.x", ffParamaters.m_ImageSpacing[0]); parameters.put("fiberfox.image.basic.spacing.y", ffParamaters.m_ImageSpacing[1]); parameters.put("fiberfox.image.basic.spacing.z", ffParamaters.m_ImageSpacing[2]); parameters.put("fiberfox.image.basic.numgradients", ffParamaters.GetNumWeightedVolumes()); parameters.put("fiberfox.image.basic.bvalue", ffParamaters.m_Bvalue); parameters.put("fiberfox.image.showadvanced", m_Controls->m_AdvancedOptionsBox_2->isChecked()); parameters.put("fiberfox.image.repetitions", ffParamaters.m_Repetitions); parameters.put("fiberfox.image.signalScale", ffParamaters.m_SignalScale); parameters.put("fiberfox.image.tEcho", ffParamaters.m_tEcho); parameters.put("fiberfox.image.tLine", m_Controls->m_LineReadoutTimeBox->value()); parameters.put("fiberfox.image.tInhom", ffParamaters.m_tInhom); parameters.put("fiberfox.image.axonRadius", ffParamaters.m_AxonRadius); parameters.put("fiberfox.image.doSimulateRelaxation", ffParamaters.m_DoSimulateRelaxation); parameters.put("fiberfox.image.doDisablePartialVolume", ffParamaters.m_DoDisablePartialVolume); parameters.put("fiberfox.image.outputvolumefractions", m_Controls->m_VolumeFractionsBox->isChecked()); parameters.put("fiberfox.image.artifacts.addnoise", m_Controls->m_AddNoise->isChecked()); parameters.put("fiberfox.image.artifacts.noisedistribution", m_Controls->m_NoiseDistributionBox->currentIndex()); parameters.put("fiberfox.image.artifacts.noisevariance", m_Controls->m_NoiseLevel->value()); parameters.put("fiberfox.image.artifacts.addghost", m_Controls->m_AddGhosts->isChecked()); parameters.put("fiberfox.image.artifacts.kspaceLineOffset", m_Controls->m_kOffsetBox->value()); parameters.put("fiberfox.image.artifacts.distortions", m_Controls->m_AddDistortions->isChecked()); parameters.put("fiberfox.image.artifacts.addeddy", m_Controls->m_AddEddy->isChecked()); parameters.put("fiberfox.image.artifacts.eddyStrength", m_Controls->m_EddyGradientStrength->value()); parameters.put("fiberfox.image.artifacts.addringing", m_Controls->m_AddGibbsRinging->isChecked()); parameters.put("fiberfox.image.artifacts.addspikes", m_Controls->m_AddSpikes->isChecked()); parameters.put("fiberfox.image.artifacts.spikesnum", m_Controls->m_SpikeNumBox->value()); parameters.put("fiberfox.image.artifacts.spikesscale", m_Controls->m_SpikeScaleBox->value()); parameters.put("fiberfox.image.artifacts.addaliasing", m_Controls->m_AddAliasing->isChecked()); parameters.put("fiberfox.image.artifacts.aliasingfactor", m_Controls->m_WrapBox->value()); parameters.put("fiberfox.image.artifacts.doAddMotion", m_Controls->m_AddMotion->isChecked()); parameters.put("fiberfox.image.artifacts.randomMotion", m_Controls->m_RandomMotion->isChecked()); parameters.put("fiberfox.image.artifacts.translation0", m_Controls->m_MaxTranslationBoxX->value()); parameters.put("fiberfox.image.artifacts.translation1", m_Controls->m_MaxTranslationBoxY->value()); parameters.put("fiberfox.image.artifacts.translation2", m_Controls->m_MaxTranslationBoxZ->value()); parameters.put("fiberfox.image.artifacts.rotation0", m_Controls->m_MaxRotationBoxX->value()); parameters.put("fiberfox.image.artifacts.rotation1", m_Controls->m_MaxRotationBoxY->value()); parameters.put("fiberfox.image.artifacts.rotation2", m_Controls->m_MaxRotationBoxZ->value()); parameters.put("fiberfox.image.compartment1.index", m_Controls->m_Compartment1Box->currentIndex()); parameters.put("fiberfox.image.compartment2.index", m_Controls->m_Compartment2Box->currentIndex()); parameters.put("fiberfox.image.compartment3.index", m_Controls->m_Compartment3Box->currentIndex()); parameters.put("fiberfox.image.compartment4.index", m_Controls->m_Compartment4Box->currentIndex()); parameters.put("fiberfox.image.compartment1.stick.d", m_Controls->m_StickWidget1->GetD()); parameters.put("fiberfox.image.compartment1.stick.t2", m_Controls->m_StickWidget1->GetT2()); parameters.put("fiberfox.image.compartment1.zeppelin.d1", m_Controls->m_ZeppelinWidget1->GetD1()); parameters.put("fiberfox.image.compartment1.zeppelin.d2", m_Controls->m_ZeppelinWidget1->GetD2()); parameters.put("fiberfox.image.compartment1.zeppelin.t2", m_Controls->m_ZeppelinWidget1->GetT2()); parameters.put("fiberfox.image.compartment1.tensor.d1", m_Controls->m_TensorWidget1->GetD1()); parameters.put("fiberfox.image.compartment1.tensor.d2", m_Controls->m_TensorWidget1->GetD2()); parameters.put("fiberfox.image.compartment1.tensor.d3", m_Controls->m_TensorWidget1->GetD3()); parameters.put("fiberfox.image.compartment1.tensor.t2", m_Controls->m_TensorWidget1->GetT2()); parameters.put("fiberfox.image.compartment2.stick.d", m_Controls->m_StickWidget2->GetD()); parameters.put("fiberfox.image.compartment2.stick.t2", m_Controls->m_StickWidget2->GetT2()); parameters.put("fiberfox.image.compartment2.zeppelin.d1", m_Controls->m_ZeppelinWidget2->GetD1()); parameters.put("fiberfox.image.compartment2.zeppelin.d2", m_Controls->m_ZeppelinWidget2->GetD2()); parameters.put("fiberfox.image.compartment2.zeppelin.t2", m_Controls->m_ZeppelinWidget2->GetT2()); parameters.put("fiberfox.image.compartment2.tensor.d1", m_Controls->m_TensorWidget2->GetD1()); parameters.put("fiberfox.image.compartment2.tensor.d2", m_Controls->m_TensorWidget2->GetD2()); parameters.put("fiberfox.image.compartment2.tensor.d3", m_Controls->m_TensorWidget2->GetD3()); parameters.put("fiberfox.image.compartment2.tensor.t2", m_Controls->m_TensorWidget2->GetT2()); parameters.put("fiberfox.image.compartment3.ball.d", m_Controls->m_BallWidget1->GetD()); parameters.put("fiberfox.image.compartment3.ball.t2", m_Controls->m_BallWidget1->GetT2()); parameters.put("fiberfox.image.compartment3.astrosticks.d", m_Controls->m_AstrosticksWidget1->GetD()); parameters.put("fiberfox.image.compartment3.astrosticks.t2", m_Controls->m_AstrosticksWidget1->GetT2()); parameters.put("fiberfox.image.compartment3.astrosticks.randomize", m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()); parameters.put("fiberfox.image.compartment3.dot.t2", m_Controls->m_DotWidget1->GetT2()); parameters.put("fiberfox.image.compartment4.ball.d", m_Controls->m_BallWidget2->GetD()); parameters.put("fiberfox.image.compartment4.ball.t2", m_Controls->m_BallWidget2->GetT2()); parameters.put("fiberfox.image.compartment4.astrosticks.d", m_Controls->m_AstrosticksWidget2->GetD()); parameters.put("fiberfox.image.compartment4.astrosticks.t2", m_Controls->m_AstrosticksWidget2->GetT2()); parameters.put("fiberfox.image.compartment4.astrosticks.randomize", m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()); parameters.put("fiberfox.image.compartment4.dot.t2", m_Controls->m_DotWidget2->GetT2()); boost::property_tree::xml_parser::write_xml(filename.toStdString(), parameters); } void QmitkFiberfoxView::LoadParameters() { QString filename = QFileDialog::getOpenFileName(0, tr("Load Parameters"), QString(itksys::SystemTools::GetFilenamePath(m_ParameterFile.toStdString()).c_str()), tr("Fiberfox Parameters (*.ffp)") ); if(filename.isEmpty() || filename.isNull()) return; m_ParameterFile = filename; boost::property_tree::ptree parameters; boost::property_tree::xml_parser::read_xml(filename.toStdString(), parameters); BOOST_FOREACH( boost::property_tree::ptree::value_type const& v1, parameters.get_child("fiberfox") ) { if( v1.first == "fibers" ) { m_Controls->m_RealTimeFibers->setChecked(v1.second.get<bool>("realtime")); m_Controls->m_AdvancedOptionsBox->setChecked(v1.second.get<bool>("showadvanced")); m_Controls->m_DistributionBox->setCurrentIndex(v1.second.get<int>("distribution")); m_Controls->m_VarianceBox->setValue(v1.second.get<double>("variance")); m_Controls->m_FiberDensityBox->setValue(v1.second.get<int>("density")); m_Controls->m_IncludeFiducials->setChecked(v1.second.get<bool>("includeFiducials")); m_Controls->m_ConstantRadiusBox->setChecked(v1.second.get<bool>("constantradius")); BOOST_FOREACH( boost::property_tree::ptree::value_type const& v2, v1.second ) { if( v2.first == "spline" ) { m_Controls->m_FiberSamplingBox->setValue(v2.second.get<double>("sampling")); m_Controls->m_TensionBox->setValue(v2.second.get<double>("tension")); m_Controls->m_ContinuityBox->setValue(v2.second.get<double>("continuity")); m_Controls->m_BiasBox->setValue(v2.second.get<double>("bias")); } if( v2.first == "rotation" ) { m_Controls->m_XrotBox->setValue(v2.second.get<double>("x")); m_Controls->m_YrotBox->setValue(v2.second.get<double>("y")); m_Controls->m_ZrotBox->setValue(v2.second.get<double>("z")); } if( v2.first == "translation" ) { m_Controls->m_XtransBox->setValue(v2.second.get<double>("x")); m_Controls->m_YtransBox->setValue(v2.second.get<double>("y")); m_Controls->m_ZtransBox->setValue(v2.second.get<double>("z")); } if( v2.first == "scale" ) { m_Controls->m_XscaleBox->setValue(v2.second.get<double>("x")); m_Controls->m_YscaleBox->setValue(v2.second.get<double>("y")); m_Controls->m_ZscaleBox->setValue(v2.second.get<double>("z")); } } } if( v1.first == "image" ) { m_Controls->m_SizeX->setValue(v1.second.get<int>("basic.size.x")); m_Controls->m_SizeY->setValue(v1.second.get<int>("basic.size.y")); m_Controls->m_SizeZ->setValue(v1.second.get<int>("basic.size.z")); m_Controls->m_SpacingX->setValue(v1.second.get<double>("basic.spacing.x")); m_Controls->m_SpacingY->setValue(v1.second.get<double>("basic.spacing.y")); m_Controls->m_SpacingZ->setValue(v1.second.get<double>("basic.spacing.z")); m_Controls->m_NumGradientsBox->setValue(v1.second.get<int>("basic.numgradients")); m_Controls->m_BvalueBox->setValue(v1.second.get<int>("basic.bvalue")); m_Controls->m_AdvancedOptionsBox_2->setChecked(v1.second.get<bool>("showadvanced")); m_Controls->m_RepetitionsBox->setValue(v1.second.get<int>("repetitions")); m_Controls->m_SignalScaleBox->setValue(v1.second.get<int>("signalScale")); m_Controls->m_TEbox->setValue(v1.second.get<double>("tEcho")); m_Controls->m_LineReadoutTimeBox->setValue(v1.second.get<double>("tLine")); m_Controls->m_T2starBox->setValue(v1.second.get<double>("tInhom")); m_Controls->m_FiberRadius->setValue(v1.second.get<double>("axonRadius")); m_Controls->m_RelaxationBox->setChecked(v1.second.get<bool>("doSimulateRelaxation")); m_Controls->m_EnforcePureFiberVoxelsBox->setChecked(v1.second.get<bool>("doDisablePartialVolume")); m_Controls->m_VolumeFractionsBox->setChecked(v1.second.get<bool>("outputvolumefractions")); m_Controls->m_AddNoise->setChecked(v1.second.get<bool>("artifacts.addnoise")); m_Controls->m_NoiseDistributionBox->setCurrentIndex(v1.second.get<int>("artifacts.noisedistribution")); m_Controls->m_NoiseLevel->setValue(v1.second.get<double>("artifacts.noisevariance")); m_Controls->m_AddGhosts->setChecked(v1.second.get<bool>("artifacts.addghost")); m_Controls->m_kOffsetBox->setValue(v1.second.get<double>("artifacts.kspaceLineOffset")); m_Controls->m_AddAliasing->setChecked(v1.second.get<bool>("artifacts.addaliasing")); m_Controls->m_WrapBox->setValue(v1.second.get<double>("artifacts.aliasingfactor")); m_Controls->m_AddDistortions->setChecked(v1.second.get<bool>("artifacts.distortions")); m_Controls->m_AddSpikes->setChecked(v1.second.get<bool>("artifacts.addspikes")); m_Controls->m_SpikeNumBox->setValue(v1.second.get<int>("artifacts.spikesnum")); m_Controls->m_SpikeScaleBox->setValue(v1.second.get<double>("artifacts.spikesscale")); m_Controls->m_AddEddy->setChecked(v1.second.get<bool>("artifacts.addeddy")); m_Controls->m_EddyGradientStrength->setValue(v1.second.get<double>("artifacts.eddyStrength")); m_Controls->m_AddGibbsRinging->setChecked(v1.second.get<bool>("artifacts.addringing")); m_Controls->m_AddMotion->setChecked(v1.second.get<bool>("artifacts.doAddMotion")); m_Controls->m_RandomMotion->setChecked(v1.second.get<bool>("artifacts.randomMotion")); m_Controls->m_MaxTranslationBoxX->setValue(v1.second.get<double>("artifacts.translation0")); m_Controls->m_MaxTranslationBoxY->setValue(v1.second.get<double>("artifacts.translation1")); m_Controls->m_MaxTranslationBoxZ->setValue(v1.second.get<double>("artifacts.translation2")); m_Controls->m_MaxRotationBoxX->setValue(v1.second.get<double>("artifacts.rotation0")); m_Controls->m_MaxRotationBoxY->setValue(v1.second.get<double>("artifacts.rotation1")); m_Controls->m_MaxRotationBoxZ->setValue(v1.second.get<double>("artifacts.rotation2")); m_Controls->m_Compartment1Box->setCurrentIndex(v1.second.get<int>("compartment1.index")); m_Controls->m_Compartment2Box->setCurrentIndex(v1.second.get<int>("compartment2.index")); m_Controls->m_Compartment3Box->setCurrentIndex(v1.second.get<int>("compartment3.index")); m_Controls->m_Compartment4Box->setCurrentIndex(v1.second.get<int>("compartment4.index")); m_Controls->m_StickWidget1->SetD(v1.second.get<double>("compartment1.stick.d")); m_Controls->m_StickWidget1->SetT2(v1.second.get<double>("compartment1.stick.t2")); m_Controls->m_ZeppelinWidget1->SetD1(v1.second.get<double>("compartment1.zeppelin.d1")); m_Controls->m_ZeppelinWidget1->SetD2(v1.second.get<double>("compartment1.zeppelin.d2")); m_Controls->m_ZeppelinWidget1->SetT2(v1.second.get<double>("compartment1.zeppelin.t2")); m_Controls->m_TensorWidget1->SetD1(v1.second.get<double>("compartment1.tensor.d1")); m_Controls->m_TensorWidget1->SetD2(v1.second.get<double>("compartment1.tensor.d2")); m_Controls->m_TensorWidget1->SetD3(v1.second.get<double>("compartment1.tensor.d3")); m_Controls->m_TensorWidget1->SetT2(v1.second.get<double>("compartment1.tensor.t2")); m_Controls->m_StickWidget2->SetD(v1.second.get<double>("compartment2.stick.d")); m_Controls->m_StickWidget2->SetT2(v1.second.get<double>("compartment2.stick.t2")); m_Controls->m_ZeppelinWidget2->SetD1(v1.second.get<double>("compartment2.zeppelin.d1")); m_Controls->m_ZeppelinWidget2->SetD2(v1.second.get<double>("compartment2.zeppelin.d2")); m_Controls->m_ZeppelinWidget2->SetT2(v1.second.get<double>("compartment2.zeppelin.t2")); m_Controls->m_TensorWidget2->SetD1(v1.second.get<double>("compartment2.tensor.d1")); m_Controls->m_TensorWidget2->SetD2(v1.second.get<double>("compartment2.tensor.d2")); m_Controls->m_TensorWidget2->SetD3(v1.second.get<double>("compartment2.tensor.d3")); m_Controls->m_TensorWidget2->SetT2(v1.second.get<double>("compartment2.tensor.t2")); m_Controls->m_BallWidget1->SetD(v1.second.get<double>("compartment3.ball.d")); m_Controls->m_BallWidget1->SetT2(v1.second.get<double>("compartment3.ball.t2")); m_Controls->m_AstrosticksWidget1->SetD(v1.second.get<double>("compartment3.astrosticks.d")); m_Controls->m_AstrosticksWidget1->SetT2(v1.second.get<double>("compartment3.astrosticks.t2")); m_Controls->m_AstrosticksWidget1->SetRandomizeSticks(v1.second.get<bool>("compartment3.astrosticks.randomize")); m_Controls->m_DotWidget1->SetT2(v1.second.get<double>("compartment3.dot.t2")); m_Controls->m_BallWidget2->SetD(v1.second.get<double>("compartment4.ball.d")); m_Controls->m_BallWidget2->SetT2(v1.second.get<double>("compartment4.ball.t2")); m_Controls->m_AstrosticksWidget2->SetD(v1.second.get<double>("compartment4.astrosticks.d")); m_Controls->m_AstrosticksWidget2->SetT2(v1.second.get<double>("compartment4.astrosticks.t2")); m_Controls->m_AstrosticksWidget2->SetRandomizeSticks(v1.second.get<bool>("compartment4.astrosticks.randomize")); m_Controls->m_DotWidget2->SetT2(v1.second.get<double>("compartment4.dot.t2")); } } } void QmitkFiberfoxView::ShowAdvancedOptions(int state) { if (state) { m_Controls->m_AdvancedFiberOptionsFrame->setVisible(true); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(true); m_Controls->m_AdvancedOptionsBox->setChecked(true); m_Controls->m_AdvancedOptionsBox_2->setChecked(true); } else { m_Controls->m_AdvancedFiberOptionsFrame->setVisible(false); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(false); m_Controls->m_AdvancedOptionsBox->setChecked(false); m_Controls->m_AdvancedOptionsBox_2->setChecked(false); } } void QmitkFiberfoxView::Comp1ModelFrameVisibility(int index) { m_Controls->m_StickWidget1->setVisible(false); m_Controls->m_ZeppelinWidget1->setVisible(false); m_Controls->m_TensorWidget1->setVisible(false); switch (index) { case 0: m_Controls->m_StickWidget1->setVisible(true); break; case 1: m_Controls->m_ZeppelinWidget1->setVisible(true); break; case 2: m_Controls->m_TensorWidget1->setVisible(true); break; } } void QmitkFiberfoxView::Comp2ModelFrameVisibility(int index) { m_Controls->m_StickWidget2->setVisible(false); m_Controls->m_ZeppelinWidget2->setVisible(false); m_Controls->m_TensorWidget2->setVisible(false); switch (index) { case 0: break; case 1: m_Controls->m_StickWidget2->setVisible(true); break; case 2: m_Controls->m_ZeppelinWidget2->setVisible(true); break; case 3: m_Controls->m_TensorWidget2->setVisible(true); break; } } void QmitkFiberfoxView::Comp3ModelFrameVisibility(int index) { m_Controls->m_BallWidget1->setVisible(false); m_Controls->m_AstrosticksWidget1->setVisible(false); m_Controls->m_DotWidget1->setVisible(false); switch (index) { case 0: m_Controls->m_BallWidget1->setVisible(true); break; case 1: m_Controls->m_AstrosticksWidget1->setVisible(true); break; case 2: m_Controls->m_DotWidget1->setVisible(true); break; } } void QmitkFiberfoxView::Comp4ModelFrameVisibility(int index) { m_Controls->m_BallWidget2->setVisible(false); m_Controls->m_AstrosticksWidget2->setVisible(false); m_Controls->m_DotWidget2->setVisible(false); m_Controls->m_Comp4FractionFrame->setVisible(false); switch (index) { case 0: break; case 1: m_Controls->m_BallWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 2: m_Controls->m_AstrosticksWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 3: m_Controls->m_DotWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; } } void QmitkFiberfoxView::OnConstantRadius(int value) { if (value>0 && m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnAddMotion(int value) { if (value>0) m_Controls->m_MotionArtifactFrame->setVisible(true); else m_Controls->m_MotionArtifactFrame->setVisible(false); } void QmitkFiberfoxView::OnAddAliasing(int value) { if (value>0) m_Controls->m_AliasingFrame->setVisible(true); else m_Controls->m_AliasingFrame->setVisible(false); } void QmitkFiberfoxView::OnAddSpikes(int value) { if (value>0) m_Controls->m_SpikeFrame->setVisible(true); else m_Controls->m_SpikeFrame->setVisible(false); } void QmitkFiberfoxView::OnAddEddy(int value) { if (value>0) m_Controls->m_EddyFrame->setVisible(true); else m_Controls->m_EddyFrame->setVisible(false); } void QmitkFiberfoxView::OnAddDistortions(int value) { if (value>0) m_Controls->m_DistortionsFrame->setVisible(true); else m_Controls->m_DistortionsFrame->setVisible(false); } void QmitkFiberfoxView::OnAddGhosts(int value) { if (value>0) m_Controls->m_GhostFrame->setVisible(true); else m_Controls->m_GhostFrame->setVisible(false); } void QmitkFiberfoxView::OnAddNoise(int value) { if (value>0) m_Controls->m_NoiseFrame->setVisible(true); else m_Controls->m_NoiseFrame->setVisible(false); } void QmitkFiberfoxView::OnDistributionChanged(int value) { if (value==1) m_Controls->m_VarianceBox->setVisible(true); else m_Controls->m_VarianceBox->setVisible(false); if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnVarianceChanged(double) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnFiberDensityChanged(int) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnFiberSamplingChanged(double) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnTensionChanged(double) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnContinuityChanged(double) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnBiasChanged(double) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::AlignOnGrid() { for (unsigned int i=0; i<m_SelectedFiducials.size(); i++) { mitk::PlanarEllipse::Pointer pe = dynamic_cast<mitk::PlanarEllipse*>(m_SelectedFiducials.at(i)->GetData()); mitk::Point3D wc0 = pe->GetWorldControlPoint(0); mitk::DataStorage::SetOfObjects::ConstPointer parentFibs = GetDataStorage()->GetSources(m_SelectedFiducials.at(i)); for( mitk::DataStorage::SetOfObjects::const_iterator it = parentFibs->begin(); it != parentFibs->end(); ++it ) { mitk::DataNode::Pointer pFibNode = *it; if ( pFibNode.IsNotNull() && dynamic_cast<mitk::FiberBundleX*>(pFibNode->GetData()) ) { mitk::DataStorage::SetOfObjects::ConstPointer parentImgs = GetDataStorage()->GetSources(pFibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = parentImgs->begin(); it2 != parentImgs->end(); ++it2 ) { mitk::DataNode::Pointer pImgNode = *it2; if ( pImgNode.IsNotNull() && dynamic_cast<mitk::Image*>(pImgNode->GetData()) ) { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(pImgNode->GetData()); mitk::BaseGeometry::Pointer geom = img->GetGeometry(); itk::Index<3> idx; geom->WorldToIndex(wc0, idx); mitk::Point3D cIdx; cIdx[0]=idx[0]; cIdx[1]=idx[1]; cIdx[2]=idx[2]; mitk::Point3D world; geom->IndexToWorld(cIdx,world); mitk::Vector3D trans = world - wc0; pe->GetGeometry()->Translate(trans); break; } } break; } } } for(unsigned int i=0; i<m_SelectedBundles2.size(); i++ ) { mitk::DataNode::Pointer fibNode = m_SelectedBundles2.at(i); mitk::DataStorage::SetOfObjects::ConstPointer sources = GetDataStorage()->GetSources(fibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it = sources->begin(); it != sources->end(); ++it ) { mitk::DataNode::Pointer imgNode = *it; if ( imgNode.IsNotNull() && dynamic_cast<mitk::Image*>(imgNode->GetData()) ) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(fibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations->begin(); it2 != derivations->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()) ) { mitk::PlanarEllipse::Pointer pe = dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()); mitk::Point3D wc0 = pe->GetWorldControlPoint(0); mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(imgNode->GetData()); mitk::BaseGeometry::Pointer geom = img->GetGeometry(); itk::Index<3> idx; geom->WorldToIndex(wc0, idx); mitk::Point3D cIdx; cIdx[0]=idx[0]; cIdx[1]=idx[1]; cIdx[2]=idx[2]; mitk::Point3D world; geom->IndexToWorld(cIdx,world); mitk::Vector3D trans = world - wc0; pe->GetGeometry()->Translate(trans); } } break; } } } for(unsigned int i=0; i<m_SelectedImages.size(); i++ ) { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(m_SelectedImages.at(i)->GetData()); mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(m_SelectedImages.at(i)); for( mitk::DataStorage::SetOfObjects::const_iterator it = derivations->begin(); it != derivations->end(); ++it ) { mitk::DataNode::Pointer fibNode = *it; if ( fibNode.IsNotNull() && dynamic_cast<mitk::FiberBundleX*>(fibNode->GetData()) ) { mitk::DataStorage::SetOfObjects::ConstPointer derivations2 = GetDataStorage()->GetDerivations(fibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations2->begin(); it2 != derivations2->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()) ) { mitk::PlanarEllipse::Pointer pe = dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()); mitk::Point3D wc0 = pe->GetWorldControlPoint(0); mitk::BaseGeometry::Pointer geom = img->GetGeometry(); itk::Index<3> idx; geom->WorldToIndex(wc0, idx); mitk::Point3D cIdx; cIdx[0]=idx[0]; cIdx[1]=idx[1]; cIdx[2]=idx[2]; mitk::Point3D world; geom->IndexToWorld(cIdx,world); mitk::Vector3D trans = world - wc0; pe->GetGeometry()->Translate(trans); } } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnFlipButton() { if (m_SelectedFiducial.IsNull()) return; std::map<mitk::DataNode*, QmitkPlanarFigureData>::iterator it = m_DataNodeToPlanarFigureData.find(m_SelectedFiducial.GetPointer()); if( it != m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; data.m_Flipped += 1; data.m_Flipped %= 2; } if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } QmitkFiberfoxView::GradientListType QmitkFiberfoxView::GenerateHalfShell(int NPoints) { NPoints *= 2; GradientListType pointshell; int numB0 = NPoints/20; if (numB0==0) numB0=1; GradientType g; g.Fill(0.0); for (int i=0; i<numB0; i++) pointshell.push_back(g); if (NPoints==0) return pointshell; vnl_vector<double> theta; theta.set_size(NPoints); vnl_vector<double> phi; phi.set_size(NPoints); double C = sqrt(4*M_PI); phi(0) = 0.0; phi(NPoints-1) = 0.0; for(int i=0; i<NPoints; i++) { theta(i) = acos(-1.0+2.0*i/(NPoints-1.0)) - M_PI / 2.0; if( i>0 && i<NPoints-1) { phi(i) = (phi(i-1) + C / sqrt(NPoints*(1-(-1.0+2.0*i/(NPoints-1.0))*(-1.0+2.0*i/(NPoints-1.0))))); // % (2*DIST_POINTSHELL_PI); } } for(int i=0; i<NPoints; i++) { g[2] = sin(theta(i)); if (g[2]<0) continue; g[0] = cos(theta(i)) * cos(phi(i)); g[1] = cos(theta(i)) * sin(phi(i)); pointshell.push_back(g); } return pointshell; } template<int ndirs> std::vector<itk::Vector<double,3> > QmitkFiberfoxView::MakeGradientList() { std::vector<itk::Vector<double,3> > retval; vnl_matrix_fixed<double, 3, ndirs>* U = itk::PointShell<ndirs, vnl_matrix_fixed<double, 3, ndirs> >::DistributePointShell(); // Add 0 vector for B0 int numB0 = ndirs/10; if (numB0==0) numB0=1; itk::Vector<double,3> v; v.Fill(0.0); for (int i=0; i<numB0; i++) { retval.push_back(v); } for(int i=0; i<ndirs;i++) { itk::Vector<double,3> v; v[0] = U->get(0,i); v[1] = U->get(1,i); v[2] = U->get(2,i); retval.push_back(v); } return retval; } void QmitkFiberfoxView::OnAddBundle() { if (m_SelectedImage.IsNull()) return; mitk::DataStorage::SetOfObjects::ConstPointer children = GetDataStorage()->GetDerivations(m_SelectedImage); mitk::FiberBundleX::Pointer bundle = mitk::FiberBundleX::New(); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( bundle ); QString name = QString("Bundle_%1").arg(children->size()); node->SetName(name.toStdString()); m_SelectedBundles.push_back(node); UpdateGui(); GetDataStorage()->Add(node, m_SelectedImage); } void QmitkFiberfoxView::OnDrawROI() { if (m_SelectedBundles.empty()) OnAddBundle(); if (m_SelectedBundles.empty()) return; mitk::DataStorage::SetOfObjects::ConstPointer children = GetDataStorage()->GetDerivations(m_SelectedBundles.at(0)); mitk::PlanarEllipse::Pointer figure = mitk::PlanarEllipse::New(); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( figure ); node->SetBoolProperty("planarfigure.3drendering", true); QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection(); for( int i=0; i<nodes.size(); i++) nodes.at(i)->SetSelected(false); m_SelectedFiducial = node; QString name = QString("Fiducial_%1").arg(children->size()); node->SetName(name.toStdString()); node->SetSelected(true); this->DisableCrosshairNavigation(); mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast<mitk::PlanarFigureInteractor*>(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "MitkPlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( node ); } UpdateGui(); GetDataStorage()->Add(node, m_SelectedBundles.at(0)); } bool CompareLayer(mitk::DataNode::Pointer i,mitk::DataNode::Pointer j) { int li = -1; i->GetPropertyValue("layer", li); int lj = -1; j->GetPropertyValue("layer", lj); return li<lj; } void QmitkFiberfoxView::GenerateFibers() { if (m_SelectedBundles.empty()) { if (m_SelectedFiducial.IsNull()) return; mitk::DataStorage::SetOfObjects::ConstPointer parents = GetDataStorage()->GetSources(m_SelectedFiducial); for( mitk::DataStorage::SetOfObjects::const_iterator it = parents->begin(); it != parents->end(); ++it ) if(dynamic_cast<mitk::FiberBundleX*>((*it)->GetData())) m_SelectedBundles.push_back(*it); if (m_SelectedBundles.empty()) return; } vector< vector< mitk::PlanarEllipse::Pointer > > fiducials; vector< vector< unsigned int > > fliplist; for (unsigned int i=0; i<m_SelectedBundles.size(); i++) { mitk::DataStorage::SetOfObjects::ConstPointer children = GetDataStorage()->GetDerivations(m_SelectedBundles.at(i)); std::vector< mitk::DataNode::Pointer > childVector; for( mitk::DataStorage::SetOfObjects::const_iterator it = children->begin(); it != children->end(); ++it ) childVector.push_back(*it); sort(childVector.begin(), childVector.end(), CompareLayer); vector< mitk::PlanarEllipse::Pointer > fib; vector< unsigned int > flip; float radius = 1; int count = 0; for( std::vector< mitk::DataNode::Pointer >::const_iterator it = childVector.begin(); it != childVector.end(); ++it ) { mitk::DataNode::Pointer node = *it; if ( node.IsNotNull() && dynamic_cast<mitk::PlanarEllipse*>(node->GetData()) ) { mitk::PlanarEllipse* ellipse = dynamic_cast<mitk::PlanarEllipse*>(node->GetData()); if (m_Controls->m_ConstantRadiusBox->isChecked()) { ellipse->SetTreatAsCircle(true); mitk::Point2D c = ellipse->GetControlPoint(0); mitk::Point2D p = ellipse->GetControlPoint(1); mitk::Vector2D v = p-c; if (count==0) { radius = v.GetVnlVector().magnitude(); ellipse->SetControlPoint(1, p); } else { v.Normalize(); v *= radius; ellipse->SetControlPoint(1, c+v); } } fib.push_back(ellipse); std::map<mitk::DataNode*, QmitkPlanarFigureData>::iterator it = m_DataNodeToPlanarFigureData.find(node.GetPointer()); if( it != m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; flip.push_back(data.m_Flipped); } else flip.push_back(0); } count++; } if (fib.size()>1) { fiducials.push_back(fib); fliplist.push_back(flip); } else if (fib.size()>0) m_SelectedBundles.at(i)->SetData( mitk::FiberBundleX::New() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } itk::FibersFromPlanarFiguresFilter::Pointer filter = itk::FibersFromPlanarFiguresFilter::New(); filter->SetFiducials(fiducials); filter->SetFlipList(fliplist); switch(m_Controls->m_DistributionBox->currentIndex()){ case 0: filter->SetFiberDistribution(itk::FibersFromPlanarFiguresFilter::DISTRIBUTE_UNIFORM); break; case 1: filter->SetFiberDistribution(itk::FibersFromPlanarFiguresFilter::DISTRIBUTE_GAUSSIAN); filter->SetVariance(m_Controls->m_VarianceBox->value()); break; } filter->SetDensity(m_Controls->m_FiberDensityBox->value()); filter->SetTension(m_Controls->m_TensionBox->value()); filter->SetContinuity(m_Controls->m_ContinuityBox->value()); filter->SetBias(m_Controls->m_BiasBox->value()); filter->SetFiberSampling(m_Controls->m_FiberSamplingBox->value()); filter->Update(); vector< mitk::FiberBundleX::Pointer > fiberBundles = filter->GetFiberBundles(); for (unsigned int i=0; i<fiberBundles.size(); i++) { m_SelectedBundles.at(i)->SetData( fiberBundles.at(i) ); if (fiberBundles.at(i)->GetNumFibers()>50000) m_SelectedBundles.at(i)->SetVisibility(false); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::GenerateImage() { if (m_SelectedBundles.empty() && m_SelectedDWI.IsNull()) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateGradientImage<unsigned int>( m_Controls->m_SizeX->value(), m_Controls->m_SizeY->value(), m_Controls->m_SizeZ->value(), m_Controls->m_SpacingX->value(), m_Controls->m_SpacingY->value(), m_Controls->m_SpacingZ->value()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Dummy"); unsigned int window = m_Controls->m_SizeX->value()*m_Controls->m_SizeY->value()*m_Controls->m_SizeZ->value(); unsigned int level = window/2; mitk::LevelWindow lw; lw.SetLevelWindow(level, window); node->SetProperty( "levelwindow", mitk::LevelWindowProperty::New( lw ) ); GetDataStorage()->Add(node); m_SelectedImage = node; mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } UpdateGui(); } else if (!m_SelectedBundles.empty()) SimulateImageFromFibers(m_SelectedBundles.at(0)); else if (m_SelectedDWI.IsNotNull()) SimulateForExistingDwi(m_SelectedDWI); } void QmitkFiberfoxView::SimulateForExistingDwi(mitk::DataNode* imageNode) { if (!dynamic_cast<mitk::DiffusionImage<short>*>(imageNode->GetData())) return; FiberfoxParameters<short> parameters = UpdateImageParameters<short>(); if (parameters.m_NoiseModel==NULL && parameters.m_Spikes==0 && parameters.m_FrequencyMap.IsNull() && parameters.m_KspaceLineOffset<=0.000001 && !parameters.m_DoAddGibbsRinging && !(parameters.m_EddyStrength>0) && parameters.m_CroppingFactor>0.999) { QMessageBox::information( NULL, "Simulation cancelled", "No valid artifact enabled! Motion artifacts and relaxation effects can NOT be added to an existing diffusion weighted image."); return; } mitk::DiffusionImage<short>::Pointer diffImg = dynamic_cast<mitk::DiffusionImage<short>*>(imageNode->GetData()); m_ArtifactsToDwiFilter = itk::AddArtifactsToDwiImageFilter< short >::New(); m_ArtifactsToDwiFilter->SetInput(diffImg->GetVectorImage()); parameters.m_ParentNode = imageNode; m_ArtifactsToDwiFilter->SetParameters(parameters); m_Worker.m_FilterType = 1; m_Thread.start(QThread::LowestPriority); } void QmitkFiberfoxView::SimulateImageFromFibers(mitk::DataNode* fiberNode) { mitk::FiberBundleX::Pointer fiberBundle = dynamic_cast<mitk::FiberBundleX*>(fiberNode->GetData()); if (fiberBundle->GetNumFibers()<=0) return; FiberfoxParameters<double> parameters = UpdateImageParameters<double>(); m_TractsToDwiFilter = itk::TractsToDWIImageFilter< short >::New(); parameters.m_ParentNode = fiberNode; m_TractsToDwiFilter->SetParameters(parameters); m_TractsToDwiFilter->SetFiberBundle(fiberBundle); + if (m_SelectedDWI.IsNotNull()) + { + mitk::DiffusionImage<short>::Pointer diffImg = dynamic_cast<mitk::DiffusionImage<short>*>(m_SelectedDWI->GetData()); + m_TractsToDwiFilter->SetInputDwi(diffImg); + } m_Worker.m_FilterType = 0; m_Thread.start(QThread::LowestPriority); } void QmitkFiberfoxView::ApplyTransform() { vector< mitk::DataNode::Pointer > selectedBundles; for(unsigned int i=0; i<m_SelectedImages.size(); i++ ) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(m_SelectedImages.at(i)); for( mitk::DataStorage::SetOfObjects::const_iterator it = derivations->begin(); it != derivations->end(); ++it ) { mitk::DataNode::Pointer fibNode = *it; if ( fibNode.IsNotNull() && dynamic_cast<mitk::FiberBundleX*>(fibNode->GetData()) ) selectedBundles.push_back(fibNode); } } if (selectedBundles.empty()) selectedBundles = m_SelectedBundles2; if (!selectedBundles.empty()) { for (std::vector<mitk::DataNode::Pointer>::const_iterator it = selectedBundles.begin(); it!=selectedBundles.end(); ++it) { mitk::FiberBundleX::Pointer fib = dynamic_cast<mitk::FiberBundleX*>((*it)->GetData()); fib->RotateAroundAxis(m_Controls->m_XrotBox->value(), m_Controls->m_YrotBox->value(), m_Controls->m_ZrotBox->value()); fib->TranslateFibers(m_Controls->m_XtransBox->value(), m_Controls->m_YtransBox->value(), m_Controls->m_ZtransBox->value()); fib->ScaleFibers(m_Controls->m_XscaleBox->value(), m_Controls->m_YscaleBox->value(), m_Controls->m_ZscaleBox->value()); // handle child fiducials if (m_Controls->m_IncludeFiducials->isChecked()) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(*it); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations->begin(); it2 != derivations->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()) ) { mitk::PlanarEllipse* pe = dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()); mitk::BaseGeometry* geom = pe->GetGeometry(); // translate mitk::Vector3D world; world[0] = m_Controls->m_XtransBox->value(); world[1] = m_Controls->m_YtransBox->value(); world[2] = m_Controls->m_ZtransBox->value(); geom->Translate(world); // calculate rotation matrix double x = m_Controls->m_XrotBox->value()*M_PI/180; double y = m_Controls->m_YrotBox->value()*M_PI/180; double z = m_Controls->m_ZrotBox->value()*M_PI/180; itk::Matrix< double, 3, 3 > rotX; rotX.SetIdentity(); rotX[1][1] = cos(x); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(x); rotX[2][1] = -rotX[1][2]; itk::Matrix< double, 3, 3 > rotY; rotY.SetIdentity(); rotY[0][0] = cos(y); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(y); rotY[2][0] = -rotY[0][2]; itk::Matrix< double, 3, 3 > rotZ; rotZ.SetIdentity(); rotZ[0][0] = cos(z); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(z); rotZ[1][0] = -rotZ[0][1]; itk::Matrix< double, 3, 3 > rot = rotZ*rotY*rotX; // transform control point coordinate into geometry translation geom->SetOrigin(pe->GetWorldControlPoint(0)); mitk::Point2D cp; cp.Fill(0.0); pe->SetControlPoint(0, cp); // rotate fiducial geom->GetIndexToWorldTransform()->SetMatrix(rot*geom->GetIndexToWorldTransform()->GetMatrix()); // implicit translation mitk::Vector3D trans; trans[0] = geom->GetOrigin()[0]-fib->GetGeometry()->GetCenter()[0]; trans[1] = geom->GetOrigin()[1]-fib->GetGeometry()->GetCenter()[1]; trans[2] = geom->GetOrigin()[2]-fib->GetGeometry()->GetCenter()[2]; mitk::Vector3D newWc = rot*trans; newWc = newWc-trans; geom->Translate(newWc); pe->Modified(); } } } } } else { for (unsigned int i=0; i<m_SelectedFiducials.size(); i++) { mitk::PlanarEllipse* pe = dynamic_cast<mitk::PlanarEllipse*>(m_SelectedFiducials.at(i)->GetData()); mitk::BaseGeometry* geom = pe->GetGeometry(); // translate mitk::Vector3D world; world[0] = m_Controls->m_XtransBox->value(); world[1] = m_Controls->m_YtransBox->value(); world[2] = m_Controls->m_ZtransBox->value(); geom->Translate(world); // calculate rotation matrix double x = m_Controls->m_XrotBox->value()*M_PI/180; double y = m_Controls->m_YrotBox->value()*M_PI/180; double z = m_Controls->m_ZrotBox->value()*M_PI/180; itk::Matrix< double, 3, 3 > rotX; rotX.SetIdentity(); rotX[1][1] = cos(x); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(x); rotX[2][1] = -rotX[1][2]; itk::Matrix< double, 3, 3 > rotY; rotY.SetIdentity(); rotY[0][0] = cos(y); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(y); rotY[2][0] = -rotY[0][2]; itk::Matrix< double, 3, 3 > rotZ; rotZ.SetIdentity(); rotZ[0][0] = cos(z); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(z); rotZ[1][0] = -rotZ[0][1]; itk::Matrix< double, 3, 3 > rot = rotZ*rotY*rotX; // transform control point coordinate into geometry translation geom->SetOrigin(pe->GetWorldControlPoint(0)); mitk::Point2D cp; cp.Fill(0.0); pe->SetControlPoint(0, cp); // rotate fiducial geom->GetIndexToWorldTransform()->SetMatrix(rot*geom->GetIndexToWorldTransform()->GetMatrix()); pe->Modified(); } if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::CopyBundles() { if ( m_SelectedBundles.size()<1 ){ QMessageBox::information( NULL, "Warning", "Select at least one fiber bundle!"); MITK_WARN("QmitkFiberProcessingView") << "Select at least one fiber bundle!"; return; } for (std::vector<mitk::DataNode::Pointer>::const_iterator it = m_SelectedBundles.begin(); it!=m_SelectedBundles.end(); ++it) { // find parent image mitk::DataNode::Pointer parentNode; mitk::DataStorage::SetOfObjects::ConstPointer parentImgs = GetDataStorage()->GetSources(*it); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = parentImgs->begin(); it2 != parentImgs->end(); ++it2 ) { mitk::DataNode::Pointer pImgNode = *it2; if ( pImgNode.IsNotNull() && dynamic_cast<mitk::Image*>(pImgNode->GetData()) ) { parentNode = pImgNode; break; } } mitk::FiberBundleX::Pointer fib = dynamic_cast<mitk::FiberBundleX*>((*it)->GetData()); mitk::FiberBundleX::Pointer newBundle = fib->GetDeepCopy(); QString name((*it)->GetName().c_str()); name += "_copy"; mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); if (parentNode.IsNotNull()) GetDataStorage()->Add(fbNode, parentNode); else GetDataStorage()->Add(fbNode); // copy child fiducials if (m_Controls->m_IncludeFiducials->isChecked()) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(*it); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations->begin(); it2 != derivations->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData()) ) { mitk::PlanarEllipse::Pointer pe = mitk::PlanarEllipse::New(); pe->DeepCopy(dynamic_cast<mitk::PlanarEllipse*>(fiducialNode->GetData())); mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetData(pe); newNode->SetName(fiducialNode->GetName()); newNode->SetBoolProperty("planarfigure.3drendering", true); GetDataStorage()->Add(newNode, fbNode); } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::JoinBundles() { if ( m_SelectedBundles.size()<2 ){ QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); MITK_WARN("QmitkFiberProcessingView") << "Select at least two fiber bundles!"; return; } std::vector<mitk::DataNode::Pointer>::const_iterator it = m_SelectedBundles.begin(); mitk::FiberBundleX::Pointer newBundle = dynamic_cast<mitk::FiberBundleX*>((*it)->GetData()); QString name(""); name += QString((*it)->GetName().c_str()); ++it; for (; it!=m_SelectedBundles.end(); ++it) { newBundle = newBundle->AddBundle(dynamic_cast<mitk::FiberBundleX*>((*it)->GetData())); name += "+"+QString((*it)->GetName().c_str()); } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::UpdateGui() { m_Controls->m_FiberBundleLabel->setText("<font color='red'>mandatory</font>"); m_Controls->m_GeometryFrame->setEnabled(true); m_Controls->m_GeometryMessage->setVisible(false); m_Controls->m_DiffusionPropsMessage->setVisible(false); m_Controls->m_FiberGenMessage->setVisible(true); m_Controls->m_TransformBundlesButton->setEnabled(false); m_Controls->m_CopyBundlesButton->setEnabled(false); m_Controls->m_GenerateFibersButton->setEnabled(false); m_Controls->m_FlipButton->setEnabled(false); m_Controls->m_CircleButton->setEnabled(false); m_Controls->m_BvalueBox->setEnabled(true); m_Controls->m_NumGradientsBox->setEnabled(true); m_Controls->m_JoinBundlesButton->setEnabled(false); m_Controls->m_AlignOnGrid->setEnabled(false); if (m_SelectedFiducial.IsNotNull()) { m_Controls->m_TransformBundlesButton->setEnabled(true); m_Controls->m_FlipButton->setEnabled(true); m_Controls->m_AlignOnGrid->setEnabled(true); } if (m_SelectedImage.IsNotNull() || !m_SelectedBundles.empty()) { m_Controls->m_TransformBundlesButton->setEnabled(true); m_Controls->m_CircleButton->setEnabled(true); m_Controls->m_FiberGenMessage->setVisible(false); m_Controls->m_AlignOnGrid->setEnabled(true); } if (m_MaskImageNode.IsNotNull() || m_SelectedImage.IsNotNull()) { m_Controls->m_GeometryMessage->setVisible(true); m_Controls->m_GeometryFrame->setEnabled(false); } if (m_SelectedDWI.IsNotNull()) { m_Controls->m_DiffusionPropsMessage->setVisible(true); m_Controls->m_BvalueBox->setEnabled(false); m_Controls->m_NumGradientsBox->setEnabled(false); m_Controls->m_GeometryMessage->setVisible(true); m_Controls->m_GeometryFrame->setEnabled(false); } if (!m_SelectedBundles.empty()) { m_Controls->m_CopyBundlesButton->setEnabled(true); m_Controls->m_GenerateFibersButton->setEnabled(true); m_Controls->m_FiberBundleLabel->setText(m_SelectedBundles.at(0)->GetName().c_str()); if (m_SelectedBundles.size()>1) m_Controls->m_JoinBundlesButton->setEnabled(true); } } void QmitkFiberfoxView::OnSelectionChanged( berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes ) { m_SelectedBundles2.clear(); m_SelectedImages.clear(); m_SelectedFiducials.clear(); m_SelectedFiducial = NULL; m_SelectedBundles.clear(); m_SelectedImage = NULL; m_SelectedDWI = NULL; m_MaskImageNode = NULL; m_Controls->m_TissueMaskLabel->setText("<font color='grey'>optional</font>"); // iterate all selected objects, adjust warning visibility for( int i=0; i<nodes.size(); i++) { mitk::DataNode::Pointer node = nodes.at(i); if ( node.IsNotNull() && dynamic_cast<mitk::DiffusionImage<short>*>(node->GetData()) ) { m_SelectedDWI = node; m_SelectedImage = node; m_SelectedImages.push_back(node); } else if( node.IsNotNull() && dynamic_cast<mitk::Image*>(node->GetData()) ) { m_SelectedImages.push_back(node); m_SelectedImage = node; bool isbinary = false; node->GetPropertyValue<bool>("binary", isbinary); if (isbinary) { m_MaskImageNode = node; m_Controls->m_TissueMaskLabel->setText(m_MaskImageNode->GetName().c_str()); } } else if ( node.IsNotNull() && dynamic_cast<mitk::FiberBundleX*>(node->GetData()) ) { m_SelectedBundles2.push_back(node); if (m_Controls->m_RealTimeFibers->isChecked()) { m_SelectedBundles.push_back(node); mitk::FiberBundleX::Pointer newFib = dynamic_cast<mitk::FiberBundleX*>(node->GetData()); if (newFib->GetNumFibers()!=m_Controls->m_FiberDensityBox->value()) GenerateFibers(); } else m_SelectedBundles.push_back(node); } else if ( node.IsNotNull() && dynamic_cast<mitk::PlanarEllipse*>(node->GetData()) ) { m_SelectedFiducials.push_back(node); m_SelectedFiducial = node; m_SelectedBundles.clear(); mitk::DataStorage::SetOfObjects::ConstPointer parents = GetDataStorage()->GetSources(node); for( mitk::DataStorage::SetOfObjects::const_iterator it = parents->begin(); it != parents->end(); ++it ) { mitk::DataNode::Pointer pNode = *it; if ( pNode.IsNotNull() && dynamic_cast<mitk::FiberBundleX*>(pNode->GetData()) ) m_SelectedBundles.push_back(pNode); } } } UpdateGui(); } void QmitkFiberfoxView::EnableCrosshairNavigation() { MITK_DEBUG << "EnableCrosshairNavigation"; // enable the crosshair navigation if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast<mitk::ILinkedRenderWindowPart*>(this->GetRenderWindowPart())) { MITK_DEBUG << "enabling linked navigation"; linkedRenderWindow->EnableLinkedNavigation(true); // linkedRenderWindow->EnableSlicingPlanes(true); } if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::DisableCrosshairNavigation() { MITK_DEBUG << "DisableCrosshairNavigation"; // disable the crosshair navigation during the drawing if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast<mitk::ILinkedRenderWindowPart*>(this->GetRenderWindowPart())) { MITK_DEBUG << "disabling linked navigation"; linkedRenderWindow->EnableLinkedNavigation(false); // linkedRenderWindow->EnableSlicingPlanes(false); } } void QmitkFiberfoxView::NodeRemoved(const mitk::DataNode* node) { mitk::DataNode* nonConstNode = const_cast<mitk::DataNode*>(node); std::map<mitk::DataNode*, QmitkPlanarFigureData>::iterator it = m_DataNodeToPlanarFigureData.find(nonConstNode); if (dynamic_cast<FiberBundleX*>(node->GetData())) { m_SelectedBundles.clear(); m_SelectedBundles2.clear(); } else if (dynamic_cast<Image*>(node->GetData())) m_SelectedImages.clear(); if( it != m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; // remove observers data.m_Figure->RemoveObserver( data.m_EndPlacementObserverTag ); data.m_Figure->RemoveObserver( data.m_SelectObserverTag ); data.m_Figure->RemoveObserver( data.m_StartInteractionObserverTag ); data.m_Figure->RemoveObserver( data.m_EndInteractionObserverTag ); m_DataNodeToPlanarFigureData.erase( it ); } } void QmitkFiberfoxView::NodeAdded( const mitk::DataNode* node ) { // add observer for selection in renderwindow mitk::PlanarFigure* figure = dynamic_cast<mitk::PlanarFigure*>(node->GetData()); bool isPositionMarker (false); node->GetBoolProperty("isContourMarker", isPositionMarker); if( figure && !isPositionMarker ) { MITK_DEBUG << "figure added. will add interactor if needed."; mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast<mitk::PlanarFigureInteractor*>(node->GetDataInteractor().GetPointer()); mitk::DataNode* nonConstNode = const_cast<mitk::DataNode*>( node ); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "MitkPlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( nonConstNode ); } MITK_DEBUG << "will now add observers for planarfigure"; QmitkPlanarFigureData data; data.m_Figure = figure; // // add observer for event when figure has been placed typedef itk::SimpleMemberCommand< QmitkFiberfoxView > SimpleCommandType; // SimpleCommandType::Pointer initializationCommand = SimpleCommandType::New(); // initializationCommand->SetCallbackFunction( this, &QmitkFiberfoxView::PlanarFigureInitialized ); // data.m_EndPlacementObserverTag = figure->AddObserver( mitk::EndPlacementPlanarFigureEvent(), initializationCommand ); // add observer for event when figure is picked (selected) typedef itk::MemberCommand< QmitkFiberfoxView > MemberCommandType; MemberCommandType::Pointer selectCommand = MemberCommandType::New(); selectCommand->SetCallbackFunction( this, &QmitkFiberfoxView::PlanarFigureSelected ); data.m_SelectObserverTag = figure->AddObserver( mitk::SelectPlanarFigureEvent(), selectCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer startInteractionCommand = SimpleCommandType::New(); startInteractionCommand->SetCallbackFunction( this, &QmitkFiberfoxView::DisableCrosshairNavigation); data.m_StartInteractionObserverTag = figure->AddObserver( mitk::StartInteractionPlanarFigureEvent(), startInteractionCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer endInteractionCommand = SimpleCommandType::New(); endInteractionCommand->SetCallbackFunction( this, &QmitkFiberfoxView::EnableCrosshairNavigation); data.m_EndInteractionObserverTag = figure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), endInteractionCommand ); m_DataNodeToPlanarFigureData[nonConstNode] = data; } } void QmitkFiberfoxView::PlanarFigureSelected( itk::Object* object, const itk::EventObject& ) { mitk::TNodePredicateDataType<mitk::PlanarFigure>::Pointer isPf = mitk::TNodePredicateDataType<mitk::PlanarFigure>::New(); mitk::DataStorage::SetOfObjects::ConstPointer allPfs = this->GetDataStorage()->GetSubset( isPf ); for ( mitk::DataStorage::SetOfObjects::const_iterator it = allPfs->begin(); it!=allPfs->end(); ++it) { mitk::DataNode* node = *it; if( node->GetData() == object ) { node->SetSelected(true); m_SelectedFiducial = node; } else node->SetSelected(false); } UpdateGui(); this->RequestRenderWindowUpdate(); } void QmitkFiberfoxView::SetFocus() { m_Controls->m_CircleButton->setFocus(); } void QmitkFiberfoxView::SetOutputPath() { // SELECT FOLDER DIALOG string outputPath = QFileDialog::getExistingDirectory(NULL, "Save images to...", QString(outputPath.c_str())).toStdString(); if (outputPath.empty()) m_Controls->m_SavePathEdit->setText("-"); else { outputPath += "/"; m_Controls->m_SavePathEdit->setText(QString(outputPath.c_str())); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp index 89fa93dd37..d960fa8205 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkODFDetailsView.cpp @@ -1,366 +1,366 @@ /*=================================================================== 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 <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "QmitkODFDetailsView.h" #include <QmitkStdMultiWidget.h> #include <QTableWidgetItem> #include <vtkFloatArray.h> #include <vtkPointData.h> #include <vtkCellData.h> #include <vtkLookupTable.h> #include <mitkOdfNormalizationMethodProperty.h> #include <QTextEdit> #include <mitkTensorImage.h> #include <QMessageBox> #include <QmitkRenderingManager.h> #include <mitkImageReadAccessor.h> const std::string QmitkODFDetailsView::VIEW_ID = "org.mitk.views.odfdetails"; QmitkODFDetailsView::QmitkODFDetailsView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_OdfNormalization(0) , m_ImageNode(NULL) { m_VtkActor = vtkActor::New(); m_VtkMapper = vtkPolyDataMapper::New(); m_Renderer = vtkRenderer::New(); m_VtkRenderWindow = vtkRenderWindow::New(); m_RenderWindowInteractor = vtkRenderWindowInteractor::New(); m_Camera = vtkCamera::New(); m_VtkRenderWindow->SetSize(300,300); } QmitkODFDetailsView::~QmitkODFDetailsView() { } void QmitkODFDetailsView::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::QmitkODFDetailsViewControls; m_Controls->setupUi( parent ); m_Controls->m_OdfBox->setVisible(false); m_Controls->m_ODFRenderWidget->setVisible(false); } } void QmitkODFDetailsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget1->GetSliceNavigationController(); itk::ReceptorMemberCommand<QmitkODFDetailsView>::Pointer command = itk::ReceptorMemberCommand<QmitkODFDetailsView>::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_SliceObserverTag1 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget2->GetSliceNavigationController(); itk::ReceptorMemberCommand<QmitkODFDetailsView>::Pointer command = itk::ReceptorMemberCommand<QmitkODFDetailsView>::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_SliceObserverTag2 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget3->GetSliceNavigationController(); itk::ReceptorMemberCommand<QmitkODFDetailsView>::Pointer command = itk::ReceptorMemberCommand<QmitkODFDetailsView>::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_SliceObserverTag3 = slicer->AddObserver( mitk::SliceNavigationController::GeometrySliceEvent(NULL, 0), command ); } } void QmitkODFDetailsView::StdMultiWidgetNotAvailable() { { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget1->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag1 ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget2->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag2 ); } { mitk::SliceNavigationController* slicer = m_MultiWidget->mitkWidget3->GetSliceNavigationController(); slicer->RemoveObserver( m_SliceObserverTag3 ); } m_MultiWidget = NULL; } void QmitkODFDetailsView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes ) { if (m_ImageNode.IsNotNull()) m_ImageNode->RemoveObserver( m_PropertyObserverTag ); m_Controls->m_InputData->setTitle("Please Select Input Data"); m_Controls->m_InputImageLabel->setText("<font color='red'>mandatory</font>"); m_ImageNode = NULL; // iterate selection for( std::vector<mitk::DataNode*>::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && (dynamic_cast<mitk::QBallImage*>(node->GetData()) || dynamic_cast<mitk::TensorImage*>(node->GetData())) ) { m_Controls->m_InputImageLabel->setText(node->GetName().c_str()); m_ImageNode = node; } } UpdateOdf(); if (m_ImageNode.IsNotNull()) { itk::ReceptorMemberCommand<QmitkODFDetailsView>::Pointer command = itk::ReceptorMemberCommand<QmitkODFDetailsView>::New(); command->SetCallbackFunction( this, &QmitkODFDetailsView::OnSliceChanged ); m_PropertyObserverTag = m_ImageNode->AddObserver( itk::ModifiedEvent(), command ); m_Controls->m_InputData->setTitle("Input Data"); } } void QmitkODFDetailsView::UpdateOdf() { try { m_Controls->m_OverviewBox->setVisible(true); if (m_ImageNode.IsNull() || !m_MultiWidget) { m_Controls->m_ODFRenderWidget->setVisible(false); m_Controls->m_OdfBox->setVisible(false); m_Controls->m_OverviewBox->setVisible(false); return; } // restore the input image label ( needed in case the last run resulted into an exception ) m_Controls->m_InputImageLabel->setText(m_ImageNode->GetName().c_str()); // ODF Normalization Property mitk::OdfNormalizationMethodProperty* nmp = dynamic_cast<mitk::OdfNormalizationMethodProperty*>(m_ImageNode->GetProperty( "Normalization" )); if(nmp) m_OdfNormalization = nmp->GetNormalization(); m_TemplateOdf = itk::OrientationDistributionFunction<float,QBALL_ODFSIZE>::GetBaseMesh(); m_OdfTransform = vtkSmartPointer<vtkTransform>::New(); m_OdfTransform->Identity(); m_OdfVals = vtkSmartPointer<vtkDoubleArray>::New(); m_OdfSource = vtkSmartPointer<vtkOdfSource>::New(); itk::OrientationDistributionFunction<double, QBALL_ODFSIZE> odf; mitk::Point3D world = m_MultiWidget->GetCrossPosition(); mitk::Point3D index; mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(m_ImageNode->GetData()); unsigned int *img_dimension = img->GetDimensions(); img->GetGeometry()->WorldToIndex(world, index); float sum = 0; float max = itk::NumericTraits<float>::NonpositiveMin(); float min = itk::NumericTraits<float>::max(); QString values; QString overviewText; // check if dynamic_cast successfull and if the crosshair position is inside of the geometry of the ODF data // otherwise possible crash for a scenario with multiple nodes if (dynamic_cast<mitk::QBallImage*>(m_ImageNode->GetData()) && ( m_ImageNode->GetData()->GetGeometry()->IsInside(world) ) ) { m_Controls->m_ODFRenderWidget->setVisible(true); m_Controls->m_OdfBox->setVisible(true); try { mitk::QBallImage* qball_image = dynamic_cast< mitk::QBallImage* >( m_ImageNode->GetData() ); // get access to the qball image data with explicitely allowing exceptions if memory locked mitk::ImageReadAccessor readAccess( qball_image, qball_image->GetVolumeData(0), mitk::ImageAccessorBase::ExceptionIfLocked ); const float* qball_cPtr = static_cast< const float*>(readAccess.GetData()); OdfVectorImgType::IndexType ind; ind[0] = (int)(index[0]+0.5); ind[1] = (int)(index[1]+0.5); ind[2] = (int)(index[2]+0.5); // pixel size = QBALL_ODFSIZE // position offset = standard offset unsigned int offset_to_data = QBALL_ODFSIZE * (ind[2] * img_dimension[1] * img_dimension[0] + ind[1] * img_dimension[0] + ind[0]); const float *pixel_data = qball_cPtr + offset_to_data; for (int i=0; i<QBALL_ODFSIZE; i++) { float val = pixel_data[i]; odf.SetNthComponent(i, val); values += QString::number(i)+": "+QString::number(val)+"\n"; sum += val; if (val>max) max = val; if (val<min) min = val; } float mean = sum/QBALL_ODFSIZE; QString pos = QString::number(ind[0])+", "+QString::number(ind[1])+", "+QString::number(ind[2]); overviewText += "Coordinates: "+pos+"\n"; overviewText += "GFA: "+QString::number(odf.GetGeneralizedFractionalAnisotropy())+"\n"; overviewText += "Sum: "+QString::number(sum)+"\n"; overviewText += "Mean: "+QString::number(mean)+"\n"; overviewText += "Min: "+QString::number(min)+"\n"; overviewText += "Max: "+QString::number(max)+"\n"; vnl_vector_fixed<double, 3> pd = odf.GetDirection(odf.GetPrincipleDiffusionDirection()); overviewText += "Main Diffusion:\n "+QString::number(pd[0])+"\n "+QString::number(pd[1])+"\n "+QString::number(pd[2])+"\n"; m_Controls->m_OdfValuesTextEdit->setText(values); m_Controls->m_OverviewTextEdit->setVisible(true); } catch( mitk::Exception &e ) { MITK_WARN << "LOCKED : " << e.what(); m_Controls->m_ODFRenderWidget->setVisible(false); m_Controls->m_OdfBox->setVisible(false); m_Controls->m_OverviewTextEdit->setVisible(false); // reset the selection m_Controls->m_InputImageLabel->setText("<font color='green'>Click image to restore rendering!</font>"); } } else if (dynamic_cast<mitk::TensorImage*>(m_ImageNode->GetData())) { m_Controls->m_ODFRenderWidget->setVisible(true); m_Controls->m_OdfBox->setVisible(false); mitk::TensorImage* qball_image = dynamic_cast< mitk::TensorImage*>(m_ImageNode->GetData()); // pixel access block try { // get access to the qball image data with explicitely allowing exceptions if memory locked mitk::ImageReadAccessor readAccess( qball_image, qball_image->GetVolumeData(0), mitk::ImageAccessorBase::ExceptionIfLocked ); const float* qball_cPtr = static_cast< const float*>(readAccess.GetData()); TensorImageType::IndexType ind; ind[0] = (int)(index[0]+0.5); ind[1] = (int)(index[1]+0.5); ind[2] = (int)(index[2]+0.5); // 6 - tensorsize // remaining computation - standard offset unsigned int offset_to_data = 6 * (ind[2] * img_dimension[1] * img_dimension[0] + ind[1] * img_dimension[0] + ind[0]); const float *pixel_data = qball_cPtr + offset_to_data; float tensorelems[6] = { *(pixel_data ), *(pixel_data + 1), *(pixel_data + 2), *(pixel_data + 3), *(pixel_data + 4), *(pixel_data + 5), }; itk::DiffusionTensor3D<float> tensor(tensorelems); odf.InitFromTensor(tensor); /** Array of eigen-values. */ typedef itk::FixedArray<float, 3> EigenValuesArrayType; /** Matrix of eigen-vectors. */ typedef itk::Matrix<float, 3, 3> MatrixType; typedef itk::Matrix<float, 3, 3> EigenVectorsMatrixType; EigenValuesArrayType eigenValues; - EigenVectorsMatrixType eigenVectors; + EigenVectorsMatrixType eigenvectors; QString pos = QString::number(ind[0])+", "+QString::number(ind[1])+", "+QString::number(ind[2]); overviewText += "Coordinates: "+pos+"\n"; overviewText += "FA: "+QString::number(tensor.GetFractionalAnisotropy())+"\n"; overviewText += "RA: "+QString::number(tensor.GetRelativeAnisotropy())+"\n"; overviewText += "Trace: "+QString::number(tensor.GetTrace())+"\n"; - tensor.ComputeEigenAnalysis(eigenValues,eigenVectors); + tensor.ComputeEigenAnalysis(eigenValues,eigenvectors); overviewText += "Eigenvalues:\n "+QString::number(eigenValues[2])+"\n "+QString::number(eigenValues[1])+"\n "+QString::number(eigenValues[0])+"\n"; - overviewText += "Main Diffusion:\n "+QString::number(eigenVectors[0][0])+"\n "+QString::number(eigenVectors[1][0])+"\n "+QString::number(eigenVectors[2][0])+"\n"; + overviewText += "Main Diffusion:\n "+QString::number(eigenvectors(2, 0))+"\n "+QString::number(eigenvectors(2, 1))+"\n "+QString::number(eigenvectors(2, 2))+"\n"; overviewText += "Values:\n "+QString::number(tensorelems[0])+"\n "+QString::number(tensorelems[1])+"\n "+QString::number(tensorelems[2])+"\n "+QString::number(tensorelems[3])+"\n "+QString::number(tensorelems[4])+"\n "+QString::number(tensorelems[5])+"\n "+"\n"; m_Controls->m_OverviewTextEdit->setVisible(true); } // end pixel access block catch(mitk::Exception &e ) { MITK_WARN << "LOCKED : " << e.what(); m_Controls->m_ODFRenderWidget->setVisible(false); m_Controls->m_OdfBox->setVisible(false); m_Controls->m_OverviewTextEdit->setVisible(false); // reset the selection m_Controls->m_InputImageLabel->setText("<font color='green'>Click image to restore rendering!</font>"); } } else { m_Controls->m_ODFRenderWidget->setVisible(false); m_Controls->m_OdfBox->setVisible(false); overviewText += "Please reinit image geometry.\n"; } // proceed only if the render widget is visible which indicates that the // predecessing computations were successfull if( m_Controls->m_ODFRenderWidget->isVisible() ) { m_Controls->m_ODFDetailsWidget->SetParameters(odf); switch(m_OdfNormalization) { case 0: odf = odf.MinMaxNormalize(); break; case 1: odf = odf.MaxNormalize(); break; case 2: odf = odf.MaxNormalize(); break; default: odf = odf.MinMaxNormalize(); } m_Controls->m_ODFRenderWidget->GenerateODF(odf); m_Controls->m_OverviewTextEdit->setText(overviewText.toStdString().c_str()); } } catch(...) { QMessageBox::critical(0, "Error", "Data could not be analyzed. The image might be corrupted."); } } void QmitkODFDetailsView::OnSliceChanged(const itk::EventObject& /*e*/) { UpdateOdf(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp index d47d657bf2..3816175810 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp @@ -1,889 +1,1390 @@ /*=================================================================== 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. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "QmitkPreprocessingView.h" #include "mitkDiffusionImagingConfigure.h" // qt includes #include <QMessageBox> // itk includes #include "itkTimeProbe.h" #include "itkB0ImageExtractionImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "itkBrainMaskExtractionImageFilter.h" #include "itkCastImageFilter.h" #include "itkVectorContainer.h" #include <itkElectrostaticRepulsionDiffusionGradientReductionFilter.h> #include <itkMergeDiffusionImagesFilter.h> #include <itkDwiGradientLengthCorrectionFilter.h> #include <itkDwiNormilzationFilter.h> // Multishell includes #include <itkRadialMultishellToSingleshellImageFilter.h> // Multishell Functors #include <itkADCAverageFunctor.h> #include <itkKurtosisFitFunctor.h> #include <itkBiExpFitFunctor.h> #include <itkADCFitFunctor.h> // mitk includes #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include <mitkPointSet.h> #include <itkAdcImageFilter.h> - +#include <itkBrainMaskExtractionImageFilter.h> +#include <mitkImageCast.h> +#include <mitkRotationOperation.h> #include <QTableWidgetItem> #include <QTableWidget> +#include <mitkInteractionConst.h> +#include <mitkImageAccessByItk.h> +#include <itkResampleDwiImageFilter.h> +#include <itkResampleImageFilter.h> const std::string QmitkPreprocessingView::VIEW_ID = - "org.mitk.views.preprocessing"; + "org.mitk.views.preprocessing"; #define DI_INFO MITK_INFO("DiffusionImaging") typedef float TTensorPixelType; QmitkPreprocessingView::QmitkPreprocessingView() - : QmitkFunctionality(), - m_Controls(NULL), - m_MultiWidget(NULL), - m_DiffusionImage(NULL) + : QmitkFunctionality(), + m_Controls(NULL), + m_MultiWidget(NULL), + m_DiffusionImage(NULL) { } QmitkPreprocessingView::~QmitkPreprocessingView() { } void QmitkPreprocessingView::CreateQtPartControl(QWidget *parent) { - if (!m_Controls) - { - // create GUI widgets - m_Controls = new Ui::QmitkPreprocessingViewControls; - m_Controls->setupUi(parent); - this->CreateConnections(); + if (!m_Controls) + { + // create GUI widgets + m_Controls = new Ui::QmitkPreprocessingViewControls; + m_Controls->setupUi(parent); + this->CreateConnections(); - m_Controls->m_MeasurementFrameTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); - m_Controls->m_MeasurementFrameTable->verticalHeader()->setResizeMode(QHeaderView::Stretch); - } + m_Controls->m_MeasurementFrameTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); + m_Controls->m_MeasurementFrameTable->verticalHeader()->setResizeMode(QHeaderView::Stretch); + + m_Controls->m_DirectionMatrixTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); + m_Controls->m_DirectionMatrixTable->verticalHeader()->setResizeMode(QHeaderView::Stretch); + } } void QmitkPreprocessingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { - m_MultiWidget = &stdMultiWidget; + m_MultiWidget = &stdMultiWidget; } void QmitkPreprocessingView::StdMultiWidgetNotAvailable() { - m_MultiWidget = NULL; + m_MultiWidget = NULL; } void QmitkPreprocessingView::CreateConnections() { - if ( m_Controls ) - { - connect( (QObject*)(m_Controls->m_ButtonAverageGradients), SIGNAL(clicked()), this, SLOT(AverageGradients()) ); - connect( (QObject*)(m_Controls->m_ButtonExtractB0), SIGNAL(clicked()), this, SLOT(ExtractB0()) ); - connect( (QObject*)(m_Controls->m_ModifyMeasurementFrame), SIGNAL(clicked()), this, SLOT(DoApplyMesurementFrame()) ); - connect( (QObject*)(m_Controls->m_ReduceGradientsButton), SIGNAL(clicked()), this, SLOT(DoReduceGradientDirections()) ); - connect( (QObject*)(m_Controls->m_ShowGradientsButton), SIGNAL(clicked()), this, SLOT(DoShowGradientDirections()) ); - connect( (QObject*)(m_Controls->m_MirrorGradientToHalfSphereButton), SIGNAL(clicked()), this, SLOT(DoHalfSphereGradientDirections()) ); - connect( (QObject*)(m_Controls->m_MergeDwisButton), SIGNAL(clicked()), this, SLOT(MergeDwis()) ); - connect( (QObject*)(m_Controls->m_AdcSignalAverage), SIGNAL(clicked()), this, SLOT(DoADCAverage()) ); - //connect( (QObject*)(m_Controls->m_AdcSignalFit), SIGNAL(clicked()), this, SLOT(DoADCFit()) ); - connect( (QObject*)(m_Controls->m_AkcSignalFit), SIGNAL(clicked()), this, SLOT(DoAKCFit()) ); - connect( (QObject*)(m_Controls->m_BiExpSignalFit), SIGNAL(clicked()), this, SLOT(DoBiExpFit()) ); - connect( (QObject*)(m_Controls->m_B_ValueMap_Rounder_SpinBox), SIGNAL(valueChanged(int)), this, SLOT(UpdateDwiBValueMapRounder(int))); - connect( (QObject*)(m_Controls->m_CreateLengthCorrectedDwi), SIGNAL(clicked()), this, SLOT(DoLengthCorrection()) ); - connect( (QObject*)(m_Controls->m_CalcAdcButton), SIGNAL(clicked()), this, SLOT(DoAdcCalculation()) ); - connect( (QObject*)(m_Controls->m_NormalizeImageValuesButton), SIGNAL(clicked()), this, SLOT(DoDwiNormalization()) ); - } + if ( m_Controls ) + { + m_Controls->m_ExtractBrainMask->setVisible(false); + m_Controls->m_BrainMaskIterationsBox->setVisible(false); + m_Controls->m_ResampleIntFrame->setVisible(false); + connect( (QObject*)(m_Controls->m_ButtonAverageGradients), SIGNAL(clicked()), this, SLOT(AverageGradients()) ); + connect( (QObject*)(m_Controls->m_ButtonExtractB0), SIGNAL(clicked()), this, SLOT(ExtractB0()) ); + connect( (QObject*)(m_Controls->m_ModifyMeasurementFrame), SIGNAL(clicked()), this, SLOT(DoApplyMesurementFrame()) ); + connect( (QObject*)(m_Controls->m_ReduceGradientsButton), SIGNAL(clicked()), this, SLOT(DoReduceGradientDirections()) ); + connect( (QObject*)(m_Controls->m_ShowGradientsButton), SIGNAL(clicked()), this, SLOT(DoShowGradientDirections()) ); + connect( (QObject*)(m_Controls->m_MirrorGradientToHalfSphereButton), SIGNAL(clicked()), this, SLOT(DoHalfSphereGradientDirections()) ); + connect( (QObject*)(m_Controls->m_MergeDwisButton), SIGNAL(clicked()), this, SLOT(MergeDwis()) ); + connect( (QObject*)(m_Controls->m_ProjectSignalButton), SIGNAL(clicked()), this, SLOT(DoProjectSignal()) ); + connect( (QObject*)(m_Controls->m_B_ValueMap_Rounder_SpinBox), SIGNAL(valueChanged(int)), this, SLOT(UpdateDwiBValueMapRounder(int))); + connect( (QObject*)(m_Controls->m_CreateLengthCorrectedDwi), SIGNAL(clicked()), this, SLOT(DoLengthCorrection()) ); + connect( (QObject*)(m_Controls->m_CalcAdcButton), SIGNAL(clicked()), this, SLOT(DoAdcCalculation()) ); + connect( (QObject*)(m_Controls->m_NormalizeImageValuesButton), SIGNAL(clicked()), this, SLOT(DoDwiNormalization()) ); + connect( (QObject*)(m_Controls->m_ModifyDirection), SIGNAL(clicked()), this, SLOT(DoApplyDirectionMatrix()) ); + connect( (QObject*)(m_Controls->m_ResampleImageButton), SIGNAL(clicked()), this, SLOT(DoResampleImage()) ); + connect( (QObject*)(m_Controls->m_ResampleTypeBox), SIGNAL(currentIndexChanged(int)), this, SLOT(DoUpdateInterpolationGui(int)) ); + // connect( (QObject*)(m_Controls->m_ExtractBrainMask), SIGNAL(clicked()), this, SLOT(DoExtractBrainMask()) ); + } +} + +void QmitkPreprocessingView::DoUpdateInterpolationGui(int i) +{ + switch (i) + { + case 0: + { + m_Controls->m_ResampleIntFrame->setVisible(false); + m_Controls->m_ResampleDoubleFrame->setVisible(true); + + m_Controls->m_ResampleDoubleX->setValue(2); + m_Controls->m_ResampleDoubleY->setValue(2); + m_Controls->m_ResampleDoubleZ->setValue(2); + break; + } + case 1: + { + m_Controls->m_ResampleIntFrame->setVisible(false); + m_Controls->m_ResampleDoubleFrame->setVisible(true); + + if (m_DiffusionImage.IsNotNull()) + { + ItkDwiType::Pointer itkDwi = m_DiffusionImage->GetVectorImage(); + m_Controls->m_ResampleDoubleX->setValue(itkDwi->GetSpacing()[0]); + m_Controls->m_ResampleDoubleY->setValue(itkDwi->GetSpacing()[1]); + m_Controls->m_ResampleDoubleZ->setValue(itkDwi->GetSpacing()[2]); + } + else if (m_SelectedImage.IsNotNull()) + { + mitk::BaseGeometry* geom = m_SelectedImage->GetGeometry(); + m_Controls->m_ResampleDoubleX->setValue(geom->GetSpacing()[0]); + m_Controls->m_ResampleDoubleY->setValue(geom->GetSpacing()[1]); + m_Controls->m_ResampleDoubleZ->setValue(geom->GetSpacing()[2]); + } + break; + } + case 2: + { + m_Controls->m_ResampleIntFrame->setVisible(true); + m_Controls->m_ResampleDoubleFrame->setVisible(false); + + if (m_DiffusionImage.IsNotNull()) + { + ItkDwiType::Pointer itkDwi = m_DiffusionImage->GetVectorImage(); + m_Controls->m_ResampleIntX->setValue(itkDwi->GetLargestPossibleRegion().GetSize(0)); + m_Controls->m_ResampleIntY->setValue(itkDwi->GetLargestPossibleRegion().GetSize(1)); + m_Controls->m_ResampleIntZ->setValue(itkDwi->GetLargestPossibleRegion().GetSize(2)); + } + else if (m_SelectedImage.IsNotNull()) + { + mitk::BaseGeometry* geom = m_SelectedImage->GetGeometry(); + m_Controls->m_ResampleIntX->setValue(geom->GetExtent(0)); + m_Controls->m_ResampleIntY->setValue(geom->GetExtent(1)); + m_Controls->m_ResampleIntZ->setValue(geom->GetExtent(2)); + } + break; + } + default: + { + m_Controls->m_ResampleDoubleX->setValue(2); + m_Controls->m_ResampleDoubleY->setValue(2); + m_Controls->m_ResampleDoubleZ->setValue(2); + m_Controls->m_ResampleIntFrame->setVisible(false); + m_Controls->m_ResampleDoubleFrame->setVisible(true); + } + } +} + +void QmitkPreprocessingView::DoExtractBrainMask() +{ + // if (m_SelectedImage.IsNull()) + // return; + + // typedef itk::Image<unsigned short, 3> ShortImageType; + // ShortImageType::Pointer itkImage = ShortImageType::New(); + // mitk::CastToItkImage(m_SelectedImage, itkImage); + + // typedef itk::BrainMaskExtractionImageFilter< unsigned char > FilterType; + // FilterType::Pointer filter = FilterType::New(); + // filter->SetInput(itkImage); + // filter->SetMaxNumIterations(m_Controls->m_BrainMaskIterationsBox->value()); + // filter->Update(); + + // mitk::Image::Pointer image = mitk::Image::New(); + // image->InitializeByItk( filter->GetOutput() ); + // image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + // mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + // imageNode->SetData( image ); + // imageNode->SetName("BRAINMASK"); + // GetDefaultDataStorage()->Add(imageNode); +} + +void QmitkPreprocessingView::DoResampleImage() +{ + if (m_DiffusionImage.IsNotNull()) + { + typedef itk::ResampleDwiImageFilter< short > ResampleFilter; + ResampleFilter::Pointer resampler = ResampleFilter::New(); + resampler->SetInput(m_DiffusionImage->GetVectorImage()); + + switch (m_Controls->m_ResampleTypeBox->currentIndex()) + { + case 0: + { + itk::Vector< double, 3 > samplingFactor; + samplingFactor[0] = m_Controls->m_ResampleDoubleX->value(); + samplingFactor[1] = m_Controls->m_ResampleDoubleY->value(); + samplingFactor[2] = m_Controls->m_ResampleDoubleZ->value(); + resampler->SetSamplingFactor(samplingFactor); + break; + } + case 1: + { + itk::Vector< double, 3 > newSpacing; + newSpacing[0] = m_Controls->m_ResampleDoubleX->value(); + newSpacing[1] = m_Controls->m_ResampleDoubleY->value(); + newSpacing[2] = m_Controls->m_ResampleDoubleZ->value(); + resampler->SetNewSpacing(newSpacing); + break; + } + case 2: + { + itk::ImageRegion<3> newRegion; + newRegion.SetSize(0, m_Controls->m_ResampleIntX->value()); + newRegion.SetSize(1, m_Controls->m_ResampleIntY->value()); + newRegion.SetSize(2, m_Controls->m_ResampleIntZ->value()); + resampler->SetNewImageSize(newRegion); + break; + } + default: + { + MITK_WARN << "Unknown resampling parameters!"; + return; + } + } + + QString outAdd; + switch (m_Controls->m_InterpolatorBox->currentIndex()) + { + case 0: + { + resampler->SetInterpolation(ResampleFilter::Interpolate_NearestNeighbour); + outAdd = "NearestNeighbour"; + break; + } + case 1: + { + resampler->SetInterpolation(ResampleFilter::Interpolate_Linear); + outAdd = "Linear"; + break; + } + case 2: + { + resampler->SetInterpolation(ResampleFilter::Interpolate_BSpline); + outAdd = "BSpline"; + break; + } + case 3: + { + resampler->SetInterpolation(ResampleFilter::Interpolate_WindowedSinc); + outAdd = "WindowedSinc"; + break; + } + default: + { + resampler->SetInterpolation(ResampleFilter::Interpolate_NearestNeighbour); + outAdd = "NearestNeighbour"; + } + } + + resampler->Update(); + + typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; + DiffusionImageType::Pointer image = DiffusionImageType::New(); + image->SetVectorImage( resampler->GetOutput() ); + image->SetReferenceBValue( m_DiffusionImage->GetReferenceBValue() ); + image->SetDirections( m_DiffusionImage->GetDirections() ); + image->InitializeFromVectorImage(); + + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + QString name = m_SelectedDiffusionNodes.back()->GetName().c_str(); + + imageNode->SetName((name+"_resampled_"+outAdd).toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); + } + else if (m_SelectedImage.IsNotNull()) + { + AccessFixedDimensionByItk(m_SelectedImage, TemplatedResampleImage,3); + } +} + + +template < typename TPixel, unsigned int VImageDimension > +void QmitkPreprocessingView::TemplatedResampleImage( itk::Image<TPixel, VImageDimension>* itkImage) +{ + itk::Vector< double, 3 > newSpacing; + itk::ImageRegion<3> newRegion; + + switch (m_Controls->m_ResampleTypeBox->currentIndex()) + { + case 0: + { + itk::Vector< double, 3 > sampling; + sampling[0] = m_Controls->m_ResampleDoubleX->value(); + sampling[1] = m_Controls->m_ResampleDoubleY->value(); + sampling[2] = m_Controls->m_ResampleDoubleZ->value(); + + newSpacing = itkImage->GetSpacing(); + newSpacing[0] /= sampling[0]; + newSpacing[1] /= sampling[1]; + newSpacing[2] /= sampling[2]; + newRegion = itkImage->GetLargestPossibleRegion(); + newRegion.SetSize(0, newRegion.GetSize(0)*sampling[0]); + newRegion.SetSize(1, newRegion.GetSize(1)*sampling[1]); + newRegion.SetSize(2, newRegion.GetSize(2)*sampling[2]); + + break; + } + case 1: + { + newSpacing[0] = m_Controls->m_ResampleDoubleX->value(); + newSpacing[1] = m_Controls->m_ResampleDoubleY->value(); + newSpacing[2] = m_Controls->m_ResampleDoubleZ->value(); + + itk::Vector< double, 3 > oldSpacing = itkImage->GetSpacing(); + itk::Vector< double, 3 > sampling; + sampling[0] = oldSpacing[0]/newSpacing[0]; + sampling[1] = oldSpacing[1]/newSpacing[1]; + sampling[2] = oldSpacing[2]/newSpacing[2]; + newRegion = itkImage->GetLargestPossibleRegion(); + newRegion.SetSize(0, newRegion.GetSize(0)*sampling[0]); + newRegion.SetSize(1, newRegion.GetSize(1)*sampling[1]); + newRegion.SetSize(2, newRegion.GetSize(2)*sampling[2]); + break; + } + case 2: + { + newRegion.SetSize(0, m_Controls->m_ResampleIntX->value()); + newRegion.SetSize(1, m_Controls->m_ResampleIntY->value()); + newRegion.SetSize(2, m_Controls->m_ResampleIntZ->value()); + + itk::ImageRegion<3> oldRegion = itkImage->GetLargestPossibleRegion(); + itk::Vector< double, 3 > sampling; + sampling[0] = (double)newRegion.GetSize(0)/oldRegion.GetSize(0); + sampling[1] = (double)newRegion.GetSize(1)/oldRegion.GetSize(1); + sampling[2] = (double)newRegion.GetSize(2)/oldRegion.GetSize(2); + + newSpacing = itkImage->GetSpacing(); + newSpacing[0] /= sampling[0]; + newSpacing[1] /= sampling[1]; + newSpacing[2] /= sampling[2]; + break; + } + default: + { + MITK_WARN << "Unknown resampling parameters!"; + return; + } + } + + itk::Point<double,3> origin = itkImage->GetOrigin(); + origin[0] -= itkImage->GetSpacing()[0]/2; + origin[1] -= itkImage->GetSpacing()[1]/2; + origin[2] -= itkImage->GetSpacing()[2]/2; + origin[0] += newSpacing[0]/2; + origin[1] += newSpacing[1]/2; + origin[2] += newSpacing[2]/2; + + typedef itk::Image<TPixel, VImageDimension> ImageType; + typename ImageType::Pointer outImage = ImageType::New(); + outImage->SetSpacing( newSpacing ); + outImage->SetOrigin( origin ); + outImage->SetDirection( itkImage->GetDirection() ); + outImage->SetLargestPossibleRegion( newRegion ); + outImage->SetBufferedRegion( newRegion ); + outImage->SetRequestedRegion( newRegion ); + outImage->Allocate(); + + typedef itk::ResampleImageFilter<ImageType, ImageType> ResampleFilter; + typename ResampleFilter::Pointer resampler = ResampleFilter::New(); + resampler->SetInput(itkImage); + resampler->SetOutputParametersFromImage(outImage); + + QString outAdd; + switch (m_Controls->m_InterpolatorBox->currentIndex()) + { + case 0: + { + typename itk::NearestNeighborInterpolateImageFunction<ImageType>::Pointer interp = itk::NearestNeighborInterpolateImageFunction<ImageType>::New(); + resampler->SetInterpolator(interp); + outAdd = "NearestNeighbour"; + break; + } + case 1: + { + typename itk::LinearInterpolateImageFunction<ImageType>::Pointer interp = itk::LinearInterpolateImageFunction<ImageType>::New(); + resampler->SetInterpolator(interp); + outAdd = "Linear"; + break; + } + case 2: + { + typename itk::BSplineInterpolateImageFunction<ImageType>::Pointer interp = itk::BSplineInterpolateImageFunction<ImageType>::New(); + resampler->SetInterpolator(interp); + outAdd = "BSpline"; + break; + } + case 3: + { + typename itk::WindowedSincInterpolateImageFunction<ImageType, 3>::Pointer interp = itk::WindowedSincInterpolateImageFunction<ImageType, 3>::New(); + resampler->SetInterpolator(interp); + outAdd = "WindowedSinc"; + break; + } + default: + { + typename itk::NearestNeighborInterpolateImageFunction<ImageType>::Pointer interp = itk::NearestNeighborInterpolateImageFunction<ImageType>::New(); + resampler->SetInterpolator(interp); + outAdd = "NearestNeighbour"; + } + } + + resampler->Update(); + + mitk::Image::Pointer image = mitk::Image::New(); + image->InitializeByItk( resampler->GetOutput() ); + image->SetVolume( resampler->GetOutput()->GetBufferPointer() ); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + QString name = m_SelectedImageNode->GetName().c_str(); + + imageNode->SetName((name+"_resampled_"+outAdd).toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedImageNode); +} + +void QmitkPreprocessingView::DoApplyDirectionMatrix() +{ + if (m_DiffusionImage.IsNotNull()) + { + MitkDwiType::Pointer newDwi = m_DiffusionImage->Clone(); + ItkDwiType::DirectionType newDirection; + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + QTableWidgetItem* item = m_Controls->m_DirectionMatrixTable->item(r,c); + if (!item) + return; + newDirection[r][c] = item->text().toDouble(); + } + + ItkDwiType::Pointer itkDwi = newDwi->GetVectorImage(); + + typedef mitk::DiffusionImage<DiffusionPixelType> MitkDwiType; + vnl_matrix_fixed< double,3,3 > oldInverseDirection = itkDwi->GetDirection().GetInverse(); + MitkDwiType::GradientDirectionContainerType::Pointer oldGradients = m_DiffusionImage->GetDirectionsWithoutMeasurementFrame(); + MitkDwiType::GradientDirectionContainerType::Pointer newGradients = MitkDwiType::GradientDirectionContainerType::New(); + + for (unsigned int i=0; i<oldGradients->Size(); i++) + { + MitkDwiType::GradientDirectionType g = oldGradients->GetElement(i); + double mag = g.magnitude(); + MitkDwiType::GradientDirectionType newG = oldInverseDirection*g; + newG = newDirection.GetVnlMatrix()*newG; + newG.normalize(); + newGradients->InsertElement(i, newG*mag); + } + + newDwi->SetDirections(newGradients); + itkDwi->SetDirection(newDirection); + newDwi->InitializeFromVectorImage(); + + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( newDwi ); + QString name = m_SelectedDiffusionNodes.back()->GetName().c_str(); + imageNode->SetName((name+"_newdirection").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); + + mitk::RenderingManager::GetInstance()->InitializeViews( imageNode->GetData()->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); + mitk::RenderingManager::GetInstance()->RequestUpdateAll(); + } + else if (m_SelectedImage.IsNotNull()) + { + AccessFixedDimensionByItk(m_SelectedImage, TemplatedApplyRotation,3); + } +} + +template < typename TPixel, unsigned int VImageDimension > +void QmitkPreprocessingView::TemplatedApplyRotation( itk::Image<TPixel, VImageDimension>* itkImage) +{ + ItkDwiType::DirectionType newDirection; + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + QTableWidgetItem* item = m_Controls->m_DirectionMatrixTable->item(r,c); + if (!item) + return; + newDirection[r][c] = item->text().toDouble(); + } + typedef itk::Image<TPixel, VImageDimension> ImageType; + + typename ImageType::Pointer newImage = ImageType::New(); + newImage->SetSpacing( itkImage->GetSpacing() ); + newImage->SetOrigin( itkImage->GetOrigin() ); + newImage->SetDirection( newDirection ); + newImage->SetLargestPossibleRegion( itkImage->GetLargestPossibleRegion() ); + newImage->SetBufferedRegion( itkImage->GetLargestPossibleRegion() ); + newImage->SetRequestedRegion( itkImage->GetLargestPossibleRegion() ); + newImage->Allocate(); + newImage->FillBuffer(0); + + itk::ImageRegionIterator< itk::Image<TPixel, VImageDimension> > it(itkImage, itkImage->GetLargestPossibleRegion()); + while(!it.IsAtEnd()) + { + newImage->SetPixel(it.GetIndex(), it.Get()); + ++it; + } + + mitk::Image::Pointer newMitkImage = mitk::Image::New(); + newMitkImage->InitializeByItk(newImage.GetPointer()); + newMitkImage->SetVolume(newImage->GetBufferPointer()); + + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( newMitkImage ); + QString name = m_SelectedImageNode->GetName().c_str(); + imageNode->SetName((name+"_newdirection").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedImageNode); + + mitk::RenderingManager::GetInstance()->InitializeViews( m_SelectedImageNode->GetData()->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); + mitk::RenderingManager::GetInstance()->RequestUpdateAll(); +} + +void QmitkPreprocessingView::DoProjectSignal() +{ + switch(m_Controls->m_ProjectionMethodBox->currentIndex()) + { + case 0: + DoADCAverage(); + break; + case 1: + DoAKCFit(); + break; + case 2: + DoBiExpFit(); + break; + default: + DoADCAverage(); + } } void QmitkPreprocessingView::DoDwiNormalization() { if (m_DiffusionImage.IsNull()) - return; + return; typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; typedef itk::DwiNormilzationFilter<short> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(m_DiffusionImage->GetVectorImage()); filter->SetGradientDirections(m_DiffusionImage->GetDirections()); + if (m_Controls->m_NormalizationMethodBox->currentIndex()==1) + filter->SetUseGlobalMax(true); filter->Update(); DiffusionImageType::Pointer image = DiffusionImageType::New(); image->SetVectorImage( filter->GetOutput() ); image->SetReferenceBValue( m_DiffusionImage->GetReferenceBValue() ); image->SetDirections( m_DiffusionImage->GetDirections() ); image->InitializeFromVectorImage(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); - QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); + QString name = m_SelectedDiffusionNodes.back()->GetName().c_str(); imageNode->SetName((name+"_normalized").toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); } void QmitkPreprocessingView::DoLengthCorrection() { - if (m_DiffusionImage.IsNull()) - return; + if (m_DiffusionImage.IsNull()) + return; - typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; - typedef itk::DwiGradientLengthCorrectionFilter FilterType; + typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; + typedef itk::DwiGradientLengthCorrectionFilter FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetRoundingValue( m_Controls->m_B_ValueMap_Rounder_SpinBox->value()); - filter->SetReferenceBValue(m_DiffusionImage->GetReferenceBValue()); - filter->SetReferenceGradientDirectionContainer(m_DiffusionImage->GetDirections()); - filter->Update(); + FilterType::Pointer filter = FilterType::New(); + filter->SetRoundingValue( m_Controls->m_B_ValueMap_Rounder_SpinBox->value()); + filter->SetReferenceBValue(m_DiffusionImage->GetReferenceBValue()); + filter->SetReferenceGradientDirectionContainer(m_DiffusionImage->GetDirections()); + filter->Update(); - DiffusionImageType::Pointer image = DiffusionImageType::New(); - image->SetVectorImage( m_DiffusionImage->GetVectorImage()); - image->SetReferenceBValue( filter->GetNewBValue() ); - image->SetDirections( filter->GetOutputGradientDirectionContainer()); - image->InitializeFromVectorImage(); + DiffusionImageType::Pointer image = DiffusionImageType::New(); + image->SetVectorImage( m_DiffusionImage->GetVectorImage()); + image->SetReferenceBValue( filter->GetNewBValue() ); + image->SetDirections( filter->GetOutputGradientDirectionContainer()); + image->InitializeFromVectorImage(); - mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); - imageNode->SetData( image ); - QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + QString name = m_SelectedDiffusionNodes.back()->GetName().c_str(); - imageNode->SetName((name+"_rounded").toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); + imageNode->SetName((name+"_rounded").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); } void QmitkPreprocessingView::UpdateDwiBValueMapRounder(int i) { - if (m_DiffusionImage.IsNull()) - return; - //m_DiffusionImage->UpdateBValueMap(); - UpdateBValueTableWidget(i); + if (m_DiffusionImage.IsNull()) + return; + //m_DiffusionImage->UpdateBValueMap(); + UpdateBValueTableWidget(i); } -void QmitkPreprocessingView::CallMultishellToSingleShellFilter(itk::DWIVoxelFunctor * functor, mitk::DiffusionImage<DiffusionPixelType>::Pointer ImPtr, QString imageName) +void QmitkPreprocessingView::CallMultishellToSingleShellFilter(itk::DWIVoxelFunctor * functor, mitk::DiffusionImage<DiffusionPixelType>::Pointer ImPtr, QString imageName, mitk::DataNode* parent) { - typedef itk::RadialMultishellToSingleshellImageFilter<DiffusionPixelType, DiffusionPixelType> FilterType; - - // filter input parameter - const mitk::DiffusionImage<DiffusionPixelType>::BValueMap - &originalShellMap = ImPtr->GetBValueMap(); + typedef itk::RadialMultishellToSingleshellImageFilter<DiffusionPixelType, DiffusionPixelType> FilterType; - const mitk::DiffusionImage<DiffusionPixelType>::ImageType - *vectorImage = ImPtr->GetVectorImage(); + // filter input parameter + const mitk::DiffusionImage<DiffusionPixelType>::BValueMap + &originalShellMap = ImPtr->GetBValueMap(); - const mitk::DiffusionImage<DiffusionPixelType>::GradientDirectionContainerType::Pointer - gradientContainer = ImPtr->GetDirections(); + const mitk::DiffusionImage<DiffusionPixelType>::ImageType + *vectorImage = ImPtr->GetVectorImage(); - const unsigned int - &bValue = ImPtr->GetReferenceBValue(); + const mitk::DiffusionImage<DiffusionPixelType>::GradientDirectionContainerType::Pointer + gradientContainer = ImPtr->GetDirections(); - mitk::DataNode::Pointer imageNode = 0; + const unsigned int + &bValue = ImPtr->GetReferenceBValue(); - // filter call - FilterType::Pointer filter = FilterType::New(); - filter->SetInput(vectorImage); - filter->SetOriginalGradientDirections(gradientContainer); - filter->SetOriginalBValueMap(originalShellMap); - filter->SetOriginalBValue(bValue); - filter->SetFunctor(functor); - filter->Update(); + mitk::DataNode::Pointer imageNode = 0; - // create new DWI image - mitk::DiffusionImage<DiffusionPixelType>::Pointer outImage = mitk::DiffusionImage<DiffusionPixelType>::New(); - outImage->SetVectorImage( filter->GetOutput() ); - outImage->SetReferenceBValue( m_Controls->m_targetBValueSpinBox->value() ); - outImage->SetDirections( filter->GetTargetGradientDirections() ); - outImage->InitializeFromVectorImage(); - - imageNode = mitk::DataNode::New(); - imageNode->SetData( outImage ); - imageNode->SetName(imageName.toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); + // filter call + FilterType::Pointer filter = FilterType::New(); + filter->SetInput(vectorImage); + filter->SetOriginalGradientDirections(gradientContainer); + filter->SetOriginalBValueMap(originalShellMap); + filter->SetOriginalBValue(bValue); + filter->SetFunctor(functor); + filter->Update(); - if(m_Controls->m_OutputRMSErrorImage->isChecked()){ - // create new Error image - FilterType::ErrorImageType::Pointer errImage = filter->GetErrorImage(); - mitk::Image::Pointer mitkErrImage = mitk::Image::New(); - mitkErrImage->InitializeByItk<FilterType::ErrorImageType>(errImage); - mitkErrImage->SetVolume(errImage->GetBufferPointer()); + // create new DWI image + mitk::DiffusionImage<DiffusionPixelType>::Pointer outImage = mitk::DiffusionImage<DiffusionPixelType>::New(); + outImage->SetVectorImage( filter->GetOutput() ); + outImage->SetReferenceBValue( m_Controls->m_targetBValueSpinBox->value() ); + outImage->SetDirections( filter->GetTargetGradientDirections() ); + outImage->InitializeFromVectorImage(); imageNode = mitk::DataNode::New(); - imageNode->SetData( mitkErrImage ); - imageNode->SetName((imageName+"_Error").toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); - } + imageNode->SetData( outImage ); + imageNode->SetName(imageName.toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, parent); + + // if(m_Controls->m_OutputRMSErrorImage->isChecked()){ + // // create new Error image + // FilterType::ErrorImageType::Pointer errImage = filter->GetErrorImage(); + // mitk::Image::Pointer mitkErrImage = mitk::Image::New(); + // mitkErrImage->InitializeByItk<FilterType::ErrorImageType>(errImage); + // mitkErrImage->SetVolume(errImage->GetBufferPointer()); + + // imageNode = mitk::DataNode::New(); + // imageNode->SetData( mitkErrImage ); + // imageNode->SetName((imageName+"_Error").toStdString().c_str()); + // GetDefaultDataStorage()->Add(imageNode); + // } } void QmitkPreprocessingView::DoBiExpFit() { - itk::BiExpFitFunctor::Pointer functor = itk::BiExpFitFunctor::New(); - - for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) - { - mitk::DiffusionImage<DiffusionPixelType>::Pointer inImage = - dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >(m_SelectedDiffusionNodes.at(i)->GetData()); - - QString name(m_SelectedDiffusionNodes.at(i)->GetName().c_str()); - - const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & originalShellMap = inImage->GetBValueMap(); - mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = originalShellMap.begin(); - ++it;/* skip b=0*/ unsigned int s = 0; /*shell index */ - vnl_vector<double> bValueList(originalShellMap.size()-1); - while(it != originalShellMap.end()) - bValueList.put(s++,(it++)->first); + itk::BiExpFitFunctor::Pointer functor = itk::BiExpFitFunctor::New(); - const double targetBValue = m_Controls->m_targetBValueSpinBox->value(); - functor->setListOfBValues(bValueList); - functor->setTargetBValue(targetBValue); - CallMultishellToSingleShellFilter(functor,inImage,name + "_BiExp"); - } + for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) + { + mitk::DiffusionImage<DiffusionPixelType>::Pointer inImage = + dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >(m_SelectedDiffusionNodes.at(i)->GetData()); + + QString name(m_SelectedDiffusionNodes.at(i)->GetName().c_str()); + + const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & originalShellMap = inImage->GetBValueMap(); + mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = originalShellMap.begin(); + ++it;/* skip b=0*/ unsigned int s = 0; /*shell index */ + vnl_vector<double> bValueList(originalShellMap.size()-1); + while(it != originalShellMap.end()) + bValueList.put(s++,(it++)->first); + + const double targetBValue = m_Controls->m_targetBValueSpinBox->value(); + functor->setListOfBValues(bValueList); + functor->setTargetBValue(targetBValue); + CallMultishellToSingleShellFilter(functor,inImage,name + "_BiExp", m_SelectedDiffusionNodes.at(i)); + } } void QmitkPreprocessingView::DoAKCFit() { - itk::KurtosisFitFunctor::Pointer functor = itk::KurtosisFitFunctor::New(); - - for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) - { - mitk::DiffusionImage<DiffusionPixelType>::Pointer inImage = - dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >(m_SelectedDiffusionNodes.at(i)->GetData()); + itk::KurtosisFitFunctor::Pointer functor = itk::KurtosisFitFunctor::New(); - QString name(m_SelectedDiffusionNodes.at(i)->GetName().c_str()); - - const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & originalShellMap = inImage->GetBValueMap(); - mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = originalShellMap.begin(); - ++it;/* skip b=0*/ unsigned int s = 0; /*shell index */ - vnl_vector<double> bValueList(originalShellMap.size()-1); - while(it != originalShellMap.end()) - bValueList.put(s++,(it++)->first); - - const double targetBValue = m_Controls->m_targetBValueSpinBox->value(); - functor->setListOfBValues(bValueList); - functor->setTargetBValue(targetBValue); - CallMultishellToSingleShellFilter(functor,inImage,name + "_AKC"); - } + for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) + { + mitk::DiffusionImage<DiffusionPixelType>::Pointer inImage = + dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >(m_SelectedDiffusionNodes.at(i)->GetData()); + + QString name(m_SelectedDiffusionNodes.at(i)->GetName().c_str()); + + const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & originalShellMap = inImage->GetBValueMap(); + mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = originalShellMap.begin(); + ++it;/* skip b=0*/ unsigned int s = 0; /*shell index */ + vnl_vector<double> bValueList(originalShellMap.size()-1); + while(it != originalShellMap.end()) + bValueList.put(s++,(it++)->first); + + const double targetBValue = m_Controls->m_targetBValueSpinBox->value(); + functor->setListOfBValues(bValueList); + functor->setTargetBValue(targetBValue); + CallMultishellToSingleShellFilter(functor,inImage,name + "_AKC", m_SelectedDiffusionNodes.at(i)); + } } void QmitkPreprocessingView::DoADCFit() { - // later + // later } void QmitkPreprocessingView::DoADCAverage() { - itk::ADCAverageFunctor::Pointer functor = itk::ADCAverageFunctor::New(); - - for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) - { - mitk::DiffusionImage<DiffusionPixelType>::Pointer inImage = - dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >(m_SelectedDiffusionNodes.at(i)->GetData()); - - QString name(m_SelectedDiffusionNodes.at(i)->GetName().c_str()); - - const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & originalShellMap = inImage->GetBValueMap(); - mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = originalShellMap.begin(); - ++it;/* skip b=0*/ unsigned int s = 0; /*shell index */ - vnl_vector<double> bValueList(originalShellMap.size()-1); - while(it != originalShellMap.end()) - bValueList.put(s++,(it++)->first); + itk::ADCAverageFunctor::Pointer functor = itk::ADCAverageFunctor::New(); - const double targetBValue = m_Controls->m_targetBValueSpinBox->value(); - functor->setListOfBValues(bValueList); - functor->setTargetBValue(targetBValue); - CallMultishellToSingleShellFilter(functor,inImage,name + "_ADC"); - } + for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) + { + mitk::DiffusionImage<DiffusionPixelType>::Pointer inImage = + dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >(m_SelectedDiffusionNodes.at(i)->GetData()); + + QString name(m_SelectedDiffusionNodes.at(i)->GetName().c_str()); + + const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & originalShellMap = inImage->GetBValueMap(); + mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = originalShellMap.begin(); + ++it;/* skip b=0*/ unsigned int s = 0; /*shell index */ + vnl_vector<double> bValueList(originalShellMap.size()-1); + while(it != originalShellMap.end()) + bValueList.put(s++,(it++)->first); + + const double targetBValue = m_Controls->m_targetBValueSpinBox->value(); + functor->setListOfBValues(bValueList); + functor->setTargetBValue(targetBValue); + CallMultishellToSingleShellFilter(functor,inImage,name + "_ADC", m_SelectedDiffusionNodes.at(i)); + } } void QmitkPreprocessingView::DoAdcCalculation() { - if (m_DiffusionImage.IsNull()) - return; - - typedef mitk::DiffusionImage< DiffusionPixelType > DiffusionImageType; - typedef itk::AdcImageFilter< DiffusionPixelType, double > FilterType; + if (m_DiffusionImage.IsNull()) + return; + typedef mitk::DiffusionImage< DiffusionPixelType > DiffusionImageType; + typedef itk::AdcImageFilter< DiffusionPixelType, double > FilterType; - for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) - { - DiffusionImageType::Pointer inImage = dynamic_cast< DiffusionImageType* >(m_SelectedDiffusionNodes.at(i)->GetData()); - FilterType::Pointer filter = FilterType::New(); - filter->SetInput(inImage->GetVectorImage()); - filter->SetGradientDirections(inImage->GetDirections()); - filter->SetB_value(inImage->GetReferenceBValue()); - filter->Update(); - mitk::Image::Pointer image = mitk::Image::New(); - image->InitializeByItk( filter->GetOutput() ); - image->SetVolume( filter->GetOutput()->GetBufferPointer() ); - mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); - imageNode->SetData( image ); - QString name = m_SelectedDiffusionNodes.at(i)->GetName().c_str(); - - imageNode->SetName((name+"_ADC").toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); - } + for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) + { + DiffusionImageType::Pointer inImage = dynamic_cast< DiffusionImageType* >(m_SelectedDiffusionNodes.at(i)->GetData()); + FilterType::Pointer filter = FilterType::New(); + filter->SetInput(inImage->GetVectorImage()); + filter->SetGradientDirections(inImage->GetDirections()); + filter->SetB_value(inImage->GetReferenceBValue()); + filter->Update(); + + mitk::Image::Pointer image = mitk::Image::New(); + image->InitializeByItk( filter->GetOutput() ); + image->SetVolume( filter->GetOutput()->GetBufferPointer() ); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + QString name = m_SelectedDiffusionNodes.at(i)->GetName().c_str(); + + imageNode->SetName((name+"_ADC").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.at(i)); + } } void QmitkPreprocessingView::UpdateBValueTableWidget(int i) { - - foreach(QCheckBox * box, m_ReduceGradientCheckboxes) - { - m_Controls->m_ReductionFrame->layout()->removeWidget(box); - delete box; - } - foreach(QSpinBox * box, m_ReduceGradientSpinboxes) - { - m_Controls->m_ReductionFrame->layout()->removeWidget(box); - delete box; - } - m_ReduceGradientCheckboxes.clear(); - m_ReduceGradientSpinboxes.clear(); - - if (m_DiffusionImage.IsNull()) - { - m_Controls->m_B_ValueMap_TableWidget->clear(); - m_Controls->m_B_ValueMap_TableWidget->setRowCount(1); - QStringList headerList; - headerList << "b-Value" << "Number of gradients"; - m_Controls->m_B_ValueMap_TableWidget->setHorizontalHeaderLabels(headerList); - m_Controls->m_B_ValueMap_TableWidget->setItem(0,0,new QTableWidgetItem("-")); - m_Controls->m_B_ValueMap_TableWidget->setItem(0,1,new QTableWidgetItem("-")); - }else{ - - typedef mitk::DiffusionImage<short>::BValueMap BValueMap; - typedef mitk::DiffusionImage<short>::BValueMap::iterator BValueMapIterator; - - BValueMapIterator it; - - BValueMap roundedBValueMap = m_DiffusionImage->GetBValueMap(); - - m_Controls->m_B_ValueMap_TableWidget->clear(); - m_Controls->m_B_ValueMap_TableWidget->setRowCount(roundedBValueMap.size() ); - QStringList headerList; - headerList << "b-Value" << "Number of gradients"; - m_Controls->m_B_ValueMap_TableWidget->setHorizontalHeaderLabels(headerList); - - - QCheckBox* checkBox; - QSpinBox* spinBox; - int i = 0 ; - for(it = roundedBValueMap.begin() ;it != roundedBValueMap.end(); it++) + if (m_DiffusionImage.IsNull()) { - m_Controls->m_B_ValueMap_TableWidget->setItem(i,0,new QTableWidgetItem(QString::number(it->first))); - m_Controls->m_B_ValueMap_TableWidget->setItem(i,1,new QTableWidgetItem(QString::number(it->second.size()))); + m_Controls->m_B_ValueMap_TableWidget->clear(); + m_Controls->m_B_ValueMap_TableWidget->setRowCount(1); + QStringList headerList; + headerList << "b-Value" << "Number of gradients"; + m_Controls->m_B_ValueMap_TableWidget->setHorizontalHeaderLabels(headerList); + m_Controls->m_B_ValueMap_TableWidget->setItem(0,0,new QTableWidgetItem("-")); + m_Controls->m_B_ValueMap_TableWidget->setItem(0,1,new QTableWidgetItem("-")); + }else{ + + typedef mitk::DiffusionImage<short>::BValueMap BValueMap; + typedef mitk::DiffusionImage<short>::BValueMap::iterator BValueMapIterator; + + BValueMapIterator it; + + BValueMap roundedBValueMap = m_DiffusionImage->GetBValueMap(); + + m_Controls->m_B_ValueMap_TableWidget->clear(); + m_Controls->m_B_ValueMap_TableWidget->setRowCount(roundedBValueMap.size() ); + QStringList headerList; + headerList << "b-Value" << "Number of gradients"; + m_Controls->m_B_ValueMap_TableWidget->setHorizontalHeaderLabels(headerList); + + int i = 0 ; + for(it = roundedBValueMap.begin() ;it != roundedBValueMap.end(); it++) + { + m_Controls->m_B_ValueMap_TableWidget->setItem(i,0,new QTableWidgetItem(QString::number(it->first))); + QTableWidgetItem* item = m_Controls->m_B_ValueMap_TableWidget->item(i,0); + item->setFlags(item->flags() & ~Qt::ItemIsEditable); + m_Controls->m_B_ValueMap_TableWidget->setItem(i,1,new QTableWidgetItem(QString::number(it->second.size()))); + i++; + } + } - // Reduce Gradients GUI adaption - if(roundedBValueMap.size() > 1){ - checkBox = new QCheckBox(QString::number(it->first) + " with " + QString::number(it->second.size()) + " directions"); - checkBox->setEnabled(true); - checkBox->setChecked(true); - checkBox->setCheckable(true); - m_ReduceGradientCheckboxes.push_back(checkBox); - m_Controls->m_ReductionFrame->layout()->addWidget(checkBox); +} - spinBox = new QSpinBox(); - spinBox->setMaximum(it->second.size()); - spinBox->setValue(std::ceil((float)it->second.size())); - spinBox->setMinimum(0); - m_ReduceGradientSpinboxes.push_back(spinBox); - m_Controls->m_ReductionFrame->layout()->addWidget(spinBox); - } - i++; - } - } +template < typename TPixel, unsigned int VImageDimension > +void QmitkPreprocessingView::TemplatedUpdateGui( itk::Image<TPixel, VImageDimension>* itkImage) +{ + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + QTableWidgetItem* item = m_Controls->m_DirectionMatrixTable->item(r,c); + delete item; + item = new QTableWidgetItem(); + item->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); + item->setText(QString::number(itkImage->GetDirection()[r][c])); + m_Controls->m_DirectionMatrixTable->setItem(r,c,item); + } } void QmitkPreprocessingView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes ) { - bool foundDwiVolume = false; - m_DiffusionImage = NULL; - m_SelectedDiffusionNodes.clear(); - - // iterate selection - for( std::vector<mitk::DataNode*>::iterator it = nodes.begin(); it != nodes.end(); ++it ) - { - mitk::DataNode::Pointer node = *it; - - if( node.IsNotNull() && dynamic_cast<mitk::DiffusionImage<short>*>(node->GetData()) ) - { - foundDwiVolume = true; - m_DiffusionImage = dynamic_cast<mitk::DiffusionImage<DiffusionPixelType>*>(node->GetData()); - m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); - m_SelectedDiffusionNodes.push_back(node); - } - } - - m_Controls->m_ButtonAverageGradients->setEnabled(foundDwiVolume); - m_Controls->m_ButtonExtractB0->setEnabled(foundDwiVolume); - m_Controls->m_CheckExtractAll->setEnabled(foundDwiVolume); - m_Controls->m_ModifyMeasurementFrame->setEnabled(foundDwiVolume); - m_Controls->m_MeasurementFrameTable->setEnabled(foundDwiVolume); - m_Controls->m_ReduceGradientsButton->setEnabled(foundDwiVolume); - m_Controls->m_ShowGradientsButton->setEnabled(foundDwiVolume); - m_Controls->m_MirrorGradientToHalfSphereButton->setEnabled(foundDwiVolume); - m_Controls->m_MergeDwisButton->setEnabled(foundDwiVolume); - m_Controls->m_B_ValueMap_Rounder_SpinBox->setEnabled(foundDwiVolume); - //m_Controls->m_AdcSignalFit->setEnabled(foundDwiVolume); - m_Controls->m_AdcSignalAverage->setEnabled(foundDwiVolume); - m_Controls->m_AkcSignalFit->setEnabled(foundDwiVolume); - m_Controls->m_BiExpSignalFit->setEnabled(foundDwiVolume); - m_Controls->m_CreateLengthCorrectedDwi->setEnabled(foundDwiVolume); - m_Controls->m_CalcAdcButton->setEnabled(foundDwiVolume); - m_Controls->m_targetBValueSpinBox->setEnabled(foundDwiVolume); - m_Controls->m_OutputRMSErrorImage->setEnabled(foundDwiVolume); - m_Controls->m_NormalizeImageValuesButton->setEnabled(foundDwiVolume); - - // reset sampling frame to 1 and update all ealted components - m_Controls->m_B_ValueMap_Rounder_SpinBox->setValue(1); - - UpdateBValueTableWidget(m_Controls->m_B_ValueMap_Rounder_SpinBox->value()); - - if (foundDwiVolume) - { - m_Controls->m_InputData->setTitle("Input Data"); - vnl_matrix_fixed< double, 3, 3 > mf = m_DiffusionImage->GetMeasurementFrame(); - for (int r=0; r<3; r++) - for (int c=0; c<3; c++) - { - QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); - delete item; - item = new QTableWidgetItem(); - item->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); - item->setText(QString::number(mf.get(r,c))); - m_Controls->m_MeasurementFrameTable->setItem(r,c,item); - } - //calculate target bValue for MultishellToSingleShellfilter - const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & bValMap = m_DiffusionImage->GetBValueMap(); - mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = bValMap.begin(); - unsigned int targetBVal = 0; - while(it != bValMap.end()) - targetBVal += (it++)->first; - targetBVal /= (float)bValMap.size()-1; - m_Controls->m_targetBValueSpinBox->setValue(targetBVal); - - } - else - { - for (int r=0; r<3; r++) - for (int c=0; c<3; c++) - { - QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); - delete item; - item = new QTableWidgetItem(); - m_Controls->m_MeasurementFrameTable->setItem(r,c,item); - } + bool foundDwiVolume = false; + bool foundImageVolume = false; + m_DiffusionImage = NULL; + m_SelectedImage = NULL; + m_SelectedImageNode = NULL; + m_SelectedDiffusionNodes.clear(); + + // iterate selection + for( std::vector<mitk::DataNode*>::iterator it = nodes.begin(); it != nodes.end(); ++it ) + { + mitk::DataNode::Pointer node = *it; + + if( node.IsNotNull() && dynamic_cast<mitk::DiffusionImage<short>*>(node->GetData()) ) + { + foundDwiVolume = true; + foundImageVolume = true; + m_DiffusionImage = dynamic_cast<mitk::DiffusionImage<DiffusionPixelType>*>(node->GetData()); + m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); + m_SelectedDiffusionNodes.push_back(node); + } + else if( node.IsNotNull() && dynamic_cast<mitk::Image*>(node->GetData()) ) + { + foundImageVolume = true; + m_SelectedImage = dynamic_cast<mitk::Image*>(node->GetData()); + m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); + m_SelectedImageNode = node; + } + } + + m_Controls->m_ButtonAverageGradients->setEnabled(foundDwiVolume); + m_Controls->m_ButtonExtractB0->setEnabled(foundDwiVolume); + m_Controls->m_CheckExtractAll->setEnabled(foundDwiVolume); + m_Controls->m_ModifyMeasurementFrame->setEnabled(foundDwiVolume); + m_Controls->m_MeasurementFrameTable->setEnabled(foundDwiVolume); + m_Controls->m_ReduceGradientsButton->setEnabled(foundDwiVolume); + m_Controls->m_ShowGradientsButton->setEnabled(foundDwiVolume); + m_Controls->m_MirrorGradientToHalfSphereButton->setEnabled(foundDwiVolume); + m_Controls->m_MergeDwisButton->setEnabled(foundDwiVolume); + m_Controls->m_B_ValueMap_Rounder_SpinBox->setEnabled(foundDwiVolume); + m_Controls->m_ProjectSignalButton->setEnabled(foundDwiVolume); + m_Controls->m_CreateLengthCorrectedDwi->setEnabled(foundDwiVolume); + m_Controls->m_CalcAdcButton->setEnabled(foundDwiVolume); + m_Controls->m_targetBValueSpinBox->setEnabled(foundDwiVolume); + m_Controls->m_NormalizeImageValuesButton->setEnabled(foundDwiVolume); + m_Controls->m_DirectionMatrixTable->setEnabled(foundImageVolume); + m_Controls->m_ModifyDirection->setEnabled(foundImageVolume); + m_Controls->m_ExtractBrainMask->setEnabled(foundImageVolume); + m_Controls->m_ResampleImageButton->setEnabled(foundImageVolume); + + // reset sampling frame to 1 and update all ealted components + m_Controls->m_B_ValueMap_Rounder_SpinBox->setValue(1); + + UpdateBValueTableWidget(m_Controls->m_B_ValueMap_Rounder_SpinBox->value()); + DoUpdateInterpolationGui(m_Controls->m_ResampleTypeBox->currentIndex()); + + if (foundDwiVolume) + { + m_Controls->m_InputData->setTitle("Input Data"); + vnl_matrix_fixed< double, 3, 3 > mf = m_DiffusionImage->GetMeasurementFrame(); + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + // Measurement frame + { + QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); + delete item; + item = new QTableWidgetItem(); + item->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); + item->setText(QString::number(mf.get(r,c))); + m_Controls->m_MeasurementFrameTable->setItem(r,c,item); + } + + // Direction matrix + { + QTableWidgetItem* item = m_Controls->m_DirectionMatrixTable->item(r,c); + delete item; + item = new QTableWidgetItem(); + item->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); + item->setText(QString::number(m_DiffusionImage->GetVectorImage()->GetDirection()[r][c])); + m_Controls->m_DirectionMatrixTable->setItem(r,c,item); + } + } + + //calculate target bValue for MultishellToSingleShellfilter + const mitk::DiffusionImage<DiffusionPixelType>::BValueMap & bValMap = m_DiffusionImage->GetBValueMap(); + mitk::DiffusionImage<DiffusionPixelType>::BValueMap::const_iterator it = bValMap.begin(); + unsigned int targetBVal = 0; + while(it != bValMap.end()) + targetBVal += (it++)->first; + targetBVal /= (float)bValMap.size()-1; + m_Controls->m_targetBValueSpinBox->setValue(targetBVal); - m_Controls->m_DiffusionImageLabel->setText("<font color='red'>mandatory</font>"); - m_Controls->m_InputData->setTitle("Please Select Input Data"); - } + } + else if (foundImageVolume) + { + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); + delete item; + item = new QTableWidgetItem(); + m_Controls->m_MeasurementFrameTable->setItem(r,c,item); + } + + AccessFixedDimensionByItk(m_SelectedImage, TemplatedUpdateGui,3); + } + else + { + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + { + QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); + delete item; + item = new QTableWidgetItem(); + m_Controls->m_MeasurementFrameTable->setItem(r,c,item); + } + { + QTableWidgetItem* item = m_Controls->m_DirectionMatrixTable->item(r,c); + delete item; + item = new QTableWidgetItem(); + m_Controls->m_DirectionMatrixTable->setItem(r,c,item); + } + } + + m_Controls->m_DiffusionImageLabel->setText("<font color='red'>mandatory</font>"); + m_Controls->m_InputData->setTitle("Please Select Input Data"); + } } void QmitkPreprocessingView::Activated() { - QmitkFunctionality::Activated(); + QmitkFunctionality::Activated(); } void QmitkPreprocessingView::Deactivated() { - QmitkFunctionality::Deactivated(); + QmitkFunctionality::Deactivated(); } void QmitkPreprocessingView::DoHalfSphereGradientDirections() { - GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); - for (unsigned int j=0; j<gradientContainer->Size(); j++) - if (gradientContainer->at(j)[0]<0) - gradientContainer->at(j) = -gradientContainer->at(j); - m_DiffusionImage->SetDirections(gradientContainer); + MitkDwiType::Pointer newDwi = m_DiffusionImage->Clone(); + GradientDirectionContainerType::Pointer gradientContainer = newDwi->GetDirections(); + + for (unsigned int j=0; j<gradientContainer->Size(); j++) + if (gradientContainer->at(j)[0]<0) + gradientContainer->at(j) = -gradientContainer->at(j); + + newDwi->SetDirections(gradientContainer); + + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( newDwi ); + QString name = m_SelectedDiffusionNodes.back()->GetName().c_str(); + imageNode->SetName((name+"_halfsphere").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); } void QmitkPreprocessingView::DoApplyMesurementFrame() { - if (m_DiffusionImage.IsNull()) - return; - - vnl_matrix_fixed< double, 3, 3 > mf; - for (int r=0; r<3; r++) - for (int c=0; c<3; c++) - { - QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); - if (!item) + if (m_DiffusionImage.IsNull()) return; - mf[r][c] = item->text().toDouble(); - } - m_DiffusionImage->SetMeasurementFrame(mf); + + vnl_matrix_fixed< double, 3, 3 > mf; + for (int r=0; r<3; r++) + for (int c=0; c<3; c++) + { + QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); + if (!item) + return; + mf[r][c] = item->text().toDouble(); + } + + MitkDwiType::Pointer newDwi = m_DiffusionImage->Clone(); + newDwi->SetMeasurementFrame(mf); + + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( newDwi ); + QString name = m_SelectedDiffusionNodes.back()->GetName().c_str(); + imageNode->SetName((name+"_new-MF").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); } void QmitkPreprocessingView::DoShowGradientDirections() { - if (m_DiffusionImage.IsNull()) - return; - - int maxIndex = 0; - unsigned int maxSize = m_DiffusionImage->GetDimension(0); - if (maxSize<m_DiffusionImage->GetDimension(1)) - { - maxSize = m_DiffusionImage->GetDimension(1); - maxIndex = 1; - } - if (maxSize<m_DiffusionImage->GetDimension(2)) - { - maxSize = m_DiffusionImage->GetDimension(2); - maxIndex = 2; - } - - mitk::Point3D origin = m_DiffusionImage->GetGeometry()->GetOrigin(); - mitk::PointSet::Pointer originSet = mitk::PointSet::New(); - - typedef mitk::DiffusionImage<short>::BValueMap BValueMap; - typedef mitk::DiffusionImage<short>::BValueMap::iterator BValueMapIterator; - BValueMap bValMap = m_DiffusionImage->GetBValueMap(); - - GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); - mitk::BaseGeometry::Pointer geometry = m_DiffusionImage->GetGeometry(); - int shellCount = 1; - for(BValueMapIterator it = bValMap.begin(); it!=bValMap.end(); ++it) - { - mitk::PointSet::Pointer pointset = mitk::PointSet::New(); - for (unsigned int j=0; j<it->second.size(); j++) - { - mitk::Point3D ip; - vnl_vector_fixed< double, 3 > v = gradientContainer->at(it->second[j]); - if (v.magnitude()>mitk::eps) - { - ip[0] = v[0]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[0]-0.5*geometry->GetSpacing()[0] + geometry->GetSpacing()[0]*m_DiffusionImage->GetDimension(0)/2; - ip[1] = v[1]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[1]-0.5*geometry->GetSpacing()[1] + geometry->GetSpacing()[1]*m_DiffusionImage->GetDimension(1)/2; - ip[2] = v[2]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[2]-0.5*geometry->GetSpacing()[2] + geometry->GetSpacing()[2]*m_DiffusionImage->GetDimension(2)/2; - - pointset->InsertPoint(j, ip); - } - else if (originSet->IsEmpty()) - { - ip[0] = v[0]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[0]-0.5*geometry->GetSpacing()[0] + geometry->GetSpacing()[0]*m_DiffusionImage->GetDimension(0)/2; - ip[1] = v[1]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[1]-0.5*geometry->GetSpacing()[1] + geometry->GetSpacing()[1]*m_DiffusionImage->GetDimension(1)/2; - ip[2] = v[2]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[2]-0.5*geometry->GetSpacing()[2] + geometry->GetSpacing()[2]*m_DiffusionImage->GetDimension(2)/2; - - originSet->InsertPoint(j, ip); - } - } - if (it->first<mitk::eps) - continue; - - // add shell to datastorage + if (m_DiffusionImage.IsNull()) + return; + + int maxIndex = 0; + unsigned int maxSize = m_DiffusionImage->GetDimension(0); + if (maxSize<m_DiffusionImage->GetDimension(1)) + { + maxSize = m_DiffusionImage->GetDimension(1); + maxIndex = 1; + } + if (maxSize<m_DiffusionImage->GetDimension(2)) + { + maxSize = m_DiffusionImage->GetDimension(2); + maxIndex = 2; + } + + mitk::Point3D origin = m_DiffusionImage->GetGeometry()->GetOrigin(); + mitk::PointSet::Pointer originSet = mitk::PointSet::New(); + + typedef mitk::DiffusionImage<short>::BValueMap BValueMap; + typedef mitk::DiffusionImage<short>::BValueMap::iterator BValueMapIterator; + BValueMap bValMap = m_DiffusionImage->GetBValueMap(); + + GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); + mitk::BaseGeometry::Pointer geometry = m_DiffusionImage->GetGeometry(); + int shellCount = 1; + for(BValueMapIterator it = bValMap.begin(); it!=bValMap.end(); ++it) + { + mitk::PointSet::Pointer pointset = mitk::PointSet::New(); + for (unsigned int j=0; j<it->second.size(); j++) + { + mitk::Point3D ip; + vnl_vector_fixed< double, 3 > v = gradientContainer->at(it->second[j]); + if (v.magnitude()>mitk::eps) + { + ip[0] = v[0]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[0]-0.5*geometry->GetSpacing()[0] + geometry->GetSpacing()[0]*m_DiffusionImage->GetDimension(0)/2; + ip[1] = v[1]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[1]-0.5*geometry->GetSpacing()[1] + geometry->GetSpacing()[1]*m_DiffusionImage->GetDimension(1)/2; + ip[2] = v[2]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[2]-0.5*geometry->GetSpacing()[2] + geometry->GetSpacing()[2]*m_DiffusionImage->GetDimension(2)/2; + + pointset->InsertPoint(j, ip); + } + else if (originSet->IsEmpty()) + { + ip[0] = v[0]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[0]-0.5*geometry->GetSpacing()[0] + geometry->GetSpacing()[0]*m_DiffusionImage->GetDimension(0)/2; + ip[1] = v[1]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[1]-0.5*geometry->GetSpacing()[1] + geometry->GetSpacing()[1]*m_DiffusionImage->GetDimension(1)/2; + ip[2] = v[2]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[2]-0.5*geometry->GetSpacing()[2] + geometry->GetSpacing()[2]*m_DiffusionImage->GetDimension(2)/2; + + originSet->InsertPoint(j, ip); + } + } + if (it->first<mitk::eps) + continue; + + // add shell to datastorage + mitk::DataNode::Pointer node = mitk::DataNode::New(); + node->SetData(pointset); + QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); + name += "_Shell_"; + name += QString::number(it->first); + node->SetName(name.toStdString().c_str()); + node->SetProperty("pointsize", mitk::FloatProperty::New((float)maxSize/50)); + int b0 = shellCount%2; + int b1 = 0; + int b2 = 0; + if (shellCount>4) + b2 = 1; + if (shellCount%4 >= 2) + b1 = 1; + + node->SetProperty("color", mitk::ColorProperty::New(b2, b1, b0)); + GetDefaultDataStorage()->Add(node, m_SelectedDiffusionNodes.front()); + shellCount++; + } + + // add origin to datastorage mitk::DataNode::Pointer node = mitk::DataNode::New(); - node->SetData(pointset); + node->SetData(originSet); QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); - name += "_Shell_"; - name += QString::number(it->first); + name += "_Origin"; node->SetName(name.toStdString().c_str()); node->SetProperty("pointsize", mitk::FloatProperty::New((float)maxSize/50)); - int b0 = shellCount%2; - int b1 = 0; - int b2 = 0; - if (shellCount>4) - b2 = 1; - if (shellCount%4 >= 2) - b1 = 1; - - node->SetProperty("color", mitk::ColorProperty::New(b2, b1, b0)); + node->SetProperty("color", mitk::ColorProperty::New(1,1,1)); GetDefaultDataStorage()->Add(node, m_SelectedDiffusionNodes.front()); - shellCount++; - } - - // add origin to datastorage - mitk::DataNode::Pointer node = mitk::DataNode::New(); - node->SetData(originSet); - QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); - name += "_Origin"; - node->SetName(name.toStdString().c_str()); - node->SetProperty("pointsize", mitk::FloatProperty::New((float)maxSize/50)); - node->SetProperty("color", mitk::ColorProperty::New(1,1,1)); - GetDefaultDataStorage()->Add(node, m_SelectedDiffusionNodes.front()); } void QmitkPreprocessingView::DoReduceGradientDirections() { - if (m_DiffusionImage.IsNull()) - return; + if (m_DiffusionImage.IsNull()) + return; - typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; - typedef itk::ElectrostaticRepulsionDiffusionGradientReductionFilter<DiffusionPixelType, DiffusionPixelType> FilterType; - typedef DiffusionImageType::BValueMap BValueMap; + typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; + typedef itk::ElectrostaticRepulsionDiffusionGradientReductionFilter<DiffusionPixelType, DiffusionPixelType> FilterType; + typedef DiffusionImageType::BValueMap BValueMap; - // GetShellSelection from GUI - BValueMap shellSlectionMap; - BValueMap originalShellMap = m_DiffusionImage->GetBValueMap(); - std::vector<unsigned int> newNumGradientDirections; - int shellCounter = 0; + // GetShellSelection from GUI + BValueMap shellSlectionMap; + BValueMap originalShellMap = m_DiffusionImage->GetBValueMap(); + std::vector<unsigned int> newNumGradientDirections; + int shellCounter = 0; - foreach(QCheckBox * box , m_ReduceGradientCheckboxes) - { - if(box->isChecked()) + QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); + for (int i=0; i<m_Controls->m_B_ValueMap_TableWidget->rowCount(); i++) { - double BValue = (box->text().split(' ')).at(0).toDouble(); - shellSlectionMap[BValue] = originalShellMap[BValue]; - newNumGradientDirections.push_back(m_ReduceGradientSpinboxes.at(shellCounter)->value()); + double BValue = m_Controls->m_B_ValueMap_TableWidget->item(i,0)->text().toDouble(); + shellSlectionMap[BValue] = originalShellMap[BValue]; + unsigned int num = m_Controls->m_B_ValueMap_TableWidget->item(i,1)->text().toUInt(); + newNumGradientDirections.push_back(num); + name += "_"; + name += QString::number(num); + shellCounter++; } - shellCounter++; - } - if (newNumGradientDirections.empty()) - return; + if (newNumGradientDirections.empty()) + return; + + GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); + FilterType::Pointer filter = FilterType::New(); + filter->SetInput(m_DiffusionImage->GetVectorImage()); + filter->SetOriginalGradientDirections(gradientContainer); + filter->SetNumGradientDirections(newNumGradientDirections); + filter->SetOriginalBValueMap(originalShellMap); + filter->SetShellSelectionBValueMap(shellSlectionMap); + filter->Update(); - GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); - FilterType::Pointer filter = FilterType::New(); - filter->SetInput(m_DiffusionImage->GetVectorImage()); - filter->SetOriginalGradientDirections(gradientContainer); - filter->SetNumGradientDirections(newNumGradientDirections); - filter->SetOriginalBValueMap(originalShellMap); - filter->SetShellSelectionBValueMap(shellSlectionMap); - filter->Update(); + DiffusionImageType::Pointer image = DiffusionImageType::New(); + image->SetVectorImage( filter->GetOutput() ); + image->SetReferenceBValue(m_DiffusionImage->GetReferenceBValue()); + image->SetDirections(filter->GetGradientDirections()); + image->SetMeasurementFrame(m_DiffusionImage->GetMeasurementFrame()); + image->InitializeFromVectorImage(); - DiffusionImageType::Pointer image = DiffusionImageType::New(); - image->SetVectorImage( filter->GetOutput() ); - image->SetReferenceBValue(m_DiffusionImage->GetReferenceBValue()); - image->SetDirections(filter->GetGradientDirections()); - image->SetMeasurementFrame(m_DiffusionImage->GetMeasurementFrame()); - image->InitializeFromVectorImage(); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + + imageNode->SetName(name.toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, m_SelectedDiffusionNodes.back()); +} + +void QmitkPreprocessingView::MergeDwis() +{ + typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; + typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; + + if (m_SelectedDiffusionNodes.size()<2) + return; - mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); - imageNode->SetData( image ); - QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); + typedef itk::VectorImage<DiffusionPixelType,3> DwiImageType; + typedef DwiImageType::PixelType DwiPixelType; + typedef DwiImageType::RegionType DwiRegionType; + typedef std::vector< DwiImageType::Pointer > DwiImageContainerType; + typedef std::vector< GradientContainerType::Pointer > GradientListContainerType; - QList<QSpinBox*>::iterator itSpinBox = m_ReduceGradientSpinboxes.begin(); - QList<QCheckBox*>::iterator itCheckBox = m_ReduceGradientCheckboxes.begin(); - while(itSpinBox != m_ReduceGradientSpinboxes.end() && itCheckBox != m_ReduceGradientCheckboxes.end()) - { + DwiImageContainerType imageContainer; + GradientListContainerType gradientListContainer; + std::vector< double > bValueContainer; - name += "_"; - if((*itCheckBox)->isChecked()){ - name += QString::number((*itSpinBox)->value()); - }else + QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); + for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) { - name += QString::number(0); + DiffusionImageType::Pointer dwi = dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >( m_SelectedDiffusionNodes.at(i)->GetData() ); + if ( dwi.IsNotNull() ) + { + imageContainer.push_back(dwi->GetVectorImage()); + gradientListContainer.push_back(dwi->GetDirections()); + bValueContainer.push_back(dwi->GetReferenceBValue()); + if (i>0) + { + name += "+"; + name += m_SelectedDiffusionNodes.at(i)->GetName().c_str(); + } + } } - ++itSpinBox; - ++itCheckBox; - } - imageNode->SetName(name.toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); -} -void QmitkPreprocessingView::MergeDwis() -{ - typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; - typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; - - if (m_SelectedDiffusionNodes.size()<2) - return; - - typedef itk::VectorImage<DiffusionPixelType,3> DwiImageType; - typedef DwiImageType::PixelType DwiPixelType; - typedef DwiImageType::RegionType DwiRegionType; - typedef std::vector< DwiImageType::Pointer > DwiImageContainerType; - - typedef std::vector< GradientContainerType::Pointer > GradientListContainerType; - - DwiImageContainerType imageContainer; - GradientListContainerType gradientListContainer; - std::vector< double > bValueContainer; - - QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); - for (unsigned int i=0; i<m_SelectedDiffusionNodes.size(); i++) - { - DiffusionImageType::Pointer dwi = dynamic_cast< mitk::DiffusionImage<DiffusionPixelType>* >( m_SelectedDiffusionNodes.at(i)->GetData() ); - if ( dwi.IsNotNull() ) - { - imageContainer.push_back(dwi->GetVectorImage()); - gradientListContainer.push_back(dwi->GetDirections()); - bValueContainer.push_back(dwi->GetReferenceBValue()); - if (i>0) - { - name += "+"; - name += m_SelectedDiffusionNodes.at(i)->GetName().c_str(); - } - } - } - - typedef itk::MergeDiffusionImagesFilter<short> FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetImageVolumes(imageContainer); - filter->SetGradientLists(gradientListContainer); - filter->SetBValues(bValueContainer); - filter->Update(); - - vnl_matrix_fixed< double, 3, 3 > mf; mf.set_identity(); - DiffusionImageType::Pointer image = DiffusionImageType::New(); - image->SetVectorImage( filter->GetOutput() ); - image->SetReferenceBValue(filter->GetB_Value()); - image->SetDirections(filter->GetOutputGradients()); - image->SetMeasurementFrame(mf); - image->InitializeFromVectorImage(); - - mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); - imageNode->SetData( image ); - imageNode->SetName(name.toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); + typedef itk::MergeDiffusionImagesFilter<short> FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetImageVolumes(imageContainer); + filter->SetGradientLists(gradientListContainer); + filter->SetBValues(bValueContainer); + filter->Update(); + + vnl_matrix_fixed< double, 3, 3 > mf; mf.set_identity(); + DiffusionImageType::Pointer image = DiffusionImageType::New(); + image->SetVectorImage( filter->GetOutput() ); + image->SetReferenceBValue(filter->GetB_Value()); + image->SetDirections(filter->GetOutputGradients()); + image->SetMeasurementFrame(mf); + image->InitializeFromVectorImage(); + + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + imageNode->SetName(name.toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode); } void QmitkPreprocessingView::ExtractB0() { - typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; - typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; + typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; + typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; - int nrFiles = m_SelectedDiffusionNodes.size(); - if (!nrFiles) return; + int nrFiles = m_SelectedDiffusionNodes.size(); + if (!nrFiles) return; - // call the extraction withou averaging if the check-box is checked - if( this->m_Controls->m_CheckExtractAll->isChecked() ) - { - DoExtractBOWithoutAveraging(); - return; - } + // call the extraction withou averaging if the check-box is checked + if( this->m_Controls->m_CheckExtractAll->isChecked() ) + { + DoExtractBOWithoutAveraging(); + return; + } - mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); - mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); + mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); + mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); - std::vector<mitk::DataNode::Pointer> nodes; - while ( itemiter != itemiterend ) // for all items - { + std::vector<mitk::DataNode::Pointer> nodes; + while ( itemiter != itemiterend ) // for all items + { - DiffusionImageType* vols = - static_cast<DiffusionImageType*>( - (*itemiter)->GetData()); + DiffusionImageType* vols = + static_cast<DiffusionImageType*>( + (*itemiter)->GetData()); - std::string nodename; - (*itemiter)->GetStringProperty("name", nodename); + std::string nodename; + (*itemiter)->GetStringProperty("name", nodename); - // Extract image using found index - typedef itk::B0ImageExtractionImageFilter<short, short> FilterType; - FilterType::Pointer filter = FilterType::New(); - filter->SetInput(vols->GetVectorImage()); - filter->SetDirections(vols->GetDirections()); - filter->Update(); + // Extract image using found index + typedef itk::B0ImageExtractionImageFilter<short, short> FilterType; + FilterType::Pointer filter = FilterType::New(); + filter->SetInput(vols->GetVectorImage()); + filter->SetDirections(vols->GetDirections()); + filter->Update(); - mitk::Image::Pointer mitkImage = mitk::Image::New(); - mitkImage->InitializeByItk( filter->GetOutput() ); - mitkImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); - mitk::DataNode::Pointer node=mitk::DataNode::New(); - node->SetData( mitkImage ); - node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0")); + mitk::Image::Pointer mitkImage = mitk::Image::New(); + mitkImage->InitializeByItk( filter->GetOutput() ); + mitkImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); + mitk::DataNode::Pointer node=mitk::DataNode::New(); + node->SetData( mitkImage ); + node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0")); - GetDefaultDataStorage()->Add(node); + GetDefaultDataStorage()->Add(node, (*itemiter)); - ++itemiter; - } + ++itemiter; + } } void QmitkPreprocessingView::DoExtractBOWithoutAveraging() { - // typedefs - typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; - typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; - typedef itk::B0ImageExtractionToSeparateImageFilter< short, short> FilterType; - - // check number of selected objects, return if empty - int nrFiles = m_SelectedDiffusionNodes.size(); - if (!nrFiles) - return; + // typedefs + typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageType; + typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; + typedef itk::B0ImageExtractionToSeparateImageFilter< short, short> FilterType; + + // check number of selected objects, return if empty + int nrFiles = m_SelectedDiffusionNodes.size(); + if (!nrFiles) + return; - mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); - mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); + mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); + mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); - while ( itemiter != itemiterend ) // for all items - { - DiffusionImageType* vols = - static_cast<DiffusionImageType*>( - (*itemiter)->GetData()); + while ( itemiter != itemiterend ) // for all items + { + DiffusionImageType* vols = + static_cast<DiffusionImageType*>( + (*itemiter)->GetData()); - std::string nodename; - (*itemiter)->GetStringProperty("name", nodename); + std::string nodename; + (*itemiter)->GetStringProperty("name", nodename); - // Extract image using found index - FilterType::Pointer filter = FilterType::New(); - filter->SetInput(vols->GetVectorImage()); - filter->SetDirections(vols->GetDirections()); - filter->Update(); + // Extract image using found index + FilterType::Pointer filter = FilterType::New(); + filter->SetInput(vols->GetVectorImage()); + filter->SetDirections(vols->GetDirections()); + filter->Update(); - mitk::Image::Pointer mitkImage = mitk::Image::New(); - mitkImage->InitializeByItk( filter->GetOutput() ); - mitkImage->SetImportChannel( filter->GetOutput()->GetBufferPointer() ); - mitk::DataNode::Pointer node=mitk::DataNode::New(); - node->SetData( mitkImage ); - node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0_ALL")); + mitk::Image::Pointer mitkImage = mitk::Image::New(); + mitkImage->InitializeByItk( filter->GetOutput() ); + mitkImage->SetImportChannel( filter->GetOutput()->GetBufferPointer() ); + mitk::DataNode::Pointer node=mitk::DataNode::New(); + node->SetData( mitkImage ); + node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0_ALL")); - GetDefaultDataStorage()->Add(node); + GetDefaultDataStorage()->Add(node, (*itemiter)); - /*A reinitialization is needed to access the time channels via the ImageNavigationController + /*A reinitialization is needed to access the time channels via the ImageNavigationController The Global-Geometry can not recognize the time channel without a re-init. (for a new selection in datamanger a automatically updated of the Global-Geometry should be done - if it contains the time channel)*/ - mitk::RenderingManager::GetInstance()->InitializeViews(node->GetData()->GetTimeGeometry(),mitk::RenderingManager::REQUEST_UPDATE_ALL, true); + mitk::RenderingManager::GetInstance()->InitializeViews(node->GetData()->GetTimeGeometry(),mitk::RenderingManager::REQUEST_UPDATE_ALL, true); - ++itemiter; - } + ++itemiter; + } } void QmitkPreprocessingView::AverageGradients() { - int nrFiles = m_SelectedDiffusionNodes.size(); - if (!nrFiles) return; + int nrFiles = m_SelectedDiffusionNodes.size(); + if (!nrFiles) return; - mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); - mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); + mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); + mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); - std::vector<mitk::DataNode::Pointer> nodes; - while ( itemiter != itemiterend ) // for all items - { + while ( itemiter != itemiterend ) // for all items + { + mitk::DiffusionImage<DiffusionPixelType>* mitkDwi = + static_cast<mitk::DiffusionImage<DiffusionPixelType>*>( + (*itemiter)->GetData()); - mitk::DiffusionImage<DiffusionPixelType>* vols = - static_cast<mitk::DiffusionImage<DiffusionPixelType>*>( - (*itemiter)->GetData()); + MitkDwiType::Pointer newDwi = mitkDwi->Clone(); + newDwi->AverageRedundantGradients(m_Controls->m_Blur->value()); - vols->AverageRedundantGradients(m_Controls->m_Blur->value()); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( newDwi ); + QString name = (*itemiter)->GetName().c_str(); + imageNode->SetName((name+"_averaged").toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode, (*itemiter)); - ++itemiter; - } + ++itemiter; + } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h index c47116f8e3..6cf54c9bd5 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.h @@ -1,122 +1,140 @@ /*=================================================================== 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 _QMITKPREPROCESSINGVIEW_H_INCLUDED #define _QMITKPREPROCESSINGVIEW_H_INCLUDED #include <QmitkFunctionality.h> #include <string> #include "ui_QmitkPreprocessingViewControls.h" #include "itkDWIVoxelFunctor.h" #include "mitkDiffusionImage.h" typedef short DiffusionPixelType; struct PrpSelListener; /*! * \ingroup org_mitk_gui_qt_preprocessing_internal * * \brief QmitkPreprocessingView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkPreprocessingView : public QmitkFunctionality { friend struct PrpSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; typedef vnl_vector_fixed< double, 3 > GradientDirectionType; typedef itk::VectorContainer< unsigned int, GradientDirectionType > GradientDirectionContainerType; + typedef mitk::DiffusionImage<short> MitkDwiType; + typedef itk::VectorImage< short, 3 > ItkDwiType; + typedef itk::ImageDuplicator< ItkDwiType > DwiDuplicatorType; QmitkPreprocessingView(); virtual ~QmitkPreprocessingView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); static const int nrconvkernels; protected slots: void AverageGradients(); void ExtractB0(); void MergeDwis(); + void DoApplyDirectionMatrix(); void DoApplyMesurementFrame(); void DoReduceGradientDirections(); void DoShowGradientDirections(); void DoHalfSphereGradientDirections(); - void DoADCAverage(); - void DoADCFit(); - void DoAKCFit(); - void DoBiExpFit(); void UpdateDwiBValueMapRounder(int i); void DoLengthCorrection(); void DoAdcCalculation(); void DoDwiNormalization(); + void DoProjectSignal(); + void DoExtractBrainMask(); + void DoResampleImage(); + void DoUpdateInterpolationGui(int i); protected: + + void DoADCFit(); + void DoAKCFit(); + void DoBiExpFit(); + void DoADCAverage(); + + template < typename TPixel, unsigned int VImageDimension > + void TemplatedApplyRotation( itk::Image<TPixel, VImageDimension>* itkImage); + + template < typename TPixel, unsigned int VImageDimension > + void TemplatedUpdateGui( itk::Image<TPixel, VImageDimension>* itkImage); + + template < typename TPixel, unsigned int VImageDimension > + void TemplatedResampleImage( itk::Image<TPixel, VImageDimension>* itkImage); + /** Called by ExtractB0 if check-box activated, extracts all b0 images without averaging */ void DoExtractBOWithoutAveraging(); void UpdateBValueTableWidget(int i); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector<mitk::DataNode*> nodes ); Ui::QmitkPreprocessingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); + mitk::DataNode::Pointer m_SelectedImageNode; + mitk::Image::Pointer m_SelectedImage; mitk::DiffusionImage<DiffusionPixelType>::Pointer m_DiffusionImage; std::vector< mitk::DataNode::Pointer > m_SelectedDiffusionNodes; - QList<QCheckBox*> m_ReduceGradientCheckboxes; - QList<QSpinBox*> m_ReduceGradientSpinboxes; - - void CallMultishellToSingleShellFilter(itk::DWIVoxelFunctor * functor, mitk::DiffusionImage<DiffusionPixelType>::Pointer ImPtr, QString imageName); + void CallMultishellToSingleShellFilter(itk::DWIVoxelFunctor * functor, mitk::DiffusionImage<DiffusionPixelType>::Pointer ImPtr, QString imageName, mitk::DataNode* parent); }; #endif // _QMITKPREPROCESSINGVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingViewControls.ui b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingViewControls.ui index 1385ca7647..57ad19ee2b 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingViewControls.ui +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingViewControls.ui @@ -1,729 +1,1128 @@ <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>QmitkPreprocessingViewControls</class> <widget class="QWidget" name="QmitkPreprocessingViewControls"> <property name="geometry"> <rect> <x>0</x> <y>0</y> - <width>892</width> - <height>1355</height> + <width>478</width> + <height>679</height> </rect> </property> <property name="minimumSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="acceptDrops"> <bool>false</bool> </property> <property name="windowTitle"> <string>QmitkPreprocessingViewControls</string> </property> <property name="autoFillBackground"> <bool>true</bool> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QGroupBox" name="m_InputData"> <property name="title"> <string>Please Select Input Data</string> </property> <layout class="QGridLayout" name="gridLayout_2"> <item row="0" column="0"> <widget class="QLabel" name="label_5"> <property name="toolTip"> <string/> </property> <property name="text"> - <string>Raw DWI:</string> + <string>Image:</string> </property> </widget> </item> <item row="0" column="1"> <widget class="QLabel" name="m_DiffusionImageLabel"> <property name="text"> <string><html><head/><body><p><span style=" color:#ff0000;">mandatory</span></p></body></html></string> </property> <property name="wordWrap"> <bool>true</bool> </property> </widget> </item> </layout> </widget> </item> <item> - <widget class="QGroupBox" name="groupBox_5"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Minimum"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> + <widget class="QTabWidget" name="tabWidget"> + <property name="currentIndex"> + <number>0</number> </property> - <property name="title"> - <string>Info</string> - </property> - <layout class="QGridLayout" name="gridLayout_3"> - <item row="0" column="0"> - <widget class="QTableWidget" name="m_B_ValueMap_TableWidget"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Minimum" vsizetype="Minimum"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="verticalScrollBarPolicy"> - <enum>Qt::ScrollBarAsNeeded</enum> - </property> - <property name="horizontalScrollBarPolicy"> - <enum>Qt::ScrollBarAlwaysOff</enum> - </property> - <attribute name="horizontalHeaderCascadingSectionResizes"> - <bool>true</bool> - </attribute> - <attribute name="horizontalHeaderDefaultSectionSize"> - <number>100</number> - </attribute> - <attribute name="horizontalHeaderStretchLastSection"> - <bool>true</bool> - </attribute> - <attribute name="verticalHeaderVisible"> - <bool>false</bool> - </attribute> - <attribute name="verticalHeaderCascadingSectionResizes"> - <bool>true</bool> - </attribute> - <column> - <property name="text"> - <string>b-Value</string> + <widget class="QWidget" name="tab_4"> + <attribute name="title"> + <string>Gradients</string> + </attribute> + <layout class="QGridLayout" name="gridLayout_6"> + <item row="0" column="0"> + <widget class="QTableWidget" name="m_B_ValueMap_TableWidget"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Minimum" vsizetype="Minimum"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> </property> - </column> - <column> - <property name="text"> - <string>Number of gradients</string> + <property name="verticalScrollBarPolicy"> + <enum>Qt::ScrollBarAsNeeded</enum> </property> - </column> - </widget> - </item> - <item row="5" column="0"> - <widget class="QCommandLinkButton" name="m_CreateLengthCorrectedDwi"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>Round b-value</string> - </property> - </widget> - </item> - <item row="6" column="0"> - <widget class="Line" name="line_3"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item row="8" column="0"> - <widget class="Line" name="line_5"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item row="3" column="0"> - <widget class="Line" name="line_4"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item row="10" column="0"> - <widget class="QSpinBox" name="m_targetBValueSpinBox"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="maximum"> - <number>100000</number> - </property> - </widget> - </item> - <item row="9" column="0"> - <layout class="QHBoxLayout" name="horizontalLayout"> - <item> - <widget class="QCommandLinkButton" name="m_AdcSignalAverage"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string><html><head/><body><p>Create a new Diffusion Weighted Image (DWI) using an ADC average over all q-shells.</p></body></html></string> - </property> + <property name="horizontalScrollBarPolicy"> + <enum>Qt::ScrollBarAlwaysOff</enum> + </property> + <attribute name="horizontalHeaderCascadingSectionResizes"> + <bool>true</bool> + </attribute> + <attribute name="horizontalHeaderDefaultSectionSize"> + <number>100</number> + </attribute> + <attribute name="horizontalHeaderStretchLastSection"> + <bool>true</bool> + </attribute> + <attribute name="verticalHeaderVisible"> + <bool>false</bool> + </attribute> + <attribute name="verticalHeaderCascadingSectionResizes"> + <bool>true</bool> + </attribute> + <column> <property name="text"> - <string>ADC Signal Average</string> - </property> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_AkcSignalFit"> - <property name="enabled"> - <bool>false</bool> + <string>b-Value</string> </property> + </column> + <column> <property name="text"> - <string>AKC Signal Fit</string> + <string>Number of gradients</string> </property> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_BiExpSignalFit"> - <property name="enabled"> - <bool>false</bool> + </column> + </widget> + </item> + <item row="3" column="0"> + <widget class="QFrame" name="frame_2"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QGridLayout" name="gridLayout_10"> + <property name="leftMargin"> + <number>0</number> </property> - <property name="text"> - <string>Bi-Exponential Signal Fit</string> + <property name="topMargin"> + <number>0</number> </property> - </widget> - </item> - </layout> - </item> - <item row="1" column="0"> - <layout class="QFormLayout" name="formLayout"> - <item row="0" column="0"> - <widget class="QLabel" name="label_2"> - <property name="toolTip"> - <string><html><head/><body><p>Define the sampling frame the b-Values are rounded with.</p></body></html></string> + <property name="rightMargin"> + <number>0</number> </property> - <property name="text"> - <string>Sampling frame:</string> + <property name="bottomMargin"> + <number>0</number> </property> - </widget> - </item> - <item row="0" column="1"> - <widget class="QSpinBox" name="m_B_ValueMap_Rounder_SpinBox"> - <property name="enabled"> - <bool>false</bool> + <property name="horizontalSpacing"> + <number>6</number> </property> - <property name="toolTip"> - <string><html><head/><body><p>Round b-values to nearest multiple of this value (click &quot;Round b-value&quot; to create new image with these values).</p></body></html></string> + <item row="5" column="0"> + <widget class="QCommandLinkButton" name="m_MirrorGradientToHalfSphereButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Sometimes the gradient directions are not located on one half sphere.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Mirror gradients to half sphere</string> + </property> + </widget> + </item> + <item row="3" column="0"> + <widget class="QCommandLinkButton" name="m_CreateLengthCorrectedDwi"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>Round b-values</string> + </property> + </widget> + </item> + <item row="7" column="0"> + <widget class="QCommandLinkButton" name="m_ReduceGradientsButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Retain only the specified number of gradient directions and according image volumes. The retained directions are spread equally over the half sphere using an iterative energy repulsion strategy.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Reduce number of gradients</string> + </property> + </widget> + </item> + <item row="3" column="1"> + <layout class="QFormLayout" name="formLayout"> + <item row="0" column="0"> + <widget class="QLabel" name="label_2"> + <property name="toolTip"> + <string><html><head/><body><p>Define the sampling frame the b-Values are rounded with.</p></body></html></string> + </property> + <property name="text"> + <string>Sampling frame:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QSpinBox" name="m_B_ValueMap_Rounder_SpinBox"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string><html><head/><body><p>Round b-values to nearest multiple of this value (click &quot;Round b-value&quot; to create new image with these values).</p></body></html></string> + </property> + <property name="correctionMode"> + <enum>QAbstractSpinBox::CorrectToNearestValue</enum> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>10000</number> + </property> + <property name="singleStep"> + <number>10</number> + </property> + </widget> + </item> + </layout> + </item> + <item row="4" column="0"> + <widget class="QCommandLinkButton" name="m_ShowGradientsButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Generate pointset displaying the gradient vectors (applied measurement frame).</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Show gradients</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="5" column="0"> + <spacer name="verticalSpacer_5"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <widget class="QWidget" name="tab_5"> + <attribute name="title"> + <string>Image Values</string> + </attribute> + <layout class="QGridLayout" name="gridLayout_8"> + <item row="3" column="0"> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0"> + <widget class="QGroupBox" name="groupBox_2"> + <property name="title"> + <string>Resample image</string> + </property> + <layout class="QGridLayout" name="gridLayout_12"> + <item row="1" column="0"> + <widget class="QFrame" name="m_ResampleDoubleFrame"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QGridLayout" name="gridLayout_5"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <property name="spacing"> + <number>0</number> + </property> + <item row="0" column="1"> + <widget class="QDoubleSpinBox" name="m_ResampleDoubleY"> + <property name="minimum"> + <double>0.010000000000000</double> + </property> + <property name="value"> + <double>2.000000000000000</double> + </property> + </widget> + </item> + <item row="0" column="0"> + <widget class="QDoubleSpinBox" name="m_ResampleDoubleX"> + <property name="minimum"> + <double>0.010000000000000</double> + </property> + <property name="value"> + <double>2.000000000000000</double> + </property> + </widget> + </item> + <item row="0" column="2"> + <widget class="QDoubleSpinBox" name="m_ResampleDoubleZ"> + <property name="minimum"> + <double>0.010000000000000</double> + </property> + <property name="value"> + <double>2.000000000000000</double> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="0" column="0"> + <widget class="QComboBox" name="m_ResampleTypeBox"> + <item> + <property name="text"> + <string>Sampling factor</string> + </property> + </item> + <item> + <property name="text"> + <string>New image spacing</string> + </property> + </item> + <item> + <property name="text"> + <string>New image size</string> + </property> + </item> + </widget> + </item> + <item row="3" column="0"> + <widget class="QFrame" name="frame_5"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QGridLayout" name="gridLayout_14"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <property name="spacing"> + <number>0</number> + </property> + <item row="0" column="0"> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>Interpolator:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QComboBox" name="m_InterpolatorBox"> + <item> + <property name="text"> + <string>Nearest neighbour</string> + </property> + </item> + <item> + <property name="text"> + <string>Linear</string> + </property> + </item> + <item> + <property name="text"> + <string>B-spline</string> + </property> + </item> + <item> + <property name="text"> + <string>Windowed sinc</string> + </property> + </item> + </widget> + </item> + <item row="1" column="0"> + <widget class="QCommandLinkButton" name="m_ResampleImageButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string/> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Resample image</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="2" column="0"> + <widget class="QFrame" name="m_ResampleIntFrame"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QGridLayout" name="gridLayout_13"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <property name="spacing"> + <number>0</number> + </property> + <item row="0" column="0"> + <widget class="QSpinBox" name="m_ResampleIntX"> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>10000</number> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QSpinBox" name="m_ResampleIntY"> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>10000</number> + </property> + </widget> + </item> + <item row="0" column="2"> + <widget class="QSpinBox" name="m_ResampleIntZ"> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>10000</number> + </property> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + </item> + <item row="0" column="0"> + <widget class="QFrame" name="frame_3"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QGridLayout" name="gridLayout_11"> + <property name="leftMargin"> + <number>0</number> </property> - <property name="correctionMode"> - <enum>QAbstractSpinBox::CorrectToNearestValue</enum> + <property name="topMargin"> + <number>0</number> </property> - <property name="minimum"> - <number>1</number> + <property name="rightMargin"> + <number>0</number> </property> - <property name="maximum"> - <number>10000</number> + <property name="bottomMargin"> + <number>0</number> </property> - <property name="singleStep"> - <number>10</number> + <property name="horizontalSpacing"> + <number>0</number> </property> - </widget> - </item> - </layout> - </item> - <item row="7" column="0"> - <widget class="QCommandLinkButton" name="m_ShowGradientsButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>Generate pointset displaying the gradient vectors (applied measurement frame).</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Show gradients</string> - </property> - </widget> - </item> - <item row="11" column="0"> - <widget class="QCheckBox" name="m_OutputRMSErrorImage"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>Output RMS-Error Image</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <widget class="QGroupBox" name="groupBox_2"> - <property name="title"> - <string>Non diffusion weighted image</string> - </property> - <layout class="QVBoxLayout" name="verticalLayout_3"> - <item> - <widget class="QLabel" name="label_3"> - <property name="minimumSize"> - <size> - <width>0</width> - <height>30</height> - </size> - </property> - <property name="text"> - <string>Average and extract all images that were acquired without diffusion weighting.</string> - </property> - <property name="wordWrap"> - <bool>true</bool> - </property> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_ButtonExtractB0"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>If multiple baseline acquisitions are present, the default behaviour is to output an averaged image.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Extract B0</string> - </property> - </widget> - </item> - <item> - <widget class="QCheckBox" name="m_CheckExtractAll"> - <property name="toolTip"> - <string>Create a 3D+t data set containing all b0 images as timesteps</string> - </property> - <property name="text"> - <string>Extract all B0 images without averaging</string> - </property> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_CalcAdcButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>If multiple baseline acquisitions are present, the default behaviour is to output an averaged image.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Calculate ADC map</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <widget class="QGroupBox" name="m_ReduceSizeLayout"> - <property name="title"> - <string>Modify DWI</string> - </property> - <layout class="QVBoxLayout" name="verticalLayout_4"> - <item> - <widget class="QFrame" name="frame"> - <property name="frameShape"> - <enum>QFrame::NoFrame</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Raised</enum> - </property> - <layout class="QFormLayout" name="formLayout_2"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> - <number>0</number> - </property> - <item row="0" column="1"> - <widget class="QDoubleSpinBox" name="m_Blur"> - <property name="toolTip"> - <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> - </property> - <property name="statusTip"> - <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> - </property> - <property name="whatsThis"> - <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> - </property> - <property name="decimals"> - <number>6</number> - </property> - <property name="maximum"> - <double>2.000000000000000</double> - </property> - <property name="singleStep"> - <double>0.000100000000000</double> - </property> - <property name="value"> - <double>0.001000000000000</double> - </property> - </widget> - </item> - <item row="0" column="0"> - <widget class="QLabel" name="label"> - <property name="toolTip"> - <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> - </property> - <property name="statusTip"> - <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> - </property> - <property name="whatsThis"> - <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> - </property> - <property name="text"> - <string>Merge radius</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_ButtonAverageGradients"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>Multiple acquistions of one gradient direction can be averaged. Due to rounding errors, similar gradients often differ in the last decimal positions. The Merge radius allows to average them by taking all directions within a certain radius into account.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Average redundant gradients</string> - </property> - </widget> - </item> - <item> - <widget class="Line" name="line_2"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item> - <widget class="QFrame" name="m_ReductionFrame"> - <property name="frameShape"> - <enum>QFrame::NoFrame</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Raised</enum> - </property> - <layout class="QGridLayout" name="gridLayout_4"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> - <number>0</number> - </property> - <property name="spacing"> - <number>9</number> - </property> - <item row="0" column="1"> - <widget class="QLabel" name="label_6"> - <property name="text"> - <string/> - </property> - </widget> - </item> - <item row="0" column="0"> - <widget class="QLabel" name="label_4"> - <property name="text"> - <string>Specify desired number of gradients per shell:</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <spacer name="horizontalSpacer_3"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QCommandLinkButton" name="m_ReduceGradientsButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>Retain only the specified number of gradient directions and according image volumes. The retained directions are spread equally over the half sphere using an iterative energy repulsion strategy.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Reduce number of gradients</string> - </property> - </widget> - </item> - <item> - <widget class="Line" name="line"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_MirrorGradientToHalfSphereButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>Sometimes the gradient directions are not located on one half sphere.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Mirror gradients to half sphere</string> - </property> - </widget> - </item> - <item> - <widget class="QCommandLinkButton" name="m_NormalizeImageValuesButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>Each image value is normalized with the corresponding basleine signal value.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Normalize image values</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <widget class="QGroupBox" name="groupBox_7"> - <property name="title"> - <string>Merge selected images</string> - </property> - <layout class="QVBoxLayout" name="verticalLayout_6"> - <item> - <widget class="QCommandLinkButton" name="m_MergeDwisButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string>Merges selected DWIs of same dimension. If several b-values are present, the resulting image will contain multiple b-shells.</string> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Merge selected DWIs</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <widget class="QGroupBox" name="groupBox_4"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="title"> - <string>Measurment frame</string> - </property> - <layout class="QGridLayout" name="gridLayout"> - <item row="0" column="1"> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="0" column="0"> - <widget class="QTableWidget" name="m_MeasurementFrameTable"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="sizePolicy"> - <sizepolicy hsizetype="Minimum" vsizetype="Minimum"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="minimumSize"> - <size> - <width>0</width> - <height>0</height> - </size> - </property> - <property name="cursor" stdset="0"> - <cursorShape>IBeamCursor</cursorShape> - </property> - <property name="autoFillBackground"> - <bool>true</bool> - </property> - <property name="verticalScrollBarPolicy"> - <enum>Qt::ScrollBarAlwaysOff</enum> - </property> - <property name="horizontalScrollBarPolicy"> - <enum>Qt::ScrollBarAlwaysOff</enum> - </property> - <property name="showGrid"> - <bool>true</bool> - </property> - <property name="cornerButtonEnabled"> - <bool>false</bool> - </property> - <attribute name="horizontalHeaderVisible"> - <bool>false</bool> - </attribute> - <attribute name="horizontalHeaderCascadingSectionResizes"> - <bool>true</bool> - </attribute> - <attribute name="horizontalHeaderHighlightSections"> - <bool>true</bool> - </attribute> - <attribute name="horizontalHeaderMinimumSectionSize"> - <number>0</number> - </attribute> - <attribute name="verticalHeaderVisible"> - <bool>false</bool> - </attribute> - <attribute name="verticalHeaderCascadingSectionResizes"> - <bool>true</bool> - </attribute> - <attribute name="verticalHeaderHighlightSections"> - <bool>true</bool> - </attribute> - <row> - <property name="text"> - <string>New Row</string> + <item row="2" column="0"> + <widget class="QCommandLinkButton" name="m_ProjectSignalButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Project image values onto one b-shell.</string> + </property> + <property name="text"> + <string>Project onto shell</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QFrame" name="frame"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QFormLayout" name="formLayout_2"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <item row="0" column="1"> + <widget class="QDoubleSpinBox" name="m_Blur"> + <property name="toolTip"> + <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> + </property> + <property name="statusTip"> + <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> + </property> + <property name="whatsThis"> + <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> + </property> + <property name="decimals"> + <number>6</number> + </property> + <property name="maximum"> + <double>2.000000000000000</double> + </property> + <property name="singleStep"> + <double>0.000100000000000</double> + </property> + <property name="value"> + <double>0.001000000000000</double> + </property> + </widget> + </item> + <item row="0" column="0"> + <widget class="QLabel" name="label"> + <property name="toolTip"> + <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> + </property> + <property name="statusTip"> + <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> + </property> + <property name="whatsThis"> + <string comment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured." extracomment="Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.">Accumulates the information that was acquired with multiple repetitions for one gradient. Vectors do not have to be precisely equal in order to be merged, if a "Merge radius" > 0 is configured.</string> + </property> + <property name="text"> + <string>Merge radius</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="1" column="0"> + <widget class="QCommandLinkButton" name="m_ButtonAverageGradients"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Multiple acquistions of one gradient direction can be averaged. Due to rounding errors, similar gradients often differ in the last decimal positions. The Merge radius allows to average them by taking all directions within a certain radius into account.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Average repetitions</string> + </property> + </widget> + </item> + <item row="3" column="1"> + <widget class="QComboBox" name="m_NormalizationMethodBox"> + <property name="toolTip"> + <string>Select projection method.</string> + </property> + <item> + <property name="text"> + <string>Local B0</string> + </property> + </item> + <item> + <property name="text"> + <string>Max B0</string> + </property> + </item> + </widget> + </item> + <item row="2" column="1"> + <widget class="QFrame" name="frame_4"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Raised</enum> + </property> + <layout class="QGridLayout" name="gridLayout_4"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <property name="spacing"> + <number>0</number> + </property> + <item row="0" column="0"> + <widget class="QSpinBox" name="m_targetBValueSpinBox"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Target b-value</string> + </property> + <property name="maximum"> + <number>100000</number> + </property> + <property name="singleStep"> + <number>500</number> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QComboBox" name="m_ProjectionMethodBox"> + <property name="toolTip"> + <string>Select projection method.</string> + </property> + <item> + <property name="text"> + <string>ADC Average</string> + </property> + </item> + <item> + <property name="text"> + <string>AKC</string> + </property> + </item> + <item> + <property name="text"> + <string>Bi-Exponential</string> + </property> + </item> + </widget> + </item> + </layout> + </widget> + </item> + <item row="3" column="0"> + <widget class="QCommandLinkButton" name="m_NormalizeImageValuesButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Each image value is normalized with the corresponding baseline signal value.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Normalize image values</string> + </property> + </widget> + </item> + <item row="5" column="0"> + <widget class="QCommandLinkButton" name="m_MergeDwisButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Merges selected DWIs of same dimension. If several b-values are present, the resulting image will contain multiple b-shells.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Merge selected DWIs</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + <widget class="QWidget" name="tab_3"> + <attribute name="title"> + <string>Header</string> + </attribute> + <layout class="QGridLayout" name="gridLayout_7"> + <item row="1" column="0"> + <widget class="QGroupBox" name="groupBox_4"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> </property> - </row> - <row> - <property name="text"> - <string>New Row</string> + <property name="title"> + <string>Measurment frame</string> + </property> + <layout class="QGridLayout" name="gridLayout"> + <item row="0" column="1"> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="0" column="0"> + <widget class="QTableWidget" name="m_MeasurementFrameTable"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="sizePolicy"> + <sizepolicy hsizetype="Minimum" vsizetype="Minimum"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + <property name="cursor" stdset="0"> + <cursorShape>IBeamCursor</cursorShape> + </property> + <property name="autoFillBackground"> + <bool>true</bool> + </property> + <property name="verticalScrollBarPolicy"> + <enum>Qt::ScrollBarAlwaysOff</enum> + </property> + <property name="horizontalScrollBarPolicy"> + <enum>Qt::ScrollBarAlwaysOff</enum> + </property> + <property name="showGrid"> + <bool>true</bool> + </property> + <property name="cornerButtonEnabled"> + <bool>false</bool> + </property> + <attribute name="horizontalHeaderVisible"> + <bool>false</bool> + </attribute> + <attribute name="horizontalHeaderCascadingSectionResizes"> + <bool>true</bool> + </attribute> + <attribute name="horizontalHeaderHighlightSections"> + <bool>true</bool> + </attribute> + <attribute name="horizontalHeaderMinimumSectionSize"> + <number>0</number> + </attribute> + <attribute name="verticalHeaderVisible"> + <bool>false</bool> + </attribute> + <attribute name="verticalHeaderCascadingSectionResizes"> + <bool>true</bool> + </attribute> + <attribute name="verticalHeaderHighlightSections"> + <bool>true</bool> + </attribute> + <row> + <property name="text"> + <string>New Row</string> + </property> + </row> + <row> + <property name="text"> + <string>New Row</string> + </property> + </row> + <row> + <property name="text"> + <string>New Row</string> + </property> + </row> + <column> + <property name="text"> + <string>New Column</string> + </property> + </column> + <column> + <property name="text"> + <string>New Column</string> + </property> + </column> + <column> + <property name="text"> + <string>New Column</string> + </property> + </column> + </widget> + </item> + <item row="1" column="0"> + <widget class="QCommandLinkButton" name="m_ModifyMeasurementFrame"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string/> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Apply new measurement frame</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="0" column="0"> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Direction Matrix</string> + </property> + <layout class="QGridLayout" name="gridLayout_3"> + <item row="0" column="0"> + <widget class="QTableWidget" name="m_DirectionMatrixTable"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="sizePolicy"> + <sizepolicy hsizetype="Minimum" vsizetype="Minimum"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + <property name="cursor" stdset="0"> + <cursorShape>IBeamCursor</cursorShape> + </property> + <property name="autoFillBackground"> + <bool>true</bool> + </property> + <property name="verticalScrollBarPolicy"> + <enum>Qt::ScrollBarAlwaysOff</enum> + </property> + <property name="horizontalScrollBarPolicy"> + <enum>Qt::ScrollBarAlwaysOff</enum> + </property> + <property name="showGrid"> + <bool>true</bool> + </property> + <property name="cornerButtonEnabled"> + <bool>false</bool> + </property> + <attribute name="horizontalHeaderVisible"> + <bool>false</bool> + </attribute> + <attribute name="horizontalHeaderCascadingSectionResizes"> + <bool>true</bool> + </attribute> + <attribute name="horizontalHeaderHighlightSections"> + <bool>true</bool> + </attribute> + <attribute name="horizontalHeaderMinimumSectionSize"> + <number>0</number> + </attribute> + <attribute name="verticalHeaderVisible"> + <bool>false</bool> + </attribute> + <attribute name="verticalHeaderCascadingSectionResizes"> + <bool>true</bool> + </attribute> + <attribute name="verticalHeaderHighlightSections"> + <bool>true</bool> + </attribute> + <row> + <property name="text"> + <string>New Row</string> + </property> + </row> + <row> + <property name="text"> + <string>New Row</string> + </property> + </row> + <row> + <property name="text"> + <string>New Row</string> + </property> + </row> + <column> + <property name="text"> + <string>New Column</string> + </property> + </column> + <column> + <property name="text"> + <string>New Column</string> + </property> + </column> + <column> + <property name="text"> + <string>New Column</string> + </property> + </column> + </widget> + </item> + <item row="0" column="1"> + <spacer name="horizontalSpacer_2"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0"> + <widget class="QCommandLinkButton" name="m_ModifyDirection"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string/> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> + </property> + <property name="text"> + <string>Apply new direction</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="2" column="0"> + <spacer name="verticalSpacer_2"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <widget class="QWidget" name="tab_2"> + <attribute name="title"> + <string>Other</string> + </attribute> + <layout class="QGridLayout" name="gridLayout_9"> + <item row="0" column="1"> + <widget class="QCheckBox" name="m_CheckExtractAll"> + <property name="toolTip"> + <string>Create a 3D+t data set containing all b0 images as timesteps</string> </property> - </row> - <row> <property name="text"> - <string>New Row</string> + <string>Disable averaging</string> + </property> + </widget> + </item> + <item row="0" column="0"> + <widget class="QCommandLinkButton" name="m_ButtonExtractB0"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>If multiple baseline acquisitions are present, the default behaviour is to output an averaged image.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> </property> - </row> - <column> <property name="text"> - <string>New Column</string> + <string>Extract baseline image</string> + </property> + </widget> + </item> + <item row="3" column="0"> + <spacer name="verticalSpacer_3"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0"> + <widget class="QCommandLinkButton" name="m_CalcAdcButton"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>If multiple baseline acquisitions are present, the default behaviour is to output an averaged image.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> </property> - </column> - <column> <property name="text"> - <string>New Column</string> + <string>Calculate ADC map</string> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="QCommandLinkButton" name="m_ExtractBrainMask"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>If multiple baseline acquisitions are present, the default behaviour is to output an averaged image.</string> + </property> + <property name="statusTip"> + <string/> + </property> + <property name="whatsThis"> + <string notr="true"/> </property> - </column> - <column> <property name="text"> - <string>New Column</string> + <string>Estimate binary brain mask</string> </property> - </column> - </widget> - </item> - <item row="1" column="0"> - <widget class="QCommandLinkButton" name="m_ModifyMeasurementFrame"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="toolTip"> - <string/> - </property> - <property name="statusTip"> - <string/> - </property> - <property name="whatsThis"> - <string notr="true"/> - </property> - <property name="text"> - <string>Apply new measurement frame</string> - </property> - </widget> - </item> - </layout> + </widget> + </item> + <item row="2" column="1"> + <widget class="QSpinBox" name="m_BrainMaskIterationsBox"> + <property name="toolTip"> + <string>Maximum number of iterations.</string> + </property> + <property name="maximum"> + <number>10000</number> + </property> + <property name="value"> + <number>10000</number> + </property> + </widget> + </item> + </layout> + </widget> </widget> </item> - <item> - <spacer name="verticalSpacer"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>40</height> - </size> - </property> - </spacer> - </item> </layout> </widget> <layoutdefault spacing="6" margin="11"/> <resources/> <connections/> </ui> diff --git a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp index 18df30ce2c..41d1170675 100644 --- a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp +++ b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp @@ -1,338 +1,351 @@ /*=================================================================== 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 <berryISelectionService.h> #include <berryIWorkbenchWindow.h> //Mitk #include <mitkDataNode.h> #include <mitkNodePredicateNot.h> #include <mitkNodePredicateProperty.h> #include <mitkIRenderingManager.h> #include <mitkImageGenerator.h> // Qmitk #include "UltrasoundSupport.h" #include <QTimer> // Qt #include <QMessageBox> // Ultrasound #include "mitkUSDevice.h" #include "QmitkUSAbstractCustomWidget.h" #include <usModuleContext.h> #include <usGetModuleContext.h> #include "usServiceReference.h" #include "internal/org_mitk_gui_qt_ultrasound_Activator.h" const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport"; void UltrasoundSupport::SetFocus() { } void UltrasoundSupport::CreateQtPartControl( QWidget *parent ) { - m_Timer = new QTimer(this); - - // create GUI widgets from the Qt Designer's .ui file - m_Controls.setupUi( parent ); - - connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities - connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget - connect( m_Controls.m_ActiveVideoDevices, SIGNAL(ServiceSelectionChanged(us::ServiceReferenceU)), this, SLOT(OnChangedActiveDevice()) ); - connect( m_Controls.m_ShowImageStream, SIGNAL(clicked()), this, SLOT(OnChangedActiveDevice()) ); - connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing - connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) ); - connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) ); - connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage())); - - // Initializations - m_Controls.m_NewVideoDeviceWidget->setVisible(false); - std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" - + "org.mitk.services.UltrasoundDevice)(" - + mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + "=true))"; - m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>( - mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL ,filter); - m_Controls.m_ActiveVideoDevices->SetAutomaticallySelectFirstEntry(true); - - // Create Node for US Stream - if (m_Node.IsNull()) - { - m_Node = mitk::DataNode::New(); - m_Node->SetName("US Support Viewing Stream"); - //create a dummy image (gray values 0..255) for correct initialization of level window, etc. - mitk::Image::Pointer dummyImage = mitk::ImageGenerator::GenerateRandomImage<float>(100, 100, 1, 1, 1, 1, 1, 255,0); - m_Node->SetData(dummyImage); - } +m_Timer = new QTimer(this); + +// create GUI widgets from the Qt Designer's .ui file +m_Controls.setupUi( parent ); + +connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities +connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget +connect( m_Controls.m_ActiveVideoDevices, SIGNAL(ServiceSelectionChanged(us::ServiceReferenceU)), this, SLOT(OnChangedActiveDevice()) ); +connect( m_Controls.m_ShowImageStream, SIGNAL(clicked()), this, SLOT(OnChangedActiveDevice()) ); +connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing +connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) ); +connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) ); +connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage())); + +// Initializations +m_Controls.m_NewVideoDeviceWidget->setVisible(false); +std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" ++ "org.mitk.services.UltrasoundDevice)(" ++ mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + "=true))"; +m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>( +mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL ,filter); +m_Controls.m_ActiveVideoDevices->SetAutomaticallySelectFirstEntry(true); + +// Create Node for US Stream +if (m_Node.IsNull()) +{ +m_Node = mitk::DataNode::New(); +m_Node->SetName("US Support Viewing Stream"); +//create a dummy image (gray values 0..255) for correct initialization of level window, etc. +mitk::Image::Pointer dummyImage = mitk::ImageGenerator::GenerateRandomImage<float>(100, 100, 1, 1, 1, 1, 1, 255,0); +m_Node->SetData(dummyImage); +m_OldGeometry = dynamic_cast<mitk::Geometry3D*>(dummyImage->GetGeometry()); +} - m_Controls.tabWidget->setTabEnabled(1, false); +m_Controls.tabWidget->setTabEnabled(1, false); } void UltrasoundSupport::OnClickedAddNewDevice() { - m_Controls.m_NewVideoDeviceWidget->setVisible(true); - m_Controls.m_DeviceManagerWidget->setVisible(false); - m_Controls.m_Headline->setText("Add New Video Device:"); - m_Controls.m_WidgetActiveDevices->setVisible(false); +m_Controls.m_NewVideoDeviceWidget->setVisible(true); +m_Controls.m_DeviceManagerWidget->setVisible(false); +m_Controls.m_Headline->setText("Add New Video Device:"); +m_Controls.m_WidgetActiveDevices->setVisible(false); } void UltrasoundSupport::DisplayImage() { - //Update device - m_Device->Modified(); - m_Device->Update(); +//Update device +m_Device->Modified(); +m_Device->Update(); - //Update data node - mitk::Image::Pointer curOutput = m_Device->GetOutput(); - m_Node->SetData(curOutput); +//Update data node +mitk::Image::Pointer curOutput = m_Device->GetOutput(); +m_Node->SetData(curOutput); - //Only update the view if the image is shown - if(m_Controls.m_ShowImageStream->isChecked()) - { - this->RequestRenderWindowUpdate(); - if ( curOutput->GetDimension() > 1 - && (curOutput->GetDimension(0) != m_CurrentImageWidth - || curOutput->GetDimension(1) != m_CurrentImageHeight) ) - { - // make a reinit on the ultrasound image - mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); - if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() ) - { - renderWindow->GetRenderingManager()->InitializeViews( - curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); - renderWindow->GetRenderingManager()->RequestUpdateAll(); - } - - m_CurrentImageWidth = curOutput->GetDimension(0); - m_CurrentImageHeight = curOutput->GetDimension(1); - } - } +// if the geometry changed: make a reinit on the ultrasound image +if(!mitk::Equal(m_OldGeometry.GetPointer(),curOutput->GetGeometry(),0.0001,false)) +{ +mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); +if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() ) +{ +renderWindow->GetRenderingManager()->InitializeViews( +curOutput->GetGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); +renderWindow->GetRenderingManager()->RequestUpdateAll(); +} +m_OldGeometry = dynamic_cast<mitk::Geometry3D*>(curOutput->GetGeometry()); +} - //Update frame counter - m_FrameCounter ++; - if (m_FrameCounter == 10) - { - int nMilliseconds = m_Clock.restart(); - int fps = 10000.0f / (nMilliseconds ); - m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS"); - m_FrameCounter = 0; - } +//Only update the view if the image is shown +if(m_Controls.m_ShowImageStream->isChecked()) +{ +this->RequestRenderWindowUpdate(); +if ( curOutput->GetDimension() > 1 +&& (curOutput->GetDimension(0) != m_CurrentImageWidth +|| curOutput->GetDimension(1) != m_CurrentImageHeight) ) +{ +// make a reinit on the ultrasound image +mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); +if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() ) +{ +renderWindow->GetRenderingManager()->InitializeViews( +curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); +renderWindow->GetRenderingManager()->RequestUpdateAll(); +} + +m_CurrentImageWidth = curOutput->GetDimension(0); +m_CurrentImageHeight = curOutput->GetDimension(1); +} +} + +//Update frame counter +m_FrameCounter ++; +if (m_FrameCounter == 10) +{ +int nMilliseconds = m_Clock.restart(); +int fps = 10000.0f / (nMilliseconds ); +m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS"); +m_FrameCounter = 0; +} } void UltrasoundSupport::OnChangedFramerateLimit(int value) { - m_Timer->setInterval(1000 / value); +m_Timer->setInterval(1000 / value); } void UltrasoundSupport::OnClickedFreezeButton() { if ( m_Device.IsNull() ) { MITK_WARN("UltrasoundSupport") << "Freeze button clicked though no device is selected."; return; } - - if ( m_Device->GetIsFreezed() ) - { - m_Device->SetIsFreezed(false); - m_Controls.m_FreezeButton->setText("Freeze"); - } - else - { - m_Device->SetIsFreezed(true); - m_Controls.m_FreezeButton->setText("Start Viewing Again"); - } +if ( m_Device->GetIsFreezed() ) +{ +m_Device->SetIsFreezed(false); +m_Controls.m_FreezeButton->setText("Freeze"); +} +else +{ +m_Device->SetIsFreezed(true); +m_Controls.m_FreezeButton->setText("Start Viewing Again"); +} } void UltrasoundSupport::OnChangedActiveDevice() { //clean up and stop timer m_Timer->stop(); this->RemoveControlWidgets(); this->GetDataStorage()->Remove(m_Node); m_Node->ReleaseData(); //get current device, abort if it is invalid m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>(); if (m_Device.IsNull()) - { - MITK_WARN << "Selected device is not valid, aborting"; - m_Controls.tabWidget->setTabEnabled(1, false); - return; - } +{ +MITK_WARN << "Selected device is not valid, aborting"; +m_Controls.tabWidget->setTabEnabled(1, false); +return; +} //create the widgets for this device and enable the widget tab this->CreateControlWidgets(); m_Controls.tabWidget->setTabEnabled(1, true); //show node if the option is enabled if(m_Controls.m_ShowImageStream->isChecked()) - {this->GetDataStorage()->Add(m_Node);} +{this->GetDataStorage()->Add(m_Node);} //start timer int interval = (1000 / m_Controls.m_FrameRate->value()); m_Timer->setInterval(interval); m_Timer->start(); } void UltrasoundSupport::OnNewDeviceWidgetDone() { - m_Controls.m_NewVideoDeviceWidget->setVisible(false); - m_Controls.m_DeviceManagerWidget->setVisible(true); - m_Controls.m_Headline->setText("Ultrasound Devices:"); - m_Controls.m_WidgetActiveDevices->setVisible(true); +m_Controls.m_NewVideoDeviceWidget->setVisible(false); +m_Controls.m_DeviceManagerWidget->setVisible(true); +m_Controls.m_Headline->setText("Ultrasound Devices:"); +m_Controls.m_WidgetActiveDevices->setVisible(true); } void UltrasoundSupport::CreateControlWidgets() { - m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets); - m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget); +m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets); +m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget); - // create b mode widget for current device - m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets); - m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls"); - if ( ! m_Device->GetControlInterfaceBMode() ) - { - m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false); - } +// create b mode widget for current device +m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets); +m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls"); +if ( ! m_Device->GetControlInterfaceBMode() ) +{ +m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false); +} - // create doppler widget for current device - m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets); - m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls"); - if ( ! m_Device->GetControlInterfaceDoppler() ) - { - m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false); - } +// create doppler widget for current device +m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets); +m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls"); +if ( ! m_Device->GetControlInterfaceDoppler() ) +{ +m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false); +} - ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); - if ( pluginContext ) - { - std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")"; - - QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() ); - m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter)); - - if (m_CustomWidgetServiceReference.size() > 0) - { - m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget> - (m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2); - m_ControlCustomWidget->SetDevice(m_Device); - m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls"); - } - else - { - m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls"); - m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false); - } - } +ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); +if ( pluginContext ) +{ +std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")"; - // select first enabled control widget - for ( int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n) - { - if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) ) - { - m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n); - break; - } - } +QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() ); +m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter)); + +if (m_CustomWidgetServiceReference.size() > 0) +{ +m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget> +(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2); +m_ControlCustomWidget->SetDevice(m_Device); +m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls"); +} +else +{ +m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls"); +m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false); +} +} + +// select first enabled control widget +for ( int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n) +{ +if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) ) +{ +m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n); +break; +} +} } void UltrasoundSupport::RemoveControlWidgets() { - if(!m_ControlProbesWidget) {return;} //widgets do not exist... nothing to do +if(!m_ControlProbesWidget) {return;} //widgets do not exist... nothing to do - // remove all control widgets from the tool box widget - while (m_Controls.m_ToolBoxControlWidgets->count() > 0) - { - m_Controls.m_ToolBoxControlWidgets->removeItem(0); - } +// remove all control widgets from the tool box widget +while (m_Controls.m_ToolBoxControlWidgets->count() > 0) +{ +m_Controls.m_ToolBoxControlWidgets->removeItem(0); +} - // remove probes widget (which is not part of the tool box widget) - m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget); - delete m_ControlProbesWidget; - m_ControlProbesWidget = 0; +// remove probes widget (which is not part of the tool box widget) +m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget); +delete m_ControlProbesWidget; +m_ControlProbesWidget = 0; - delete m_ControlBModeWidget; - m_ControlBModeWidget = 0; +delete m_ControlBModeWidget; +m_ControlBModeWidget = 0; - delete m_ControlDopplerWidget; - m_ControlDopplerWidget = 0; +delete m_ControlDopplerWidget; +m_ControlDopplerWidget = 0; - // delete custom widget if it is present - if ( m_ControlCustomWidget ) - { - ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); - delete m_ControlCustomWidget; m_ControlCustomWidget = 0; +// delete custom widget if it is present +if ( m_ControlCustomWidget ) +{ +ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); +delete m_ControlCustomWidget; m_ControlCustomWidget = 0; - if ( m_CustomWidgetServiceReference.size() > 0 ) - { - pluginContext->ungetService(m_CustomWidgetServiceReference.at(0)); - } - } +if ( m_CustomWidgetServiceReference.size() > 0 ) +{ +pluginContext->ungetService(m_CustomWidgetServiceReference.at(0)); +} +} } void UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event) { - if ( m_Device.IsNull() || event.getType() != us::ServiceEvent::MODIFIED ) { return; } +if ( m_Device.IsNull() || event.getType() != us::ServiceEvent::MODIFIED ) { return; } - ctkServiceReference service = event.getServiceReference(); +ctkServiceReference service = event.getServiceReference(); - if ( m_Device->GetManufacturer() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_MANUFACTURER)).toString().toStdString() - && m_Device->GetName() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_NAME)).toString().toStdString() ) - { - return; - } +if ( m_Device->GetManufacturer() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_MANUFACTURER)).toString().toStdString() +&& m_Device->GetName() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_NAME)).toString().toStdString() ) +{ +return; +} - if ( ! m_Device->GetIsActive() && m_Timer->isActive() ) - { - m_Timer->stop(); - } +if ( ! m_Device->GetIsActive() && m_Timer->isActive() ) +{ +m_Timer->stop(); +} - if ( m_CurrentDynamicRange != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DYNAMIC_RANGE)).toDouble() ) - { - m_CurrentDynamicRange = service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DYNAMIC_RANGE)).toDouble(); +if ( m_CurrentDynamicRange != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DYNAMIC_RANGE)).toDouble() ) +{ +m_CurrentDynamicRange = service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_BMODE_DYNAMIC_RANGE)).toDouble(); - // update level window for the current dynamic range - mitk::LevelWindow levelWindow; - m_Node->GetLevelWindow(levelWindow); - levelWindow.SetAuto(m_Image, true, true); - m_Node->SetLevelWindow(levelWindow); - } +// update level window for the current dynamic range +mitk::LevelWindow levelWindow; +m_Node->GetLevelWindow(levelWindow); +levelWindow.SetAuto(m_Image, true, true); +m_Node->SetLevelWindow(levelWindow); +} } UltrasoundSupport::UltrasoundSupport() : m_ControlCustomWidget(0), m_ControlBModeWidget(0), - m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false), - m_CurrentImageWidth(0), m_CurrentImageHeight(0) +m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false), +m_CurrentImageWidth(0), m_CurrentImageHeight(0) { - ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); +ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext(); - if ( pluginContext ) - { - // to be notified about service event of an USDevice - pluginContext->connectServiceListener(this, "OnDeciveServiceEvent", - QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<mitk::USDevice>() + ")")); - } +if ( pluginContext ) +{ +// to be notified about service event of an USDevice +pluginContext->connectServiceListener(this, "OnDeciveServiceEvent", +QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<mitk::USDevice>() + ")")); +} } UltrasoundSupport::~UltrasoundSupport() { } diff --git a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.h b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.h index 54f7fd5b40..ac2fa56c8e 100644 --- a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.h +++ b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.h @@ -1,125 +1,127 @@ /*=================================================================== 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 UltrasoundSupport_h #define UltrasoundSupport_h #include <berryISelectionListener.h> #include <QmitkAbstractView.h> #include "ui_UltrasoundSupportControls.h" #include "QmitkUSAbstractCustomWidget.h" #include "QmitkUSControlsBModeWidget.h" #include "QmitkUSControlsDopplerWidget.h" #include "QmitkUSControlsProbesWidget.h" #include <QTime> #include <ctkServiceEvent.h> /*! \brief UltrasoundSupport This plugin provides functionality to manage Ultrasound devices, create video devices and to view device images. \sa QmitkFunctionality \ingroup ${plugin_target}_internal */ class UltrasoundSupport : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: virtual void SetFocus(); static const std::string VIEW_ID; virtual void CreateQtPartControl(QWidget *parent); UltrasoundSupport(); virtual ~UltrasoundSupport(); public slots: /* * \brief This is called when the newDeviceWidget is closed */ void OnNewDeviceWidgetDone(); protected slots: void OnClickedAddNewDevice(); void OnChangedFramerateLimit(int); /* *\brief Called, when the selection in the list of the active devices changes. */ void OnChangedActiveDevice(); void OnClickedFreezeButton(); void OnDeciveServiceEvent(const ctkServiceEvent event); /* * \brief This is the main imaging loop that is called regularily during the imaging process */ void DisplayImage(); protected: void CreateControlWidgets(); void RemoveControlWidgets(); int m_FrameCounter; /* * \brief This timer triggers periodic updates to the pipeline */ QTimer* m_Timer; QTime m_Clock; /* * \brief The device that is currently used to aquire images */ mitk::USDevice::Pointer m_Device; /* * \brief The node that we feed images into */ mitk::DataNode::Pointer m_Node; mitk::Image::Pointer m_Image; + mitk::Geometry3D::Pointer m_OldGeometry; + Ui::UltrasoundSupportControls m_Controls; QmitkUSAbstractCustomWidget* m_ControlCustomWidget; QmitkUSControlsBModeWidget* m_ControlBModeWidget; QmitkUSControlsDopplerWidget* m_ControlDopplerWidget; QmitkUSControlsProbesWidget* m_ControlProbesWidget; QList<ctkServiceReference> m_CustomWidgetServiceReference; bool m_ImageAlreadySetToNode; unsigned int m_CurrentImageWidth; unsigned int m_CurrentImageHeight; double m_CurrentDynamicRange; }; #endif // UltrasoundSupport_h diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp index b55b5a1600..55235f791a 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp @@ -1,446 +1,446 @@ /*=================================================================== 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 "QmitkXnatEditor.h" // Qmitk #include "QmitkXnatObjectEditorInput.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" // CTK XNAT Core #include "ctkXnatObject.h" #include "ctkXnatDataModel.h" -#include "ctkXnatScanResource.h" +#include "ctkXnatResource.h" #include "ctkXnatFile.h" // CTK XNAT Widgets #include "ctkXnatListModel.h" // Blueberry #include <berryQModelIndexObject.h> #include <berryIWorkbenchPage.h> // Qt #include <QListView> #include <QRegExp> #include <QModelIndex> #include <QDir> // MITK #include <mitkDataStorage.h> #include <mitkIOUtil.h> const std::string QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser"; QmitkXnatEditor::QmitkXnatEditor() : m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()), m_Session(0), m_ListModel(new ctkXnatListModel()), m_SelectionListener(new berry::SelectionChangedAdapter<QmitkXnatEditor>(this, &QmitkXnatEditor::SelectionChanged)), m_DownloadPath(berry::Platform::GetServiceRegistry(). GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID)-> GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", "").c_str()) { m_DataStorageServiceTracker.open(); if(m_DownloadPath.isEmpty()) { QString xnatFolder = "XNAT_DOWNLOADS"; QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath()); dir.mkdir(xnatFolder); dir.setPath(dir.path() + "/" + xnatFolder); m_DownloadPath = dir.path() + "/"; } } QmitkXnatEditor::~QmitkXnatEditor() { delete m_ListModel; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); s->RemoveSelectionListener(m_SelectionListener); m_DataStorageServiceTracker.close(); } bool QmitkXnatEditor::IsDirty() const { return false; } bool QmitkXnatEditor::IsSaveAsAllowed() const { return false; } void QmitkXnatEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { this->SetInput(input); this->SetSite(site); } void QmitkXnatEditor::DoSave() { } void QmitkXnatEditor::DoSaveAs() { } void QmitkXnatEditor::SetInput(berry::IEditorInput::Pointer input) { // If the input is not a QmitkXnatObjectEditorInput the semi global xnat session will be loaded. QmitkXnatObjectEditorInput::Pointer oPtr = input.Cast<QmitkXnatObjectEditorInput>(); if(oPtr.IsNotNull()) { SetInputWithNotify(oPtr); this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch(); } else { m_Session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatConnectionManager()->GetXnatConnection(); if(m_Session == 0) { MITK_INFO << "Please check your XNAT Connection Preferences!"; return; } QmitkXnatObjectEditorInput::Pointer xoPtr = QmitkXnatObjectEditorInput::New( m_Session->dataModel() ); berry::IEditorInput::Pointer editorInput( xoPtr ); SetInputWithNotify(editorInput); this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch(); } } void QmitkXnatEditor::SetFocus() { } void QmitkXnatEditor::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); m_Controls.treeView->setModel(m_ListModel); GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener); connect( m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnObjectActivated(const QModelIndex&)) ); connect( m_Controls.buttonDownloadResource, SIGNAL(clicked()), this, SLOT(DownloadResource()) ); connect( m_Controls.buttonDownloadFile, SIGNAL(clicked()), this, SLOT(DownloadFile()) ); connect( m_Controls.buttonDataModel, SIGNAL(clicked()), this, SLOT(OnDataModelButtonClicked()) ); connect( m_Controls.buttonProject, SIGNAL(clicked()), this, SLOT(OnProjectButtonClicked()) ); connect( m_Controls.buttonSubject, SIGNAL(clicked()), this, SLOT(OnSubjectButtonClicked()) ); connect( m_Controls.buttonExperiment, SIGNAL(clicked()), this, SLOT(OnExperimentButtonClicked()) ); connect( m_Controls.buttonKindOfData, SIGNAL(clicked()), this, SLOT(OnKindOfDataButtonClicked()) ); connect( m_Controls.buttonSession, SIGNAL(clicked()), this, SLOT(OnSessionButtonClicked()) ); connect( m_Controls.buttonResource, SIGNAL(clicked()), this, SLOT(OnResourceButtonClicked()) ); // Makes the breadcrumb feature invisible for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(false); } for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i); child->widget()->setVisible(false); } UpdateList(); } void QmitkXnatEditor::UpdateList() { QmitkXnatObjectEditorInput::Pointer xoPtr(GetEditorInput().Cast<QmitkXnatObjectEditorInput>()); if( xoPtr.IsNull() ) return; ctkXnatObject* inputObject = xoPtr->GetXnatObject(); if( inputObject == NULL ) return; m_ListModel->setRootObject( inputObject ); m_Controls.treeView->reset(); // recursive method to check parents of the inputObject m_ParentCount = ParentChecker(inputObject); // breadcrumb labels for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(false); } for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i); child->widget()->setVisible(false); } ctkXnatObject* parent = NULL; for(int i = m_ParentCount*2; i >= 0; i--) { if(i > 12) break; m_Controls.breadcrumbDescriptionLayout->itemAt(i)->widget()->setVisible(true); QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(true); if(i>0) { m_Controls.breadcrumbHorizontalLayout->itemAt(i-1)->widget()->setVisible(true); m_Controls.breadcrumbDescriptionLayout->itemAt(i-1)->widget()->setVisible(true); } if(parent == NULL) { parent = inputObject; } // make breadcrumb button QPushButton* breadcrumbButton = dynamic_cast<QPushButton*>(child->widget()); breadcrumbButton->setText(parent->id()); parent = parent->parent(); i--; } } void QmitkXnatEditor::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection) { // check for null selection if (selection.IsNull()) { return; } // exclude own selection events and check whether this kind of selection can be handled if (sourcepart != this && selection.Cast<const berry::IStructuredSelection>()) { berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast<const berry::IStructuredSelection>(); // iterates over the selection for (berry::IStructuredSelection::iterator itr = currentSelection->Begin(); itr != currentSelection->End(); ++itr) { if (berry::SmartPointer<berry::QModelIndexObject> objectPointer = itr->Cast<berry::QModelIndexObject>()) { // get object of selected ListWidgetElement ctkXnatObject* object = objectPointer->GetQModelIndex().data(Qt::UserRole).value<ctkXnatObject*>(); // if a file is selected, don't change the input and list view if ( dynamic_cast<ctkXnatFile*>(object) == NULL ){ QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( object ); berry::IEditorInput::Pointer editorInput( oPtr ); if ( !(editorInput == this->GetEditorInput()) ) this->SetInput(editorInput); UpdateList(); } } } } } void QmitkXnatEditor::DownloadResource() { if (!m_Controls.treeView->selectionModel()->hasSelection()) return; const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); QVariant variant = m_ListModel->data(index, Qt::UserRole); if ( variant.isValid() ) { - ctkXnatScanResource* resource = dynamic_cast<ctkXnatScanResource*>(variant.value<ctkXnatObject*>()); + ctkXnatResource* resource = dynamic_cast<ctkXnatResource*>(variant.value<ctkXnatObject*>()); if (resource != NULL) { MITK_INFO << "Download started ..."; MITK_INFO << "..."; QString resourcePath = m_DownloadPath + resource->id() + ".zip"; resource->download(resourcePath); // Testing if the path exists QDir downDir(m_DownloadPath); if( downDir.exists(resource->id() + ".zip") ) { MITK_INFO << "Download of " << resource->id().toStdString() << ".zip was completed!"; } else { MITK_INFO << "Download of " << resource->id().toStdString() << ".zip failed!"; } } else { MITK_INFO << "Selection was not a resource folder!"; } } } void QmitkXnatEditor::DownloadFile() { if (!m_Controls.treeView->selectionModel()->hasSelection()) return; const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); InternalFileDownload(index); } void QmitkXnatEditor::ToHigherLevel() { ctkXnatObject* parent = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->parent(); if( parent == NULL) { return; } QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( parent ); berry::IEditorInput::Pointer editorInput( oPtr ); SetInput(editorInput); UpdateList(); } void QmitkXnatEditor::OnObjectActivated(const QModelIndex &index) { if (!index.isValid()) return; ctkXnatObject* child = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->children().at(index.row()); if( child != NULL ) { ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(child); if( file != NULL ) { // Download file and put into datamanager InternalFileDownload(index); mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService(); if(dsService != NULL) { mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode((m_DownloadPath + file->id()).toStdString()); if ( ( node.IsNotNull() ) && ( node->GetData() != NULL ) ) { dsService->GetDataStorage()->GetDataStorage()->Add(node); mitk::BaseData::Pointer basedata = node->GetData(); mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); } } } else { // Updates the root item QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( child ); berry::IEditorInput::Pointer editorInput( oPtr ); SetInput(editorInput); this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch(); UpdateList(); } } } void QmitkXnatEditor::InternalFileDownload(const QModelIndex& index) { QVariant variant = m_ListModel->data(index, Qt::UserRole); if ( variant.isValid() ) { ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(variant.value<ctkXnatObject*>()); if (file != NULL) { MITK_INFO << "Download started ..."; MITK_INFO << "..."; QString filePath = m_DownloadPath + file->id(); file->download(filePath); // Testing if the file exists QDir downDir(m_DownloadPath); if( downDir.exists(file->id()) ) { MITK_INFO << "Download of " << file->id().toStdString() << " was completed!"; } else { MITK_INFO << "Download of " << file->id().toStdString() << " failed!"; } } else { MITK_INFO << "Selection was not a file!"; } } } int QmitkXnatEditor::ParentChecker(ctkXnatObject* child) { int sum; if( child->parent() == NULL ) { return 0; } else { sum = 1 + ParentChecker(child->parent()); } return sum; } void QmitkXnatEditor::OnDataModelButtonClicked() { for(int i = m_ParentCount; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnProjectButtonClicked() { for(int i = m_ParentCount-1; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnSubjectButtonClicked() { for(int i = m_ParentCount-2; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnExperimentButtonClicked() { for(int i = m_ParentCount-3; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnKindOfDataButtonClicked() { for(int i = m_ParentCount-4; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnSessionButtonClicked() { for(int i = m_ParentCount-5; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnResourceButtonClicked() { for(int i = m_ParentCount-6; i > 0; i--) { ToHigherLevel(); } }