Main modules

Basic Functions

AstronomyCalc.basic_functions.a_to_z(a)[source]

Convert scale factor (a) to redshift (z).

Parameters:

a (float or numpy array) – scale factor value(s).

Returns:

redshifts

AstronomyCalc.basic_functions.z_to_a(z)[source]

Convert redshift (z) to scale factor (a).

Parameters:

z (float or numpy array) – redshift value(s).

Returns:

scale factor

Bayesian Inference

class AstronomyCalc.mcmc.ImportanceSampling(target_distribution, proposal_distribution=None, proposal_sampler=None, n_jobs=1, proposal_mean=None, proposal_cov=None)[source]

Bases: object

Simple Importance Sampling for estimating expectations with MCMC.

Methods

estimate_expectation

sample

estimate_expectation(function)[source]
sample(n_samples=10000)[source]
class AstronomyCalc.mcmc.MetropolisHastings(nwalkers, ndim, log_probability, proposal='Normal', proposal_cov=None, n_jobs=1)[source]

Bases: object

Metropolis-Hastings Algorithm for Monte Carlo Markov Chains.

Methods

acceptance_probability

adapt_proposal_covariance

draw_from_proposal

get_flat_samples

initialise

run_sampler

walk

acceptance_probability(mean, next_sample, q_next_mean, q_mean_next)[source]
adapt_proposal_covariance(n_step, adapt_window=100, scale_factor=100)[source]
draw_from_proposal(mean, cov, size=None)[source]
get_flat_samples(burn_in=0)[source]
initialise(initial_value)[source]
run_sampler(n_samples, initial_value=None, adapt_window=None)[source]
walk(proposal_cov)[source]
AstronomyCalc.mcmc.plot_posterior_corner(flat_samples, labels, truths=None, weights=None, confidence_levels=None, smooth=0.5, smooth1d=0.5)[source]

Plots the posterior distributions with corner plots, including 1-sigma and 2-sigma contours.

Parameters: - flat_samples (dict or array-like): Dictionary with dataset names as keys and MCMC samples as values, or just the samples array if only one dataset is present. - labels (list of str, optional): Labels for the parameters. - truths (array-like, optional): True parameter values for comparison. - weights (array-like, optional): Weights for the samples. - confidence_levels (list of float, optional): Confidence levels for the contours (e.g., [0.68, 0.95, 0.99]). - smooth (float, optional): Smoothing factor for 2D contours. Default is 0.5. - smooth1d (float, optional): Smoothing factor for 1D histograms. Default is 0.5.

Returns: - None

Cosmological Calculator

AstronomyCalc.cosmo_calculator.Hubble(param, z=None, a=None)[source]

Calculate the Hubble parameter at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to evaluate the Hubble parameter.

  • a (float, optional) – The scale factor at which to evaluate the Hubble parameter. Only one of z or a should be provided.

Returns:

float – The Hubble parameter (H) at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.Hubble_distance(param)[source]

Calculate the Hubble distance.

Parameters:

param (dict) – A dictionary containing cosmological parameters.

Returns:

float – The Hubble distance (c / H0) in Mpc.

AstronomyCalc.cosmo_calculator.age_estimator(param, z)[source]

Age estimator of the Universe.

Parameters:
  • param (object) – object containing the parameter values

  • z (float) – redshift

Returns:

  • The age of the universe in Gyr

AstronomyCalc.cosmo_calculator.angular_diameter_distance(param, z=None, a=None)[source]

Calculate the angular diameter distance at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the angular distance.

  • a (float, optional) – The scale factor at which to calculate the angular distance. Only one of z or a should be provided.

Returns:

float – The angular diameter distance in Mpc at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.comoving_distance(param, z=None, a=None)[source]

Calculate the comoving distance at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the comoving distance.

  • a (float, optional) – The scale factor at which to calculate the comoving distance. Only one of z or a should be provided.

Returns:

float – The comoving distance in Mpc at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.cosmic_age(param, z=None, a=None)[source]

Calculate the cosmic age at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the cosmic age.

  • a (float, optional) – The scale factor at which to calculate the cosmic age. Only one of z or a should be provided.

Returns:

float – The age of the universe in Gyr at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.distance_modulus(param, z=None, a=None)[source]

