from autofit.tools import path_util
from autofit.optimize import non_linear as nl
from autofit.mapper import prior
from autofit.tools import phase as autofit_ph
from autolens.data.array import mask as msk
from autolens.model.galaxy import galaxy_model as gm
from autolens.pipeline import phase as ph
from autolens.pipeline import pipeline
from autolens.model.profiles import light_profiles as lp
from autolens.model.profiles import mass_profiles as mp
from autolens.model.inversion import pixelizations as pix
from autolens.model.inversion import regularization as reg

# In this pipeline, we'll perform a basic analysis which initializes a lens model (the lens's light, mass and source's \
# light) and then fits the source galaxy using an inversion. This pipeline will use four phases:

# Phase 1) Fit the lens galaxy's light using an elliptical Sersic light profile.

# Phase 2) Use this lens subtracted image to fit the lens galaxy's mass (SIE+Shear) and source galaxy's light (Sersic).

# Phase 4) Initialize the resolution and regularization coefficient of the inversion using the best-fit lens model from
#          phases 1 and 2.

# Phase 5) Refit the lens galaxy's light and mass models using an inversion, with lens galaxy priors initialized from
#          phases 1 and 2 and source-pixelization parameters from phase 3.

# Phase 6) Perform a sensitivity analysis on the lens, where we determine what mass subhalos our analysis is sensitive too.

# Phase 7) Inject subhalos on a grid over the image.

# The first 3 phases of this pipeline are identical to the 'lens_light_and_x1_source_parametric.py' pipeline.

