### Install PyAutoConf Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Install the PyAutoConf library using pip. ```bash pip install autoconf ``` -------------------------------- ### Install PyAuto Parent Projects Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Install the core PyAuto parent projects via pip. ```bash pip install autoconf pip install autofit pip install autoarray pip install autogalaxy ``` -------------------------------- ### Install Numba Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/pip.md Install Numba, an optional library that significantly speeds up PyAutoLens. This is strongly recommended for performance. ```bash pip install numba ``` -------------------------------- ### Install Source Build Dependencies Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Install the required dependencies for each PyAuto project from their respective requirement files. ```bash pip install -r PyAutoFit/requirements.txt pip install -r PyAutoArray/requirements.txt pip install -r PyAutoGalaxy/requirements.txt pip install -r PyAutoLens/requirements.txt ``` -------------------------------- ### Run PyAutoLens Unit Tests Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Navigate to the PyAutoLens directory and run the unit tests to verify the installation. Ensure pytest is installed (`pip install pytest`). ```bash cd /path/to/PyAutoLens python3 -m pytest ``` -------------------------------- ### Install PyAutoLens Dependencies Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Install the necessary dependencies for PyAutoLens from its requirements file. ```bash pip install -r PyAutoLens/requirements.txt ``` -------------------------------- ### Run Welcome Script Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/conda.md Execute the welcome.py script from the cloned workspace to verify PyAutoLens installation and functionality. ```bash python3 welcome.py ``` -------------------------------- ### Install Optional Interferometer Dependencies Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/conda.md Install optional dependencies 'pynufft' required for interferometer analysis. These are not needed for general PyAutoLens usage. ```bash pip install pynufft ``` -------------------------------- ### Install Numba Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/conda.md Install Numba, an optional library that significantly speeds up PyAutoLens performance. It is recommended but not required for basic functionality. ```bash pip install numba --no-cache-dir ``` -------------------------------- ### Install PyAutoLens Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/conda.md Install the latest version of PyAutoLens using pip. The --no-cache-dir flag helps prevent installation issues caused by cached data. ```bash pip install autolens --no-cache-dir ``` -------------------------------- ### Install PyAutoLens with Development Dependencies Source: https://github.com/pyautolabs/pyautolens/blob/main/AGENTS.md Installs PyAutoLens in editable mode, including development dependencies required for testing and contributing. ```bash pip install -e ".[dev]" ``` -------------------------------- ### JAX-traced solve (GPU-accelerated) Source: https://context7.com/pyautolabs/pyautolens/llms.txt Use JAX for GPU-accelerated solving of tracer calculations. Requires JAX to be installed and configured for GPU usage. ```python import jax.numpy as jnp positions_jax = solver.solve(tracer=tracer, source_plane_coordinate=(0.07, 0.07), xp=jnp) ``` -------------------------------- ### Install PyAutoLens Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/pip.md Install the latest version of PyAutoLens using pip. Specifying the version ensures clean dependencies. ```bash pip install autolens ``` -------------------------------- ### Setup and Fit a Lens Model with PyAutoFit Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/index.md This snippet illustrates setting up a lens model using PyAutoFit for model fitting. It involves loading imaging data, creating a mask, defining model components for lens and source galaxies, specifying a non-linear search, and running the fit. Requires importing autofit, autolens, and autolens.plot. ```python import autofit as af import autolens as al import autolens.plot as aplt """ Load Imaging data of the strong lens from the dataset folder of the workspace. """ dataset = al.Imaging.from_fits( data_path="/path/to/dataset/image.fits", noise_map_path="/path/to/dataset/noise_map.fits", psf_path="/path/to/dataset/psf.fits", pixel_scales=0.1, ) """ Create a mask for the imaging data, which we setup as a 3.0" circle, and apply it. """ mask = al.Mask2D.circular( shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0 ) dataset = dataset.apply_mask(mask=mask) """ We model the lens galaxy using an elliptical isothermal mass profile and the source galaxy using an elliptical sersic light profile. To setup these profiles as model components whose parameters are free & fitted for we set up each Galaxy as a `Model` and define the model as a `Collection` of all galaxies. """ # Lens: mass = af.Model(al.mp.Isothermal) lens = af.Model(al.Galaxy, redshift=0.5, mass=lens_mass_profile) # Source: disk = af.Model(al.lp.SersicCore) source = af.Model(al.Galaxy, redshift=1.0, disk=disk) # Overall Lens Model: model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) """ We define the non-linear search used to fit the model to the data (in this case, Dynesty). """ search = af.Nautilus(name="search[example]", n_live=50) """ We next set up the `Analysis`, which contains the `log likelihood function` that the non-linear search calls to fit the lens model to the data. """ analysis = al.AnalysisImaging(dataset=dataset) """ To perform the model-fit we pass the model and analysis to the search's fit method. This will output results (e.g., dynesty samples, model parameters, visualization) to hard-disk. """ result = search.fit(model=model, analysis=analysis) """ The results contain information on the fit, for example the maximum likelihood model from the Dynesty parameter space search. """ print(result.samples.max_log_likelihood()) ``` -------------------------------- ### Install Optional Unit Test Requirements Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Install optional requirements for PyAutoArray to ensure unit tests pass. ```bash pip install -r PyAutoArray/optional_requirements.txt ``` -------------------------------- ### Setup Analysis with PositionsLH Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/general/demagnified_solutions.md Instantiate an AnalysisImaging object with a list of PositionsLH objects, enabling the use of positions penalty in the likelihood function. ```python analysis = al.AnalysisImaging( dataset=dataset, positions_likelihood_list=[result_1.positions_likelihood_from( factor=3.0, minimum_threshold=0.2 )], ) ``` -------------------------------- ### Run PyAuto Project Unit Tests Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Navigate to each PyAuto project directory and run its unit tests using pytest. Ensure pytest is installed via 'pip install pytest'. ```bash cd /path/to/PyAutoFit python3 -m pytest cd ../PyAutoArray python3 -m pytest cd ../PyAutoGalaxy python3 -m pytest cd ../PyAutoLens python3 -m pytest ``` -------------------------------- ### Setup Analysis with Multiple PositionsLH from Result Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/general/demagnified_solutions.md Configure an AnalysisImaging object with multiple PositionsLH objects derived from a result, specifying the redshift for each source plane. ```python analysis = al.AnalysisImaging( dataset=dataset, positions_likelihood_list=[ source_lp_result.positions_likelihood_from( factor=3.0, minimum_threshold=0.2, plane_redshift=source_lp_result.instance.galaxies.source_1.redshift, ), source_lp_result.positions_likelihood_from( factor=3.0, minimum_threshold=0.2, plane_redshift=source_lp_result.instance.galaxies.source_2.redshift, ) ], ) ``` -------------------------------- ### Plotter Figure Convergence Example Source: https://github.com/pyautolabs/pyautolens/blob/main/PLOT_REFACTOR_PLAN.md Demonstrates the `figure_convergence` method, which can either create its own figure or draw on a provided axes. It plots a specified array with overlays and handles figure saving and closing if it created the figure internally. ```python Plotter.figure_convergence(ax=None) owns_figure = ax is None if owns_figure: fig, ax = plt.subplots(1, 1, figsize=conf_figsize("figures")) plot_array(array=tracer.convergence, title="Convergence", ax=ax, lines=critical_curves + radial_curves) if owns_figure: save_figure(fig, ...) ; plt.close(fig) ``` -------------------------------- ### Upgrade Pip Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/troubleshooting.md Ensure you are using the latest version of pip to avoid installation errors. Run these commands if you encounter issues with `pip install autolens`. ```bash pip install --upgrade pip ``` ```bash pip3 install --upgrade pip ``` -------------------------------- ### Install Specific Legacy Version of PyAutoLens Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/pip.md Install a specific legacy version of PyAutoLens by pinning the version. This is useful for existing projects that require pre-2026.4.5.3 releases. ```bash pip install autolens==2025.10.6.1 ``` -------------------------------- ### Bayesian Point-Source Lens Modeling with AutoFit Source: https://context7.com/pyautolabs/pyautolens/llms.txt Perform Bayesian inference for point-source lens models using `AnalysisPoint` and `PyAutoFit` searches. Requires `autofit` and `autolens` to be installed. ```python import autofit as af import autolens as al dataset = al.PointDataset( name="quasar", positions=[(1.2, 0.3), (-0.5, 1.1), (-1.0, -0.4), (0.4, -1.2)], positions_noise_map=0.05, ) solver = al.PointSolver.for_grid( grid=al.Grid2D.uniform(shape_native=(200, 200), pixel_scales=0.05), pixel_scale_precision=0.001, ) lens = af.Model(al.Galaxy, redshift=0.5, mass=al.mp.Isothermal) source = af.Model(al.Galaxy, redshift=1.0, quasar=al.ps.Point) model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) analysis = al.AnalysisPoint(dataset=dataset, solver=solver) search = af.Nautilus(path_prefix="point_fit", name="quasar_lens", n_live=100) result = search.fit(model=model, analysis=analysis) print(result.max_log_likelihood_tracer) print(result.samples.median_pdf_instance.galaxies.lens.mass.einstein_radius) ``` -------------------------------- ### Load Model from JSON Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/general/model_cookbook.md Load a previously saved model configuration from a JSON file. This allows for reusing and modifying model setups. ```python model = af.Model.from_json(file=model_file) ``` -------------------------------- ### Create and Plot Tracer Image Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/overview/overview_1_start_here.md Initializes a Tracer object with a list of galaxies and a cosmology, then plots the resulting lensed image on a grid. This simulates the observed strong lensing effect. ```python tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy], cosmology=al.cosmo.Planck15()) aplt.plot_array(array=tracer.image_2d_from(grid=grid), title="Image") ``` -------------------------------- ### Simulate Imaging Data with SimulatorImaging Source: https://context7.com/pyautolabs/pyautolens/llms.txt Simulate imaging data from a tracer, including PSF convolution, background sky, and noise. Requires exposure time, PSF, and background level. ```python import autolens as al import numpy as np lens = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.6), ) source = al.Galaxy( redshift=1.0, light=al.lp.Sersic(centre=(0.05, 0.1), ell_comps=(0.0, 0.2), intensity=0.3, effective_radius=0.3, sersic_index=1.0), ) tracer = al.Tracer(galaxies=[lens, source]) grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1, over_sample_size=4) psf = al.Kernel2D.from_gaussian(shape_native=(11, 11), sigma=0.1, pixel_scales=0.1, normalize=True) simulator = al.SimulatorImaging( exposure_time=300.0, psf=psf, background_sky_level=0.1, add_poisson_noise=True, ) dataset = simulator.via_tracer_from(tracer=tracer, grid=grid) print(dataset.data.shape_native) # (100, 100) - the simulated image print(dataset.noise_map.native.mean()) # estimated noise per pixel # Save and load al.output_to_fits(dataset.data, file_path="image.fits") ``` -------------------------------- ### Import Libraries Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/overview/overview_1_start_here.md Imports necessary libraries for PyAutoLens and AutoArray. These imports are common in most PyAutoLens examples. ```python import autolens as al import autoarray as aa import autolens.plot as aplt ``` -------------------------------- ### Initialize Tracer and Compute Lensed Image Source: https://context7.com/pyautolabs/pyautolens/llms.txt Defines lens and source galaxies, creates a Tracer object, and computes lensing quantities like the lensed image, deflection angles, convergence, potential, and time delays. ```python import autolens as al import autolens.plot as aplt # Define a lens galaxy (Isothermal sphere) at z=0.5 lens_galaxy = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal( centre=(0.0, 0.0), ell_comps=(0.0, 0.05), einstein_radius=1.6, ), light=al.lp.Sersic( centre=(0.0, 0.0), ell_comps=(0.0, 0.0), intensity=0.5, effective_radius=0.8, sersic_index=4.0, ), ) # Define a source galaxy (Exponential disk) at z=1.0 source_galaxy = al.Galaxy( redshift=1.0, light=al.lp.Exponential( centre=(0.1, 0.1), ell_comps=(0.0, 0.1), intensity=1.0, effective_radius=0.3, ), ) tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) # Build an image-plane grid grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05) # Compute lensed image (ray-traces source through lens mass) image = tracer.image_2d_from(grid=grid) print(image.shape_native) # (100, 100) print(image.native.max()) # peak surface brightness # Multi-plane deflection angles deflections = tracer.deflections_yx_2d_from(grid=grid) # Lensing maps convergence = tracer.convergence_2d_from(grid=grid) potential = tracer.potential_2d_from(grid=grid) # Time delays at image-plane positions time_delays = tracer.time_delays_from(grid=grid) ``` -------------------------------- ### Upgrade Pip Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/conda.md Upgrade pip within the activated conda environment to ensure compatibility for library installations. ```bash pip install --upgrade pip ``` -------------------------------- ### Create and Trace a Strong Lensing System Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/index.md This snippet demonstrates how to define lens and source galaxies with their respective mass and light profiles, and then use a Tracer to compute strong lensing sightlines. It requires importing autolens, autolens.plot, and astropy.cosmology. ```python import autolens as al import autolens.plot as aplt from astropy import cosmology as cosmo """ To describe the deflection of light by mass, two-dimensional grids of (y,x) Cartesian coordinates are used. """ grid = al.Grid2D.uniform( shape_native=(50, 50), pixel_scales=0.05, # <- Conversion from pixel units to arc-seconds. ) """ The lens galaxy has an elliptical isothermal mass profile and is at redshift 0.5. """ mass = al.mp.Isothermal( centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.6 ) lens_galaxy = al.Galaxy(redshift=0.5, mass=mass) """ The source galaxy has an elliptical exponential light profile and is at redshift 1.0. """ disk = al.lp.Exponential( centre=(0.3, 0.2), ell_comps=(0.05, 0.25), intensity=0.05, effective_radius=0.5, ) source_galaxy = al.Galaxy(redshift=1.0, disk=disk) """ We create the strong lens using a Tracer, which uses the galaxies, their redshifts and an input cosmology to determine how light is deflected on its path to Earth. """ tracer = al.Tracer( galaxies=[lens_galaxy, source_galaxy], cosmology = al.cosmo.Planck15() ) """ We can use the Grid2D and Tracer to perform many lensing calculations, for example plotting the image of the lensed source. """ tracer_plotter = aplt.Tracer(tracer=tracer, grid=grid) tracer_plotter.figures_2d(image=True) ``` -------------------------------- ### Create Sersic Light Profile Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/overview/overview_1_start_here.md Instantiates an elliptical Sersic light profile, a common model for galaxy light distributions. Parameters define its center, ellipticity, intensity, effective radius, and concentration. ```python sersic_light_profile = al.lp.Sersic( centre=(0.0, 0.0), # The light profile centre [units of arc-seconds]. ell_comps=( 0.2, 0.1, ), # The light profile elliptical components [can be converted to axis-ratio and position angle]. intensity=0.005, # The overall intensity normalisation [units arbitrary and are matched to the data]. effective_radius=2.0, # The effective radius containing half the profile's total luminosity [units of arc-seconds]. sersic_index=4.0, # Describes the profile's shape [higher value -> more concentrated profile]. ) ``` -------------------------------- ### Line-of-Sight Plane Slicing Source: https://context7.com/pyautolabs/pyautolens/llms.txt Demonstrates setting up a tracer with multiple line-of-sight galaxies, which can then be binned into sliced planes to reduce computational cost for multi-plane calculations. ```python import autolens as al lens_galaxy = al.Galaxy(redshift=0.5, mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.0, 0.0), einstein_radius=1.6)) source_galaxy = al.Galaxy(redshift=2.0, light=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.0, 0.0), intensity=1.0, effective_radius=0.3, sersic_index=1.0)) # 100 line-of-sight perturbers at various redshifts import numpy as np los_galaxies = [ al.Galaxy( redshift=np.random.uniform(0.1, 1.9), mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=0.05), ) for _ in range(100) ] ``` -------------------------------- ### Configure Matplotlib Backend Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/troubleshooting.md If Matplotlib causes crashes, modify the `general.yaml` configuration file to use a different backend. TKAgg and Qt5Agg are suggested alternatives to 'default'. ```yaml general: backend: default ``` ```yaml general: backend: TKAgg ``` -------------------------------- ### Plotter Subplot Fit Example Source: https://github.com/pyautolabs/pyautolens/blob/main/PLOT_REFACTOR_PLAN.md Illustrates how the `subplot_fit` method in the new design creates a matplotlib figure and axes, then plots various arrays onto specific subplots using direct matplotlib calls. It shows how overlay data is passed as lists and how the figure is saved. ```python Plotter.subplot_fit( array=fit.data, title="Data", ax=axes[0,0] ) Plotter.subplot_fit( array=fit.noise_map, title="Noise", ax=axes[0,1] ) Plotter.subplot_fit( array=fit.model_image, title="Model", ax=axes[0,2], lines=[critical_curves], ) save_figure(fig, path=output_path, filename="subplot_fit") plt.close(fig) ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/pyautolabs/pyautolens/blob/main/CONTRIBUTING.md Stage all changes, commit them with a descriptive message, and push your feature branch to GitHub. Remember to use '-u' for the initial push. ```bash git add . git commit -m "Your detailed description of your changes." git push origin feature/name-of-your-branch ``` -------------------------------- ### Generate Light Profile Image Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/overview/overview_1_start_here.md Generates a 2D image of the light profile by evaluating its intensity on the specified grid. This simulates the light distribution of a galaxy. ```python image = sersic_light_profile.image_2d_from(grid=grid) ``` -------------------------------- ### Set Configuration and Output Paths Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/general/configs.md Manually set the configuration and output paths for PyAutoLens using PyAutoConf. This is useful when not running scripts from the default autolens_workspace directory. ```python from autoconf import conf conf.instance.push( config_path="path/to/config", output_path=f"path/to/output" ) ``` -------------------------------- ### Create Lens and Source Galaxies Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/overview/overview_1_start_here.md Constructs Galaxy objects for both the lens and source, assigning a redshift, mass profile (for the lens), and light profile (for the source). ```python lens_galaxy = al.Galaxy( redshift=0.5, light=sersic_light_profile, # The foreground lens's light is typically observed in a strong lens. mass=isothermal_mass_profile, # Its mass is what causes the strong lensing effect. ) source_light_profile = al.lp.Exponential( centre=( 0.3, 0.2, ), # The source galaxy's light is observed, appearing as multiple images around the lens galaxy. ell_comps=( 0.1, 0.0, ), # However, the mass of the source does not impact the strong lensing effect. intensity=0.1, # and is not included. effective_radius=0.5, ) source_galaxy = al.Galaxy(redshift=1.0, light=source_light_profile) ``` -------------------------------- ### Fit Interferometer Data with PyAutoLens Source: https://context7.com/pyautolabs/pyautolens/llms.txt Fit interferometer data in the uv-plane using DFT or NUFFT. Requires setting up interferometer dataset, masks, and transformer settings. ```python import autolens as al import autoarray as aa dataset = aa.Interferometer.from_fits( data_path="visibilities.fits", noise_map_path="noise_map.fits", uv_wavelengths_path="uv_wavelengths.fits", ) mask = aa.Mask2D.circular(shape_native=(200, 200), pixel_scales=0.05, radius=3.0) real_space_mask = aa.Mask2D.circular(shape_native=(200, 200), pixel_scales=0.05, radius=3.0) settings = aa.SettingsInterferometer(transformer_class=aa.TransformerNUFFT) dataset = dataset.apply_settings(settings=settings) lens = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.0, 0.0), einstein_radius=1.4), ) source = al.Galaxy( redshift=1.0, light=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.0, 0.0), intensity=1.0, effective_radius=0.4, sersic_index=1.0), ) tracer = al.Tracer(galaxies=[lens, source]) fit = al.FitInterferometer(dataset=dataset, tracer=tracer) print(fit.log_likelihood) print(fit.chi_squared) print(fit.residual_map_real.shape) # residuals in the visibility domain ``` -------------------------------- ### Run Full PyAutoLens Test Suite Source: https://github.com/pyautolabs/pyautolens/blob/main/AGENTS.md Executes the complete test suite for PyAutoLens to ensure code integrity. ```bash python -m pytest test_autolens/ ``` -------------------------------- ### Run PyAutoLens Imaging Fit Tests with Output Source: https://github.com/pyautolabs/pyautolens/blob/main/AGENTS.md Executes tests for the imaging fit functionality, enabling verbose output with the -s flag. ```bash python -m pytest test_autolens/imaging/test_fit_imaging.py -s ``` -------------------------------- ### Add PyAuto Projects to PYTHONPATH Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/source.md Add each PyAuto source repository to your PYTHONPATH environment variable. Remember to replace '/path/to' with the actual directory path. ```bash export PYTHONPATH=$PYTHONPATH:/path/to/PyAutoFit export PYTHONPATH=$PYTHONPATH:/path/to/PyAutoArray export PYTHONPATH=$PYTHONPATH:/path/to/PyAutoGalaxy export PYTHONPATH=$PYTHONPATH:/path/to/PyAutoLens ``` -------------------------------- ### Print Model Info Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/general/model_cookbook.md Prints detailed information about the model's parameters and their priors, providing a comprehensive overview of the model structure. ```python print(model.info) ``` -------------------------------- ### Create Feature Branch Source: https://github.com/pyautolabs/pyautolens/blob/main/CONTRIBUTING.md Use this command to create a new branch for your local development. Ensure you do this for PyAutoLens and any parent projects you modify. ```bash git checkout -b feature/name-of-your-branch ``` -------------------------------- ### Create Tracer with Sliced Planes Source: https://context7.com/pyautolabs/pyautolens/llms.txt Use `sliced_tracer_from` to create a tracer with a specified number of planes between lenses and sources. This is useful for complex lens systems. ```python tracer = al.Tracer.sliced_tracer_from( lens_galaxies=[lens_galaxy], line_of_sight_galaxies=los_galaxies, source_galaxies=[source_galaxy], planes_between_lenses=[2, 3], ) print(tracer.total_planes) # 7 planes (2 + lens + 3 + source) ``` -------------------------------- ### Fit Imaging Data with FitImaging Source: https://context7.com/pyautolabs/pyautolens/llms.txt Evaluate how well a tracer fits imaging data by computing log-likelihood, chi-squared, and generating model images. Requires masked imaging data and a tracer. ```python import autolens as al import autoarray as aa # Load real or simulated imaging data dataset = aa.Imaging.from_fits( data_path="data.fits", psf_path="psf.fits", noise_map_path="noise_map.fits", pixel_scales=0.1, ) mask = aa.Mask2D.circular( shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0, ) dataset = dataset.apply_mask(mask=mask) lens = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.05, 0.02), einstein_radius=1.6), ) source = al.Galaxy( redshift=1.0, light=al.lp.Sersic(centre=(0.1, 0.05), ell_comps=(0.0, 0.1), intensity=0.5, effective_radius=0.3, sersic_index=1.0), ) tracer = al.Tracer(galaxies=[lens, source]) fit = al.FitImaging(dataset=dataset, tracer=tracer) print(fit.log_likelihood) # scalar log likelihood print(fit.chi_squared) # chi-squared statistic print(fit.blurred_image.shape_native) # PSF-convolved model image print(fit.residual_map.shape_native) # data - model print(fit.normalized_residual_map.native.std()) # ~1 for a good fit ``` -------------------------------- ### Bayesian Lens Modeling with AnalysisImaging Source: https://context7.com/pyautolabs/pyautolens/llms.txt Connects the FitImaging engine to a PyAutoFit non-linear search for Bayesian lens modeling. Requires loading and masking imaging data, building a parametric model, and setting up the analysis. ```python import autofit as af import autolens as al import autoarray as aa # Load and mask the imaging data dataset = aa.Imaging.from_fits( data_path="data.fits", psf_path="psf.fits", noise_map_path="noise_map.fits", pixel_scales=0.1 ) mask = aa.Mask2D.circular(shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0) dataset = dataset.apply_mask(mask=mask) # Build the parametric model lens = af.Model(al.Galaxy, redshift=0.5, mass=al.mp.Isothermal) source = af.Model(al.Galaxy, redshift=1.0, light=al.lp.Sersic) model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) # Set up the analysis analysis = al.AnalysisImaging(dataset=dataset) # Run a non-linear search (Nautilus nested sampler) search = af.Nautilus(path_prefix="lens_fit", name="mass_light", n_live=150) result = search.fit(model=model, analysis=analysis) # Inspect the result print(result.max_log_likelihood_tracer) # best-fit Tracer print(result.samples.median_pdf_instance) # median posterior model fit = al.FitImaging(dataset=dataset, tracer=result.max_log_likelihood_tracer) print(fit.log_likelihood) ``` -------------------------------- ### Create Conda Environment Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/installation/conda.md Create a new conda environment named 'autolens' with Python 3.12. ```bash conda create -n autolens python=3.12 ``` -------------------------------- ### Create Tracer with Multiple Galaxies and Profiles Source: https://github.com/pyautolabs/pyautolens/blob/main/docs/overview/overview_1_start_here.md Define a Tracer object with multiple galaxies, each having distinct light and mass profiles (including stellar and dark matter components). This demonstrates PyAutoLens's extensibility for complex strong lensing systems. ```python lens_galaxy_0 = al.Galaxy( redshift=0.5, bulge=al.lmp.Sersic( centre=(0.0, 0.0), ell_comps=(0.0, 0.05), intensity=0.5, effective_radius=0.3, sersic_index=3.5, mass_to_light_ratio=0.6, ), disk=al.lmp.Exponential( centre=(0.0, 0.0), ell_comps=(0.0, 0.1), intensity=1.0, effective_radius=2.0, mass_to_light_ratio=0.2, ), dark=al.mp.NFWSph(centre=(0.0, 0.0), kappa_s=0.08, scale_radius=30.0), ) lens_galaxy_1 = al.Galaxy( redshift=1.0, bulge=al.lp.Exponential( centre=(0.00, 0.00), ell_comps=(0.05, 0.05), intensity=1.2, effective_radius=0.1, ), mass=al.mp.Isothermal( centre=(0.0, 0.0), ell_comps=(0.05, 0.05), einstein_radius=0.6 ), ) source_galaxy = al.Galaxy( redshift=2.0, bulge=al.lp.Sersic( centre=(0.0, 0.0), ell_comps=(0.0, 0.111111), intensity=0.7, effective_radius=0.1, sersic_index=1.5, ), ) tracer = al.Tracer(galaxies=[lens_galaxy_0, lens_galaxy_1, source_galaxy]) aplt.plot_array(array=tracer.image_2d_from(grid=grid), title="Image") ``` -------------------------------- ### Image-Plane Position Solver with PointSolver Source: https://context7.com/pyautolabs/pyautolens/llms.txt Solves the lens equation numerically for a given source-plane position by recursively tiling the image plane. Outputs image-plane multiple-image positions as a Grid2DIrregular. ```python import autolens as al lens = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.6), ) tracer = al.Tracer(galaxies=[lens, al.Galaxy(redshift=1.0)]) solver = al.PointSolver.for_grid( grid=al.Grid2D.uniform(shape_native=(200, 200), pixel_scales=0.05), pixel_scale_precision=0.001, ) # Solve for image-plane positions of a source at (0.07, 0.07) positions = solver.solve(tracer=tracer, source_plane_coordinate=(0.07, 0.07)) print(positions) # Grid2DIrregular with 4 image positions (quad lens) print(len(positions)) # typically 4 for an elliptical isothermal lens ``` -------------------------------- ### Run Pytest Source: https://github.com/pyautolabs/pyautolens/blob/main/CONTRIBUTING.md Navigate to the test directory and run pytest to ensure all tests pass. This should be done after making changes to verify code integrity. ```bash cd PyAutoLens/test_autolens python3 -m pytest ```