diff --git a/autogalaxy/analysis/analysis/analysis.py b/autogalaxy/analysis/analysis/analysis.py index 13160cc4a..cf7d96eb7 100644 --- a/autogalaxy/analysis/analysis/analysis.py +++ b/autogalaxy/analysis/analysis/analysis.py @@ -1,18 +1,12 @@ -import json import logging -from typing import Dict, List, Optional, Tuple, Union -from os import path -import os -import time +from typing import List, Optional -from autoconf import conf import autofit as af import autoarray as aa from autogalaxy.galaxy.galaxy import Galaxy from autogalaxy.galaxy.galaxies import Galaxies from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 logger = logging.getLogger(__name__) @@ -20,7 +14,7 @@ class Analysis(af.Analysis): - def __init__(self, cosmology: LensingCosmology = Planck15): + def __init__(self, cosmology: LensingCosmology = None): """ Fits a model to a dataset via a non-linear search. @@ -34,7 +28,10 @@ def __init__(self, cosmology: LensingCosmology = Planck15): cosmology The Cosmology assumed for this analysis. """ - self.cosmology = cosmology + + from autogalaxy.cosmology.wrap import Planck15 + + self.cosmology = cosmology or Planck15() def galaxies_via_instance_from( self, diff --git a/autogalaxy/analysis/analysis/dataset.py b/autogalaxy/analysis/analysis/dataset.py index d63b3181a..bc1d89967 100644 --- a/autogalaxy/analysis/analysis/dataset.py +++ b/autogalaxy/analysis/analysis/dataset.py @@ -1,4 +1,3 @@ -import copy import logging from typing import Optional, Union @@ -10,7 +9,6 @@ from autogalaxy.analysis.adapt_images.adapt_image_maker import AdaptImageMaker from autogalaxy.analysis.adapt_images.adapt_images import AdaptImages from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.analysis.analysis.analysis import Analysis from autogalaxy.analysis.result import ResultDataset @@ -24,7 +22,7 @@ def __init__( self, dataset: Union[aa.Imaging, aa.Interferometer], adapt_image_maker: Optional[AdaptImageMaker] = None, - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, settings_inversion: aa.SettingsInversion = None, title_prefix: str = None, ): diff --git a/autogalaxy/analysis/plotter_interface.py b/autogalaxy/analysis/plotter_interface.py index 447560912..35763e5f0 100644 --- a/autogalaxy/analysis/plotter_interface.py +++ b/autogalaxy/analysis/plotter_interface.py @@ -236,16 +236,11 @@ def should_plot(name): mapper_list = inversion.cls_list_from(cls=aa.AbstractMapper) for i, mapper in enumerate(mapper_list): - y = mapper.mapper_grids.source_plane_mesh_grid[:, 0].array - x = mapper.mapper_grids.source_plane_mesh_grid[:, 1].array + y = mapper.mapper_grids.source_plane_mesh_grid[:, 0] + x = mapper.mapper_grids.source_plane_mesh_grid[:, 1] reconstruction = inversion.reconstruction_dict[mapper] noise_map = inversion.reconstruction_noise_map_dict[mapper] - print(y) - print(x) - print(reconstruction) - print(noise_map) - with open( self.image_path / f"source_plane_reconstruction_{i}.csv", mode="w", diff --git a/autogalaxy/convert.py b/autogalaxy/convert.py index 37a42c025..3a199d220 100644 --- a/autogalaxy/convert.py +++ b/autogalaxy/convert.py @@ -1,4 +1,3 @@ -from astropy import units from typing import Tuple import jax @@ -322,6 +321,8 @@ def multipole_comps_from(k_m: float, phi_m: float, m: int) -> Tuple[float, float ------- The multipole component parameters. """ + from astropy import units + multipole_comp_0 = k_m * jnp.sin(phi_m * float(m) * units.deg.to(units.rad)) multipole_comp_1 = k_m * jnp.cos(phi_m * float(m) * units.deg.to(units.rad)) diff --git a/autogalaxy/cosmology/__init__.py b/autogalaxy/cosmology/__init__.py index c711bd2a7..5923b9c27 100644 --- a/autogalaxy/cosmology/__init__.py +++ b/autogalaxy/cosmology/__init__.py @@ -1,5 +1,2 @@ from .lensing import LensingCosmology from .wrap import Planck15 -from .model import LambdaCDMWrap -from .model import FlatwCDMWrap -from .model import FlatLambdaCDMWrap diff --git a/autogalaxy/cosmology/lensing.py b/autogalaxy/cosmology/lensing.py index 818504c6e..5823c6d9d 100644 --- a/autogalaxy/cosmology/lensing.py +++ b/autogalaxy/cosmology/lensing.py @@ -1,10 +1,8 @@ -from astropy import constants -from astropy import cosmology as cosmo import math import numpy as np -class LensingCosmology(cosmo.FLRW): +class LensingCosmology: """ Class containing specific functions for performing gravitational lensing cosmology calculations. @@ -12,6 +10,12 @@ class LensingCosmology(cosmo.FLRW): calculations. """ + def __init__(self): + + from astropy.cosmology import FLRW + + self._cosmo = FLRW() + def arcsec_per_kpc_from(self, redshift: float) -> float: """ Angular separation in arcsec corresponding to a proper kpc at redshift `z`. @@ -189,6 +193,8 @@ def critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( The redshift of the second strong lens galaxy (E.g. the lens galaxy) for which the critical surface density is calculated. """ + from astropy import constants + const = constants.c.to("kpc / s") ** 2.0 / ( 4 * math.pi * constants.G.to("kpc3 / (solMass s2)") ) @@ -305,6 +311,8 @@ def velocity_dispersion_from( redshift_1 The redshift of the second strong lens galaxy (the source). """ + from astropy import constants + const = constants.c.to("kpc / s") angular_diameter_distance_to_redshift_0_kpc = ( diff --git a/autogalaxy/cosmology/wrap.py b/autogalaxy/cosmology/wrap.py index 2728b545b..fdb808266 100644 --- a/autogalaxy/cosmology/wrap.py +++ b/autogalaxy/cosmology/wrap.py @@ -1,25 +1,25 @@ -from astropy import cosmology as cosmo +def Planck15(): + """ + A lazy-loading wrapper for the astropy `Planck15` cosmology class. -from autogalaxy.cosmology.lensing import LensingCosmology + The actual class is only created (and astropy imported) when this function is called. + """ + from astropy import cosmology as cosmo + from autogalaxy.cosmology.lensing import LensingCosmology -class Planck15(cosmo.FlatLambdaCDM, LensingCosmology): - def __init__(self): - """ - A wrapper for the astropy `Planck15` cosmology class. + class _Planck15(cosmo.FlatLambdaCDM, LensingCosmology): + def __init__(self): + Planck15_astropy = cosmo.Planck15 - The only role of this class is to instantiate the `Planck15` cosmology class from astropy, but to additionally - inherit from `LensingCosmology`, which is a class that provides additional functionality for calculating lensing - specific quantities in the cosmology. - """ - Planck15 = cosmo.Planck15 + super().__init__( + H0=Planck15_astropy.H0, + Om0=Planck15_astropy.Om0, + Tcmb0=Planck15_astropy.Tcmb0, + Neff=Planck15_astropy.Neff, + m_nu=Planck15_astropy.m_nu, + Ob0=Planck15_astropy.Ob0, + name=Planck15_astropy.name, + ) - super().__init__( - H0=Planck15.H0, - Om0=Planck15.Om0, - Tcmb0=Planck15.Tcmb0, - Neff=Planck15.Neff, - m_nu=Planck15.m_nu, - Ob0=Planck15.Ob0, - name=Planck15.name, - ) + return _Planck15() diff --git a/autogalaxy/ellipse/dataset_interp.py b/autogalaxy/ellipse/dataset_interp.py index ea165c5bc..a1b801b10 100644 --- a/autogalaxy/ellipse/dataset_interp.py +++ b/autogalaxy/ellipse/dataset_interp.py @@ -1,5 +1,4 @@ import numpy as np -from scipy import interpolate from typing import Tuple from autoconf import cached_property @@ -45,11 +44,13 @@ def points_interp(self) -> Tuple[np.ndarray, np.ndarray]: return (x, y) @cached_property - def mask_interp(self) -> interpolate.RegularGridInterpolator: + def mask_interp(self) -> "interpolate.RegularGridInterpolator": """ Returns a 2D interpolation of the mask, which is used to determine whether inteprolated values use a masked pixel for the interpolation and thus should not be included in a fit. """ + from scipy import interpolate + return interpolate.RegularGridInterpolator( points=self.points_interp, values=np.float64(self.dataset.data.mask), @@ -58,10 +59,12 @@ def mask_interp(self) -> interpolate.RegularGridInterpolator: ) @cached_property - def data_interp(self) -> interpolate.RegularGridInterpolator: + def data_interp(self) -> "interpolate.RegularGridInterpolator": """ Returns a 2D interpolation of the data, which is used to evaluate the data at any point in 2D space. """ + from scipy import interpolate + return interpolate.RegularGridInterpolator( points=self.points_interp, values=np.float64(self.dataset.data.native), @@ -70,10 +73,11 @@ def data_interp(self) -> interpolate.RegularGridInterpolator: ) @cached_property - def noise_map_interp(self) -> interpolate.RegularGridInterpolator: + def noise_map_interp(self) -> "interpolate.RegularGridInterpolator": """ Returns a 2D interpolation of the noise-map, which is used to evaluate the noise-map at any point in 2D space. """ + from scipy import interpolate return interpolate.RegularGridInterpolator( points=self.points_interp, diff --git a/autogalaxy/ellipse/plot/fit_ellipse_plot_util.py b/autogalaxy/ellipse/plot/fit_ellipse_plot_util.py deleted file mode 100644 index 43bf81b5d..000000000 --- a/autogalaxy/ellipse/plot/fit_ellipse_plot_util.py +++ /dev/null @@ -1,236 +0,0 @@ -import copy, matplotlib -import numpy as np -import matplotlib.pyplot as plt - -from astropy import units -from matplotlib.colors import LinearSegmentedColormap - - -def subplot_fit(fit_list): - # NOTE: - logscale = False - - # NOTE: - figure, axes = plt.subplots(nrows=1, ncols=2, figsize=(16, 8)) - - image = fit.data.native - image_temp = image - - # NOTE: - # image = copy.copy(sample.image) - # if sample.mask is not None: - # image[sample.mask.astype(bool)] = np.nan - # - # image_temp = copy.copy(sample.image) - # image_temp[~sample.mask.astype(bool)] = np.nan - # else: - # image_temp = None - - # NOTE: - def custom_colormap(): - # Define the colors - # colors = ['white', 'black', 'red'] - # positions = [0.0, 0.5, 1.0] - colors = ["grey", "white", "red", "darkred", "black"] - positions = [0.0, 0.25, 0.5, 0.75, 1.0] - - # Create the colormap - cmap = LinearSegmentedColormap.from_list( - "custom_colormap", list(zip(positions, colors)) - ) - - return cmap - - vmin = None - vmax = None - - if vmin is None: - vmin = 0.025 - if vmax is None: - vmax = 5.0 - - norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) - - im = axes[0].imshow( - np.log10(image) if logscale else image, - cmap="jet", - aspect="auto", - norm=norm, - ) - if image_temp is not None: - axes[0].imshow( - np.log10(image_temp) if logscale else image_temp, - cmap="jet", - aspect="auto", - alpha=0.5, - ) - - ellipse_list = [fit.ellipse for fit in fit_list] - - list_of_angles = [] - list_of_y_fit = [] - list_of_y_errors_fit = [] - y_means = [] - y_stds = [] - - radii - - for i, (a, parameters) in enumerate(zip(array, list_of_parameters)): - if i == 0: - m = sum(1 for value in parameters.values() if value is not None) - - y_fit, y_errors_fit, (x, y), angles = sample.extract( - a=a, parameters=parameters, condition=extract_condition - ) - list_of_angles.append(angles) - list_of_y_fit.append(y_fit) - list_of_y_errors_fit.append(y_errors_fit) - - if y_errors_fit is None: - # y_errors_fit = 0.05 * y_fit - raise NotImplementedError() - - # NOTE: - y_mean = np.nanmean(y_fit) - y_means.append(y_mean) - - # NOTE: - y_std = np.nanstd(y_fit) - y_stds.append(y_std) - - # NOTE: - axes[0].plot(x, y, marker="o", markersize=2.5, color="w") - - # NOTE: - axes[1].errorbar( - angles * units.rad.to(units.deg), - y_fit, - yerr=y_errors_fit, - linestyle="None", - marker="o", - markersize=2.5, - color="black", - ) - axes[1].axhline(y_mean, linestyle=":", color="black") - - levels = np.sort(np.log10(y_means)) if logscale else np.sort(y_means) - axes[0].contour( - np.log10(image) if logscale else image, - # levels=y_means[::-1], - levels=levels, - colors="black", - ) - colors = [im.cmap(im.norm(level)) for level in levels][::-1] - - for i, (angles, y_fit, y_errors_fit) in enumerate( - zip(list_of_angles, list_of_y_fit, list_of_y_errors_fit) - ): - axes[1].errorbar( - angles * units.rad.to(units.deg), - y_fit, - yerr=y_errors_fit, - linestyle="None", - marker="o", - markersize=2.5, - color=colors[i], - ) - # axes[0].plot( - # [247], - # [250], - # marker="o" - # ) - xticks = np.linspace(0, image.shape[1], 11) - yticks = np.linspace(0, image.shape[0], 11) - axes[0].set_xticks(xticks) - axes[0].set_yticks(xticks) - axes[1].set_xticks([0, 90, 180, 270, 360]) - axes[1].set_xlabel(r"$\phi$ (deg)", fontsize=15) - axes[1].set_ylabel(r"$\rm I(\phi)$ [E/s]", fontsize=15) - axes[1].tick_params(axis="y", labelsize=12.5) - axes[1].yaxis.tick_right() - axes[1].yaxis.set_label_position("right") - for i, ax in enumerate(axes): - ax.minorticks_on() - ax.tick_params( - axis="both", - which="major", - length=6, - right=True, - top=True, - direction="in", - colors="w" if i == 0 else "black", - ) - ax.tick_params( - axis="both", - which="minor", - length=3, - right=True, - top=True, - direction="in", - colors="w" if i == 0 else "black", - ) - - axes[1].set_yscale("log") - - # text = axes[0].text( - # 0.05, - # 0.95, - # "model 1", - # horizontalalignment='left', - # verticalalignment='center', - # transform=axes[0].transAxes, - # fontsize=25, - # weight="bold", - # color="w" - # ) - # text.set_path_effects([patheffects.withStroke(linewidth=3, foreground='black')]) - - # text = axes[0].text( - # 0.7, - # 0.95, - # "NGC 2274", - # horizontalalignment='left', - # verticalalignment='center', - # transform=axes[0].transAxes, - # fontsize=25, - # weight="bold", - # color="w" - # ) - # text.set_path_effects([patheffects.withStroke(linewidth=3, foreground='black')]) - - if a_max is None: - axes[0].set_xlim(0, image.shape[1]) - axes[0].set_ylim(0, image.shape[0]) - else: - x0 = list_of_parameters[0]["x0"] - y0 = list_of_parameters[0]["y0"] - axes[0].set_xlim(x0 - a_max, x0 + a_max) - axes[0].set_ylim(y0 - a_max, y0 + a_max) - - # NOTE: - figure.subplots_adjust(left=0.05, right=0.95, bottom=0.075, top=0.95, wspace=0.0) - - y = [] - for i, (a, chi_squares_i) in enumerate(zip(array, chi_squares)): - n = len(chi_squares_i) - 1 - - # NOTE: - y_i = np.nansum(chi_squares_i[:-1]) / (n - m) - y.append(y_i) - - figure_stats, axes_stats = plt.subplots() - axes_stats.plot(array, y, linestyle="None", marker="o", color="black") - axes_stats.set_xscale("log") - axes_stats.set_yscale("log") - # directory = "./MASSIVE/metadata" - # filename = "{}/xy_model_default.numpy".format(directory) - # with open(filename, 'wb') as f: - # np.save(f, [x, y]) - # plt.show() - # exit() - - # NOTE: - # chi_squares_flattened = list(itertools.chain(*chi_squares)) - # plt.hist(chi_squares_flattened, bins=100, alpha=0.75) - - # plt.show();exit() diff --git a/autogalaxy/ellipse/plot/fit_ellipse_plotters.py b/autogalaxy/ellipse/plot/fit_ellipse_plotters.py index b6d99eeb7..8ae0f792d 100644 --- a/autogalaxy/ellipse/plot/fit_ellipse_plotters.py +++ b/autogalaxy/ellipse/plot/fit_ellipse_plotters.py @@ -1,14 +1,9 @@ -import matplotlib.pyplot as plt import numpy as np from typing import List -from autoconf import conf - import autoarray as aa from autoarray import plot as aplt -from autoarray.plot.auto_labels import AutoLabels - from autogalaxy.ellipse.fit_ellipse import FitEllipse from autogalaxy.plot.abstract_plotters import Plotter from autogalaxy.plot.mat_plot.one_d import MatPlot1D @@ -23,12 +18,12 @@ class FitEllipsePlotter(Plotter): def __init__( self, fit_list: List[FitEllipse], - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): super().__init__( mat_plot_1d=mat_plot_1d, diff --git a/autogalaxy/galaxy/plot/adapt_plotters.py b/autogalaxy/galaxy/plot/adapt_plotters.py index 933242c65..0f2f39d2e 100644 --- a/autogalaxy/galaxy/plot/adapt_plotters.py +++ b/autogalaxy/galaxy/plot/adapt_plotters.py @@ -13,9 +13,9 @@ class AdaptPlotter(Plotter): def __init__( self, - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d diff --git a/autogalaxy/galaxy/plot/galaxies_plotters.py b/autogalaxy/galaxy/plot/galaxies_plotters.py index 14573cd4b..473cb5c8a 100644 --- a/autogalaxy/galaxy/plot/galaxies_plotters.py +++ b/autogalaxy/galaxy/plot/galaxies_plotters.py @@ -23,12 +23,12 @@ def __init__( self, galaxies: List[Galaxy], grid: aa.type.Grid1D2DLike, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): """ Plots the attributes of a list of galaxies using the matplotlib methods `plot()` and `imshow()` and many diff --git a/autogalaxy/galaxy/plot/galaxy_plotters.py b/autogalaxy/galaxy/plot/galaxy_plotters.py index 003f6767f..06926ffca 100644 --- a/autogalaxy/galaxy/plot/galaxy_plotters.py +++ b/autogalaxy/galaxy/plot/galaxy_plotters.py @@ -33,12 +33,12 @@ def __init__( self, galaxy: Galaxy, grid: aa.type.Grid1D2DLike, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): """ Plots the attributes of `Galaxy` objects using the matplotlib methods `plot()` and `imshow()` and many @@ -535,12 +535,12 @@ def __init__( self, galaxy_pdf_list: List[Galaxy], grid: aa.Grid2D, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, sigma: Optional[float] = 3.0, ): """ diff --git a/autogalaxy/gui/scribbler.py b/autogalaxy/gui/scribbler.py index 8362a0fee..74385a73d 100644 --- a/autogalaxy/gui/scribbler.py +++ b/autogalaxy/gui/scribbler.py @@ -1,7 +1,5 @@ from collections import OrderedDict import numpy as np -import matplotlib -import matplotlib.pyplot as plt from typing import Tuple @@ -58,6 +56,7 @@ def __init__( extent = (x0_pix, x1_pix, y0_pix, y1_pix) + import matplotlib import matplotlib.pyplot as plt matplotlib.use(backend) @@ -129,6 +128,9 @@ def on_mouse_down(self, event): self.add_circle_to_scribble(center) def on_mouse_motion(self, event): + + import matplotlib + center = (event.xdata, event.ydata) # draw the bush circle @@ -166,6 +168,9 @@ def on_keypress(self, event): self.active_scribble_color = self.scribble_colors[num] def add_circle_to_scribble(self, center): + + import matplotlib + circle = matplotlib.patches.Circle( center, radius=self.brush_radius, @@ -198,10 +203,14 @@ def shrink_brush(self): self.figure.canvas.draw() def quit_(self): + import matplotlib.pyplot as plt + plt.close() self.figure.canvas.stop_event_loop() def show_mask(self): + import matplotlib.pyplot as plt + masks = self.get_scribble_masks() junk_mask = masks["1"] feature_mask = masks["2"] diff --git a/autogalaxy/imaging/model/analysis.py b/autogalaxy/imaging/model/analysis.py index 2f27c2a17..90e3c3e47 100644 --- a/autogalaxy/imaging/model/analysis.py +++ b/autogalaxy/imaging/model/analysis.py @@ -1,23 +1,15 @@ -import numpy as np -from typing import Dict, Optional, Tuple - -from autoconf.fitsable import hdu_list_for_output_from +from typing import Optional import autofit as af import autoarray as aa -from autoarray.exc import PixelizationException - from autogalaxy.analysis.adapt_images.adapt_image_maker import AdaptImageMaker from autogalaxy.analysis.analysis.dataset import AnalysisDataset from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.imaging.model.result import ResultImaging from autogalaxy.imaging.model.visualizer import VisualizerImaging from autogalaxy.imaging.fit_imaging import FitImaging -from autogalaxy import exc - class AnalysisImaging(AnalysisDataset): Result = ResultImaging @@ -27,7 +19,7 @@ def __init__( self, dataset: aa.Imaging, adapt_image_maker: Optional[AdaptImageMaker] = None, - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, settings_inversion: aa.SettingsInversion = None, title_prefix: str = None, ): diff --git a/autogalaxy/imaging/plot/fit_imaging_plotters.py b/autogalaxy/imaging/plot/fit_imaging_plotters.py index 439d3e9aa..8c6575a21 100644 --- a/autogalaxy/imaging/plot/fit_imaging_plotters.py +++ b/autogalaxy/imaging/plot/fit_imaging_plotters.py @@ -18,9 +18,9 @@ class FitImagingPlotter(Plotter): def __init__( self, fit: FitImaging, - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, residuals_symmetric_cmap: bool = True, ): """ diff --git a/autogalaxy/interferometer/model/analysis.py b/autogalaxy/interferometer/model/analysis.py index c774e73f9..9abffdb33 100644 --- a/autogalaxy/interferometer/model/analysis.py +++ b/autogalaxy/interferometer/model/analysis.py @@ -1,23 +1,17 @@ import logging -import numpy as np -from typing import Dict, Optional, Tuple +from typing import Optional from autoconf.dictable import to_dict -from autoconf.fitsable import hdu_list_for_output_from import autofit as af import autoarray as aa -from autoarray.exc import PixelizationException - from autogalaxy.analysis.adapt_images.adapt_image_maker import AdaptImageMaker from autogalaxy.analysis.analysis.dataset import AnalysisDataset from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.interferometer.model.result import ResultInterferometer from autogalaxy.interferometer.fit_interferometer import FitInterferometer from autogalaxy.interferometer.model.visualizer import VisualizerInterferometer -from autogalaxy import exc logger = logging.getLogger(__name__) @@ -32,7 +26,7 @@ def __init__( self, dataset: aa.Interferometer, adapt_image_maker: Optional[AdaptImageMaker] = None, - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, settings_inversion: aa.SettingsInversion = None, title_prefix: str = None, ): diff --git a/autogalaxy/interferometer/plot/fit_interferometer_plotters.py b/autogalaxy/interferometer/plot/fit_interferometer_plotters.py index 8fd3995ab..3c063d31d 100644 --- a/autogalaxy/interferometer/plot/fit_interferometer_plotters.py +++ b/autogalaxy/interferometer/plot/fit_interferometer_plotters.py @@ -22,12 +22,12 @@ class FitInterferometerPlotter(Plotter): def __init__( self, fit: FitInterferometer, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, residuals_symmetric_cmap: bool = True, ): """ diff --git a/autogalaxy/plot/abstract_plotters.py b/autogalaxy/plot/abstract_plotters.py index 2816e7a94..94803bd94 100644 --- a/autogalaxy/plot/abstract_plotters.py +++ b/autogalaxy/plot/abstract_plotters.py @@ -4,8 +4,43 @@ from autoarray.plot.abstract_plotters import AbstractPlotter +from autogalaxy.plot.mat_plot.one_d import MatPlot1D +from autogalaxy.plot.mat_plot.two_d import MatPlot2D +from autogalaxy.plot.visuals.one_d import Visuals1D +from autogalaxy.plot.visuals.two_d import Visuals2D +from autogalaxy.plot.include.one_d import Include1D +from autogalaxy.plot.include.two_d import Include2D + class Plotter(AbstractPlotter): + + def __init__( + self, + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, + ): + + super().__init__( + mat_plot_1d=mat_plot_1d, + visuals_1d=visuals_1d, + include_1d=include_1d, + mat_plot_2d=mat_plot_2d, + visuals_2d=visuals_2d, + include_2d=include_2d, + ) + + self.visuals_1d = visuals_1d or Visuals1D() + self.include_1d = include_1d or Include1D() + self.mat_plot_1d = mat_plot_1d or MatPlot1D() + + self.visuals_2d = visuals_2d or Visuals2D() + self.include_2d = include_2d or Include2D() + self.mat_plot_2d = mat_plot_2d or MatPlot2D() + @property def get_1d(self): from autogalaxy.plot.get_visuals.one_d import GetVisuals1D diff --git a/autogalaxy/plot/mass_plotter.py b/autogalaxy/plot/mass_plotter.py index ca8f2577c..51ba4f56e 100644 --- a/autogalaxy/plot/mass_plotter.py +++ b/autogalaxy/plot/mass_plotter.py @@ -18,9 +18,9 @@ def __init__( mass_obj, grid: aa.type.Grid2DLike, get_visuals_2d: Callable, - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d diff --git a/autogalaxy/plot/visuals/two_d.py b/autogalaxy/plot/visuals/two_d.py index c692619f3..5cd816214 100644 --- a/autogalaxy/plot/visuals/two_d.py +++ b/autogalaxy/plot/visuals/two_d.py @@ -1,4 +1,3 @@ -from matplotlib import patches as ptch from typing import List, Union, Optional import autoarray as aa @@ -16,7 +15,7 @@ def __init__( grid: Union[aa.Grid2D] = None, mesh_grid: aa.Grid2D = None, vectors: aa.VectorYX2DIrregular = None, - patches: Union[ptch.Patch] = None, + patches: "Union[ptch.Patch]" = None, array_overlay: aa.Array2D = None, light_profile_centres: aa.Grid2DIrregular = None, mass_profile_centres: aa.Grid2DIrregular = None, diff --git a/autogalaxy/profiles/light/abstract.py b/autogalaxy/profiles/light/abstract.py index 27646eba0..da88cbcc4 100644 --- a/autogalaxy/profiles/light/abstract.py +++ b/autogalaxy/profiles/light/abstract.py @@ -1,5 +1,4 @@ import numpy as np -from scipy.integrate import quad from typing import Optional, Tuple import autoarray as aa @@ -117,6 +116,7 @@ def luminosity_within_circle_from(self, radius: float) -> float: radius The radius of the circle to compute the dimensionless luminosity within. """ + from scipy.integrate import quad return quad(func=self.luminosity_integral, a=0.0, b=radius)[0] diff --git a/autogalaxy/profiles/light/snr/abstract.py b/autogalaxy/profiles/light/snr/abstract.py index 71350f0c0..d4f0525d0 100644 --- a/autogalaxy/profiles/light/snr/abstract.py +++ b/autogalaxy/profiles/light/snr/abstract.py @@ -3,8 +3,6 @@ import autoarray as aa -from scipy.optimize import root_scalar - class LightProfileSNR: def __init__(self, signal_to_noise_ratio: float = 10.0): @@ -78,6 +76,8 @@ def set_intensity_from( The psf of the simulated imaging which can change the S/N of the light profile due to spreading out the emission. """ + from scipy.optimize import root_scalar + self.intensity = 1.0 background_sky_level_counts = background_sky_level * exposure_time diff --git a/autogalaxy/profiles/light/standard/shapelets/cartesian.py b/autogalaxy/profiles/light/standard/shapelets/cartesian.py index 331a6f579..76785e471 100644 --- a/autogalaxy/profiles/light/standard/shapelets/cartesian.py +++ b/autogalaxy/profiles/light/standard/shapelets/cartesian.py @@ -1,7 +1,5 @@ import jax.numpy as jnp import numpy as np -from scipy.special import hermite -from jax.scipy.special import factorial from typing import Optional, Tuple import autoarray as aa @@ -84,6 +82,8 @@ def image_2d_from( image The image of the Cartesian Shapelet evaluated at every (y,x) coordinate on the transformed grid. """ + from jax.scipy.special import factorial + from scipy.special import hermite hermite_y = hermite(n=self.n_y) hermite_x = hermite(n=self.n_x) diff --git a/autogalaxy/profiles/light/standard/shapelets/exponential.py b/autogalaxy/profiles/light/standard/shapelets/exponential.py index ce6955e94..9dbf5bee7 100644 --- a/autogalaxy/profiles/light/standard/shapelets/exponential.py +++ b/autogalaxy/profiles/light/standard/shapelets/exponential.py @@ -1,7 +1,5 @@ import jax.numpy as jnp import numpy as np -from scipy.special import genlaguerre -from jax.scipy.special import factorial from typing import Optional, Tuple import autoarray as aa @@ -85,6 +83,8 @@ def image_2d_from( image The image of the Exponential Shapelet evaluated at every (y,x) coordinate on the transformed grid. """ + from scipy.special import genlaguerre + from jax.scipy.special import factorial radial = (grid.array[:, 0] ** 2 + grid.array[:, 1] ** 2) / self.beta theta = jnp.arctan(grid.array[:, 1] / grid.array[:, 0]) diff --git a/autogalaxy/profiles/light/standard/shapelets/polar.py b/autogalaxy/profiles/light/standard/shapelets/polar.py index affeb52b5..9733308fc 100644 --- a/autogalaxy/profiles/light/standard/shapelets/polar.py +++ b/autogalaxy/profiles/light/standard/shapelets/polar.py @@ -1,7 +1,5 @@ import jax.numpy as jnp import numpy as np -from scipy.special import genlaguerre -from jax.scipy.special import factorial from typing import Optional, Tuple import autoarray as aa @@ -85,6 +83,8 @@ def image_2d_from( image The image of the Polar Shapelet evaluated at every (y,x) coordinate on the transformed grid. """ + from scipy.special import genlaguerre + from jax.scipy.special import factorial laguerre = genlaguerre( n=(self.n - jnp.abs(self.m)) / 2.0, alpha=jnp.abs(self.m) diff --git a/autogalaxy/profiles/mass/abstract/abstract.py b/autogalaxy/profiles/mass/abstract/abstract.py index a7fd585ad..fe6655ef1 100644 --- a/autogalaxy/profiles/mass/abstract/abstract.py +++ b/autogalaxy/profiles/mass/abstract/abstract.py @@ -1,6 +1,4 @@ import numpy as np -from scipy.integrate import quad -from scipy.optimize import root_scalar from typing import Tuple import autoarray as aa @@ -82,6 +80,7 @@ def mass_angular_within_circle_from(self, radius: float): radius : dim.Length The radius of the circle to compute the dimensionless mass within. """ + from scipy.integrate import quad return quad(self.mass_integral, a=0.0, b=radius)[0] @@ -124,6 +123,7 @@ def average_convergence_of_1_radius(self): This radius corresponds to the Einstein radius of the mass profile, and is a property of a number of \ mass profiles below. """ + from scipy.optimize import root_scalar def func(radius): return ( diff --git a/autogalaxy/profiles/mass/abstract/cse.py b/autogalaxy/profiles/mass/abstract/cse.py index 1917c0355..9d096aa7a 100644 --- a/autogalaxy/profiles/mass/abstract/cse.py +++ b/autogalaxy/profiles/mass/abstract/cse.py @@ -1,6 +1,5 @@ from abc import ABC, abstractmethod import numpy as np -from scipy.linalg import lstsq from typing import Callable, List, Tuple @@ -85,6 +84,8 @@ def _decompose_convergence_via_cse_from( A list of amplitudes and core radii of every cored steep elliptical (cse) the mass profile is decomposed into. """ + from scipy.linalg import lstsq + error_sigma = 0.1 # error spread. Could be any value. r_samples = np.logspace(np.log10(radii_min), np.log10(radii_max), sample_points) diff --git a/autogalaxy/profiles/mass/abstract/mge_numpy.py b/autogalaxy/profiles/mass/abstract/mge_numpy.py index 08576fd41..124d278cf 100644 --- a/autogalaxy/profiles/mass/abstract/mge_numpy.py +++ b/autogalaxy/profiles/mass/abstract/mge_numpy.py @@ -1,5 +1,4 @@ import numpy as np -from scipy.special import comb def w_f_approx(z): @@ -110,7 +109,6 @@ def __init__(self): self.expv = 0 @staticmethod - # @aa.util.numba.jit() def zeta_from(grid, amps, sigmas, axis_ratio): """ The key part to compute the deflection angle of each Gaussian. @@ -165,6 +163,8 @@ def eta(p): """ see Eq.(6) of 1906.00263 """ + from scipy.special import comb + eta_list = np.zeros(int(2 * p + 1)) kesi_list = np.zeros(int(2 * p + 1)) kesi_list[0] = 0.5 diff --git a/autogalaxy/profiles/mass/abstract/mge_numpy_coleman.py b/autogalaxy/profiles/mass/abstract/mge_numpy_coleman.py index 08fd0c50d..5f5b8a97b 100644 --- a/autogalaxy/profiles/mass/abstract/mge_numpy_coleman.py +++ b/autogalaxy/profiles/mass/abstract/mge_numpy_coleman.py @@ -1,5 +1,4 @@ import numpy as np -from scipy.special import comb def w_f_approx(z): @@ -108,7 +107,6 @@ def __init__(self): self.expv = 0 @staticmethod - # @aa.util.numba.jit() def zeta_from(grid, amps, sigmas, axis_ratio): """ The key part to compute the deflection angle of each Gaussian. @@ -163,6 +161,8 @@ def eta(p): """ see Eq.(6) of 1906.00263 """ + from scipy.special import comb + eta_list = np.zeros(int(2 * p + 1)) kesi_list = np.zeros(int(2 * p + 1)) kesi_list[0] = 0.5 diff --git a/autogalaxy/profiles/mass/dark/abstract.py b/autogalaxy/profiles/mass/dark/abstract.py index fc777ef0d..bcab55d48 100644 --- a/autogalaxy/profiles/mass/dark/abstract.py +++ b/autogalaxy/profiles/mass/dark/abstract.py @@ -1,12 +1,10 @@ import numpy as np -from scipy.optimize import fsolve from typing import Tuple import autoarray as aa from autogalaxy.profiles.mass.abstract.abstract import MassProfile from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.profiles.mass.abstract.mge_numpy import ( MassProfileMGE, ) @@ -141,7 +139,6 @@ def coord_func_f(self, grid_radius): ) @staticmethod - @aa.util.numba.jit() def coord_func_f_jit(grid_radius, f): for index in range(f.shape[0]): if np.real(grid_radius[index]) > 1.0: @@ -168,7 +165,6 @@ def coord_func_g(self, grid_radius): ) @staticmethod - @aa.util.numba.jit() def coord_func_g_jit(grid_radius, f_r, g): for index in range(f_r.shape[0]): if np.real(grid_radius[index]) > 1.0: @@ -184,12 +180,16 @@ def coord_func_h(self, grid_radius): return np.log(grid_radius / 2.0) + self.coord_func_f(grid_radius=grid_radius) def rho_at_scale_radius_solar_mass_per_kpc3( - self, redshift_object, redshift_source, cosmology: LensingCosmology = Planck15() + self, redshift_object, redshift_source, cosmology: LensingCosmology = None ): """ The Cosmic average density is defined at the redshift of the profile. """ + from autogalaxy.cosmology.wrap import Planck15 + + cosmology = cosmology or Planck15() + critical_surface_density = cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( redshift_0=redshift_object, redshift_1=redshift_source ) @@ -207,8 +207,13 @@ def delta_concentration( redshift_object, redshift_source, redshift_of_cosmic_average_density="profile", - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, ): + + from autogalaxy.cosmology.wrap import Planck15 + + cosmology = cosmology or Planck15() + if redshift_of_cosmic_average_density == "profile": redshift_calc = redshift_object elif redshift_of_cosmic_average_density == "local": @@ -238,8 +243,15 @@ def concentration( redshift_profile, redshift_source, redshift_of_cosmic_average_density="profile", - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, ): + + from autogalaxy.cosmology.wrap import Planck15 + + cosmology = cosmology or Planck15() + + from scipy.optimize import fsolve + """ Computes the NFW halo concentration, `c_{200m}` """ @@ -273,11 +285,15 @@ def radius_at_200( redshift_object, redshift_source, redshift_of_cosmic_average_density="profile", - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, ): """ Returns `r_{200m}` for this halo in **arcseconds** """ + from autogalaxy.cosmology.wrap import Planck15 + + cosmology = cosmology or Planck15() + concentration = self.concentration( redshift_profile=redshift_object, redshift_source=redshift_source, @@ -292,8 +308,12 @@ def mass_at_200_solar_masses( redshift_object, redshift_source, redshift_of_cosmic_average_density="profile", - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, ): + from autogalaxy.cosmology.wrap import Planck15 + + cosmology = cosmology or Planck15() + """ Returns `M_{200m}` of this NFW halo, in solar masses, at the given cosmology. """ diff --git a/autogalaxy/profiles/mass/dark/gnfw.py b/autogalaxy/profiles/mass/dark/gnfw.py index 171016849..047154085 100644 --- a/autogalaxy/profiles/mass/dark/gnfw.py +++ b/autogalaxy/profiles/mass/dark/gnfw.py @@ -1,8 +1,4 @@ -import inspect import numpy as np -from scipy import LowLevelCallable -from scipy import special -from scipy.integrate import quad from typing import Tuple import autoarray as aa @@ -10,78 +6,6 @@ from autogalaxy.profiles.mass.dark.abstract import AbstractgNFW -def jit_integrand(integrand_function): - from numba import cfunc - from numba.types import intc, CPointer, float64 - - jitted_function = aa.util.numba.jit(nopython=True, cache=True)(integrand_function) - no_args = len(inspect.getfullargspec(integrand_function).args) - - wrapped = None - - if no_args == 4: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function(xx[0], xx[1], xx[2], xx[3]) - - elif no_args == 5: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function(xx[0], xx[1], xx[2], xx[3], xx[4]) - - elif no_args == 6: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function(xx[0], xx[1], xx[2], xx[3], xx[4], xx[5]) - - elif no_args == 7: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function(xx[0], xx[1], xx[2], xx[3], xx[4], xx[5], xx[6]) - - elif no_args == 8: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function( - xx[0], xx[1], xx[2], xx[3], xx[4], xx[5], xx[6], xx[7] - ) - - elif no_args == 9: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function( - xx[0], xx[1], xx[2], xx[3], xx[4], xx[5], xx[6], xx[7], xx[8] - ) - - elif no_args == 10: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function( - xx[0], xx[1], xx[2], xx[3], xx[4], xx[5], xx[6], xx[7], xx[8], xx[9] - ) - - elif no_args == 11: - # noinspection PyUnusedLocal - def wrapped(n, xx): - return jitted_function( - xx[0], - xx[1], - xx[2], - xx[3], - xx[4], - xx[5], - xx[6], - xx[7], - xx[8], - xx[9], - xx[10], - ) - - cf = cfunc(float64(intc, CPointer(float64))) - - return LowLevelCallable(cf(wrapped).ctypes) - - class gNFW(AbstractgNFW): def deflections_yx_2d_from(self, grid: aa.type.Grid2DLike, **kwargs): return self.deflections_2d_via_mge_from(grid=grid, **kwargs) @@ -110,7 +34,6 @@ def deflections_2d_via_integral_from( """ - @jit_integrand def surface_density_integrand(x, kappa_radius, scale_radius, inner_slope): return ( (3 - inner_slope) @@ -119,6 +42,9 @@ def surface_density_integrand(x, kappa_radius, scale_radius, inner_slope): ) def calculate_deflection_component(npow, yx_index): + + from scipy.integrate import quad + deflection_grid = np.zeros(grid.shape[0]) for i in range(grid.shape[0]): @@ -158,6 +84,8 @@ def calculate_deflection_component(npow, yx_index): surface_density_integral = np.zeros((tabulate_bins,)) for i in range(tabulate_bins): + from scipy.integrate import quad + eta = 10.0 ** (minimum_log_eta + (i - 1) * bin_size) integral = quad( @@ -202,6 +130,9 @@ def deflection_func( return kap / (1.0 - (1.0 - axis_ratio**2) * u) ** (npow + 0.5) def convergence_func(self, grid_radius: float) -> float: + + from scipy.integrate import quad + def integral_y(y, eta): return (y + eta) ** (self.inner_slope - 4) * (1 - np.sqrt(1 - y**2)) @@ -244,7 +175,9 @@ def potential_2d_from(self, grid: aa.type.Grid2DLike, tabulate_bins=1000, **kwar """ - @jit_integrand + from scipy import special + from scipy.integrate import quad + def deflection_integrand(x, kappa_radius, scale_radius, inner_slope): return (x + kappa_radius / scale_radius) ** (inner_slope - 3) * ( (1 - np.sqrt(1 - x**2)) / x @@ -390,6 +323,10 @@ def deflection_integrand(y, eta, inner_slope): return (y + eta) ** (inner_slope - 3) * ((1 - np.sqrt(1 - y**2)) / y) def deflection_func_sph(self, eta): + + from scipy import special + from scipy.integrate import quad + integral_y_2 = quad( self.deflection_integrand, a=0.0, diff --git a/autogalaxy/profiles/mass/dark/gnfw_virial_mass_conc.py b/autogalaxy/profiles/mass/dark/gnfw_virial_mass_conc.py index 838b67453..7a2292fbd 100644 --- a/autogalaxy/profiles/mass/dark/gnfw_virial_mass_conc.py +++ b/autogalaxy/profiles/mass/dark/gnfw_virial_mass_conc.py @@ -2,17 +2,16 @@ from autogalaxy.profiles.mass.dark.gnfw import gNFWSph -from astropy import units - import numpy as np from autogalaxy import cosmology as cosmo -from scipy.integrate import quad - def kappa_s_and_scale_radius( cosmology, virial_mass, c_2, overdens, redshift_object, redshift_source, inner_slope ): + from astropy import units + from scipy.integrate import quad + concentration = (2 - inner_slope) * c_2 # gNFW concentration critical_density = ( diff --git a/autogalaxy/profiles/mass/dark/gnfw_virial_mass_gnfw_conc.py b/autogalaxy/profiles/mass/dark/gnfw_virial_mass_gnfw_conc.py index 5be2e7840..e30205982 100644 --- a/autogalaxy/profiles/mass/dark/gnfw_virial_mass_gnfw_conc.py +++ b/autogalaxy/profiles/mass/dark/gnfw_virial_mass_gnfw_conc.py @@ -2,13 +2,9 @@ from autogalaxy.profiles.mass.dark.gnfw import gNFWSph -from astropy import units - import numpy as np from autogalaxy import cosmology as cosmo -from scipy.integrate import quad - def kappa_s_and_scale_radius( cosmology, @@ -19,6 +15,9 @@ def kappa_s_and_scale_radius( redshift_source, inner_slope, ): + from astropy import units + from scipy.integrate import quad + # gNFW concentration imported critical_density = ( diff --git a/autogalaxy/profiles/mass/dark/mcr_util.py b/autogalaxy/profiles/mass/dark/mcr_util.py index f3fc01197..f8d1b84bb 100644 --- a/autogalaxy/profiles/mass/dark/mcr_util.py +++ b/autogalaxy/profiles/mass/dark/mcr_util.py @@ -1,10 +1,6 @@ -from astropy import units - import numpy as np import warnings -from autogalaxy.cosmology.wrap import Planck15 - def kappa_s_and_scale_radius_for_duffy(mass_at_200, redshift_object, redshift_source): """ @@ -13,6 +9,11 @@ def kappa_s_and_scale_radius_for_duffy(mass_at_200, redshift_object, redshift_so Interprets mass as *`M_{200c}`*, not `M_{200m}`. """ + + from astropy import units + + from autogalaxy.cosmology.wrap import Planck15 + cosmology = Planck15() cosmic_average_density = ( @@ -64,11 +65,14 @@ def kappa_s_and_scale_radius_for_ludlow( Interprets mass as *`M_{200c}`*, not `M_{200m}`. """ + from astropy import units from colossus.cosmology import cosmology as col_cosmology from colossus.halo.concentration import concentration as col_concentration warnings.filterwarnings("ignore") + from autogalaxy.cosmology.wrap import Planck15 + cosmology = Planck15() col_cosmo = col_cosmology.setCosmology("planck15") diff --git a/autogalaxy/profiles/mass/dark/nfw.py b/autogalaxy/profiles/mass/dark/nfw.py index 3dd3d7cce..d983782ec 100644 --- a/autogalaxy/profiles/mass/dark/nfw.py +++ b/autogalaxy/profiles/mass/dark/nfw.py @@ -1,6 +1,5 @@ import jax.numpy as jnp import numpy as np -from scipy.integrate import quad from typing import Tuple import autoarray as aa @@ -59,6 +58,7 @@ def deflections_2d_via_integral_from(self, grid: aa.type.Grid2DLike, **kwargs): The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ + from scipy.integrate import quad def calculate_deflection_component(npow, index): deflection_grid = np.array(self.axis_ratio * grid.array[:, index]) @@ -157,6 +157,7 @@ def potential_2d_from(self, grid: aa.type.Grid2DLike, **kwargs): The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ + from scipy.integrate import quad potential_grid = np.zeros(grid.shape[0]) diff --git a/autogalaxy/profiles/mass/dark/nfw_hk24_util.py b/autogalaxy/profiles/mass/dark/nfw_hk24_util.py index 71bdce62c..0d24b679d 100644 --- a/autogalaxy/profiles/mass/dark/nfw_hk24_util.py +++ b/autogalaxy/profiles/mass/dark/nfw_hk24_util.py @@ -5,9 +5,6 @@ """ import numpy as np -from astropy.cosmology import Planck15 - -cosmo = Planck15 def semi_major_axis_from(x1: np.ndarray, x2: np.ndarray, e: np.ndarray) -> np.ndarray: diff --git a/autogalaxy/profiles/mass/dark/nfw_truncated.py b/autogalaxy/profiles/mass/dark/nfw_truncated.py index 7699f73f7..119077aee 100644 --- a/autogalaxy/profiles/mass/dark/nfw_truncated.py +++ b/autogalaxy/profiles/mass/dark/nfw_truncated.py @@ -4,7 +4,6 @@ import autoarray as aa from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.profiles.mass.dark.abstract import AbstractgNFW @@ -109,8 +108,12 @@ def mass_at_truncation_radius_solar_mass( redshift_profile, redshift_source, redshift_of_cosmic_average_density="profile", - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, ): + from autogalaxy.cosmology.wrap import Planck15 + + cosmology = cosmology or Planck15() + mass_at_200 = self.mass_at_200_solar_masses( redshift_object=redshift_profile, redshift_source=redshift_source, diff --git a/autogalaxy/profiles/mass/dark/nfw_virial_mass_conc.py b/autogalaxy/profiles/mass/dark/nfw_virial_mass_conc.py index 5ca0d3590..d11cf8acd 100644 --- a/autogalaxy/profiles/mass/dark/nfw_virial_mass_conc.py +++ b/autogalaxy/profiles/mass/dark/nfw_virial_mass_conc.py @@ -2,17 +2,16 @@ from autogalaxy.profiles.mass.dark.nfw import NFWSph -from astropy import units - import numpy as np -import warnings - -from autogalaxy.cosmology.wrap import Planck15 def kappa_s_and_scale_radius( virial_mass, concentration, virial_overdens, redshift_object, redshift_source ): + + from astropy import units + from autogalaxy.cosmology.wrap import Planck15 + cosmology = Planck15() cosmic_average_density = ( diff --git a/autogalaxy/profiles/mass/point/smbh.py b/autogalaxy/profiles/mass/point/smbh.py index 0a92246bb..40fc054ec 100644 --- a/autogalaxy/profiles/mass/point/smbh.py +++ b/autogalaxy/profiles/mass/point/smbh.py @@ -1,7 +1,6 @@ import numpy as np from typing import Tuple -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.profiles.mass.point.point import PointMass @@ -30,11 +29,12 @@ def __init__( redshift_source The redshift of the source galaxy, which is used to convert the mass of the SMBH to an Einstein radius. """ - - self.mass = mass + from autogalaxy.cosmology.wrap import Planck15 cosmology = Planck15() + self.mass = mass + critical_surface_density = ( cosmology.critical_surface_density_between_redshifts_from( redshift_0=redshift_object, diff --git a/autogalaxy/profiles/mass/stellar/gaussian.py b/autogalaxy/profiles/mass/stellar/gaussian.py index ac2d267c5..433ebbba1 100644 --- a/autogalaxy/profiles/mass/stellar/gaussian.py +++ b/autogalaxy/profiles/mass/stellar/gaussian.py @@ -1,11 +1,9 @@ -import copy import numpy as np from autofit.jax_wrapper import use_jax if use_jax: import jax -from scipy.special import wofz -from scipy.integrate import quad + from typing import Tuple import autoarray as aa @@ -102,6 +100,7 @@ def deflections_2d_via_integral_from(self, grid: aa.type.Grid2DLike, **kwargs): Note: sigma is divided by sqrt(q) here. """ + from scipy.integrate import quad def calculate_deflection_component(npow, index): deflection_grid = np.array(self.axis_ratio * grid.array[:, index]) @@ -195,6 +194,9 @@ def axis_ratio(self): return axis_ratio if axis_ratio < 0.9999 else 0.9999 def zeta_from(self, grid: aa.type.Grid2DLike): + + from scipy.special import wofz + q2 = self.axis_ratio**2.0 ind_pos_y = grid.array[:, 0] >= 0 shape_grid = np.shape(grid) diff --git a/autogalaxy/profiles/mass/stellar/sersic.py b/autogalaxy/profiles/mass/stellar/sersic.py index adafa0dc1..093f8d68c 100644 --- a/autogalaxy/profiles/mass/stellar/sersic.py +++ b/autogalaxy/profiles/mass/stellar/sersic.py @@ -1,6 +1,5 @@ import numpy as np -from scipy.integrate import quad from typing import List, Tuple import autoarray as aa @@ -384,6 +383,7 @@ def deflections_2d_via_integral_from(self, grid: aa.type.Grid2DLike, **kwargs): The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ + from scipy.integrate import quad def calculate_deflection_component(npow, index): sersic_constant = self.sersic_constant diff --git a/autogalaxy/profiles/mass/stellar/sersic_gradient.py b/autogalaxy/profiles/mass/stellar/sersic_gradient.py index 9a5b9de97..92c07fd0d 100644 --- a/autogalaxy/profiles/mass/stellar/sersic_gradient.py +++ b/autogalaxy/profiles/mass/stellar/sersic_gradient.py @@ -1,5 +1,4 @@ import numpy as np -from scipy.integrate import quad from typing import List, Tuple import autoarray as aa @@ -62,12 +61,12 @@ def deflections_2d_via_integral_from(self, grid: aa.type.Grid2DLike, **kwargs): The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ + from scipy.integrate import quad def calculate_deflection_component(npow, index): sersic_constant = self.sersic_constant - deflection_grid = self.axis_ratio * grid[:, index] - deflection_grid = np.array(deflection_grid.array) + deflection_grid = np.array(self.axis_ratio * grid.array[:, index]) for i in range(grid.shape[0]): deflection_grid[i] *= ( diff --git a/autogalaxy/profiles/mass/total/power_law_core.py b/autogalaxy/profiles/mass/total/power_law_core.py index a46a02a7c..c07a44eca 100644 --- a/autogalaxy/profiles/mass/total/power_law_core.py +++ b/autogalaxy/profiles/mass/total/power_law_core.py @@ -1,6 +1,5 @@ import jax.numpy as jnp import numpy as np -from scipy.integrate import quad from typing import Tuple import autoarray as aa @@ -86,6 +85,7 @@ def potential_2d_from(self, grid: aa.type.Grid2DLike, **kwargs): grid The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ + from scipy.integrate import quad potential_grid = np.zeros(grid.shape[0]) @@ -117,6 +117,7 @@ def deflections_yx_2d_from(self, grid: aa.type.Grid2DLike, **kwargs): The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ + from scipy.integrate import quad def calculate_deflection_component(npow, index): einstein_radius_rescaled = self.einstein_radius_rescaled diff --git a/autogalaxy/profiles/mass/total/power_law_multipole.py b/autogalaxy/profiles/mass/total/power_law_multipole.py index a44c75626..16e5a2a88 100644 --- a/autogalaxy/profiles/mass/total/power_law_multipole.py +++ b/autogalaxy/profiles/mass/total/power_law_multipole.py @@ -1,4 +1,3 @@ -from astropy import units import jax.numpy as jnp import numpy as np from typing import Tuple @@ -114,6 +113,8 @@ def __init__( grid=grid ) """ + from astropy import units + super().__init__(centre=centre, ell_comps=(0.0, 0.0)) self.m = int(m) diff --git a/autogalaxy/profiles/plot/basis_plotters.py b/autogalaxy/profiles/plot/basis_plotters.py index 1cbdd763e..c304aea85 100644 --- a/autogalaxy/profiles/plot/basis_plotters.py +++ b/autogalaxy/profiles/plot/basis_plotters.py @@ -21,12 +21,12 @@ def __init__( self, basis: Basis, grid: aa.type.Grid1D2DLike, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): """ Plots the attributes of `Basis` objects using the matplotlib methods `plot()` and `imshow()` and many diff --git a/autogalaxy/profiles/plot/light_profile_plotters.py b/autogalaxy/profiles/plot/light_profile_plotters.py index f4d37f8f8..45388e275 100644 --- a/autogalaxy/profiles/plot/light_profile_plotters.py +++ b/autogalaxy/profiles/plot/light_profile_plotters.py @@ -23,12 +23,12 @@ def __init__( self, light_profile: LightProfile, grid: aa.type.Grid1D2DLike, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): """ Plots the attributes of `LightProfile` objects using the matplotlib methods `plot()` and `imshow()` and many @@ -156,12 +156,12 @@ def __init__( self, light_profile_pdf_list: List[LightProfile], grid: aa.type.Grid2DLike, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, sigma: Optional[float] = 3.0, ): """ diff --git a/autogalaxy/profiles/plot/mass_profile_plotters.py b/autogalaxy/profiles/plot/mass_profile_plotters.py index c7b7527a4..248977955 100644 --- a/autogalaxy/profiles/plot/mass_profile_plotters.py +++ b/autogalaxy/profiles/plot/mass_profile_plotters.py @@ -22,12 +22,12 @@ def __init__( self, mass_profile: MassProfile, grid: aa.type.Grid2DLike, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): """ Plots the attributes of `MassProfile` objects using the matplotlib methods `plot()` and `imshow()` and many @@ -152,12 +152,12 @@ def __init__( self, mass_profile_pdf_list: List[MassProfile], grid: aa.Grid2D, - mat_plot_1d: MatPlot1D = MatPlot1D(), - visuals_1d: Visuals1D = Visuals1D(), - include_1d: Include1D = Include1D(), - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_1d: MatPlot1D = None, + visuals_1d: Visuals1D = None, + include_1d: Include1D = None, + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, sigma: Optional[float] = 3.0, ): """ diff --git a/autogalaxy/quantity/model/analysis.py b/autogalaxy/quantity/model/analysis.py index 45cd49be8..48621ba26 100644 --- a/autogalaxy/quantity/model/analysis.py +++ b/autogalaxy/quantity/model/analysis.py @@ -1,18 +1,14 @@ from autoconf.dictable import to_dict -from autoconf.fitsable import hdu_list_for_output_from import autofit as af from autogalaxy.analysis.analysis.analysis import Analysis from autogalaxy.cosmology.lensing import LensingCosmology -from autogalaxy.cosmology.wrap import Planck15 from autogalaxy.quantity.dataset_quantity import DatasetQuantity from autogalaxy.quantity.model.result import ResultQuantity from autogalaxy.quantity.model.visualizer import VisualizerQuantity from autogalaxy.quantity.fit_quantity import FitQuantity -from autogalaxy import exc - class AnalysisQuantity(Analysis): Result = ResultQuantity @@ -22,7 +18,7 @@ def __init__( self, dataset: DatasetQuantity, func_str: str, - cosmology: LensingCosmology = Planck15(), + cosmology: LensingCosmology = None, title_prefix: str = None, ): """ diff --git a/autogalaxy/quantity/model/plotter_interface.py b/autogalaxy/quantity/model/plotter_interface.py index d15741191..91e72f83f 100644 --- a/autogalaxy/quantity/model/plotter_interface.py +++ b/autogalaxy/quantity/model/plotter_interface.py @@ -51,7 +51,7 @@ def dataset_quantity(self, dataset: DatasetQuantity): def fit_quantity( self, fit: FitQuantity, - visuals_2d: Visuals2D = Visuals2D(), + visuals_2d: Visuals2D = None, fit_quanaity_plotter_cls=FitQuantityPlotter, ): """ diff --git a/autogalaxy/quantity/plot/fit_quantity_plotters.py b/autogalaxy/quantity/plot/fit_quantity_plotters.py index 83632cb2c..07f449471 100644 --- a/autogalaxy/quantity/plot/fit_quantity_plotters.py +++ b/autogalaxy/quantity/plot/fit_quantity_plotters.py @@ -17,9 +17,9 @@ class FitQuantityPlotter(Plotter): def __init__( self, fit: FitQuantity, - mat_plot_2d: MatPlot2D = MatPlot2D(), - visuals_2d: Visuals2D = Visuals2D(), - include_2d: Include2D = Include2D(), + mat_plot_2d: MatPlot2D = None, + visuals_2d: Visuals2D = None, + include_2d: Include2D = None, ): """ Plots the attributes of `FitQuantity` objects using the matplotlib method `imshow()` and many diff --git a/autogalaxy/util/mock/mock_cosmology.py b/autogalaxy/util/mock/mock_cosmology.py index 858bdc111..d41f918fb 100644 --- a/autogalaxy/util/mock/mock_cosmology.py +++ b/autogalaxy/util/mock/mock_cosmology.py @@ -1,8 +1,5 @@ -from astropy import constants import math -from autogalaxy.cosmology.wrap import Planck15 - # Mock Cosmology # @@ -14,7 +11,7 @@ def to(self, *args, **kwargs): return Value(value=self.value) -class MockCosmology(Planck15): +class MockCosmology: def __init__( self, arcsec_per_kpc=0.5, @@ -22,7 +19,6 @@ def __init__( critical_surface_density=2.0, cosmic_average_density=2.0, ): - super().__init__() self.arcsec_per_kpc = arcsec_per_kpc self.kpc_per_arcsec = kpc_per_arcsec @@ -39,6 +35,8 @@ def angular_diameter_distance(self, z): return Value(value=1.0) def angular_diameter_distance_z1z2(self, z1, z2): + from astropy import constants + const = constants.c.to("kpc / s") ** 2.0 / ( 4 * math.pi * constants.G.to("kpc3 / (solMass s2)") ) @@ -46,3 +44,137 @@ def angular_diameter_distance_z1z2(self, z1, z2): def critical_density(self, z): return Value(value=self.cosmic_average_density) + + def cosmic_average_density_solar_mass_per_kpc3_from(self, redshift: float) -> float: + """ + Critical density of the Universe at an input `redshift` in units of solar masses per kiloparsecs**3. + + For simplicity, **PyAutoLens** internally uses only certain units to perform lensing cosmology calculations. + This function therefore returns only the value of the astropy function it wraps, omitting the units instance. + + Parameters + ---------- + redshift + Redshift at which the critiical density in solMass/kpc^3 of the Universe is calculated. + """ + cosmic_average_density_kpc = ( + self.critical_density(z=redshift).to("solMass / kpc^3").value + ) + + return cosmic_average_density_kpc + + def critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( + self, redshift_0: float, redshift_1: float + ) -> float: + """ + The critical surface density for lensing, often written as $\sigma_{cr}$, is given by: + + critical_surface_density = (c^2 * D_s) / (4 * pi * G * D_ls * D_l) + + c = speed of light + G = Newton's gravity constant + D_s = Angular diameter distance of source redshift to earth + D_ls = Angular diameter distance of lens redshift to source redshift + D_l = Angular diameter distance of lens redshift to earth + + This function returns the critical surface density in units of solar masses / kpc^2, which are convenient + units for converting the inferred masses of a model from angular units (e.g. dimensionless units inferred + from data in arcseconds) to solar masses. + + Parameters + ---------- + redshift_0 + The redshift of the first strong lens galaxy (E.g. the lens galaxy) for which the critical surface + density is calculated. + redshift_1 + The redshift of the second strong lens galaxy (E.g. the lens galaxy) for which the critical surface + density is calculated. + """ + from astropy import constants + + const = constants.c.to("kpc / s") ** 2.0 / ( + 4 * math.pi * constants.G.to("kpc3 / (solMass s2)") + ) + + angular_diameter_distance_of_redshift_0_to_earth_kpc = ( + self.angular_diameter_distance_to_earth_in_kpc_from(redshift=redshift_0) + ) + + angular_diameter_distance_of_redshift_1_to_earth_kpc = ( + self.angular_diameter_distance_to_earth_in_kpc_from(redshift=redshift_1) + ) + + angular_diameter_distance_between_redshifts_kpc = ( + self.angular_diameter_distance_between_redshifts_in_kpc_from( + redshift_0=redshift_0, redshift_1=redshift_1 + ) + ) + + return ( + const + * angular_diameter_distance_of_redshift_1_to_earth_kpc + / ( + angular_diameter_distance_between_redshifts_kpc + * angular_diameter_distance_of_redshift_0_to_earth_kpc + ) + ).value + + def angular_diameter_distance_to_earth_in_kpc_from(self, redshift: float) -> float: + """ + Angular diameter distance from the input `redshift` to redshift zero (e.g. us, the observer on earth) in + kiloparsecs. + + This gives the proper (sometimes called 'physical') transverse distance corresponding to an angle of 1 radian + for an object at redshift `z`. + + Weinberg, 1972, pp 421-424; Weedman, 1986, pp 65-67; Peebles, 1993, pp 325-327. + + For simplicity, **PyAutoLens** internally uses only certain units to perform lensing cosmology calculations. + This function therefore returns only the value of the astropy function it wraps, omitting the units instance. + + Parameters + ---------- + redshift + Input redshift from which the angular diameter distance to Earth is calculated. + """ + angular_diameter_distance_kpc = self.angular_diameter_distance(z=redshift).to( + "kpc" + ) + + return angular_diameter_distance_kpc.value + + def angular_diameter_distance_between_redshifts_in_kpc_from( + self, redshift_0: float, redshift_1: float + ) -> float: + """ + Angular diameter distance from an input `redshift_0` to another input `redshift_1`. + + For simplicity, **PyAutoLens** internally uses only certain units to perform lensing cosmology calculations. + This function therefore returns only the value of the astropy function it wraps, omitting the units instance. + + Parameters + ---------- + redshift_0 + Redshift from which the angular diameter distance to the other redshift is calculated. + redshift_1 + Redshift from which the angular diameter distance to the other redshift is calculated. + """ + angular_diameter_distance_between_redshifts_kpc = ( + self.angular_diameter_distance_z1z2(redshift_0, redshift_1).to("kpc") + ) + + return angular_diameter_distance_between_redshifts_kpc.value + + def kpc_per_arcsec_from(self, redshift: float) -> float: + """ + Separation in transverse proper kpc corresponding to an arcminute at redshift `z`. + + For simplicity, **PyAutoLens** internally uses only certain units to perform lensing cosmology calculations. + This function therefore returns only the value of the astropy function it wraps, omitting the units instance. + + Parameters + ---------- + redshift + Input redshift from which the transverse proper kpc value is calculated at. + """ + return 1.0 / self.arcsec_per_kpc_proper(z=redshift).value diff --git a/autogalaxy/util/shear_field.py b/autogalaxy/util/shear_field.py index 179e8f09a..d77d5b1ea 100644 --- a/autogalaxy/util/shear_field.py +++ b/autogalaxy/util/shear_field.py @@ -1,5 +1,4 @@ import logging -from matplotlib.patches import Ellipse import numpy as np import typing @@ -47,11 +46,12 @@ def phis(self) -> aa.ArrayIrregular: ) @property - def elliptical_patches(self) -> typing.List[Ellipse]: + def elliptical_patches(self) -> "typing.List[Ellipse]": """ If we treat this vector field as a set of weak lensing shear measurements, the elliptical patch representing each galaxy ellipticity. This patch is used for visualizing an ellipse of each galaxy in an image. """ + from matplotlib.patches import Ellipse return [ Ellipse( diff --git a/test_autogalaxy/conftest.py b/test_autogalaxy/conftest.py index 7e20c8ee3..4be353fba 100644 --- a/test_autogalaxy/conftest.py +++ b/test_autogalaxy/conftest.py @@ -1,3 +1,9 @@ +import jax.numpy as jnp + +def pytest_configure(): + _ = jnp.sum(jnp.array([0.0])) # Force backend init + + import os from os import path diff --git a/test_autogalaxy/cosmology/test_model.py b/test_autogalaxy/cosmology/test_model.py index ae8e9564e..8154a82da 100644 --- a/test_autogalaxy/cosmology/test_model.py +++ b/test_autogalaxy/cosmology/test_model.py @@ -1,10 +1,11 @@ import pytest -import autogalaxy as ag - def test__cosmology(Planck15): - cosmology = ag.cosmo.FlatwCDMWrap() + + from autogalaxy.cosmology.model import FlatwCDMWrap + + cosmology = FlatwCDMWrap() critical_surface_density = ( cosmology.critical_surface_density_between_redshifts_from( @@ -14,7 +15,9 @@ def test__cosmology(Planck15): assert critical_surface_density == pytest.approx(17613991217.945473, 1.0e-4) - cosmology = ag.cosmo.FlatLambdaCDMWrap() + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap() critical_surface_density = ( cosmology.critical_surface_density_between_redshifts_from( diff --git a/test_autogalaxy/profiles/mass/dark/test_abstract.py b/test_autogalaxy/profiles/mass/dark/test_abstract.py index 6a4670ef0..e3cfecc2f 100644 --- a/test_autogalaxy/profiles/mass/dark/test_abstract.py +++ b/test_autogalaxy/profiles/mass/dark/test_abstract.py @@ -267,7 +267,10 @@ def test__mass_at_200__unit_conversions_work(): def test__values_of_quantities_for_real_cosmology(): - cosmology = ag.cosmo.LambdaCDMWrap(H0=70.0, Om0=0.3, Ode0=0.7) + + from autogalaxy.cosmology.model import LambdaCDMWrap + + cosmology = LambdaCDMWrap(H0=70.0, Om0=0.3, Ode0=0.7) mp = ag.mp.NFWTruncatedSph(kappa_s=0.5, scale_radius=5.0, truncation_radius=10.0) diff --git a/test_autogalaxy/profiles/mass/dark/test_nfw_mcr.py b/test_autogalaxy/profiles/mass/dark/test_nfw_mcr.py index 18d8b0543..7d8465412 100644 --- a/test_autogalaxy/profiles/mass/dark/test_nfw_mcr.py +++ b/test_autogalaxy/profiles/mass/dark/test_nfw_mcr.py @@ -1,4 +1,3 @@ -import numpy as np import pytest import autogalaxy as ag @@ -7,7 +6,10 @@ def test__mass_and_concentration_consistent_with_normal_nfw(): - cosmology = ag.cosmo.FlatLambdaCDMWrap(H0=70.0, Om0=0.3) + + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap(H0=70.0, Om0=0.3) mp = ag.mp.NFWMCRDuffySph( centre=(1.0, 2.0), @@ -53,7 +55,10 @@ def test__mass_and_concentration_consistent_with_normal_nfw(): def test__mass_and_concentration_consistent_with_normal_nfw__scatter_0(): - cosmology = ag.cosmo.FlatLambdaCDMWrap(H0=70.0, Om0=0.3) + + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap(H0=70.0, Om0=0.3) mp = ag.mp.NFWMCRLudlowSph( centre=(1.0, 2.0), @@ -100,7 +105,10 @@ def test__mass_and_concentration_consistent_with_normal_nfw__scatter_0(): def test__same_as_above_but_elliptical(): - cosmology = ag.cosmo.FlatLambdaCDMWrap(H0=70.0, Om0=0.3) + + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap(H0=70.0, Om0=0.3) mp = ag.mp.NFWMCRLudlow( centre=(1.0, 2.0), @@ -153,7 +161,10 @@ def test__same_as_above_but_elliptical(): def test__same_as_above_but_generalized_elliptical(): - cosmology = ag.cosmo.FlatLambdaCDMWrap(H0=70.0, Om0=0.3) + + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap(H0=70.0, Om0=0.3) mp = ag.mp.gNFWMCRLudlow( centre=(1.0, 2.0), diff --git a/test_autogalaxy/profiles/mass/dark/test_nfw_truncated_mcr.py b/test_autogalaxy/profiles/mass/dark/test_nfw_truncated_mcr.py index b47f504ad..64adf18fb 100644 --- a/test_autogalaxy/profiles/mass/dark/test_nfw_truncated_mcr.py +++ b/test_autogalaxy/profiles/mass/dark/test_nfw_truncated_mcr.py @@ -7,7 +7,10 @@ def test__duffy__mass_and_concentration_consistent_with_normal_truncated_nfw(): - cosmology = ag.cosmo.FlatLambdaCDMWrap(H0=70.0, Om0=0.3) + + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap(H0=70.0, Om0=0.3) mp = ag.mp.NFWTruncatedMCRDuffySph( centre=(1.0, 2.0), @@ -51,7 +54,10 @@ def test__duffy__mass_and_concentration_consistent_with_normal_truncated_nfw(): def test__ludlow__mass_and_concentration_consistent_with_normal_truncated_nfw__scatter_0(): - cosmology = ag.cosmo.FlatLambdaCDMWrap(H0=70.0, Om0=0.3) + + from autogalaxy.cosmology.model import FlatLambdaCDMWrap + + cosmology = FlatLambdaCDMWrap(H0=70.0, Om0=0.3) mp = ag.mp.NFWTruncatedMCRLudlowSph( centre=(1.0, 2.0), diff --git a/test_autogalaxy/profiles/mass/sheets/test_decorators.py b/test_autogalaxy/profiles/mass/sheets/test_decorators.py deleted file mode 100644 index c79027a81..000000000 --- a/test_autogalaxy/profiles/mass/sheets/test_decorators.py +++ /dev/null @@ -1,32 +0,0 @@ -import autogalaxy as ag -import numpy as np - -grid = ag.Grid2DIrregular([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [2.0, 4.0]]) - - -def test__mass_quantity_functions__output_is_autoarray_structure(): - grid = ag.Grid2D.uniform(shape_native=(2, 2), pixel_scales=1.0) - - mass_sheet = ag.mp.MassSheet() - - convergence = mass_sheet.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = mass_sheet.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = mass_sheet.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - shear = ag.mp.ExternalShear() - - convergence = shear.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = shear.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = shear.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) diff --git a/test_autogalaxy/profiles/mass/total/test_decorators.py b/test_autogalaxy/profiles/mass/total/test_decorators.py deleted file mode 100644 index 091ed1158..000000000 --- a/test_autogalaxy/profiles/mass/total/test_decorators.py +++ /dev/null @@ -1,127 +0,0 @@ -import numpy as np - -import autogalaxy as ag - -grid = ag.Grid2DIrregular([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [2.0, 4.0]]) - - -def test__mass_quantity_functions__output_is_autoarray_structure(): - grid = ag.Grid2D.uniform(shape_native=(2, 2), pixel_scales=1.0) - - point_mass = ag.mp.PointMass() - deflections = point_mass.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - cored_power_law = ag.mp.PowerLawBroken() - - convergence = cored_power_law.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - deflections = cored_power_law.deflections_yx_2d_from(grid=grid) - assert deflections.shape_native == (2, 2) - - cored_power_law = ag.mp.PowerLawBrokenSph() - - convergence = cored_power_law.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - deflections = cored_power_law.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - cored_power_law = ag.mp.PowerLawCore() - - convergence = cored_power_law.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = cored_power_law.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = cored_power_law.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - cored_power_law = ag.mp.PowerLawCoreSph() - - convergence = cored_power_law.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = cored_power_law.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = cored_power_law.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - power_law = ag.mp.PowerLaw() - - convergence = power_law.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = power_law.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = power_law.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - power_law = ag.mp.PowerLawSph() - - convergence = power_law.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = power_law.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = power_law.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - cored_isothermal = ag.mp.IsothermalCore() - - convergence = cored_isothermal.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = cored_isothermal.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = cored_isothermal.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - cored_isothermal = ag.mp.IsothermalCoreSph() - - convergence = cored_isothermal.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = cored_isothermal.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = cored_isothermal.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - isothermal = ag.mp.Isothermal() - - convergence = isothermal.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = isothermal.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = isothermal.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) - - isothermal = ag.mp.IsothermalSph() - - convergence = isothermal.convergence_2d_from(grid=grid) - assert convergence.shape_native == (2, 2) - - potential = isothermal.potential_2d_from(grid=grid) - assert potential.shape_native == (2, 2) - - deflections = isothermal.deflections_yx_2d_from(grid=grid) - assert isinstance(deflections, ag.VectorYX2D) - assert deflections.shape_native == (2, 2) diff --git a/test_autogalaxy/profiles/mass/total/test_isothermal.py b/test_autogalaxy/profiles/mass/total/test_isothermal.py index 11b433292..21ca57d5c 100644 --- a/test_autogalaxy/profiles/mass/total/test_isothermal.py +++ b/test_autogalaxy/profiles/mass/total/test_isothermal.py @@ -148,28 +148,3 @@ def test__shear_yx_2d_from(): assert shear[0, 0] == pytest.approx(0.0, abs=1e-4) assert shear[0, 1] == pytest.approx(-1.11803398874, 1e-4) - - -def test__compare_to_cored_power_law(): - isothermal = ag.mp.Isothermal( - centre=(0.0, 0.0), ell_comps=(0.333333, 0.0), einstein_radius=1.0 - ) - cored_power_law = ag.mp.PowerLawCore( - centre=(0.0, 0.0), - ell_comps=(0.333333, 0.0), - einstein_radius=1.0, - core_radius=0.0, - ) - - assert isothermal.potential_2d_from(grid=grid) == pytest.approx( - cored_power_law.potential_2d_from(grid=grid).array, 1e-3 - ) - assert isothermal.potential_2d_from(grid=grid) == pytest.approx( - cored_power_law.potential_2d_from(grid=grid).array, 1e-3 - ) - assert isothermal.deflections_yx_2d_from(grid=grid) == pytest.approx( - cored_power_law.deflections_yx_2d_from(grid=grid).array, 1e-3 - ) - assert isothermal.deflections_yx_2d_from(grid=grid) == pytest.approx( - cored_power_law.deflections_yx_2d_from(grid=grid).array, 1e-3 - ) diff --git a/test_autogalaxy/profiles/mass/total/test_isothermal_cored.py b/test_autogalaxy/profiles/mass/total/test_isothermal_cored.py index eca702deb..88cb13e1e 100644 --- a/test_autogalaxy/profiles/mass/total/test_isothermal_cored.py +++ b/test_autogalaxy/profiles/mass/total/test_isothermal_cored.py @@ -207,33 +207,3 @@ def test__potential_2d_from(): assert elliptical.potential_2d_from(grid=grid) == pytest.approx( spherical.potential_2d_from(grid=grid).array, 1e-4 ) - - -def test__compare_to_cored_power_law(): - power_law = ag.mp.IsothermalCore( - centre=(0.0, 0.0), - ell_comps=(0.333333, 0.0), - einstein_radius=1.0, - core_radius=0.1, - ) - - cored_power_law = ag.mp.PowerLawCore( - centre=(0.0, 0.0), - ell_comps=(0.333333, 0.0), - einstein_radius=1.0, - slope=2.0, - core_radius=0.1, - ) - - assert power_law.potential_2d_from(grid=grid) == pytest.approx( - cored_power_law.potential_2d_from(grid=grid).array, 1e-3 - ) - assert power_law.potential_2d_from(grid=grid) == pytest.approx( - cored_power_law.potential_2d_from(grid=grid).array, 1e-3 - ) - assert power_law.deflections_yx_2d_from(grid=grid) == pytest.approx( - cored_power_law.deflections_yx_2d_from(grid=grid).array, 1e-3 - ) - assert power_law.deflections_yx_2d_from(grid=grid) == pytest.approx( - cored_power_law.deflections_yx_2d_from(grid=grid).array, 1e-3 - ) diff --git a/test_autogalaxy/profiles/mass/total/test_power_law.py b/test_autogalaxy/profiles/mass/total/test_power_law.py index 227451d5f..b78f9d335 100644 --- a/test_autogalaxy/profiles/mass/total/test_power_law.py +++ b/test_autogalaxy/profiles/mass/total/test_power_law.py @@ -192,33 +192,3 @@ def test__potential_2d_from(): assert elliptical.potential_2d_from(grid=grid) == pytest.approx( spherical.potential_2d_from(grid=grid).array, 1e-4 ) - - -def test__compare_to_cored_power_law(): - power_law = ag.mp.PowerLaw( - centre=(0.0, 0.0), - ell_comps=(0.333333, 0.0), - einstein_radius=1.0, - slope=2.3, - ) - - cored_power_law = ag.mp.PowerLawCore( - centre=(0.0, 0.0), - ell_comps=(0.333333, 0.0), - einstein_radius=1.0, - slope=2.3, - core_radius=0.0, - ) - - assert power_law.potential_2d_from(grid=grid) == pytest.approx( - cored_power_law.potential_2d_from(grid=grid).array, 1e-3 - ) - assert power_law.potential_2d_from(grid=grid) == pytest.approx( - cored_power_law.potential_2d_from(grid=grid).array, 1e-3 - ) - assert power_law.deflections_yx_2d_from(grid=grid) == pytest.approx( - cored_power_law.deflections_yx_2d_from(grid=grid).array, 1e-3 - ) - assert power_law.deflections_yx_2d_from(grid=grid) == pytest.approx( - cored_power_law.deflections_yx_2d_from(grid=grid).array, 1e-3 - )