def make_pipeline(phase_folders=None):

    pipeline_name = 'pipeline_light_and_source_inversion'

    # This function uses the phase folders and pipeline name to set up the output directory structure,
    # e.g. 'autolens_workspace/output/phase_folder_1/phase_folder_2/pipeline_name/phase_name/'
    phase_folders = path_util.phase_folders_from_phase_folders_and_pipeline_name(phase_folders=phase_folders,
                                                                                pipeline_name=pipeline_name)

    ### PHASE 1 ###

    # In phase 1, we will fit only the lens galaxy's light, where we:

    # 1) Set our priors on the lens galaxy (y,x) centre such that we assume the image is centred around the lens galaxy.
    # 2) Use a circular mask which includes the lens and source galaxy light.

    class LensPhase(ph.LensPlanePhase):

        def pass_priors(self, results):

            self.lens_galaxies.lens.bulge.centre_0 = prior.GaussianPrior(mean=0.0, sigma=0.1)
            self.lens_galaxies.lens.bulge.centre_1 = prior.GaussianPrior(mean=0.0, sigma=0.1)

            self.lens_galaxies.lens.bulge.centre_0 = self.lens_galaxies.lens.envelope.centre_0
            self.lens_galaxies.lens.bulge.centre_1 = self.lens_galaxies.lens.envelope.centre_1

    phase1 = LensPhase(phase_name='phase_1_lens_light_only', phase_folders=phase_folders,
                       lens_galaxies=dict(lens=gm.GalaxyModel(bulge=lp.EllipticalSersic, 
                                                              envelope=lp.EllipticalExponential)),
                       optimizer_class=nl.MultiNest)

    # You'll see these lines throughout all of the example pipelines. They are used to make MultiNest sample the \
    # non-linear parameter space faster (if you haven't already, checkout the tutorial '' in howtolens/chapter_2).

    phase1.optimizer.const_efficiency_mode = True
    phase1.optimizer.n_live_points = 30
    phase1.optimizer.sampling_efficiency = 0.3

    ### PHASE 2 ###

    # In phase 2, we will fit the lens galaxy's mass and source galaxy's light, where we:

    # 1) Use a lens-subtracted image generated by subtracting model lens galaxy image from phase 1.
    # 2) Use a annular mask (made from the specific outer mask and a small circular mask) which includes only the source-galaxy light.
    # 3) Initialize the priors on the centre of the lens galaxy's mass-profile by linking them to those inferred for \
    #    its light profile in phase 1.

    class LensSubtractedPhase(ph.LensSourcePlanePhase):

        def modify_image(self, image, results):
            return image - results.from_phase('phase_1_lens_light_only').unmasked_lens_plane_model_image

        def pass_priors(self, results):

            self.lens_galaxies.lens.mass.centre_0 = \
                results.from_phase('phase_1_lens_light_only').variable.lens.bulge.centre_0
            self.lens_galaxies.lens.mass.centre_1 = \
                results.from_phase('phase_1_lens_light_only').variable.lens.bulge.centre_1

    phase2 = LensSubtractedPhase(phase_name='phase_2_source_only', phase_folders=phase_folders,
                                 lens_galaxies=dict(lens=gm.GalaxyModel(mass=mp.EllipticalIsothermal,
                                                                        shear=mp.ExternalShear)),
                                 source_galaxies=dict(source=gm.GalaxyModel(light=lp.EllipticalSersic)),
                                 optimizer_class=nl.MultiNest, inner_circular_mask_radii=0.3,
                                 use_positions=True)

    phase2.optimizer.const_efficiency_mode = True
    phase2.optimizer.n_live_points = 75
    phase2.optimizer.sampling_efficiency = 0.2


    ### PHASE 3 ###

    # In phase 3, we will fit simultaneously the lens and source galaxies, where we:

    # 1) Initialize the lens's light, mass, shear and source's light using the results of phases 1 and 2.

    class LensSourcePhase(ph.LensSourcePlanePhase):

        def pass_priors(self, results):

            self.lens_galaxies.lens.bulge = results.from_phase('phase_1_lens_light_only').variable.lens.bulge
            self.lens_galaxies.lens.envelope = results.from_phase('phase_1_lens_light_only').variable.lens.envelope
            self.lens_galaxies.lens.mass = results.from_phase('phase_2_source_only').variable.lens.mass
            self.lens_galaxies.lens.shear = results.from_phase('phase_2_source_only').variable.lens.shear
            self.source_galaxies.source = results.from_phase('phase_2_source_only').variable.source

            self.lens_galaxies.lens.bulge.centre_0 = self.lens_galaxies.lens.envelope.centre_0
            self.lens_galaxies.lens.bulge.centre_1 = self.lens_galaxies.lens.envelope.centre_1

    phase3 = LensSourcePhase(phase_name='phase_3_both', phase_folders=phase_folders,
                             lens_galaxies=dict(lens=gm.GalaxyModel(bulge=lp.EllipticalSersic,
                                                                    envelope=lp.EllipticalExponential,
                                                                    mass=mp.EllipticalIsothermal,
                                                                    shear=mp.ExternalShear)),
                             source_galaxies=dict(source=gm.GalaxyModel(light=lp.EllipticalSersic)),
                             use_positions=True,
                             optimizer_class=nl.MultiNest)

    phase3.optimizer.const_efficiency_mode = True
    phase3.optimizer.n_live_points = 75
    phase3.optimizer.sampling_efficiency = 0.1

    ### PHASE 4 ###

    # In phase 4, we initialize the inversion's resolution and regularization coefficient, where we:

    # 1) Use a lens-subtracted image generated by subtracting model lens galaxy image from phase 1.
    # 2) Fix our mass model to the lens galaxy mass-model from phase 2.
    # 3) Use a circular annular mask which includes only the source-galaxy light.

    class InversionPhase(ph.LensSourcePlanePhase):

        def modify_image(self, image, results):
            return image - results.from_phase('phase_3_both').unmasked_lens_plane_model_image

        def pass_priors(self, results):

            self.lens_galaxies.lens.mass = results.from_phase('phase_3_both').constant.lens.mass
            self.lens_galaxies.lens.shear = results.from_phase('phase_3_both').constant.lens.shear

    phase4 = InversionPhase(phase_name='phase_4_inversion_init', phase_folders=phase_folders,
                            lens_galaxies=dict(lens=gm.GalaxyModel(mass=mp.EllipticalIsothermal,
                                                                   shear=mp.ExternalShear)),
                            source_galaxies=dict(source=gm.GalaxyModel(pixelization=pix.AdaptiveMagnification,
                                                                      regularization=reg.Constant)),
                            optimizer_class=nl.MultiNest, inner_circular_mask_radii=0.3)

    phase4.optimizer.const_efficiency_mode = True
    phase4.optimizer.n_live_points = 20
    phase4.optimizer.sampling_efficiency = 0.8

    ### PHASE 5 ###

    # In phase 5, we fit the len galaxy light, mass and source galxy simultaneously, using an inversion. We will:

    # 1) Initialize the priors of the lens galaxy and source galaxy from phases 3+4.
    # 2) Use a annular mask which includes only the source galaxy light.

    class InversionPhase(ph.LensSourcePlanePhase):

        def modify_image(self, image, results):
            return image - results.from_phase('phase_3_both').unmasked_lens_plane_model_image

        def pass_priors(self, results):

            self.lens_galaxies.lens.mass = results.from_phase('phase_3_both').variable.lens.mass
            self.lens_galaxies.lens.shear = results.from_phase('phase_3_both').variable.lens.shear
            self.source_galaxies.source = results.from_phase('phase_4_inversion_init').variable.source

    phase5 = InversionPhase(phase_name='phase_5_inversion', phase_folders=phase_folders,
                            lens_galaxies=dict(lens=gm.GalaxyModel(mass=mp.EllipticalIsothermal,
                                                                   shear=mp.ExternalShear)),
                            source_galaxies=dict(source=gm.GalaxyModel(pixelization=pix.AdaptiveMagnification,
                                                                      regularization=reg.Constant)),
                            optimizer_class=nl.MultiNest, use_positions=True, inner_circular_mask_radii=0.3)

    phase5.optimizer.const_efficiency_mode = True
    phase5.optimizer.n_live_points = 75
    phase5.optimizer.sampling_efficiency = 0.1
    
    ### Phase 6 ###

    # In phase 6, we perform the sensitivity analysis of our lens, using a grid search of subhalo (y,x) coordinates and
    # mass, where:

    # 1) The lens model and source-pixelization parameters are held fixed to the best-fit values from phase 2.

    class GridPhase(ph.LensSourcePlanePhase):

        def modify_image(self, image, results):
            return image - results.from_phase('phase_3_both').unmasked_lens_plane_model_image

        def pass_priors(self, results):

            self.lens_galaxies.lens.mass = results.from_phase('phase_5_inversion').constant.lens.mass
            self.source_galaxies.source.pixelization = results.from_phase('phase_5_inversion').constant.source.pixelization
            self.source_galaxies.source.regularization = results.from_phase('phase_5_inversion').constant.source.regularization

            self.lens_galaxies.subhalo.mass.centre_0 = prior.UniformPrior(lower_limit=-2.0, upper_limit=2.0)
            self.lens_galaxies.subhalo.mass.centre_1 = prior.UniformPrior(lower_limit=-2.0, upper_limit=2.0)
            self.lens_galaxies.subhalo.mass.kappa_s = prior.UniformPrior(lower_limit=0.0, upper_limit=1.0)
            self.lens_galaxies.subhalo.mass.scale_radius = 5.0

    phase6 = GridPhase(phase_name='phase_6_sensitivity', phase_folders=phase_folders,
                       lens_galaxies=dict(lens=gm.GalaxyModel(mass=mp.EllipticalIsothermal),
                                          subhalo=gm.GalaxyModel(mass=mp.SphericalNFW)),
                       source_galaxies=dict(source=gm.GalaxyModel(pixelization=pix.AdaptiveMagnification,
                                                                  regularization=reg.Constant)),
                       optimizer_class=nl.GridSearch)

    ### Phase 7 ###

    # In phase 7, we attempt to detect subhalos, by performing a NxN grid search of MultiNest searches, where:

    # 1) The lens model and source-pixelization parameters are held fixed to the best-fit values from phase 2.
    # 2) Each grid search varies the subhalo (y,x) coordinates and mass as free parameters.
    # 3) The priors on these (y,x) coordinates are UniformPriors, with limits corresponding to the grid-cells.

    class GridPhase(autofit_ph.as_grid_search(ph.LensSourcePlanePhase)):

        def modify_image(self, image, results):
            return image - results.from_phase('phase_3_both').unmasked_lens_plane_model_image

        @property
        def grid_priors(self):
            return [self.variable.subhalo.mass.centre_0, self.variable.subhalo.mass.centre_1]

        def pass_priors(self, results):

            self.lens_galaxies.subhalo.mass.centre_0 = prior.UniformPrior(lower_limit=-2.0, upper_limit=2.0)
            self.lens_galaxies.subhalo.mass.centre_1 = prior.UniformPrior(lower_limit=-2.0, upper_limit=2.0)
            self.lens_galaxies.subhalo.mass.kappa_s = prior.UniformPrior(lower_limit=0.0, upper_limit=0.2)

            self.lens_galaxies.lens.mass = results.from_phase('phase_5_inversion').constant.lens.mass
            self.source_galaxies.source.pixelization = \
                results.from_phase('phase_5_inversion').constant.source.pixelization
            self.source_galaxies.source.regularization = \
                results.from_phase('phase_5_inversion').constant.source.regularization


    phase7 = GridPhase(phase_name='phase_7_subhalo_search', phase_folders=phase_folders,
                       lens_galaxies=dict(lens=gm.GalaxyModel(mass=mp.EllipticalIsothermal),
                                          subhalo=gm.GalaxyModel(mass=mp.SphericalNFW)),
                       source_galaxies=dict(source=gm.GalaxyModel(pixelization=pix.AdaptiveMagnification,
                                                                  regularization=reg.Constant)),
                       number_of_steps=6, optimizer_class=nl.MultiNest)

    return pipeline.PipelineImaging(pipeline_name, phase1, phase2, phase3, phase4, phase5, phase6, phase7)