def _contruct_ilang_model(self): self.ilang_model = ModelRigidSSD('RigidSSD') self.graph = ProbabilisticGraphicalModel(['target','source','transformation']) self.graph.set_nodes_given(['target','source'],True) self.graph.set_node_value('source',self.source.get_data()) self.graph.set_node_value('target',self.target.get_data()) self.graph.set_node_value('transformation',numpy.zeros((1,6))) self.graph.add_dependence(self.ilang_model,{'target':'target','source':'source','transformation':'transformation'}) self.sampler = Sampler(self.graph)
def __make_graph(self): self.ilang_model = SSD_ilang() # The following is an alternative use of ilang models: define the log_p and gradient functions here in order to have access to # the local variables. self.ilang_model.log_conditional_probability_transformation = self.__P self.ilang_model.log_conditional_probability_gradient_transformation = self.__G self.ilang_graph = ProbabilisticGraphicalModel( ['source', 'target', 'transformation', 'sigma']) self.ilang_graph.set_nodes_given(['sigma', 'source', 'target'], True) self.ilang_graph.add_dependence( self.ilang_model, { 'source': 'source', 'target': 'target', 'sigma': 'sigma', 'transformation': 'transformation' }) self.ilang_sampler = Sampler(self.ilang_graph)
def __make_graph(self): self.ilang_graph = ProbabilisticGraphicalModel() for i in range(len(self.__images)): self.ilang_graph.add_node('im_%d' % i) self.ilang_graph.set_nodes_given([ 'im_%d' % i, ], True) for i in range(len(self.__images) - 1): self.ilang_graph.add_nodes(['sigma_%d' % i, 'T_%d' % i]) self.ilang_graph.set_nodes_given([ 'sigma_%d' % i, ], True) model = SSD_ilang('SSD_%d' % i) self.ilang_graph.add_dependence( model, { 'sigma': 'sigma_%d' % i, 'transformation': 'T_%d' % i, 'source': 'im_%d' % i, 'target': 'im_%d' % (i + 1) }) self.ilang_sampler = Sampler(self.ilang_graph)
def __make_graph(self): self.ilang_model = SSD_ilang() # The following is an alternative use of ilang models: define the log_p and gradient functions here in order to have access to # the local variables. self.ilang_model.log_conditional_probability_transformation = self.__P self.ilang_model.log_conditional_probability_gradient_transformation = self.__G self.ilang_graph = ProbabilisticGraphicalModel(["source", "target", "transformation", "sigma"]) self.ilang_graph.set_nodes_given(["sigma", "source", "target"], True) self.ilang_graph.add_dependence( self.ilang_model, {"source": "source", "target": "target", "sigma": "sigma", "transformation": "transformation"}, ) self.ilang_sampler = Sampler(self.ilang_graph)
def __make_graph(self): self.ilang_graph = ProbabilisticGraphicalModel() self.ilang_graph.add_node("template") for i in range(len(self.__images)): self.ilang_graph.add_node("im_%d" % i) self.ilang_graph.set_nodes_given(["im_%d" % i], True) for i in range(len(self.__images)): self.ilang_graph.add_nodes(["sigma_%d" % i, "T_%d" % i]) self.ilang_graph.set_nodes_given(["sigma_%d" % i], True) model = SSD_ilang("SSD_%d" % i) self.ilang_graph.add_dependence( model, {"sigma": "sigma_%d" % i, "transformation": "T_%d" % i, "source": "im_%d" % i, "target": "template"}, ) self.ilang_sampler = Sampler(self.ilang_graph)
class Registration_N_Images(): def __init__(self, images): self.__images = images self.__make_graph() def set_transformation(self, tr): pass def set_cost_function(self, cost): pass def register(self): pass def __make_graph(self): self.ilang_graph = ProbabilisticGraphicalModel() self.ilang_graph.add_node('template') for i in range(len(self.__images)): self.ilang_graph.add_node('im_%d' % i) self.ilang_graph.set_nodes_given([ 'im_%d' % i, ], True) for i in range(len(self.__images)): self.ilang_graph.add_nodes(['sigma_%d' % i, 'T_%d' % i]) self.ilang_graph.set_nodes_given([ 'sigma_%d' % i, ], True) model = SSD_ilang('SSD_%d' % i) self.ilang_graph.add_dependence( model, { 'sigma': 'sigma_%d' % i, 'transformation': 'T_%d' % i, 'source': 'im_%d' % i, 'target': 'template' }) self.ilang_sampler = Sampler(self.ilang_graph) def _repr_html_(self): return self.ilang_graph._repr_html_() def __repr__(self): return "Registration of N images. "
class Registration_Two_Images(object): def __init__(self, source=None, target=None, degrees_of_freedom=3, sigma=DEFAULT_SIGMA, initial_transformation=None): self.set_source(source) self.set_target(target) self.set_sigma(sigma) self.__make_graph() if initial_transformation == None: self.set_transformation(numpy.zeros(degrees_of_freedom)) else: self.set_transformation(initial_transformation) def __make_graph(self): self.ilang_model = SSD_ilang() # The following is an alternative use of ilang models: define the log_p and gradient functions here in order to have access to # the local variables. self.ilang_model.log_conditional_probability_transformation = self.__P self.ilang_model.log_conditional_probability_gradient_transformation = self.__G self.ilang_graph = ProbabilisticGraphicalModel( ['source', 'target', 'transformation', 'sigma']) self.ilang_graph.set_nodes_given(['sigma', 'source', 'target'], True) self.ilang_graph.add_dependence( self.ilang_model, { 'source': 'source', 'target': 'target', 'sigma': 'sigma', 'transformation': 'transformation' }) self.ilang_sampler = Sampler(self.ilang_graph) def __set_space(self): # make sure that the images are in the same space if self.source.space != self.target.space: raise "Source [%s] and Target [%s] must be in the same space" % ( source.space, target.space) self.space = self.source.space def set_transformation(self, tr): self.__transformation = tr def __get_transformation(self): return self.__transformation def set_cost_function(self, cost): pass def __initialize_registration(self, optimization_method='QuasiNewton_L_BFGS_B', n_points=DEFAULT_N_POINTS): self.ilang_graph.set_node_value('source', self.source.data) self.ilang_graph.set_node_value('target', self.target.data) self.ilang_graph.set_node_value('sigma', self.sigma) if n_points == None: n_points = self.target.shape self.grid = self.target.get_world_grid(n_points) self.resampled_target = self.target.compute_resample_on_grid(self.grid) self.ilang_sampler.set_node_sampling_method_manual( 'transformation', optimization_method) def register(self, optimization_method='GradientAscent', iterations=DEFAULT_N_ITER, n_points=DEFAULT_N_POINTS): self.__initialize_registration(optimization_method, n_points) self.ilang_graph.set_node_value('transformation', self.transformation) self.ilang_sampler.sample(iterations) self.transformation = self.ilang_graph.get_node_value('transformation') def set_source(self, source): self.source = source if hasattr(self, 'target'): self.__set_space() def set_target(self, target): self.target = target if hasattr(self, 'source'): self.__set_space() def set_sigma(self, sigma): self.sigma = sigma def get_result(self): result = self.source.copy() result.transform(self.get_transformation_matrix()) return result def get_transformation_matrix(self): #rot = self.__transformation[0:3] #tra = self.__transformation[3:6] tra = self.__transformation return Transform_Translation( tra, self.space, self.space) #FIXME: rotation and translation def display(self): D = MultipleVolumesNiftyCore( [self.source, self.target, self.get_result()]) #D = MultipleVolumes([self.source, self.target]) return D def __G(self, transformation): # print "Transformation: ", transformation #rot = transformation[0:3] #tra = transformation[3:6] tra = transformation T = Transform_Translation(tra, self.space, self.space) #FIXME: rotation and translation re_s = self.source.compute_resample_on_grid( self.grid, affine_grid_to_world=T) #FIXME: memoize gr_s = self.source.compute_gradient_on_grid(self.grid, affine_grid_to_world=T) re_t = self.resampled_target G_tra0 = (re_t.data - re_t.data * gr_s[0]).sum() G_tra1 = (re_t.data - re_t.data * gr_s[1]).sum() G_tra2 = (re_t.data - re_t.data * gr_s[2]).sum() G_tra = [G_tra0, G_tra1, G_tra2] G = numpy.asarray([G_tra[0], G_tra[1], G_tra[2]]) / self.sigma # print "gradient: ", G # print "log_likelihood: ", self.__P(transformation) return G def __P(self, transformation): # FIXME: memoize (now image is resampled to compute log_p and the gradient) #print transformation #rot = transformation[0:3] #tra = transformation[3:6] tra = transformation T = Transform_Translation(tra, self.space, self.space) #FIXME: rotation and translation resampled_source = self.source.compute_resample_on_grid( self.grid, affine_grid_to_world=T) P = -numpy.linalg.norm(resampled_source.data - self.resampled_target. data) / self.sigma #FIXME: verify # print "log_likelihood: ", P return P def _repr_html_(self): #return self.ilang_graph._repr_html_() return self.display()._repr_html_() def __repr__(self): return "Registration of 2 images." transformation = property(__get_transformation, set_transformation)
class RigidTransformationSSD(): def __init__(self,target,source): self.target = target self.source = source self._resampled_source_cache = None self._resampled_source_need_update = True self._contruct_ilang_model() self._set_transformation(numpy.zeros((1,6))) def _contruct_ilang_model(self): self.ilang_model = ModelRigidSSD('RigidSSD') self.graph = ProbabilisticGraphicalModel(['target','source','transformation']) self.graph.set_nodes_given(['target','source'],True) self.graph.set_node_value('source',self.source.get_data()) self.graph.set_node_value('target',self.target.get_data()) self.graph.set_node_value('transformation',numpy.zeros((1,6))) self.graph.add_dependence(self.ilang_model,{'target':'target','source':'source','transformation':'transformation'}) self.sampler = Sampler(self.graph) def _set_transformation(self,transformation): self.graph.set_node_value('transformation',transformation) self._resampled_source_need_update = True def _get_transformation(self): return self.graph.get_node_value('transformation') def estimate_transformation(self,method=None,iterations=30000,trace=True,parameters=None, display_progress=True): if method!=None: self.sampler.set_node_sampling_method_manual('transformation',method) else: self.sampler.set_node_sampling_method_auto('transformation') last_sample = self.sampler.sample_node('transformation',nsamples=iterations,trace=trace) # This is not necessary, but it triggers the cache of the resampled source image: self._set_transformation(last_sample) return last_sample def resample_in_target_space(self,image): # FIXME #print "Resampling .." transformation = self._get_transformation() return image def _get_resampled_source(self): #FIXME: remove the next few lines if self.transformation.sum() != 0: return self.target if self._resampled_source_need_update: resampled_source = self.resample_in_target_space(self.source) self._resampled_source_cache = resampled_source self._resampled_source_need_update = False else: resampled_source = self._resampled_source_cache return resampled_source def display_in_browser(self,axis=0,shrink=256,rotate=90,subsample_slices=4,scale_factors=None): self.display(axis,shrink,rotate,scale_factors,open_browser=True) def display(self,axis=0,shrink=256,rotate=90,subsample_slices=4,scale_factors=None,open_browser=False): resampled = self.resampled_source D = MultipleVolumes([resampled,self.target], axis, shrink, rotate, subsample_slices, scale_factors, open_browser) return D.display() def _repr_html_(self): return self.display()._repr_html_() transformation = property(_get_transformation, _set_transformation, None) resampled_source = property(_get_resampled_source, None, None)
from ilang.Graphs import Dependence, ProbabilisticGraphicalModel from ilang.Models import Poisson, Smoothness from ilang.Samplers import Sampler from ilang.Tracers import RamTracer from ilang.Display import MatplotlibDisplay import numpy # Define the model components observation = Poisson('SPECT') prior_activity = Smoothness('Smoothing_Activity') prior_attenuation = Smoothness('Smoothing_Attenuation') # Build the graph dag = ProbabilisticGraphicalModel(['activity','attenuation','counts','smoothing-activity','smoothing-attenuation']) dag.set_nodes_given(['counts','smoothing-activity','smoothing-attenuation'], True) dag.add_dependence(observation,{'lambda':'activity','alpha':'attenuation','z':'counts'}) dag.add_dependence(prior_activity,{'x':'activity','beta':'smoothing-activity'}) dag.add_dependence(prior_attenuation,{'x':'attenuation','beta':'smoothing-attenuation'}) # Initialize the nodes of the graph dag.set_node_value('activity',numpy.ones((10,10))) # Instantiate the sampler, tracer and display sampler = Sampler(dag) tracer = RamTracer(sampler) display = MatplotlibDisplay(tracer) # Sample sampler.sample(1000,trace=False)
class RigidTransformationSSD(): def __init__(self, target, source): self.target = target self.source = source self._resampled_source_cache = None self._resampled_source_need_update = True self._contruct_ilang_model() self._set_transformation(numpy.zeros((1, 6))) def _contruct_ilang_model(self): self.ilang_model = ModelRigidSSD('RigidSSD') self.graph = ProbabilisticGraphicalModel( ['target', 'source', 'transformation']) self.graph.set_nodes_given(['target', 'source'], True) self.graph.set_node_value('source', self.source.get_data()) self.graph.set_node_value('target', self.target.get_data()) self.graph.set_node_value('transformation', numpy.zeros((1, 6))) self.graph.add_dependence( self.ilang_model, { 'target': 'target', 'source': 'source', 'transformation': 'transformation' }) self.sampler = Sampler(self.graph) def _set_transformation(self, transformation): self.graph.set_node_value('transformation', transformation) self._resampled_source_need_update = True def _get_transformation(self): return self.graph.get_node_value('transformation') def estimate_transformation(self, method=None, iterations=30000, trace=True, parameters=None, display_progress=True): if method != None: self.sampler.set_node_sampling_method_manual( 'transformation', method) else: self.sampler.set_node_sampling_method_auto('transformation') last_sample = self.sampler.sample_node('transformation', nsamples=iterations, trace=trace) # This is not necessary, but it triggers the cache of the resampled source image: self._set_transformation(last_sample) return last_sample def resample_in_target_space(self, image): # FIXME #print "Resampling .." transformation = self._get_transformation() return image def _get_resampled_source(self): #FIXME: remove the next few lines if self.transformation.sum() != 0: return self.target if self._resampled_source_need_update: resampled_source = self.resample_in_target_space(self.source) self._resampled_source_cache = resampled_source self._resampled_source_need_update = False else: resampled_source = self._resampled_source_cache return resampled_source def display_in_browser(self, axis=0, shrink=256, rotate=90, subsample_slices=4, scale_factors=None): self.display(axis, shrink, rotate, scale_factors, open_browser=True) def display(self, axis=0, shrink=256, rotate=90, subsample_slices=4, scale_factors=None, open_browser=False): resampled = self.resampled_source D = MultipleVolumes([resampled, self.target], axis, shrink, rotate, subsample_slices, scale_factors, open_browser) return D.display() def _repr_html_(self): return self.display()._repr_html_() transformation = property(_get_transformation, _set_transformation, None) resampled_source = property(_get_resampled_source, None, None)
from ilang.Graphs import Dependence, ProbabilisticGraphicalModel from ilang.Models import MultivariateGaussian from ilang.Samplers import Sampler from ilang.Tracers import RamTracer from ilang.Display import MatplotlibDisplay import numpy # Define the model ndim = 10 model = MultivariateGaussian('gaussian') # Build the graph dag = ProbabilisticGraphicalModel(['x','mu','cov']) dag.set_nodes_given(['mu','cov'], True) dag.add_dependence(model,{'x':'x','mu':'mu','cov':'cov'}) # Initialize the nodes of the graph dag.set_node_value('x',numpy.ones((1,ndim))) dag.set_node_value('mu',numpy.zeros((1,ndim))) dag.set_node_value('cov',numpy.eye(ndim)) # Initialise sampler, tracer, display sampler = Sampler(dag) tracer = RamTracer(sampler) display = MatplotlibDisplay(tracer) # Sample sampler.sample(1000,trace=False)
class Registration_N_Images: def __init__(self, images): self.__images = images self.__make_graph() def set_transformation(self, tr): pass def set_cost_function(self, cost): pass def register(self): pass def __make_graph(self): self.ilang_graph = ProbabilisticGraphicalModel() self.ilang_graph.add_node("template") for i in range(len(self.__images)): self.ilang_graph.add_node("im_%d" % i) self.ilang_graph.set_nodes_given(["im_%d" % i], True) for i in range(len(self.__images)): self.ilang_graph.add_nodes(["sigma_%d" % i, "T_%d" % i]) self.ilang_graph.set_nodes_given(["sigma_%d" % i], True) model = SSD_ilang("SSD_%d" % i) self.ilang_graph.add_dependence( model, {"sigma": "sigma_%d" % i, "transformation": "T_%d" % i, "source": "im_%d" % i, "target": "template"}, ) self.ilang_sampler = Sampler(self.ilang_graph) def _repr_html_(self): return self.ilang_graph._repr_html_() def __repr__(self): return "Registration of N images. "
class Registration_Two_Images(object): def __init__( self, source=None, target=None, degrees_of_freedom=3, sigma=DEFAULT_SIGMA, initial_transformation=None ): self.set_source(source) self.set_target(target) self.set_sigma(sigma) self.__make_graph() if initial_transformation == None: self.set_transformation(numpy.zeros(degrees_of_freedom)) else: self.set_transformation(initial_transformation) def __make_graph(self): self.ilang_model = SSD_ilang() # The following is an alternative use of ilang models: define the log_p and gradient functions here in order to have access to # the local variables. self.ilang_model.log_conditional_probability_transformation = self.__P self.ilang_model.log_conditional_probability_gradient_transformation = self.__G self.ilang_graph = ProbabilisticGraphicalModel(["source", "target", "transformation", "sigma"]) self.ilang_graph.set_nodes_given(["sigma", "source", "target"], True) self.ilang_graph.add_dependence( self.ilang_model, {"source": "source", "target": "target", "sigma": "sigma", "transformation": "transformation"}, ) self.ilang_sampler = Sampler(self.ilang_graph) def __set_space(self): # make sure that the images are in the same space if self.source.space != self.target.space: raise "Source [%s] and Target [%s] must be in the same space" % (source.space, target.space) self.space = self.source.space def set_transformation(self, tr): self.__transformation = tr def __get_transformation(self): return self.__transformation def set_cost_function(self, cost): pass def __initialize_registration(self, optimization_method="QuasiNewton_L_BFGS_B", n_points=DEFAULT_N_POINTS): self.ilang_graph.set_node_value("source", self.source.data) self.ilang_graph.set_node_value("target", self.target.data) self.ilang_graph.set_node_value("sigma", self.sigma) if n_points == None: n_points = self.target.shape self.grid = self.target.get_world_grid(n_points) self.resampled_target = self.target.compute_resample_on_grid(self.grid) self.ilang_sampler.set_node_sampling_method_manual("transformation", optimization_method) def register(self, optimization_method="GradientAscent", iterations=DEFAULT_N_ITER, n_points=DEFAULT_N_POINTS): self.__initialize_registration(optimization_method, n_points) self.ilang_graph.set_node_value("transformation", self.transformation) self.ilang_sampler.sample(iterations) self.transformation = self.ilang_graph.get_node_value("transformation") def set_source(self, source): self.source = source if hasattr(self, "target"): self.__set_space() def set_target(self, target): self.target = target if hasattr(self, "source"): self.__set_space() def set_sigma(self, sigma): self.sigma = sigma def get_result(self): result = self.source.copy() result.transform(self.get_transformation_matrix()) return result def get_transformation_matrix(self): # rot = self.__transformation[0:3] # tra = self.__transformation[3:6] tra = self.__transformation return Transform_Translation(tra, self.space, self.space) # FIXME: rotation and translation def display(self): D = MultipleVolumesNiftyPy([self.source, self.target, self.get_result()]) # D = MultipleVolumes([self.source, self.target]) return D def __G(self, transformation): # print "Transformation: ", transformation # rot = transformation[0:3] # tra = transformation[3:6] tra = transformation T = Transform_Translation(tra, self.space, self.space) # FIXME: rotation and translation re_s = self.source.compute_resample_on_grid(self.grid, affine_grid_to_world=T) # FIXME: memoize gr_s = self.source.compute_gradient_on_grid(self.grid, affine_grid_to_world=T) re_t = self.resampled_target G_tra0 = (re_t.data - re_t.data * gr_s[0]).sum() G_tra1 = (re_t.data - re_t.data * gr_s[1]).sum() G_tra2 = (re_t.data - re_t.data * gr_s[2]).sum() G_tra = [G_tra0, G_tra1, G_tra2] G = numpy.asarray([G_tra[0], G_tra[1], G_tra[2]]) / self.sigma # print "gradient: ", G # print "log_likelihood: ", self.__P(transformation) return G def __P(self, transformation): # FIXME: memoize (now image is resampled to compute log_p and the gradient) # print transformation # rot = transformation[0:3] # tra = transformation[3:6] tra = transformation T = Transform_Translation(tra, self.space, self.space) # FIXME: rotation and translation resampled_source = self.source.compute_resample_on_grid(self.grid, affine_grid_to_world=T) P = -numpy.linalg.norm(resampled_source.data - self.resampled_target.data) / self.sigma # FIXME: verify # print "log_likelihood: ", P return P def _repr_html_(self): # return self.ilang_graph._repr_html_() return self.display()._repr_html_() def __repr__(self): return "Registration of 2 images." transformation = property(__get_transformation, set_transformation)