### First-Time Development Setup Script Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/git-commits.md Run this script once after cloning the repository to install necessary Git hooks for local validation. ```bash ./Utilities/SetupForDevelopment.sh ``` -------------------------------- ### Run Developer Setup Script Source: https://github.com/brainsia/brainstools/blob/main/github/CONTRIBUTING.md Execute the setup script to prepare your work tree and configure Git aliases for development. ```sh $ ./Utilities/SetupForDevelopment.sh ``` -------------------------------- ### Running Example on OSX Source: https://github.com/brainsia/brainstools/blob/main/AutoWorkup/README.md An example command to run `singleSession.py` on an OSX system, setting environment variables and specifying script parameters. ```sh env="OSX" NamicBuild="/Shared/sinapse/scratch/eunyokim/src/NamicExternal/build_OSX_20150619/" export PATH=$NamicBuild/bin:$PATH export PYTHONPATH=$NamicBuild/SimpleITK-build/Wrapping/:$NamicBuild/BRAINSTools/AutoWorkup/:$NamicBuild/NIPYPE:$PYTHONPATH wfrun="local" python $NamicBuild/BRAINSTools/AutoWorkup/singleSession.py \ --wfrun $wfrun \ --workphase atlas-based-reference \ --pe ${env} \ --ExperimentConfig ./KIDsHD.config \ --use-sentinal \ all ``` -------------------------------- ### Setup for Developer Workflow Source: https://github.com/brainsia/brainstools/blob/main/docs/index.md Run the setup script to configure Git hooks, remotes, and establish the recommended developer workflow for BRAINSTools. ```bash cd BRAINSTools bash ./Utilities/SetupForDevelopment.sh ``` -------------------------------- ### Setup and Build BRAINSTools (macOS) Source: https://github.com/brainsia/brainstools/blob/main/README.md Steps to clone the BRAINSTools repository, run the setup script, configure with CMake, and build the project on macOS. Includes commands for finding the number of CPU threads. ```sh mkdir brains cd brains git clone http://github.com/BRAINSIa/BRAINSTools.git cd BRAINSTools ./Utilities/SetupForDevelopment.sh cd .. mkdir build cd build cmake ../BRAINSTools ## NOTE: To configure options in the cmake GUI, use: ## ccmake ../BRAINSTools ## instead make -j${NUMOFTHREADS} -k ## NOTE: To find the number of threads from the OSX terminal, use: ## sysctl -n hw.ncpu ``` -------------------------------- ### Clone and Set Up BRAINSTools Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/building.md Initial steps to clone the repository and set up development environment with git hooks. This is a one-time setup. ```bash git clone https://github.com/BRAINSia/BRAINSTools.git cd BRAINSTools ./Utilities/SetupForDevelopment.sh # install git hooks; required once ``` -------------------------------- ### BRAINSTools Install Layout Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/building.md Illustrates the directory structure of a typical BRAINSTools installation, showing the locations of executables, libraries, and headers. ```text BRAINSTools-build/BRAINSTools-Release-5.8.0/ ← CMAKE_INSTALL_PREFIX ├── bin/ ← compiled tool executables ├── lib/ ← shared libraries │ └── cmake/ ← CMake config files └── include/ ← public headers ``` -------------------------------- ### Install CMake and Build BRAINSTools (Linux Debian/Ubuntu) Source: https://github.com/brainsia/brainstools/blob/main/README.md Instructions for building BRAINSTools on a fresh Linux Debian/Ubuntu install, including installing a specific CMake version from binaries and compiling the project. ```sh sudo apt-get update sudo apt-get upgrade sudo apt-get install git python2.7 python2.7-dev g++ freeglut3-dev ``` ```sh # You can find the URL of the latest CMake binary by # * Go to www.cmake.org/download in a browser # * Hover over the desired 'Binary distribution' for your operating # system # * Right-click and select 'Copy Link Address' for the file ending in # "tar.gz" URL=http://www.cmake.org/files/v3.2/cmake-3.2.1-Linux-x86_64.tar.gz wget ${URL} # Decompress the file tar -xzvf cmake-3.2.1-Linux-x86_64.tar.gz # Add the binary to your PATH environment variable export PATH=${PWD}/cmake-3.2.1-Linux-x86_64/bin:${PATH} ``` ```sh git clone https://github.com/BRAINSia/BRAINSTools.git mkdir build cd build CC=/usr/bin/gcc-4.8 \ CXX=/usr/bin/g++-4.8 \ cmake ../BRAINSTools \ make -j${NUMOFTHREADS} -k :warning: You can find the number of threads on your system in Ubuntu with `lscpu` ``` -------------------------------- ### AutoWorkup Configuration Examples Source: https://context7.com/brainsia/brainstools/llms.txt Examples of input CSV and INI configuration files for the AutoWorkup pipeline. The CSV lists MRI sessions, and the INI file specifies experiment parameters and Nipype settings. ```csv "projectA","111","session001","{'T1-30':['data/sub-111/t1.nii.gz'],'T2-30':['data/sub-111/t2.nii.gz']}" "projectA","112","session002","{'T1-30':['data/sub-112/t1.nii.gz','data/sub-112/t1_rep.nii.gz'],'T2-30':['data/sub-112/t2.nii.gz']}" ``` ```ini [EXPERIMENT] SESSION_DB_BASE=./bawInputList.csv SESSION_DB_TEMP=%(SESSION_DB_BASE)s BASE_OUTPUT_DIR=./experiment_results EXPERIMENT_BASE=20240101_base WORKFLOW_COMPONENTS_BASE=['denoise','landmark','auxlmk','tissue_classify','warp_atlas_to_subject'] ATLAS_PATH=/path/to/Atlas/Atlas_20131115 [NIPYPE] GLOBAL_DATA_SINK_REWRITE=False [OSX] QUEUE=-q all _BRAINSTOOLS_BIN_DIR=/path/to/BRAINSTools-build/bin APPEND_PATH=%(_BRAINSTOOLS_BIN_DIR)s ``` -------------------------------- ### Install BRAINS Build Scripts Source: https://github.com/brainsia/brainstools/blob/main/BRAINSCommonLib/CMakeLists.txt Globally finds and configures build scripts from the BuildScripts directory and installs them. Use this to ensure common build utilities are available. ```cmake file(GLOB BRAINSBUILD_FILES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "BuildScripts/*") foreach(BUILDFILE ${BRAINSBUILD_FILES}) #message(STATUS "${BUILDFILE} ${CMAKE_CURRENT_BINARY_DIR}/${BUILDFILE}") configure_file(${BUILDFILE} ${CMAKE_CURRENT_BINARY_DIR}/${BUILDFILE} @ONLY IMMEDIATE) endforeach() install(FILES ${BRAINSBUILD_FILES} DESTINATION ${BRAINSTools_CLI_INSTALL_ARCHIVE_DESTINATION}/BuildScripts COMPONENT Development) ``` -------------------------------- ### Example Input List File (bawInputList.csv) Source: https://github.com/brainsia/brainstools/blob/main/AutoWorkup/README.md Defines the input MRI data for the pipeline. Each line specifies project, subject, session, and a dictionary of T1 and T2 scan paths. Ensure MRISessionName is unique. ```python "projectName","subjectName","MRISessionName","{'T1-30':[t1 repeated scans list],'T2-30':[t2 repeated scans list]}" "projectA","111","12345611","{'T1-30':['somewhere/T1_filename.nii.gz'],'T2-30':['somewhere/T2_COR.nii.gz']}" "projectB","112","12345614","{'T1-30':['somewhere/T1_filename.nii.gz', 'somewhere/T1_COR_REP1.nii.gz'],'T2-30':['somewhere/T2_COR.nii.gz']}" "projectA","111","12345698","{'T1-30':['somewhere/T1_COR.nii.gz', 'somewhere/T1_COR_REP1.nii.gz'],'T2-30':['somewhere/T2_COR.nii.gz']}" ``` -------------------------------- ### Create New Topic Branch from Origin Release Source: https://github.com/brainsia/brainstools/blob/main/github/CONTRIBUTING.md Start a new topic branch from 'origin/release' for fixes on the release branch. Use a 'release-' prefix for the topic name. ```sh $ git checkout -b my-topic origin/release ``` -------------------------------- ### Commit Message Format Example Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/style.md Follow this format for commit messages, including a prefix, a brief subject line, and an optional longer explanation. ```text PREFIX: Brief description Longer explanation if needed. Describe *what* changed and *why*. ``` -------------------------------- ### Clean Build BRAINSTools (Linux RedHat 6) Source: https://github.com/brainsia/brainstools/blob/main/README.md Example session for a clean build of BRAINSTools on Linux RedHat 6, including specific GCC/G++ versions and CMake configuration options. ```sh mkdir ~/src/mytester cd ~/src/mytester git clone https://github.com/BRAINSia/BRAINSTools.git cd BRAINSTools/ bash ./Utilities/SetupForDevelopment.sh mkdir -p ../BRAINSTools-build cd ../BRAINSTools-build/ CC=/usr/bin/gcc-4.2 CXX=/usr/bin/g++-4.2 ccmake ../BRAINSTools \ -DUSE_BRAINSConstellationDetector:BOOL=ON \ -DUSE_BRAINSABC:BOOL=ON make -j${NUMOFTHREADS} -k ## NOTE: The fetching of data still has problems with parallel builds, so we need to restart it at least # once make ``` -------------------------------- ### BRAINSConstellationDetector Landmark Comparison Test Setup Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/TestSuite/CMakeLists.txt Sets up a test for BRAINSConstellationDetector focused on landmark comparison. It generates aligned landmarks and a verification script. ```cmake set(BCDTestName BCDTestForLandmarkCompare) ExternalData_add_test( ${BRAINSTools_ExternalData_DATA_MANAGEMENT_TARGET} NAME ${BCDTestName} COMMAND ${LAUNCH_EXE} $ BRAINSConstellationDetectorTest --inputVolume DATA{${TestData_DIR}/T1.nii.gz} --LLSModel DATA{${TestData_DIR}/Transforms_h5/LLSModel_50Lmks.${XFRM_EXT}} --inputTemplateModel DATA{${TestData_DIR}/T1_50Lmks.mdl} --outputVolume ${CMAKE_CURRENT_BINARY_DIR}/${BCDTestName}_aligned.nrrd --outputLandmarksInACPCAlignedSpace ${CMAKE_CURRENT_BINARY_DIR}/${BCDTestName}_ACPCSpace_aligned.fcsv --outputLandmarksInInputSpace ${CMAKE_CURRENT_BINARY_DIR}/${BCDTestName}_InputSpace_aligned.fcsv --outputVerificationScript ${CMAKE_CURRENT_BINARY_DIR}/${BCDTestName}_aligned.sh ) set_tests_properties(${BCDTestName} PROPERTIES TIMEOUT 9876 PROCESSORS ${_brainstools_test_nproc}) ``` -------------------------------- ### Create New Topic Branch from Origin Master Source: https://github.com/brainsia/brainstools/blob/main/github/CONTRIBUTING.md Start a new topic branch from the latest 'origin/master' for new feature development. ```sh $ git checkout -b my-topic origin/master ``` -------------------------------- ### Build BRAINSTools with LLVM 10 Source: https://github.com/brainsia/brainstools/blob/main/Utilities/build_configs/README.md Use this script to set up the build environment and compile BRAINSTools using LLVM 10 in RelWithDebInfo mode. Ensure you have Git, CMake, and Ninja installed. ```bash mkdir -p src cd src git clone git@github.com:BRAINSia/BRAINSTools.git mkdir -p BRAINSTools-llvm10-RelWithDebInfo cmake \ -G Ninja \ -S BRAINSTools \ -B BRAINSTools-RelWithDebInfo \ -C BRAINSTools/Utilities/build_configs/Darwin/BRAINSTools-llvm10-RelWithDebInfo.cmake cd BRAINSTools-llvm10-RelWithDebInfo ninja ``` -------------------------------- ### Add Test Executable and Link Libraries Source: https://github.com/brainsia/brainstools/blob/main/BRAINSCommonLib/TestLargestForegroundFilledMaskImageFilter/CMakeLists.txt Defines the test executable name, adds the source file, and links the necessary library. This is a standard setup for creating test executables in CMake. ```cmake set(TestName TestLargestForegroundFilledMaskImageFilter) add_executable(${TestName} ${TestName}.cxx) target_link_libraries(${TestName} PRIVATE BRAINSCommonLib) set_target_properties(${TestName} PROPERTIES FOLDER ${MODULE_FOLDER}) ``` -------------------------------- ### Configure and Build BRAINSTools (Phase I Superbuild) Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/building.md Configures the project for a two-phase superbuild and then builds it. Phase I fetches dependencies, and Phase II builds the tools. ```bash mkdir ../BRAINSTools-build cd ../BRAINSTools-build cmake ../BRAINSTools \ -DCMAKE_BUILD_TYPE=Release \ -DBRAINSTools_SUPERBUILD=ON make -j$(nproc) ``` -------------------------------- ### Add Dependency for External Data Installation Source: https://github.com/brainsia/brainstools/blob/main/BRAINSPosteriorToContinuousClass/TestSuite/CMakeLists.txt Ensures that the reference atlas data is installed before the test driver is built, by adding a dependency on the InstallReferenceAtlas target. ```cmake if(TARGET InstallReferenceAtlas) add_dependencies(BRAINSPosteriorToContinuousClassTestDriver InstallReferenceAtlas) ## Needed to ensure data is installed endif() ``` -------------------------------- ### Build Configuration (Old Method) Source: https://github.com/brainsia/brainstools/blob/main/AutoWorkup/README.md Use this INI configuration if NAMICExternal was built without an Anaconda environment. ```INI ############## A -- if you built NAMICExternal without anaconda env (old) ########### _BRAINSTOOLS_BIN_DIR=%(_BUILD_DIR)s/bin _SIMPLEITK_PYTHON_LIB=%(_BUILD_DIR)s/lib _SIMPLEITK_PACKAGE_DIR=%(_BUILD_DIR)s/SimpleITK-build/Wrapping _NIPYPE_PACKAGE_DIR=%(_BUILD_DIR)s/NIPYPE ############## -- You should not need to modify below here. ########### APPEND_PYTHONPATH=%(_NIPYPE_PACKAGE_DIR)s:%(_SIMPLEITK_PYTHON_LIB)s:%(_SIMPLEITK_PACKAGE_DIR)s APPEND_PATH=%(_BRAINSTOOLS_BIN_DIR)s:%(_SIMPLEITK_PYTHON_LIB)s:%(_GRAPHVIZ_BIN)s ############## end of OSX specification ############## ``` -------------------------------- ### Install BRAINS Test Data Source: https://github.com/brainsia/brainstools/blob/main/BRAINSCommonLib/CMakeLists.txt Recursively finds SHA512 checksum files in the TestData directory, configures them, and installs them. This is used to ensure test data integrity. ```cmake file(GLOB_RECURSE BRAINSTEST_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/TestData" "*.sha512") set(TESTFILES_TO_INSTALL "") foreach(TESTFILE ${BRAINSTEST_FILES}) #message(STATUS "### ${TESTFILE} ${CMAKE_CURRENT_BINARY_DIR}/TestData/${TESTFILE}") configure_file("TestData/${TESTFILE}" ${CMAKE_CURRENT_BINARY_DIR}/TestData/${TESTFILE} @ONLY IMMEDIATE) list(APPEND TESTFILES_TO_INSTALL "TestData/${TESTFILE}") endforeach() install(FILES ${TESTFILES_TO_INSTALL} DESTINATION ${BRAINSTools_CLI_INSTALL_ARCHIVE_DESTINATION}/TestData COMPONENT Development) ``` -------------------------------- ### Build Simple CLP Programs Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/landmarkStatistics/CMakeLists.txt Sets up simple CLP programs using the StandardBRAINSBuildMacro, specifying target libraries for common functionality. ```cmake set(PROGS_LIST_2 GenerateAverageLmkFile ) foreach(prog ${PROGS_LIST_2}) StandardBRAINSBuildMacro(NAME ${prog} TARGET_LIBRARIES landmarksConstellationCOMMONLIB BRAINSCommonLib) endforeach() ``` -------------------------------- ### singleSession.py Options Source: https://github.com/brainsia/brainstools/blob/main/AutoWorkup/README.md Detailed explanation of the available command-line options for the `singleSession.py` script. ```sh Options: -h, --help Show this help and exit -v, --version Print the version and exit --rewrite-datasinks Turn on the Nipype option to overwrite all files in the 'results' directory --use-sentinal Use the t1_average file as a marker to determine if session needs to be run --dry-run Do not submit jobs, but print diagnostics about which jobs would be run --pe ENV The processing environment to use from configuration file --wfrun PLUGIN The name of the workflow plugin option (default: 'local', 'SGE','SGEGraph', 'local4') --workphase WORKPHASE The type of processing to be done [atlas-based-reference|subject-based-reference] --ExperimentConfig FILE The configuration file ``` -------------------------------- ### Build Configuration (Newer Method) Source: https://github.com/brainsia/brainstools/blob/main/AutoWorkup/README.md Use this INI configuration if NAMICExternal was built with an Anaconda environment. ```INI ############## -- -- if you built NAMICExternal with anaconda env (newer) ########### _BRAINSTOOLS_BIN_DIR=%(_BUILD_DIR)s/bin ############## -- You should not need to modify below here. ########### APPEND_PYTHONPATH= APPEND_PATH=%(_BRAINSTOOLS_BIN_DIR)s:%(_GRAPHVIZ_BIN)s ############## end of OSX specification ############## ``` -------------------------------- ### BRAINSConstellationDetector Test Driver Command Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/TestSuite/CMakeLists.txt Example of invoking the BRAINSConstellationDetectorTestDriver executable with various input parameters for testing purposes. ```cmake BRAINSConstellationDetectorTest --inputVolume DATA{${TestData_DIR}/T1.nii.gz} --outputVolume ${CMAKE_CURRENT_BINARY_DIR}/${BCDTestName}_aligned.nrrd --inputTemplateModel DATA{${TestData_DIR}/T1_50Lmks.mdl} --LLSModel DATA{${TestData_DIR}/Transforms_h5/LLSModel_50Lmks.${XFRM_EXT}}) ``` -------------------------------- ### Migrate from DWIConvert to dcm2niix Source: https://github.com/brainsia/brainstools/blob/main/DWIConvert/README.md Replace DWIConvert command-line invocations with the equivalent dcm2niix command. Install dcm2niix from its GitHub repository. ```bash # Before (DWIConvert) DWIConvert --inputDicomDirectory /path/to/dicoms --outputVolume out.nii.gz # After (dcm2niix) dcm2niix -o /path/to/output /path/to/dicoms ``` -------------------------------- ### Create Input List from Denoised Images Source: https://github.com/brainsia/brainstools/wiki/BCD-Manual-Corrections Generates a text file containing paths to denoised NIfTI images, used as input for BCD processing. ```bash find /Shared/johnsonhj/HDNI/Neuromorphometrics/2012Subscription/Data -name "*_UNM_denoised.nii.gz" >> inputFiles.txt ``` -------------------------------- ### Clone and Build BRAINSTools Source: https://context7.com/brainsia/brainstools/llms.txt Steps to clone the BRAINSTools repository, set up development environment, and configure/build the project using CMake. Includes instructions for both initial build and iterating on source code. ```bash # Clone repository git clone https://github.com/BRAINSia/BRAINSTools.git cd BRAINSTools # Install git hooks (required once per clone) ./Utilities/SetupForDevelopment.sh # Configure and build (out-of-source, Release recommended) mkdir ../BRAINSTools-build && cd ../BRAINSTools-build cmake ../BRAINSTools \ -DCMAKE_BUILD_TYPE=Release \ -DBRAINSTools_SUPERBUILD=ON # Build — Phase I fetches deps, Phase II compiles all tools make -j$(nproc) # Install layout after build: # BRAINSTools-build/BRAINSTools-Release-5.8.0/bin/ ← executables # BRAINSTools-build/BRAINSTools-Release-5.8.0/lib/ ← shared libraries # BRAINSTools-build/BRAINSTools-Release-5.8.0/include/ # Iterate on BRAINSTools source without rebuilding deps (Phase II only) cd BRAINSTools-build/BRAINSTools-Release-EPRelease-build make -j$(nproc) ``` -------------------------------- ### Program List and Build Macro Source: https://github.com/brainsia/brainstools/blob/main/BRAINSLabelStats/CMakeLists.txt Sets the list of programs to build and applies standard build macros for each. ```cmake set(ALL_PROGS_LIST BRAINSLabelStats ) foreach(prog ${ALL_PROGS_LIST}) StandardBRAINSBuildMacro(NAME ${prog} TARGET_LIBRARIES BRAINSCommonLib ${BRAINSLabelStats_ITK_LIBRARIES}) endforeach() ``` -------------------------------- ### Update Local Master Branch Source: https://github.com/brainsia/brainstools/blob/main/github/CONTRIBUTING.md Ensure your local master branch is up-to-date with the remote repository before starting new work. ```sh $ git checkout master $ git pullall ``` -------------------------------- ### Project and Include Directories Source: https://github.com/brainsia/brainstools/blob/main/BRAINSDeface/CMakeLists.txt Defines the project name and sets the binary directory for include files. ```cmake project(BRAINSDeface) #include_directories(${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Checkout BRAINSConstellationDetector Source Code Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/README.md Use SVN to download the source files from the NITRC repository. Ensure you have an SVN client installed. ```bash svn checkout https://www.nitrc.org/svn/brainscdetector/branches/wei-lu/MedicalSliceViewer ``` -------------------------------- ### Build Test Executable for landmarksConstellationTrainingDefinitionIO Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/TestSuite/CMakeLists.txt Defines a test executable for landmarksConstellationTrainingDefinitionIO and links it with required libraries. ```cmake add_executable(TestlandmarksConstellationTrainingDefinitionIO TestlandmarksConstellationTrainingDefinitionIO.cxx) target_link_libraries(TestlandmarksConstellationTrainingDefinitionIO PRIVATE BRAINSCommonLib ${BRAINSConstellationDetector_ITK_LIBRARIES} ${VTK_LIBRARIES}) set_target_properties(TestlandmarksConstellationTrainingDefinitionIO PROPERTIES FOLDER ${MODULE_FOLDER}) ``` -------------------------------- ### Build All Programs Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/src/CMakeLists.txt Defines a list of programs to be built and then iterates through this list, using a macro to build each program. This macro likely handles common build steps for executables. ```cmake set(ALL_PROGS_LIST BRAINSConstellationModeler BRAINSLinearModelerEPCA BRAINSConstellationDetector BRAINSAlignMSP BRAINSClipInferior BRAINSTrimForegroundInDirection BRAINSLmkTransform BRAINSTransformFromFiducials BRAINSEyeDetector insertMidACPCpoint fcsv_to_hdf5 landmarksConstellationAligner landmarksConstellationWeights BinaryMaskEditorBasedOnLandmarks BRAINSConstellationLandmarksTransform ) foreach(prog ${ALL_PROGS_LIST}) StandardBRAINSBuildMacro(NAME ${prog} TARGET_LIBRARIES landmarksConstellationCOMMONLIB ${VTK_LIBRARIES}) endforeach() ``` -------------------------------- ### BRAINSFit Test with Initial Transform Source: https://github.com/brainsia/brainstools/blob/main/BRAINSFit/TestSuite/CMakeLists.txt Configures a BRAINSFit test case using an initial transform, suitable for scenarios where a starting point is known. ```cmake set(BRAINSFitTestName BRAINSFitTest_ScaleSkewVersorScaleNoMasks) ExternalData_add_test( ${BRAINSTools_ExternalData_DATA_MANAGEMENT_TARGET} NAME ${BRAINSFitTestName} COMMAND ${LAUNCH_EXE} $ --compare DATA{${TestData_DIR}/${BRAINSFitTestName}.result.nii.gz} ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz --compareIntensityTolerance 9 --compareRadiusTolerance 0 --compareNumberOfPixelsTolerance 1000 BRAINSFitTest --costMetric MMI --failureExitCode -1 --writeTransformOnFailure --numberOfIterations 2500 --numberOfHistogramBins 200 --samplingPercentage 0.3 --translationScale 250 --minimumStepLength 0.001 --outputVolumePixelType uchar --transformType ScaleSkewVersor3D --initialTransform DATA{${TestData_DIR}/Transforms_h5/Initializer_0.05_${BRAINSFitTestName}.${XFRM_EXT}} --fixedVolume DATA{${TestData_DIR}/test.nii.gz} --movingVolume DATA{${TestData_DIR}/scale.test.nii.gz} --outputVolume ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz --outputTransform ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.${XFRM_EXT} ) ``` -------------------------------- ### ITK Object Creation and Pipeline Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/conventions.md Use the factory method `New()` for object creation and `SmartPointer` for managing object lifetimes. `Update()` triggers execution, and parameters changed after `Update()` require another call to `Update()`. ```cpp // Factory method returns SmartPointer — never use new/delete auto filter = FilterType::New(); filter->SetInput(image); filter->Update(); // Lazy: nothing runs until here auto output = filter->GetOutput(); // Parameters changed after Update() require another Update() filter->SetRadius(3); filter->Update(); ``` -------------------------------- ### Configure GTRACTCommon Include Directories Source: https://github.com/brainsia/brainstools/blob/main/GTRACT/Common/CMakeLists.txt Sets public include directories for the GTRACTCommon library, including the binary directory and the current source directory. ```cmake target_include_directories(GTRACTCommon PUBLIC ${GTRACT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) ``` -------------------------------- ### Import necessary libraries for DWI processing Source: https://github.com/brainsia/brainstools/blob/main/DWIConvert/TestSuite/DWI_ProcessingTest.ipynb Imports essential libraries for handling neuroimaging data, DTI models, and plotting. Ensure these are installed before running. ```python from dipy.data import get_data import nibabel as nib from dipy.io import read_bvals_bvecs from dipy.core.gradients import gradient_table from dipy.reconst.dti import TensorModel from dipy.reconst.dti import fractional_anisotropy from dipy.reconst.dti import color_fa %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np ``` -------------------------------- ### Slicer Execution Model (SEM) CLI Pattern Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/conventions.md Tools often expose a Command Line Interface (CLI) through an XML descriptor. The `main()` function is typically minimal, using the `PARSE_ARGS` macro to handle argument parsing based on the SEM XML specification. ```cpp // ToolName.cxx #include "ToolNameCLP.h" // generated by SEM from ToolName.xml int main(int argc, char * argv[]) { PARSE_ARGS; // SEM macro: parses argc/argv using the XML spec // ... call into BRAINSToolNameHelper or itk filters return EXIT_SUCCESS; } ``` -------------------------------- ### Test Case: Output Resampled Volume Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/TestSuite/CMakeLists.txt Initiates a test case for BRAINSConstellationDetector focusing on the output of the resampled volume. This setup is part of a larger test configuration. ```cmake set(BCDTestName BCDTest_T1_outputResampledVolume) ExternalData_add_test( ${BRAINSTools_ExternalData_DATA_MANAGEMENT_TARGET} NAME ${BCDTestName} COMMAND ${LAUNCH_EXE} $ ``` -------------------------------- ### Define Project and Build Targets Source: https://github.com/brainsia/brainstools/blob/main/BRAINSMultiModeSegment/CMakeLists.txt This section defines the main project and iterates through a list of programs to build, applying a standard build macro. It also includes conditional logic for testing. ```cmake set(ALL_PROGS_LIST BRAINSMultiModeSegment ) foreach(prog ${ALL_PROGS_LIST}) StandardBRAINSBuildMacro(NAME ${prog} TARGET_LIBRARIES BRAINSCommonLib ) endforeach() if(BUILD_TESTING AND NOT BRAINSTools_DISABLE_TESTING) # add_subdirectory(TestSuite) endif() ``` -------------------------------- ### Conditional Test Execution in CMakeLists.txt Source: https://github.com/brainsia/brainstools/blob/main/docs/index.md Conditionally add tests based on the BRAINSTools_MAX_TEST_LEVEL variable. This example shows how to add a specific test if the level is greater than 8. ```cmake if(${BRAINSTools_MAX_TEST_LEVEL} GREATER 8) ExternalData_add_test(BRAINSToolsFetchData NAME itkResampleInPlaceImageFilterTest COMMAND $ itkResampleInPlaceImageFilterTest input1 transform1 checkresult ) endif() ``` -------------------------------- ### Registering Tests in CMakeLists.txt Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/testing.md Tests are registered within the `TestSuite/CMakeLists.txt` file using CMake commands. This example shows the basic structure for adding a test executable. ```cmake add_executable(ToolNameTest ToolNameTest.cxx) target_link_libraries(ToolNameTest PRIVATE ITKCommon BRAINSCommon BRAINSCommon-test ) add_test(NAME ToolNameTest COMMAND ToolNameTest WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) # For GoogleTest, use gtest_discover_tests() instead of add_test() # gtest_discover_tests(ToolNameGTest) ``` -------------------------------- ### Build GUI Programs Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/gui/CMakeLists.txt Iterates through a list of programs to build, using the StandardBRAINSBuildMacro to configure each program with the BRAINSConstellationDetectorGUICOMMONLIB. ```cmake set(ALL_PROGS_LIST BRAINSConstellationDetectorGUI ) foreach(prog ${ALL_PROGS_LIST}) StandardBRAINSBuildMacro(NAME ${prog} TARGET_LIBRARIES BRAINSConstellationDetectorGUICOMMONLIB ) endforeach() ``` -------------------------------- ### Portable Shell Scripting: Readlink Source: https://github.com/brainsia/brainstools/blob/main/Documentation/AI/style.md Avoid GNU's 'readlink -f'. Use Python for a portable way to resolve symbolic links and get the real path. ```python import os,sys; print(os.path.realpath(sys.argv[1])) ``` -------------------------------- ### Create SR_support Library Source: https://github.com/brainsia/brainstools/blob/main/BRAINSSuperResolution/EdgeBasedWeightedTV/CMakeLists.txt Creates a static library named 'SR_support' from specified C++ source files. This library likely contains core functionalities for super-resolution support. ```cmake add_library(SR_support FFTWUpsample.cpp OpWeightedL2.cpp) ``` -------------------------------- ### Add 2D Images and Get Statistics Source: https://github.com/brainsia/brainstools/blob/main/ImageCalculator/doc/Examples.txt Adds two 2D images and outputs the result along with various statistics. Ensure input images are compatible with UCHAR type. ```bash -in 2 UpperHalfHundreds.png LowerHalfHundreds.png -intype UCHAR -outtype UCHAR -add -out AllHundreds.png -Dimensions 2 -statNPX -statMIN -statAVG -statMAX -statVAR -statSUM ``` -------------------------------- ### Define Project Programs and Build Macros Source: https://github.com/brainsia/brainstools/blob/main/BRAINSInitializedControlPoints/CMakeLists.txt Defines the list of programs to be built for the project and applies a standard build macro for each program. Links against BRAINSCommonLib. ```cmake set(ALL_PROGS_LIST BRAINSInitializedControlPoints ) foreach(prog ${ALL_PROGS_LIST}) StandardBRAINSBuildMacro(NAME ${prog} TARGET_LIBRARIES BRAINSCommonLib ) endforeach() ``` -------------------------------- ### BRAINSFit Test: MSEScaleSkewVersorRotationMasks Source: https://github.com/brainsia/brainstools/blob/main/BRAINSFit/TestSuite/CMakeLists.txt Configures a BRAINSFit test using the MSE cost metric with a ScaleSkewVersor3D transform and masked volumes. This setup is appropriate for testing registration accuracy with scaling, skewing, and rotation. ```cmake set(BRAINSFitTestName BRAINSFitTest_MSEScaleSkewVersorRotationMasks) ExternalData_add_test( ${BRAINSTools_ExternalData_DATA_MANAGEMENT_TARGET} NAME ${BRAINSFitTestName} COMMAND ${LAUNCH_EXE} $ --compare DATA{${TestData_DIR}/${BRAINSFitTestName}.result.nii.gz} ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz --compareIntensityTolerance 11 --compareRadiusTolerance 0 --compareNumberOfPixelsTolerance 1000 BRAINSFitTest --costMetric MSE --failureExitCode -1 --writeTransformOnFailure --numberOfIterations 2500 --numberOfHistogramBins 200 --samplingPercentage 0.5 --translationScale 250 --minimumStepLength 0.001 --outputVolumePixelType uchar --transformType ScaleSkewVersor3D --initialTransform DATA{${TestData_DIR}/Transforms_h5/BRAINSFitTest_Initializer_RigidRotationNoMasks.${XFRM_EXT}} ) ``` -------------------------------- ### Configure Project and Common Library Source: https://github.com/brainsia/brainstools/blob/main/BRAINSSuperResolution/GenerateEdgeMap/CMakeLists.txt Configures the project and copies a header file template to the build directory. This is a standard CMake practice for generating configuration headers. ```cmake project(BRAINSSuperResolution) #----------------------------------------------------------------------------- # Dependencies. # #----------------------------------------------------------------------------- # Output directories. # configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/BRAINSSuperResolutionCommonLib.h.in ${CMAKE_CURRENT_BINARY_DIR}/BRAINSSuperResolutionCommonLib.h ) ``` -------------------------------- ### BRAINSFit: Deformable BSpline Registration Source: https://context7.com/brainsia/brainstools/llms.txt Example of using BRAINSFit for deformable BSpline registration for fine alignment. Specifies BSpline grid size, maximum displacement, sampling percentage, and cost metric. ```bash # Deformable BSpline registration (for final fine alignment) BRAINSFit \ --fixedVolume atlas_t1.nii.gz \ --movingVolume subject_t1_registered.nii.gz \ --useBSpline \ --splineGridSize 14,10,12 \ --maxBSplineDisplacement 0.0 \ --samplingPercentage 0.1 \ --costMetric MMI \ --bsplineTransform bspline_output.h5 \ --outputVolumePixelType float ``` -------------------------------- ### Build GUI Version using CMake (Linux 64-bit) Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/README.md Build the Qt-based GUI version of the BRAINSConstellationDetector on Linux 64-bit using CMake. Requires Qt libraries version 4.6.2 or higher and CMake version 2.8 or higher. ```bash mkdir brainscdetector-build cd brainscdetector-build cmake –DBUILD_MEDICAL_SLICEVIEWER_GUI=ON –C ../MedicalSliceViewer/InitialCache-Linux64.cmake ../MedicalSliceViewer ``` -------------------------------- ### Create FFTWUpsampleTest Executable Source: https://github.com/brainsia/brainstools/blob/main/BRAINSSuperResolution/EdgeBasedWeightedTV/CMakeLists.txt Creates an executable named 'FFTWUpsampleTest' from 'FFTWUpsampleTest.cpp'. This executable is likely for testing the FFTW upsampling functionality. ```cmake add_executable(FFTWUpsampleTest FFTWUpsampleTest.cpp) ``` -------------------------------- ### BRAINSFit: Rigid Registration Source: https://context7.com/brainsia/brainstools/llms.txt Example of using BRAINSFit for rigid registration (6 DOF) to align a subject's T1-weighted MRI to an atlas T1. Uses center-of-head alignment and specifies sampling percentage. ```bash # Rigid registration (6 DOF): align subject T1 to atlas T1 BRAINSFit \ --fixedVolume atlas_t1.nii.gz \ --movingVolume subject_t1.nii.gz \ --useRigid \ --initializeTransformMode useCenterOfHeadAlign \ --samplingPercentage 0.05 \ --linearTransform rigid_output.h5 \ --outputVolume subject_t1_registered.nii.gz ``` -------------------------------- ### Define Test Driver and Include Directories Source: https://github.com/brainsia/brainstools/blob/main/BRAINSPosteriorToContinuousClass/TestSuite/CMakeLists.txt Sets up the test driver executable and specifies the necessary include directories for the BRAINSPosteriorToContinuousClass tests. ```cmake MakeTestDriverFromSEMTool(BRAINSPosteriorToContinuousClass BRAINSPosteriorToContinuousClassTest.cxx) target_include_directories(BRAINSPosteriorToContinuousClassTestDriver PRIVATE ${BRAINSPosteriorToContinuousClass_SOURCE_DIR}/BRAINSPosteriorToContinuousClass ) ``` -------------------------------- ### BRAINSFit Test with Initial Transform and Auto Masking Source: https://github.com/brainsia/brainstools/blob/main/BRAINSFit/TestSuite/CMakeLists.txt Configures a BRAINSFit test case with an initial transform and automatic mask processing, suitable for scenarios requiring a specific starting transform and automated mask handling. ```cmake set(BRAINSFitTestName BRAINSFitTest_ScaleTranslationRescaleHeadMasksInit) ExternalData_add_test( ${BRAINSTools_ExternalData_DATA_MANAGEMENT_TARGET} NAME ${BRAINSFitTestName} COMMAND ${LAUNCH_EXE} $ --compare DATA{${TestData_DIR}/${BRAINSFitTestName}.result.nii.gz} ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz --compareIntensityTolerance 7 --compareRadiusTolerance 0 --compareNumberOfPixelsTolerance 777 BRAINSFitTest --costMetric MMI --failureExitCode -1 --writeTransformOnFailure --numberOfIterations 2500 --numberOfHistogramBins 200 --samplingPercentage 0.3 --translationScale 250 --minimumStepLength 0.001 --outputVolumePixelType uchar --maskProcessingMode ROIAUTO --initialTransform DATA{${TestData_DIR}/Transforms_h5/Initializer_BRAINSFitTest_TranslationRescaleHeadMasks.${XFRM_EXT}} --transformType ScaleVersor3D --fixedVolume DATA{${TestData_DIR}/test.nii.gz} --movingVolume DATA{${TestData_DIR}/translation.rescale.test.nii.gz} --outputVolume ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz --outputTransform ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.${XFRM_EXT} ) ``` -------------------------------- ### INI Configuration File: DEFAULT Section Source: https://github.com/brainsia/brainstools/blob/main/AutoWorkup/README.md Sets default parameters for the pipeline, such as mount prefixes and modules. ```ini [DEFAULT] MOUNT_PREFIX= MODULES= ``` -------------------------------- ### Configure landmarksConstellationAligner Test Source: https://github.com/brainsia/brainstools/blob/main/BRAINSConstellationDetector/TestSuite/CMakeLists.txt Sets up a test for the landmarksConstellationAligner program, defining input and output landmark files for comparison. ```cmake set(BCDTestName landmarksConstellationAlignerTest) #This test aims to generate the output of the landmarksConstellationAligner to be compared with the baseline file ExternalData_add_test( ${BRAINSTools_ExternalData_DATA_MANAGEMENT_TARGET} NAME ${BCDTestName} COMMAND ${LAUNCH_EXE} $ ${BCDTestName} --inputLandmarksPaired DATA{${TestData_DIR}/${BCDTestName}_input.fcsv} --outputLandmarksPaired ${CMAKE_CURRENT_BINARY_DIR}/${BCDTestName}.fcsv #output of the program ) ``` -------------------------------- ### BRAINSFit Test Driver with GD Cost Metric Source: https://github.com/brainsia/brainstools/blob/main/BRAINSFit/TestSuite/CMakeLists.txt Configures and runs the BRAINSFit test driver using the Gradient Difference (GD) cost metric. This setup includes parameters for comparison, iteration, sampling, and transform type. ```cmake COMMAND ${LAUNCH_EXE} $ \ --compare DATA{${TestData_DIR}/test.nii.gz} \ ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz \ --compareIntensityTolerance 9 \ --compareRadiusTolerance 0 \ --compareNumberOfPixelsTolerance 1000 \ BRAINSFitTest \ --costMetric GD \ --failureExitCode -1 --writeTransformOnFailure \ --numberOfIterations 25 \ --numberOfHistogramBins 200 \ --samplingPercentage 0.3 \ --translationScale 250 \ --minimumStepLength 0.001 \ --outputVolumePixelType uchar \ --transformType Rigid --initializeTransformMode useMomentsAlign \ --fixedVolume DATA{${TestData_DIR}/test.nii.gz} \ --movingVolume DATA{${TestData_DIR}/test.nii.gz} \ --outputVolume ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.test.nii.gz \ --outputTransform ${CMAKE_CURRENT_BINARY_DIR}/${BRAINSFitTestName}.${XFRM_EXT} ``` -------------------------------- ### BRAINSTools Commit Message Format Source: https://context7.com/brainsia/brainstools/llms.txt Enforces a specific commit message format using a git hook. Subject lines must be ≤78 characters with a mandatory prefix. Includes examples of valid single-line and multi-line commit messages. ```bash # Valid commit message examples (pass the hook) git commit -m "ENH: Add robust min/max computation to BRAINSCommonLib" git commit -m "BUG: Fix segfault in NrrdToFSL when input has zero components" git commit -m "COMP: Fix unused variable warning in BRAINSFit optimizer path" git commit -m "DOC: Update building.md with Phase II iteration instructions" git commit -m "STYLE: Apply clang-format to BRAINSConstellationDetector sources" git commit -m "PERF: Replace linear scan with binary search in landmark lookup" ``` ```bash # Multi-line with body git commit -m "$(cat <<'EOF' BUG: Correct gradient direction sign for coronal DICOM acquisitions SetDirectionsFromSliceOrder assumed axial acquisition geometry; for coronal scans the AP cosine is in a different matrix column. This fix reads the ImageOrientationPatient tag to detect acquisition plane before assigning axis signs. EOF )" ``` ```bash # Prefix reference # ENH: New feature or enhancement # BUG: Runtime crash or incorrect result # COMP: Compiler error or warning fix # DOC: Documentation only # STYLE: Formatting/naming, no logic change # PERF: Performance improvement ``` -------------------------------- ### Create Build Directory Source: https://github.com/brainsia/brainstools/blob/main/docs/BRAINSToolsInClion.md Create a separate build directory outside the source tree to manage build artifacts and SuperBuild files. ```bash mkdir BRAINSTools-build cd BRAINSTools-build ``` -------------------------------- ### Example Failure Log in BCD Source: https://github.com/brainsia/brainstools/wiki/Oz-T1-only-sample-failures This log indicates a failure in the BRAINSConstellationDetector (BCD) during landmark initialization. The error occurs when saving aligned image and zero eye centers landmarks, suggesting an issue with the EMSP.fcsv file format or content. ```text itk::ExceptionObject (0x7b07b00) Location: "unknown" File: /Shared/pinc/sharedopt/20170302/RHEL7/NEP-intel/BRAINSTools/BRAINSConstellationDetector/src/landmarksConstellationDetector.cxx Line: 1475 Description: itk::ERROR: EMSP aligned image and zero eye centers landmarks are written to ./. Use GUI corrector to correct the landmarks in.EMSP.fcsvINITIAL LMKS: EMSP.fcsvFOR IMAGE: Image (0x7b08790) RTTI typeinfo: itk::Image Reference Count: 2 Modified Time: 12892440 Debug: Off Object Name: Observers: none Source: (none) Source output name: (none) Release Data: Off Data Released: False Global Release Data: Off PipelineMTime: 12892430 UpdateMTime: 12892439 RealTimeStamp: 0 seconds LargestPossibleRegion: Dimension: 3 Index: [0, 0, 0] Size: [256, 256, 256] BufferedRegion: Dimension: 3 Index: [0, 0, 0] Size: [256, 256, 256] RequestedRegion: Dimension: 3 Index: [0, 0, 0] Size: [256, 256, 256] Spacing: [1, 1, 1] Origin: [-127.5, -127.5, -127.5] Direction: 1 0 0 0 1 0 0 0 1 IndexToPointMatrix: 1 0 0 0 1 0 0 0 1 PointToIndexMatrix: 1 0 0 0 1 0 0 0 1 Inverse Direction: 1 0 0 0 1 0 0 0 1 PixelContainer: ImportImageContainer (0x7b07b90) RTTI typeinfo: itk::ImportImageContainer Reference Count: 1 Modified Time: 12892437 Debug: Off Object Name: Observers: none Pointer: 0x7b110d0 Container manages memory: true Size: 16777216 Capacity: 16777216 IN DIR: ./ ```