lama/elastix/deformations.py
def _get_deformations(tform: Path,
                      deformation_dir: Path,
                      jacobian_dir: Path,
                      log_jacobians_dir: Path,
                      filetype: str,
                      specimen_id: str,
                      threads: int,
                      make_jacmat: bool,
                      write_vectors: bool = False,
                      write_raw_jacobians: bool = False,
                      write_log_jacobians: bool = True) -> Union[None, np.array]:
    """
    Generate spatial jacobians and optionally deformation files.

    Returns
    -------
    the jacobian array if there are any values < 0
    """

    cmd = ['transformix',
           '-out', str(deformation_dir),
           '-tp', str(tform),
           '-jac', 'all'
           ]

    if write_vectors:
        cmd.extend(['-def', 'all'])
    if make_jacmat:
        cmd.extend(['-jacmat', 'all'])
    if threads:
        cmd.extend(['-threads', str(threads)])

    try:
        subprocess.check_output(cmd)

    except subprocess.CalledProcessError as e:
        logging.exception('transformix failed')
        logging.exception(e)
        # raise subprocess.CalledProcessError(f'### Transformix failed ###\nError message: {e}\nelastix command:{cmd}')
        raise ValueError
    else:
        deformation_out = deformation_dir / f'deformationField.{filetype}'
        jacobian_out = deformation_dir / f'spatialJacobian.{filetype}'

        # rename and move output
        if write_vectors:
            new_def = deformation_dir / (specimen_id + '.' + filetype)
            shutil.move(deformation_out, new_def)

        new_jac = jacobian_dir / (specimen_id + '.' + filetype)

        try:
            shutil.move(jacobian_out, new_jac)
        except IOError:
            #  Bit of a hack. If trasforms conatain subtransforms from pairwise, elastix is unable to generate
            # deformation fields. So try with itk
            def_img = sitk.ReadImage(new_def)
            jac_img = sitk.DisplacementFieldJacobianDeterminant(def_img)
            sitk.WriteImage(jac_img, new_jac)

        # if we have full jacobian matrix, rename and remove that
        if make_jacmat:
            make_jacmat.mkdir()
            jacmat_file = deformation_dir / f'fullSpatialJacobian.{filetype}'  # The name given by elastix
            jacmat_new = make_jacmat / (specimen_id + '.' + filetype)           # New informative name
            shutil.move(jacmat_file, jacmat_new)

        # test if there has been any folding in the jacobians
        jac_img = sitk.ReadImage(str(new_jac))
        jac_arr = sitk.GetArrayFromImage(jac_img)
        jac_min = jac_arr.min()
        jac_max = jac_arr.max()
        logging.info("{} spatial jacobian, min:{}, max:{}".format(specimen_id, jac_min, jac_max))

        if jac_min <= 0:
            logging.warning(
                "The jacobian determinant for {} has negative values. You may need to add a penalty term to the later registration stages".format(
                    specimen_id))
            # Highlight the regions folding
            jac_arr[jac_arr > 0] = 0
            log_jac_path = log_jacobians_dir / ('ERROR_NEGATIVE_JACOBIANS_' + specimen_id + '.' + filetype)
            common.write_array(jac_arr, log_jac_path)

        elif write_log_jacobians:
            # Spit out the log transformed jacobians
            log_jac = np.log(jac_arr)
            log_jac_path = log_jacobians_dir / ( 'log_jac_' + specimen_id + '.' + filetype)

            if not write_raw_jacobians:
                new_jac.unlink()

            common.write_array(log_jac, log_jac_path)


    logging.info('Finished generating deformation fields')

    if jac_min <=0:
        return jac_arr

    Generate spatial jacobians and optionally deformation files.

    Returns
    -------
    the jacobian array if there are any values < 0
    
Generate spatial jacobians and optionally deformation files.
Returns

the jacobian array if there are any values < 0
Generate spatial jacobians and optionally deformation files . Returns the jacobian array if there are any values < 0
def _get_deformations(tform: Path,
                      deformation_dir: Path,
                      jacobian_dir: Path,
                      log_jacobians_dir: Path,
                      filetype: str,
                      specimen_id: str,
                      threads: int,
                      make_jacmat: bool,
                      write_vectors: bool = False,
                      write_raw_jacobians: bool = False,
                      write_log_jacobians: bool = True) -> Union[None, np.array]:
    cmd = ['transformix',
           '-out', str(deformation_dir),
           '-tp', str(tform),
           '-jac', 'all'
           ]
    if write_vectors:
        cmd.extend(['-def', 'all'])
    if make_jacmat:
        cmd.extend(['-jacmat', 'all'])
    if threads:
        cmd.extend(['-threads', str(threads)])
    try:
        subprocess.check_output(cmd)
    except subprocess.CalledProcessError as e:
        logging.exception('transformix failed')
        logging.exception(e)
        raise ValueError
    else:
        deformation_out = deformation_dir / f'deformationField.{filetype}'
        jacobian_out = deformation_dir / f'spatialJacobian.{filetype}'
        if write_vectors:
            new_def = deformation_dir / (specimen_id + '.' + filetype)
            shutil.move(deformation_out, new_def)
        new_jac = jacobian_dir / (specimen_id + '.' + filetype)
        try:
            shutil.move(jacobian_out, new_jac)
        except IOError:
            def_img = sitk.ReadImage(new_def)
            jac_img = sitk.DisplacementFieldJacobianDeterminant(def_img)
            sitk.WriteImage(jac_img, new_jac)
        if make_jacmat:
            make_jacmat.mkdir()
            jacmat_file = deformation_dir / f'fullSpatialJacobian.{filetype}'  
            jacmat_new = make_jacmat / (specimen_id + '.' + filetype)           
            shutil.move(jacmat_file, jacmat_new)
        jac_img = sitk.ReadImage(str(new_jac))
        jac_arr = sitk.GetArrayFromImage(jac_img)
        jac_min = jac_arr.min()
        jac_max = jac_arr.max()
        logging.info("{} spatial jacobian, min:{}, max:{}".format(specimen_id, jac_min, jac_max))
        if jac_min <= 0:
            logging.warning(
                "The jacobian determinant for {} has negative values. You may need to add a penalty term to the later registration stages".format(
                    specimen_id))
            jac_arr[jac_arr > 0] = 0
            log_jac_path = log_jacobians_dir / ('ERROR_NEGATIVE_JACOBIANS_' + specimen_id + '.' + filetype)
            common.write_array(jac_arr, log_jac_path)
        elif write_log_jacobians:
            log_jac = np.log(jac_arr)
            log_jac_path = log_jacobians_dir / ( 'log_jac_' + specimen_id + '.' + filetype)
            if not write_raw_jacobians:
                new_jac.unlink()
            common.write_array(log_jac, log_jac_path)
    logging.info('Finished generating deformation fields')
    if jac_min <=0:
        return jac_arr
