<commit_before># vtk includes
from __main__ import vtk
import logging


class LevelSetSegmentationLogic( object ):
    '''
    classdocs
    '''


    def __init__( self ):
        '''
        Constructor
        '''


    def performInitialization( self, image, lowerThreshold, upperThreshold, sourceSeedIds, targetSeedIds, method="collidingfronts" ):
        '''
        '''
        # import the vmtk libraries
        try:
            import vtkvmtkSegmentationPython as vtkvmtkSegmentation
        except ImportError:
            logging.error("Unable to import the SlicerVmtk libraries")

        cast = vtk.vtkImageCast()
        cast.SetInputData( image )
        cast.SetOutputScalarTypeToFloat()
        cast.Update()
        image = cast.GetOutput()

        scalarRange = image.GetScalarRange()

        imageDimensions = image.GetDimensions()
        maxImageDimensions = max( imageDimensions )

        threshold = vtk.vtkImageThreshold()
        threshold.SetInputData( image )
        threshold.ThresholdBetween( lowerThreshold, upperThreshold )
        threshold.ReplaceInOff()
        threshold.ReplaceOutOn()
        threshold.SetOutValue( scalarRange[0] - scalarRange[1] )
        threshold.Update()

        thresholdedImage = threshold.GetOutput()

        scalarRange = thresholdedImage.GetScalarRange()

        shiftScale = vtk.vtkImageShiftScale()
        shiftScale.SetInputData( thresholdedImage )
        shiftScale.SetShift( -scalarRange[0] )
        shiftScale.SetScale( 1.0 / ( scalarRange[1] - scalarRange[0] ) )
        shiftScale.Update()

        speedImage = shiftScale.GetOutput()

        if method == "collidingfronts":
            # ignore sidebranches, use colliding fronts
            logging.debug("Using Colliding fronts")
            logging.debug("number of vtk ids: " + str(sourceSeedIds.GetNumberOfIds()))
            logging.debug("SourceSeedIds:")
            logging.debug(sourceSeedIds)
            collidingFronts = vtkvmtkSegmentation.vtkvmtkCollidingFrontsImageFilter()
            collidingFronts.SetInputData( speedImage )
            sourceSeedId1 = vtk.vtkIdList()
            sourceSeedId1.InsertNextId( sourceSeedIds.GetId(0) )
            sourceSeedId2 = vtk.vtkIdList()
            sourceSeedId2.InsertNextId( sourceSeedIds.GetId(1) )
            collidingFronts.SetSeeds1( sourceSeedId1 )
            collidingFronts.SetSeeds2( sourceSeedId2 )
            collidingFronts.ApplyConnectivityOn()
            collidingFronts.StopOnTargetsOn()
            collidingFronts.Update()

            subtract = vtk.vtkImageMathematics()
            subtract.SetInputData( collidingFronts.GetOutput() )
            subtract.SetOperationToAddConstant()
            subtract.SetConstantC( -10 * collidingFronts.GetNegativeEpsilon() )
            subtract.Update()

        elif method == "fastmarching":
            fastMarching = vtkvmtkSegmentation.vtkvmtkFastMarchingUpwindGradientImageFilter()
            fastMarching.SetInputData( speedImage )
            fastMarching.SetSeeds( sourceSeedIds )
            fastMarching.GenerateGradientImageOn()
            fastMarching.SetTargetOffset( 0.0 )
            fastMarching.SetTargets( targetSeedIds )
            if targetSeedIds.GetNumberOfIds() > 0:
                fastMarching.SetTargetReachedModeToOneTarget()
            else:
                fastMarching.SetTargetReachedModeToNoTargets()
            fastMarching.Update()

            if targetSeedIds.GetNumberOfIds() > 0:
                subtract = vtk.vtkImageMathematics()
                subtract.SetInputData( fastMarching.GetOutput() )
                subtract.SetOperationToAddConstant()
                subtract.SetConstantC( -fastMarching.GetTargetValue() )
                subtract.Update()

            else:
                subtract = vtk.vtkImageThreshold()
                subtract.SetInputData( fastMarching.GetOutput() )
                subtract.ThresholdByLower( 2000 )  # TODO find robuste value
                subtract.ReplaceInOff()
                subtract.ReplaceOutOn()
                subtract.SetOutValue( -1 )
                subtract.Update()
        
        elif method == "threshold":
            raise NotImplementedError()
        elif method == "isosurface":
            raise NotImplementedError()
        elif method == "seeds":
            raise NotImplementedError()
        else:
            raise NameError()

        outImageData = vtk.vtkImageData()
        outImageData.DeepCopy( subtract.GetOutput() )

        return outImageData



    def performEvolution( self, originalImage, segmentationImage, numberOfIterations, inflation, curvature, attraction, method='geodesic' ):
        '''

        '''
        # import the vmtk libraries
        try:
            import vtkvmtkSegmentationPython as vtkvmtkSegmentation
        except ImportError:
            logging.error("Unable to import the SlicerVmtk libraries")

        featureDerivativeSigma = 0.0
        maximumRMSError = 1E-20
        isoSurfaceValue = 0.0

        logging.debug("NumberOfIterations: " + str(numberOfIterations))
        logging.debug("inflation: " + str(inflation))
        logging.debug("curvature: " + str(curvature))
        logging.debug("attraction: " + str(attraction))

        if method == 'curves':
            levelSets = vtkvmtkSegmentation.vtkvmtkCurvesLevelSetImageFilter()
        else:
            logging.debug("using vtkvmtkGeodesicActiveContourLevelSetImageFilter")
            levelSets = vtkvmtkSegmentation.vtkvmtkGeodesicActiveContourLevelSetImageFilter()

        levelSets.SetFeatureImage( self.buildGradientBasedFeatureImage( originalImage ) )
        levelSets.SetDerivativeSigma( featureDerivativeSigma )
        levelSets.SetAutoGenerateSpeedAdvection( 1 )
        levelSets.SetPropagationScaling( inflation * ( -1 ) )
        levelSets.SetCurvatureScaling( curvature )
        levelSets.SetAdvectionScaling( attraction * ( -1 ) )
        levelSets.SetInputData( segmentationImage )
        levelSets.SetNumberOfIterations( numberOfIterations )
        levelSets.SetIsoSurfaceValue( isoSurfaceValue )<commit_msg>ENH: added levelsetstype switch in levelsetsegmentation<commit_after># vtk includes
