### Python Setup with AstroPhot Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb This snippet sets up the AstroPhot environment by loading the autoreload extension, importing necessary libraries (os, astrophot, numpy, torch, astropy, matplotlib, time), and enabling inline plotting. It's a standard initialization for interactive AstroPhot sessions. ```python %load_ext autoreload %autoreload 2 import os import astrophot as ap import numpy as np import torch from astropy.io import fits from astropy.wcs import WCS import matplotlib.pyplot as plt from time import time %matplotlib inline ``` -------------------------------- ### Configure AstroPhot logging output Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Demonstrates how to control AstroPhot's logging output behavior. Shows examples of directing logs to file only, console only, or both simultaneously. Requires AstroPhot library import. No return values, configuration affects subsequent log messages. ```python # note that the log file will be where these tutorial notebooks are in your filesystem # Here we change the settings so AstroPhot only prints to a log file ap.AP_config.set_logging_output(stdout=False, filename="AstroPhot.log") ap.AP_config.ap_logger.info("message 1: this should only appear in the AstroPhot log file") # Here we change the settings so AstroPhot only prints to console ap.AP_config.set_logging_output(stdout=True, filename=None) ap.AP_config.ap_logger.info("message 2: this should only print to the console") # Here we change the settings so AstroPhot prints to both, which is the default ap.AP_config.set_logging_output(stdout=True, filename="AstroPhot.log") ap.AP_config.ap_logger.info("message 3: this should appear in both the console and the log file") ``` -------------------------------- ### Save and Load Target Image (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Demonstrates saving a target image to a FITS file and then loading it back into a `Target_Image` object. This process allows for persistence and reuse of observation data. ```python # Save and load a target image target.save("target.fits") new_target = ap.image.Target_Image(filename="target.fits") fig, ax = plt.subplots(figsize=(8, 8)) ap.plots.target_image(fig, ax, new_target) plt.show() ``` -------------------------------- ### Create AstroPhot Model (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb This snippet demonstrates creating an AstroPhot model object. It initializes the model with a unique name, model type, parameter values, and a target image. The model is then initialized to prepare it for fitting. ```python model1 = ap.models.AstroPhot_Model( name="model1", # every model must have a unique name model_type="sersic galaxy model", # this specifies the kind of model parameters= { "center": [50, 50], "q": 0.6, "PA": 60 * np.pi / 180, "n": 2, "Re": 10, "Ie": 1, }, # here we set initial values for each parameter target=ap.image.Target_Image( data=np.zeros((100, 100)), zeropoint=22.5, pixelscale=1.0 ), # every model needs a target, more on this later ) model1.initialize() # before using the model it is good practice to call initialize so the model can get itself ready # We can print the model's current state model1.parameters ``` -------------------------------- ### Load Model from File (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Loads a model configuration from a specified YAML file. The target image must still be provided separately. This enables reusing previously saved model structures. ```python # load a model from a file # note that the target still must be specified, only the parameters are saved model4 = ap.models.AstroPhot_Model(name="new name", filename="AstroPhot.yaml", target=target) print( model4 ) # can see that it has been constructed with all the same parameters as the saved model2. ``` -------------------------------- ### Create a Sersic Galaxy model directly with AstroPhot Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Shows how to instantiate a Sersic_Galaxy model by providing parameter values, a target image, and a specific PSF mode. Requires numpy and AstroPhot. The model object can be printed or further used in fitting workflows. ```Python model1_v2 = ap.models.Sersic_Galaxy( parameters={"center": [50, 50], "q": 0.6, "PA": 60 * np.pi / 180, "n": 2, "Re": 10, "Ie": 1}, target=ap.image.Target_Image(data=np.zeros((100, 100)), pixelscale=1), psf_mode="full", # only change is the psf_mode ) # This will be the same as model1, except note that the "psf_mode" keyword is now tracked since it isn't a default value print(model1_v2) ``` -------------------------------- ### Load Target Image (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb This snippet demonstrates loading an image from a URL using astropy.io.fits, converting it to a numpy array, and creating a Target_Image object with appropriate pixelscale and zeropoint. It also sets the variance to 'auto'. ```python hdu = fits.open( "https://www.legacysurvey.org/viewer/fits-cutout?ra=36.3684&dec=-25.6389&size=700&layer=ls-dr9&pixscale=0.262&bands=r" ) target_data = np.array(hdu[0].data, dtype=np.float64) # Create a target object with specified pixelscale and zeropoint target = ap.image.Target_Image( data=target_data, pixelscale=0.262, # Every target image needs to know it’s pixelscale in arcsec/pixel zeropoint=22.5, # optionally, you can give a zeropoint to tell AstroPhot what the pixel flux units are variance="auto", # Automatic variance estimate for testing and demo purposes, in real analysis use weight maps, counts, gain, etc to compute variance! ) # The default AstroPhot target plotting method uses log scaling in bright areas and histogram scaling in faint areas fig3, ax3 = plt.subplots(figsize=(8, 8)) ap.plots.target_image(fig3, ax3, target) plt.show() ``` -------------------------------- ### Plot AstroPhot Model Image (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb This snippet uses AstroPhot's plotting functionality to display the initial model image. It sets up a matplotlib figure and axes and then calls ap.plots.model_image to generate the plot. ```python fig, ax = plt.subplots(figsize=(8, 7)) ap.plots.model_image(fig, ax, model1) plt.show() ``` -------------------------------- ### Save Model Image to File (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Generates a model image based on the current model parameters and saves it to a FITS file. The saved image can then be loaded and displayed, for example, using matplotlib. ```python # Save the model image to a file model_image_sample = model2() model_image_sample.save("model2.fits") saved_image_hdu = fits.open("model2.fits") fig, ax = plt.subplots(figsize=(8, 8)) ax.imshow( np.log10(saved_image_hdu[0].data), origin="lower", cmap="plasma", ) plt.show() ``` -------------------------------- ### Force AstroPhot to use CPU instead of GPU Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Explicitly sets AstroPhot's device to CPU, which must be done before creating any models, images, or other objects that depend on the global device setting. ```Python ap.AP_config.ap_device = "cpu" # BEFORE creating anything else (models, images, etc.) ``` -------------------------------- ### Load target image with WCS information using AstroPhot Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Downloads a FITS cutout, extracts the image data and WCS header, creates an AstroPhot Target_Image object with appropriate metadata, and visualizes it. Requires astropy, numpy, matplotlib, and AstroPhot. Input is a URL; output is a displayed figure. ```Python hdu = fits.open( "https://www.legacysurvey.org/viewer/fits-cutout?ra=36.3684&dec=-25.6389&size=700&layer=ls-dr9&pixscale=0.262&bands=r" ) target_data = np.array(hdu[0].data, dtype=np.float64) wcs = WCS(hdu[0].header) # Create a target object with WCS which will specify the pixelscale and origin for us! target = ap.image.Target_Image( data=target_data, zeropoint=22.5, wcs=wcs, ) fig3, ax3 = plt.subplots(figsize=(8, 8)) ap.plots.target_image( fig3, ax3, target, flipx=True ) # note we flip the x-axis since RA coordinates are backwards plt.show() ``` -------------------------------- ### Fit AstroPhot Model to Target (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb This snippet demonstrates fitting an AstroPhot model to a loaded target image using the Levenberg-Marquardt (LM) algorithm. It initializes a model with the target image and then calls ap.fit.LM to perform the fitting. The fit message is printed to indicate convergence. ```python model2 = ap.models.AstroPhot_Model( name="model with target", model_type="sersic galaxy model", # feel free to swap out sersic with other profile types target=target, # now the model knows what its trying to match ) # Instead of giving initial values for all the parameters, it is possible to simply call "initialize" and AstroPhot # will try to guess initial values for every parameter assuming the galaxy is roughly centered. It is also possible # to set just a few parameters and let AstroPhot try to figure out the rest. For example you could give it an initial # Guess for the center and it will work from there. model2.initialize() # Plotting the initial parameters and residuals, we see it gets the rough shape of the galaxy right, but still has some fitting to do fig4, ax4 = plt.subplots(1, 2, figsize=(16, 6)) ap.plots.model_image(fig4, ax4[0], model2) ap.plots.residual_image(fig4, ax4[1], model2) plt.show() # Now that the model has been set up with a target and initialized with parameter values, it is time to fit the image result = ap.fit.LM(model2, verbose=1).fit() # See that we use ap.fit.LM, this is the Levenberg-Marquardt Chi^2 minimization method, it is the recommended technique # for most least-squares problems. However, there are situations in which different optimizers may be more desirable # so the ap.fit package includes a few options to pick from. The various fitting methods will be described in a # different tutorial. print("Fit message:", result.message) # the fitter will return a message about its convergence ``` -------------------------------- ### Save Model to File (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Saves the current state of a model to a YAML file. The file contains the model's parameters, allowing it to be reloaded later. Defaults to saving as 'AstroPhot.yaml'. ```python # Save the model to a file model2.save() # will default to save as AstroPhot.yaml with open("AstroPhot.yaml", "r") as f: print(f.read()) # show what the saved file looks like ``` -------------------------------- ### Inspect Model Parameter Order (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Prints the 'parameter_order' tuples for two models. This helps understand the sequence in which parameters are stored and accessed, which is crucial for manual parameter manipulation. ```python # Keep in mind that both models have full control over the parameter, it is listed in both of # their "parameter_order" tuples. print("model_1 parameters: ", model_1.parameter_order) print("model_2 parameters: ", model_2.parameter_order) ``` -------------------------------- ### Define Model with Target Window and Fit Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Defines an astronomical model (e.g., Sersic galaxy model) focused on a specific region of an image ('target window'). A unique name is automatically generated if not provided. The code then initializes the model and performs a fit using the `ap.fit.LM` optimizer. ```python # note, we don't provide a name here. A unique name will automatically be generated using the model type model3 = ap.models.AstroPhot_Model( model_type="sersic galaxy model", target=target, window=[ [480, 595], [555, 665], ], # this is a region in pixel coordinates ((xmin,xmax),(ymin,ymax)) ) print(f"automatically generated name: '{model3.name}'") # We can plot the "model window" to show us what part of the image will be analyzed by that model fig6, ax6 = plt.subplots(figsize=(8, 8)) ap.plots.target_image(fig6, ax6, model3.target) ap.plots.model_window(fig6, ax6, model3)plt.show() ``` ```python model3.initialize() result = ap.fit.LM(model3, verbose=1).fit() print(result.message) ``` -------------------------------- ### List available AstroPhot model names Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Retrieves and prints all registered AstroPhot model class names, optionally filtering for usable models or sub‑models of a specific type. Useful for discovering built‑in and user‑added models. ```Python print( ap.models.AstroPhot_Model.List_Model_Names(usable=True) ) # set usable = None for all models, or usable = False for only base classes print("---------------------------") # It is also possible to get all sub models of a specific Type print("only warp models: ", ap.models.Warp_Galaxy.List_Model_Names()) ``` -------------------------------- ### Manually Set Model Parameter Values (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Shows how to manually update all parameters of a model using a tensor of new values. It requires initializing the model and then using `vector_set_values`. The process includes plotting the model before and after the update. ```python # Give the model new parameter values manually print( "parameter input order: ", model4.parameter_order ) # use this to see what order you have to give the parameters as input # plot the old model fig9, ax9 = plt.subplots(1, 2, figsize=(16, 6)) ap.plots.model_image(fig9, ax9[0], model4) T = ax9[0].set_title("parameters as loaded") # update and plot the new parameters new_parameters = torch.tensor( [75, 110, 0.4, 20 * np.pi / 180, 3, 25, 0.12] ) # note that the center parameter needs two values as input model4.initialize() # initialize must be called before optimization, or any other activity in which parameters are updated model4.parameters.vector_set_values( new_parameters ) # full_sample will update the parameters, then run sample and return the model image ap.plots.model_image(fig9, ax9[1], model4) T = ax9[1].set_title("new parameter values") ``` -------------------------------- ### Switch AstroPhot precision to float32 for GPU acceleration Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Changes the global data type to single‑precision (float32) to improve GPU memory usage and speed, demonstrates the effect on newly created Window objects, and then reverts back to double‑precision (float64). ```Python # Again do this BEFORE creating anything else ap.AP_config.ap_dtype = torch.float32 # Now new AstroPhot objects will be made with single bit precision W1 = ap.image.Window(origin=[0, 0], pixel_shape=[1, 1], pixelscale=1) print("now a single:", W1.origin.dtype) # Here we switch back to double precision ap.AP_config.ap_dtype = torch.float64 W2 = ap.image.Window(origin=[0, 0], pixel_shape=[1, 1], pixelscale=1) print("back to double:", W2.origin.dtype) print("old window is still single:", W1.origin.dtype) ``` -------------------------------- ### Load AstroPhot libraries and enable autoreload Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/BasicPSFModels.ipynb Imports the AstroPhot library along with supporting packages and activates the IPython autoreload extension for automatic module reloading. This setup is required before using AstroPhot functionalities in a notebook environment. ```python %load_ext autoreload\n%autoreload 2\n\nimport astrophot as ap\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\n\n%matplotlib inline ``` -------------------------------- ### Import AstroPhot and Libraries Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/AdvancedPSFModels.ipynb Imports necessary libraries for AstroPhot, numerical operations, PyTorch, FITS file handling, and plotting. This setup is standard for most AstroPhot analyses. ```python import astrophot as ap import numpy as np import torch from astropy.io import fits import matplotlib.pyplot as plt %matplotlib inline ``` -------------------------------- ### Bulge-Disk Decomposition Setup Source: https://context7.com/autostronomy/astrophot/llms.txt Sets up a target image and a sky background model for bulge-disk decomposition. The target image includes data, variance, pixel scale, and PSF information. A flat sky model is defined, which will be used in conjunction with other components to model the galaxy's structure. ```python import astrophot as ap # Create target image target = ap.image.Target_Image( data=image_data, variance=variance_map, pixelscale=0.262, psf=psf_data ) # Define sky background sky = ap.models.AstroPhot_Model( name="sky", model_type="flat sky model", target=target ) ``` -------------------------------- ### Visualize AstroPhot Group Model Initialization Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GroupModels.ipynb Plots the target image and the initialized group model, showing the fitting windows for sub-models and the overall model image with auto-initialized parameters. This helps in verifying the initial setup before fitting. ```python fig, ax = plt.subplots(1, 2, figsize=(18, 8)) ap.plots.target_image(fig, ax[0], groupmodel.target) ap.plots.model_window(fig, ax[0], groupmodel) ax[0].set_title("Sub model fitting windows") ap.plots.model_image(fig, ax[1], groupmodel) ax[1].set_title("auto initialized parameters") plt.show() ``` -------------------------------- ### Constrain Model Parameters (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Defines an AstroPhot_Model with specific limits and a locked value for the PA parameter. This is useful for fixing certain parameters during model fitting. ```python constrained_param_model = ap.models.AstroPhot_Model( name="constrained parameters", model_type="sersic galaxy model", parameters={ "q": {"limits": [0.4, 0.6]}, "n": {"limits": [2, 3]}, "PA": {"value": 60 * np.pi / 180, "locked": True}, }, ) ``` -------------------------------- ### Check if AstroPhot detected a CUDA GPU Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Prints the device configuration detected by AstroPhot, indicating whether a CUDA‑enabled GPU is available or if computation will fall back to the CPU. ```Python print(ap.AP_config.ap_device) # most likely this will say "cpu" unless you already have a cuda GPU, # in which case it should say "cuda:0" ``` -------------------------------- ### Instantiate and Initialize Custom AstroPhot Model (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/CustomModels.ipynb This Python code demonstrates how to instantiate the custom 'My_Super_Sersic' model and then call its 'initialize' method. It also includes plotting the initial model and residual images before fitting, and then fitting the model using the Levenberg-Marquardt algorithm. ```python my_super_model = My_Super_Sersic( # notice we switched the custom class name="goodness I made another one", target=target, ) # no longer need to provide initial values! my_super_model.initialize() # The starting point for this model is still not very good, lets see what the optimizer can do! fig, ax = plt.subplots(1, 2, figsize=(16, 7)) ap.plots.model_image(fig, ax[0], my_super_model) ap.plots.residual_image(fig, ax[1], my_super_model) plt.show() ``` ```python # We made a "good" initializer so this should be faster to optimize result = ap.fit.LM(my_super_model, verbose=1).fit() print(result.message) ``` ```python fig, ax = plt.subplots(1, 2, figsize=(16, 7)) ap.plots.model_image(fig, ax[0], my_super_model) ap.plots.residual_image(fig, ax[1], my_super_model) plt.show() ``` -------------------------------- ### Python: Basic Image Creation and Model Fitting Source: https://context7.com/autostronomy/astrophot/llms.txt Demonstrates loading observational data, creating a target image, defining a Sersic galaxy model, auto-initializing parameters, and fitting using the Levenberg-Marquardt optimizer. ```Python import astrophot as ap import numpy as np from astropy.io import fits from astropy.wcs import WCS # Load observational data hdu = fits.open('galaxy_image.fits') image_data = hdu[0].data wcs = WCS(hdu[0].header) variance_map = hdu[1].data # Variance extension psf_data = fits.getdata('psf.fits') # Create target image with all necessary components target = ap.image.Target_Image( data=image_data, wcs=wcs, variance=variance_map, psf=psf_data, mask=image_data < 0, # Mask negative pixels identity="r_band" ) # Create Sersic galaxy model model = ap.models.AstroPhot_Model( name="my_galaxy", model_type="sersic galaxy model", target=target, parameters={ "center": [150.5, 150.5], # Initial guess in pixels "PA": 45 * np.pi / 180, # Position angle in radians "q": 0.6, "n": 4.0, "Re": 10.0, "Ie": 20.0 } ) # Auto-initialize parameters if not fully specified model.initialize() # Fit using Levenberg-Marquardt optimizer result = ap.fit.LM(model, verbose=1, max_iter=100).fit() # Extract results print(result.message) # Convergence message result.update_uncertainty() # Calculate parameter uncertainties # Access fitted parameters print(f"Center: {model['center'].value}") print(f"PA: {model['PA'].value * 180/np.pi:.2f} degrees") print(f"q: {model['q'].value:.3f}") print(f"n: {model['n'].value:.3f} ± {model['n'].uncertainty:.3f}") print(f"Re: {model['Re'].value:.3f} arcsec") print(f"Chi-squared: {result.χ2}") # Get model image model_img = model.make_model_image() residual = target - model_img ``` -------------------------------- ### NUTS Sampler Initialization and Execution Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/FittingMethods.ipynb Initializes a model and runs the No-U-Turn Sampler (NUTS) for parameter estimation. This sampler is generally recommended for its efficiency and ability to adapt step sizes. It uses LM for initial point estimation and then NUTS to explore the posterior. ```python MODEL = initialize_model(target, False) # Use LM to start the sampler at a high likelihood location, no burn-in needed! res_nuts = ap.fit.NUTS(MODEL).fit() ``` -------------------------------- ### Load Configuration, Fit Model, and Save Results with AstroPhot Source: https://context7.com/autostronomy/astrophot/llms.txt This code snippet demonstrates loading a model configuration from a YAML file, setting up a target image and PSF, building and fitting an AstroPhot model using Levenberg-Marquardt optimization, and saving the fit results back to a configuration format. It also shows how to reload a fitted model later. ```python import yaml import astrophot as ap # Load configuration and create model with open('model_config.yaml', 'r') as f: loaded_config = yaml.safe_load(f) # Load target image target = ap.image.Target_Image(filename=loaded_config["target"]) target.set_psf(ap.image.PSF_Image(filename=loaded_config["psf"])) # Build model from config model = ap.models.AstroPhot_Model.from_config(loaded_config, target=target) # Run fit result = ap.fit.LM(model, verbose=1).fit() # Save results back to config format result_config = model.to_config() result_config["fit_results"] = { "chi2": result.χ2, "reduced_chi2": result.reduced_χ2, "message": result.message } with open('model_result.yaml', 'w') as f: yaml.dump(result_config, f) # Later: reload fitted model with open('model_result.yaml', 'r') as f: saved_config = yaml.safe_load(f) fitted_model = ap.models.AstroPhot_Model.from_config(saved_config, target=target) # Model now has fitted parameters loaded ``` -------------------------------- ### Equality Constraints Between Models (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Demonstrates how to apply equality constraints between parameters of different models. Here, the 'PA' parameter of model_2 is linked to model_1, so changes to one affect the other. This is useful for ensuring shared characteristics like orientation. ```python # model 1 is a sersic model model_1 = ap.models.AstroPhot_Model( model_type="sersic galaxy model", parameters={"center": [50, 50], "PA": np.pi / 4} ) # model 2 is an exponential model model_2 = ap.models.AstroPhot_Model( model_type="exponential galaxy model", ) # Here we add the constraint for "PA" to be the same for each model. # In doing so we provide the model and parameter name which should # be connected. model_2["PA"].value = model_1["PA"] # Here we can see how the two models now both can modify this parameter print( "initial values: model_1 PA", model_1["PA"].value.item(), "model_2 PA", model_2["PA"].value.item(), ) # Now we modify the PA for model_1 model_1["PA"].value = np.pi / 3 print( "change model_1: model_1 PA", model_1["PA"].value.item(), "model_2 PA", model_2["PA"].value.item(), ) # Similarly we modify the PA for model_2 model_2["PA"].value = np.pi / 2 print( "change model_2: model_1 PA", model_1["PA"].value.item(), "model_2 PA", model_2["PA"].value.item(), ) ``` -------------------------------- ### Initialize AstroPhot model with parameters (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/FittingMethods.ipynb Creates an AstroPhot model group containing a flat sky component and multiple Sérsic galaxy components. Chooses true or initial parameters, builds the model list, and calls initialize() to prepare the model for fitting. ```Python def initialize_model(target, use_true_params=True): # Pick parameters to start the model with if use_true_params: sersic_params, sky_param = true_params() else: sersic_params, sky_param = init_params() # List of models, starting with the sky model_list = [ ap.models.AstroPhot_Model( name="sky", model_type="flat sky model", target=target, parameters={"F": sky_param[0]}, ) ] # Add models to the list for i, params in enumerate(sersic_params): model_list.append( [ ap.models.AstroPhot_Model( name=f"sersic {i}", model_type="sersic galaxy model", target=target, parameters={ "center": [params[0], params[1]], "q": params[2], "PA": params[3], "n": params[4], "Re": params[5], "Ie": params[6], }, # psf_mode = "full", # uncomment to try everything with PSF blurring (takes longer) ) ] ) MODEL = ap.models.Group_Model( name="group", models=model_list, target=target, ) # Make sure every model is ready to go MODEL.initialize() return MODEL ``` -------------------------------- ### Initialize AstroPhot Environment and Basic Target Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/ModelZoo.ipynb Sets up the AstroPhot environment with autoreload and imports necessary libraries. It then creates a basic target image for demonstration purposes. ```python %load_ext autoreload %autoreload 2 import astrophot as ap import numpy as np import torch import matplotlib.pyplot as plt %matplotlib inline basic_target = ap.image.Target_Image(data=np.zeros((100, 100)), pixelscale=1, zeropoint=20) ``` -------------------------------- ### Plot Model Image with Discrete Levels (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Visualizes a model's image with a specified number of discrete color levels using `ap.plots.model_image`. This function is useful for highlighting subtle features and assessing brightness at specific locations. ```python # Plot model image with discrete levels # this is very useful for visualizing subtle features and for eyeballing the brightness at a given location. # just add the "cmap_levels" keyword to the model_image call and tell it how many levels you want fig11, ax11 = plt.subplots(figsize=(8, 8)) ap.plots.model_image(fig11, ax11, model2, cmap_levels=15) plt.show() ``` -------------------------------- ### Automated Parameter Initialization for Single Source with AstroPhot Source: https://context7.com/autostronomy/astrophot/llms.txt This Python code snippet shows how to use AstroPhot's automatic initialization for a single source. It loads an image with minimal information, creates a model without initial parameters, and then calls `model.initialize()` to automatically estimate parameters like center, PA, q, Re, n, and Ie from the image data. Dependencies include `astrophot` and `numpy`. ```python import astrophot as ap import numpy as np # Load image with minimal information target = ap.image.Target_Image( data=image_data, variance=variance_map, pixelscale=0.262, psf=psf_data ) # Create model with NO initial parameters model = ap.models.AstroPhot_Model( name="auto_galaxy", model_type="sersic galaxy model", target=target ) # Auto-initialize will: # 1. Find center using center of mass / peak finding # 2. Estimate PA and q from image moments # 3. Estimate Re from isophotal analysis # 4. Estimate n from profile shape # 5. Estimate Ie from surface brightness model.initialize() print("Auto-initialized parameters:") for param_name, param in model.parameters.items(): print(f" {param_name}: {param.value}") ``` -------------------------------- ### Plot Fitted Model and Residuals (Python) Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb This snippet plots the fitted model image and the image residuals using AstroPhot's plotting functions. It sets up a matplotlib figure with two subplots and uses ap.plots.model_image and ap.plots.residual_image to generate the plots. ```python fig5, ax5 = plt.subplots(1, 2, figsize=(16, 6)) ap.plots.model_image(fig5, ax5[0], model2) ap.plots.residual_image(fig5, ax5[1], model2, normalize_residuals=True) plt.show() ``` -------------------------------- ### Plot Covariance Matrix Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Visualizes the covariance matrix of model parameters. While the scale may depend on image variance accuracy, this plot shows how parameter covariances interact within a fit. It requires the covariance matrix, parameter vector values, and parameter names. ```python # Plot the uncertainty matrix # While the scale of the uncertainty may not be meaningful if the image variance is not accurate, we # can still see how the covariance of the parameters plays out in a given fit. fig, ax = ap.plots.covariance_matrix( result.covariance_matrix.detach().cpu().numpy(), model2.parameters.vector_values().detach().cpu().numpy(), model2.parameters.vector_names(), ) plt.show() ``` -------------------------------- ### Plot Model and Residual Images for a Specific Window Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Generates plots for the model image and the residual image when fitting is constrained to a specific window. The residual image is normalized for better visualization. This function is useful for assessing the fit quality within the defined target window. ```python # Note that when only a window is fit, the default plotting methods will only show that window fig7, ax7 = plt.subplots(1, 2, figsize=(16, 6)) ap.plots.model_image(fig7, ax7[0], model3) ap.plots.residual_image(fig7, ax7[1], model3, normalize_residuals=True) plt.show() ``` -------------------------------- ### Automated Parameter Initialization for Crowded Fields with AstroPhot Source: https://context7.com/autostronomy/astrophot/llms.txt This Python code demonstrates initializing multiple AstroPhot models automatically from a segmentation map for crowded fields. It uses `photutils` to detect and deblend sources, then iterates through each detected source to create a windowed target and initialize a model. Finally, it groups these models and fits them together. Dependencies include `astrophot`, `numpy`, `photutils.segmentation`, and `astropy.convolution`. ```python import astrophot as ap import numpy as np from photutils.segmentation import detect_sources, deblend_sources from astropy.convolution import Gaussian2DKernel # Detect sources threshold = 3.0 * np.sqrt(np.median(variance_map)) kernel = Gaussian2DKernel(2.0) segmap = detect_sources(image_data, threshold, npixels=10, kernel=kernel) segmap = deblend_sources(image_data, segmap, npixels=10, kernel=kernel) # Initialize multiple models from segmentation models = [] for i in range(1, segmap.nlabels + 1): # Create mask for this source source_mask = segmap.data == i # Create windowed target y_indices, x_indices = np.where(source_mask) window = [ [x_indices.min(), x_indices.max()], [y_indices.min(), y_indices.max()] ] # Create model source_model = ap.models.AstroPhot_Model( name=f"source_{i}", model_type="sersic galaxy model", target=target, window=window ) # Initialize from segmentation source_model.initialize(mask=source_mask) models.append(source_model) # Create group and fit all sources group = ap.models.AstroPhot_Model( name="field", model_type="group model", models=models, target=target ) result = ap.fit.LM(group, verbose=2).fit() print(f"Fitted {len(models)} sources with χ²/DOF = {result.reduced_χ2:.3f}") ``` -------------------------------- ### Create Model from YAML Configuration in Python Source: https://context7.com/autostronomy/astrophot/llms.txt Demonstrates creating an astrophotography model from a YAML configuration file. Includes model parameters with values, limits, and uncertainties. Shows saving configuration to YAML file for reproducibility. ```python import astrophot as ap # Create model from configuration dictionary config = { "name": "my_galaxy_fit", "model_type": "group model", "models": [ { "name": "sky", "model_type": "flat sky model", "parameters": {"F": {"value": 1000, "locked": False}} }, { "name": "galaxy", "model_type": "sersic galaxy model", "parameters": { "center": {"value": [150, 150], "uncertainty": [0.1, 0.1]}, "PA": {"value": 0.785, "limits": [0, 3.14159]}, "q": {"value": 0.6, "limits": [0.1, 1.0]}, "n": {"value": 4.0, "limits": [0.5, 8.0]}, "Re": {"value": 10.0, "limits": [1.0, 100.0]}, "Ie": {"value": 50.0, "limits": [0.1, 1e6]} }, "window": [[100, 200], [100, 200]], "psf_mode": "full", "sampling_mode": "simpsons" } ], "target": "target_image.fits", "psf": "psf.fits" } # Save configuration import yaml with open('model_config.yaml', 'w') as f: yaml.dump(config, f) ``` -------------------------------- ### Record Total Flux and Magnitude Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Calculates and prints the total flux and magnitude of a model, along with their uncertainties. For models with analytic total fluxes, integration is to infinity; otherwise, it's the total flux within the window. The `.item()` method extracts the scalar value from a tensor. ```python print( f"Total Flux: {model2.total_flux().item():.1f} +- {model2.total_flux_uncertainty().item():.1f}" ) print( f"Total Magnitude: {model2.total_magnitude().item():.4f} +- {model2.total_magnitude_uncertainty().item():.4f}" ) ``` -------------------------------- ### Update Uncertainty Estimates with LM Optimizer Source: https://github.com/autostronomy/astrophot/blob/main/docs/source/tutorials/GettingStarted.ipynb Updates the uncertainty estimates for model parameters using the `ap.fit.LM` optimizer. It can also return the full covariance matrix. Ensure the variance image is accurate for meaningful uncertainties. This function returns statistical uncertainties, not systematic ones. ```python result.update_uncertainty() print(model2) ```