Calculate the distance modulus at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the luminosity distance.

  • a (float, optional) – The scale factor at which to calculate the luminosity distance. Only one of z or a should be provided.

Returns:

float – The distance modulus in Mpc at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.horizon_distance(param)[source]

Calculate the horizon distance, which is the maximum distance from which light has traveled to the observer in the age of the universe.

Parameters:

param (dict) – A dictionary containing cosmological parameters.

Returns:

float – The horizon distance in Mpc.

AstronomyCalc.cosmo_calculator.light_travel_distance(param, z=None, a=None)[source]

Calculate the light travel distance (also known as lookback distance) at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the light travel distance.

  • a (float, optional) – The scale factor at which to calculate the light travel distance. Only one of z or a should be provided.

Returns:

float – The light travel distance in Mpc at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.luminosity_distance(param, z=None, a=None)[source]

Calculate the luminosity distance at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the luminosity distance.

  • a (float, optional) – The scale factor at which to calculate the luminosity distance. Only one of z or a should be provided.

Returns:

float – The luminosity distance in Mpc at the specified redshift or scale factor.

AstronomyCalc.cosmo_calculator.proper_distance(param, z=None, a=None)[source]

Calculate the proper distance at a given redshift or scale factor.

Parameters:
  • param (dict) – A dictionary containing cosmological parameters.

  • z (float, optional) – The redshift at which to calculate the proper distance.

  • a (float, optional) – The scale factor at which to calculate the proper distance. Only one of z or a should be provided.

Returns:

float – The proper distance in Mpc at the specified redshift or scale factor.

Cosmological Equations

class AstronomyCalc.cosmo_equations.CosmoDistances(param)[source]

Bases: FriedmannEquation

Cosmological distances

Variables:

param (object) – object containing the parameter values

Methods

H

Hubble_dist

age

angular_dist

comoving_dist

create_functions

horizon_dist

light_travel_dist

luminosity_dist

proper_dist

Hubble_dist()[source]
angular_dist(z=None, a=None)[source]
comoving_dist(z=None, a=None)[source]
horizon_dist()[source]
light_travel_dist(z=None, a=None)[source]
luminosity_dist(z=None, a=None)[source]
proper_dist(z=None, a=None)[source]
class AstronomyCalc.cosmo_equations.FriedmannEquation(param)[source]

Bases: object

Friedmann equation.

Variables:

H – function to give the value of the Hubble parameter in km/s/Mpc.

Methods

H

age

create_functions

H(z=None, a=None)[source]
age(z=None, a=None)[source]
create_functions()[source]

Generate Data

AstronomyCalc.create_data.Hubble1929_data()[source]

Load the Hubble (1929) dataset of distance vs velocity.

Parameters:

data_link (str) – URL to the CSV file containing the Hubble 1929 data. If not provided, the default link is used.

Returns:

tuple

Two ndarrays containing the distances and velocities, respectively.
  • distances (ndarray): Array of distances.

  • velocities (ndarray): Array of velocities.

AstronomyCalc.create_data.PantheonPlus_distance_modulus(zmin=0.023, zmax=6, zval='hd')[source]
class AstronomyCalc.create_data.SPARC_Galaxy_dataset[source]

Bases: object