from __main__ import vtk
import logging


class LevelSetSegmentationLogic( object ):
    '''
    classdocs
    '''


    def __init__( self ):
        '''
        Constructor
        '''


    def performInitialization( self, image, lowerThreshold, upperThreshold, sourceSeedIds, targetSeedIds, method="collidingfronts" ):
        '''
        '''
        # import the vmtk libraries
        try:
            import vtkvmtkSegmentationPython as vtkvmtkSegmentation
        except ImportError:
            logging.error("Unable to import the SlicerVmtk libraries")

        cast = vtk.vtkImageCast()
        cast.SetInputData( image )
        cast.SetOutputScalarTypeToFloat()
        cast.Update()
        image = cast.GetOutput()

        scalarRange = image.GetScalarRange()

        imageDimensions = image.GetDimensions()
        maxImageDimensions = max( imageDimensions )

        threshold = vtk.vtkImageThreshold()
        threshold.SetInputData( image )
        threshold.ThresholdBetween( lowerThreshold, upperThreshold )
        threshold.ReplaceInOff()
        threshold.ReplaceOutOn()
        threshold.SetOutValue( scalarRange[0] - scalarRange[1] )
        threshold.Update()

        thresholdedImage = threshold.GetOutput()

        scalarRange = thresholdedImage.GetScalarRange()

        shiftScale = vtk.vtkImageShiftScale()
        shiftScale.SetInputData( thresholdedImage )
        shiftScale.SetShift( -scalarRange[0] )
        shiftScale.SetScale( 1.0 / ( scalarRange[1] - scalarRange[0] ) )
        shiftScale.Update()

        speedImage = shiftScale.GetOutput()

        if method == "collidingfronts":
            # ignore sidebranches, use colliding fronts
            logging.debug("Using Colliding fronts algorithm")
            logging.debug("number of vtk ids: " + str(sourceSeedIds.GetNumberOfIds()))
            logging.debug("SourceSeedIds:")
            logging.debug(sourceSeedIds)
            collidingFronts = vtkvmtkSegmentation.vtkvmtkCollidingFrontsImageFilter()
            collidingFronts.SetInputData( speedImage )
            sourceSeedId1 = vtk.vtkIdList()
            sourceSeedId1.InsertNextId( sourceSeedIds.GetId(0) )
            sourceSeedId2 = vtk.vtkIdList()
            sourceSeedId2.InsertNextId( sourceSeedIds.GetId(1) )
            collidingFronts.SetSeeds1( sourceSeedId1 )
            collidingFronts.SetSeeds2( sourceSeedId2 )
            collidingFronts.ApplyConnectivityOn()
            collidingFronts.StopOnTargetsOn()
            collidingFronts.Update()

            subtract = vtk.vtkImageMathematics()
            subtract.SetInputData( collidingFronts.GetOutput() )
            subtract.SetOperationToAddConstant()
            subtract.SetConstantC( -10 * collidingFronts.GetNegativeEpsilon() )
            subtract.Update()

        elif method == "fastmarching":
            fastMarching = vtkvmtkSegmentation.vtkvmtkFastMarchingUpwindGradientImageFilter()
            fastMarching.SetInputData( speedImage )
            fastMarching.SetSeeds( sourceSeedIds )
            fastMarching.GenerateGradientImageOn()
            fastMarching.SetTargetOffset( 0.0 )
            fastMarching.SetTargets( targetSeedIds )
            if targetSeedIds.GetNumberOfIds() > 0:
                fastMarching.SetTargetReachedModeToOneTarget()
            else:
                fastMarching.SetTargetReachedModeToNoTargets()
            fastMarching.Update()

            if targetSeedIds.GetNumberOfIds() > 0:
                subtract = vtk.vtkImageMathematics()
                subtract.SetInputData( fastMarching.GetOutput() )
                subtract.SetOperationToAddConstant()
                subtract.SetConstantC( -fastMarching.GetTargetValue() )
                subtract.Update()

            else:
                subtract = vtk.vtkImageThreshold()
                subtract.SetInputData( fastMarching.GetOutput() )
                subtract.ThresholdByLower( 2000 )  # TODO find robuste value
                subtract.ReplaceInOff()
                subtract.ReplaceOutOn()
                subtract.SetOutValue( -1 )
                subtract.Update()
        
        elif method == "threshold":
            raise NotImplementedError()
        elif method == "isosurface":
            raise NotImplementedError()
        elif method == "seeds":
            raise NotImplementedError()
        else:
            raise NameError('Unsupported InitializationType')

        outImageData = vtk.vtkImageData()
        outImageData.DeepCopy( subtract.GetOutput() )

        return outImageData



    def performEvolution( self, originalImage, segmentationImage, numberOfIterations, inflation, curvature, attraction, levelSetsType='geodesic' ):
        '''

        '''
        # import the vmtk libraries
        try:
            import vtkvmtkSegmentationPython as vtkvmtkSegmentation
        except ImportError:
            logging.error("Unable to import the SlicerVmtk libraries")

        featureDerivativeSigma = 0.0
        maximumRMSError = 1E-20
        isoSurfaceValue = 0.0

        logging.debug("NumberOfIterations: " + str(numberOfIterations))
        logging.debug("inflation: " + str(inflation))
        logging.debug("curvature: " + str(curvature))
        logging.debug("attraction: " + str(attraction))

        if levelSetsType == 'geodesic':
            logging.debug("using vtkvmtkGeodesicActiveContourLevelSetImageFilter")
            levelSets = vtkvmtkSegmentation.vtkvmtkGeodesicActiveContourLevelSetImageFilter()
            levelSets.SetFeatureImage( self.buildGradientBasedFeatureImage( originalImage ) )
            levelSets.SetDerivativeSigma( featureDerivativeSigma )
            levelSets.SetAutoGenerateSpeedAdvection( 1 )
            levelSets.SetPropagationScaling( inflation * ( -1 ) )
            levelSets.SetCurvatureScaling( curvature )
            levelSets.SetAdvectionScaling( attraction * ( -1 ) )
        elif levelSetsType == 'curves':
            levelSets = vtkvmtkSegmentation.vtkvmtkCurvesLevelSetImageFilter()
            levelSets.SetFeatureImage( self.buildGradientBasedFeatureImage( originalImage ) )
            levelSets.SetDerivativeSigma( featureDerivativeSigma )
            levelSets.SetAutoGenerateSpeedAdvection( 1 )
            levelSets.SetPropagationScaling( inflation * ( -1 ) )
            levelSets.SetCurvatureScaling( curvature )
            levelSets.SetAdvectionScaling( attraction * ( -1 ) )
        elif levelSetsType == 'threshold':
            raise NotImplementedError()
        elif levelSetsType == 'laplacian':
            raise NotImplementedError()
        else:
            raise NameError('Unsupported LevelSetsType')

        levelSets.SetInputData( segmentationImage )
        levelSets.SetNumberOfIterations( numberOfIterations )
        levelSets.SetIsoSurfaceValue( isoSurfaceValue )
{'fraction_non_alphanumeric': 0.08077011582419268, 'fraction_numerical': 0.006059676305898596, 'mean_word_length': 2.4184583114840064, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6035172', 'n_tokens_mistral': 3665, 'n_tokens_neox': 3484, 'n_words': 594}