def _get_deformations ( tform : Path , deformation_dir : Path , jacobian_dir : Path , log_jacobians_dir : Path , filetype : str , specimen_id : str , threads : int , make_jacmat : bool , write_vectors : bool = False , write_raw_jacobians : bool = False , write_log_jacobians : bool = True ) -> Union [ None , np . array ] : cmd = [ 'transformix' , '-out' , str ( deformation_dir ) , '-tp' , str ( tform ) , '-jac' , 'all' ] if write_vectors : cmd . extend ( [ '-def' , 'all' ] ) if make_jacmat : cmd . extend ( [ '-jacmat' , 'all' ] ) if threads : cmd . extend ( [ '-threads' , str ( threads ) ] ) try : subprocess . check_output ( cmd ) except subprocess . CalledProcessError as e : logging . exception ( 'transformix failed' ) logging . exception ( e ) raise ValueError else : deformation_out = deformation_dir / f'deformationField.{filetype}' jacobian_out = deformation_dir / f'spatialJacobian.{filetype}' if write_vectors : new_def = deformation_dir / ( specimen_id + '.' + filetype ) shutil . move ( deformation_out , new_def ) new_jac = jacobian_dir / ( specimen_id + '.' + filetype ) try : shutil . move ( jacobian_out , new_jac ) except IOError : def_img = sitk . ReadImage ( new_def ) jac_img = sitk . DisplacementFieldJacobianDeterminant ( def_img ) sitk . WriteImage ( jac_img , new_jac ) if make_jacmat : make_jacmat . mkdir ( ) jacmat_file = deformation_dir / f'fullSpatialJacobian.{filetype}' jacmat_new = make_jacmat / ( specimen_id + '.' + filetype ) shutil . move ( jacmat_file , jacmat_new ) jac_img = sitk . ReadImage ( str ( new_jac ) ) jac_arr = sitk . GetArrayFromImage ( jac_img ) jac_min = jac_arr . min ( ) jac_max = jac_arr . max ( ) logging . info ( "{} spatial jacobian, min:{}, max:{}" . format ( specimen_id , jac_min , jac_max ) ) if jac_min <= 0 : logging . warning ( "The jacobian determinant for {} has negative values. You may need to add a penalty term to the later registration stages" . format ( specimen_id ) ) jac_arr [ jac_arr > 0 ] = 0 log_jac_path = log_jacobians_dir / ( 'ERROR_NEGATIVE_JACOBIANS_' + specimen_id + '.' + filetype ) common . write_array ( jac_arr , log_jac_path ) elif write_log_jacobians : log_jac = np . log ( jac_arr ) log_jac_path = log_jacobians_dir / ( 'log_jac_' + specimen_id + '.' + filetype ) if not write_raw_jacobians : new_jac . unlink ( ) common . write_array ( log_jac , log_jac_path ) logging . info ( 'Finished generating deformation fields' ) if jac_min <= 0 : return jac_arr
Generate spatial jacobians and optionally deformation files.
Generate spatial jacobians and optionally deformation files .
"""
    Generate spatial jacobians and optionally deformation files.

    Returns
    -------
    the jacobian array if there are any values < 0
    """ # raise subprocess.CalledProcessError(f'### Transformix failed ###\nError message: {e}\nelastix command:{cmd}') # rename and move output #  Bit of a hack. If trasforms conatain subtransforms from pairwise, elastix is unable to generate # deformation fields. So try with itk # if we have full jacobian matrix, rename and remove that # The name given by elastix # New informative name # test if there has been any folding in the jacobians # Highlight the regions folding # Spit out the log transformed jacobians
tform
Path
deformation_dir
Path
jacobian_dir
Path
log_jacobians_dir
Path
filetype
str
specimen_id
str
threads
int
make_jacmat
bool
write_vectors
bool
write_raw_jacobians
bool
write_log_jacobians
bool