
///\file "medical/DICOM/.README.txt"
///\brief ExampleDICOM README page

/*! \page ExampleDICOM Example DICOM


The DICOM application has been originally developed by the Geant4 users: \n
Louis Archambault,(1)Luc Beaulieu, (2)Vincent Hubert-Tremblay.

- (1) Centre Hospitalier Universitaire de Quebec (CHUQ),   \n
Hotel-Dieu de Quebec, departement de Radio-oncologie  \n
11 cote du palais. Quebec, QC, Canada, G1R 2J6        \n
tel (418) 525-4444 #6720                              \n
fax (418) 691 5268                                    \n
web : thomson.phy.ulaval.ca/phys_med                  \n

- (2) Universite Laval, Quebec (QC) Canada

And it has been deeply reviewed by Pedro Arce in December 2007. \n
Very small changes by Stephane Chauvie in January 2008. \n
Stephane Chauvie, Oct 2009: changed Physics list; changes in DICOM read.  \n
Stephane Chauvie and Andrea Armando; June 2010 adapted for reading  whatever DICOM file \n
Jonathan Madsen, Nov 2013: updated DICOM to utilize multithreading now available in Geant4.10 \n


\section DICOM_s0 NEW DICOM READER BASED ON DCMTK

A new way to read DICOM files has been implemented since release 10.3, to avoid the often problems found by users when reading DICOM files. 
It can also read RT structures in DICOM format as well as RT plans. 
This utility uses the DCMTK (http://dicom.offis.de/dcmtk.php.en).

\section DICOM_s1 NEW DICOM HEAD Project

A new DICOM Digital Head included by S. Guatelli (susanna@uow.edu.au) and V. Giacometti. Available since Geant4 10.4. 
The Digital model is documented in: Giacometti, V., Guatelli, S., Bazalova-Carter, M., Rosenfeld, A.B., Schulte, R.W.,
"Development of a high resolution voxelised head phantom for medical physics applications", (2017) Physica Medica, 33, pp. 182-188.

\section DICOM_s2 Introduction

This example serves first to convert a DICOM file to a simple ASCII file, where the Hounsfield numbers are converted to materials and densities so that it can be used by GEANT4. It serves also to create a GEANT4 geometry based on the DICOM file information using the G4PhantomParameterisation. 

You can find the phantom reproduced in the image PhantomCT.jpg.
In the application the phantom is placed on a table.
 
\section DICOM_s3a Installation OLD:

 - A standard Geant4 example CMakeLists.txt is provided
 - Configure via cmake with 'cmake -DGeant4_DIR=/path_to_geant4_install/lib/Geant4-x.x.x /path/to/DICOM/source' then make

\section DICOM_s3b Installation NEW:

You have to download and install DCMTK, see http://dicom.offis.de/dcmtk.php.en . At least you need version 3.6.1 or newer; the important thing is that you make sure it contains the dcmrt package.
Then define the enviromental variable DCMTK_BASE_DIR to point to the directory where you have installed it. 
And to run it, you have to add to the enviromental variable LD_LIBRARY_PATH the path ${DCMTK_BASE_DIR}/lib (i.e.  export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${DCMTK_BASE_DIR}/lib )

Then you have to set the enviromental variable DICOM_USE_DCMTK to 1. 
 - A standard Geant4 example GNUmakefile is provided, but have to uncomment the line 
\verbatim
#DICOM_USE_DCMTK := true                                                             
\endverbatim
 - Compile it with 'make'/'gmake'

 - A standard Geant4 example CMakeLists.txt is provided
 - Configure via cmake with 
\verbatim
 'cmake -DGeant4_DIR=/path_to_geant4_install/lib/Geant4-x.x.x \ 
        -DDCMTK_DIR=/path_to_dcmtk_install /path/to/DICOM/source' 
\endverbatim
 then make

\section DICOM_s3c CMake installation and inheriting from DICOM

 - Set the CMAKE_INSTALL_PREFIX (typically use the same install prefix as the Geant4 distribution)
 - Install the project
 - Installation will install libraries + DICOMConfig.cmake + other config files
   - if DCMTK is enabled, will also install dicomReader library + icomReaderConfig.cmake and it's other config files
 - In the new Geant4 application, add "find_package(DICOM REQUIRED)" to CMakeLists.txt
   - (optionally) add "set(DICOM_DIR ${Geant4_DIR} CACHE PATH "Path to DICOM installation config files") to CMakeLists.txt
   - add "include_directories(${DICOM_INCLUDE_DIRS}) and link target to ${DICOM_LIBRARIES}
   - if DCMTK is enabled, DICOMConfig.cmake will include the DCMTK and dicomReader installations, i.e. there is not need for "find_package(dicomReader)" or "find_package(DCMTK)"

\section DICOM_s4 Run the example:

 - To run the environment variable G4LEDATA needs to be set, pointing to the low energy data base, and the G4LEVELGAMMADATA pointing to the PhotonEvaporation data base

 - batch mode:
\verbatim
DICOM run.mac 
\endverbatim

 - interactive mode:
\verbatim
DICOM
\endverbatim
   the file vis.mac is read in order to visualise the phantom with OpenGL, DAWN or VRML

   
 - Environment variables:
   - DICOM_CHANGE_MATERIAL_DENSITY
     - set to the minimum density difference before making a separate material
     - e.g. if DenseBone is from > 1.496 to <= 1.654 and DICOM_CHANGE_MATERIAL_DENSITY=0.079
         then DenseBone would be separated into DenseBone > 1.496 to <= 1.575 and DenseBone > 1.575 to <= 1.654
   - DICOM_PARTIAL_PARAM
     - set to 1 to build the partial build instead of regular or nested construction (see section 9)
   - DICOM_NESTED_PARAM
     - set to 1 to build the nested construction (see section 9; overridden by DICOM_PARTIAL_PARAM)
   - DICOM_NTHREADS
     - To set the number of threads (when G4MULTITHREADED is defined via GEANT4_BUILD_MULTITHREADED=ON during Geant4 source build)
     - Needs to be set to the number of desired threads, e.g. DICOM_NTHREADS=8 (default is 4 threads)
   - DICOM_USE_HEAD
     - set to 1 (export DICOM_USE_HEAD=1) to use the digital head phantom documented in Giacometti, V., Guatelli, S., Bazalova-Carter, M., Rosenfeld, A.B., Schulte, R.W.,
       "Development of a high resolution voxelised head phantom for medical physics applications", (2017) Physica Medica, 33, pp. 182-188. 
       To use this option, the DICOM library needs to be downloaded. This is distributed with the other Geant4 data files on the Geant4 Download site.
       For convenience of use, it is suggested to have the DICOM library directory in the DICOM Geant4 extended example or in the directory containing the DICOM executable.
       When using this option,
       1) export DICOM_USE_HEAD=1
       2) export DICOM_PATH=path/to/DICOM1.1/DICOM_HEAD - to use the full DICOM HEAD project 
          or
          export DICOM_PATH=path/to/DICOM1.1/DICOM_HEAD_TEST - to use 4 DICOM files of the DICOM HEAD project. This option is useful for testing purposes.
       3) THE DICOM_HEAD uses the OLD version of the Metadata files (see point 4a)
       Note 1: The Conversion of Hounsfield numbers to materials (point 5) is not used. The material is associated to the voxel in the Detector Construction 
               without using the calibration curve.This happens because the DICOM project has already been segmented and cleaned from artefacts (see publication).

\section DICOM_s5 Metadata file:

The old version of "Data.dat" is found in "Data.dat.old", when the project is configured with DICOM_USE_DCMTK=OFF,
"Data.dat.old" is copied into the binary directory at "Data.dat".
  - i.e. cp ${PROJECT_SOURCE_DIR}/Data.dat.old ${PROJECT_BINARY_DIR}/Data.dat

The new version of "Data.dat" is found in "Data.dat.new", when the project is configured with DICOM_USE_DCMTK=ON,
"Data.dat.new" is copied into the binary directory as "Data.dat".
  - i.e. cp ${PROJECT_SOURCE_DIR}/Data.dat.new ${PROJECT_BINARY_DIR}/Data.dat

\section DICOM_s5a Metadata file, OLD version:

 The file Data.dat has the following information
  - A line with the compression value (used only to create the .g4dcm and .g4dcmb, not to read it)
  - A line with the number of files 
  - A line for each file name (to these names it will be added the suffix .dcm to read the DICOM files in their original format, and the suffix .g4dcm to read the text files that contain the DICOM information where the Hounsfield numbers have been converted to material and densities)

In case you want to convert DICOM files to text files, it must have the following lines:
  - The number of materials you want to use
  - A line for each material describing its name and the upper bound of the density interval. The materials should be described in increasing order of density. The voxels with a density between 0. and the first upper bound will be assigned to the first material, those with a density between the first upper bound and the second upper bound will be assigned to the second material, etc.

\section DICOM_s5b Metadata file, NEW version (based on DCMTK):

As for the previous version, a Data.dat file has to be defined to manage the conversion options. The format of this file is though quite different from the previous version. The format of this file is based on tags (similary to the ASCII geometry files).
The following tags should be used:

\subsection DICOM_s5b_sub1 :COMPRESSION level 
Where "level" is the number of voxels that will be merged into one in the X and Y dimen-
sions. The Hounsfield numbers of the voxels merged are averaged to give the
resulting value for the new voxel.\n
Example:
\verbatim
:COMPRESSION 4 
\endverbatim
4 X 4 voxels will be merged, so that the number of voxels in X and Y dimensions will be reduced by a factor 4

\subsection DICOM_s5b_sub2 :FILE file_name
These are the list of files (one line per file) in DICOM format that will be treated.
They can be of modality CT, RTSTRUCT or RTPLAN (the code will automatically
detect its modality and treat it correspondingly).\n
Example:
\verbatim
:FILE 1.dcm
:FILE 2.dcm
:FILE 3.dcm
\endverbatim

\subsection DICOM_s5b_sub3 :CT2D  Hounsfield_number density
These sets of value pairs build the calibration curve (linearly interpolating between them). In other words, each Hounsfield number is given a material density using a function that is built interpolating between this list of value pairs.\n
Example:
\verbatim
:CT2D -5000 0. 
:CT2D -1000 0.01 
:CT2D -400 0.602 
:CT2D  300 1.145 
:CT2D 2000 1.856
\endverbatim

\subsection DICOM_s5b_sub4 :MATE material_name upper_bound_of_material_Hounsfield_number_interval
This serves for the Hounsfield number to material name conversion. The voxels with a Hounsfield number between 0. and the first upper bound will be assigned to the first material, those with a Hounsfiled number between the first upper bound and the second upper bound will be assigned to the second material, etc.\n
Example:
\verbatim
:MATE G4_AIR -800
:MATE G4_LUNG_ICRP -145
:MATE G4_ADIPOSE_TISSUE_ICRP -60
:MATE G4_WATER 0
\endverbatim

Alternatively to the use of :MATE, you can use the :MATE_DENS
\subsection DICOM_s5b_sub5 :MATE_DENS material_name upper_bound_of_material_density_interval
This serves for the material density to material name conversion. The voxels with a density between 0. and the first upper bound will be assigned to the first material, those with a density between the first upper bound and the second upper bound will be assigned to the second material, etc.\n
Example:
\verbatim
:MATE_DENS G4_AIR 0.207
:MATE_DENS G4_LUNG_ICRP 0.919
:MATE_DENS G4_ADIPOSE_TISSUE_ICRP 0.979
:MATE_DENS G4_WATER 1.01
\endverbatim

We recommend the use of :MATE instead of :MATE_DENS as this is the way is used more often in the literature.

\subsection DICOM_s5b_sub6 :FILE_OUT file_name
Name of output file containing the DICOM information in ASCII format

\section DICOM_s6 Conversion of Hounsfield numbers to materials:

After reading the name of files from Data.dat, if a file .dcm is found, then it looks for the corresponding .g4dcm file and if not found creates it. 
Each file corresponds to a Z slice. The Z slices will be merged at runtime to form a unique patient volume; therefore the different slices have to be contiguous in Z.

The DICOM images pixel values represent CT (Hounsfield) numbers and they should be converted, first, to a given density and then to a material type.  The relation between CT number and density is more or less linear. 
The file CT2Density.dat contains the calibration curve to convert CT (Hounsfield) number to physical density
The assignment of material densities to materials is done following the information from the file Data.dat (see below). In this case we have used:

<pre>
           #####################################################
           #     Density Range                   Material      #
           #---------------------------------------------------#
           #       mg/cm3                            -         #
           #---------------------------------------------------#
           #  [ 0.    , 0.207 )                 Air            #
           #  [ 0.207 , 0.481 )                 Lungs (inhale) #
           #  [ 0.481 , 0.919 )                 Lungs (exhale) #
           #  [ 0.919 , 0.979 )                 Adipose        #
           #  [ 0.979 , 1.004 )                 Breast         #
           #  [ 1.004 , 1.043 )                 Phantom        #
           #  [ 1.043 , 1.109 )                 Liver          #
           #  [ 1.109 , 1.113 )                 Muscle         #
           #  [ 1.113 , 1.496 )                 Trabecular Bone#
           #  [ 1.496 , 1.654 ]                 Dense Bone     #
           #####################################################
</pre>

Data taken from the International Commission on Radiation Units and measurements (ICRU) report 46 was used to build the materials (lung, liver, breast, bones, ...)

\section DICOM_s7 Splitting materials in density intervals:

In the class DicomDetectorConstruction, it is defined a density interval

\verbatim
G4double densityDiff = 0.1;
\endverbatim

This means that the voxels of each material will be grouped in density intervals of 0.1 g/cm3 and a new material will be created for each group of voxels.

\section DICOM_s8 Voxel colouring:

The file Colormap.dat defines the colour that will be assigned to the voxels of each material.

\section DICOM_s9 DICOM file formats:

The DICOM files are converted to a simple text format. You may create your own file with the following format (see e.g. 14196616.g4dcm):

- A line with the number of materials
- A line for each material with its index and name (the same name of materials that you construct as G4Material's)
- A line with the number of voxels in X, Y and Z
- A line with the minimum and maximum extension in X (mm)
- A line with the minimum and maximum extension in Y (mm)
- A line with the minimum and maximum extension in Z (mm)
- A number of lines containing the nVoxelX*nVoxelY*nVoxelZ material indices (one per voxel)
- A number of lines containing the nVoxelX*nVoxelY*nVoxelZ material densities (one per voxel)

As commented before the DICOM files (.dcm) are assumed to describe one Z slice per file, and therefore the GEANT4 text files (.g4dcm) created from them have also one unique Z slice per file. Nevertheless if you create your own .g4dcm file you may include as many Z slices as desired. In any case you have to respect the rule that the Z slices must be contiguous.

The same information is also used to fill a file in binary format, that contains the same information as the text format. Its name ends in .g4dcmb, instead of .g4dcm .

\section DICOM_s10 Choosing different parameterisation/navigation options:

There are four possible ways in GEANT4 to treat the navigation in regular voxelised volumes:

-# The 3D optimisation with G4SmartVoxel: a 3D grid is built, so that the location of voxels is fast, but it requires a lot of memory
-# Using G4NestedParameterisation. The search is done hierarchically in X, Y and Z. It is fast and does not require big memory
-# Using G4PhantomParameterisation/G4RegularNavigation: an special algorithm to navigate in regular voxelised geometries (see GEANT4 doc). This is the fastest way without any extra memory requirement (and it is the default in this example). It includes an option (default) to skip frontiers between voxels when they have the same material. When using this option at each step the energy is all deposited in the last voxel; for properly distribution of the dose (=energy/volume) the G4PSDoseDeposit scorer can be used for *regular* navigation and G4PSDoseDeposit3D for *nested* parameterisation (see descriptions below).

Obsolete option:
-# The 1D optimisation . It will be very slow because each time a track exits a voxel it has to loop to all other voxels to know which one it may enter

You can select among the four options in the following way:

- By default the example will run with G4RegularNavigation

- To use the first option at RegularDicomDetectorConstruction.cc you just have to set
\verbatim
patient_phys->SetRegularStructureId(0);
\endverbatim

- To use the second option (Nested Parameterisation) you must set the enviromental variable DICOM_NESTED_PARAM to 1

- To use the final, obsolete 1D-option, apart from the change above at RegularDicomDetectorConstructio\
n.cc you need to replace (i.e. use kUndefined)
\verbatim
G4PVParameterised* patient_phys 
  = new G4PVParameterised("Patient",voxel_logic,container_logic,
	 		  kXAxis, nVoxelX*nVoxelY*nVoxelZ, param);
\endverbatim
by 
\verbatim
G4PVParameterised * patient_phys 
  = new G4PVParameterised("Patient",voxel_logic,container_logic,
			  kUndefined, nVoxelX*nVoxelY*nVoxelZ, param);
\endverbatim

Note also you must *not* set the enviromental variable DICOM_NESTED_PARAM.


\section DICOM_s11 Calculating dose in phantom voxels for regular navigation

As mentioned above the regular navigation has the option to keip voxel frontiers when two voxels share the same material, what can make the CPU time several times smaller. But this option makes that all energy deposited is computed in the last voxel, instead of distributing it along the voxels traversed. To properly calculate the dose in each voxel the G4PSDoseDeposit_RegNav scorer can be used.

It takes into account the fact that,  when the particle travels through the voxels it looses energy and therefore the energy lost per length (dEdx) is bigger and also the effect of the multiple scattering is bigger. 
The algorithm to make this correction is an iterative one, as the step length increase due multiple scattering (that converts the geometrical step length in what we will call the true step length) and the energy loss are correlated.
It works in the folloing way: first the total true step length is distributed among the voxels proportionally to their geometrical step length; with these values it is calculated one voxel after another the value of dEdx and then the value of the kinetic energy at the entrance of each voxel; with these values it is calculated the geometrical to true step corrections due to multiple scattering for each voxel; finally these new values are used to recalculate the energy lost in each voxel. It has been demonstrated for dose in a water phantom and in a real phantom that the two-step iteration described is enough to reproduce the dose calcualted when no skipping of voxel frontiers is done.

This scorer is implemented in this examples if the regular navigation option is 
chosen. It is triggered at the method RegularDicomDetectorConstruction::ConstructPhantom() by the call
\verbatim
SetScorer(voxel_logic);
\endverbatim

\section DICOM_s12 Calculating dose in phantom voxels for nested parameterisation

For the nested parameterisation the geometry comprises replicas in X and Y which are then parameterised in Z. This means that to get the correct voxel idendification the replica depth has to be taken into account. The G4PSDoseDeposit3D scorers uses a fixed algorithm to calculate the voxel ID, according to the number of voxels in each axes and the associated replica depth.
\verbatim
G4PSDoseDeposit3D("DoseDeposit", fNoVoxelsZ, fNoVoxelsY, fNoVoxelsX, 0, 2, 1)
\endverbatim
contains the number of voxels at the top (Z) level (0) and then two daughter levels down for the Y-voxels and one depth down for X.

\section DICOM_s13 Output
dicom.out is produced running the macro file run.mac. It has 2 columns: the first is the number of 
voxel (ordered in x,y,z) and the second the dose there deposited (in Gy)
It is produced, as an example, with a compression value of 32


\section DICOM_s14 Partial phantom 
It is possible to create a partial phantom, that is the intersection of a phantom with a volume. You may define the volume with the command 

\verbatim
/dicom/intersectWithUserVolume 0. 0. 0. 45.*deg 0. 0. TUBE 0. 150. 100.
\endverbatim

where the first three arguments are its position, its second three arguments are the rotation around the global X, Y and Z axis and the rest of the parameters are the same that you use to build a solid using the ASCII geometry format

Alternatively you can intersect the phantom with an existing Geant4 volume with the command

\verbatim
/dicom/intersectWithG4Volume VOLUME_NAME
\endverbatim

The job will create an ASCII file names "phantom.g4pdcm" containing the partial phantom. To read this file all what is needed is to set the enviromental variable DICOM_PARTIAL_PARAM to 1

\section DICOM_s15 Visualisation

The Geant4 drivers are not meant for visualizing millions of voxel and visualising the DICOM geometries can be very computationally demanding.
The users may want to visualise each DICOM slice separately or use higher compression values when visualising a part of DICOM project.

*/