A class to handle the SPARC Galaxy dataset (http://astroweb.cwru.edu/SPARC/).

This class can download, read, and process files from the SPARC Galaxy dataset.

Variables:
  • package_folder (str) – Path to the package input data folder.

  • data_folder (str) – Path to the folder containing the rotation curve data.

Methods

download_data

read_rotation_curves

download_data()[source]
read_rotation_curves(filename=None, name=None)[source]
AstronomyCalc.create_data.SPARC_galaxy_rotation_curves_data(filename=None, name=None)[source]

Retrieves the rotation curve data for a specific galaxy from the SPARC dataset.

This function utilizes the SPARC_Galaxy_dataset class to read the rotation curves of galaxies from the SPARC dataset. The data can be accessed either by directly providing the filename or by specifying the galaxy name.

Parameters:
  • filename (str, optional) – The path to the rotation curve file. If provided, this file will be used directly.

  • name (str, optional) – The name of the galaxy for which to retrieve rotation curve data. If provided, the function will look for the corresponding file in the dataset.

Returns:

dict

A dictionary containing the rotation curve data. The dictionary has two keys:
  • ’values’: A dictionary where each key corresponds to a specific quantity

    (e.g., ‘Rad’, ‘Vobs’) and the value is an array of data for that quantity.

  • ’units’: A dictionary mapping each quantity to its unit (e.g., ‘kpc’,

    ’km/s’).

Raises:

AssertionError – If neither filename nor name is provided, the function raises an assertion error, requiring one of the inputs.

AstronomyCalc.create_data.download_data(url, target_folder=None)[source]
AstronomyCalc.create_data.generate_distance_modulus(n_samples=100, z0=0.3, dmu_0=0.1, dmu_1=0.02, random_state=42, cosmo=None, param=None)[source]

Generate a dataset of distance modulus (mu) vs redshift.

Parameters:
  • n_samples (int) – Size of generated data.

  • z0 (float) – Parameter in redshift distribution: p(z) ∼ (z / z0)^2 exp[-1.5 (z / z0)].

  • dmu_0 (float) – Base error in mu.

  • dmu_1 (float) – Error in mu as a function of mu.

  • random_state (int or np.random.RandomState instance) – Random seed or random number generator.

  • cosmo (astropy.cosmology instance) – Cosmology to use when generating the sample. If not provided, a Flat Lambda CDM model with H0=71, Om0=0.27, Tcmb=0 is used.

  • param (object) – Object containing the parameter values.

Returns:

z (ndarray) – Array of redshifts of shape (n_samples,). mu (ndarray): Array of distance moduli of shape (n_samples,). dmu (ndarray): Array of errors in distance moduli of shape (n_samples,).

AstronomyCalc.create_data.line_data(true_m=2, true_b=1, sigma=1, n_samples=50, error_sigma=None)[source]

Generate synthetic linear data for testing and modeling.

This function generates a set of synthetic data points that lie on a line with a specified slope and intercept, while adding Gaussian noise to the y-values to simulate real-world data.

Parameters: - true_m (float): The slope of the line. Defaults to 2. - true_b (float): The y-intercept of the line. Defaults to 1. - sigma (float): The standard deviation of the Gaussian noise added to the y-values. Defaults to 1. - n_samples (int): The number of data points to generate. Defaults to 50.

Returns: - np.ndarray: A 2D array where each row is a data point with two columns: the x-value and the corresponding y-value. The x-values are evenly spaced between 0 and 10, and the y-values are generated according to the line equation y = true_m * x + true_b with added Gaussian noise.

Parameters

External Parameters

This is a useful file if this package is a simulator. All the parameter can be initialised and them passed as an param object to the simulator functions and classes.

class AstronomyCalc.param.Bunch(data)[source]

Bases: object

A simple class to translate dictionary keys to object attributes.

Variables:

__dict__ (dict) – Updates the object’s __dict__ with the provided data dictionary.

AstronomyCalc.param.code_par(**kwargs)[source]

Define default parameters for cosmological simulations.

Keyword Arguments:
  • zmin (float) – Minimum redshift. Default is 0.01.

  • zmax (float) – Maximum redshift. Default is 9.00.

  • Nz (int) – Number of redshift bins. Default is 20.

  • verbose (bool) – If True, the simulator prints messages. Default is True.

Returns:

Bunch – An object with the specified parameters as attributes.

AstronomyCalc.param.cosmo_par(**kwargs)[source]

Define default cosmological parameters.

Keyword Arguments:
  • Om (float) – Matter overdensity. Default is 0.31.

  • Or (float) – Radiation overdensity. Default is 9e-5.

  • Ok (float) – Curvature overdensity. Default is 0.0.

  • Ode (float) – Dark energy overdensity. Default is None (calculated as 1 - Om - Or - Ok).

  • h (float) – Hubble constant divided by 100. Default is 0.68.

  • Tcmb (float) – CMB temperature at redshift 0. Default is 2.725.

Returns:

Bunch – An object with the specified parameters as attributes.

AstronomyCalc.param.param(cosmo=None, code=None)[source]

Combine cosmological and code parameters into a single Bunch object.

Parameters:
  • cosmo (dict, optional) – Dictionary of cosmological parameters to override defaults.

  • code (dict, optional) – Dictionary of code parameters to override defaults.

Returns:

Bunch – An object containing both cosmological and code parameters as attributes.