metadata
dict
text
stringlengths
0
40.6M
id
stringlengths
14
255
{ "filename": "full_simulation.py", "repo_name": "lsstdesc/sn_pipe", "repo_path": "sn_pipe_extracted/sn_pipe-master/run_scripts/fakes/full_simulation.py", "type": "Python" }
import os from optparse import OptionParser import numpy as np parser = OptionParser() parser.add_option("--fake_config", type="str", default='Fake_cadence.yaml', help="config file name for fake obs[%default]") parser.add_option("--fake_output", type="str", default='Fake_DESC', help="output file namefor fake_obs[%default]") parser.add_option("--RAmin", type=float, default=-0.05, help="RA min for obs area [%default]") parser.add_option("--RAmax", type=float, default=0.05, help="RA max for obs area [%default]") parser.add_option("--Decmin", type=float, default=-0.05, help="Dec min for obs area [%default]") parser.add_option("--Decmax", type=float, default=0.05, help="Dec max for obs area [%default]") parser.add_option("--outDir_simu", type=str, default='Output_Simu', help="output dir for simulation results[%default]") parser.add_option("--simulator", type=str, default='sn_cosmo', help="simulator for LC [%default]") parser.add_option("--x1", type=float, default=-2.0, help="SN x1 [%default]") parser.add_option("--color", type=float, default=0.2, help="SN color[%default]") parser.add_option("--zmin", type=float, default=0.01, help="min redshift[%default]") parser.add_option("--zmax", type=float, default=1.0, help="min redshift[%default]") parser.add_option("--zstep", type=float, default=0.01, help="step redshift[%default]") parser.add_option("--ebvofMW", type=float, default=-1., help="ebvofMW value[%default]") opts, args = parser.parse_args() fake_config = opts.fake_config fake_output = opts.fake_output RAmin = opts.RAmin RAmax = opts.RAmax Decmin = opts.Decmin Decmax = opts.Decmax outDir_simu = opts.outDir_simu simulator = opts.simulator x1 = np.round(opts.x1, 1) color = np.round(opts.color, 1) ebvofMW = opts.ebvofMW zmin = opts.zmin zmax = opts.zmax zstep = opts.zstep prodid = '{}_Fake_{}_seas_-1_{}_{}_ebvofMW_{}'.format( simulator, fake_output, x1, color, ebvofMW) # first step: create fake data from yaml configuration file cmd = 'python run_scripts/fakes/make_fake.py --config {} --output {}'.format( fake_config, fake_output) os.system(cmd) # now run the full simulation on these data cmd = 'python run_scripts/simulation/run_simulation.py --dbDir .' cmd += ' --dbName {}'.format(opts.fake_output) cmd += ' --dbExtens npy' cmd += ' --x1min {} --x1Type unique'.format(x1) cmd += ' --colormin {} --colorType unique'.format(color) cmd += ' --fieldType Fake' cmd += ' --coadd 0 --radius 0.01' cmd += ' --outDir {}'.format(outDir_simu) cmd += ' --simulator {}'.format(simulator) cmd += ' --nproc 1' cmd += ' --RAmin 0.0' cmd += ' --RAmax 0.1' cmd += ' --prodid {}'.format(prodid) cmd += ' --zmin {}'.format(zmin) cmd += ' --zmax {}'.format(zmax) cmd += ' --zstep {}'.format(zstep) cmd += ' --ebvofMW {}'.format(ebvofMW) print(cmd) os.system(cmd)
lsstdescREPO_NAMEsn_pipePATH_START.@sn_pipe_extracted@sn_pipe-master@run_scripts@fakes@full_simulation.py@.PATH_END.py
{ "filename": "annotation_polar.py", "repo_name": "matplotlib/matplotlib", "repo_path": "matplotlib_extracted/matplotlib-main/galleries/examples/text_labels_and_annotations/annotation_polar.py", "type": "Python" }
""" ==================== Annotate polar plots ==================== This example shows how to create an annotation on a polar graph. For a complete overview of the annotation capabilities, also see the :ref:`annotations`. .. redirect-from:: /gallery/pyplots/annotation_polar """ import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(projection='polar') r = np.arange(0, 1, 0.001) theta = 2 * 2*np.pi * r line, = ax.plot(theta, r, color='#ee8d18', lw=3) ind = 800 thisr, thistheta = r[ind], theta[ind] ax.plot([thistheta], [thisr], 'o') ax.annotate('a polar annotation', xy=(thistheta, thisr), # theta, radius xytext=(0.05, 0.05), # fraction, fraction textcoords='figure fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='bottom', ) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.projections.polar` # - `matplotlib.axes.Axes.annotate` / `matplotlib.pyplot.annotate`
matplotlibREPO_NAMEmatplotlibPATH_START.@matplotlib_extracted@matplotlib-main@galleries@examples@text_labels_and_annotations@annotation_polar.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "esheldon/ngmix", "repo_path": "ngmix_extracted/ngmix-master/ngmix/__init__.py", "type": "Python" }
# flake8: noqa from numba.core.errors import NumbaExperimentalFeatureWarning import warnings warnings.simplefilter('ignore', category=NumbaExperimentalFeatureWarning) from ._version import __version__ from . import util from .util import print_pars from . import flags from . import defaults from . import gmix from .gmix import ( GMix, GMixModel, GMixCoellip, ) from . import gmix_ndim from .gmix_ndim import GMixND from . import jacobian from .jacobian import ( Jacobian, UnitJacobian, DiagonalJacobian, ) from . import fastexp_nb from . import priors from .priors import srandu from . import joint_prior from . import shape from .shape import Shape from . import moments from . import gexceptions from .gexceptions import * from . import fitting from . import runners from . import bootstrap from . import guessers from . import em from . import admom from . import gaussmom from . import ksigmamom from . import prepsfmom from . import observation from .observation import Observation, ObsList, MultiBandObsList from . import metacal from . import simobs from . import gaussap
esheldonREPO_NAMEngmixPATH_START.@ngmix_extracted@ngmix-master@ngmix@__init__.py@.PATH_END.py
{ "filename": "potentials.py", "repo_name": "hmuellergoe/mrbeam", "repo_path": "mrbeam_extracted/mrbeam-main/mr_beam/itreg/regpy/util/potentials.py", "type": "Python" }
import numpy as np def bell(domain): v = domain.zeros() r = np.linalg.norm(domain.coords, axis=0) v[r < 1] = np.exp(-1 / (1 - r[r < 1]**2)) return v def peaks(domain): r = np.linalg.norm(domain.coords, axis=0) M = mollifier(r) X = domain.coords f = 3 * (1 - X[0])**2 * np.exp(-X[0]**2 - (X[1] - 1)**2) \ - 10 * (X[0] / 5 - X[0]**3 - X[1]**5) * np.exp(-r**2) \ - 1 / 3 * np.exp(-(X[0] + 1)**2 - X[1]**2) return f * M def mollifier(r): M = np.zeros(r.shape) r_ctf = r < 1 M[~r_ctf] = 0 M[r_ctf] = np.exp(1 - 1 / (1 - r[r_ctf]**2)) return M
hmuellergoeREPO_NAMEmrbeamPATH_START.@mrbeam_extracted@mrbeam-main@mr_beam@itreg@regpy@util@potentials.py@.PATH_END.py
{ "filename": "within_saa.py", "repo_name": "jotaylor/acdc-hst", "repo_path": "acdc-hst_extracted/acdc-hst-main/src/acdc/database/within_saa.py", "type": "Python" }
import numpy as np import math # Model 31 from https://github.com/spacetelescope/costools/blob/master/costools/saamodel.py COS_FUV_MODEL = [ (-28.3, 14.0), (-27.5, 15.0), (-26.1, 13.0), (-19.8, 1.5), ( -9.6, 341.0), ( -7.6, 330.4), ( -6.0, 318.8), ( -7.9, 297.2), (-12.0, 286.1), (-17.1, 279.9), (-20.3, 277.5), (-23.5, 276.5), (-26.0, 276.4), (-28.6, 276.7)] DEGtoRAD = math.pi / 180. TWOPI = 2. * math.pi # This cutoff is based on current models in saamodel.py; this is used when # finding the middle of the SAA region (middle_SAA). SAA_LONGITUDE_CUTOFF = 200. def testWithinSAA(hst, vertices, middle_SAA): """Test whether HST is within the polygon for an SAA contour. Args: hst (array_like): Unit vector pointing from the center of the Earth toward the location of HST at a particular time. vertices (array_like, shape (nvertices,3)): vertices[i] is a unit vector from the center of the Earth toward vertex number i of a polygon that defines one of the SAA contour. middle_SAA (array_like): Unit vector from the center of the Earth toward a point near the middle of the SAA region. This is for making a quick check that hst is close enough to the SAA contour to be worth making a detailed check. Returns: bool: True if hst is within the SAA contour defined by vertices. """ # This test is primarily to exclude points that are diametrically # opposite to the SAA contour (because this would not be caught by # the code below!), but it should also save unnecessary arithmetic # most of the time. if np.dot(hst, middle_SAA) < 0.: return False nvertices = len(vertices) sin_lat_hst = hst[2] cos_lat_hst = math.sqrt(1. - sin_lat_hst**2) cos_long_hst = hst[0] / cos_lat_hst sin_long_hst = hst[1] / cos_lat_hst # vertices rotated to put hst in the x-z plane v_rot = vertices.copy() v_rot[:,0] = vertices[:,0] * cos_long_hst + vertices[:,1] * sin_long_hst v_rot[:,1] = -vertices[:,0] * sin_long_hst + vertices[:,1] * cos_long_hst # v_rot rotated to put hst on the x axis v_rotrot = v_rot.copy() v_rotrot[:,0] = v_rot[:,0] * cos_lat_hst + v_rot[:,2] * sin_lat_hst v_rotrot[:,2] = -v_rot[:,0] * sin_lat_hst + v_rot[:,2] * cos_lat_hst azimuth = np.arctan2(v_rotrot[:,2], v_rotrot[:,1]) azimuth = np.where(azimuth < 0., azimuth + TWOPI, azimuth) delta_az = azimuth[1:] - azimuth[0:-1] delta_az = np.where(delta_az < -np.pi, delta_az + TWOPI, delta_az) delta_az = np.where(delta_az > np.pi, delta_az - TWOPI, delta_az) sum_delta_az = delta_az.sum() return not (sum_delta_az < 0.1 and sum_delta_az > -0.1) def saaFilter(longitude_col, latitude_col, model=COS_FUV_MODEL): """Flag within the specified SAA contour as bad. Args: model (int): The SAA model number. Currently these range from 2 to 32 inclusive. (Models 0 and 1 are radio frequence interference contours.) Returns: flag (array_like): This is a boolean array, one element for each row of the TIMELINE table. True means that HST was within the SAA contour (specified by model) at the time corresponding to the TIMELINE row. """ nelem = len(longitude_col) flag = np.zeros(nelem, dtype=np.bool8) model_vertices = model model_vertices.append(model_vertices[0]) # make a closed loop nvertices = len(model_vertices) # will be unit vectors from center of Earth pointing toward vertices vertices = np.zeros((nvertices, 3), dtype=np.float64) minmax_long = [720., -360.] # will be minimum, maximum longitudes minmax_lat = [90., -90.] # will be minimum, maximum latitudes for i in range(nvertices): (latitude, longitude) = model_vertices[i] vertices[i] = toRect(longitude, latitude) # change the order if longitude < SAA_LONGITUDE_CUTOFF: longitude += 360. minmax_long[0] = min(longitude, minmax_long[0]) minmax_long[1] = max(longitude, minmax_long[1]) minmax_lat[0] = min(latitude, minmax_lat[0]) minmax_lat[1] = max(latitude, minmax_lat[1]) middle_long = (minmax_long[0] + minmax_long[1]) / 2. middle_lat = (minmax_lat[0] + minmax_lat[1]) / 2. middle_SAA = toRect(middle_long, middle_lat) # for each row in TIMELINE table for k in range(nelem): hst = toRect(longitude_col[k], latitude_col[k]) flag[k] = testWithinSAA(hst, vertices, middle_SAA) return flag def toRect(longitude, latitude): """Convert longitude and latitude to rectangular coordinates. Args: longitude (float): longitude in degrees. latitude (float): latitude in degrees. Returns: rect (array-like): Unit vector in rectangular coordinates. """ rect = np.array([1.0, 0.0, 0.0], dtype=np.float64) longitude *= DEGtoRAD latitude *= DEGtoRAD rect[0] = math.cos(latitude) * math.cos(longitude) rect[1] = math.cos(latitude) * math.sin(longitude) rect[2] = math.sin(latitude) return rect
jotaylorREPO_NAMEacdc-hstPATH_START.@acdc-hst_extracted@acdc-hst-main@src@acdc@database@within_saa.py@.PATH_END.py
{ "filename": "halo_model.py", "repo_name": "LSSTDESC/CCL", "repo_path": "CCL_extracted/CCL-master/pyccl/halos/halo_model.py", "type": "Python" }
__all__ = ("HMCalculator",) import numpy as np from scipy.integrate import simpson from .. import CCLAutoRepr, unlock_instance from .. import physical_constants as const from . import MassDef from ..pyutils import _spline_integrate class HMCalculator(CCLAutoRepr): """This class implements a set of methods that can be used to compute various halo model quantities. A lot of these quantities will involve integrals of the sort: .. math:: \\int dM\\,n(M,a)\\,f(M,k,a), where :math:`n(M,a)` is the halo mass function, and :math:`f` is an arbitrary function of mass, scale factor and Fourier scales. Args: mass_function (str or :class:`~pyccl.halos.halo_model_base.MassFunc`): the mass function to use halo_bias (str or :class:`~pyccl.halos.halo_model_base.HaloBias`): the halo bias function to use mass_def (str or :class:`~pyccl.halos.massdef.MassDef`): the halo mass definition to use log10M_min (:obj:`float`): lower bound of the mass integration range (base-10 logarithmic). log10M_max (:obj:`float`): lower bound of the mass integration range (base-10 logarithmic). nM (:obj:`int`): number of uniformly-spaced samples in :math:`\\log_{10}(M)` to be used in the mass integrals. integration_method_M (:obj:`str`): integration method to use in the mass integrals. Options: "simpson" and "spline". """ # noqa __repr_attrs__ = __eq_attrs__ = ( "mass_function", "halo_bias", "mass_def", "precision",) def __init__(self, *, mass_function, halo_bias, mass_def=None, log10M_min=8., log10M_max=16., nM=128, integration_method_M='simpson'): # Initialize halo model ingredients. out = MassDef.from_specs(mass_def, mass_function=mass_function, halo_bias=halo_bias) if len(out) != 3: raise ValueError("A valid mass function and halo bias is " "needed") self.mass_def, self.mass_function, self.halo_bias = out self.precision = { 'log10M_min': log10M_min, 'log10M_max': log10M_max, 'nM': nM, 'integration_method_M': integration_method_M} self._lmass = np.linspace(log10M_min, log10M_max, nM) self._mass = 10.**self._lmass self._m0 = self._mass[0] if integration_method_M == "simpson": self._integrator = self._integ_simpson elif integration_method_M == "spline": self._integrator = self._integ_spline else: raise ValueError("Invalid integration method.") # Cache last results for mass function and halo bias. self._cosmo_mf = self._cosmo_bf = None self._a_mf = self._a_bf = -1 def _integ_simpson(self, fM, log10M): return simpson(fM, x=log10M) def _integ_spline(self, fM, log10M): # Spline integrator return _spline_integrate(log10M, fM, log10M[0], log10M[-1]) def _check_mass_def(self, *others): # Verify that internal & external mass definitions are consistent. if set([x.mass_def for x in others]) != set([self.mass_def]): raise ValueError("Inconsistent mass definitions.") @unlock_instance(mutate=False) def _get_mass_function(self, cosmo, a, rho0): # Compute the mass function at this cosmo and a. if a != self._a_mf or cosmo != self._cosmo_mf: self._mf = self.mass_function(cosmo, self._mass, a) integ = self._integrator(self._mf*self._mass, self._lmass) self._mf0 = (rho0 - integ) / self._m0 self._cosmo_mf, self._a_mf = cosmo, a # cache @unlock_instance(mutate=False) def _get_halo_bias(self, cosmo, a, rho0): # Compute the halo bias at this cosmo and a. if a != self._a_bf or cosmo != self._cosmo_bf: self._bf = self.halo_bias(cosmo, self._mass, a) integ = self._integrator(self._mf*self._bf*self._mass, self._lmass) self._mbf0 = (rho0 - integ) / self._m0 self._cosmo_bf, self._a_bf = cosmo, a # cache def _get_ingredients(self, cosmo, a, *, get_bf): """Compute mass function and halo bias at some scale factor.""" rho0 = const.RHO_CRITICAL * cosmo["Omega_m"] * cosmo["h"]**2 self._get_mass_function(cosmo, a, rho0) if get_bf: self._get_halo_bias(cosmo, a, rho0) def _integrate_over_mf(self, array_2): # ∫ dM n(M) f(M) i1 = self._integrator(self._mf * array_2, self._lmass) return i1 + self._mf0 * array_2[..., 0] def _integrate_over_mbf(self, array_2): # ∫ dM n(M) b(M) f(M) i1 = self._integrator(self._mf * self._bf * array_2, self._lmass) return i1 + self._mbf0 * array_2[..., 0] def integrate_over_massfunc(self, func, cosmo, a): """ Returns the integral over mass of a given funcion times the mass function: .. math:: \\int dM\\,n(M,a)\\,f(M) Args: func (:obj:`callable`): a function accepting an array of halo masses as a single argument, and returning an array of the same size. cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. a (:obj:`float`): scale factor. Returns: :obj:`float`: integral value. """ # noqa fM = func(self._mass) self._get_ingredients(cosmo, a, get_bf=False) return self._integrate_over_mf(fM) def number_counts(self, cosmo, *, selection, a_min=None, a_max=1.0, na=128): """ Solves the integral: .. math:: nc(sel) = \\int dM\\int da\\,\\frac{dV}{dad\\Omega}\\, n(M,a)\\,sel(M,a) where :math:`n(M,a)` is the halo mass function, and :math:`sel(M,a)` is the selection function as a function of halo mass and scale factor. Note that the selection function is normalized to integrate to unity and assumed to represent the selection probaility per unit scale factor and per unit mass. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. selection (:obj:`callable`): function of mass and scale factor that returns the selection function. This function should take in floats or arrays with a signature ``sel(m, a)`` and return an array with shape ``(len(m), len(a))`` according to the numpy broadcasting rules. a_min (:obj:`float`): the minimum scale factor at which to start integrals over the selection function. Default: value of ``cosmo.cosmo.spline_params.A_SPLINE_MIN`` a_max (:obj:`float`): the maximum scale factor at which to end integrals over the selection function. na (:obj:`int`): number of samples in scale factor to be used in the integrals. Returns: :obj:`float`: the total number of clusters/halos. """ # noqa # get a values for integral if a_min is None: a_min = cosmo.cosmo.spline_params.A_SPLINE_MIN a = np.linspace(a_min, a_max, na) # compute the volume element dVda = cosmo.comoving_volume_element(a) # now do m intergrals in a loop mint = np.zeros_like(a) for i, _a in enumerate(a): self._get_ingredients(cosmo, _a, get_bf=False) _selm = np.atleast_2d(selection(self._mass, _a)).T mint[i] = self._integrator( dVda[i] * self._mf[..., :] * _selm[..., :], self._lmass ).squeeze() # now do scale factor integral return self._integrator(mint, a) def I_0_1(self, cosmo, k, a, prof): """ Solves the integral: .. math:: I^0_1(k,a|u) = \\int dM\\,n(M,a)\\,\\langle u(k,a|M)\\rangle, where :math:`n(M,a)` is the halo mass function, and :math:`\\langle u(k,a|M)\\rangle` is the halo profile as a function of scale, scale factor and halo mass. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. k (:obj:`float` or `array`): comoving wavenumber. a (:obj:`float`): scale factor. prof (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): halo profile. Returns: (:obj:`float` or `array`): integral values evaluated at each value of ``k``. """ self._check_mass_def(prof) self._get_ingredients(cosmo, a, get_bf=False) uk = prof.fourier(cosmo, k, self._mass, a).T return self._integrate_over_mf(uk) def I_1_1(self, cosmo, k, a, prof): """ Solves the integral: .. math:: I^1_1(k,a|u) = \\int dM\\,n(M,a)\\,b(M,a)\\, \\langle u(k,a|M)\\rangle, where :math:`n(M,a)` is the halo mass function, :math:`b(M,a)` is the halo bias, and :math:`\\langle u(k,a|M)\\rangle` is the halo profile as a function of scale, scale factor and halo mass. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. k (:obj:`float` or `array`): comoving wavenumber. a (:obj:`float`): scale factor. prof (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): halo profile. Returns: (:obj:`float` or `array`): integral values evaluated at each value of ``k``. """ self._check_mass_def(prof) self._get_ingredients(cosmo, a, get_bf=True) uk = prof.fourier(cosmo, k, self._mass, a).T return self._integrate_over_mbf(uk) def I_1_3(self, cosmo, k, a, prof, *, prof2=None, prof_2pt, prof3=None): """ Solves the integral: .. math:: I^1_3(k,a|u_2, v_1, v_2) = \\int dM\\,n(M,a)\\,b(M,a)\\, \\langle u_2(k,a|M) v_1(k',a|M) v_2(k',a|M)\\rangle, where we approximate .. math:: \\langle u_2(k,a|M) v_1(k',a|M) v_2(k', a|M)\\rangle \\sim \\langle u_2(k,a|M)\\rangle \\langle v_1(k',a|M) v_2(k', a|M)\\rangle, where :math:`n(M,a)` is the halo mass function, :math:`b(M,a)` is the halo bias, and :math:`\\langle u_2(k,a|M) v_1(k',a|M) v_2(k',a|M)\\rangle` is the 3pt halo profile as a function of scales `k` and `k'`, scale factor and halo mass. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. k (:obj:`float` or `array`): comoving wavenumber. a (:obj:`float`): scale factor. prof (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): halo profile. Returns: (:obj:`float` or `array`): integral values evaluated at each value of ``k``. Its shape will be ``(N_k, N_k)``, with ``N_k`` the size of the ``k`` array. """ # Compute mass function and halo bias # and transpose to move the M-axis last if prof2 is None: prof2 = prof if prof3 is None: prof3 = prof2 self._check_mass_def(prof, prof2, prof3) self._get_ingredients(cosmo, a, get_bf=True) uk1 = prof.fourier(cosmo, k, self._mass, a).T uk23 = prof_2pt.fourier_2pt(cosmo, k, self._mass, a, prof2, prof2=prof3).T uk = uk1[None, :, :] * uk23[:, None, :] i13 = self._integrate_over_mbf(uk) return i13 def I_0_2(self, cosmo, k, a, prof, *, prof2=None, prof_2pt): """ Solves the integral: .. math:: I^0_2(k,a|u,v) = \\int dM\\,n(M,a)\\, \\langle u(k,a|M) v(k,a|M)\\rangle, where :math:`n(M,a)` is the halo mass function, and :math:`\\langle u(k,a|M) v(k,a|M)\\rangle` is the two-point moment of the two halo profiles. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. k (:obj:`float` or `array`): comoving wavenumber. a (:obj:`float`): scale factor. prof (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): halo profile. prof2 (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): a second halo profile. If ``None``, ``prof`` will be used as ``prof2``. prof_2pt (:class:`~pyccl.halos.profiles_2pt.Profile2pt`): a profile covariance object returning the the two-point moment of the two profiles being correlated. Returns: (:obj:`float` or `array`): integral values evaluated at each value of ``k``. """ if prof2 is None: prof2 = prof self._check_mass_def(prof, prof2) self._get_ingredients(cosmo, a, get_bf=False) uk = prof_2pt.fourier_2pt(cosmo, k, self._mass, a, prof, prof2=prof2).T return self._integrate_over_mf(uk) def I_1_2(self, cosmo, k, a, prof, *, prof2=None, prof_2pt, diag=True): """ Solves the integral: .. math:: I^1_2(k,a|u,v) = \\int dM\\,n(M,a)\\,b(M,a)\\, \\langle u(k,a|M) v(k,a|M)\\rangle, where :math:`n(M,a)` is the halo mass function, :math:`b(M,a)` is the halo bias, and :math:`\\langle u(k,a|M) v(k,a|M)\\rangle` is the two-point moment of the two halo profiles. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. k (:obj:`float` or `array`): comoving wavenumber. a (:obj:`float`): scale factor. prof (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): halo profile. prof2 (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): a second halo profile. If ``None``, ``prof`` will be used as ``prof2``. prof_2pt (:class:`~pyccl.halos.profiles_2pt.Profile2pt`): a profile covariance object returning the the two-point moment of the two profiles being correlated. diag (bool): If True, both halo profiles depend on the same k. If False, they will depend on k and k', respectively. Default True. Returns: (:obj:`float` or `array`): integral values evaluated at each value of ``k``. If `diag` is True, the output will be a 1D-array; 2D-array, otherwise. """ if prof2 is None: prof2 = prof self._check_mass_def(prof, prof2) self._get_ingredients(cosmo, a, get_bf=True) uk = prof_2pt.fourier_2pt(cosmo, k, self._mass, a, prof, prof2=prof2, diag=diag) if diag is True: uk = uk.T else: uk = np.transpose(uk, axes=[1, 2, 0]) i12 = self._integrate_over_mbf(uk) return i12 def I_0_22(self, cosmo, k, a, prof, *, prof2=None, prof3=None, prof4=None, prof12_2pt, prof34_2pt=None): """ Solves the integral: .. math:: I^0_{2,2}(k_u,k_v,a|u_{1,2},v_{1,2}) = \\int dM\\,n(M,a)\\, \\langle u_1(k_u,a|M) u_2(k_u,a|M)\\rangle \\langle v_1(k_v,a|M) v_2(k_v,a|M)\\rangle, where :math:`n(M,a)` is the halo mass function, and :math:`\\langle u(k,a|M) v(k,a|M)\\rangle` is the two-point moment of the two halo profiles. Args: cosmo (:class:`~pyccl.cosmology.Cosmology`): a Cosmology object. k (:obj:`float` or `array`): comoving wavenumber. a (:obj:`float`): scale factor. prof (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): halo profile. prof2 (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): a second halo profile. If ``None``, ``prof`` will be used as ``prof2``. prof3 (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): a third halo profile. If ``None``, ``prof`` will be used as ``prof3``. prof4 (:class:`~pyccl.halos.profiles.profile_base.HaloProfile`): a fourth halo profile. If ``None``, ``prof2`` will be used as ``prof4``. prof12_2pt (:class:`~pyccl.halos.profiles_2pt.Profile2pt`): a profile covariance object returning the the two-point moment of ``prof`` and ``prof2``. prof34_2pt (:class:`~pyccl.halos.profiles_2pt.Profile2pt`): a profile covariance object returning the the two-point moment of ``prof3`` and ``prof4``. If ``None``, ``prof12_2pt`` will be used. Returns: (:obj:`float` or `array`): integral values evaluated at each value of ``k``. """ if prof3 is None: prof3 = prof if prof4 is None: prof4 = prof2 if prof34_2pt is None: prof34_2pt = prof12_2pt self._check_mass_def(prof, prof2, prof3, prof4) self._get_ingredients(cosmo, a, get_bf=False) uk12 = prof12_2pt.fourier_2pt( cosmo, k, self._mass, a, prof, prof2=prof2).T if (prof, prof2, prof12_2pt) == (prof3, prof4, prof34_2pt): # 4pt approximation of the same profile uk34 = uk12 else: uk34 = prof34_2pt.fourier_2pt( cosmo, k, self._mass, a, prof3, prof2=prof4).T return self._integrate_over_mf(uk12[None, :, :] * uk34[:, None, :])
LSSTDESCREPO_NAMECCLPATH_START.@CCL_extracted@CCL-master@pyccl@halos@halo_model.py@.PATH_END.py
{ "filename": "_style.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/barpolar/legendgrouptitle/font/_style.py", "type": "Python" }
import _plotly_utils.basevalidators class StyleValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="style", parent_name="barpolar.legendgrouptitle.font", **kwargs, ): super(StyleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), values=kwargs.pop("values", ["normal", "italic"]), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@barpolar@legendgrouptitle@font@_style.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "hpparvi/PyTransit", "repo_path": "PyTransit_extracted/PyTransit-master/README.md", "type": "Markdown" }
PyTransit ========= [![Licence](http://img.shields.io/badge/license-GPLv2-blue.svg?style=flat)](http://www.gnu.org/licenses/gpl-2.0.html) [![MNRAS](https://img.shields.io/badge/MNRAS-10.1093%2Fmnras%2Fstv894-blue.svg)](http://mnras.oxfordjournals.org/content/450/3/3233) [![arXiv](http://img.shields.io/badge/arXiv-1504.07433-blue.svg?style=flat)](http://arxiv.org/abs/1504.07433) [![ASCL](https://img.shields.io/badge/ASCL-A1505.024-blue.svg?style=flat)](http://ascl.net/1505.024) [![DOI](https://zenodo.org/badge/5871/hpparvi/PyTransit.svg)](https://zenodo.org/badge/latestdoi/5871/hpparvi/PyTransit) *PyTransit: fast and versatile exoplanet transit light curve modelling in Python.* PyTransit provides a set of optimised transit models with a unified API that makes modelling complex sets of heterogeneous light curve (nearly) as easy as modelling individual transit light curves. The models are optimised with Numba which allows for model evaluation speeds paralleling Fortran and C-implementations but with hassle-free platform-independent multithreading. The package has been under continuous development since 2009, and is described in [Parviainen (2015)](http://arxiv.org/abs/1504.07433), [Parviainen (2020a)](https://ui.adsabs.harvard.edu/abs/2020MNRAS.499.1633P/abstract), and [Parviainen & Korth (2020b)](https://ui.adsabs.harvard.edu/abs/2020MNRAS.499.3356P/abstract). ```Python from pytransit import RoadRunnerModel tm = RoadRunnerModel('quadratic') tm.set_data(times) tm.evaluate(k=0.1, ldc=[0.2, 0.1], t0=0.0, p=1.0, a=3.0, i=0.5*pi) tm.evaluate(k=[0.10, 0.12], ldc=[[0.2, 0.1], [0.5, 0.1]], t0=0.0, p=1.0, a=3.0, i=0.5*pi) tm.evaluate(k=[[0.10, 0.12], [0.11, 0.13]], ldc=[[0.2, 0.1], [0.5, 0.1],[0.4, 0.2, 0.75, 0.1]], t0=[0.0, 0.01], p=[1, 1], a=[3.0, 2.9], i=[.5*pi, .5*pi]) ``` ![](doc/source/basic_example_1.svg) ![](doc/source/basic_example_2.svg) ![](doc/source/basic_example_3.svg) ## Examples and tutorials ### EMAC Workshop introduction video [![EMAC Workshop PyTransit introduction video](video1.png)](https://youtu.be/bLnxkFNrMDQ?si=OTjr4kUGK1kkhkLC) ### RoadRunner transit model RoadRunner [(Parviainen, 2020a)](https://ui.adsabs.harvard.edu/abs/2020MNRAS.499.1633P/abstract) is a fast exoplanet transit model that can use any radially symmetric function to model stellar limb darkening while still being faster to evaluate than the analytical transit model for quadratic limb darkening. - [RRModel example 1](https://github.com/hpparvi/PyTransit/blob/dev/doc/source/notebooks/models/roadrunner/roadrunner_model_example_1.ipynb) shows how to use RoadRunner with the included limb darkening models. - [RRModel example 2](https://github.com/hpparvi/PyTransit/blob/dev/doc/source/notebooks/models/roadrunner/roadrunner_model_example_2.ipynb) shows how to use RoadRunner with your own limb darkening model. - [RRModel example 3](https://github.com/hpparvi/PyTransit/blob/dev/doc/source/notebooks/models/roadrunner/roadrunner_model_example_3.ipynb) shows how to use an LDTk-based limb darkening model LDTkM with RoadRunner. ### Transmission spectroscopy transit model Transmission spectroscopy transit model (TSModel) is a special version of the RoadRunner model dedicated to modelling transmission spectrum light curves. - [TSModel Example 1](https://github.com/hpparvi/PyTransit/blob/dev/notebooks/roadrunner/tsmodel_example_1.ipynb) ## Documentation Read the docs at [pytransit.readthedocs.io](https://pytransit.readthedocs.io). Installation ------------ ### PyPI The easiest way to install PyTransit is by using `pip` pip install pytransit ### GitHub Clone the repository from github and do the normal python package installation git clone https://github.com/hpparvi/PyTransit.git cd PyTransit pip install . Citing ------ If you use PyTransit in your reserach, please cite Parviainen, H. MNRAS 450, 3233–3238 (2015) (DOI:10.1093/mnras/stv894). or use this ready-made BibTeX entry @article{Parviainen2015, author = {Parviainen, Hannu}, doi = {10.1093/mnras/stv894}, journal = {MNRAS}, number = {April}, pages = {3233--3238}, title = {{PYTRANSIT: fast and easy exoplanet transit modelling in PYTHON}}, url = {http://mnras.oxfordjournals.org/cgi/doi/10.1093/mnras/stv894}, volume = {450}, year = {2015} } Author ------ - [Hannu Parviainen](mailto:hpparvi@gmail.com), Instituto de Astrofísica de Canarias
hpparviREPO_NAMEPyTransitPATH_START.@PyTransit_extracted@PyTransit-master@README.md@.PATH_END.py
{ "filename": "paper.md", "repo_name": "galsci/pysm", "repo_path": "pysm_extracted/pysm-main/paper/paper.md", "type": "Markdown" }
--- title: 'The Python Sky Model 3 software' tags: - cosmology - astronomy - python authors: - name: Andrea Zonca orcid: 0000-0001-6841-1058 affiliation: "1" - name: Ben Thorne orcid: 0000-0002-0457-0153 affiliation: "2" - name: Nicoletta Krachmalnicoff affiliation: "3,4,5" - name: Julian Borrill affiliation: "6,7" affiliations: - name: San Diego Supercomputer Center, University of California San Diego, San Diego, USA index: 1 - name: Department of Physics, University of California Davis, One Shields Avenue, Davis, CA 95616, USA index: 2 - name: SISSA, Via Bonomea 265, 34136 Trieste, Italy index: 3 - name: INFN, Via Valerio 2, 34127 Trieste, Italy index: 4 - name: IFPU, Via Beirut 2, 34014 Trieste, Italy index: 5 - name: Computational Cosmology Center, Lawrence Berkeley National Laboratory, Berkeley, CA 94720, USA index: 6 - name: Space Sciences Laboratory at University of California, 7 Gauss Way, Berkeley, CA 94720 index: 7 date: 22 July 2021 bibliography: paper.bib --- # Statement of Need The Cosmic Microwave Background (CMB) radiation, emitted just 370 thousand years after the Big Bang, is a pristine probe of the Early Universe. After being emitted at high temperatures, the CMB was redshifted by the subsequent 13.8 billion years of cosmic expansion, such that it is brightest at microwave frequencies today. However, our own Milky Way galaxy also emits in the microwave portion of the spectrum, obscuring our view of the CMB. Examples of this emission are thermal radiation by interstellar dust grains and synchrotron emission by relativistic electrons spiraling in magnetic fields. Cosmologists need to create synthetic maps of the CMB and of the galactic emission based on available data and on physical models that extrapolate observations to different frequencies. The resulting maps are useful to test data reduction algorithms, to understand residual systematics, to forecast maps produced by future instruments, to run Monte Carlo analysis for noise estimation, and more. # Summary The Python Sky Model (PySM) is a Python package used by Cosmic Microwave Background (CMB) experiments to simulate maps, in HEALPix [@gorski05; @healpy09] pixelization, of the various diffuse astrophysical components of Galactic emission relevant at CMB frequencies (i.e., dust, synchrotron, free-free and Anomalous Microwave Emission), as well as the CMB itself. These maps may be integrated over a given instrument bandpass and smoothed with a given instrument beam. The template emission maps used by PySM are based on Planck [@planck18] and WMAP [@wmap13] data and are noise-dominated at small scales. Therefore, PySM simulation templates are smoothed to retain the large-scale information, and then supplemented with modulated Gaussian realizations at smaller scales. This strategy allows one to simulate data at higher resolution than the input maps. PySM 2 [@pysm17], released in 2016, has become the de-facto standard for simulating Galactic emission; it is used, for example, by CMB-S4, Simons Observatory, LiteBird, PICO, CLASS, POLARBEAR, and other CMB experiments, as shown by the [80+ citations of the PySM 2 publication](https://scholar.google.com/scholar?start=0&hl=en&as_sdt=2005&sciodt=0,5&cites=16628417670342266167&scipsc=). As the resolution of upcoming experiments increases, the PySM 2 software has started to show some limitations: * Emission templates are provided at 7.9 arcminutes resolution (HEALPix $N_{side}=512$), while the next generation of CMB experiments will require sub-arcminute resolution. * The software is implemented in pure `numpy`, meaning that it has significant memory overhead and is not multi-threaded, precluding simply replacing the current templates with higher-resolution versions. * Emission templates are included in the PySM 2 Python package, which is still practical when each of the roughly 40 input maps is ~10 Megabytes, but will not be if they are over 1 Gigabyte. The solution to these issues was to reimplement PySM from scratch focusing of these features: * Reimplement all the models with the `numba` [@numba] Just-In-Time compiler for Python to reduce memory overhead and optimize performance: the whole integration loop of a template map over the frequency response of an instrument is performed in a single pass in automatically compiled and multi-threaded Python code. * Use MPI through `mpi4py` to coordinate execution of PySM 3 across multiple nodes, this allows supporting template maps at a resolution up to 0.4 arcminutes (HEALPix $N_{side}=8192$). * Rely on `libsharp` [@libsharp], a distributed implementation of spherical harmonic transforms, to smooth the maps with the instrument beam when maps are distributed over multiple nodes with MPI. * Employ the data utilities infrastructure provided by `astropy` [@astropy2013; @astropy2018] to download the input templates and cache them when requested. At this stage we strive to maintain full compatibility with PySM 2, therefore we implement the exact same astrophysical emission models with the same naming scheme. In the extensive test suite we compare the output of each PySM 3 model with the results obtained by PySM 2. # Performance As an example of the performance improvements achieved with PySM 3 over PySM 2, we run the following configuration: * An instrument with 3 channels, with different beams, and a top-hat bandpass defined numerically at 10 frequency samples. * A sky model with the simplest models of dust, synchrotron, free-free and AME [`a1,d1,s1,f1` in PySM terms]. * Execute on a 12-core Intel processor with 12 GB of RAM. The following tables shows the walltime and peak memory usage of this simulation executed at the native PySM 2 resolution of $N_{side}=512$ and at two higher resolutions: | Output $N_{side}$ | PySM 3 | PySM 2 | |-------------------|---------------|---------------| | 512 | 1m 0.7 GB | 1m40s 1.45 GB | | 1024 | 3m30s 2.3 GB | 7m20s 5.5 GB | | 2048 | 16m10s 8.5 GB | Out of memory | The models at $N_{side}=512$ have been tested to be equal given a relative tolerance of `1e-5`. At the moment it is not very useful to run at resolutions higher than $N_{side}=512$ because there is no actual template signal at smaller scales. However, this demonstrates the performance improvements that will make working with higher resolution templates possible. # Future work PySM 3 opens the way to implement a new category of models at much higher resolution. However, instead of just upgrading the current models to smaller scales, we want to also update them with the latest knowledge of Galactic emission and gather feedback from each of the numerous CMB experiments. For this reason we are collaborating with the Panexperiment Galactic Science group to lead the development of the new class of models to be included in PySM 3. # How to cite If you are using PySM 3 for your work, please cite this paper for the software itself; for the actual emission modeling please also cite the original PySM 2 paper [@pysm17]. There will be a future paper on the generation of new PySM 3 astrophysical models. # Acknowledgments * This work was supported in part by NASA grant `80NSSC18K1487`. * The software was tested, in part, on facilities run by the Scientific Computing Core of the Flatiron Institute. * This research used resources of the National Energy Research Scientific Computing Center (NERSC), a U.S. Department of Energy Office of Science User Facility located at Lawrence Berkeley National Laboratory, operated under Contract No. `DE-AC02-05CH11231`. # References
galsciREPO_NAMEpysmPATH_START.@pysm_extracted@pysm-main@paper@paper.md@.PATH_END.py
{ "filename": "pyNTHCOMP.py", "repo_name": "scotthgn/relagn", "repo_path": "relagn_extracted/relagn-main/src/python_version/pyNTHCOMP.py", "type": "Python" }
""" This was taken from https://github.com/arnauqb/qsosed/tree/master/qsosed, which in turn was taken from https://github.com/ADThomas-astro/oxaf/blob/master/oxaf.py . Credit to A.D. Thomas. Code was adapted from Xspec for https://arxiv.org/pdf/1611.05165.pdf . """ import numpy as np def donthcomp(ear, param): """ This function was adapted by ADT from the subroutine donthcomp in donthcomp.f, distributed with XSpec. Nthcomp documentation: https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/XSmodelNthcomp.html Refs: Zdziarski, Johnson & Magdziarz 1996, MNRAS, 283, 193, as extended by Zycki, Done & Smith 1999, MNRAS 309, 561 Note that the subroutine has been modified so that parameter 4 is ignored, and the seed spectrum is always a blackbody. ear: Energy vector, listing "Energy At Right" of bins (keV) param: list of parameters; see the 5 parameters listed below. The original fortran documentation for this subroutine is included below: Driver for the Comptonization code solving Kompaneets equation seed photons - (disk) blackbody reflection + Fe line with smearing Model parameters: 1: photon spectral index 2: plasma temperature in keV 3: (disk)blackbody temperature in keV 4: type of seed spectrum (0 - blackbody, 1 - diskbb) 5: redshift """ param = np.array(param) param = np.insert(param,0,0) ne = ear.size # Length of energy bin vector # Note that this model does not calculate errors. #c xth is the energy array (units m_e c^2) #c spnth is the nonthermal spectrum alone (E F_E) #c sptot is the total spectrum array (E F_E), = spref if no reflection zfactor = 1.0 + param[5] #c calculate internal source spectrum # blackbody temp, plasma temp, Gamma xth, nth, spt = _thcompton(param[3] / 511.0, param[2] / 511.0, param[1]) # The temperatures are normalized by 511 keV, the electron rest energy # Calculate normfac: xninv = 511.0 / zfactor ih = 1 xx = 1.0 / xninv while (ih < nth and xx > xth[ih]): ih = ih + 1 il = ih - 1 spp = spt[il] + (spt[ih] - spt[il]) * (xx - xth[il]) / (xth[ih] - xth[il]) normfac = 1.0 / spp #c zero arrays photar = np.zeros(ne) prim = np.zeros(ne) #c put primary into final array only if scale >= 0. j = 0 for i in range(0, ne): while (j <= nth and 511.0 * xth[j] < ear[i] * zfactor): j = j + 1 if (j <= nth): if (j > 0): jl = j - 1 prim[i] = spt[jl] + ((ear[i] / 511.0 * zfactor - xth[jl]) * (spt[jl + 1] - spt[jl]) / (xth[jl + 1] - xth[jl]) ) else: prim[i] = spt[0] for i in range(1, ne): photar[i] = (0.5 * (prim[i] / ear[i]**2 + prim[i - 1] / ear[i - 1]**2) * (ear[i] - ear[i - 1]) * normfac ) return photar def _thcompton(tempbb, theta, gamma): """ This function was adapted by ADT from the subroutine thcompton in donthcomp.f, distributed with XSpec. Nthcomp documentation: https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/XSmodelNthcomp.html Refs: Zdziarski, Johnson & Magdziarz 1996, MNRAS, 283, 193, as extended by Zycki, Done & Smith 1999, MNRAS 309, 561 The original fortran documentation for this subroutine is included below: Thermal Comptonization; solves Kompaneets eq. with some relativistic corrections. See Lightman \ Zdziarski (1987), ApJ The seed spectrum is a blackbody. version: January 96 #c input parameters: #real * 8 tempbb,theta,gamma """ #c use internally Thomson optical depth tautom = np.sqrt(2.250 + 3.0 / (theta * ((gamma + .50)**2 - 2.250))) - 1.50 # Initialise arrays dphdot = np.zeros(900); rel = np.zeros(900); c2 = np.zeros(900) sptot = np.zeros(900); bet = np.zeros(900); x = np.zeros(900) #c JMAX - # OF PHOTON ENERGIES #c delta is the 10 - log interval of the photon array. delta = 0.02 deltal = delta * np.log(10.0) xmin = 1e-4 * tempbb xmax = 40.0 * theta jmax = min(899, int(np.log10(xmax / xmin) / delta) + 1) #c X - ARRAY FOR PHOTON ENERGIES # Energy array is normalized by 511 keV, the rest energy of an electron x[:(jmax + 1)] = xmin * 10.0**(np.arange(jmax + 1) * delta) #c compute c2(x), and rel(x) arrays #c c2(x) is the relativistic correction to Kompaneets equation #c rel(x) is the Klein - Nishina cross section divided by the #c Thomson crossection for j in range(0, jmax): w = x[j] #c c2 is the Cooper's coefficient calculated at w1 #c w1 is x(j + 1 / 2) (x(i) defined up to jmax + 1) w1 = np.sqrt(x[j] * x[j + 1]) c2[j] = (w1**4 / (1.0 + 4.60 * w1 + 1.1 * w1 * w1)) if (w <= 0.05): #c use asymptotic limit for rel(x) for x less than 0.05 rel[j] = (1.0 - 2.0 * w + 26.0 * w * w * 0.2) else: z1 = (1.0 + w) / w**3 z2 = 1.0 + 2.0 * w z3 = np.log(z2) z4 = 2.0 * w * (1.0 + w) / z2 z5 = z3 / 2.0 / w z6 = (1.0 + 3.0 * w) / z2 / z2 rel[j] = (0.75 * (z1 * (z4 - z3) + z5 - z6)) #c the thermal emission spectrum jmaxth = min(900, int(np.log10(50 * tempbb / xmin) / delta)) if (jmaxth > jmax): jmaxth = jmax planck = 15.0 / (np.pi * tempbb)**4 dphdot[:jmaxth] = planck * x[:jmaxth]**2 / (np.exp(x[:jmaxth] / tempbb)-1) #c compute beta array, the probability of escape per Thomson time. #c bet evaluated for spherical geometry and nearly uniform sources. #c Between x = 0.1 and 1.0, a function flz modifies beta to allow #c the increasingly large energy change per scattering to gradually #c eliminate spatial diffusion jnr = int(np.log10(0.10 / xmin) / delta + 1) jnr = min(jnr, jmax - 1) jrel = int(np.log10(1 / xmin) / delta + 1) jrel = min(jrel, jmax) xnr = x[jnr - 1] xr = x[jrel - 1] for j in range(0, jnr - 1): taukn = tautom * rel[j] bet[j] = 1.0 / tautom / (1.0 + taukn / 3.0) for j in range(jnr - 1, jrel): taukn = tautom * rel[j] arg = (x[j] - xnr) / (xr - xnr) flz = 1 - arg bet[j] = 1.0 / tautom / (1.0 + taukn / 3.0 * flz) for j in range(jrel, jmax): bet[j] = 1.0 / tautom dphesc = _thermlc(tautom, theta, deltal, x, jmax, dphdot, bet, c2) #c the spectrum in E F_E for j in range(0, jmax - 1): sptot[j] = dphesc[j] * x[j]**2 return x, jmax, sptot def _thermlc(tautom, theta, deltal, x, jmax, dphdot, bet, c2): """ This function was adapted by ADT from the subroutine thermlc in donthcomp.f, distributed with XSpec. Nthcomp documentation: https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/XSmodelNthcomp.html Refs: Zdziarski, Johnson & Magdziarz 1996, MNRAS, 283, 193, as extended by Zycki, Done & Smith 1999, MNRAS 309, 561 The original fortran documentation for this subroutine is included below: This program computes the effects of Comptonization by nonrelativistic thermal electrons in a sphere including escape, and relativistic corrections up to photon energies of 1 MeV. the dimensionless photon energy is x = hv / (m * c * c) The input parameters and functions are: dphdot(x), the photon production rate tautom, the Thomson scattering depth theta, the temperature in units of m*c*c c2(x), and bet(x), the coefficients in the K - equation and the probability of photon escape per Thomson time, respectively, including Klein - Nishina corrections The output parameters and functions are: dphesc(x), the escaping photon density """ dphesc = np.zeros(900) # Initialise the output a = np.zeros(900); b = np.zeros(900); c = np.zeros(900) d = np.zeros(900); alp = np.zeros(900); u = np.zeros(900) g = np.zeros(900); gam = np.zeros(900) #c u(x) is the dimensionless photon occupation number c20 = tautom / deltal #c determine u #c define coefficients going into equation #c a(j) * u(j + 1) + b(j) * u(j) + c(j) * u(j - 1) = d(j) for j in range(1, jmax - 1): w1 = np.sqrt( x[j] * x[j + 1] ) w2 = np.sqrt( x[j - 1] * x[j] ) #c w1 is x(j + 1 / 2) #c w2 is x(j - 1 / 2) a[j] = -c20 * c2[j] * (theta / deltal / w1 + 0.5) t1 = -c20 * c2[j] * (0.5 - theta / deltal / w1) t2 = c20 * c2[j - 1] * (theta / deltal / w2 + 0.5) t3 = x[j]**3 * (tautom * bet[j]) b[j] = t1 + t2 + t3 c[j] = c20 * c2[j - 1] * (0.5 - theta / deltal / w2) d[j] = x[j] * dphdot[j] #c define constants going into boundary terms #c u(1) = aa * u(2) (zero flux at lowest energy) #c u(jx2) given from region 2 above x32 = np.sqrt(x[0] * x[1]) aa = (theta / deltal / x32 + 0.5) / (theta / deltal / x32 - 0.5) #c zero flux at the highest energy u[jmax - 1] = 0.0 #c invert tridiagonal matrix alp[1] = b[1] + c[1] * aa gam[1] = a[1] / alp[1] for j in range(2, jmax - 1): alp[j] = b[j] - c[j] * gam[j - 1] gam[j] = a[j] / alp[j] g[1] = d[1] / alp[1] for j in range(2, jmax - 2): g[j] = (d[j] - c[j] * g[j - 1]) / alp[j] g[jmax - 2] = (d[jmax - 2] - a[jmax - 2] * u[jmax - 1] - c[jmax - 2] * g[jmax - 3]) / alp[jmax - 2] u[jmax - 2] = g[jmax - 2] for j in range(2, jmax + 1): jj = jmax - j u[jj] = g[jj] - gam[jj] * u[jj + 1] u[0] = aa * u[1] #c compute new value of dph(x) and new value of dphesc(x) dphesc[:jmax] = x[:jmax] * x[:jmax] * u[:jmax] * bet[:jmax] * tautom return dphesc
scotthgnREPO_NAMErelagnPATH_START.@relagn_extracted@relagn-main@src@python_version@pyNTHCOMP.py@.PATH_END.py
{ "filename": "plots.py", "repo_name": "jcforbes/gidget", "repo_path": "gidget_extracted/gidget-master/py/plots.py", "type": "Python" }
from readoutput import * from balanceplot import balance, balancesig import argparse import cleanup import pdb def makeThePlots(args): if args.time is False and args.radial is False and args.scaled is False and args.mass==0 and args.balance is False: print ("Warning: you did not ask me to produce any plots! Use python plots.py -h to look at the options available.") print ("plots.py in makeThePlots: args.models: ",args.models) balanceArgs=[] AMargs=[] MONDargs=[] if(args.balance): balanceArgs=['colTr','colAccr','colsfr','dcoldt','MassLoadingFactor','Mdot','colREC', 'dsigdtLoss', 'dsigdtGI', 'dsigdtAccr', 'dsigdtSN', 'dsigdtAdv'] if(args.angularMomentum): AMargs = ['colTr','r','vPhi','dA'] if(args.quick): MONDargs = ['gbar', 'gtot', 'hGas', 'sSFRRadial', 'rxl', 'colstNormalizedKravtsov', 'colNormalizedKravtsov', 'colHI', 'colH2', 'colst', 'fH2', 'vPhi', 'sigstR', 'sigstZ', 'ageRadial', 'colsfr', 'Z', 'sig'] for modelName in args.models: print ("Beginning to analyze experiment ",modelName) theExp = Experiment(modelName) print ("Reading in the experiment keeping: ", args.vsr + balanceArgs + AMargs +MONDargs) theExp.read(args.vsr+balanceArgs+AMargs+MONDargs, keepStars=(args.stellarPops or args.quick), computeFit=args.fit, fh=args.fh) nts = int(theExp.models[0].p['Noutputs']+1) tis = [nts/5,nts/2,nts] if args.scalings or args.genzel: theExp.storeScalingRelation('MS', 'mstar','sfr') theExp.storeScalingRelation('MZR', 'mstar','integratedZ') theExp.storeScalingRelation('MFG', 'mstar','gasToStellarRatio') theExp.storeScalingRelation('TF', 'mstar','vPhiOuter') theExp.storeScalingRelation('MsTd', 'mstar','tdep') theExp.storeScalingRelation('MsTdH2', 'mstar','tDepH2') theExp.storeScalingRelation('Rg', 'mstar','halfMassGas') theExp.storeScalingRelation('mRho', 'mstar','rho1') theExp.assignIndices() for i,rankby in enumerate(args.rankby): tti=None if(args.rbz[i]>=0): tti,_ = Nearest(theExp.models[0].var['z'].sensible(),args.rbz[i]) theExp.rankBy(var=rankby,timeIndex=tti) stepsize = args.step for cb in args.colorby: if(args.time): if(args.percentiles): per = [2.5, 16, 50, 84, 97.5] theExp.timePlot(colorby=cb, perc=per,vsz=False) theExp.timePlot(colorby=cb, perc=per,vsz=True) else: theExp.timePlot(colorby=cb,vsz=False) theExp.timePlot(colorby=cb,vsz=True) if(args.radial): theExp.radialPlot(timeIndex=list(range(1,nts+1,stepsize))+[nts],variables=args.vsr,colorby=cb,logR=args.logR) if(args.scaled): theExp.radialPlot(timeIndex=list(range(1,nts+1,stepsize))+[nts],variables=args.vsr,scaleR=True,colorby=cb,logR=args.logR) #if(args.mass): # theExp.ptMovie(timeIndex=range(1,202,stepsize)+[201],prev=args.prev,colorby=cb) # theExp.ptMovie(timeIndex=range(1,202,stepsize)+[201],xvar='Mh',prev=args.prev,colorby=cb) if len(args.mass)!=0: for xv in args.mass: theExp.ptMovie(timeIndex=list(range(1,nts+1,stepsize))+[nts],xvar=xv,prev=args.prev,colorby=cb,movie=True) theExp.ptMovie(timeIndex=list(range(1,nts+1,stepsize))+[nts],xvar=xv,prev=0,colorby=cb,movie=False) if len(args.mass)!=0 and args.snapshot: for xv in args.mass: theExp.ptMovie(timeIndex=tis,xvar=xv,prev=0,colorby='t',movie=False) theExp.ptMovie(timeIndex=tis,xvar=xv,yvar=args.vsr,prev=0,colorby='t',movie=False) if(args.radial and args.snapshot): theExp.radialPlot(timeIndex=tis,variables=args.vsr,colorby='t',logR=args.logR,movie=False) if(args.scaled and args.snapshot): theExp.radialPlot(timeIndex=tis,variables=args.vsr,scaleR=True,colorby='t',logR=args.logR,movie=False) if args.snapshot: pass #theExp.hist1d(timeIndex=tis, vars=None, movie=False) # END loop over for cb in colorby # OK, this is just a test.. #theExp.ptMovie(timeIndex=tis,xvar='colsfr',yvar=['MassLoadingFactor'],prev=0,colorby='t',movie=False) #theExp.ptMovie(timeIndex=tis,xvar='hGas',yvar=['MassLoadingFactor'],prev=0,colorby='t',movie=False) #theExp.ptMovie(timeIndex=tis,xvar='Mh',yvar=['MassLoadingFactor','mstar','fg','integratedMLF','integratedZ'],prev=0,colorby='t',movie=False) #theExp.ptMovie(timeIndex=tis,xvar='x3',yvar=['MassLoadingFactor'],prev=0,colorby='t',movie=False) #theExp.ptMovie(timeIndex=tis,xvar='colsfr',yvar=['colTr','colAccr','colOut'],prev=0,colorby='t',movie=False) #theExp.ptMovie(timeIndex=tis,xvar='r',yvar=['col','colst','Z','vPhi','Q','MassLoadingFactor','hGas','colsfr','fH2','fgRadial','colTr','colAccr','colOut','equilibrium'],prev=0,colorby='t',movie=False) theExp.krumholzAnalysis() if args.genzel: theExp.globalGenzelAnalysis() if args.quick: theExp.quickCheck() if args.fraction: theExp.globalFractionAnalysis() theExp.globalFractionAnalysis(funcs=[np.std]) if args.stellarPops: theExp.plotAgeFuncs() if(args.percentiles): per = [2.5, 16, 50, 84, 97.5] if(args.radial): theExp.radialPlot(timeIndex=range(1,nts+1,stepsize)+[nts],variables=args.vsr,colorby=args.colorby[0],logR=args.logR,percentiles=per) if args.snapshot: theExp.radialPlot(timeIndex=tis,variables=args.vsr,colorby=args.colorby[0],logR=args.logR,percentiles=per,movie=False) if(args.scaled): theExp.radialPlot(timeIndex=range(1,nts+1,stepsize)+[nts],variables=args.vsr,colorby=args.colorby[0],logR=args.logR,percentiles=per,scaleR=True) if(args.balance): #balance(theExp.models,timeIndex=range(1,nts+1,stepsize)+[nts],name=modelName,sortby=args.colorby[0],logR=args.logR, ncols=5, nrows=3) balance(theExp.models,timeIndex=list(range(1,nts+1,stepsize))+[nts],name=modelName,sortby=args.colorby[0],logR=args.logR, ncols=1, nrows=1) balancesig(theExp.models,timeIndex=list(range(1,nts+1,stepsize))+[nts],name=modelName,sortby=args.colorby[0],logR=args.logR, ncols=1, nrows=1) #theExp.customPlotPPD( expensive=True) # theExp.customPlotPPD( expensive=False) if args.angularMomentum: theExp.angularMomentumAnalysis() if __name__=='__main__': parser = argparse.ArgumentParser(description='Analyze data from GIDGET experiments.') parser.add_argument('models', metavar='experiment',type=str,nargs='+', help='Each experiment specified will be constructed and analyzed. For instance, rh01 rh02 rh03 will analyze as a single Experiment any experiment matching *rh01*, then any experiment matching *rh02*, etc. All of them could be analyzed together (e.g. all the models would appear simultaneously on the same plots) by giving rh0 as an argument (this would also include rh04, rh05,...).') parser.add_argument('--step',type=int,default=3,help='Stepsize among snapshots to make movies (default: every 3rd)') parser.add_argument('--time',dest='time',action='store_true',help="Make plots vs t.") parser.set_defaults(time=False) parser.add_argument('--radial',dest='radial',action='store_true',help="Make plots vs r.") parser.set_defaults(radial=False) parser.add_argument('--scaled',dest='scaled',action='store_true',help="Make plots vs r/racc.") parser.set_defaults(scaled=False) parser.add_argument('--balance',dest='balance',action='store_true',help="Make balance plots.") parser.set_defaults(balance=False) parser.add_argument('--angularMomentum',dest='angularMomentum',action='store_true',help="Make some simple plots to try to understand angular momentum.") parser.set_defaults(angularMomentum=False) #parser.add_argument('--mass',dest='mass',action='store_true',help="Make plots vs mstar") #parser.set_defaults(mass=False) parser.add_argument('--mass',type=str,nargs='+',default=[],help='List of x- variables to use in point movies. Eg. mstar, Mh, sSFR,...') parser.add_argument('--colorby',type=str,nargs='+',default=['Mh0'],help='List of variables to color points by in vs mstar plots. Default is halo mass at z=0') oldVsrDefaults = ['colsfr','colst','NHI','sig','col','Z','fH2','MJeans','tDepRadial','tDepH2Radial','Q','Qg','Qst','fgRadial','equilibrium','colHI','colH2','vPhi','colTrPerAccr','hGas','hStars','sigstR','sigstZ', 'JColGas', 'JColStars','MassLoadingFactor'] parser.add_argument('--vsr',type=str,nargs='+',default=oldVsrDefaults,help='List of variables to plot vs mstar. Default is '+repr(oldVsrDefaults)) parser.add_argument('--prev',type=int,default=5,help='Number of previous points to plot in vsmstar movies.') parser.add_argument('--rankby',type=str,nargs='+',default=[],help='Sort the models according to these arguments.') parser.add_argument('--rbz',type=float,nargs='+',default=[],help='Sort at a particular redshift (use -1 to keep the full time information)') parser.add_argument('--logR',dest='logR',action='store_true',help="Use logarithmic radial coordinate in plots vs. r") parser.set_defaults(logR=False) parser.add_argument('--percentiles',dest='percentiles',action='store_true',help="In radial plots overplot percentiles.") parser.add_argument('--snapshot',dest='snapshot',action='store_true',help="Produce 1d histograms of all parameters and time variables.") parser.add_argument('--stellarPops',dest='stellarPops',action='store_true',help="Produce plots relating to the passive stellar pops") parser.add_argument('--genzel', dest='genzel', action='store_true',help="Produce plots relating to Genzel et al 2015") parser.add_argument('--fraction', dest='fraction', action='store_true',help="Produce heatmaps of quantites as fn of Mh and z") parser.add_argument('--fit', dest='fit', action='store_true',help="Fit the stellar column density profiles. May be time-consuming") parser.add_argument('--scalings', dest='scalings', action='store_true',help="Fit galaxy scaling relations - only really makes sense in runs where you have a decent range of masses and some source of variability between galaxies at a given mass.") parser.add_argument('--quick', dest='quick', action='store_true',help="Quickly check fit to scaling relations.") parser.add_argument('--fh', type=float, dest='fh', default=0.3, help='Fraction of accreted stars to be included in the stellar mass') args = parser.parse_args() weNeed = len(args.rankby) - len(args.rbz) if(weNeed>0): for i in range(weNeed): args.rbz.append(-1) makeThePlots(args) cleanup.moveFiles()
jcforbesREPO_NAMEgidgetPATH_START.@gidget_extracted@gidget-master@py@plots.py@.PATH_END.py
{ "filename": "_upperfence.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/box/_upperfence.py", "type": "Python" }
import _plotly_utils.basevalidators class UpperfenceValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="upperfence", parent_name="box", **kwargs): super(UpperfenceValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@box@_upperfence.py@.PATH_END.py
{ "filename": "body.py", "repo_name": "mikecokina/elisa", "repo_path": "elisa_extracted/elisa-master/src/elisa/base/body.py", "type": "Python" }
import numpy as np from typing import Dict from copy import copy from abc import ( ABCMeta, abstractmethod ) from .. utils import is_empty from .. base.spot import Spot from .. logger import getLogger from .. import ( units as u, umpy as up ) logger = getLogger('base.body') class Body(metaclass=ABCMeta): """ Abstract class that defines bodies modelled by this package. """ ID = 1 MANDATORY_KWARGS = [] OPTIONAL_KWARGS = [] ALL_KWARGS = MANDATORY_KWARGS + OPTIONAL_KWARGS def __init__(self, name: str, **kwargs): """ Properties of abstract class Body. """ # initial kwargs self.kwargs: Dict = copy(kwargs) if is_empty(name): self.name = str(Body.ID) logger.debug(f"name of class instance {self.__class__.__name__} set to {self.name}") Body.ID += 1 else: self.name = str(name) # initializing paramas to default values self.synchronicity: float = np.nan self.mass: float = np.nan self.albedo: float = np.nan self.discretization_factor: float = np.float64(up.radians(5)) self.t_eff: float = np.nan self.polar_radius: float = np.nan self._spots: Dict = dict() self.equatorial_radius: float = np.nan self.atmosphere: str = "" @abstractmethod def init(self): pass @abstractmethod def transform_input(self, *args, **kwargs): pass @property def spots(self): """ :return: Dict[int, elisa.base.spot.Spot] """ return self._spots @spots.setter def spots(self, spots): """ Order in which the spots are defined will determine the layering of the spots (spot defined as first will lay bellow any subsequently defined overlapping spot). Example of defined spots :: [ {"longitude": 90, "latitude": 58, "angular_radius": 15, "temperature_factor": 0.9}, {"longitude": 85, "latitude": 80, "angular_radius": 30, "temperature_factor": 1.05}, {"longitude": 45, "latitude": 90, "angular_radius": 30, "temperature_factor": 0.95}, ] :param spots: Iterable[Dict]; definition of spots for given object """ self._spots = {idx: Spot(**spot_meta) for idx, spot_meta in enumerate(spots)} if not is_empty(spots) else dict() for spot_idx, spot_instance in self.spots.items(): self.setup_spot_instance_discretization_factor(spot_instance, spot_idx) def has_spots(self): """ Find whether object has defined spots. :return: bool; """ return len(self._spots) > 0 def remove_spot(self, spot_index: int): """ Remove n-th spot index of object. :param spot_index: int; """ del self._spots[spot_index] def setup_spot_instance_discretization_factor(self, spot_instance, spot_index): """ Setup discretization factor for given spot instance based on defined rules. - use value of the parent star if the spot discretization factor is not defined - if spot_instance.discretization_factor > 0.5 * spot_instance.angular_diameter then factor is set to 0.5 * spot_instance.angular_diameter :param spot_instance: elisa.base.spot.Spot; :param spot_index: int; spot index (has no affect on process, used for logging) :return: elisa.base.spot.Spot; """ if is_empty(spot_instance.discretization_factor): logger.debug(f'angular density of the spot {spot_index} on {self.name} component was not supplied ' f'and discretization factor of star {self.discretization_factor} was used.') spot_instance.discretization_factor = (0.9 * self.discretization_factor * u.ARC_UNIT).value if spot_instance.discretization_factor > spot_instance.angular_radius: logger.debug(f'angular density {self.discretization_factor} of the spot {spot_index} on {self.name} ' f'component was larger than its angular radius. Therefore value of angular density was ' f'set to be equal to 0.5 * angular diameter') spot_instance.discretization_factor = spot_instance.angular_radius return spot_instance
mikecokinaREPO_NAMEelisaPATH_START.@elisa_extracted@elisa-master@src@elisa@base@body.py@.PATH_END.py
{ "filename": "obsrate_metric.md", "repo_name": "lsstdesc/sn_pipe", "repo_path": "sn_pipe_extracted/sn_pipe-master/docs/Metrics/obsrate_metric.md", "type": "Markdown" }
# ObsRate metric ## Definition This metric is an estimate of the observation rate of faint [(x1,color) = (-2.0,0.2)] using gri (default) bands. It is defined as the fraction of supernovae with minimal SNR per band. Let us suppose that we have a set of measurements of (fluxes,error fluxes): (f<sub>i</sub>,&sigma;<sub>i</sub>). Then the Signal-to-Noise Ratio (SNR) may be written, per band b: <img src="SNR.png" height="100"> In the background-dominating regime, one has: <img src="sigma_bd.png" height="100"> where f<sub>i</sub><sup>5,b</sup> is the 5-&sigma; flux related to the 5&sigma; depth (m<sub>5</sub>) by: <img src="m5_f5.png" height="130"> Since m<sub>5</sub> is given by observing conditions, it is possible to estimate SNR<sup>b>/sup> provided a flux template for supernovae is available. ## Installation of the metric package ``` python pip_sn_pack.py --action install --package=sn_metrics ``` ## Input parameters - x1 - color - band - SNRs - Li_files : list of npy files with light curves - mag_to_flux : list of npy files with mag to flux conversion This metric may be run yearly, per season or using the complete survey. ## How to run this metric - use the script [run_metrics.py](usage_run_metrics.md) ## Output analysis The analysis/display of the metric results can be done using the sn_plotters package that can be installed as follow: ``` python pip_sn_pack.py --action install --package=sn_plotters ``` The script [plot_snr_metric.py](../Plots/usage_plot_snr_metric.md) may be used to display the results.
lsstdescREPO_NAMEsn_pipePATH_START.@sn_pipe_extracted@sn_pipe-master@docs@Metrics@obsrate_metric.md@.PATH_END.py
{ "filename": "check_templates.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/docs/scripts/check_templates.py", "type": "Python" }
import json import re import sys from functools import cache from pathlib import Path from typing import Dict, Iterable, List, Union CURR_DIR = Path(__file__).parent.absolute() CLI_TEMPLATE_DIR = ( CURR_DIR.parent.parent / "libs/cli/langchain_cli/integration_template/docs" ) INFO_BY_DIR: Dict[str, Dict[str, Union[int, str]]] = { "chat": { "issue_number": 22296, }, "document_loaders": { "issue_number": 22866, }, "stores": {"issue_number": 24888}, "llms": { "issue_number": 24803, }, "text_embedding": {"issue_number": 14856}, "toolkits": {"issue_number": 24820}, "tools": {"issue_number": "TODO"}, "vectorstores": {"issue_number": 24800}, "retrievers": {"issue_number": 24908}, } @cache def _get_headers(doc_dir: str) -> Iterable[str]: """Gets all markdown headers ## and below from the integration template. Ignores headers that contain "TODO".""" ipynb_name = f"{doc_dir}.ipynb" if not (CLI_TEMPLATE_DIR / ipynb_name).exists(): raise FileNotFoundError(f"Could not find {ipynb_name} in {CLI_TEMPLATE_DIR}") with open(CLI_TEMPLATE_DIR / ipynb_name, "r") as f: nb = json.load(f) headers: List[str] = [] for cell in nb["cells"]: if cell["cell_type"] == "markdown": for line in cell["source"]: if not line.startswith("## ") or "TODO" in line: continue header = line.strip() headers.append(header) return headers def check_header_order(path: Path) -> None: if path.name.startswith("index."): # skip index pages return doc_dir = path.parent.name if doc_dir not in INFO_BY_DIR: # Skip if not a directory we care about return headers = _get_headers(doc_dir) issue_number = INFO_BY_DIR[doc_dir].get("issue_number", "nonexistent") print(f"Checking {doc_dir} page {path}") with open(path, "r") as f: doc = f.read() notfound = [] for header in headers: index = doc.find(header) if index == -1: notfound.append(header) doc = doc[index + len(header) :] if notfound: notfound_headers = "\n- ".join(notfound) raise ValueError( f"Document {path} is missing headers:" "\n- " f"{notfound_headers}" "\n\n" "Please see https://github.com/langchain-ai/langchain/issues/" f"{issue_number} for instructions on how to correctly format a " f"{doc_dir} integration page." ) def main(*new_doc_paths: Union[str, Path]) -> None: for path in new_doc_paths: path = Path(path).resolve().absolute() if CURR_DIR.parent / "docs" / "integrations" in path.parents: check_header_order(path) else: continue if __name__ == "__main__": main(*sys.argv[1:])
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@docs@scripts@check_templates.py@.PATH_END.py
{ "filename": "ktransit.py", "repo_name": "mrtommyb/ktransit", "repo_path": "ktransit_extracted/ktransit-master/ktransit/ktransit.py", "type": "Python" }
from __future__ import absolute_import import numpy as np from ._tmodtom import transitmodel class LCModel(object): def __init__(self): self.nplanets = 0 self.T0 = [] self.period = [] self.impact = [] self.rprs = [] self.ecosw = [] self.esinw = [] self.rvamp = [] self.occ = [] self.ell = [] self.alb = [] self.rvtime = [] def add_star(self, rho=1.5, ld1=0.2, ld2=0.4, ld3=0.0, ld4=0.0, dil=0.0, veloffset=0.0, zpt=0.0): """ add details of the star about which the planet(s) orbit ldX are the limb darkening parameters if only ld1 and and ld2 are non-zero a quadrativ limb darkening model is used if ld3 and ld4 are also non-zoro then a 4-parameter limb darkening law is used rho = mean stellar density in g/cc**3 dil is the proportion of the total light not coming from the target star 0.5 means thatyou ahve two stars of equal brightness """ self.rho = rho self.ldp = [ld1,ld2,ld3,ld4] self.dil = dil self.veloffset = veloffset self.zpt = zpt def update_star(self,**kwargs): [setattr(self,k,v) for k,v in kwargs.items()] def update_planet(self,pnum,**kwargs): for k,v in kwargs.items(): valarr = getattr(self,k) valarr[pnum] = v setattr(self,k,valarr) def add_planet(self,replace=None, T0=1.0, period=1.0, impact=0.1, rprs=0.1, ecosw=0.0, esinw=0.0, rvamp=0.0, occ=0.0, ell=0.0, alb=0.0): if replace == None: self.nplanets = self.nplanets + 1 pnum = self.nplanets - 1 self.add_dimention_to_planet_params() else: pnum = replace self.T0[pnum] = T0 self.period[pnum] = period self.impact[pnum] = impact self.rprs[pnum] = rprs self.ecosw[pnum] = ecosw self.esinw[pnum] = esinw self.rvamp[pnum] = rvamp self.occ[pnum] = occ self.ell[pnum] = ell self.alb[pnum] = alb def add_dimention_to_planet_params(self): self.T0 = np.r_[self.T0, 0.0] self.period = np.r_[self.period, 0.0] self.impact = np.r_[self.impact, 0.0] self.rprs = np.r_[self.rprs, 0.0] self.ecosw = np.r_[self.ecosw, 0.0] self.esinw = np.r_[self.esinw, 0.0] self.rvamp = np.r_[self.rvamp, 0.0] self.occ = np.r_[self.occ, 0.0] self.ell = np.r_[self.ell, 0.0] self.alb = np.r_[self.alb, 0.0] def add_data(self, time=np.arange(0, 10, 0.0188), itime=None, ntt=None, tobs=None, omc=None, datatype=None): """ Add data after all the planets are added!! """ self.time = time npt = len(self.time) nmax = 1500000 if itime is None: default_cadence = 1625.3 / 86400. self.itime = np.zeros(npt) + default_cadence else: self.itime = itime if ntt is None: self.ntt = np.zeros(self.nplanets) else: self.ntt = ntt if tobs is None: self.tobs = np.empty([self.nplanets, nmax]) else: self.tobs = tobs if omc is None: self.omc = np.empty([self.nplanets, nmax]) else: self.omc = omc if datatype is None: self.datatype = np.zeros(npt) else: self.datatype = datatype def add_rv(self, rvtime=None, rvitime=None): if rvtime is None: self.rvtime = np.arange( self.T0[0], 4. * self.period[0], 1.0) else: self.rvtime = rvtime if rvitime is None: default_cadence = 30. / 1440. # 30 mins self.rvitime = np.zeros_like(self.rvtime) + default_cadence else: self.rvitime = rvitime @property def transitmodel(self): """ return a transit model calling of model is transitmodel(nplanets,sol,time,itime, ntt,tobs,omc,datatype) sol is [rho,ld1,ld2,ld3,ld4, dil,veloffset,zpt,T0,per,b,rprs,ecosw,esinw, rvamp,occ,ell,alb] """ ld1,ld2,ld3,ld4 = self.ldp sol = np.zeros(8 + self.nplanets*10) sol[0:8] = [self.rho,ld1,ld2,ld3,ld4,self.dil, self.veloffset,self.zpt] sol[8:] = np.array([self.T0,self.period, self.impact,self.rprs, self.ecosw,self.esinw, self.rvamp,self.occ, self.ell,self.alb]).T.flatten() if np.shape(self.rvtime)[0] != 0: time = np.r_[self.time,self.rvtime] itime = np.r_[self.itime,self.rvitime] datatype = np.r_[ self.datatype,np.ones_like(self.rvtime)] fmod = transitmodel(self.nplanets, sol,time,itime,self.ntt, self.tobs,self.omc,datatype) nrv = np.shape(self.rvtime)[0] self._transitmodel = fmod[:-nrv] self._rvmodel = fmod[-nrv:] else: time = self.time itime = self.itime datatype = self.datatype self._transitmodel = transitmodel(self.nplanets, sol,time,itime,self.ntt, self.tobs,self.omc,datatype) self._rvmodel = None return self._transitmodel - 1.0 @property def rvmodel(self): try: return self._rvmodel except AttributeError: tmod = self.transitmodel return self._rvmodel def get_ancil_vals(self): npt = len(self.time) itime = np.zeros(self._npt) + (self.cadence) ntt = np.zeros(self._nplanets) tobs = np.empty([self._nplanets,npt]) omc = np.empty([self._nplanets,npt]) datatype = np.zeros(npt) return [itime,ntt,tobs,omc,datatype] def give_me_earth(): M = LCModel() M.add_star() M.add_planet(rprs=0.009155,period=365.25) M.add_data(time=np.arange(0,1000,0.0188)) return (M.time, M.transitmodel)
mrtommybREPO_NAMEktransitPATH_START.@ktransit_extracted@ktransit-master@ktransit@ktransit.py@.PATH_END.py
{ "filename": "test_toa_shuffle.py", "repo_name": "nanograv/PINT", "repo_path": "PINT_extracted/PINT-master/tests/test_toa_shuffle.py", "type": "Python" }
import io import os from copy import deepcopy import numpy as np import pytest from hypothesis import given from hypothesis.strategies import ( composite, permutations, ) from astropy import units as u from pinttestdata import datadir from pint import simulation, toa import pint.residuals from pint.models import get_model shuffletoas = """FORMAT 1 test 1234.0 54321 0 pks test2 888 59055 0 meerkat test3 350 59000 0 gbt """ class TOAOrderSetup: parfile = os.path.join(datadir, "NGC6440E.par") model = get_model(parfile) # fake a multi-telescope, multi-frequency data-set and make sure the results don't depend on TOA order fakes = [ simulation.make_fake_toas_uniform( 55000, 55500, 30, model=model, freq=1400 * u.MHz, obs="ao" ), simulation.make_fake_toas_uniform( 55010, 55500, 40, model=model, freq=800 * u.MHz, obs="gbt" ), simulation.make_fake_toas_uniform( 55020, 55500, 50, model=model, freq=2000 * u.MHz, obs="@" ), ] f = io.StringIO() for t in fakes: t.write_TOA_file(f) f.seek(0) t = toa.get_TOAs(f) r = pint.residuals.Residuals(t, model, subtract_mean=False) @classmethod @composite def toas_and_order(draw, cls): # note that draw must come before cls n = len(cls.t) ix = draw(permutations(np.arange(n))) return cls.t, ix @given(TOAOrderSetup.toas_and_order()) def test_shuffle_toas_residuals_match(t_and_permute): toas, ix = t_and_permute tcopy = deepcopy(toas) tcopy.table = tcopy.table[ix] rsort = pint.residuals.Residuals(tcopy, TOAOrderSetup.model, subtract_mean=False) assert np.all(TOAOrderSetup.r.time_resids[ix] == rsort.time_resids) @given(TOAOrderSetup.toas_and_order()) def test_shuffle_toas_chi2_match(t_and_permute): toas, ix = t_and_permute tcopy = deepcopy(toas) tcopy.table = tcopy.table[ix] rsort = pint.residuals.Residuals(tcopy, TOAOrderSetup.model, subtract_mean=False) # the differences seem to be related to floating point math assert np.isclose(TOAOrderSetup.r.calc_chi2(), rsort.calc_chi2(), atol=1e-14) @pytest.mark.parametrize("sortkey", ["freq", "mjd_float"]) def test_resorting_toas_residuals_match(sortkey): tcopy = deepcopy(TOAOrderSetup.t) i = np.argsort(TOAOrderSetup.t.table[sortkey]) tcopy.table = tcopy.table[i] rsort = pint.residuals.Residuals(tcopy, TOAOrderSetup.model, subtract_mean=False) assert np.all(TOAOrderSetup.r.time_resids[i] == rsort.time_resids) @pytest.mark.parametrize("sortkey", ["freq", "mjd_float"]) def test_resorting_toas_chi2_match(sortkey): tcopy = deepcopy(TOAOrderSetup.t) i = np.argsort(TOAOrderSetup.t.table[sortkey]) tcopy.table = tcopy.table[i] rsort = pint.residuals.Residuals(tcopy, TOAOrderSetup.model, subtract_mean=False) # the differences seem to be related to floating point math assert np.isclose(TOAOrderSetup.r.calc_chi2(), rsort.calc_chi2(), atol=1e-14) class TOALineOrderSetup: timfile = io.StringIO(shuffletoas) t = toa.get_TOAs(timfile) timfile.seek(0) lines = timfile.readlines() preamble = lines[0] # string any comments or blank lines to make sure the datalines correspond to the TOAs datalines = np.array( [ x for x in lines[1:] if not (x.startswith("C") or x.startswith("#") or len(x.strip()) == 0) ] ) clkcorr = t.get_flag_value("clkcorr", 0, np.float64)[0] * u.s @classmethod @composite def toas_and_order(draw, cls): # note that draw must come before cls n = len(cls.t) return draw(permutations(np.arange(n))) @given(TOALineOrderSetup.toas_and_order()) def test_shuffle_toas_clock_corr(permute): f = io.StringIO( TOALineOrderSetup.preamble + "".join([str(x) for x in TOALineOrderSetup.datalines[permute]]) ) t = toa.get_TOAs(f) clkcorr = t.get_flag_value("clkcorr", 0, np.float64)[0] * u.s assert (clkcorr == TOALineOrderSetup.clkcorr[permute]).all()
nanogravREPO_NAMEPINTPATH_START.@PINT_extracted@PINT-master@tests@test_toa_shuffle.py@.PATH_END.py
{ "filename": "_minexponent.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/histogram2dcontour/colorbar/_minexponent.py", "type": "Python" }
import _plotly_utils.basevalidators class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="minexponent", parent_name="histogram2dcontour.colorbar", **kwargs ): super(MinexponentValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), role=kwargs.pop("role", "style"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@histogram2dcontour@colorbar@_minexponent.py@.PATH_END.py
{ "filename": "errors.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/parso/py3/parso/python/errors.py", "type": "Python" }
# -*- coding: utf-8 -*- import codecs import sys import warnings import re from contextlib import contextmanager from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule from parso.python.tokenize import _get_token_collection _BLOCK_STMTS = ('if_stmt', 'while_stmt', 'for_stmt', 'try_stmt', 'with_stmt') _STAR_EXPR_PARENTS = ('testlist_star_expr', 'testlist_comp', 'exprlist') # This is the maximal block size given by python. _MAX_BLOCK_SIZE = 20 _MAX_INDENT_COUNT = 100 ALLOWED_FUTURES = ( 'nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'generator_stop', ) _COMP_FOR_TYPES = ('comp_for', 'sync_comp_for') def _get_rhs_name(node, version): type_ = node.type if type_ == "lambdef": return "lambda" elif type_ == "atom": comprehension = _get_comprehension_type(node) first, second = node.children[:2] if comprehension is not None: return comprehension elif second.type == "dictorsetmaker": if version < (3, 8): return "literal" else: if second.children[1] == ":" or second.children[0] == "**": if version < (3, 10): return "dict display" else: return "dict literal" else: return "set display" elif ( first == "(" and (second == ")" or (len(node.children) == 3 and node.children[1].type == "testlist_comp")) ): return "tuple" elif first == "(": return _get_rhs_name(_remove_parens(node), version=version) elif first == "[": return "list" elif first == "{" and second == "}": if version < (3, 10): return "dict display" else: return "dict literal" elif first == "{" and len(node.children) > 2: return "set display" elif type_ == "keyword": if "yield" in node.value: return "yield expression" if version < (3, 8): return "keyword" else: return str(node.value) elif type_ == "operator" and node.value == "...": if version < (3, 10): return "Ellipsis" else: return "ellipsis" elif type_ == "comparison": return "comparison" elif type_ in ("string", "number", "strings"): return "literal" elif type_ == "yield_expr": return "yield expression" elif type_ == "test": return "conditional expression" elif type_ in ("atom_expr", "power"): if node.children[0] == "await": return "await expression" elif node.children[-1].type == "trailer": trailer = node.children[-1] if trailer.children[0] == "(": return "function call" elif trailer.children[0] == "[": return "subscript" elif trailer.children[0] == ".": return "attribute" elif ( ("expr" in type_ and "star_expr" not in type_) # is a substring or "_test" in type_ or type_ in ("term", "factor") ): if version < (3, 10): return "operator" else: return "expression" elif type_ == "star_expr": return "starred" elif type_ == "testlist_star_expr": return "tuple" elif type_ == "fstring": return "f-string expression" return type_ # shouldn't reach here def _iter_stmts(scope): """ Iterates over all statements and splits up simple_stmt. """ for child in scope.children: if child.type == 'simple_stmt': for child2 in child.children: if child2.type == 'newline' or child2 == ';': continue yield child2 else: yield child def _get_comprehension_type(atom): first, second = atom.children[:2] if second.type == 'testlist_comp' and second.children[1].type in _COMP_FOR_TYPES: if first == '[': return 'list comprehension' else: return 'generator expression' elif second.type == 'dictorsetmaker' and second.children[-1].type in _COMP_FOR_TYPES: if second.children[1] == ':': return 'dict comprehension' else: return 'set comprehension' return None def _is_future_import(import_from): # It looks like a __future__ import that is relative is still a future # import. That feels kind of odd, but whatever. # if import_from.level != 0: # return False from_names = import_from.get_from_names() return [n.value for n in from_names] == ['__future__'] def _remove_parens(atom): """ Returns the inner part of an expression like `(foo)`. Also removes nested parens. """ try: children = atom.children except AttributeError: pass else: if len(children) == 3 and children[0] == '(': return _remove_parens(atom.children[1]) return atom def _skip_parens_bottom_up(node): """ Returns an ancestor node of an expression, skipping all levels of parens bottom-up. """ while node.parent is not None: node = node.parent if node.type != 'atom' or node.children[0] != '(': return node return None def _iter_params(parent_node): return (n for n in parent_node.children if n.type == 'param' or n.type == 'operator') def _is_future_import_first(import_from): """ Checks if the import is the first statement of a file. """ found_docstring = False for stmt in _iter_stmts(import_from.get_root_node()): if stmt.type == 'string' and not found_docstring: continue found_docstring = True if stmt == import_from: return True if stmt.type == 'import_from' and _is_future_import(stmt): continue return False def _iter_definition_exprs_from_lists(exprlist): def check_expr(child): if child.type == 'atom': if child.children[0] == '(': testlist_comp = child.children[1] if testlist_comp.type == 'testlist_comp': yield from _iter_definition_exprs_from_lists(testlist_comp) return else: # It's a paren that doesn't do anything, like 1 + (1) yield from check_expr(testlist_comp) return elif child.children[0] == '[': yield testlist_comp return yield child if exprlist.type in _STAR_EXPR_PARENTS: for child in exprlist.children[::2]: yield from check_expr(child) else: yield from check_expr(exprlist) def _get_expr_stmt_definition_exprs(expr_stmt): exprs = [] for list_ in expr_stmt.children[:-2:2]: if list_.type in ('testlist_star_expr', 'testlist'): exprs += _iter_definition_exprs_from_lists(list_) else: exprs.append(list_) return exprs def _get_for_stmt_definition_exprs(for_stmt): exprlist = for_stmt.children[1] return list(_iter_definition_exprs_from_lists(exprlist)) def _is_argument_comprehension(argument): return argument.children[1].type in _COMP_FOR_TYPES def _any_fstring_error(version, node): if version < (3, 9) or node is None: return False if node.type == "error_node": return any(child.type == "fstring_start" for child in node.children) elif node.type == "fstring": return True else: return node.search_ancestor("fstring") class _Context: def __init__(self, node, add_syntax_error, parent_context=None): self.node = node self.blocks = [] self.parent_context = parent_context self._used_name_dict = {} self._global_names = [] self._local_params_names = [] self._nonlocal_names = [] self._nonlocal_names_in_subscopes = [] self._add_syntax_error = add_syntax_error def is_async_funcdef(self): # Stupidly enough async funcdefs can have two different forms, # depending if a decorator is used or not. return self.is_function() \ and self.node.parent.type in ('async_funcdef', 'async_stmt') def is_function(self): return self.node.type == 'funcdef' def add_name(self, name): parent_type = name.parent.type if parent_type == 'trailer': # We are only interested in first level names. return if parent_type == 'global_stmt': self._global_names.append(name) elif parent_type == 'nonlocal_stmt': self._nonlocal_names.append(name) elif parent_type == 'funcdef': self._local_params_names.extend( [param.name.value for param in name.parent.get_params()] ) else: self._used_name_dict.setdefault(name.value, []).append(name) def finalize(self): """ Returns a list of nonlocal names that need to be part of that scope. """ self._analyze_names(self._global_names, 'global') self._analyze_names(self._nonlocal_names, 'nonlocal') global_name_strs = {n.value: n for n in self._global_names} for nonlocal_name in self._nonlocal_names: try: global_name = global_name_strs[nonlocal_name.value] except KeyError: continue message = "name '%s' is nonlocal and global" % global_name.value if global_name.start_pos < nonlocal_name.start_pos: error_name = global_name else: error_name = nonlocal_name self._add_syntax_error(error_name, message) nonlocals_not_handled = [] for nonlocal_name in self._nonlocal_names_in_subscopes: search = nonlocal_name.value if search in self._local_params_names: continue if search in global_name_strs or self.parent_context is None: message = "no binding for nonlocal '%s' found" % nonlocal_name.value self._add_syntax_error(nonlocal_name, message) elif not self.is_function() or \ nonlocal_name.value not in self._used_name_dict: nonlocals_not_handled.append(nonlocal_name) return self._nonlocal_names + nonlocals_not_handled def _analyze_names(self, globals_or_nonlocals, type_): def raise_(message): self._add_syntax_error(base_name, message % (base_name.value, type_)) params = [] if self.node.type == 'funcdef': params = self.node.get_params() for base_name in globals_or_nonlocals: found_global_or_nonlocal = False # Somehow Python does it the reversed way. for name in reversed(self._used_name_dict.get(base_name.value, [])): if name.start_pos > base_name.start_pos: # All following names don't have to be checked. found_global_or_nonlocal = True parent = name.parent if parent.type == 'param' and parent.name == name: # Skip those here, these definitions belong to the next # scope. continue if name.is_definition(): if parent.type == 'expr_stmt' \ and parent.children[1].type == 'annassign': if found_global_or_nonlocal: # If it's after the global the error seems to be # placed there. base_name = name raise_("annotated name '%s' can't be %s") break else: message = "name '%s' is assigned to before %s declaration" else: message = "name '%s' is used prior to %s declaration" if not found_global_or_nonlocal: raise_(message) # Only add an error for the first occurence. break for param in params: if param.name.value == base_name.value: raise_("name '%s' is parameter and %s"), @contextmanager def add_block(self, node): self.blocks.append(node) yield self.blocks.pop() def add_context(self, node): return _Context(node, self._add_syntax_error, parent_context=self) def close_child_context(self, child_context): self._nonlocal_names_in_subscopes += child_context.finalize() class ErrorFinder(Normalizer): """ Searches for errors in the syntax tree. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._error_dict = {} self.version = self.grammar.version_info def initialize(self, node): def create_context(node): if node is None: return None parent_context = create_context(node.parent) if node.type in ('classdef', 'funcdef', 'file_input'): return _Context(node, self._add_syntax_error, parent_context) return parent_context self.context = create_context(node) or _Context(node, self._add_syntax_error) self._indentation_count = 0 def visit(self, node): if node.type == 'error_node': with self.visit_node(node): # Don't need to investigate the inners of an error node. We # might find errors in there that should be ignored, because # the error node itself already shows that there's an issue. return '' return super().visit(node) @contextmanager def visit_node(self, node): self._check_type_rules(node) if node.type in _BLOCK_STMTS: with self.context.add_block(node): if len(self.context.blocks) == _MAX_BLOCK_SIZE: self._add_syntax_error(node, "too many statically nested blocks") yield return elif node.type == 'suite': self._indentation_count += 1 if self._indentation_count == _MAX_INDENT_COUNT: self._add_indentation_error(node.children[1], "too many levels of indentation") yield if node.type == 'suite': self._indentation_count -= 1 elif node.type in ('classdef', 'funcdef'): context = self.context self.context = context.parent_context self.context.close_child_context(context) def visit_leaf(self, leaf): if leaf.type == 'error_leaf': if leaf.token_type in ('INDENT', 'ERROR_DEDENT'): # Indents/Dedents itself never have a prefix. They are just # "pseudo" tokens that get removed by the syntax tree later. # Therefore in case of an error we also have to check for this. spacing = list(leaf.get_next_leaf()._split_prefix())[-1] if leaf.token_type == 'INDENT': message = 'unexpected indent' else: message = 'unindent does not match any outer indentation level' self._add_indentation_error(spacing, message) else: if leaf.value.startswith('\\'): message = 'unexpected character after line continuation character' else: match = re.match('\\w{,2}("{1,3}|\'{1,3})', leaf.value) if match is None: message = 'invalid syntax' if ( self.version >= (3, 9) and leaf.value in _get_token_collection( self.version ).always_break_tokens ): message = "f-string: " + message else: if len(match.group(1)) == 1: message = 'EOL while scanning string literal' else: message = 'EOF while scanning triple-quoted string literal' self._add_syntax_error(leaf, message) return '' elif leaf.value == ':': parent = leaf.parent if parent.type in ('classdef', 'funcdef'): self.context = self.context.add_context(parent) # The rest is rule based. return super().visit_leaf(leaf) def _add_indentation_error(self, spacing, message): self.add_issue(spacing, 903, "IndentationError: " + message) def _add_syntax_error(self, node, message): self.add_issue(node, 901, "SyntaxError: " + message) def add_issue(self, node, code, message): # Overwrite the default behavior. # Check if the issues are on the same line. line = node.start_pos[0] args = (code, message, node) self._error_dict.setdefault(line, args) def finalize(self): self.context.finalize() for code, message, node in self._error_dict.values(): self.issues.append(Issue(node, code, message)) class IndentationRule(Rule): code = 903 def _get_message(self, message, node): message = super()._get_message(message, node) return "IndentationError: " + message @ErrorFinder.register_rule(type='error_node') class _ExpectIndentedBlock(IndentationRule): message = 'expected an indented block' def get_node(self, node): leaf = node.get_next_leaf() return list(leaf._split_prefix())[-1] def is_issue(self, node): # This is the beginning of a suite that is not indented. return node.children[-1].type == 'newline' class ErrorFinderConfig(NormalizerConfig): normalizer_class = ErrorFinder class SyntaxRule(Rule): code = 901 def _get_message(self, message, node): message = super()._get_message(message, node) if ( "f-string" not in message and _any_fstring_error(self._normalizer.version, node) ): message = "f-string: " + message return "SyntaxError: " + message @ErrorFinder.register_rule(type='error_node') class _InvalidSyntaxRule(SyntaxRule): message = "invalid syntax" fstring_message = "f-string: invalid syntax" def get_node(self, node): return node.get_next_leaf() def is_issue(self, node): error = node.get_next_leaf().type != 'error_leaf' if ( error and _any_fstring_error(self._normalizer.version, node) ): self.add_issue(node, message=self.fstring_message) else: # Error leafs will be added later as an error. return error @ErrorFinder.register_rule(value='await') class _AwaitOutsideAsync(SyntaxRule): message = "'await' outside async function" def is_issue(self, leaf): return not self._normalizer.context.is_async_funcdef() def get_error_node(self, node): # Return the whole await statement. return node.parent @ErrorFinder.register_rule(value='break') class _BreakOutsideLoop(SyntaxRule): message = "'break' outside loop" def is_issue(self, leaf): in_loop = False for block in self._normalizer.context.blocks: if block.type in ('for_stmt', 'while_stmt'): in_loop = True return not in_loop @ErrorFinder.register_rule(value='continue') class _ContinueChecks(SyntaxRule): message = "'continue' not properly in loop" message_in_finally = "'continue' not supported inside 'finally' clause" def is_issue(self, leaf): in_loop = False for block in self._normalizer.context.blocks: if block.type in ('for_stmt', 'while_stmt'): in_loop = True if block.type == 'try_stmt': last_block = block.children[-3] if ( last_block == "finally" and leaf.start_pos > last_block.start_pos and self._normalizer.version < (3, 8) ): self.add_issue(leaf, message=self.message_in_finally) return False # Error already added if not in_loop: return True @ErrorFinder.register_rule(value='from') class _YieldFromCheck(SyntaxRule): message = "'yield from' inside async function" def get_node(self, leaf): return leaf.parent.parent # This is the actual yield statement. def is_issue(self, leaf): return leaf.parent.type == 'yield_arg' \ and self._normalizer.context.is_async_funcdef() @ErrorFinder.register_rule(type='name') class _NameChecks(SyntaxRule): message = 'cannot assign to __debug__' message_none = 'cannot assign to None' def is_issue(self, leaf): self._normalizer.context.add_name(leaf) if leaf.value == '__debug__' and leaf.is_definition(): return True @ErrorFinder.register_rule(type='string') class _StringChecks(SyntaxRule): if sys.version_info < (3, 10): message = "bytes can only contain ASCII literal characters." else: message = "bytes can only contain ASCII literal characters" def is_issue(self, leaf): string_prefix = leaf.string_prefix.lower() if 'b' in string_prefix \ and any(c for c in leaf.value if ord(c) > 127): # b'ä' return True if 'r' not in string_prefix: # Raw strings don't need to be checked if they have proper # escaping. payload = leaf._get_payload() if 'b' in string_prefix: payload = payload.encode('utf-8') func = codecs.escape_decode else: func = codecs.unicode_escape_decode try: with warnings.catch_warnings(): # The warnings from parsing strings are not relevant. warnings.filterwarnings('ignore') func(payload) except UnicodeDecodeError as e: self.add_issue(leaf, message='(unicode error) ' + str(e)) except ValueError as e: self.add_issue(leaf, message='(value error) ' + str(e)) @ErrorFinder.register_rule(value='*') class _StarCheck(SyntaxRule): message = "named arguments must follow bare *" def is_issue(self, leaf): params = leaf.parent if params.type == 'parameters' and params: after = params.children[params.children.index(leaf) + 1:] after = [child for child in after if child not in (',', ')') and not child.star_count] return len(after) == 0 @ErrorFinder.register_rule(value='**') class _StarStarCheck(SyntaxRule): # e.g. {**{} for a in [1]} # TODO this should probably get a better end_pos including # the next sibling of leaf. message = "dict unpacking cannot be used in dict comprehension" def is_issue(self, leaf): if leaf.parent.type == 'dictorsetmaker': comp_for = leaf.get_next_sibling().get_next_sibling() return comp_for is not None and comp_for.type in _COMP_FOR_TYPES @ErrorFinder.register_rule(value='yield') @ErrorFinder.register_rule(value='return') class _ReturnAndYieldChecks(SyntaxRule): message = "'return' with value in async generator" message_async_yield = "'yield' inside async function" def get_node(self, leaf): return leaf.parent def is_issue(self, leaf): if self._normalizer.context.node.type != 'funcdef': self.add_issue(self.get_node(leaf), message="'%s' outside function" % leaf.value) elif self._normalizer.context.is_async_funcdef() \ and any(self._normalizer.context.node.iter_yield_exprs()): if leaf.value == 'return' and leaf.parent.type == 'return_stmt': return True @ErrorFinder.register_rule(type='strings') class _BytesAndStringMix(SyntaxRule): # e.g. 's' b'' message = "cannot mix bytes and nonbytes literals" def _is_bytes_literal(self, string): if string.type == 'fstring': return False return 'b' in string.string_prefix.lower() def is_issue(self, node): first = node.children[0] first_is_bytes = self._is_bytes_literal(first) for string in node.children[1:]: if first_is_bytes != self._is_bytes_literal(string): return True @ErrorFinder.register_rule(type='import_as_names') class _TrailingImportComma(SyntaxRule): # e.g. from foo import a, message = "trailing comma not allowed without surrounding parentheses" def is_issue(self, node): if node.children[-1] == ',' and node.parent.children[-1] != ')': return True @ErrorFinder.register_rule(type='import_from') class _ImportStarInFunction(SyntaxRule): message = "import * only allowed at module level" def is_issue(self, node): return node.is_star_import() and self._normalizer.context.parent_context is not None @ErrorFinder.register_rule(type='import_from') class _FutureImportRule(SyntaxRule): message = "from __future__ imports must occur at the beginning of the file" def is_issue(self, node): if _is_future_import(node): if not _is_future_import_first(node): return True for from_name, future_name in node.get_paths(): name = future_name.value allowed_futures = list(ALLOWED_FUTURES) if self._normalizer.version >= (3, 7): allowed_futures.append('annotations') if name == 'braces': self.add_issue(node, message="not a chance") elif name == 'barry_as_FLUFL': m = "Seriously I'm not implementing this :) ~ Dave" self.add_issue(node, message=m) elif name not in allowed_futures: message = "future feature %s is not defined" % name self.add_issue(node, message=message) @ErrorFinder.register_rule(type='star_expr') class _StarExprRule(SyntaxRule): message_iterable_unpacking = "iterable unpacking cannot be used in comprehension" def is_issue(self, node): def check_delete_starred(node): while node.parent is not None: node = node.parent if node.type == 'del_stmt': return True if node.type not in (*_STAR_EXPR_PARENTS, 'atom'): return False return False if self._normalizer.version >= (3, 9): ancestor = node.parent else: ancestor = _skip_parens_bottom_up(node) # starred expression not in tuple/list/set if ancestor.type not in (*_STAR_EXPR_PARENTS, 'dictorsetmaker') \ and not (ancestor.type == 'atom' and ancestor.children[0] != '('): self.add_issue(node, message="can't use starred expression here") return if check_delete_starred(node): if self._normalizer.version >= (3, 9): self.add_issue(node, message="cannot delete starred") else: self.add_issue(node, message="can't use starred expression here") return if node.parent.type == 'testlist_comp': # [*[] for a in [1]] if node.parent.children[1].type in _COMP_FOR_TYPES: self.add_issue(node, message=self.message_iterable_unpacking) @ErrorFinder.register_rule(types=_STAR_EXPR_PARENTS) class _StarExprParentRule(SyntaxRule): def is_issue(self, node): def is_definition(node, ancestor): if ancestor is None: return False type_ = ancestor.type if type_ == 'trailer': return False if type_ == 'expr_stmt': return node.start_pos < ancestor.children[-1].start_pos return is_definition(node, ancestor.parent) if is_definition(node, node.parent): args = [c for c in node.children if c != ','] starred = [c for c in args if c.type == 'star_expr'] if len(starred) > 1: if self._normalizer.version < (3, 9): message = "two starred expressions in assignment" else: message = "multiple starred expressions in assignment" self.add_issue(starred[1], message=message) elif starred: count = args.index(starred[0]) if count >= 256: message = "too many expressions in star-unpacking assignment" self.add_issue(starred[0], message=message) @ErrorFinder.register_rule(type='annassign') class _AnnotatorRule(SyntaxRule): # True: int # {}: float message = "illegal target for annotation" def get_node(self, node): return node.parent def is_issue(self, node): type_ = None lhs = node.parent.children[0] lhs = _remove_parens(lhs) try: children = lhs.children except AttributeError: pass else: if ',' in children or lhs.type == 'atom' and children[0] == '(': type_ = 'tuple' elif lhs.type == 'atom' and children[0] == '[': type_ = 'list' trailer = children[-1] if type_ is None: if not (lhs.type == 'name' # subscript/attributes are allowed or lhs.type in ('atom_expr', 'power') and trailer.type == 'trailer' and trailer.children[0] != '('): return True else: # x, y: str message = "only single target (not %s) can be annotated" self.add_issue(lhs.parent, message=message % type_) @ErrorFinder.register_rule(type='argument') class _ArgumentRule(SyntaxRule): def is_issue(self, node): first = node.children[0] if self._normalizer.version < (3, 8): # a((b)=c) is valid in <3.8 first = _remove_parens(first) if node.children[1] == '=' and first.type != 'name': if first.type == 'lambdef': # f(lambda: 1=1) if self._normalizer.version < (3, 8): message = "lambda cannot contain assignment" else: message = 'expression cannot contain assignment, perhaps you meant "=="?' else: # f(+x=1) if self._normalizer.version < (3, 8): message = "keyword can't be an expression" else: message = 'expression cannot contain assignment, perhaps you meant "=="?' self.add_issue(first, message=message) if _is_argument_comprehension(node) and node.parent.type == 'classdef': self.add_issue(node, message='invalid syntax') @ErrorFinder.register_rule(type='nonlocal_stmt') class _NonlocalModuleLevelRule(SyntaxRule): message = "nonlocal declaration not allowed at module level" def is_issue(self, node): return self._normalizer.context.parent_context is None @ErrorFinder.register_rule(type='arglist') class _ArglistRule(SyntaxRule): @property def message(self): if self._normalizer.version < (3, 7): return "Generator expression must be parenthesized if not sole argument" else: return "Generator expression must be parenthesized" def is_issue(self, node): arg_set = set() kw_only = False kw_unpacking_only = False for argument in node.children: if argument == ',': continue if argument.type == 'argument': first = argument.children[0] if _is_argument_comprehension(argument) and len(node.children) >= 2: # a(a, b for b in c) return True if first in ('*', '**'): if first == '*': if kw_unpacking_only: # foo(**kwargs, *args) message = "iterable argument unpacking " \ "follows keyword argument unpacking" self.add_issue(argument, message=message) else: kw_unpacking_only = True else: # Is a keyword argument. kw_only = True if first.type == 'name': if first.value in arg_set: # f(x=1, x=2) message = "keyword argument repeated" if self._normalizer.version >= (3, 9): message += ": {}".format(first.value) self.add_issue(first, message=message) else: arg_set.add(first.value) else: if kw_unpacking_only: # f(**x, y) message = "positional argument follows keyword argument unpacking" self.add_issue(argument, message=message) elif kw_only: # f(x=2, y) message = "positional argument follows keyword argument" self.add_issue(argument, message=message) @ErrorFinder.register_rule(type='parameters') @ErrorFinder.register_rule(type='lambdef') class _ParameterRule(SyntaxRule): # def f(x=3, y): pass message = "non-default argument follows default argument" def is_issue(self, node): param_names = set() default_only = False star_seen = False for p in _iter_params(node): if p.type == 'operator': if p.value == '*': star_seen = True default_only = False continue if p.name.value in param_names: message = "duplicate argument '%s' in function definition" self.add_issue(p.name, message=message % p.name.value) param_names.add(p.name.value) if not star_seen: if p.default is None and not p.star_count: if default_only: return True elif p.star_count: star_seen = True default_only = False else: default_only = True @ErrorFinder.register_rule(type='try_stmt') class _TryStmtRule(SyntaxRule): message = "default 'except:' must be last" def is_issue(self, try_stmt): default_except = None for except_clause in try_stmt.children[3::3]: if except_clause in ('else', 'finally'): break if except_clause == 'except': default_except = except_clause elif default_except is not None: self.add_issue(default_except, message=self.message) @ErrorFinder.register_rule(type='fstring') class _FStringRule(SyntaxRule): _fstring_grammar = None message_expr = "f-string expression part cannot include a backslash" message_nested = "f-string: expressions nested too deeply" message_conversion = "f-string: invalid conversion character: expected 's', 'r', or 'a'" def _check_format_spec(self, format_spec, depth): self._check_fstring_contents(format_spec.children[1:], depth) def _check_fstring_expr(self, fstring_expr, depth): if depth >= 2: self.add_issue(fstring_expr, message=self.message_nested) expr = fstring_expr.children[1] if '\\' in expr.get_code(): self.add_issue(expr, message=self.message_expr) children_2 = fstring_expr.children[2] if children_2.type == 'operator' and children_2.value == '=': conversion = fstring_expr.children[3] else: conversion = children_2 if conversion.type == 'fstring_conversion': name = conversion.children[1] if name.value not in ('s', 'r', 'a'): self.add_issue(name, message=self.message_conversion) format_spec = fstring_expr.children[-2] if format_spec.type == 'fstring_format_spec': self._check_format_spec(format_spec, depth + 1) def is_issue(self, fstring): self._check_fstring_contents(fstring.children[1:-1]) def _check_fstring_contents(self, children, depth=0): for fstring_content in children: if fstring_content.type == 'fstring_expr': self._check_fstring_expr(fstring_content, depth) class _CheckAssignmentRule(SyntaxRule): def _check_assignment(self, node, is_deletion=False, is_namedexpr=False, is_aug_assign=False): error = None type_ = node.type if type_ == 'lambdef': error = 'lambda' elif type_ == 'atom': first, second = node.children[:2] error = _get_comprehension_type(node) if error is None: if second.type == 'dictorsetmaker': if self._normalizer.version < (3, 8): error = 'literal' else: if second.children[1] == ':': if self._normalizer.version < (3, 10): error = 'dict display' else: error = 'dict literal' else: error = 'set display' elif first == "{" and second == "}": if self._normalizer.version < (3, 8): error = 'literal' else: if self._normalizer.version < (3, 10): error = "dict display" else: error = "dict literal" elif first == "{" and len(node.children) > 2: if self._normalizer.version < (3, 8): error = 'literal' else: error = "set display" elif first in ('(', '['): if second.type == 'yield_expr': error = 'yield expression' elif second.type == 'testlist_comp': # ([a, b] := [1, 2]) # ((a, b) := [1, 2]) if is_namedexpr: if first == '(': error = 'tuple' elif first == '[': error = 'list' # This is not a comprehension, they were handled # further above. for child in second.children[::2]: self._check_assignment(child, is_deletion, is_namedexpr, is_aug_assign) else: # Everything handled, must be useless brackets. self._check_assignment(second, is_deletion, is_namedexpr, is_aug_assign) elif type_ == 'keyword': if node.value == "yield": error = "yield expression" elif self._normalizer.version < (3, 8): error = 'keyword' else: error = str(node.value) elif type_ == 'operator': if node.value == '...': if self._normalizer.version < (3, 10): error = 'Ellipsis' else: error = 'ellipsis' elif type_ == 'comparison': error = 'comparison' elif type_ in ('string', 'number', 'strings'): error = 'literal' elif type_ == 'yield_expr': # This one seems to be a slightly different warning in Python. message = 'assignment to yield expression not possible' self.add_issue(node, message=message) elif type_ == 'test': error = 'conditional expression' elif type_ in ('atom_expr', 'power'): if node.children[0] == 'await': error = 'await expression' elif node.children[-2] == '**': if self._normalizer.version < (3, 10): error = 'operator' else: error = 'expression' else: # Has a trailer trailer = node.children[-1] assert trailer.type == 'trailer' if trailer.children[0] == '(': error = 'function call' elif is_namedexpr and trailer.children[0] == '[': error = 'subscript' elif is_namedexpr and trailer.children[0] == '.': error = 'attribute' elif type_ == "fstring": if self._normalizer.version < (3, 8): error = 'literal' else: error = "f-string expression" elif type_ in ('testlist_star_expr', 'exprlist', 'testlist'): for child in node.children[::2]: self._check_assignment(child, is_deletion, is_namedexpr, is_aug_assign) elif ('expr' in type_ and type_ != 'star_expr' # is a substring or '_test' in type_ or type_ in ('term', 'factor')): if self._normalizer.version < (3, 10): error = 'operator' else: error = 'expression' elif type_ == "star_expr": if is_deletion: if self._normalizer.version >= (3, 9): error = "starred" else: self.add_issue(node, message="can't use starred expression here") else: if self._normalizer.version >= (3, 9): ancestor = node.parent else: ancestor = _skip_parens_bottom_up(node) if ancestor.type not in _STAR_EXPR_PARENTS and not is_aug_assign \ and not (ancestor.type == 'atom' and ancestor.children[0] == '['): message = "starred assignment target must be in a list or tuple" self.add_issue(node, message=message) self._check_assignment(node.children[1]) if error is not None: if is_namedexpr: message = 'cannot use assignment expressions with %s' % error else: cannot = "can't" if self._normalizer.version < (3, 8) else "cannot" message = ' '.join([cannot, "delete" if is_deletion else "assign to", error]) self.add_issue(node, message=message) @ErrorFinder.register_rule(type='sync_comp_for') class _CompForRule(_CheckAssignmentRule): message = "asynchronous comprehension outside of an asynchronous function" def is_issue(self, node): expr_list = node.children[1] if expr_list.type != 'expr_list': # Already handled. self._check_assignment(expr_list) return node.parent.children[0] == 'async' \ and not self._normalizer.context.is_async_funcdef() @ErrorFinder.register_rule(type='expr_stmt') class _ExprStmtRule(_CheckAssignmentRule): message = "illegal expression for augmented assignment" extended_message = "'{target}' is an " + message def is_issue(self, node): augassign = node.children[1] is_aug_assign = augassign != '=' and augassign.type != 'annassign' if self._normalizer.version <= (3, 8) or not is_aug_assign: for before_equal in node.children[:-2:2]: self._check_assignment(before_equal, is_aug_assign=is_aug_assign) if is_aug_assign: target = _remove_parens(node.children[0]) # a, a[b], a.b if target.type == "name" or ( target.type in ("atom_expr", "power") and target.children[1].type == "trailer" and target.children[-1].children[0] != "(" ): return False if self._normalizer.version <= (3, 8): return True else: self.add_issue( node, message=self.extended_message.format( target=_get_rhs_name(node.children[0], self._normalizer.version) ), ) @ErrorFinder.register_rule(type='with_item') class _WithItemRule(_CheckAssignmentRule): def is_issue(self, with_item): self._check_assignment(with_item.children[2]) @ErrorFinder.register_rule(type='del_stmt') class _DelStmtRule(_CheckAssignmentRule): def is_issue(self, del_stmt): child = del_stmt.children[1] if child.type != 'expr_list': # Already handled. self._check_assignment(child, is_deletion=True) @ErrorFinder.register_rule(type='expr_list') class _ExprListRule(_CheckAssignmentRule): def is_issue(self, expr_list): for expr in expr_list.children[::2]: self._check_assignment(expr) @ErrorFinder.register_rule(type='for_stmt') class _ForStmtRule(_CheckAssignmentRule): def is_issue(self, for_stmt): # Some of the nodes here are already used, so no else if expr_list = for_stmt.children[1] if expr_list.type != 'expr_list': # Already handled. self._check_assignment(expr_list) @ErrorFinder.register_rule(type='namedexpr_test') class _NamedExprRule(_CheckAssignmentRule): # namedexpr_test: test [':=' test] def is_issue(self, namedexpr_test): # assigned name first = namedexpr_test.children[0] def search_namedexpr_in_comp_for(node): while True: parent = node.parent if parent is None: return parent if parent.type == 'sync_comp_for' and parent.children[3] == node: return parent node = parent if search_namedexpr_in_comp_for(namedexpr_test): # [i+1 for i in (i := range(5))] # [i+1 for i in (j := range(5))] # [i+1 for i in (lambda: (j := range(5)))()] message = 'assignment expression cannot be used in a comprehension iterable expression' self.add_issue(namedexpr_test, message=message) # defined names exprlist = list() def process_comp_for(comp_for): if comp_for.type == 'sync_comp_for': comp = comp_for elif comp_for.type == 'comp_for': comp = comp_for.children[1] exprlist.extend(_get_for_stmt_definition_exprs(comp)) def search_all_comp_ancestors(node): has_ancestors = False while True: node = node.search_ancestor('testlist_comp', 'dictorsetmaker') if node is None: break for child in node.children: if child.type in _COMP_FOR_TYPES: process_comp_for(child) has_ancestors = True break return has_ancestors # check assignment expressions in comprehensions search_all = search_all_comp_ancestors(namedexpr_test) if search_all: if self._normalizer.context.node.type == 'classdef': message = 'assignment expression within a comprehension ' \ 'cannot be used in a class body' self.add_issue(namedexpr_test, message=message) namelist = [expr.value for expr in exprlist if expr.type == 'name'] if first.type == 'name' and first.value in namelist: # [i := 0 for i, j in range(5)] # [[(i := i) for j in range(5)] for i in range(5)] # [i for i, j in range(5) if True or (i := 1)] # [False and (i := 0) for i, j in range(5)] message = 'assignment expression cannot rebind ' \ 'comprehension iteration variable %r' % first.value self.add_issue(namedexpr_test, message=message) self._check_assignment(first, is_namedexpr=True)
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@parso@py3@parso@python@errors.py@.PATH_END.py
{ "filename": "TauRunner_examples.ipynb", "repo_name": "icecube/TauRunner", "repo_path": "TauRunner_extracted/TauRunner-master/examples/TauRunner_examples.ipynb", "type": "Jupyter Notebook" }
## TauRunner Welcome to the TauRunner tutorial! This software is capable of simulating neutrinos (and anti-neutrinos) of all flavors, accounting for tau regeneration and losses in the nutau channel. The output is a set of particle energies, number of interactions, angle, and particle type. The user has the option to propagate: 1. monochromatic fluxes 2. power-law fluxes 3. Any provided arbitrary flux by means of sampling from a cdf. All of these can be propagated through either: 1. a fixed angle 2. a range of angles 3. uniformly sampled angles in the sky. In terms of astrophysical bodies, we provide implementations for the Earth and Sun with capabilities of adding additional layers and changing the detector depth. In addition, we will demonstrate how to define any astrophysical object, or a slab of constant density to propagate through. All of these capabilities will be shown in the following examples. Happy running! ## Example 1: Monochromatic flux through single angle in Earth ## The main function that runs the monte carlo is called `run_MC` and required a few arguments, which we show you how to create below * `energies`: An array of initial particle energies in eV * `thetas`: A corresponding array of initial nadir angles in radians * `body`: The body which we are propagating through (Earth, Sun, custom, etc.) * `xs`: a CrossSections object which is based on a certain cross section model * `propagator`: PROPOSAL propagator object for charged lepton propagation ```python import numpy as np from taurunner.main import run_MC from taurunner.body.earth import construct_earth from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e, make_initial_thetas nevents = 5000 # number of events to simulate eini = 1e19 # initial energy in eV theta = 89.0 # incidence angle (nadir) pid = 16 # PDG MC Encoding particle ID (nutau) xs_model = "CSMS" # neutrino cross section model random_seed = 925 earth = construct_earth(layers=[(4., 1.0)]) # Make Earth object with 4km water layer xs = CrossSections(xs_model) energies = make_initial_e(nevents, eini) # Return array of initial energies in eV thetas = make_initial_thetas(nevents, theta) output = run_MC( energies, thetas, earth, xs, seed=random_seed ) ``` ```python import matplotlib.pyplot as plt pid_names = { 11: r'$e$', 12: r'$\nu_{e}$', 13: r'$\mu$', 14: r'$\nu_{\mu}$', 15: r'$\tau$', 16: r'$\nu_{\tau}$' } bins = np.logspace(12, 19, 75) zeros = output['Eout']==0. for pid in np.unique(output['PDG_Encoding']): particle_msk = np.logical_and(np.abs(output['PDG_Encoding'])==pid, ~zeros) name = pid_names[abs(pid)]ty plt.hist(output['Eout'][particle_msk], bins=bins, label=name, lw=2., histtype='step') plt.legend(frameon=False, loc=2) plt.loglog() plt.xlabel(r'$E~\left(\rm{eV}\right)$') plt.ylabel('Number') plt.show() ``` ## Example 2: Power law flux `taurunner` also provides helper functions to propagate other spectral shapes, such as power laws or pre-loaded models of cosmogenic neutrinos. Here, we are choosing to propagate an $E^{-2}$ spectrum over an entire hemisphere. There are some additional keyword arguments that allow the user to turn off tau energy losses (which are less important for more steeply inclined angles) or ignore secondary particles ```python import numpy as np from taurunner.main import run_MC from taurunner.body.earth import construct_earth from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e, make_initial_thetas nevents = 5000 # number of events to simulate pid = 16 xs_model = "CSMS" no_secondaries = True random_seed = 925 np.random.seed(random_seed) Earth = construct_earth(layers=[(4., 1.0)]) xs = CrossSections(xs_model) # Sample power-law with index -2 between 1e6 GeV and 1e12 GeV pl_exp = -2 # power law exponent e_min = 1e15 # Minimum energy to sample in eV e_max = 1e21 # Maximum energy to sample in eV energies = make_initial_e( nevents, pl_exp, e_min=e_max, e_max=e_min ) # Sample uniform in solid angle over hemisphere th_min = 0 # Minimum nadir angle to sample from th_max = 90 # Maximum nadir angle to sample from thetas = make_initial_thetas( nevents, (th_min, th_max), ) output = run_MC( energies, thetas, Earth, xs, seed=random_seed, no_secondaries=no_secondaries ) ``` ```python import matplotlib.pyplot as plt from matplotlib.colors import LogNorm zeros = output['Eout']==0. nutau_msk = np.logical_and(np.abs(output['PDG_Encoding'])==16, ~zeros) plt.hist2d( output['Eini'][nutau_msk], np.cos(np.radians(output['Theta'][nutau_msk])), bins=[ np.logspace(15., 21., 21), np.linspace(0., 1., 21) ], norm=LogNorm() ) plt.xscale('log') plt.xlabel(r'$E_{\rm{initial}}~(\rm{eV})$') plt.ylabel(r'$\cos(\theta)$') plt.title("Initial Energy Distribution") plt.show() ``` ```python from matplotlib.colors import LogNorm bins = np.logspace(12, 19, 75) zeros = output['Eout']==0. nutau_msk = np.logical_and(np.abs(output['PDG_Encoding'])==16, ~zeros) plt.hist2d( output['Eout'][nutau_msk], np.cos(np.radians(output['Theta'][nutau_msk])), bins=[np.logspace(11, 18., 21), np.linspace(0., 1., 21)], norm=LogNorm() ) plt.xscale('log') plt.xlabel(r'$E_{\rm{final}}~(\rm{eV})$') plt.ylabel(r'$\cos(\theta)$') plt.title("Final Energy Distribution") plt.show() ``` Here, it is evident that the neutrinos that were propagated through more Earth (larger $\cos(\theta)$) exit the Earth at much lower energies than the neutrinos that were able to pass through skimming trajectories undergoing few, if any, interactions We can also look at the one-dimensional energy spectra ```python zeros = output['Eout']==0. for pid in np.unique(output['PDG_Encoding']): particle_msk = np.logical_and(np.abs(output['PDG_Encoding'])==pid, ~zeros) name = pid_names[abs(pid)] plt.hist(output['Eout'][particle_msk], bins=bins, label=name, lw=2., histtype='step') plt.legend(frameon=False, loc=1) plt.loglog() plt.xlabel(r'$E$ (eV)') plt.ylabel('Number') plt.show() ``` Notice how there are only tau neutrinos because we chose to not propagate any secondary particles. ## Example 3: Propagating a custom flux through Earth `taurunner` allows the user to supply CDFs in energy to be samlped from. Here we show an example of sampling from a GZK model. An example of how to create these CDFs is given in `make_flux_CDF.ipynb` NOTE: If you downloaded the code using the versioins released on PyPI (i.e. you did not clone the github repository), then you will not have access to the default CDF, and you should instead make your own CDF using the example notebook linked above ```python import numpy as np import taurunner as tr from taurunner.main import run_MC from taurunner.body.earth import construct_earth from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e, make_initial_thetas nevents = 5000 pid = 16 xs_model = "CSMS" random_seed = 925 Earth = construct_earth(layers=[(4., 1.0)]) xs = CrossSections(xs_model) # Sample from pickled CDF pkl_f = f'{tr.__path__[0]}/resources/ahlers2010_test.pkl' # Path to pickle file with CDF to sample from np.random.seed(random_seed) energies = make_initial_e( nevents, pkl_f, ) # Sample uniform in solid angle over hemisphere th_min = 0 # Minimum nadir angle to sample from th_max = 90 # Maximum nadir angle to sample from thetas = make_initial_thetas( nevents, (th_min, th_max), ) output = run_MC( energies, thetas, Earth, xs, ) ``` ```python import matplotlib.pyplot as plt from matplotlib.colors import LogNorm bins = np.logspace(12, 19, 75) zeros = output['Eout']==0. nutau_msk = np.logical_and(np.abs(output['PDG_Encoding'])==16, ~zeros) plt.hist2d( output['Eini'][nutau_msk], np.cos(np.radians(output['Theta'][nutau_msk])), bins=[np.logspace(12., 19., 27), np.linspace(0., 1., 21)], norm=LogNorm() ) plt.xscale('log') plt.xlabel(r'$E_{\rm{initial}}$ (eV)') plt.ylabel(r'$\cos(\theta)$') plt.title("Initial Energy Distribution") plt.show() ``` ```python from matplotlib.colors import LogNorm bins = np.logspace(12, 19, 75) zeros = output['Eout']==0. nutau_msk = np.logical_and(np.abs(output['PDG_Encoding'])==16, ~zeros) plt.hist2d( output['Eout'][nutau_msk], np.cos(np.radians(output['Theta'][nutau_msk])), bins=[np.logspace(12., 19., 27), np.linspace(0., 1., 21)], norm=LogNorm() ) plt.xscale('log') plt.xlabel(r'$E_{\rm{final}}$ (eV)') plt.ylabel(r'$\cos(\theta)$') plt.title("Final Energy Distribution") plt.show() ``` ## Example 4: Radial trajectories TauRunner supports custom trajectories besides chords. TauRunner includes a radial trajectory which moves radially outward from the center of the body ```python import numpy as np from taurunner.main import run_MC from taurunner.body.earth import construct_earth from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e nevents = 5000 eini = 1e19 pid = 16 xs_model = "CSMS" Earth = construct_earth(layers=[(4., 1.0)]) # Make Earth object with 4km water layer xs = CrossSections(xs_model) energies = make_initial_e(nevents, eini) thetas = np.zeros(nevents) output = run_MC( energies, thetas, Earth, xs, ) ``` ```python import matplotlib.pyplot as plt pid_names = { 11: r'$e$', 12: r'$\nu_{e}$', 13: r'$\mu$', 14: r'$\nu_{\mu}$', 15: r'$\tau$', 16: r'$\nu_{\tau}$' } bins = np.logspace(12, 19, 75) zeros = output['Eout']==0. for pid, name in pid_names.items(): particle_msk = np.logical_and(np.abs(output['PDG_Encoding'])==pid, ~zeros) # name = pid_names[pid] plt.hist( output['Eout'][particle_msk], bins=bins, label=name, lw=2., histtype='step' ) plt.legend(frameon=False, loc=1) plt.loglog() plt.xlabel(r'$E~\left(\rm{eV}\right)$') plt.ylabel('Number') plt.show() ``` ## Example 5: Propagating through other bodies In addition to propagating neutrinos through the Earth, you can also propagate neutrinos through the Sun or through any object given a density profile ```python from taurunner.body import construct_sun from taurunner.body import Body ``` ### First, through the Sun ```python import numpy as np from taurunner.main import run_MC from taurunner.body import construct_sun from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e, make_initial_thetas, units nevents = 5000 eini = 1e13 # the sun is opaque at high energies theta = 10.0 pid = 16 xs_model = "dipole" solar_model = "HZ_Sun" # Can also be "LZ_Sun" random_seed = 925 xs = CrossSections(xs_model) energies = make_initial_e(nevents, eini) thetas = make_initial_thetas(nevents, theta) sun = construct_sun(solar_model) output = run_MC( energies, thetas, sun, xs, seed=random_seed ) ``` ```python import matplotlib.pyplot as plt bins = np.logspace(1, 3.5, 26) zeros = output['Eout']==0. pid_names = { 11: 'r$e$', 12: r'$\nu_{e}$', 13: r'$\mu$', 14: r'$\nu_{\mu}$', 15: r'$\tau$', 16: r'$\nu_{\tau}$' } for pid in reversed(range(12,17)): particle_msk = np.logical_and(np.abs(output['PDG_Encoding'])==pid, ~zeros) name = pid_names[pid] plt.hist(output['Eout'][particle_msk]/units.GeV, bins=bins, label=name, lw=2., histtype='step') plt.legend(frameon=False, loc=1) plt.loglog() plt.xlabel(r'$E~\left(\rm{GeV}\right)$') plt.ylabel('Number') plt.show() ``` ### And next, through a slab of constant density which we construct using the `Body` object and a radial trajectory ```python import numpy as np from taurunner.body import Body from taurunner.main import run_MC from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e, make_initial_thetas nevents = 5000 eini = 1e17 theta = 0 pid = 14 xs_model = "CSMS" # Make body with density 3.14 g/cm^3 and radius 1000 km body = Body(3.14, 1e3) xs = CrossSections(xs_model) energies = make_initial_e(nevents, eini) thetas = make_initial_thetas(nevents, theta) output = run_MC( energies, thetas, body, xs, flavor=pid ) ``` ```python import matplotlib.pyplot as plt bins = np.logspace(5, 19, 26) zeros = output['Eout']==0. pid_names = { 11: 'r$e$', 12: r'$\nu_{e}$', 13: r'$\mu$', 14: r'$\nu_{\mu}$', 15: r'$\tau$', 16: r'$\nu_{\tau}$' } for pid in np.unique(output['PDG_Encoding']): particle_msk = np.logical_and(output['PDG_Encoding']==pid, ~zeros) name = pid_names[abs(pid)] plt.hist(output['Eout'][particle_msk], bins=bins, label=name, lw=2., histtype='step') plt.plot() plt.xlim(1e11,1e15) plt.legend(frameon=False, loc=1) plt.loglog() plt.xlabel(r'$E$ (eV)') plt.ylabel('Number') plt.show() ``` ### And next, through a layered slab The constant density slab may be generalized to a slab of multiple layers. The densities in each layer may be positive scalars, unary functions which return positive scalars, or a potentially mixed list of such objects. In this example, we show how to accomplish this latter option. ```python import numpy as np from taurunner.body import Body from taurunner.main import run_MC from taurunner.cross_sections import CrossSections from taurunner.utils import make_initial_e, make_initial_thetas nevents = 1000 eini = 1e15 theta = 0 pid = 16 xs_model = "CSMS" # Make layered body with radius 1,000 km def density_f(x): return x**-2/4 densities = [4, density_f, 1, 0.4] boundaries = [0.25, 0.3, 0.5, 1] # Right hand boundaries of the layers last boundary should always be 1 body = Body([(d, b) for d, b in zip(densities, boundaries)], 1e3) xs = CrossSections(xs_model) energies = make_initial_e(nevents, eini) thetas = make_initial_thetas(nevents, theta) output = run_MC( energies, thetas, body, xs, ) ``` ```python import matplotlib.pyplot as plt bins = np.logspace(12.5, 19, 26) zeros = output['Eout']==0. pid_names = { 11: 'r$e$', 12: r'$\nu_{e}$', 13: r'$\mu$', 14: r'$\nu_{\mu}$', 15: r'$\tau$', 16: r'$\nu_{\tau}$' } for pid in reversed(range(12,17)): particle_msk = np.logical_and(np.abs(output['PDG_Encoding'])==pid, ~zeros) name = pid_names[pid] plt.hist(output['Eout'][particle_msk], bins=bins, label=name, lw=2., histtype='step') plt.legend(frameon=False, loc=1) plt.loglog() plt.xlabel(r'$E$ (eV)') plt.ylabel('Number') plt.show() ``` ## Example 4: Running from the command line As is described more thoroughly in the `README`, `taurunner` can also be called from the command line, an example of which is shown inline below ```python !python ../taurunner/main.py -n 20 -t 0.0 -e 1e18 ``` ```python ```
icecubeREPO_NAMETauRunnerPATH_START.@TauRunner_extracted@TauRunner-master@examples@TauRunner_examples.ipynb@.PATH_END.py
{ "filename": "nimrod.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/Pygments/py2/pygments/lexers/nimrod.py", "type": "Python" }
# -*- coding: utf-8 -*- """ pygments.lexers.nimrod ~~~~~~~~~~~~~~~~~~~~~~ Lexer for the Nim language (formerly known as Nimrod). :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, include, default from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Error __all__ = ['NimrodLexer'] class NimrodLexer(RegexLexer): """ For `Nim <http://nim-lang.org/>`_ source code. .. versionadded:: 1.5 """ name = 'Nimrod' aliases = ['nim', 'nimrod'] filenames = ['*.nim', '*.nimrod'] mimetypes = ['text/x-nim'] flags = re.MULTILINE | re.IGNORECASE | re.UNICODE def underscorize(words): newWords = [] new = "" for word in words: for ch in word: new += (ch + "_?") newWords.append(new) new = "" return "|".join(newWords) keywords = [ 'addr', 'and', 'as', 'asm', 'atomic', 'bind', 'block', 'break', 'case', 'cast', 'concept', 'const', 'continue', 'converter', 'defer', 'discard', 'distinct', 'div', 'do', 'elif', 'else', 'end', 'enum', 'except', 'export', 'finally', 'for', 'func', 'if', 'in', 'yield', 'interface', 'is', 'isnot', 'iterator', 'let', 'macro', 'method', 'mixin', 'mod', 'not', 'notin', 'object', 'of', 'or', 'out', 'proc', 'ptr', 'raise', 'ref', 'return', 'shared', 'shl', 'shr', 'static', 'template', 'try', 'tuple', 'type', 'when', 'while', 'with', 'without', 'xor' ] keywordsPseudo = [ 'nil', 'true', 'false' ] opWords = [ 'and', 'or', 'not', 'xor', 'shl', 'shr', 'div', 'mod', 'in', 'notin', 'is', 'isnot' ] types = [ 'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64', 'bool', 'char', 'range', 'array', 'seq', 'set', 'string' ] tokens = { 'root': [ (r'##.*$', String.Doc), (r'#.*$', Comment), (r'[*=><+\-/@$~&%!?|\\\[\]]', Operator), (r'\.\.|\.|,|\[\.|\.\]|\{\.|\.\}|\(\.|\.\)|\{|\}|\(|\)|:|\^|`|;', Punctuation), # Strings (r'(?:[\w]+)"', String, 'rdqs'), (r'"""', String, 'tdqs'), ('"', String, 'dqs'), # Char ("'", String.Char, 'chars'), # Keywords (r'(%s)\b' % underscorize(opWords), Operator.Word), (r'(p_?r_?o_?c_?\s)(?![(\[\]])', Keyword, 'funcname'), (r'(%s)\b' % underscorize(keywords), Keyword), (r'(%s)\b' % underscorize(['from', 'import', 'include']), Keyword.Namespace), (r'(v_?a_?r)\b', Keyword.Declaration), (r'(%s)\b' % underscorize(types), Keyword.Type), (r'(%s)\b' % underscorize(keywordsPseudo), Keyword.Pseudo), # Identifiers (r'\b((?![_\d])\w)(((?!_)\w)|(_(?!_)\w))*', Name), # Numbers (r'[0-9][0-9_]*(?=([e.]|\'f(32|64)))', Number.Float, ('float-suffix', 'float-number')), (r'0x[a-f0-9][a-f0-9_]*', Number.Hex, 'int-suffix'), (r'0b[01][01_]*', Number.Bin, 'int-suffix'), (r'0o[0-7][0-7_]*', Number.Oct, 'int-suffix'), (r'[0-9][0-9_]*', Number.Integer, 'int-suffix'), # Whitespace (r'\s+', Text), (r'.+$', Error), ], 'chars': [ (r'\\([\\abcefnrtvl"\']|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape), (r"'", String.Char, '#pop'), (r".", String.Char) ], 'strings': [ (r'(?<!\$)\$(\d+|#|\w+)+', String.Interpol), (r'[^\\\'"$\n]+', String), # quotes, dollars and backslashes must be parsed one at a time (r'[\'"\\]', String), # unhandled string formatting sign (r'\$', String) # newlines are an error (use "nl" state) ], 'dqs': [ (r'\\([\\abcefnrtvl"\']|\n|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape), (r'"', String, '#pop'), include('strings') ], 'rdqs': [ (r'"(?!")', String, '#pop'), (r'""', String.Escape), include('strings') ], 'tdqs': [ (r'"""(?!")', String, '#pop'), include('strings'), include('nl') ], 'funcname': [ (r'((?![\d_])\w)(((?!_)\w)|(_(?!_)\w))*', Name.Function, '#pop'), (r'`.+`', Name.Function, '#pop') ], 'nl': [ (r'\n', String) ], 'float-number': [ (r'\.(?!\.)[0-9_]*', Number.Float), (r'e[+-]?[0-9][0-9_]*', Number.Float), default('#pop') ], 'float-suffix': [ (r'\'f(32|64)', Number.Float), default('#pop') ], 'int-suffix': [ (r'\'i(32|64)', Number.Integer.Long), (r'\'i(8|16)', Number.Integer), default('#pop') ], }
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@Pygments@py2@pygments@lexers@nimrod.py@.PATH_END.py
{ "filename": "feature_set.py", "repo_name": "dwkim78/upsilon", "repo_path": "upsilon_extracted/upsilon-master/upsilon/extract_features/feature_set.py", "type": "Python" }
def get_feature_set(): """ Return a list of features' names. Features' name that are used to train a model and predict a class. Sorted by the names. Returns ------- feature_names : list A list of features' names. """ features = ['amplitude', 'hl_amp_ratio', 'kurtosis', 'period', 'phase_cusum', 'phase_eta', 'phi21', 'phi31', 'quartile31', 'r21', 'r31', 'shapiro_w', 'skewness', 'slope_per10', 'slope_per90', 'stetson_k'] features.sort() return features def get_feature_set_all(): """ Return a list of entire features. A set of entire features regardless of being used to train a model or predict a class. Returns ------- feature_names : list A list of features' names. """ features = get_feature_set() features.append('cusum') features.append('eta') features.append('n_points') features.append('period_SNR') features.append('period_log10FAP') features.append('period_uncertainty') features.append('weighted_mean') features.append('weighted_std') features.sort() return features if __name__ == '__main__': print(get_feature_set())
dwkim78REPO_NAMEupsilonPATH_START.@upsilon_extracted@upsilon-master@upsilon@extract_features@feature_set.py@.PATH_END.py
{ "filename": "_family.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/heatmap/colorbar/title/font/_family.py", "type": "Python" }
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", parent_name="heatmap.colorbar.title.font", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), no_blank=kwargs.pop("no_blank", True), strict=kwargs.pop("strict", True), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@heatmap@colorbar@title@font@_family.py@.PATH_END.py
{ "filename": "finecenter.py", "repo_name": "t-brandt/acorns-adi", "repo_path": "acorns-adi_extracted/acorns-adi-master/centroid/finecenter.py", "type": "Python" }
#!/usr/bin/env python # # Original filename: finecenter.py # # Author: Tim Brandt # Email: tbrandt@astro.princeton.edu # Date: May 2012 # # Summary: Interactively refine the centroid of an image sequence # #from speckle_centroid import speckle_centroid from easygui import * from pylab import * import pyfits as pyf def finecenter(flux, objname, output_dir): """ function finecenter interactively refines the centroid of an image sequence. The routine averages a sequence of frames, plots the central 80x80 pixels (0.8x0.8 arcseconds for HiCIAO) and labels the center. The user then inputs the offset, and, when satisfied, clicks 'OK'. The final image is saved in the output directory. The function takes three inputs: 1. A 3D flux array; the first index should run over frame number 2. The object name, for naming the output file. This should be a string. 3. The output directory. This should be a string, and the directory should exist and have write permissions. The function returns the user-determined offset in the centroid as [y_offset, x_offset]. """ ################################################################ # Extract, plot the central portion of the flux array. Try to # centroid between pairs of speckles (local maxima in intensity) # to form a guess as to the absolute centroid. This doesn't # always improve things; the user will soon check interactively. ################################################################ dimy, dimx = flux.shape #y, x = speckle_centroid('', flux, center=[dimy // 2, dimx // 2]) y, x = [dimy // 2, dimx // 2] dimy, dimx = flux.shape di = min(40, dimy // 2 - 1, dimx // 2 - 1) subarr = flux[dimy // 2 - di:dimy // 2 + di + 1, dimx // 2 - di:dimx // 2 + di + 1] grid = np.arange(di * 2 + 1) grid_y, grid_x = np.meshgrid(grid, grid) yc, xc = [0., 0.] while 1: ################################################################ # Plot the central part of the image with bullseye-type # annotations until the user indicates he/she is satisfied. ################################################################ r = np.sqrt((grid_y - di - y + 100 - yc)**2 + (grid_x - di - x + 100 - xc)**2) figure(figsize=(8,8)) imshow(np.sqrt(subarr), interpolation='bilinear', origin='lower') contour(grid_x, grid_y, r, [4, 4, 15, 25, 35], linewidths=(4, 1, 3, 3, 3,), colors=('k', 'm', 'k', 'k', 'k'), linestyles=('solid', 'solid', 'dashed', 'dashed', 'dashed')) plot([di + xc + x - 100], [di + y + yc - 100], color='y', marker='+', markersize=8, mew=2) axis('off') savefig(output_dir + '/' + objname + '_center_verify.png') show(block=False) clf() shift = enterbox(msg='Check/refine the pipeline absolute center.\n' + 'Enter an offset to apply in the format dx, dy.\n' + 'Graphic has dimensions ' + str(subarr.shape[0]) + ' x ' + str(subarr.shape[1]) + '.\n' + 'Click OK to keep the current center.', title='Fine Centroiding', default=str(xc) + ',' + str(yc)) try: yc_tmp = float(shift.split(',')[1]) xc_tmp = float(shift.split(',')[0]) if yc_tmp == yc and xc_tmp == xc: if ynbox(msg='Keep the center shown?', title='Fine Centroiding'): break else: yc, xc = [yc_tmp, xc_tmp] except: msgbox(msg='Invalid format, please try again.', title='Fine Centroiding') ################################################################ # Return the user-determined offset. ################################################################ return [yc + y - 100, xc + x - 100]
t-brandtREPO_NAMEacorns-adiPATH_START.@acorns-adi_extracted@acorns-adi-master@centroid@finecenter.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "nespinoza/mc-spam", "repo_path": "mc-spam_extracted/mc-spam-master/README.md", "type": "Markdown" }
# mc-spam MC-SPAM (Monte-Carlo Synthetic-Photometry/Atmosphere-Model) is an algorithm to generate limb-darkening coefficients from models that are comparable to transit photometry according to the formalism described in Espinoza & Jordan (2015), which improves the original SPAM algorithm proposed by Howarth (2011) by taking in consideration the uncertainty on the stellar and transit parameters of the system under analysis. If you use this code for your research, please consider citing Espinoza & Jordan (2015; http://arxiv.org/abs/1503.07020). DEPENDENCIES ------------ This code makes use of three important libraries: + Numpy. + Scipy. + Pyfits. All of them are open source and can be easily installed in any machine. INSTALLATION ------------ Because this code uses transit modelling to obtain the MC-SPAM limb-darkening coefficients, it needs an implementation of the Mandel & Agol (2002) transit modelling in order to run. For this, a Fortran implementation of the code is under the "main_codes" folder, which in turn is called by our Python routines. In order for this link to be made, you need to "install" the package by simply running: python install.py Which will automatically generate the needed files for the transit code to run. USAGE ----- In order to run, the code needs to know the following parameters of a given system: p: The planet-to-star radius ratio, Rp/R_*. i: The inclination of the orbit (in degrees). aR: The semi-major axis to stellar radius ratio (a/R_*) e: The eccentricity of the orbit. omega: The argument of periastron (in degrees). Teff: Effective temperature of the host star (in Kelvins) logg: Log-gravity of the host star. MH: Metallicity of the host star (~[Fe/H]). vturb: Microturbulent velocity of the host star (in km/s). These parameters can be either estimated, in which case you need the associated uncertainties, fixed or obtained through an MCMC chain. If you have any data for your system that was estimated by previous works (or from you and for which you do not have an MCMC chain), you must input it under the "estimated_parameters" folder; the "planet_data.dat" stores the parameters of the transit, while "star_data.dat" stores the parameters of the host star (note that the names of both systems must match; see the files for example inputs). If a parameter is fixed by some reason, fix their upper and lower errors to zero. If you want to use an MCMC chain for a given parameter, input any value for that parameter in the above mentioned files and modify the "get_mcspam_vals.py" file in order to input your MCMC chains (see the example under lines 76 to 83 of the "get_mcspam_vals.py" code). After all of the above is set, you can edit the options in the top part of the "get_mcspam_vals.py" file and run it by simply doing: python get_mcspam_vals.py This will then generate the MC-SPAM estimates of the model limb-darkening coefficients. OUTPUTS ------- The program will generate an output folder with a user-defined name (the default is "results"), in which a folder for each system will be created along with a mc_spam_results.dat file that will contain the 0.16, 0.5 and 0.84 quantiles (i.e., the median and the "1-sigma" errors) of the distribution of both the model and the MC-SPAM estimates of the limb-darkening coefficients. Inside each folder, the Monte-Carlo samples of both the original model and the estimated MC-SPAM limb-darkening coefficients will be saved as FITS files.
nespinozaREPO_NAMEmc-spamPATH_START.@mc-spam_extracted@mc-spam-master@README.md@.PATH_END.py
{ "filename": "_variant.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/ohlc/legendgrouptitle/font/_variant.py", "type": "Python" }
import _plotly_utils.basevalidators class VariantValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="variant", parent_name="ohlc.legendgrouptitle.font", **kwargs ): super(VariantValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), values=kwargs.pop( "values", [ "normal", "small-caps", "all-small-caps", "all-petite-caps", "petite-caps", "unicase", ], ), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@ohlc@legendgrouptitle@font@_variant.py@.PATH_END.py
{ "filename": "html.py", "repo_name": "pandas-dev/pandas", "repo_path": "pandas_extracted/pandas-main/pandas/io/html.py", "type": "Python" }
""" :mod:`pandas.io.html` is a module containing functionality for dealing with HTML IO. """ from __future__ import annotations from collections import abc import errno import numbers import os import re from re import Pattern from typing import ( TYPE_CHECKING, Literal, cast, ) from pandas._libs import lib from pandas.compat._optional import import_optional_dependency from pandas.errors import ( AbstractMethodError, EmptyDataError, ) from pandas.util._decorators import doc from pandas.util._validators import check_dtype_backend from pandas.core.dtypes.common import is_list_like from pandas import isna from pandas.core.indexes.base import Index from pandas.core.indexes.multi import MultiIndex from pandas.core.series import Series from pandas.core.shared_docs import _shared_docs from pandas.io.common import ( get_handle, is_url, stringify_path, validate_header_arg, ) from pandas.io.formats.printing import pprint_thing from pandas.io.parsers import TextParser if TYPE_CHECKING: from collections.abc import ( Iterable, Sequence, ) from pandas._typing import ( BaseBuffer, DtypeBackend, FilePath, HTMLFlavors, ReadBuffer, StorageOptions, ) from pandas import DataFrame ############# # READ HTML # ############# _RE_WHITESPACE = re.compile(r"[\r\n]+|\s{2,}") def _remove_whitespace(s: str, regex: Pattern = _RE_WHITESPACE) -> str: """ Replace extra whitespace inside of a string with a single space. Parameters ---------- s : str or unicode The string from which to remove extra whitespace. regex : re.Pattern The regular expression to use to remove extra whitespace. Returns ------- subd : str or unicode `s` with all extra whitespace replaced with a single space. """ return regex.sub(" ", s.strip()) def _get_skiprows(skiprows: int | Sequence[int] | slice | None) -> int | Sequence[int]: """ Get an iterator given an integer, slice or container. Parameters ---------- skiprows : int, slice, container The iterator to use to skip rows; can also be a slice. Raises ------ TypeError * If `skiprows` is not a slice, integer, or Container Returns ------- it : iterable A proper iterator to use to skip rows of a DataFrame. """ if isinstance(skiprows, slice): start, step = skiprows.start or 0, skiprows.step or 1 return list(range(start, skiprows.stop, step)) elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows): return cast("int | Sequence[int]", skiprows) elif skiprows is None: return 0 raise TypeError(f"{type(skiprows).__name__} is not a valid type for skipping rows") def _read( obj: FilePath | BaseBuffer, encoding: str | None, storage_options: StorageOptions | None, ) -> str | bytes: """ Try to read from a url, file or string. Parameters ---------- obj : str, unicode, path object, or file-like object Returns ------- raw_text : str """ try: with get_handle( obj, "r", encoding=encoding, storage_options=storage_options ) as handles: return handles.handle.read() except OSError as err: if not is_url(obj): raise FileNotFoundError( f"[Errno {errno.ENOENT}] {os.strerror(errno.ENOENT)}: {obj}" ) from err raise class _HtmlFrameParser: """ Base class for parsers that parse HTML into DataFrames. Parameters ---------- io : str or file-like This can be either a string path, a valid URL using the HTTP, FTP, or FILE protocols or a file-like object. match : str or regex The text to match in the document. attrs : dict List of HTML <table> element attributes to match. encoding : str Encoding to be used by parser displayed_only : bool Whether or not items with "display:none" should be ignored extract_links : {None, "all", "header", "body", "footer"} Table elements in the specified section(s) with <a> tags will have their href extracted. .. versionadded:: 1.5.0 Attributes ---------- io : str or file-like raw HTML, URL, or file-like object match : regex The text to match in the raw HTML attrs : dict-like A dictionary of valid table attributes to use to search for table elements. encoding : str Encoding to be used by parser displayed_only : bool Whether or not items with "display:none" should be ignored extract_links : {None, "all", "header", "body", "footer"} Table elements in the specified section(s) with <a> tags will have their href extracted. .. versionadded:: 1.5.0 Notes ----- To subclass this class effectively you must override the following methods: * :func:`_build_doc` * :func:`_attr_getter` * :func:`_href_getter` * :func:`_text_getter` * :func:`_parse_td` * :func:`_parse_thead_tr` * :func:`_parse_tbody_tr` * :func:`_parse_tfoot_tr` * :func:`_parse_tables` * :func:`_equals_tag` See each method's respective documentation for details on their functionality. """ def __init__( self, io: FilePath | ReadBuffer[str] | ReadBuffer[bytes], match: str | Pattern, attrs: dict[str, str] | None, encoding: str, displayed_only: bool, extract_links: Literal[None, "header", "footer", "body", "all"], storage_options: StorageOptions = None, ) -> None: self.io = io self.match = match self.attrs = attrs self.encoding = encoding self.displayed_only = displayed_only self.extract_links = extract_links self.storage_options = storage_options def parse_tables(self): """ Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables. """ tables = self._parse_tables(self._build_doc(), self.match, self.attrs) return (self._parse_thead_tbody_tfoot(table) for table in tables) def _attr_getter(self, obj, attr): """ Return the attribute value of an individual DOM node. Parameters ---------- obj : node-like A DOM node. attr : str or unicode The attribute, such as "colspan" Returns ------- str or unicode The attribute value. """ # Both lxml and BeautifulSoup have the same implementation: return obj.get(attr) def _href_getter(self, obj) -> str | None: """ Return a href if the DOM node contains a child <a> or None. Parameters ---------- obj : node-like A DOM node. Returns ------- href : str or unicode The href from the <a> child of the DOM node. """ raise AbstractMethodError(self) def _text_getter(self, obj): """ Return the text of an individual DOM node. Parameters ---------- obj : node-like A DOM node. Returns ------- text : str or unicode The text from an individual DOM node. """ raise AbstractMethodError(self) def _parse_td(self, obj): """ Return the td elements from a row element. Parameters ---------- obj : node-like A DOM <tr> node. Returns ------- list of node-like These are the elements of each row, i.e., the columns. """ raise AbstractMethodError(self) def _parse_thead_tr(self, table): """ Return the list of thead row elements from the parsed table element. Parameters ---------- table : a table element that contains zero or more thead elements. Returns ------- list of node-like These are the <tr> row elements of a table. """ raise AbstractMethodError(self) def _parse_tbody_tr(self, table): """ Return the list of tbody row elements from the parsed table element. HTML5 table bodies consist of either 0 or more <tbody> elements (which only contain <tr> elements) or 0 or more <tr> elements. This method checks for both structures. Parameters ---------- table : a table element that contains row elements. Returns ------- list of node-like These are the <tr> row elements of a table. """ raise AbstractMethodError(self) def _parse_tfoot_tr(self, table): """ Return the list of tfoot row elements from the parsed table element. Parameters ---------- table : a table element that contains row elements. Returns ------- list of node-like These are the <tr> row elements of a table. """ raise AbstractMethodError(self) def _parse_tables(self, document, match, attrs): """ Return all tables from the parsed DOM. Parameters ---------- document : the DOM from which to parse the table element. match : str or regular expression The text to search for in the DOM tree. attrs : dict A dictionary of table attributes that can be used to disambiguate multiple tables on a page. Raises ------ ValueError : `match` does not match any text in the document. Returns ------- list of node-like HTML <table> elements to be parsed into raw data. """ raise AbstractMethodError(self) def _equals_tag(self, obj, tag) -> bool: """ Return whether an individual DOM node matches a tag Parameters ---------- obj : node-like A DOM node. tag : str Tag name to be checked for equality. Returns ------- boolean Whether `obj`'s tag name is `tag` """ raise AbstractMethodError(self) def _build_doc(self): """ Return a tree-like object that can be used to iterate over the DOM. Returns ------- node-like The DOM from which to parse the table element. """ raise AbstractMethodError(self) def _parse_thead_tbody_tfoot(self, table_html): """ Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ----- Header and body are lists-of-lists. Top level list is a list of rows. Each row is a list of str text. Logic: Use <thead>, <tbody>, <tfoot> elements to identify header, body, and footer, otherwise: - Put all rows into body - Move rows from top of body to header only if all elements inside row are <th> - Move rows from bottom of body to footer only if all elements inside row are <th> """ header_rows = self._parse_thead_tr(table_html) body_rows = self._parse_tbody_tr(table_html) footer_rows = self._parse_tfoot_tr(table_html) def row_is_all_th(row): return all(self._equals_tag(t, "th") for t in self._parse_td(row)) if not header_rows: # The table has no <thead>. Move the top all-<th> rows from # body_rows to header_rows. (This is a common case because many # tables in the wild have no <thead> or <tfoot> while body_rows and row_is_all_th(body_rows[0]): header_rows.append(body_rows.pop(0)) header, rem = self._expand_colspan_rowspan(header_rows, section="header") body, rem = self._expand_colspan_rowspan( body_rows, section="body", remainder=rem, overflow=len(footer_rows) > 0, ) footer, _ = self._expand_colspan_rowspan( footer_rows, section="footer", remainder=rem, overflow=False ) return header, body, footer def _expand_colspan_rowspan( self, rows, section: Literal["header", "footer", "body"], remainder: list[tuple[int, str | tuple, int]] | None = None, overflow: bool = True, ) -> tuple[list[list], list[tuple[int, str | tuple, int]]]: """ Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s section : the section that the rows belong to (header, body or footer). remainder: list[tuple[int, str | tuple, int]] | None Any remainder from the expansion of previous section overflow: bool If true, return any partial rows as 'remainder'. If not, use up any partial rows. True by default. Returns ------- list of list Each returned row is a list of str text, or tuple (text, link) if extract_links is not None. remainder Remaining partial rows if any. If overflow is False, an empty list is returned. Notes ----- Any cell with ``rowspan`` or ``colspan`` will have its contents copied to subsequent cells. """ all_texts = [] # list of rows, each a list of str text: str | tuple remainder = remainder if remainder is not None else [] for tr in rows: texts = [] # the output for this row next_remainder = [] index = 0 tds = self._parse_td(tr) for td in tds: # Append texts from previous rows with rowspan>1 that come # before this <td> while remainder and remainder[0][0] <= index: prev_i, prev_text, prev_rowspan = remainder.pop(0) texts.append(prev_text) if prev_rowspan > 1: next_remainder.append((prev_i, prev_text, prev_rowspan - 1)) index += 1 # Append the text from this <td>, colspan times text = _remove_whitespace(self._text_getter(td)) if self.extract_links in ("all", section): href = self._href_getter(td) text = (text, href) rowspan = int(self._attr_getter(td, "rowspan") or 1) colspan = int(self._attr_getter(td, "colspan") or 1) for _ in range(colspan): texts.append(text) if rowspan > 1: next_remainder.append((index, text, rowspan - 1)) index += 1 # Append texts from previous rows at the final position for prev_i, prev_text, prev_rowspan in remainder: texts.append(prev_text) if prev_rowspan > 1: next_remainder.append((prev_i, prev_text, prev_rowspan - 1)) all_texts.append(texts) remainder = next_remainder if not overflow: # Append rows that only appear because the previous row had non-1 # rowspan while remainder: next_remainder = [] texts = [] for prev_i, prev_text, prev_rowspan in remainder: texts.append(prev_text) if prev_rowspan > 1: next_remainder.append((prev_i, prev_text, prev_rowspan - 1)) all_texts.append(texts) remainder = next_remainder return all_texts, remainder def _handle_hidden_tables(self, tbl_list, attr_name: str): """ Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of the accessor for retrieving HTML attributes Returns ------- list of node-like Return type matches `tbl_list` """ if not self.displayed_only: return tbl_list return [ x for x in tbl_list if "display:none" not in getattr(x, attr_name).get("style", "").replace(" ", "") ] class _BeautifulSoupHtml5LibFrameParser(_HtmlFrameParser): """ HTML to DataFrame parser that uses BeautifulSoup under the hood. See Also -------- pandas.io.html._HtmlFrameParser pandas.io.html._LxmlFrameParser Notes ----- Documentation strings for this class are in the base class :class:`pandas.io.html._HtmlFrameParser`. """ def _parse_tables(self, document, match, attrs): element_name = "table" tables = document.find_all(element_name, attrs=attrs) if not tables: raise ValueError("No tables found") result = [] unique_tables = set() tables = self._handle_hidden_tables(tables, "attrs") for table in tables: if self.displayed_only: for elem in table.find_all("style"): elem.decompose() for elem in table.find_all(style=re.compile(r"display:\s*none")): elem.decompose() if table not in unique_tables and table.find(string=match) is not None: result.append(table) unique_tables.add(table) if not result: raise ValueError(f"No tables found matching pattern {match.pattern!r}") return result def _href_getter(self, obj) -> str | None: a = obj.find("a", href=True) return None if not a else a["href"] def _text_getter(self, obj): return obj.text def _equals_tag(self, obj, tag) -> bool: return obj.name == tag def _parse_td(self, row): return row.find_all(("td", "th"), recursive=False) def _parse_thead_tr(self, table): return table.select("thead tr") def _parse_tbody_tr(self, table): from_tbody = table.select("tbody tr") from_root = table.find_all("tr", recursive=False) # HTML spec: at most one of these lists has content return from_tbody + from_root def _parse_tfoot_tr(self, table): return table.select("tfoot tr") def _setup_build_doc(self): raw_text = _read(self.io, self.encoding, self.storage_options) if not raw_text: raise ValueError(f"No text parsed from document: {self.io}") return raw_text def _build_doc(self): from bs4 import BeautifulSoup bdoc = self._setup_build_doc() if isinstance(bdoc, bytes) and self.encoding is not None: udoc = bdoc.decode(self.encoding) from_encoding = None else: udoc = bdoc from_encoding = self.encoding soup = BeautifulSoup(udoc, features="html5lib", from_encoding=from_encoding) for br in soup.find_all("br"): br.replace_with("\n" + br.text) return soup def _build_xpath_expr(attrs) -> str: """ Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- expr : unicode An XPath expression that checks for the given HTML attributes. """ # give class attribute as class_ because class is a python keyword if "class_" in attrs: attrs["class"] = attrs.pop("class_") s = " and ".join([f"@{k}={v!r}" for k, v in attrs.items()]) return f"[{s}]" _re_namespace = {"re": "http://exslt.org/regular-expressions"} class _LxmlFrameParser(_HtmlFrameParser): """ HTML to DataFrame parser that uses lxml under the hood. Warning ------- This parser can only handle HTTP, FTP, and FILE urls. See Also -------- _HtmlFrameParser _BeautifulSoupLxmlFrameParser Notes ----- Documentation strings for this class are in the base class :class:`_HtmlFrameParser`. """ def _href_getter(self, obj) -> str | None: href = obj.xpath(".//a/@href") return None if not href else href[0] def _text_getter(self, obj): return obj.text_content() def _parse_td(self, row): # Look for direct children only: the "row" element here may be a # <thead> or <tfoot> (see _parse_thead_tr). return row.xpath("./td|./th") def _parse_tables(self, document, match, kwargs): pattern = match.pattern # 1. check all descendants for the given pattern and only search tables # GH 49929 xpath_expr = f"//table[.//text()[re:test(., {pattern!r})]]" # if any table attributes were given build an xpath expression to # search for them if kwargs: xpath_expr += _build_xpath_expr(kwargs) tables = document.xpath(xpath_expr, namespaces=_re_namespace) tables = self._handle_hidden_tables(tables, "attrib") if self.displayed_only: for table in tables: # lxml utilizes XPATH 1.0 which does not have regex # support. As a result, we find all elements with a style # attribute and iterate them to check for display:none for elem in table.xpath(".//style"): elem.drop_tree() for elem in table.xpath(".//*[@style]"): if "display:none" in elem.attrib.get("style", "").replace(" ", ""): elem.drop_tree() if not tables: raise ValueError(f"No tables found matching regex {pattern!r}") return tables def _equals_tag(self, obj, tag) -> bool: return obj.tag == tag def _build_doc(self): """ Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet connection will fail. See Also -------- pandas.io.html._HtmlFrameParser._build_doc """ from lxml.etree import XMLSyntaxError from lxml.html import ( HTMLParser, parse, ) parser = HTMLParser(recover=True, encoding=self.encoding) if is_url(self.io): with get_handle(self.io, "r", storage_options=self.storage_options) as f: r = parse(f.handle, parser=parser) else: # try to parse the input in the simplest way try: r = parse(self.io, parser=parser) except OSError as err: raise FileNotFoundError( f"[Errno {errno.ENOENT}] {os.strerror(errno.ENOENT)}: {self.io}" ) from err try: r = r.getroot() except AttributeError: pass else: if not hasattr(r, "text_content"): raise XMLSyntaxError("no text parsed from document", 0, 0, 0) for br in r.xpath("*//br"): br.tail = "\n" + (br.tail or "") return r def _parse_thead_tr(self, table): rows = [] for thead in table.xpath(".//thead"): rows.extend(thead.xpath("./tr")) # HACK: lxml does not clean up the clearly-erroneous # <thead><th>foo</th><th>bar</th></thead>. (Missing <tr>). Add # the <thead> and _pretend_ it's a <tr>; _parse_td() will find its # children as though it's a <tr>. # # Better solution would be to use html5lib. elements_at_root = thead.xpath("./td|./th") if elements_at_root: rows.append(thead) return rows def _parse_tbody_tr(self, table): from_tbody = table.xpath(".//tbody//tr") from_root = table.xpath("./tr") # HTML spec: at most one of these lists has content return from_tbody + from_root def _parse_tfoot_tr(self, table): return table.xpath(".//tfoot//tr") def _expand_elements(body) -> None: data = [len(elem) for elem in body] lens = Series(data) lens_max = lens.max() not_max = lens[lens != lens_max] empty = [""] for ind, length in not_max.items(): body[ind] += empty * (lens_max - length) def _data_to_frame(**kwargs): head, body, foot = kwargs.pop("data") header = kwargs.pop("header") kwargs["skiprows"] = _get_skiprows(kwargs["skiprows"]) if head: body = head + body # Infer header when there is a <thead> or top <th>-only rows if header is None: if len(head) == 1: header = 0 else: # ignore all-empty-text rows header = [i for i, row in enumerate(head) if any(text for text in row)] if foot: body += foot # fill out elements of body that are "ragged" _expand_elements(body) with TextParser(body, header=header, **kwargs) as tp: return tp.read() _valid_parsers = { "lxml": _LxmlFrameParser, None: _LxmlFrameParser, "html5lib": _BeautifulSoupHtml5LibFrameParser, "bs4": _BeautifulSoupHtml5LibFrameParser, } def _parser_dispatch(flavor: HTMLFlavors | None) -> type[_HtmlFrameParser]: """ Choose the parser based on the input flavor. Parameters ---------- flavor : {{"lxml", "html5lib", "bs4"}} or None The type of parser to use. This must be a valid backend. Returns ------- cls : _HtmlFrameParser subclass The parser class based on the requested input flavor. Raises ------ ValueError * If `flavor` is not a valid backend. ImportError * If you do not have the requested `flavor` """ valid_parsers = list(_valid_parsers.keys()) if flavor not in valid_parsers: raise ValueError( f"{flavor!r} is not a valid flavor, valid flavors are {valid_parsers}" ) if flavor in ("bs4", "html5lib"): import_optional_dependency("html5lib") import_optional_dependency("bs4") else: import_optional_dependency("lxml.etree") return _valid_parsers[flavor] def _print_as_set(s) -> str: arg = ", ".join([pprint_thing(el) for el in s]) return f"{{{arg}}}" def _validate_flavor(flavor): if flavor is None: flavor = "lxml", "bs4" elif isinstance(flavor, str): flavor = (flavor,) elif isinstance(flavor, abc.Iterable): if not all(isinstance(flav, str) for flav in flavor): raise TypeError( f"Object of type {type(flavor).__name__!r} " f"is not an iterable of strings" ) else: msg = repr(flavor) if isinstance(flavor, str) else str(flavor) msg += " is not a valid flavor" raise ValueError(msg) flavor = tuple(flavor) valid_flavors = set(_valid_parsers) flavor_set = set(flavor) if not flavor_set & valid_flavors: raise ValueError( f"{_print_as_set(flavor_set)} is not a valid set of flavors, valid " f"flavors are {_print_as_set(valid_flavors)}" ) return flavor def _parse( flavor, io, match, attrs, encoding, displayed_only, extract_links, storage_options, **kwargs, ): flavor = _validate_flavor(flavor) compiled_match = re.compile(match) # you can pass a compiled regex here retained = None for flav in flavor: parser = _parser_dispatch(flav) p = parser( io, compiled_match, attrs, encoding, displayed_only, extract_links, storage_options, ) try: tables = p.parse_tables() except ValueError as caught: # if `io` is an io-like object, check if it's seekable # and try to rewind it before trying the next parser if hasattr(io, "seekable") and io.seekable(): io.seek(0) elif hasattr(io, "seekable") and not io.seekable(): # if we couldn't rewind it, let the user know raise ValueError( f"The flavor {flav} failed to parse your input. " "Since you passed a non-rewindable file " "object, we can't rewind it to try " "another parser. Try read_html() with a different flavor." ) from caught retained = caught else: break else: assert retained is not None # for mypy raise retained ret = [] for table in tables: try: df = _data_to_frame(data=table, **kwargs) # Cast MultiIndex header to an Index of tuples when extracting header # links and replace nan with None (therefore can't use mi.to_flat_index()). # This maintains consistency of selection (e.g. df.columns.str[1]) if extract_links in ("all", "header") and isinstance( df.columns, MultiIndex ): df.columns = Index( ((col[0], None if isna(col[1]) else col[1]) for col in df.columns), tupleize_cols=False, ) ret.append(df) except EmptyDataError: # empty table continue return ret @doc(storage_options=_shared_docs["storage_options"]) def read_html( io: FilePath | ReadBuffer[str], *, match: str | Pattern = ".+", flavor: HTMLFlavors | Sequence[HTMLFlavors] | None = None, header: int | Sequence[int] | None = None, index_col: int | Sequence[int] | None = None, skiprows: int | Sequence[int] | slice | None = None, attrs: dict[str, str] | None = None, parse_dates: bool = False, thousands: str | None = ",", encoding: str | None = None, decimal: str = ".", converters: dict | None = None, na_values: Iterable[object] | None = None, keep_default_na: bool = True, displayed_only: bool = True, extract_links: Literal[None, "header", "footer", "body", "all"] = None, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, storage_options: StorageOptions = None, ) -> list[DataFrame]: r""" Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str, path object, or file-like object String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``read()`` function. The string can represent a URL. Note that lxml only accepts the http, ftp and file url protocols. If you have a URL that starts with ``'https'`` you might try removing the ``'s'``. .. deprecated:: 2.1.0 Passing html literal strings is deprecated. Wrap literal string/bytes input in ``io.StringIO``/``io.BytesIO`` instead. match : str or compiled regular expression, optional The set of tables containing text matching this regex or string will be returned. Unless the HTML is extremely simple you will probably need to pass a non-empty string here. Defaults to '.+' (match any non-empty string). The default value will return all tables contained on a page. This value is converted to a regular expression so that there is consistent behavior between Beautiful Soup and lxml. flavor : {{"lxml", "html5lib", "bs4"}} or list-like, optional The parsing engine (or list of parsing engines) to use. 'bs4' and 'html5lib' are synonymous with each other, they are both there for backwards compatibility. The default of ``None`` tries to use ``lxml`` to parse and if that fails it falls back on ``bs4`` + ``html5lib``. header : int or list-like, optional The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to make the columns headers. index_col : int or list-like, optional The column (or list of columns) to use to create the index. skiprows : int, list-like or slice, optional Number of rows to skip after parsing the column integer. 0-based. If a sequence of integers or a slice is given, will skip the rows indexed by that sequence. Note that a single element sequence means 'skip the nth row' whereas an integer means 'skip n rows'. attrs : dict, optional This is a dictionary of attributes that you can pass to use to identify the table in the HTML. These are not checked for validity before being passed to lxml or Beautiful Soup. However, these attributes must be valid HTML table attributes to work correctly. For example, :: attrs = {{"id": "table"}} is a valid attribute dictionary because the 'id' HTML tag attribute is a valid HTML attribute for *any* HTML tag as per `this document <https://html.spec.whatwg.org/multipage/dom.html#global-attributes>`__. :: attrs = {{"asdf": "table"}} is *not* a valid attribute dictionary because 'asdf' is not a valid HTML attribute even if it is a valid XML attribute. Valid HTML 4.01 table attributes can be found `here <http://www.w3.org/TR/REC-html40/struct/tables.html#h-11.2>`__. A working draft of the HTML 5 spec can be found `here <https://html.spec.whatwg.org/multipage/tables.html>`__. It contains the latest information on table attributes for the modern web. parse_dates : bool, optional See :func:`~read_csv` for more details. thousands : str, optional Separator to use to parse thousands. Defaults to ``','``. encoding : str, optional The encoding used to decode the web page. Defaults to ``None``.``None`` preserves the previous encoding behavior, which depends on the underlying parser library (e.g., the parser library will try to use the encoding provided by the document). decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). converters : dict, default None Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the cell (not column) content, and return the transformed content. na_values : iterable, default None Custom NA values. keep_default_na : bool, default True If na_values are specified and keep_default_na is False the default NaN values are overridden, otherwise they're appended to. displayed_only : bool, default True Whether elements with "display: none" should be parsed. extract_links : {{None, "all", "header", "body", "footer"}} Table elements in the specified section(s) with <a> tags will have their href extracted. .. versionadded:: 1.5.0 dtype_backend : {{'numpy_nullable', 'pyarrow'}} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame` .. versionadded:: 2.0 {storage_options} .. versionadded:: 2.1.0 Returns ------- dfs A list of DataFrames. See Also -------- read_csv : Read a comma-separated values (csv) file into DataFrame. Notes ----- Before using this function you should read the :ref:`gotchas about the HTML parsing libraries <io.html.gotchas>`. Expect to do some cleanup after you call this function. For example, you might need to manually assign column names if the column names are converted to NaN when you pass the `header=0` argument. We try to assume as little as possible about the structure of the table and push the idiosyncrasies of the HTML contained in the table to the user. This function searches for ``<table>`` elements and only for ``<tr>`` and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>`` element in the table. ``<td>`` stands for "table data". This function attempts to properly handle ``colspan`` and ``rowspan`` attributes. If the function has a ``<thead>`` argument, it is used to construct the header, otherwise the function attempts to find the header within the body (by putting rows with only ``<th>`` elements into the header). Similar to :func:`~read_csv` the `header` argument is applied **after** `skiprows` is applied. This function will *always* return a list of :class:`DataFrame` *or* it will fail, i.e., it will *not* return an empty list, save for some rare cases. It might return an empty list in case of inputs with single row and ``<td>`` containing only whitespaces. Examples -------- See the :ref:`read_html documentation in the IO section of the docs <io.read_html>` for some examples of reading in HTML tables. """ # Type check here. We don't want to parse only to fail because of an # invalid value of an integer skiprows. if isinstance(skiprows, numbers.Integral) and skiprows < 0: raise ValueError( "cannot skip rows starting from the end of the " "data (you passed a negative value)" ) if extract_links not in [None, "header", "footer", "body", "all"]: raise ValueError( "`extract_links` must be one of " '{None, "header", "footer", "body", "all"}, got ' f'"{extract_links}"' ) validate_header_arg(header) check_dtype_backend(dtype_backend) io = stringify_path(io) return _parse( flavor=flavor, io=io, match=match, header=header, index_col=index_col, skiprows=skiprows, parse_dates=parse_dates, thousands=thousands, attrs=attrs, encoding=encoding, decimal=decimal, converters=converters, na_values=na_values, keep_default_na=keep_default_na, displayed_only=displayed_only, extract_links=extract_links, dtype_backend=dtype_backend, storage_options=storage_options, )
pandas-devREPO_NAMEpandasPATH_START.@pandas_extracted@pandas-main@pandas@io@html.py@.PATH_END.py
{ "filename": "from_vizier_table.ipynb", "repo_name": "cds-astro/mocpy", "repo_path": "mocpy_extracted/mocpy-master/notebooks/from_vizier_table.ipynb", "type": "Jupyter Notebook" }
# Get the MOC corresponding to a table ```python from mocpy import MOC ``` ```python gum_qso_moc = MOC.from_vizier_table("VI/137/gum_qso", nside=512) ``` WARNING: Keyword 'TTYPE1' found more than once in a same HDU! We use the first occurrence. ```python gum_qso_moc.display_preview() ``` ![png](output_3_0.png) ```python denis_moc = MOC.from_ivorn("ivo://CDS/B/denis/denis", nside=64) denis_moc.display_preview() ``` WARNING: Keyword 'TTYPE1' found more than once in a same HDU! We use the first occurrence. ![png](output_4_1.png)
cds-astroREPO_NAMEmocpyPATH_START.@mocpy_extracted@mocpy-master@notebooks@from_vizier_table.ipynb@.PATH_END.py
{ "filename": "EarthSystem.ipynb", "repo_name": "james-trayford/strauss", "repo_path": "strauss_extracted/strauss-main/examples/colab/EarthSystem.ipynb", "type": "Jupyter Notebook" }
#### Preamble for `CoLab` To use this notebook (if you haven't already) you can first save a copy to your local drive by clicking `File > Save a Copy in Drive` and run on that copy. _Note_: `Colab` is a really handy way to test and try `strauss`, though it will generally run and display audio more slowly than running on your local machine. For a more responsive experience, why not install `strauss` locally, following the instructions [on the Github](https://github.com/james-trayford/strauss) Run these cells, so that the notebook functions on the _Google_ `Colab` platform: ```python %pip --quiet install strauss ``` ```python !git clone https://github.com/james-trayford/strauss.git ``` ```python %cd strauss/examples/ ``` ### <u> Generate the Earth rotation sound for the Planetarium Show</u> **First, import relevant modules:** ```python %reload_ext autoreload %autoreload 2 import matplotlib.pyplot as plt import ffmpeg as ff import wavio as wav from strauss.sonification import Sonification from strauss.sources import Objects from strauss import channels from strauss.score import Score import numpy as np from strauss.generator import Synthesizer import IPython.display as ipd import os from scipy.interpolate import interp1d %matplotlib inline ``` **Then, import the land fraction data** The land fraction as a function of longitude is converted to a water fraction (i.e. $1-f_{\rm water}$), and mapped of three rotation cycles to control the LP filter cutoff. This is normalised to a range within the [0,1] range, chosen to sound good. ```python datafile = "../data/datasets/landfrac.txt" data = np.genfromtxt(datafile) longitude = data[:,0] waterfrac = 1-data[:,1] startlong = 180-(96 + 15./60 + 2.2/3600) # we travel backwards in longitude per the earth's rotation longgrid = (np.linspace(startlong,720+startlong,2599)%360 - 180.)[::-1] wfrac = interp1d(longitude, waterfrac) wfracgrid = wfrac(longgrid)*0.75 + 0.15 timegrid = np.linspace(0,1,wfracgrid.size) plt.plot(timegrid, wfracgrid) plt.ylabel("Normalised Water Fraction") plt.xlabel(r"${\rm Rotation}\; [6\pi]$") plt.show() ``` and set up the synthesiser ```python # chord representing the earth (a Gbsus7 chord) notes = [['Gb3', 'Db4', 'E4', 'B4']] # specify audio system (e.g. mono, stereo, 5.1, ...) system = "stereo" length = 60. # set up synth and turn on LP filter generator = Synthesizer() generator.modify_preset({'filter':'on'}) ``` Map the data and render sonification for the Earth's rotation... ```python score = Score(notes, length) # volume swell is directly ahead data = {'cutoff':[wfracgrid]*4, 'time_evo':[timegrid]*4, 'pitch':list(range(4))} # set up source sources = Objects(data.keys()) sources.fromdict(data) sources.apply_mapping_functions() soni = Sonification(score, sources, generator, system) soni.render() ``` **Listen to and plot the waveforms from the sonification:** ```python soni.notebook_display() ``` **Combine and save sonification to a multi-channel wav** NOTE: Change `"../../FILENAME.wav"` to your filepath of choice ```python soni.save("../../earth.wav") ``` ```python ```
james-trayfordREPO_NAMEstraussPATH_START.@strauss_extracted@strauss-main@examples@colab@EarthSystem.ipynb@.PATH_END.py
{ "filename": "ImagePath.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/Pillow/py3/PIL/ImagePath.py", "type": "Python" }
# # The Python Imaging Library # $Id$ # # path interface # # History: # 1996-11-04 fl Created # 2002-04-14 fl Added documentation stub class # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1996. # # See the README file for information on usage and redistribution. # from __future__ import annotations from . import Image Path = Image.core.path
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@Pillow@py3@PIL@ImagePath.py@.PATH_END.py
{ "filename": "_namelengthsrc.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/treemap/hoverlabel/_namelengthsrc.py", "type": "Python" }
import _plotly_utils.basevalidators class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="namelengthsrc", parent_name="treemap.hoverlabel", **kwargs ): super(NamelengthsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@treemap@hoverlabel@_namelengthsrc.py@.PATH_END.py
{ "filename": "openapi.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/utilities/openapi.py", "type": "Python" }
"""Utility functions for parsing an OpenAPI spec.""" from __future__ import annotations import copy import json import logging import re from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Union import requests import yaml from pydantic import ValidationError logger = logging.getLogger(__name__) class HTTPVerb(str, Enum): """Enumerator of the HTTP verbs.""" GET = "get" PUT = "put" POST = "post" DELETE = "delete" OPTIONS = "options" HEAD = "head" PATCH = "patch" TRACE = "trace" @classmethod def from_str(cls, verb: str) -> HTTPVerb: """Parse an HTTP verb.""" try: return cls(verb) except ValueError: raise ValueError(f"Invalid HTTP verb. Valid values are {cls.__members__}") if TYPE_CHECKING: from openapi_pydantic import ( Components, Operation, Parameter, PathItem, Paths, Reference, RequestBody, Schema, ) try: from openapi_pydantic import OpenAPI except ImportError: OpenAPI = object # type: ignore class OpenAPISpec(OpenAPI): """OpenAPI Model that removes mis-formatted parts of the spec.""" openapi: str = "3.1.0" # overriding overly restrictive type from parent class @property def _paths_strict(self) -> Paths: if not self.paths: raise ValueError("No paths found in spec") return self.paths def _get_path_strict(self, path: str) -> PathItem: path_item = self._paths_strict.get(path) if not path_item: raise ValueError(f"No path found for {path}") return path_item @property def _components_strict(self) -> Components: """Get components or err.""" if self.components is None: raise ValueError("No components found in spec. ") return self.components @property def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]: """Get parameters or err.""" parameters = self._components_strict.parameters if parameters is None: raise ValueError("No parameters found in spec. ") return parameters @property def _schemas_strict(self) -> Dict[str, Schema]: """Get the dictionary of schemas or err.""" schemas = self._components_strict.schemas if schemas is None: raise ValueError("No schemas found in spec. ") return schemas @property def _request_bodies_strict(self) -> Dict[str, Union[RequestBody, Reference]]: """Get the request body or err.""" request_bodies = self._components_strict.requestBodies if request_bodies is None: raise ValueError("No request body found in spec. ") return request_bodies def _get_referenced_parameter(self, ref: Reference) -> Union[Parameter, Reference]: """Get a parameter (or nested reference) or err.""" ref_name = ref.ref.split("/")[-1] parameters = self._parameters_strict if ref_name not in parameters: raise ValueError(f"No parameter found for {ref_name}") return parameters[ref_name] def _get_root_referenced_parameter(self, ref: Reference) -> Parameter: """Get the root reference or err.""" from openapi_pydantic import Reference parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference): parameter = self._get_referenced_parameter(parameter) return parameter def get_referenced_schema(self, ref: Reference) -> Schema: """Get a schema (or nested reference) or err.""" ref_name = ref.ref.split("/")[-1] schemas = self._schemas_strict if ref_name not in schemas: raise ValueError(f"No schema found for {ref_name}") return schemas[ref_name] def get_schema( self, schema: Union[Reference, Schema], depth: int = 0, max_depth: Optional[int] = None, ) -> Schema: if max_depth is not None and depth >= max_depth: raise RecursionError( f"Max depth of {max_depth} has been exceeded when resolving references." ) from openapi_pydantic import Reference if isinstance(schema, Reference): schema = self.get_referenced_schema(schema) # TODO: Resolve references on all fields of Schema ? # (e.g. patternProperties, etc...) if schema.properties is not None: for p_name, p in schema.properties.items(): schema.properties[p_name] = self.get_schema(p, depth + 1, max_depth) if schema.items is not None: schema.items = self.get_schema(schema.items, depth + 1, max_depth) return schema def _get_root_referenced_schema(self, ref: Reference) -> Schema: """Get the root reference or err.""" from openapi_pydantic import Reference schema = self.get_referenced_schema(ref) while isinstance(schema, Reference): schema = self.get_referenced_schema(schema) return schema def _get_referenced_request_body( self, ref: Reference ) -> Optional[Union[Reference, RequestBody]]: """Get a request body (or nested reference) or err.""" ref_name = ref.ref.split("/")[-1] request_bodies = self._request_bodies_strict if ref_name not in request_bodies: raise ValueError(f"No request body found for {ref_name}") return request_bodies[ref_name] def _get_root_referenced_request_body( self, ref: Reference ) -> Optional[RequestBody]: """Get the root request Body or err.""" from openapi_pydantic import Reference request_body = self._get_referenced_request_body(ref) while isinstance(request_body, Reference): request_body = self._get_referenced_request_body(request_body) return request_body @staticmethod def _alert_unsupported_spec(obj: dict) -> None: """Alert if the spec is not supported.""" warning_message = ( " This may result in degraded performance." + " Convert your OpenAPI spec to 3.1.* spec" + " for better support." ) swagger_version = obj.get("swagger") openapi_version = obj.get("openapi") if isinstance(openapi_version, str): if openapi_version != "3.1.0": logger.warning( f"Attempting to load an OpenAPI {openapi_version}" f" spec. {warning_message}" ) else: pass elif isinstance(swagger_version, str): logger.warning( f"Attempting to load a Swagger {swagger_version}" f" spec. {warning_message}" ) else: raise ValueError( "Attempting to load an unsupported spec:" f"\n\n{obj}\n{warning_message}" ) @classmethod def parse_obj(cls, obj: dict) -> OpenAPISpec: try: cls._alert_unsupported_spec(obj) return super().parse_obj(obj) except ValidationError as e: # We are handling possibly misconfigured specs and # want to do a best-effort job to get a reasonable interface out of it. new_obj = copy.deepcopy(obj) for error in e.errors(): keys = error["loc"] item = new_obj for key in keys[:-1]: item = item[key] item.pop(keys[-1], None) return cls.parse_obj(new_obj) @classmethod def from_spec_dict(cls, spec_dict: dict) -> OpenAPISpec: """Get an OpenAPI spec from a dict.""" return cls.parse_obj(spec_dict) @classmethod def from_text(cls, text: str) -> OpenAPISpec: """Get an OpenAPI spec from a text.""" try: spec_dict = json.loads(text) except json.JSONDecodeError: spec_dict = yaml.safe_load(text) return cls.from_spec_dict(spec_dict) @classmethod def from_file(cls, path: Union[str, Path]) -> OpenAPISpec: """Get an OpenAPI spec from a file path.""" path_ = path if isinstance(path, Path) else Path(path) if not path_.exists(): raise FileNotFoundError(f"{path} does not exist") with path_.open("r") as f: return cls.from_text(f.read()) @classmethod def from_url(cls, url: str) -> OpenAPISpec: """Get an OpenAPI spec from a URL.""" response = requests.get(url) return cls.from_text(response.text) @property def base_url(self) -> str: """Get the base url.""" return self.servers[0].url def get_methods_for_path(self, path: str) -> List[str]: """Return a list of valid methods for the specified path.""" from openapi_pydantic import Operation path_item = self._get_path_strict(path) results = [] for method in HTTPVerb: operation = getattr(path_item, method.value, None) if isinstance(operation, Operation): results.append(method.value) return results def get_parameters_for_path(self, path: str) -> List[Parameter]: from openapi_pydantic import Reference path_item = self._get_path_strict(path) parameters = [] if not path_item.parameters: return [] for parameter in path_item.parameters: if isinstance(parameter, Reference): parameter = self._get_root_referenced_parameter(parameter) parameters.append(parameter) return parameters def get_operation(self, path: str, method: str) -> Operation: """Get the operation object for a given path and HTTP method.""" from openapi_pydantic import Operation path_item = self._get_path_strict(path) operation_obj = getattr(path_item, method, None) if not isinstance(operation_obj, Operation): raise ValueError(f"No {method} method found for {path}") return operation_obj def get_parameters_for_operation(self, operation: Operation) -> List[Parameter]: """Get the components for a given operation.""" from openapi_pydantic import Reference parameters = [] if operation.parameters: for parameter in operation.parameters: if isinstance(parameter, Reference): parameter = self._get_root_referenced_parameter(parameter) parameters.append(parameter) return parameters def get_request_body_for_operation( self, operation: Operation ) -> Optional[RequestBody]: """Get the request body for a given operation.""" from openapi_pydantic import Reference request_body = operation.requestBody if isinstance(request_body, Reference): request_body = self._get_root_referenced_request_body(request_body) return request_body @staticmethod def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str: """Get a cleaned operation id from an operation id.""" operation_id = operation.operationId if operation_id is None: # Replace all punctuation of any kind with underscore path = re.sub(r"[^a-zA-Z0-9]", "_", path.lstrip("/")) operation_id = f"{path}_{method}" return operation_id.replace("-", "_").replace(".", "_").replace("/", "_")
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@utilities@openapi.py@.PATH_END.py
{ "filename": "spl.py", "repo_name": "COSMOGRAIL/PyCS", "repo_path": "PyCS_extracted/PyCS-master/pycs/gen/spl.py", "type": "Python" }
""" Module defining the Spline class, something easy to wrap around SciPy splines. Includes BOK algorithms (Mollinari et al) Some rules of splrep (k = 3) - do not put more then 2 knots between data points. - splrep wants inner knots only, do not give extremal knots, even only "once". """ import numpy as np import sys import pycs.gen.util import copy as pythoncopy import matplotlib.pyplot as plt import scipy.optimize as spopt import scipy.interpolate as si class DataPoints(): """ An ultralight version of a lightcurve, made for fast computations. Can be "merged" from a list of lightcurves, see factory function below. A Spline object has such a DataPoints object as attribute. ATTENTION Datapoints are expected to be ALWAYS SORTED BY JDS, and no two datapoints have the same jd ! See the splitup option of the constructor. Note that this is not the case for lightcurves ! Hence the existence of datapoints. Should be enforced in every function that builds datapoints. ABOUT STAB POINTS With scipy splines, we always get the last knots at the extrema of data points. So to get knots "outside" of the real datapoints, we have to insert fake points. And while we are at it, these fake points can also be used to stabilize the spline in gaps. The mask is used to differentiate between actual data points and "stabilization points" that are inserted to make the spline behave well at the extrema and in season gaps. It is modified by the two addgappts and addextpts. The info about stabpoints is written into the object, so that they can be reconstrucuted from any new jds and mags. """ def __init__(self, jds, mags, magerrs, splitup=True, deltat=0.000001, sort=True, stab=False, stabext=300.0, stabgap = 30.0, stabstep = 5.0, stabmagerr = -2.0, stabrampsize = 0, stabrampfact = 1.0): """ Constructor Always leave splitup and sort on True ! Only if you know that you are already sorted you can skip them. You cannot specify a mask, I do this myself. (could be done in principle). stab : do you want stabilization points ? Don't forget to run splitup, sort, and addstab again if you change the data ! """ self.jds = jds self.mags = mags self.magerrs = magerrs self.stab = stab self.stabext = stabext self.stabgap = stabgap self.stabstep = stabstep self.stabmagerr = stabmagerr self.stabrampsize = stabrampsize self.stabrampfact = stabrampfact self.mask = np.ones(len(self.jds), dtype=np.bool) # an array of True self.deltat = deltat if splitup: self.splitup() elif sort: # If we do the splitup, we sort anyway. self.sort() self.putstab() # def update(self, jds, mags, magerrs): # """ # NOT NEEDED ANYMORE, JUST CALL MERGE AND GIVE AN OLDDP. SAFER. # # Give me some new datapoints (no stabs) (already splitup and sorted, by definition), I'll update myself. # In fact everything might move ! # """ # if newdatapoints.stab = True: # raise RuntimeError("Give me points without stab !") # self.jds = newdatapoints.jds # self.mags = newdatapoints.mags # self.magerrs = newdatapoints.magerrs # self.mask = np.ones(len(self.jds), dtype=np.bool) # self.addstab() # runs only if stab = True def splitup(self): """ TO WRITE !!! We avoid that two points get the same jds... Note that this might change the order of the jds, but only of very close ones, so one day it would be ok to leave the mags as they are. """ self.jds += self.deltat * np.random.randn(len(self.jds)) self.sort() def sort(self): """ Absolutely mandatory, called in the constructor. """ sortedindices = np.argsort(self.jds) self.jds = self.jds[sortedindices] self.mags = self.mags[sortedindices] self.magerrs = self.magerrs[sortedindices] self.mask = self.mask[sortedindices] self.validate() def validate(self): """ We check that the datapoint jds are increasing strictly : """ first = self.jds[:-1] second = self.jds[1:] if not np.alltrue(np.less(first,second)): # Not less_equal ! Strictly increasing ! raise RuntimeError, "These datapoints don't have strcitly increasing jds !" def rmstab(self): """ Deletes all stabilization points """ self.jds = self.jds[self.mask] self.mags = self.mags[self.mask] self.magerrs = self.magerrs[self.mask] self.mask = np.ones(len(self.jds), dtype=np.bool) def putstab(self): """ Runs only if stab is True. I will : add datapoints (new jds, new mags, new magerrs) modify the mask = False for all those new datapoints. """ if self.stab == True: # We start by deleting any previous stab stuff : self.rmstab() self.addgappts() self.addextpts() else: pass def calcstabmagerr(self): """ Computes the mag err of the stabilisation points. """ if self.stabmagerr >= 0.0: return self.stabmagerr else: return - self.stabmagerr * np.median(self.magerrs) def addgappts(self): """ We add stabilization points with low weights into the season gaps to avoid those big excursions of the splines. This is done by a linear interpolation across the gaps. """ absstabmagerr = self.calcstabmagerr() gaps = self.jds[1:] - self.jds[:-1] # has a length of len(self.jds) - 1 gapindices = np.arange(len(self.jds) - 1)[gaps > self.stabgap] # indices of those gaps that are larger than stabgap for n in range(len(gapindices)): i = gapindices[n] a = self.jds[i] b = self.jds[i+1] newgapjds = np.linspace(a, b, float(b-a)/float(self.stabstep))[1:-1] newgapindices = i + 1 + np.zeros(len(newgapjds)) newgapmags = np.interp(newgapjds, [a, b], [self.mags[i], self.mags[i+1]]) newgapmagerrs = absstabmagerr * np.ones(newgapmags.shape) newgapmask = np.zeros(len(newgapjds), dtype=np.bool) self.jds = np.insert(self.jds, newgapindices, newgapjds) self.mags = np.insert(self.mags, newgapindices, newgapmags) self.magerrs = np.insert(self.magerrs, newgapindices, newgapmagerrs) self.mask = np.insert(self.mask, newgapindices, newgapmask) gapindices += newgapjds.size # yes, as we inserted some points the indices change. # If you change this structure, be sure to check SplineML.settargetmags as well ! self.validate() def addextpts(self): """ We add stabilization points at both extrema of the lightcurves This is done by "repeating" the extremal points, and a ramp in the magerrs """ absstabmagerr = self.calcstabmagerr() extjds = np.arange(self.jds[0], self.jds[0] - self.stabext, -1*self.stabstep)[::-1][:-1] extmags = self.mags[0] * np.ones(extjds.shape) extmagerrs = absstabmagerr * np.ones(extjds.shape) for i in range(1, self.stabrampsize+1): extmagerrs[-i] += (self.stabrampsize +1 -i) * absstabmagerr * self.stabrampfact extindices = np.zeros(extjds.shape) mask = np.zeros(len(extjds), dtype=np.bool) self.jds = np.insert(self.jds, extindices, extjds) self.mags = np.insert(self.mags, extindices, extmags) self.magerrs = np.insert(self.magerrs, extindices, extmagerrs) self.mask = np.insert(self.mask, extindices, mask) # And the same at the other end : extjds = np.arange(self.jds[-1], self.jds[-1] + self.stabext, self.stabstep)[1:] extmags = self.mags[-1] * np.ones(extjds.shape) extmagerrs = absstabmagerr * np.ones(extjds.shape) for i in range(0, self.stabrampsize): extmagerrs[i] += (self.stabrampsize -i) * absstabmagerr * self.stabrampfact extindices = len(self.jds) + np.zeros(extjds.shape) mask = np.zeros(len(extjds), dtype=np.bool) self.jds = np.insert(self.jds, extindices, extjds) self.mags = np.insert(self.mags, extindices, extmags) self.magerrs = np.insert(self.magerrs, extindices, extmagerrs) self.mask = np.insert(self.mask, extindices, mask) self.validate() def getmaskbounds(self): """ Returns the upper and lower bounds of the regions containing stabilization points. This is used when placing knots, so to put fewer knots in these regions. Crazy stuff... """ maskindices = np.where(self.mask == False)[0] #print maskindices if len(maskindices) < 3: print "Hmm, not much masked here ..." return (np.array([]), np.array([])) else: lcuts = maskindices[np.where(maskindices[1:] - maskindices[:-1] > 1)[0] + 1] lcuts = np.insert(lcuts, 0, maskindices[0]) ucuts = maskindices[np.where(maskindices[1:] - maskindices[:-1] > 1)[0]] ucuts = np.insert(ucuts, len(ucuts), maskindices[-1]) return (lcuts, ucuts) def ntrue(self): """ Returns the number of real datapoints (skipping stabilization points) """ return np.sum(self.mask) def merge(lcs, olddp=None, splitup=True, deltat=0.000001, sort=True, stab=False, stabext=300.0, stabgap = 30.0, stabstep = 5.0, stabmagerr = 2.0, stabrampsize = 0, stabrampfact = 1.0): """ Factory function for DataPoints objects, starting from lightcurves. Takes a list of lightcurves and quickly concatenate the jds, mags, and magerrs. Instead of specifying all the stab point parameters, you can give me an old datapoints object, and I will reuse its settings... This is useful if you want to "update" the data points. If overlap is True, I will keep only points that are "covered" by all four lightcurves ! This is useful when you want to build a first source spline, and your microlensing is messy at the borders. NOT YET IMPLEMENTED ... """ jds = np.concatenate([l.getjds() for l in lcs]) mags = np.concatenate([l.getmags() for l in lcs]) magerrs = np.concatenate([l.getmagerrs() for l in lcs]) if olddp == None: return DataPoints(jds, mags, magerrs, splitup=splitup, deltat=deltat, sort=sort, stab=stab, stabext=stabext, stabgap=stabgap, stabstep=stabstep, stabmagerr=stabmagerr, stabrampsize=stabrampsize, stabrampfact=stabrampfact) else: return DataPoints(jds, mags, magerrs, splitup=splitup, sort=sort, deltat=olddp.deltat, stab=olddp.stab, stabext=olddp.stabext, stabgap=olddp.stabgap, stabstep=olddp.stabstep, stabmagerr=olddp.stabmagerr, stabrampsize=olddp.stabrampsize, stabrampfact=olddp.stabrampfact) class Spline(): """ A class to represent a spline, that is essentially a set of knots and coefficients. As finding knots and coefficients requires access to some data points, these are included in the form of a DataPoints object. Abount knots : Spline.t are all the knots, including extremas with multiplicity. But splrep wants internal knots only ! By internal we mean : not even the data extremas ! Spline.getintt() returns only these internal knots. """ def __init__(self, datapoints, t = None, c = None, k = 3, bokeps = 2.0, boktests = 5, bokwindow = None, plotcolour="black"): """ t : all the knots (not only internal ones !) c : corresponding coeffs k : degree : default = cubic splines k=3 -> "order = 4" ??? whatever ... 3 means that you can differentiate twice at the knots. """ #self.origdatapoints = datapoints self.datapoints = datapoints # At this point we know that your datapoint jds are monotonously increasing. This is tested # by validate() of datapoints. self.t = t # the array of knots self.c = c # the coeffs self.k = k self.bokeps = bokeps self.boktests = boktests self.bokwindow = bokwindow self.knottype = "none" self.plotcolour = plotcolour self.showknots = True # Bounds, for BOK self.lims = None self.l = None self.u = None # We want to keep trace of the r2 of a spline. self.lastr2nostab = 0.0 # without stab points (the real thing) self.lastr2stab = 0.0 # with stab points (usually not so interesting) # If you did not give me a t&c, I'll make some default ones for you : try: if (self.t is None): self.uniknots(2) # This also puts self.c to 0s except: if (len(self.t) == 0): self.uniknots(2) # This also puts self.c to 0s def __str__(self): """ Returns a string with: * degree * knot placement * number of intervals """ #return "Spline of degree %i, %i knots (%i inner knots), and %i intervals." % (self.k, len(self.t), len(self.getintt()), self.getnint()) if len(self.knottype) > 6: # That's a string knottext = "%il%ib" % (self.knottype.count("l"), self.knottype.count("b")) else: knottext = self.knottype return "~%i/%s/%i~" % (self.k, knottext, self.getnint()) def copy(self): """ Returns a "deep copy" of the spline. """ return pythoncopy.deepcopy(self) def shifttime(self, timeshift): """ Hard-shifts your spline along the time axis. By "hard-shift", I mean that unlike for a lightcurve, the spline will not know that it was shifted ! It's up to you to be sure that you want to move it. We shift both the datapoints and the knots. """ self.t += timeshift self.datapoints.jds += timeshift def shiftmag(self, magshift): """ Hard-shifts your spline along the mag axis. By "hard-shift", I mean that unlike for a lightcurve, the spline will not know that it was shifted ! It's up to you to be sure that you want to move it. We shift both the datapoints and the knots. """ self.c += magshift self.datapoints.mags += magshift def updatedp(self, newdatapoints, dpmethod="stretch"): """ Replaces the datapoints of the spline, and makes sure that the knots stay compatible. If you tweaked your datapoints, I will have to tweak my knots to make sure that my external knots fit. Hence this method ! Due to the splitup, this is needed even if you just tweaked the mags ! And anyway in this case I have to rebuild the stab points. .. warning :: IT'S UP TO YOU TO CHECK THAT YOU DON'T REPLACE DATATOINTS WITH DIFFERENT STAB SETTINGS Anyway it would work, just look ugly ! Replaces the datapoints (jds, mags, and magerrs) touching the knots and coeffs as less as possible. Note that we also have to deal with stab points here ! This is made for instance for time shifts that only very slightly change the datapoints, and you don't want to optimize the knots all the time from scratch again. The current knots are "streched" (keeping their relative spacings) accross the new datapoints. Options for "dpmethod" : - "stretch" : changes all the knots - "extadj" : does not touch the internal knots, but adjusts the external ones only, to fit the new datapoints. Probably the method to use when optimizing time shifts. - "leave" : does not touch the knots -> ok to evaluate the spline, but you will not be able to fit it anymore, as the external knots don't correspond to datapoints. .. todo:: In principle, why don't we just update the real datapoints here, and leave the stab as they are ? """ if dpmethod == "stretch": oldmin = self.datapoints.jds[0] # This includes potential stab points oldmax = self.datapoints.jds[-1] newmin = newdatapoints.jds[0] # Idem newmax = newdatapoints.jds[-1] oldknots = self.getinttex() #print oldknots # we will stretch the oldknots by a factor a : a = (newmax - newmin)/(oldmax - oldmin) newknots = newmin + a*(oldknots-oldmin) # We set the new datapoints: self.datapoints = newdatapoints self.setinttex(newknots) elif dpmethod == "extadj" : intknots = self.getintt() self.datapoints = newdatapoints # Ok, now the newdatapoints might be narrower or wider than the knots, we have to deal with this. # If they are wider, it's easy : setint will put move the external knot on the external datapoint. # If they are narrower, it's trickier : we have to remove some extra knots, so to really just keep the "internal" ones. # to feed into setintt. #if True: # works as well, but maybe faster to test first : if (self.datapoints.jds[0] >= intknots[0]) or (self.datapoints.jds[-1] <= intknots[-1]): keepmask = np.ones(intknots.shape, dtype=np.bool) for i in range(len(intknots)): # Starting from the left ... if intknots[i] <= self.datapoints.jds[0]: keepmask[i] = False else: break for i in range(len(intknots))[::-1]: # And now the right ... if intknots[i] >= self.datapoints.jds[-1]: keepmask[i] = False else: break #nkick = np.sum(keepmask == False) #if nkick != 0: # print "I'll kick %i knots !" % (nkick) # And finally, we apply the mask . intknots = intknots[keepmask] self.setintt(intknots) # This automatically adjusts the extremal knots. elif dpmethod == "leave" : knots = self.getinttex() self.datapoints = newdatapoints # We quickly check the boundaries if ( knots[0] >= self.datapoints.jds[0] ) or ( knots[-1] <= self.datapoints.jds[-1] ): raise RuntimeError("Your newdatapoints are to wide for the current knots !") else: raise RuntimeError("Don't know this updatedp method !") # We reset any bounds just to be sure. self.lims = None self.l = None self.u = None def uniknots(self, nint, n=True): """ Uniform distribution of internal knots across the datapoints (including any stab points). We don't make a difference between stab and real points. :param nint: The number of intervals, or the step :param n: If True, nint is the number of intervals (== piecewise polynoms) you want. If False : nint is a step in days you want between the knots (approximately). :type n: boolean .. note:: I also put all coeffs back to 0.0 ! """ #intt = np.linspace(self.datapoints.jds[0], self.datapoints.jds[-1], step+1)[1:-1] # we remove the extremas a = self.datapoints.jds[0] b = self.datapoints.jds[-1] if n: intt = np.linspace(a, b, nint + 1)[1:-1] else: intt = np.linspace(a, b, float(b-a)/float(nint))[1:-1] if len(intt) == 0: raise RuntimeError("I am uniknots, and I have only 0 (zero) internal knots ! Increase this number !") self.setintt(intt) self.knottype = "u" # Important : we put some 0 coeffs to go with the new knots self.resetc() def resetc(self): """ Sets all coeffs to 0.0 -- if you want to start again your fit, keeping the knot positions. """ self.c = np.zeros(len(self.t)) def reset(self): """ Calls uniknots, i.e. resets both coeffs and knot positions, keeping the same number of knots. """ self.uniknots(self.getnint() ,n=True) def buildbounds(self, verbose = True): """ Build bounds for bok. By default I will make those bounds as wide as possible, still respecting epsilon. The parameter epsilon is the minimum distance two knots can have. If you give me a window size, I will not make the bounds as wide as possible, but only put them 0.5*window days around the current knots (still respecting all this epsilon stuff of course). I look where your current knots are, and for each knots I build the bounds so that epsilon distance is respected between adjacent upper and lower bounds. But, there might already be knots only epsilon apart. So I'm a bit tricky, not so straightforward as my predecessors. Knots at the extrema are not allowed to move. Requires existing knots, puts lims in between them, and builds the bounds. @todo: Optimize me using numpy ! This is experiemental code for now. """ if verbose: print "Building BOK bounds (bokeps = %.3f, bokwindow = %s) ..." % (self.bokeps, self.bokwindow) knots = self.getinttex() # Including extremal knots (once). n = len(knots) # We start by checking the knot spacing knotspacings = knots[1:] - knots[:-1] if not np.alltrue(knotspacings > 0.0): raise RuntimeError("Ouch, your knots are not sorted !") minspace = np.min(knotspacings) if verbose : print "Minimal knot spacing : %.3f" % (minspace) if minspace < self.bokeps - 0.00001: # Rounding errors, we decrease epsilon a bit... # If this does still happens, then it was not just a rounding error ... # Yes it still happens, due to updatedp stretch ... raise RuntimeError("Knot spacing min = %f, epsilon = %f" % (minspace, self.bokeps)) # Loop through the knots. lowers = [knots[0]] # First knot is not allowed to move uppers = [knots[0]] for i in range(1, n-1): # Internal knots tk = knots[i] # this knot pk = knots[i-1] # previous knot nk = knots[i+1] # next knot # First we build the wide bounds : guessl = 0.5*(pk + tk) + 0.5*self.bokeps if guessl >= tk: guessl = tk guessu = 0.5*(nk + tk) - 0.5*self.bokeps if guessu <= tk: guessu = tk # Now we see if the use wants a narrower window within those bounds : if self.bokwindow != None: if tk - 0.5*self.bokwindow >= guessl: guessl = tk - 0.5*self.bokwindow if tk + 0.5*self.bokwindow <= guessu: guessu = tk + 0.5*self.bokwindow lowers.append(guessl) uppers.append(guessu) # And now this last knot, doesn't move, like the first one: lowers.append(knots[-1]) uppers.append(knots[-1]) self.l = np.array(lowers) self.u = np.array(uppers) self.knottype += "l" if verbose: print "Buildbounds done." def bok(self, bokmethod="BF", verbose=True, trace=False): """ We optimize the positions of knots by some various techniques. We use fixed bounds for the exploration, run buildbounds (with low epsilon) first. This means that I will not move my bounds. For each knot, i will try ntestpos linearly spaced positions within its bounds. In this version, the bounds are included : I might put a knot on a bound ! The way the bounds are placed by buildbounds ensures that in any case the minimal distance of epsilon is respected. Using this sheme, it is now possible to iteratively call mybok and buildbounds in a loop and still respect epsilon at any time. bokmethods : - MCBF : Monte Carlo brute force with ntestpos trial positions for each knot - BF : brute force, deterministic. Call me twice - fminind : fminbound on one knot after the other. - fmin :global fminbound Exit is automatic, if result does not improve anymore... """ intknots = self.getintt() # only internal, the ones we will move nintknots = len(intknots) weights = 1.0/self.datapoints.magerrs def score(intknots, index, value): modifknots = intknots.copy() modifknots[index] = value return si.splrep(self.datapoints.jds, self.datapoints.mags, w=weights, xb=None, xe=None, k=self.k, task=-1, s=None, t=modifknots, full_output=1, per=0, quiet=1)[1] iniscore = score(intknots, 0, intknots[0]) lastchange = 1 lastscore = iniscore iterations = 0 if verbose: print "Starting BOK-%s on %i intknots (boktests = %i)" % (bokmethod, nintknots, self.boktests) if bokmethod == "MCBF": while True: if lastchange >= 2*nintknots: # somewhat arbitrary, but why not. break i = np.random.randint(0, nintknots) # (inclusive, exclusive) testknots = np.linspace(self.l[i+1], self.u[i+1], self.boktests) # +1, as u and l include extremal knots... # So we include the extremas in our range to test. testscores = np.array([score(intknots, i, testknot) for testknot in testknots]) bestone = np.argmin(testscores) bestscore = testscores[bestone] if bestscore < lastscore: lastchange = 0 intknots[i] = testknots[bestone] # WE UPDATE the intknots array ! lastscore = bestscore lastchange += 1 iterations += 1 if trace: self.optc() pycs.gen.util.trace([], [self]) if bokmethod == "BF": intknotindices = range(nintknots) # We could potentially change the order, just to see if that makes sense. # No, it doesn't really help #mid = int(len(intknotindices)/2.0) #intknotindices = np.concatenate([intknotindices[mid:], intknotindices[:mid][::-1]]) for i in intknotindices: testknots = np.linspace(self.l[i+1], self.u[i+1], self.boktests) # +1, as u and l include extremal knots... # So we include the extremas in our range to test. testscores = np.array([score(intknots, i, testknot) for testknot in testknots]) bestone = np.argmin(testscores) bestscore = testscores[bestone] intknots[i] = testknots[bestone] # WE UPDATE the intknots array ! iterations += 1 if trace: self.optc() pycs.gen.util.trace([], [self]) if bokmethod == "fminind": intknotindices = range(nintknots) for i in intknotindices: def target(value): return score(intknots, i, value) #inival = intknots[i] #bounds = (self.l[i+1], self.u[i+1]) out = spopt.fminbound(target, self.l[i+1], self.u[i+1], xtol=0.01, maxfun=100, full_output=1, disp=1) #print out optval = out[0] bestscore = out[1] intknots[i] = optval # WE UPDATE the intknots array ! iterations += 1 if trace: self.optc() pycs.gen.util.trace([], [self]) if bokmethod == "fmin": def target(modifknots): #iterations += 1 #if trace: # self.optc() # pycs.gen.util.trace([], [self]) return si.splrep(self.datapoints.jds, self.datapoints.mags, w=weights, xb=None, xe=None, k=self.k, task=-1, s=None, t=modifknots, full_output=1, per=0, quiet=1)[1] bounds = [(a, b) for (a, b) in zip(self.l[1:-1], self.u[1:-1])] out = spopt.fmin_l_bfgs_b(target, intknots, approx_grad=True, bounds=bounds, m=10, factr=1e7, pgtol=1.e-05, epsilon=1e-04, iprint=-1, maxfun=15000) #out = spopt.fminbound(target, self.l[1:-1], self.u[1:-1], xtol=0.01, maxfun=1000, full_output=1, disp=3) #print out intknots = out[0] bestscore = out[1] # relative improvement : relimp = (iniscore - bestscore)/iniscore self.knottype += "b" self.setintt(intknots) #pycs.gen.lc.display([],[self]) #self.display() self.optc() # Yes, not yet done ! finalr2 = self.r2(nostab=True) if verbose: print "r2 = %f (without stab poins)" % finalr2 print "Done in %i iterations, relative improvement = %f" % (iterations, relimp) # We count all datapoints here, as score returns the full chi2 including stab pts. return finalr2 # Some stuff about knots : def getintt(self): """ Returns the internal knots (i.e., not even the datapoints extrema) This is what you need to feed into splrep ! There are nint - 1 such knots """ return self.t[(self.k+1):-(self.k+1)].copy() # We cut the outer knots. def getinttex(self): """ Same as above, but we include the extremal points "once". """ return self.t[(self.k):-(self.k)].copy() def knotstats(self): """ Returns a string describing the knot spacing """ knots = self.getinttex() spacings = knots[1:] - knots[:-1] return " ".join(["%.1f" % (spacing) for spacing in sorted(spacings)]) def setintt(self, intt): """ Give me some internal knots (not even containing the datapoints extrema), and I build the correct total knot vector t for you. I add the extremas, with appropriate multiplicity. @TODO: check consistency of intt with datapoints ! """ # Ok a quick test for consisency : if len(intt) == 0: raise RuntimeError("Your list of internal knots is empty !") if not self.datapoints.jds[0] < intt[0]: raise RuntimeError("Ouch.") if not self.datapoints.jds[-1] > intt[-1]: raise RuntimeError("Ouch.") #assert self.datapoints.jds[0] < intt[0] # should we put <= here ? #assert self.datapoints.jds[-1] > intt[-1] pro = self.datapoints.jds[0] * np.ones(self.k+1) post = self.datapoints.jds[-1] * np.ones(self.k+1) self.t = np.concatenate((pro, intt, post)) def setinttex(self, inttex): """ Including extremal knots """ #pro = self.datapoints.jds[0] * np.ones(self.k) #post = self.datapoints.jds[-1] * np.ones(self.k) pro = inttex[0] * np.ones(self.k) post = inttex[-1] * np.ones(self.k) self.t = np.concatenate((pro, inttex, post)) def getnint(self): """ Returns the number of intervals """ return(len(self.t) - 2* (self.k + 1) + 1) # Similar stuff about coeffs : def getc(self, m=0): """ Returns all active coefficients of the spline, the ones it makes sense to play with. The length of this guy is number of intervals - 2 ! """ return self.c[m:-(self.k + 1 + m)].copy() def setc(self, c, m=0): """ Puts the coeffs from getc back into place. """ self.c[m:-(self.k + 1 + m)] = c def getco(self, m=0): """ Same as getc, but reorders the coeffs in a way more suited for nonlinear optimization """ c = self.getc(m=m) mid = int(len(c)/2.0) return np.concatenate([c[mid:], c[:mid][::-1]]) def setco(self, c, m=0): """ The inverse of getco. """ mid = int(len(c)/2.0) self.setc(np.concatenate([c[mid+1:][::-1], c[:mid+1]]), m=m) def setcflat(self, c): """ Give me coeffs like those from getc(m=1), I will set the coeffs so that the spline extremas are flat (i.e. slope = 0). """ self.setc(c, m=1) self.c[0] = self.c[1] self.c[-(self.k + 2)] = self.c[-(self.k + 3)] def setcoflat(self, c): """ idem, but for reordered coeffs. """ mid = int(len(c)/2.0) self.setcflat(np.concatenate([c[mid:][::-1], c[:mid]])) def r2(self, nostab=True, nosquare=False): """ Evaluates the spline, compares it with the data points and returns a weighted sum of residuals r2. If nostab = False, stab points are included This is precisely the same r2 as is used by splrep for the fit, and thus the same value as returned by optc ! This method can set lastr2nostab, so be sure to end any optimization with it. If nostab = True, we don't count the stab points """ if nostab == True : splinemags = self.eval(nostab = True, jds = None) errs = self.datapoints.mags[self.datapoints.mask] - splinemags werrs = errs/self.datapoints.magerrs[self.datapoints.mask] if nosquare: r2 = np.sum(np.fabs(werrs)) else: r2 = np.sum(werrs * werrs) self.lastr2nostab = r2 else : splinemags = self.eval(nostab = False, jds = None) errs = self.datapoints.mags - splinemags werrs = errs/self.datapoints.magerrs if nosquare: r2 = np.sum(np.fabs(werrs)) else: r2 = np.sum(werrs * werrs) self.lastr2stab = r2 return r2 #if red: # return chi2/len(self.datapoints.jds) def tv(self): """ Returns the total variation of the spline. Simple ! http://en.wikipedia.org/wiki/Total_variation """ # Method 1 : linear approximation ptd = 5 # point density in days ... this is enough ! a = self.t[0] b = self.t[-1] x = np.linspace(a, b, int((b-a) * ptd)) y = self.eval(jds = x) tv1 = np.sum(np.fabs(y[1:] - y[:-1])) #print "TV1 : %f" % (tv1) return tv1 # Method 2 : integrating the absolute value of the derivative ... hmm, splint does not integrate derivatives .. #si.splev(jds, (self.t, self.c, self.k)) def optc(self): """ Optimize the coeffs, don't touch the knots This is the fast guy, one reason to use splines :-) Returns the chi2 in case you want it (including stabilization points) ! Sets lastr2stab, but not lastr2nostab ! """ out = si.splrep(self.datapoints.jds, self.datapoints.mags, w=1.0/self.datapoints.magerrs, xb=None, xe=None, k=self.k, task=-1, s=None, t=self.getintt(), full_output=1, per=0, quiet=1) # We check if it worked : if not out[2] <= 0: raise RuntimeError("Problem with spline representation, message = %s" % (out[3])) self.c = out[0][1] # save the coeffs #import matplotlib.pyplot as plt #plt.plot(self.datapoints.jds, self.datapoints.magerrs) #plt.show() self.lastr2stab = out[1] return out[1] def optcflat(self, verbose = False): """ Optimizes only the "border coeffs" so to get zero slope at the extrema Run optc() first ... This has to be done with an iterative optimizer """ full = self.getc(m=1) inip = self.getc(m=1)[[0, 1, -2, -1]] # 4 coeffs def setp(p): full[[0, 1, -2, -1]] = p self.setcflat(full) if verbose: print "Starting flat coeff optimization ..." print "Initial pars : ", inip def errorfct(p): setp(p) return self.r2(nostab=False) # To get the same as optc would return ! minout = spopt.fmin_powell(errorfct, inip, full_output=1, disp=verbose) popt = minout[0] if popt.shape == (): popt = np.array([popt]) if verbose: print "Optimal pars : ", popt setp(popt) return self.r2(nostab=False) # We include the stab points, like optc does. # This last line also updates self.lastr2 ... def eval(self, jds = None, nostab = True): """ Evaluates the spline at jds, and returns the corresponding mags-like vector. By default, we exclude the stabilization points ! If jds is not None, we use them instead of our own jds (in this case excludestab makes no sense) """ if jds is None: if nostab: jds = self.datapoints.jds[self.datapoints.mask] else: jds = self.datapoints.jds else: # A minimal check for non-extrapolation condition should go here ! pass fitmags = si.splev(jds, (self.t, self.c, self.k)) # By default ext=0 : we do return extrapolated values return fitmags def display(self, showbounds = True, showdatapoints = True, showerrorbars=True, figsize=(16,8)): """ A display of the spline object, with knots, jds, stab points, etc. For debugging and checks. """ fig = plt.figure(figsize=figsize) if showdatapoints: if showerrorbars: mask = self.datapoints.mask plt.errorbar(self.datapoints.jds[mask], self.datapoints.mags[mask], yerr=self.datapoints.magerrs[mask], linestyle="None", color="blue") if not np.alltrue(mask): mask = mask == False plt.errorbar(self.datapoints.jds[mask], self.datapoints.mags[mask], yerr=self.datapoints.magerrs[mask], linestyle="None", color="gray") else: plt.plot(self.datapoints.jds, self.datapoints.mags, "b,") if (np.any(self.t) != None) : if getattr(self, "showknots", True) == True: for knot in self.t: plt.axvline(knot, color="gray") # We draw the spline : xs = np.linspace(self.datapoints.jds[0], self.datapoints.jds[-1], 1000) ys = self.eval(jds = xs) plt.plot(xs, ys, "b-") if showbounds : if (np.any(self.l) != None) and (np.any(self.u) != None) : for l in self.l: plt.axvline(l, color="blue", dashes=(4, 4)) for u in self.u: plt.axvline(u, color="red", dashes=(5, 5)) axes = plt.gca() axes.set_ylim(axes.get_ylim()[::-1]) plt.show() # Some functions to interact directly with lightcurves : def fit(lcs, knotstep=20.0, n=None, knots=None, stab=True, stabext=300.0, stabgap=20.0, stabstep=5.0, stabmagerr=-2.0, stabrampsize=0, stabrampfact=1.0, bokit=1, bokeps=2.0, boktests=5, bokwindow=None, k=3, verbose=True): """ The highlevel function to make a spline fit. lcs : a list of lightcurves (I will fit the spline through the merged curves) Specify either knotstep : spacing of knots or n : how many knots to place or knots : give me actual initial knot locations, for instance prepared by seasonknots. stab : do you want to insert stabilization points ? stabext : number of days to the left and right to fill with stabilization points stabgap : interval of days considered as a gap to fill with stab points. stabstep : step of stab points stabmagerr : if negative, absolte mag err of stab points. If positive, the error bar will be stabmagerr times the median error bar of the data points. bokit : number of BOK iterations (put to 0 to not move knots) bokeps : epsilon of BOK boktests : number of test positions for each knot """ dp = merge(lcs, stab=stab, stabext=stabext, stabgap=stabgap, stabstep=stabstep, stabmagerr=stabmagerr, stabrampsize=stabrampsize, stabrampfact=stabrampfact) s = Spline(dp, k=k, bokeps=bokeps, boktests=boktests, bokwindow=bokwindow) if knots==None: if n == None: s.uniknots(nint = knotstep, n = False) else : s.uniknots(nint = n, n = True) else: s.setintt(knots) #if stab: # s.unistabknots(stabknotn,n=True) for n in range(bokit): s.buildbounds(verbose=verbose) s.bok(bokmethod="BF", verbose=verbose) s.optc() s.r2(nostab=True) # This is to set s.lastr2nostab return s def seasonknots(lcs, knotstep, ingap, seasongap=60.0): """ A little helper to get some knot locations inside of seasons only knotstep is for inside seasons ingap is the number of knots inside gaps. """ knots = [] #knotstep = 10 dp = merge(lcs, splitup=True, deltat=0.000001, sort=True, stab=False) gaps = dp.jds[1:] - dp.jds[:-1] gapindices = list(np.arange(len(dp.jds)-1)[gaps > seasongap]) # knots inside of seasons : a = dp.jds[0] for gapi in gapindices: b = dp.jds[gapi] #print (a, b) knots.append(np.linspace(a, b, float(b - a)/float(knotstep))) a = dp.jds[gapi+1] b = dp.jds[-1] knots.append(np.linspace(a, b, float(b - a)/float(knotstep))) # knots inside of gaps for gapi in gapindices: a = dp.jds[gapi] b = dp.jds[gapi+1] knots.append(np.linspace(a, b, ingap+2)[1:-1]) knots = np.concatenate(knots) knots.sort() return knots #print gapindices """ for n in range(len(gapindices)): i = gapindices[n] a = self.jds[i] b = self.jds[i+1] newgapjds = np.linspace(a, b, float(b-a)/float(self.stabstep))[1:-1] newgapindices = i + 1 + np.zeros(len(newgapjds)) newgapmags = np.interp(newgapjds, [a, b], [self.mags[i], self.mags[i+1]]) newgapmagerrs = absstabmagerr * np.ones(newgapmags.shape) newgapmask = np.zeros(len(newgapjds), dtype=np.bool) self.jds = np.insert(self.jds, newgapindices, newgapjds) knotstep """ def r2(lcs, spline, nosquare=False): """ I do not modify the spline (not even its datapoints) ! Just evaluate the quality of the match, returning an r2 (without any stab points, of course). This is used if you want to optimize something on the lightcurves without touching the spline. Of course, I do not touch lastr2nostab or lastr2stab of the spline ! So this has really nothing to do with source spline optimization ! """ myspline = spline.copy() newdp = pycs.gen.spl.merge(lcs, stab=False) # Indeed we do not care about stabilization points here. myspline.updatedp(newdp, dpmethod="leave") return myspline.r2(nostab=True, nosquare=nosquare) def mltv(lcs, spline, weight=True): """ Calculates the TV norm of the difference between a lightcurve (disregarding any microlensing !) and the spline. I return the sum over the curves in lcs. Also returns a abs(chi) like distance between the lcs without ML and the spline If weight is True, we weight the terms in sums according to their error bars. Idea : weight the total variation somehow by the error bars ! Not sure if needed, the spline is already weighted. """ #import matplotlib.pyplot as plt tv = 0.0 dist = 0.0 for l in lcs: # We have a spline, and a lightcurve lmags = l.getmags(noml = True) # We get the mags without ML (but with mag and fluxshift !) ljds = l.getjds() # Inluding any time shifts. # Evaluating the spline at those jds : splinemags = spline.eval(ljds) # The residues : res = lmags - splinemags #plt.plot(ljds, res, "r.") #plt.show() if weight == False: tv += np.sum(np.fabs(res[1:] - res[:-1])) dist += np.sum(np.fabs(res)) else: magerrs = l.getmagerrs() a = res[1:] aerrs = magerrs[1:] b = res[:-1] berrs = magerrs[:-1] vari = np.fabs(a - b) varierrs = np.sqrt(aerrs * aerrs + berrs * berrs) tv += np.sum(vari/varierrs) dist += np.sum(np.fabs(res) / np.fabs(magerrs)) return (tv, dist) def optcmltv(lcs, spline, verbose=True): """ I will optimize the coefficients of the spline so to minimize the mltv. I do not use the microlensing of the lcs at all ! Simple powell optimization, slow. A pity. Add BOK and time shifts in there and it might be bingo ! Would be more efficient if we add knots on the fly """ inic = spline.getc(m=2) def setc(c): spline.setc(c, m=2) def errorfct(c): setc(c) (tv, dist) = mltv(lcs, spline, weight=False) print "put weight" return tv + 0.1*spline.tv() minout = spopt.fmin_powell(errorfct, inic, full_output=1, disp=verbose) copt = minout[0] # We find a common shift to all coeffs so that the level matches meanc = np.mean(spline.getc(m=2)) meanmag = np.mean(np.concatenate([l.getmags(noml = True) for l in lcs])) setc(copt) spline.c += meanmag - meanc
COSMOGRAILREPO_NAMEPyCSPATH_START.@PyCS_extracted@PyCS-master@pycs@gen@spl.py@.PATH_END.py
{ "filename": "3GC_split_model_images.py", "repo_name": "IanHeywood/oxkat", "repo_path": "oxkat_extracted/oxkat-master/oxkat/3GC_split_model_images.py", "type": "Python" }
#!/usr/bin/env python # ian.heywood@physics.ox.ac.uk import glob import numpy import shutil from astropy import wcs from astropy.io import fits from optparse import OptionParser # --------------------------------------------------------------------------------------- def hms2deg(hms,delimiter=':'): """ Right ascention string in hms to float in decimal degrees """ h,m,s = hms.split(delimiter) h = float(h) m = float(m) s = float(s) deg = 15.0*(h+(m/60.0)+(s/3600.0)) return deg def dms2deg(dms,delimiter=':'): """ Declination string in dms to float in decimal degrees """ d,m,s = dms.split(delimiter) if d[0] == '-': decsign = -1.0 d = float(d[1:]) elif d[0] == '+': decsign = 1.0 d = float(d[1:]) else: decsign = 1.0 d = float(d) m = float(m) s = float(s) deg = decsign*(d+(m/60.0)+(s/3600.0)) return deg def radius2deg(radius): """ String with arcsec or arcmin unit to decimal degrees """ if radius[-1] == '"': radius = float(radius[:-1])/3600.0 elif radius[-1] == "'": radius = float(radius[:-1])/60.0 else: radius = float(radius) return radius def process_region_file(region_file): """ Extract RA,dec,radius as floats in degrees from a DS9 region file containing circles """ circles = [] f = open(region_file,'r') line = f.readline() while line: if line[0:6] == 'circle': line = line.replace(' ','') line = line.rstrip('\n').replace('(',' ').replace(')',' ') ra,dec,radius = line.split()[1].split(',') if ':' in ra: ra = hms2deg(ra) else: ra = float(ra) if ':' in dec: dec = dms2deg(dec) else: dec = float(dec) radius = radius2deg(radius) circles.append((ra,dec,radius)) line = f.readline() f.close() return circles def get_image(fits_file): """ Get the image data from a FITS file """ input_hdu = fits.open(fits_file)[0] if len(input_hdu.data.shape) == 2: image = numpy.array(input_hdu.data[:,:]) elif len(input_hdu.data.shape) == 3: image = numpy.array(input_hdu.data[0,:,:]) else: image = numpy.array(input_hdu.data[0,0,:,:]) return image def flush_fits(image,fits_file): """ Write 2D numpy array image to fits_file """ f = fits.open(fits_file,mode='update') input_hdu = f[0] if len(input_hdu.data.shape) == 2: input_hdu.data[:,:] =image elif len(input_hdu.data.shape) == 3: input_hdu.data[0,:,:] = image else: input_hdu.data[0,0,:,:] = image f.flush() def apply_circle(image,xpix,ypix,rpix): """ Apply a circle with values of 1, of radius rpix to xpix,ypix in image array """ xg,yg = numpy.mgrid[int(xpix-rpix):int(xpix+rpix)+1,int(ypix-rpix):int(ypix+rpix)+1] xg = xg.ravel() yg = yg.ravel() for i,j in zip(xg,yg): sep = ((i-xpix)**2.0 + (j-ypix)**2.0)**0.5 if sep < rpix: image[j,i] = 1.0 return image def fmt(xx): return str(round(xx,5)) def spacer(): print('--------------|---------------------------------------------') # --------------------------------------------------------------------------------------- def main(): parser = OptionParser(usage = '%prog [options]') parser.add_option('--region', dest = 'region_file', help = 'DS9 region file') parser.add_option('--prefix', dest = 'model_pattern', help = 'wsclean image prefix') parser.add_option('--subtract', dest = 'subtract', help = 'Produce model image with components within region subtracted (default = False)', action = 'store_true', default = False) (options,args) = parser.parse_args() region_file = options.region_file model_pattern = options.model_pattern subtract = options.subtract circles = process_region_file(region_file) suffix = region_file.split('/')[-1].split('.')[0] spacer() print('DS9 region : '+region_file) print('Contains : '+str(len(circles))+' circles') print('Model suffix : '+suffix) spacer() model_list = sorted(glob.glob(model_pattern+'-0*model*fits')) for fits_file in model_list: print('Reading : '+fits_file) dir1_fits = fits_file.replace(model_pattern,model_pattern+'-'+suffix) if subtract: subtract_fits = fits_file.replace(model_pattern,model_pattern+'-'+suffix+'-subtracted') img = get_image(fits_file) mask = img*0.0 hdulist = fits.open(fits_file) w = wcs.WCS(hdulist[0].header) ref_pix1 = hdulist[0].header['CRPIX1'] ref_pix2 = hdulist[0].header['CRPIX2'] pixscale = hdulist[0].header['CDELT2'] for circle in circles: ra = circle[0] dec = circle[1] coord = (ra,dec,0,0) pixels = w.wcs_world2pix([coord],0) radius = circle[2] xpix = pixels[0][0] ypix = pixels[0][1] rpix = radius/pixscale print('Masking : sky '+fmt(ra)+' '+fmt(dec)+' '+fmt(radius)) print(' : pixel '+fmt(xpix)+' '+fmt(ypix)+' '+fmt(rpix)) mask = apply_circle(mask,xpix,ypix,rpix) dir1 = img*mask print('Writing : '+dir1_fits) shutil.copyfile(fits_file,dir1_fits) flush_fits(dir1,dir1_fits) if subtract: subt = img*(1.0-mask) print('Writing : '+subtract_fits) shutil.copyfile(fits_file,subtract_fits) flush_fits(subt,subtract_fits) spacer() if __name__ == '__main__': main()
IanHeywoodREPO_NAMEoxkatPATH_START.@oxkat_extracted@oxkat-master@oxkat@3GC_split_model_images.py@.PATH_END.py
{ "filename": "_spectral.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/scipy/py3/scipy/optimize/_spectral.py", "type": "Python" }
""" Spectral Algorithm for Nonlinear Equations """ import collections import numpy as np from scipy.optimize import OptimizeResult from scipy.optimize._optimize import _check_unknown_options from ._linesearch import _nonmonotone_line_search_cruz, _nonmonotone_line_search_cheng class _NoConvergence(Exception): pass def _root_df_sane(func, x0, args=(), ftol=1e-8, fatol=1e-300, maxfev=1000, fnorm=None, callback=None, disp=False, M=10, eta_strategy=None, sigma_eps=1e-10, sigma_0=1.0, line_search='cruz', **unknown_options): r""" Solve nonlinear equation with the DF-SANE method Options ------- ftol : float, optional Relative norm tolerance. fatol : float, optional Absolute norm tolerance. Algorithm terminates when ``||func(x)|| < fatol + ftol ||func(x_0)||``. fnorm : callable, optional Norm to use in the convergence check. If None, 2-norm is used. maxfev : int, optional Maximum number of function evaluations. disp : bool, optional Whether to print convergence process to stdout. eta_strategy : callable, optional Choice of the ``eta_k`` parameter, which gives slack for growth of ``||F||**2``. Called as ``eta_k = eta_strategy(k, x, F)`` with `k` the iteration number, `x` the current iterate and `F` the current residual. Should satisfy ``eta_k > 0`` and ``sum(eta, k=0..inf) < inf``. Default: ``||F||**2 / (1 + k)**2``. sigma_eps : float, optional The spectral coefficient is constrained to ``sigma_eps < sigma < 1/sigma_eps``. Default: 1e-10 sigma_0 : float, optional Initial spectral coefficient. Default: 1.0 M : int, optional Number of iterates to include in the nonmonotonic line search. Default: 10 line_search : {'cruz', 'cheng'} Type of line search to employ. 'cruz' is the original one defined in [Martinez & Raydan. Math. Comp. 75, 1429 (2006)], 'cheng' is a modified search defined in [Cheng & Li. IMA J. Numer. Anal. 29, 814 (2009)]. Default: 'cruz' References ---------- .. [1] "Spectral residual method without gradient information for solving large-scale nonlinear systems of equations." W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006). .. [2] W. La Cruz, Opt. Meth. Software, 29, 24 (2014). .. [3] W. Cheng, D.-H. Li. IMA J. Numer. Anal. **29**, 814 (2009). """ _check_unknown_options(unknown_options) if line_search not in ('cheng', 'cruz'): raise ValueError(f"Invalid value {line_search!r} for 'line_search'") nexp = 2 if eta_strategy is None: # Different choice from [1], as their eta is not invariant # vs. scaling of F. def eta_strategy(k, x, F): # Obtain squared 2-norm of the initial residual from the outer scope return f_0 / (1 + k)**2 if fnorm is None: def fnorm(F): # Obtain squared 2-norm of the current residual from the outer scope return f_k**(1.0/nexp) def fmerit(F): return np.linalg.norm(F)**nexp nfev = [0] f, x_k, x_shape, f_k, F_k, is_complex = _wrap_func(func, x0, fmerit, nfev, maxfev, args) k = 0 f_0 = f_k sigma_k = sigma_0 F_0_norm = fnorm(F_k) # For the 'cruz' line search prev_fs = collections.deque([f_k], M) # For the 'cheng' line search Q = 1.0 C = f_0 converged = False message = "too many function evaluations required" while True: F_k_norm = fnorm(F_k) if disp: print("iter %d: ||F|| = %g, sigma = %g" % (k, F_k_norm, sigma_k)) if callback is not None: callback(x_k, F_k) if F_k_norm < ftol * F_0_norm + fatol: # Converged! message = "successful convergence" converged = True break # Control spectral parameter, from [2] if abs(sigma_k) > 1/sigma_eps: sigma_k = 1/sigma_eps * np.sign(sigma_k) elif abs(sigma_k) < sigma_eps: sigma_k = sigma_eps # Line search direction d = -sigma_k * F_k # Nonmonotone line search eta = eta_strategy(k, x_k, F_k) try: if line_search == 'cruz': alpha, xp, fp, Fp = _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta=eta) elif line_search == 'cheng': alpha, xp, fp, Fp, C, Q = _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta=eta) except _NoConvergence: break # Update spectral parameter s_k = xp - x_k y_k = Fp - F_k sigma_k = np.vdot(s_k, s_k) / np.vdot(s_k, y_k) # Take step x_k = xp F_k = Fp f_k = fp # Store function value if line_search == 'cruz': prev_fs.append(fp) k += 1 x = _wrap_result(x_k, is_complex, shape=x_shape) F = _wrap_result(F_k, is_complex) result = OptimizeResult(x=x, success=converged, message=message, fun=F, nfev=nfev[0], nit=k) return result def _wrap_func(func, x0, fmerit, nfev_list, maxfev, args=()): """ Wrap a function and an initial value so that (i) complex values are wrapped to reals, and (ii) value for a merit function fmerit(x, f) is computed at the same time, (iii) iteration count is maintained and an exception is raised if it is exceeded. Parameters ---------- func : callable Function to wrap x0 : ndarray Initial value fmerit : callable Merit function fmerit(f) for computing merit value from residual. nfev_list : list List to store number of evaluations in. Should be [0] in the beginning. maxfev : int Maximum number of evaluations before _NoConvergence is raised. args : tuple Extra arguments to func Returns ------- wrap_func : callable Wrapped function, to be called as ``F, fp = wrap_func(x0)`` x0_wrap : ndarray of float Wrapped initial value; raveled to 1-D and complex values mapped to reals. x0_shape : tuple Shape of the initial value array f : float Merit function at F F : ndarray of float Residual at x0_wrap is_complex : bool Whether complex values were mapped to reals """ x0 = np.asarray(x0) x0_shape = x0.shape F = np.asarray(func(x0, *args)).ravel() is_complex = np.iscomplexobj(x0) or np.iscomplexobj(F) x0 = x0.ravel() nfev_list[0] = 1 if is_complex: def wrap_func(x): if nfev_list[0] >= maxfev: raise _NoConvergence() nfev_list[0] += 1 z = _real2complex(x).reshape(x0_shape) v = np.asarray(func(z, *args)).ravel() F = _complex2real(v) f = fmerit(F) return f, F x0 = _complex2real(x0) F = _complex2real(F) else: def wrap_func(x): if nfev_list[0] >= maxfev: raise _NoConvergence() nfev_list[0] += 1 x = x.reshape(x0_shape) F = np.asarray(func(x, *args)).ravel() f = fmerit(F) return f, F return wrap_func, x0, x0_shape, fmerit(F), F, is_complex def _wrap_result(result, is_complex, shape=None): """ Convert from real to complex and reshape result arrays. """ if is_complex: z = _real2complex(result) else: z = result if shape is not None: z = z.reshape(shape) return z def _real2complex(x): return np.ascontiguousarray(x, dtype=float).view(np.complex128) def _complex2real(z): return np.ascontiguousarray(z, dtype=complex).view(np.float64)
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@scipy@py3@scipy@optimize@_spectral.py@.PATH_END.py
{ "filename": "spawn.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/setuptools/py3/setuptools/_distutils/spawn.py", "type": "Python" }
"""distutils.spawn Provides the 'spawn()' function, a front-end to various platform- specific functions for launching another program in a sub-process. """ from __future__ import annotations import os import platform import shutil import subprocess import sys import warnings from typing import Mapping from ._log import log from .debug import DEBUG from .errors import DistutilsExecError def _debug(cmd): """ Render a subprocess command differently depending on DEBUG. """ return cmd if DEBUG else cmd[0] def _inject_macos_ver(env: Mapping[str:str] | None) -> Mapping[str:str] | None: if platform.system() != 'Darwin': return env from .util import MACOSX_VERSION_VAR, get_macosx_target_ver target_ver = get_macosx_target_ver() update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {} return {**_resolve(env), **update} def _resolve(env: Mapping[str:str] | None) -> Mapping[str:str]: return os.environ if env is None else env def spawn(cmd, search_path=True, verbose=False, dry_run=False, env=None): """Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. There is no way to run a program with a name different from that of its executable. If 'search_path' is true (the default), the system's executable search path will be used to find the program; otherwise, cmd[0] must be the exact path to the executable. If 'dry_run' is true, the command will not actually be run. Raise DistutilsExecError if running the program fails in any way; just return on success. """ log.info(subprocess.list2cmdline(cmd)) if dry_run: return if search_path: executable = shutil.which(cmd[0]) if executable is not None: cmd[0] = executable try: subprocess.check_call(cmd, env=_inject_macos_ver(env)) except OSError as exc: raise DistutilsExecError( f"command {_debug(cmd)!r} failed: {exc.args[-1]}" ) from exc except subprocess.CalledProcessError as err: raise DistutilsExecError( f"command {_debug(cmd)!r} failed with exit code {err.returncode}" ) from err def find_executable(executable, path=None): """Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. """ warnings.warn( 'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2 ) _, ext = os.path.splitext(executable) if (sys.platform == 'win32') and (ext != '.exe'): executable = executable + '.exe' if os.path.isfile(executable): return executable if path is None: path = os.environ.get('PATH', None) # bpo-35755: Don't fall through if PATH is the empty string if path is None: try: path = os.confstr("CS_PATH") except (AttributeError, ValueError): # os.confstr() or CS_PATH is not available path = os.defpath # PATH='' doesn't match, whereas PATH=':' looks in the current directory if not path: return None paths = path.split(os.pathsep) for p in paths: f = os.path.join(p, executable) if os.path.isfile(f): # the file exists, we have a shot at spawn working return f return None
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@setuptools@py3@setuptools@_distutils@spawn.py@.PATH_END.py
{ "filename": "suspect.py", "repo_name": "astrocatalogs/supernovae", "repo_path": "supernovae_extracted/supernovae-master/tasks/suspect.py", "type": "Python" }
"""Import tasks for SUSPECT. """ import csv import json import os import re import urllib from glob import glob from html import unescape from math import floor from astropy.time import Time as astrotime from bs4 import BeautifulSoup from astrocats.catalog.utils import (get_sig_digits, is_number, jd_to_mjd, pbar, pbar_strings, pretty_num, uniq_cdl) from decimal import Decimal from ..supernova import SUPERNOVA def do_suspect_photo(catalog): task_str = catalog.get_current_task_str() with open( os.path.join(catalog.get_current_task_repo(), 'suspectreferences.csv'), 'r') as f: tsvin = csv.reader(f, delimiter=',', skipinitialspace=True) suspectrefdict = {} for row in tsvin: suspectrefdict[row[0]] = row[1] file_names = list( sorted( glob( os.path.join(catalog.get_current_task_repo(), 'SUSPECT/*.html')))) for datafile in pbar_strings(file_names, task_str): basename = os.path.basename(datafile) basesplit = basename.split('-') oldname = basesplit[1] name = catalog.add_entry(oldname) if name.startswith('SN') and is_number(name[2:]): name = name + 'A' band = basesplit[3].split('.')[0] ei = int(basesplit[2]) bandlink = 'file://' + os.path.abspath(datafile) bandresp = urllib.request.urlopen(bandlink) bandsoup = BeautifulSoup(bandresp, 'html5lib') bandtable = bandsoup.find('table') names = bandsoup.body.findAll(text=re.compile('Name')) reference = '' for link in bandsoup.body.findAll('a'): if 'adsabs' in link['href']: reference = str(link).replace('"', "'") bibcode = unescape(suspectrefdict[reference]) source = catalog.entries[name].add_source(bibcode=bibcode) sec_ref = 'SUSPECT' sec_refurl = 'https://www.nhn.ou.edu/~suspect/' sec_source = catalog.entries[name].add_source( name=sec_ref, url=sec_refurl, secondary=True) catalog.entries[name].add_quantity(SUPERNOVA.ALIAS, oldname, sec_source) if ei == 1: year = re.findall(r'\d+', name)[0] catalog.entries[name].add_quantity(SUPERNOVA.DISCOVER_DATE, year, sec_source) catalog.entries[name].add_quantity( SUPERNOVA.HOST, names[1].split(':')[1].strip(), sec_source) redshifts = bandsoup.body.findAll(text=re.compile('Redshift')) if redshifts: catalog.entries[name].add_quantity( SUPERNOVA.REDSHIFT, redshifts[0].split(':')[1].strip(), sec_source, kind='heliocentric') # hvels = bandsoup.body.findAll(text=re.compile('Heliocentric # Velocity')) # if hvels: # vel = hvels[0].split(':')[1].strip().split(' ')[0] # catalog.entries[name].add_quantity(SUPERNOVA.VELOCITY, vel, # sec_source, # kind='heliocentric') types = bandsoup.body.findAll(text=re.compile('Type')) catalog.entries[name].add_quantity( SUPERNOVA.CLAIMED_TYPE, types[0].split(':')[1].strip().split(' ')[0], sec_source) for r, row in enumerate(bandtable.findAll('tr')): if r == 0: continue col = row.findAll('td') mjd = str(jd_to_mjd(Decimal(col[0].contents[0]))) mag = col[3].contents[0] if mag.isspace(): mag = '' else: mag = str(mag) e_magnitude = col[4].contents[0] if e_magnitude.isspace(): e_magnitude = '' else: e_magnitude = str(e_magnitude) catalog.entries[name].add_photometry( time=mjd, u_time='MJD', band=band, magnitude=mag, e_magnitude=e_magnitude, source=sec_source + ',' + source) catalog.journal_entries() return def do_suspect_spectra(catalog): task_str = catalog.get_current_task_str() with open( os.path.join(catalog.get_current_task_repo(), 'Suspect/sources.json'), 'r') as f: sourcedict = json.loads(f.read()) with open( os.path.join(catalog.get_current_task_repo(), 'Suspect/filename-changes.txt'), 'r') as f: rows = f.readlines() changedict = {} for row in rows: if not row.strip() or row[0] == "#": continue items = row.strip().split(' ') changedict[items[1]] = items[0] suspectcnt = 0 folders = next( os.walk(os.path.join(catalog.get_current_task_repo(), 'Suspect')))[1] for folder in pbar(folders, task_str): eventfolders = next( os.walk( os.path.join(catalog.get_current_task_repo(), 'Suspect/') + folder))[1] oldname = '' for eventfolder in pbar(eventfolders, task_str): name = eventfolder if is_number(name[:4]): name = 'SN' + name name = catalog.get_preferred_name(name) if oldname and name != oldname: catalog.journal_entries() oldname = name name = catalog.add_entry(name) sec_ref = 'SUSPECT' sec_refurl = 'https://www.nhn.ou.edu/~suspect/' sec_bibc = '2001AAS...199.8408R' sec_source = catalog.entries[name].add_source( name=sec_ref, url=sec_refurl, bibcode=sec_bibc, secondary=True) catalog.entries[name].add_quantity(SUPERNOVA.ALIAS, name, sec_source) fpath = os.path.join(catalog.get_current_task_repo(), 'Suspect', folder, eventfolder) eventspectra = next(os.walk(fpath))[2] for spectrum in eventspectra: sources = [sec_source] bibcode = '' if spectrum in changedict: specalias = changedict[spectrum] else: specalias = spectrum if specalias in sourcedict: bibcode = sourcedict[specalias] elif name in sourcedict: bibcode = sourcedict[name] if bibcode: source = catalog.entries[name].add_source( bibcode=unescape(bibcode)) sources += [source] sources = uniq_cdl(sources) date = spectrum.split('_')[1] year = date[:4] month = date[4:6] day = date[6:] sig = get_sig_digits(day) + 5 day_fmt = str(floor(float(day))).zfill(2) time = astrotime(year + '-' + month + '-' + day_fmt).mjd time = time + float(day) - floor(float(day)) time = pretty_num(time, sig=sig) fpath = os.path.join(catalog.get_current_task_repo(), 'Suspect', folder, eventfolder, spectrum) with open(fpath, 'r') as f: specdata = list( csv.reader( f, delimiter=' ', skipinitialspace=True)) specdata = list(filter(None, specdata)) newspec = [] oldval = '' for row in specdata: if row[1] == oldval: continue newspec.append(row) oldval = row[1] specdata = newspec haserrors = len(specdata[0]) == 3 and specdata[0][ 2] and specdata[0][2] != 'NaN' specdata = [list(i) for i in zip(*specdata)] wavelengths = specdata[0] fluxes = specdata[1] errors = '' if haserrors: errors = specdata[2] catalog.entries[name].add_spectrum( u_wavelengths='Angstrom', u_fluxes='Uncalibrated', u_time='MJD', time=time, wavelengths=wavelengths, fluxes=fluxes, errors=errors, u_errors='Uncalibrated', source=sources, filename=spectrum) suspectcnt = suspectcnt + 1 if (catalog.args.travis and suspectcnt % catalog.TRAVIS_QUERY_LIMIT == 0): break catalog.journal_entries() return
astrocatalogsREPO_NAMEsupernovaePATH_START.@supernovae_extracted@supernovae-master@tasks@suspect.py@.PATH_END.py
{ "filename": "dev_ops.md", "repo_name": "andreatramacere/jetset", "repo_path": "jetset_extracted/jetset-master/dev_ops.md", "type": "Markdown" }
## local operations - update version: update the tag in `jetset/pkg_info.json` - clean `__pycache__`: ```find . -type d -name __pycache__ | xargs rm -r``` - If you want to make a tag you can use the script, the `-do_remote_tag` option will create the tag remotely, deleting remotely the one with the same name, e.g.: - `./make_tag.py -tag 1.1.2 -do_remote_tag` To use as tag the current version - `./make_tag.py -do_remote_tag` To just print the tag without creating it: - `./make_tag.py -dry` ## operations on the action workflow - If you want to create a release from the same branch of the workflow 1) set the release tag in the 'tag to create a release' field - If you want to create a release from a specific tag or branch (different from the branch of the workflow) 1) set the git tag in the `checkout this tag` field of the action wf 2) set the release tag in the `tag to create a release` field of action wf - when publishing a new version create both the tag for the version and the stable - Anaconda `meta.yaml` is built from `requirements.txt` using: `python .github/workflows/requirements_to_conda_yml.py` directly in the action wf - if you do not pass a `tag to create a release` value, the Release will not be created - to run test on action leave the `skip test` form empty, otherwise type `yes` to skip the tests ## testing locally <!-- - python -c"import iminuit; print('iminuit',iminuit.__version__); import jetset; print('jetset',jetset.#__version__)" --> - user test: - `pytest --pyargs -vvv jetset.tests.test_users::TestUser` - specific module test (eg: test_jet_model): - `pytest --pyargs -vvv -s jetset.tests.test_jet_model` - integration test : - `pytest --pyargs -vvv jetset.tests.test_integration::TestIntegration` - test a specificmethod: - `pytest --pyargs -vvv jetset.tests.test_integration::TestIntegration::tets_method` ## Installation - installing from source without setup.py install - `rm -rf ./build` - `pip install --verbose .`
andreatramacereREPO_NAMEjetsetPATH_START.@jetset_extracted@jetset-master@dev_ops.md@.PATH_END.py
{ "filename": "nasm.py", "repo_name": "duvall3/rat-pac", "repo_path": "rat-pac_extracted/rat-pac-master/python/SCons/Tool/nasm.py", "type": "Python" }
"""SCons.Tool.nasm Tool-specific initialization for nasm, the famous Netwide Assembler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/nasm.py 4043 2009/02/23 09:06:45 scons" import SCons.Defaults import SCons.Tool import SCons.Util ASSuffixes = ['.s', '.asm', '.ASM'] ASPPSuffixes = ['.spp', '.SPP', '.sx'] if SCons.Util.case_sensitive_suffixes('.s', '.S'): ASPPSuffixes.extend(['.S']) else: ASSuffixes.extend(['.S']) def generate(env): """Add Builders and construction variables for nasm to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) env['AS'] = 'nasm' env['ASFLAGS'] = SCons.Util.CLVar('') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES' def exists(env): return env.Detect('nasm') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
duvall3REPO_NAMErat-pacPATH_START.@rat-pac_extracted@rat-pac-master@python@SCons@Tool@nasm.py@.PATH_END.py
{ "filename": "test_endpoint.py", "repo_name": "jdswinbank/Comet", "repo_path": "Comet_extracted/Comet-master/comet/utility/test/test_endpoint.py", "type": "Python" }
from twisted.internet import reactor from twisted.trial import unittest from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint class coerce_to_client_endpoint_TestCase(unittest.TestCase): HOST, PORT, DEFAULT_PORT = "test", 1234, 4321 def test_good_tcp_parse(self): ep = coerce_to_client_endpoint( reactor, f"tcp:{self.HOST}:{self.PORT}", self.DEFAULT_PORT ) self.assertEqual(ep._host, self.HOST) self.assertEqual(ep._port, self.PORT) def test_good_unix_parse(self): filename = "/dev/null" ep = coerce_to_client_endpoint(reactor, f"unix:{filename}", self.DEFAULT_PORT) self.assertEqual(ep._path, filename) def test_missing_protocol(self): ep = coerce_to_client_endpoint( reactor, f"{self.HOST}:{self.PORT}", self.DEFAULT_PORT ) self.assertEqual(ep._host, self.HOST) self.assertEqual(ep._port, self.PORT) def test_missing_port(self): ep = coerce_to_client_endpoint(reactor, f"tcp:{self.HOST}", self.DEFAULT_PORT) self.assertEqual(ep._host, self.HOST) self.assertEqual(ep._port, self.DEFAULT_PORT) def test_missing_both(self): ep = coerce_to_client_endpoint(reactor, self.HOST, self.DEFAULT_PORT) self.assertEqual(ep._host, self.HOST) self.assertEqual(ep._port, self.DEFAULT_PORT) def test_bad_parse(self): self.assertRaises( ValueError, coerce_to_client_endpoint, reactor, "tcp:tcp:tcp", self.DEFAULT_PORT, ) class coerce_to_server_endpoint_TestCase(unittest.TestCase): PORT = 1234 def test_good_tcp_parse(self): ep = coerce_to_server_endpoint(reactor, f"tcp:{self.PORT}") self.assertEqual(ep._port, self.PORT) def test_good_unix_parse(self): filename = "/dev/null" ep = coerce_to_server_endpoint(reactor, f"unix:{filename}") self.assertEqual(ep._address, filename) def test_missing_protocol(self): ep = coerce_to_server_endpoint(reactor, self.PORT) self.assertEqual(ep._port, self.PORT) def test_bad_parse(self): self.assertRaises(ValueError, coerce_to_server_endpoint, reactor, "tcp:")
jdswinbankREPO_NAMECometPATH_START.@Comet_extracted@Comet-master@comet@utility@test@test_endpoint.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "OpenAccess-AI-Collective/axolotl", "repo_path": "axolotl_extracted/axolotl-main/src/axolotl/core/trainers/__init__.py", "type": "Python" }
OpenAccess-AI-CollectiveREPO_NAMEaxolotlPATH_START.@axolotl_extracted@axolotl-main@src@axolotl@core@trainers@__init__.py@.PATH_END.py
{ "filename": "3)_Simple_Visualization.ipynb", "repo_name": "rennehan/yt-swift", "repo_path": "yt-swift_extracted/yt-swift-main/doc/source/quickstart/3)_Simple_Visualization.ipynb", "type": "Jupyter Notebook" }
# Simple Visualizations of Data Just like in our first notebook, we have to load yt and then some data. ```python import yt ``` For this notebook, we'll load up a cosmology dataset. ```python ds = yt.load_sample("enzo_tiny_cosmology") print("Redshift =", ds.current_redshift) ``` In the terms that yt uses, a projection is a line integral through the domain. This can either be unweighted (in which case a column density is returned) or weighted, in which case an average value is returned. Projections are, like all other data objects in yt, full-fledged data objects that churn through data and present that to you. However, we also provide a simple method of creating Projections and plotting them in a single step. This is called a Plot Window, here specifically known as a `ProjectionPlot`. One thing to note is that in yt, we project all the way through the entire domain at a single time. This means that the first call to projecting can be somewhat time consuming, but panning, zooming and plotting are all quite fast. yt is designed to make it easy to make nice plots and straightforward to modify those plots directly. The cookbook in the documentation includes detailed examples of this. ```python p = yt.ProjectionPlot(ds, "y", ("gas", "density")) p.show() ``` The `show` command simply sends the plot to the IPython notebook. You can also call `p.save()` which will save the plot to the file system. This function accepts an argument, which will be prepended to the filename and can be used to name it based on the width or to supply a location. Now we'll zoom and pan a bit. ```python p.zoom(2.0) ``` ```python p.pan_rel((0.1, 0.0)) ``` ```python p.zoom(10.0) ``` ```python p.pan_rel((-0.25, -0.5)) ``` ```python p.zoom(0.1) ``` If we specify multiple fields, each time we call `show` we get multiple plots back. Same for `save`! ```python p = yt.ProjectionPlot( ds, "z", [("gas", "density"), ("gas", "temperature")], weight_field=("gas", "density"), ) p.show() ``` We can adjust the colormap on a field-by-field basis. ```python p.set_cmap(("gas", "temperature"), "hot") ``` And, we can re-center the plot on different locations. One possible use of this would be to make a single `ProjectionPlot` which you move around to look at different regions in your simulation, saving at each one. ```python v, c = ds.find_max(("gas", "density")) p.set_center((c[0], c[1])) p.zoom(10) ``` Okay, let's load up a bigger simulation (from `Enzo_64` this time) and make a slice plot. ```python ds = yt.load_sample("Enzo_64/DD0043/data0043") s = yt.SlicePlot( ds, "z", [("gas", "density"), ("gas", "velocity_magnitude")], center="max" ) s.set_cmap(("gas", "velocity_magnitude"), "cmyt.pastel") s.zoom(10.0) ``` We can adjust the logging of various fields: ```python s.set_log(("gas", "velocity_magnitude"), True) ``` yt provides many different annotations for your plots. You can see all of these in the documentation, or if you type `s.annotate_` and press tab, a list will show up here. We'll annotate with velocity arrows. ```python s.annotate_velocity() ``` Contours can also be overlaid: ```python s = yt.SlicePlot(ds, "x", ("gas", "density"), center="max") s.annotate_contour(("gas", "temperature")) s.zoom(2.5) ``` Finally, we can save out to the file system. ```python s.save() ```
rennehanREPO_NAMEyt-swiftPATH_START.@yt-swift_extracted@yt-swift-main@doc@source@quickstart@3)_Simple_Visualization.ipynb@.PATH_END.py
{ "filename": "README.md", "repo_name": "desihub/desitarget", "repo_path": "desitarget_extracted/desitarget-main/py/desitarget/streams/gaia_dr3_parallax_zero_point/README.md", "type": "Markdown" }
## Attribution The code and coefficient files in this directory are a snapshot of the [gaiadr3_zeropoint](https://gitlab.com/icc-ub/public/gaiadr3_zeropoint/-/blob/master/) package (downloaded on 2024-03-05). Please refer to [the original code](https://gitlab.com/icc-ub/public/gaiadr3_zeropoint/) for details and attribution. ## License The contents of this (and only this) directory retain the original [GNU LESSER GENERAL PUBLIC LICENSE included herein](./LICENSE). ## Justification The gaiadr3_zeropoint package includes some dependencies that are not supported by [desihub](https://github.com/desihub) and the DESI project. We have therefore taken a snapshot of the package to simplify maintenance of the DESI software stack.
desihubREPO_NAMEdesitargetPATH_START.@desitarget_extracted@desitarget-main@py@desitarget@streams@gaia_dr3_parallax_zero_point@README.md@.PATH_END.py
{ "filename": "_exponentformat.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/parcoords/line/colorbar/_exponentformat.py", "type": "Python" }
import _plotly_utils.basevalidators class ExponentformatValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="exponentformat", parent_name="parcoords.line.colorbar", **kwargs, ): super(ExponentformatValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), values=kwargs.pop("values", ["none", "e", "E", "power", "SI", "B"]), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@parcoords@line@colorbar@_exponentformat.py@.PATH_END.py
{ "filename": "likelihood.py", "repo_name": "aconley/mbb_emcee", "repo_path": "mbb_emcee_extracted/mbb_emcee-master/mbb_emcee/likelihood.py", "type": "Python" }
import numpy as np import math import copy from .modified_blackbody import modified_blackbody from .response import response, response_set, special_types __all__ = ["likelihood"] #hack for basestring try: basestring except: #Python 3 basestring = str class likelihood(object): """Class holding data, defining likelihood""" _param_order = {'t': 0, 't/(1+z)': 0, 'beta': 1, 'lambda0': 2, 'lambda0*(1+z)': 2, 'lambda_0': 2, 'lambda_0*(1+z)': 2, 'alpha': 3, 'fnorm': 4, 'f500': 4} def __init__(self, photfile=None, covfile=None, covextn=0, wavenorm=500.0, noalpha=False, opthin=False, response=False, responsefile=None, responsedir=None): """ Object for computing likelihood of a given set of parameters. Parameters ---------- photfile : string Text file containing photometry covfile : string FITS file containing covariance matrix. None for no file covextn : integer Extension of covaraince file wavenorm : float Wavelength of normalization in microns noalpha : bool Ignore alpha in fit opthin : bool Assume optically thin response : bool Use response integration responsefile : string Name of file containing response specifications if not using standard set. Ignored unless response is set. responsedir : string Directory to look for response files in. Ignored unless response is set """ self._wavenorm = float(wavenorm) self._noalpha = bool(noalpha) self._opthin = bool(opthin) # Set up information about fixed params, param limits, and # priors. # All parameters have lower limits # Make these small but slightly larger than 0, except # for T, which shouldn't get too small or odd things happen # Keep in mind the minimum Temperature should be Tcmb*(1+z) # so as long as we stay above that self._lowlim = np.array([1, 0.1, 1, 0.1, 1e-3]) # That includes setting up a dictionary that includes the # lambda peak prior for gaussian priors and upper limits self._limprior_order = copy.copy(self._param_order) self._limprior_order.update({'lambda_peak': 5, 'peaklam': 5, 'lambdapeak': 5, 'peak_lambda': 5}) # Setup upper limits; note that alpha and beta have # upper limits by default. The last element is on the peak lambda self._has_uplim = [False, True, False, True, False, False] inf = float("inf") self._uplim = np.array([inf, 20.0, inf, 20.0, inf, inf]) # Setup Gaussian prior on params plus peak lambda self._any_gprior = False self._has_gprior = [False, False, False, False, False, False] self._gprior_mean = np.zeros(6) self._gprior_sigma = np.zeros(6) self._gprior_ivar = np.ones(6) # Responses self._response_integrate = False if response: self.read_responses(responsefile, responsedir=responsedir) # Data self._data_read = False self._has_covmatrix = False if not photfile is None: self.read_phot(photfile) if not covfile is None: if not isinstance(covfile, basestring): raise TypeError("covfile must be string-like") self.read_cov(covfile, extn=covextn) # Reset normalization flux lower limit based on data self._lowlim[4] = 1e-3 * self._flux.min() else: if not covfile is None: raise Exception("Can't pass in covfile if no photfile") self._badval = float("-inf") @property def wavenorm(self): """ Normalization wavelength in microns""" return self._wavenorm @property def noalpha(self): """ Not including a blue side power law?""" return self._noalpha @property def opthin(self): """ Assuming an optically thin model?""" return self._opthin @property def response_integrate(self): """Is filter integration being used?""" return self._response_integrate def read_responses(self, responsefile=None, responsedir=None): """ Read in responses Parameters ---------- responsefile : string File containing filter specification information. If None, reads default information. responsedir : string Directory to look for actual responses in. Notes ----- Calling this turns on filter integration """ self._responsewheel = response_set(responsefile, dir=responsedir) self._response_integrate = True def set_phot(self, firstarg, flux, flux_unc): """ Sets photometry Parameters ---------- firstarg : array like If using response integration, a string array of response names. Otherwise, an array of wavelengths, in microns flux : array like Array of flux densities, in mJy flux_unc : array like Array of flux density uncertainties, in mJy Notes ----- This wipes out any covariance matrix already present, and turns off response integration """ if self._response_integrate: # Get filter responses in same order as photometry if not isinstance(firstarg[0], basestring): raise ValueError("Expecting response string name") self._responses = [] for name in firstarg: # Make sure we have, or can construct, the right passband if not name in self._responsewheel: # Figure out if it's a 'special' one (delta, boxcar, alma) # these are -assumed- to be frequency, since the usual # use is to add interferometer tunable passbands if name.find('_'): # May be -- split off first part bs = name.split('_')[1].lower() if bs in special_types: # Add it! self._responsewheel.add_special(name) else: errstr = "Unknown filter response {:s}" raise ValueError(errstr.format(name)) else: errstr = "Unknown filter response {:s}" raise ValueError(errstr.format(name)) self._responses.append(self._responsewheel[name]) self._response_names = [r.name for r in self._responses] self._wave = np.array([resp.effective_wavelength for resp in self._responses]) else: self._wave = np.asarray(firstarg, dtype=np.float64) self._ndata = len(self._wave) if self._ndata == 0: raise ValueError("No elements in wavelength vector") self._flux = np.asarray(flux) self._flux_unc = np.asarray(flux_unc) if self._ndata != len(self._flux): raise ValueError("wave not same length as flux") if self._ndata != len(self._flux_unc): raise ValueError("wave not same length as flux_unc") self._ivar = 1.0 / self._flux_unc**2 # Set upper limit on lambda0 -- if its 3x above # our longest wavelength point, we can't say anything # about it. if not self._has_uplim[2]: self._has_uplim[2] = True self._uplim[2] = 3.0 * self._wave.max() self._data_read = True self._has_covmatrix = False def read_phot(self, filename): """Reads in the photometry file Parameters ---------- filename : string Name of file to read input from. This file should have three columns: the wavelength [microns], the flux density [mJy], and the uncertainty in the flux density [mJy]. Notes ----- This wipes out any covariance matrix present """ import astropy.io.ascii if not isinstance(filename, basestring): raise TypeError("filename must be string-like") data = astropy.io.ascii.read(filename, comment='^#') if len(data) == 0: errstr = "No data read from %s" % filename raise IOError(errstr) self.set_phot([dat[0] for dat in data], [dat[1] for dat in data], [dat[2] for dat in data]) @property def data_read(self): """ Has the data been set?""" return self._data_read @property def ndata(self): """ The number of data points""" if self._data_read: return self._ndata else: return 0 @property def data_wave(self): """ The data wavelengths, in microns""" if self._data_read: return self._wave else: return None @property def response_names(self): """ Returns names of responses corresponding to data""" if not hasattr(self, '_response_names'): return None return self._response_names def has_response(self, name): """ Is the specified response function available?""" if not hasattr(self, '_responsewheel'): return False return name in self._responsewheel def get_response(self, name): """ Return the matching response object""" if not hasattr(self, '_responsewheel'): return None return self._responsewheel[name] @property def data_flux(self): """ The flux densities, in mJy""" if self._data_read: return self._flux else: return None @property def data_flux_unc(self): """ The uncertainties in the flux densities, in mJy. Notes ----- If a covariance matrix is available, these values are not used by the fits. """ if self._data_read: if self._has_covmatrix: return np.sqrt(np.diag(self._covmatrix)) else: return self._flux_unc else: return None def set_cov(self, covmatrix): """ Sets covariance matrix Parameters ---------- covmatrix : array like Covariance matrix """ if not self._data_read: raise Exception("Can't set covariance matrix without photometry") if len(covmatrix.shape) != 2: raise ValueError("Covariance matrix is not 2 dimensional") if covmatrix.shape[0] != covmatrix.shape[1]: errstr = "Covariance matrix from is not square: %d by %d" raise ValueError(errstr % covmatrix.shape) if covmatrix.shape[0] != self._ndata: errstr = "Covariance matrix doesn't have same number of "\ "datapoints as photometry; {0:d} vs. {1:d}" raise ValueError(errstt.format(covmatrix.shape[0], self._ndata)) self._covmatrix = covmatrix self._invcovmatrix = np.linalg.inv(self._covmatrix) self._has_covmatrix = True def read_cov(self, filename, extn=0): """Reads in the covariance matrix from a FITS file. Parameters ---------- filename : string File to read covariance matrix from extn : int Extension to look for covariance matrix in """ import astropy.io.fits if not self._data_read: raise Exception("Can't read in covaraince matrix without phot") hdu = astropy.io.fits.open(filename) self.set_cov(hdu[extn].data) @property def has_data_covmatrix(self): """ Does this object have a flux density covariance matrix?""" return self._has_covmatrix @property def data_covmatrix(self): """ The covariance matrix of the flux densities, in mJy^2""" if self._has_covmatrix: return self._covmatrix else: return None @property def data_invcovmatrix(self): """ Get inverse covariance matrix""" if self._has_covmatrix: return self._invcovmatrix else: return None def get_paramindex(self, paramname): """ Convert the name of a parameter into its index. Parameters ---------- paramname : string Name of parameter (e.g., 'beta') Returns ------- index : int Parameter index """ return self._param_order[paramname] def set_lowlim(self, param, val): """Sets the specified parameter lower limit to value. Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. """ if isinstance(param, str): self._lowlim[self._param_order[param.lower()]] = val else: self._lowlim[param] = val def lowlim(self, param): """Gets the specified parameter lower limit Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. """ if isinstance(param, str): paramidx = self._param_order[param.lower()] else: paramidx = int(param) return self._lowlim[paramidx] @property def lowlims(self): """ Get the list of lower parameter limits. Returns ------- lowlims : ndarray The order is T/(1+z), beta, lambda0 (1+z), alpha, fnorm. """ return self._lowlim def set_uplim(self, param, val): """Sets the specified parameter upper limit to value. Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. val : float The upper limit to set. """ if isinstance(param, str): paramidx = self._limprior_order[param.lower()] else: paramidx = int(param) self._has_uplim[paramidx] = True self._uplim[paramidx] = val def has_uplim(self, param): """ Does the likelihood have an upper limit for a given parameter? Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. Returns ------- val : bool True if there is an upper limit, false otherwise """ if isinstance(param, str): paramidx = self._limprior_order[param.lower()] else: paramidx = int(param) return self._has_uplim[paramidx] def uplim(self, param): """ What is the upper limit for a given parameter? Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. Returns ------- val : float Upper limit, or None if there isn't one """ if isinstance(param, str): paramidx = self._limprior_order[param.lower()] else: paramidx = int(param) if not self._has_uplim[paramidx]: return None return self._uplim[paramidx] @property def has_uplims(self): return self._has_uplim @property def uplims(self): return self._uplim def set_gaussian_prior(self, param, mean, sigma): """Sets up a Gaussian prior on the specified parameter. Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. The parameters are the usual (T, beta, lambda0, alpha, fnorm) plus the peak wavelength in microns mean : float Mean of Gaussian prior sigma : float Sigma of Gaussian prior """ if isinstance(param, str): paramidx = self._limprior_order[param.lower()] else: paramidx = int(param) self._any_gprior = True self._has_gprior[paramidx] = True self._gprior_mean[paramidx] = float(mean) self._gprior_sigma[paramidx] = float(sigma) self._gprior_ivar[paramidx] = 1.0 / (float(sigma)**2) @property def has_gpriors(self): return self._has_gprior @property def gprior_means(self): return self._gprior_mean @property def gprior_sigmas(self): return self._gprior_sigma @property def gprior_ivars(self): return self._gprior_ivar def has_gaussian_prior(self, param): """ Does the given parameter have a Gaussian prior set? Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. The parameters are the usual (T, beta, lambda0, alpha, fnorm) plus the peak wavelength in microns Returns ------- has_prior : bool True if a Gaussian prior is set, False otherwise """ if isinstance(param, str): paramidx = self._limprior_order[param.lower()] else: paramidx = int(param) return self._has_gprior[paramidx] def get_gaussian_prior(self, param): """ Return Gaussian prior values Parameters ---------- param : int or string Parameter specification. Either an index into the parameter list, or a string name for the parameter. The parameters are the usual (T, beta, lambda0, alpha, fnorm) plus the peak wavelength in microns Returns ------- tup : tuple or None Mean, variance if set, None otherwise """ if not self._any_gprior: return None if isinstance(param, str): paramidx = self._limprior_order[param.lower()] else: paramidx = int(param) if not self._has_gprior[paramidx]: return None return (self._gprior_mean[paramidx], self._gprior_sigma[paramidx]) def _check_lowlim(self, pars): """Checks to see if a given parameter set passes the lower limits. Parameters ---------- pars : array like 5 element list of parameters (T, beta, lambda0, alpha, fnorm). Returns ------- pass_check : bool True if it passes, False if it doesn't. Notes ----- Unlike the upper limits, in the most common case the SED simply can't be compuated below the lower limits, so we can't just apply a likelihood penalty. """ if len(pars) != 5: raise ValueError("pars is not of expected length 5") for idx, val in enumerate(pars): if val < self._lowlim[idx]: return False return True def _uplim_prior(self, pars): """ Gets log likelihood of upper limit priors Parameters ---------- pars : array like 5 element list of parameters (T, beta, lambda0, alpha, fnorm). Returns ------- like_penalty : float Penalty to apply to log likelihood based on these parameters. This should be added to the log likelihood (that is, it is negative). Notes ----- For values above the upper limit, applies a Gaussian penalty centered at the limit with sigma = limit range/50.0. A soft upper limit seems to work better than a hard one. In addition to the actual fit parameters, it is possible to have a prior on the peak lambda. """ # This should only be called if _set_sed has already been called if len(pars) != 5: raise ValueError("pars is not of expected length 5") logpenalty = 0.0 for idx, val in enumerate(pars): if self._has_uplim[idx]: lim = self._uplim[idx] if val > lim: limvar = (0.02 * (lim - self._lowlim[idx]))**2 logpenalty -= 0.5*(val - lim)**2 / limvar # Peak lambda if self._has_uplim[5]: val = self._sed.max_wave() # _set_sed had better have been called lim = self._uplim[5] if val > lim: limvar = (0.02 * (lim))**2 logpenalty -= 0.5*(val - lim)**2 / limvar return logpenalty def _gprior(self, pars): """ Gets log likelihood of Gaussian priors Parameters ---------- pars : array like 5 element list of parameters (T, beta, lambda0, alpha, fnorm). Returns ------- like_penalty : float Penalty to apply to log likelihood based on these parameters. This should be added to the log likelihood (that is, it is negative). """ # This should only be called if _set_sed has already been called if not self._any_gprior: return 0.0 penalty = 0.0 # Parameter priors for idx, val in enumerate(pars): if self._has_gprior[idx]: delta = val - self._gprior_mean[idx] penalty -= 0.5 * self._gprior_ivar[idx] * delta**2 # Peak lambda prior if self._has_gprior[5]: delta = self._sed.max_wave() - self._gprior_mean[5] penalty -= 0.5 * self._gprior_ivar[5] * delta**2 return penalty def _set_sed(self, pars): """ Set up the SED for the provided parameters Parameters ---------- pars : array like 5 element list of parameters (T, beta, lambda0, alpha, fnorm). """ if len(pars) != 5: raise ValueError("pars is not of expected length 5") self._sed = modified_blackbody(pars[0], pars[1], pars[2], pars[3], pars[4], wavenorm=self._wavenorm, noalpha=self._noalpha, opthin=self._opthin) def get_sed(self, pars, wave): """ Get the model SED at the specified wavelengths for a set of params. Parameters ---------- pars : array like 5 element list of parameters (T, beta, lambda0, alpha, fnorm). wave : array like Wavelengths, in microns Returns ------- sed : ndarray SED of the parameters in mJy at the specified wavelengths. """ self._set_sed(pars) return self._sed(wave) def __call__(self, pars): """ Gets log likelihood of the parameters. Parameters ---------- pars : array like 5 element list of parameters (T, beta, lambda0, alpha, fnorm). Returns ------- log_likelihood : float log P(pars | data), including priors and limits. """ # First check limits # Return large negative number if bad if not self._check_lowlim(pars): return self._badval # Set up SED model self._set_sed(pars) # Get model fluxes for comparison with data if self._response_integrate: model_flux = np.array([resp(self._sed) for resp in self._responses]) else: model_flux = self._sed(self._wave) # Compute likelihood # Assume Gaussian uncertanties, ignore constant prefactor diff = self._flux - model_flux if self._has_covmatrix: lnlike = -0.5 * np.dot(diff, np.dot(self._invcovmatrix, diff)) else: lnlike = -0.5 * np.sum(diff**2 * self._ivar) # Add in upper limit priors to likelihood lnlike += self._uplim_prior(pars) # Add Gaussian priors to likelihood if self._any_gprior: lnlike += self._gprior(pars) return lnlike
aconleyREPO_NAMEmbb_emceePATH_START.@mbb_emcee_extracted@mbb_emcee-master@mbb_emcee@likelihood.py@.PATH_END.py
{ "filename": "5_residual_profiles.py", "repo_name": "ldolan05/ACID", "repo_path": "ACID_extracted/ACID-main/.other_scripts/5_residual_profiles.py", "type": "Python" }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 22 14:14:17 2021 @author: lucydolan """ import numpy as np import math import glob import Mandel_Agol as ma from scipy.interpolate import interp1d from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.optimize import curve_fit import matplotlib.pyplot as plt from astropy.io import fits from matplotlib.pyplot import cm #def combineccfs(spectra): # spectrum[:] = np.sum(spectra[:])/len(spectra[:]) #return spectrum def gauss(x, rv, sd, height, cont): y = cont*(1-height*np.exp(-(x-rv)**2/(2*sd**2))) return y def residualccfs(in_ccfs, in_ccfs_errors, master_out, master_out_errors, velocities): residuals=[] residual_errors = [] #plt.figure('residuals') for i in range(len(in_ccfs)): ccf = in_ccfs[i] ccf_err = in_ccfs_errors[i] residual = (master_out+1)-(ccf+1) error = (np.sqrt(master_out_errors**2 + ccf_err**2))/np.sqrt(len(ccf_err)) #residual = (ccf+1)/(master_out+1)-1 #plt.scatter(velocities,residual) residuals.append(residual) residual_errors.append(error) ''' plt.figure() plt.plot(ccf) plt.plot(master_out) #plt.plot(residual) plt.show() ''' #plt.show() return residuals, residual_errors #################################################################################################################################################################### ##path = '/Users/lucydolan/Documents/CCF_method/HD189733_HARPS_CCFS/' path = '/home/lsd/Documents/Starbase/novaprime/Documents/LSD_Figures/' #path = '/Users/lucydolan/Starbase/LSD_Figures/' month = 'August2007' #August, July, Sep #path = '%s%s_master_out_LSD_profile.fits'%(save_path, month) months = [#'August2007', 'July2007'#, #'July2006', #'Sep2006' ] all_resi=[] all_phase=[] all_prof=[] results_all = [] masters = [] for month in months: directory = '%s'%(path) #file ='%s%s_master_out.fits'%(directory, month) file ='%s%s_master_out_LSD_profile.fits'%(directory, month) #ccf_file='%s%s_master_out_ccfs.fits'%(directory, month) #file ='%s%s_master_out_LSD_v3.fits'%(directory, month) #file ='%s%s_master_out_cegla.fits'%(directory, month) # all_ccfs = fits.open(ccf_file) all_profiles = fits.open(file) profile_spec = all_profiles[0].data[0] velocities = np.linspace(-10,10,len(profile_spec)) count = 0 rv_phases = [] rv_results = [] ccf_rv_results = [] rvs = [] fwhm = [] plt.figure() st = 15 end = -15 st = 0 end = len(velocities) # cmap = plt.colormaps('Blues')' # colour = cm.Blues(np.linspace(0, 1, len(all_profiles))) # plt.figure() # for i in range(len(all_profiles)-1): # y = all_profiles[i].data[0] # popt, pcov = curve_fit(gauss, velocities[st:end], y[st:end]) # perr= np.sqrt(np.diag(pcov)) # plt.plot(velocities[st:end], y[st:end], 'k') # plt.plot(velocities[st:end], gauss(velocities[st:end], popt[0], popt[1], popt[2], popt[3]), 'r') # rvs.append(popt[0]) # fwhm.append(2.355*popt[1]) # rv_phases.append(all_profiles[count].header['PHASE']) # rv_results.append(all_profiles[count].header['RESULT']) # count += 1 # #plt.legend() # plt.figure('ACID and CCF RV (-median)', figsize = [9, 7]) # plt.ylabel('RV - median(RV)') # plt.xlabel('Phase') # plt.scatter(rv_phases, rvs-np.median(rvs), label = 'ACID NEW', color = 'm') # # plt.scatter(rv_phases, rvs2-np.median(rvs2), label = 'ACID NEW_moremask', color = 'k') # plt.legend() # plt.show() # ccf_spec = all_ccfs[0].data[0] # ccf_velocities=all_ccfs[0].header['CRVAL1']+(np.arange(ccf_spec.shape[0]))*all_ccfs[0].header['CDELT1'] # ccf_velocities = np.linspace(-19,19,len(ccf_spec)) # master_position_ccf = len(all_ccfs)-1 # master_out_ccf, master_out_errors_ccf= all_ccfs[master_position_ccf].data master_position = len(all_profiles)-1 master_out, master_out_errors= all_profiles[master_position].data masters.append(master_out) plt.figure('master out') plt.plot(velocities, master_out, label = 'LSD') # plt.plot(ccf_velocities, master_out_ccf/master_out_ccf[0]-1, label = 'ccf') plt.legend() plt.show() # master_out_ccf = master_out_ccf/master_out_ccf[0]-1 in_profiles = [] in_profiles_errors = [] phases = [] results = [] in_ccfs = [] in_ccfs_errors = [] phases_ccfs = [] ccf_results = [] out_profiles = [] out_profile_error = [] plt.figure('all_ccfs') # for line in range(0,master_position_ccf): # ccf = all_ccfs[line].data[0] # ccf_errors = all_ccfs[line].data[1] # ccf_phase = all_ccfs[line].header['PHASE'] # in_ccfs.append(ccf/ccf[0]-1) # in_ccfs_errors.append(ccf_errors/ccf[0]) # #plt.plot(ccf, label = '%s_%s'%(result, line)) # phases_ccfs.append(ccf_phase) # #all_phase.append(phase) # #ccf_results.append(ccf_result) for line in range(0, master_position): profile = all_profiles[line].data[0] profile_errors = all_profiles[line].data[1] phase = all_profiles[line].header['PHASE'] result = all_profiles[line].header['RESULT'] ##adding in M and A curve P=2.21857567 #Cegla et al, 2016 - days T=2454279.436714 #cegla et al,2016 a_Rs = 8.786 #Cristo et al - 8.786 b=0.687 #Cristo et al, 2022 RpRs = 0.15667 u1=0.816 u2=0 #Sing et al, 2011 i = 85.5*np.pi/180 #Cristo et al, 2022 z = ma.MandelandAgol(phase, a_Rs, i) transit_curve = ma.occultquad(z, RpRs, [u1, u2]) print(line) print(phase) print(transit_curve) print(result) # profile = (profile[5:-5]+1)*transit_curve # profile_errors = profile_errors[5:-5]*transit_curve # if line ==0: # velocities = velocities[5:-5] # print(velocities.shape, profile.shape) profile = (profile+1)*transit_curve profile_errors = profile_errors*transit_curve in_profiles.append(profile) in_profiles_errors.append(profile_errors) plt.plot(velocities, profile, label = '%s_%s'%(result, line)) phases.append(phase) all_phase.append(phase) if result == 'out': out_profiles.append(profile) out_profile_error.append(profile) results.append(result) results_all.append(result) plt.legend() plt.show() # plt.figure('ccfs - LSDs') # f2 = interp1d(ccf_velocities, in_ccfs, kind='linear', bounds_error=False, fill_value=np.nan) # plt.imshow(f2(velocities)-in_profiles) # plt.colorbar() # plt.show() #print(phases) # profile_spec = all_profiles[0].data[0] # #velocities=all_profiles[0].header['CRVAL1']+(np.arange(profile_spec.shape[0]))*all_profiles[0].header['CDELT1'] # velocities = np.linspace(-15,15,len(profile_spec)) # ccf_spec = all_ccfs[0].data[0] # ccf_velocities=all_ccfs[0].header['CRVAL1']+(np.arange(ccf_spec.shape[0]))*all_ccfs[0].header['CDELT1'] # K = -2.277 #km/s - Boisse et al, 2009 #velocities = velocities - K ### Adjusting doppler reflex ### residual_profiles, residual_profile_errors = residualccfs(in_profiles, in_profiles_errors, master_out, master_out_errors, velocities) # plt.figure() # for out_prof in out_profiles: # residual_profiles, residual_profile_errors = residualccfs(out_profiles, out_profile_error, out_prof, master_out_errors, velocities) # # for resi_prof in residual_profiles: # plt.plot(np.mean(residual_profiles, axis = 1)) # plt.show() # residual_ccfs, residual_errors = residualccfs(in_ccfs, in_ccfs_errors, master_out_ccf, master_out_errors_ccf, ccf_velocities) ''' plt.figure(month) outs=[] ins = [] for ccf in residual_ccfs: if max(ccf)<0.4: plt.plot(ccf) ins.append(ccf) else:outs.append(ccf) print(len(outs)) print(len(ins)) ''' # phases = np.array(phases) # results = np.array(results) # print(month) # plt.figure() # i=0 # for ccf1 in residual_ccfs: # for phase in phases: # if phases_ccfs[i] == phase: # print(results[tuple([phases==phase])]) # if results[tuple([phases==phase])]=='out':colour = '--' # else:colour = '-' # plt.plot(ccf_velocities, ccf1, label = '%s'%(i), linestyle = colour) # # #plt.fill_between(ccf_velocities, ccf1-residual_errors[i], ccf1+residual_errors[i], alpha = 0.3) # #all_resi.append(ccf1) # i+=1 # #plt.legend() # plt.show() print(month) plt.figure(month) i=0 for ccf1 in residual_profiles: if results[i]=='out':colour = '--' else:colour = '-' plt.plot(velocities, ccf1, label = '%s_%s'%(results[i], i), linestyle = colour) plt.fill_between(velocities, ccf1-residual_profile_errors[i], ccf1+residual_profile_errors[i], alpha = 0.3) all_resi.append(ccf1+1) all_prof.append(in_profiles[i]) i+=1 plt.legend() plt.show() #write in data hdu=fits.HDUList() for data in residual_profiles: hdu.append(fits.PrimaryHDU(data=data)) #hdu.append(fits.PrimaryHDU(data=master_out)) plt.figure() #write in header for p in range(len(phases)): phase = phases[p] hdr=fits.Header() hdr['CRVAL1']=all_profiles[0].header['CRVAL1'] hdr['CDELT1']=all_profiles[0].header['CDELT1'] hdr['OBJECT']='HD189733b' hdr['NIGHT']='%s'%month hdr['K']=-2.277 hdr['PHASE']=phase # hdu[p].header=hdr print(phase) print(results[p]) if results[p] == 'out': plt.plot(residual_profiles[p], label = '%s, %s'%(phases[p], max(residual_profiles[p])-min(residual_profiles[p]))) plt.legend() plt.show() #hdu.writeto('%s%s_residual_ccfs.fits'%(directory, month), output_verify='fix', overwrite = 'True') #hdu.writeto('%s%s_residual_ccfs_LSD_v3.fits'%(directory, month), output_verify='fix', overwrite = 'True') n1 = len(all_resi) col0=((np.round(np.linspace(0,170,num=n1))).astype(int)) #col1=((np.round(np.linspace(0,170,num=n2))).astype(int)) #col2=((np.round(np.linspace(50,220,num=n3))).astype(int)) #plt.cm.Reds(col1[i-n1]) #plt.cm.Greens(col2[i]) #plt.cm.Reds(col1[i]) #plt.cm.Blues(col0[i]) ''' fig, ax1 = plt.subplots(1,1) for i in range(len(all_resi)): ax1.plot(velocities, all_resi[i],color=plt.cm.gist_rainbow(col0[i]),linewidth=0.7) plt.show() ''' fig, ax = plt.subplots(2) #ax[0], ax[1] = fig.add_subplot() ax[0].set_title('Residual LSD Profiles') for ccf in all_resi: ax[0].plot(velocities, ccf) ax[0].set_ylabel('Residual Flux') #plt.savefig('/Users/lucydolan/Documents/CCF_method/Figures/residual_ccfs_mine') cmap = plt.get_cmap('jet') divider = make_axes_locatable(ax[1]) cax = divider.append_axes('right', size="7%", pad=0.2,) im = ax[1].pcolormesh(velocities, all_phase, all_resi, cmap = cmap) ax[1].set_ylim(-0.02, 0.02) fig.colorbar(im,label='Residual Flux', cax = cax) ax[1].set_xlabel('Velocity (km/s)') ax[1].set_ylabel('Phase') plt.show() ## Cegla style fitting of rvs x = velocities#[1:] all_resi = np.array(all_resi) # all_resi = all_resi[:, 1:] rvs = [] count = 0 P=2.21857567 #Cegla et al, 2006 - days t=0.076125 #Torres et al, 2008 - days rv_phases = [] for y in all_prof: #if (-t/(2*P)+0.001)<all_phase[count]<0.0155: popt, pcov = curve_fit(gauss, x, y) perr= np.sqrt(np.diag(pcov)) rvs.append([popt[0], perr[0]]) rv_phases.append(all_phase[count]) count += 1 rvs = np.array(rvs) plt.figure('RV measured from full profile') plt.xlabel('Phase') plt.ylabel('Local RV (km/s)') plt.errorbar(rv_phases, rvs[:,0], yerr = rvs[:,1], fmt='o', label = 'LSD') x = velocities#[1:] all_resi = np.array(all_resi) #all_resi = all_resi[:, 1:] rvs = [] count = 0 P=2.21857567 #Cegla et al, 2006 - days t=0.076125 #Torres et al, 2008 - days rv_phases = [] plt.figure() for y in all_resi: #if (-t/(2*P)+0.001)<all_phase[count]<0.0155: if np.max(y) - np.min(y)>0.006: # plt.figure() # plt.plot(x, y) # plt.show() try: popt, pcov = curve_fit(gauss, x, y) perr= np.sqrt(np.diag(pcov)) rvs.append([popt[0], perr[0]]) rv_phases.append(all_phase[count]) except: print('could not fit phase: %s'%all_phase[count]) else: plt.plot(x, y) print(results_all[count]) count += 1 rvs = np.array(rvs) # plt.figure('RV measured from residual profile') # plt.xlabel('Phase') # plt.ylabel('Local RV (km/s)') # plt.errorbar(rv_phases, rvs[:,0], yerr = rvs[:,1], fmt='o', label = 'LSD') # plt.show() plt.figure('master profiles') for i in range(len(months)): plt.plot(velocities, masters[i], label = '%s'%months[i]) plt.legend() plt.show()
ldolan05REPO_NAMEACIDPATH_START.@ACID_extracted@ACID-main@.other_scripts@5_residual_profiles.py@.PATH_END.py
{ "filename": "_contours.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/graph_objs/contour/_contours.py", "type": "Python" }
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Contours(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "contour" _path_str = "contour.contours" _valid_props = { "coloring", "end", "labelfont", "labelformat", "operation", "showlabels", "showlines", "size", "start", "type", "value", } # coloring # -------- @property def coloring(self): """ Determines the coloring method showing the contour values. If "fill", coloring is done evenly between each contour level If "heatmap", a heatmap gradient coloring is applied between each contour level. If "lines", coloring is done on the contour lines. If "none", no coloring is applied on this trace. The 'coloring' property is an enumeration that may be specified as: - One of the following enumeration values: ['fill', 'heatmap', 'lines', 'none'] Returns ------- Any """ return self["coloring"] @coloring.setter def coloring(self, val): self["coloring"] = val # end # --- @property def end(self): """ Sets the end contour level value. Must be more than `contours.start` The 'end' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["end"] @end.setter def end(self, val): self["end"] = val # labelfont # --------- @property def labelfont(self): """ Sets the font used for labeling the contour levels. The default color comes from the lines, if shown. The default family and size come from `layout.font`. The 'labelfont' property is an instance of Labelfont that may be specified as: - An instance of :class:`plotly.graph_objs.contour.contours.Labelfont` - A dict of string/value properties that will be passed to the Labelfont constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans", "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all- lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- plotly.graph_objs.contour.contours.Labelfont """ return self["labelfont"] @labelfont.setter def labelfont(self, val): self["labelfont"] = val # labelformat # ----------- @property def labelformat(self): """ Sets the contour label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. The 'labelformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["labelformat"] @labelformat.setter def labelformat(self, val): self["labelformat"] = val # operation # --------- @property def operation(self): """ Sets the constraint operation. "=" keeps regions equal to `value` "<" and "<=" keep regions less than `value` ">" and ">=" keep regions greater than `value` "[]", "()", "[)", and "(]" keep regions inside `value[0]` to `value[1]` "][", ")(", "](", ")[" keep regions outside `value[0]` to value[1]` Open vs. closed intervals make no difference to constraint display, but all versions are allowed for consistency with filter transforms. The 'operation' property is an enumeration that may be specified as: - One of the following enumeration values: ['=', '<', '>=', '>', '<=', '[]', '()', '[)', '(]', '][', ')(', '](', ')['] Returns ------- Any """ return self["operation"] @operation.setter def operation(self, val): self["operation"] = val # showlabels # ---------- @property def showlabels(self): """ Determines whether to label the contour lines with their values. The 'showlabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlabels"] @showlabels.setter def showlabels(self, val): self["showlabels"] = val # showlines # --------- @property def showlines(self): """ Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to "fill". The 'showlines' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlines"] @showlines.setter def showlines(self, val): self["showlines"] = val # size # ---- @property def size(self): """ Sets the step between each contour level. Must be positive. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val # start # ----- @property def start(self): """ Sets the starting contour level value. Must be less than `contours.end` The 'start' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["start"] @start.setter def start(self, val): self["start"] = val # type # ---- @property def type(self): """ If `levels`, the data is represented as a contour plot with multiple levels displayed. If `constraint`, the data is represented as constraints with the invalid region shaded as specified by the `operation` and `value` parameters. The 'type' property is an enumeration that may be specified as: - One of the following enumeration values: ['levels', 'constraint'] Returns ------- Any """ return self["type"] @type.setter def type(self, val): self["type"] = val # value # ----- @property def value(self): """ Sets the value or values of the constraint boundary. When `operation` is set to one of the comparison values (=,<,>=,>,<=) "value" is expected to be a number. When `operation` is set to one of the interval values ([],(),[),(],][,)(,](,)[) "value" is expected to be an array of two numbers where the first is the lower bound and the second is the upper bound. The 'value' property accepts values of any type Returns ------- Any """ return self["value"] @value.setter def value(self, val): self["value"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ coloring Determines the coloring method showing the contour values. If "fill", coloring is done evenly between each contour level If "heatmap", a heatmap gradient coloring is applied between each contour level. If "lines", coloring is done on the contour lines. If "none", no coloring is applied on this trace. end Sets the end contour level value. Must be more than `contours.start` labelfont Sets the font used for labeling the contour levels. The default color comes from the lines, if shown. The default family and size come from `layout.font`. labelformat Sets the contour label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. operation Sets the constraint operation. "=" keeps regions equal to `value` "<" and "<=" keep regions less than `value` ">" and ">=" keep regions greater than `value` "[]", "()", "[)", and "(]" keep regions inside `value[0]` to `value[1]` "][", ")(", "](", ")[" keep regions outside `value[0]` to value[1]` Open vs. closed intervals make no difference to constraint display, but all versions are allowed for consistency with filter transforms. showlabels Determines whether to label the contour lines with their values. showlines Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to "fill". size Sets the step between each contour level. Must be positive. start Sets the starting contour level value. Must be less than `contours.end` type If `levels`, the data is represented as a contour plot with multiple levels displayed. If `constraint`, the data is represented as constraints with the invalid region shaded as specified by the `operation` and `value` parameters. value Sets the value or values of the constraint boundary. When `operation` is set to one of the comparison values (=,<,>=,>,<=) "value" is expected to be a number. When `operation` is set to one of the interval values ([],(),[),(],][,)(,](,)[) "value" is expected to be an array of two numbers where the first is the lower bound and the second is the upper bound. """ def __init__( self, arg=None, coloring=None, end=None, labelfont=None, labelformat=None, operation=None, showlabels=None, showlines=None, size=None, start=None, type=None, value=None, **kwargs, ): """ Construct a new Contours object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.contour.Contours` coloring Determines the coloring method showing the contour values. If "fill", coloring is done evenly between each contour level If "heatmap", a heatmap gradient coloring is applied between each contour level. If "lines", coloring is done on the contour lines. If "none", no coloring is applied on this trace. end Sets the end contour level value. Must be more than `contours.start` labelfont Sets the font used for labeling the contour levels. The default color comes from the lines, if shown. The default family and size come from `layout.font`. labelformat Sets the contour label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. operation Sets the constraint operation. "=" keeps regions equal to `value` "<" and "<=" keep regions less than `value` ">" and ">=" keep regions greater than `value` "[]", "()", "[)", and "(]" keep regions inside `value[0]` to `value[1]` "][", ")(", "](", ")[" keep regions outside `value[0]` to value[1]` Open vs. closed intervals make no difference to constraint display, but all versions are allowed for consistency with filter transforms. showlabels Determines whether to label the contour lines with their values. showlines Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to "fill". size Sets the step between each contour level. Must be positive. start Sets the starting contour level value. Must be less than `contours.end` type If `levels`, the data is represented as a contour plot with multiple levels displayed. If `constraint`, the data is represented as constraints with the invalid region shaded as specified by the `operation` and `value` parameters. value Sets the value or values of the constraint boundary. When `operation` is set to one of the comparison values (=,<,>=,>,<=) "value" is expected to be a number. When `operation` is set to one of the interval values ([],(),[),(],][,)(,](,)[) "value" is expected to be an array of two numbers where the first is the lower bound and the second is the upper bound. Returns ------- Contours """ super(Contours, self).__init__("contours") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.contour.Contours constructor must be a dict or an instance of :class:`plotly.graph_objs.contour.Contours`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("coloring", None) _v = coloring if coloring is not None else _v if _v is not None: self["coloring"] = _v _v = arg.pop("end", None) _v = end if end is not None else _v if _v is not None: self["end"] = _v _v = arg.pop("labelfont", None) _v = labelfont if labelfont is not None else _v if _v is not None: self["labelfont"] = _v _v = arg.pop("labelformat", None) _v = labelformat if labelformat is not None else _v if _v is not None: self["labelformat"] = _v _v = arg.pop("operation", None) _v = operation if operation is not None else _v if _v is not None: self["operation"] = _v _v = arg.pop("showlabels", None) _v = showlabels if showlabels is not None else _v if _v is not None: self["showlabels"] = _v _v = arg.pop("showlines", None) _v = showlines if showlines is not None else _v if _v is not None: self["showlines"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v _v = arg.pop("start", None) _v = start if start is not None else _v if _v is not None: self["start"] = _v _v = arg.pop("type", None) _v = type if type is not None else _v if _v is not None: self["type"] = _v _v = arg.pop("value", None) _v = value if value is not None else _v if _v is not None: self["value"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@graph_objs@contour@_contours.py@.PATH_END.py
{ "filename": "_stream.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scatter/_stream.py", "type": "Python" }
import _plotly_utils.basevalidators class StreamValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="stream", parent_name="scatter", **kwargs): super(StreamValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Stream"), data_docs=kwargs.pop( "data_docs", """ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart- studio.plotly.com/settings for more details. """, ), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scatter@_stream.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/graph_objs/histogram2d/legendgrouptitle/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._font import Font else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import(__name__, [], ["._font.Font"])
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@graph_objs@histogram2d@legendgrouptitle@__init__.py@.PATH_END.py
{ "filename": "_enabled.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattermap/marker/colorbar/tickformatstop/_enabled.py", "type": "Python" }
import _plotly_utils.basevalidators class EnabledValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__( self, plotly_name="enabled", parent_name="scattermap.marker.colorbar.tickformatstop", **kwargs, ): super(EnabledValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattermap@marker@colorbar@tickformatstop@_enabled.py@.PATH_END.py
{ "filename": "_family.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/choroplethmap/hoverlabel/font/_family.py", "type": "Python" }
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", parent_name="choroplethmap.hoverlabel.font", **kwargs, ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), no_blank=kwargs.pop("no_blank", True), strict=kwargs.pop("strict", True), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@choroplethmap@hoverlabel@font@_family.py@.PATH_END.py
{ "filename": "psd_math.py", "repo_name": "hpc4cmb/toast", "repo_path": "toast_extracted/toast-main/src/toast/fod/psd_math.py", "type": "Python" }
# Copyright (c) 2015-2020 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. import numpy as np from scipy.signal import fftconvolve from ..mpi import MPI from ..timing import function_timer from .._libtoast import fod_autosums, fod_crosssums from ..tod import flagged_running_average def highpass_flagged_signal(sig, good, naverage): """Highpass-filter the signal to remove sub harmonic modes. Args: sig (array): The signal. good (array): Sample flags (zero == *BAD*) naverage (int): The number of samples to average. Returns: (array): The processed array. """ # First fit and remove a linear trend. Loss of power from this # filter is assumed negligible in the frequency bins of interest ngood = np.sum(good) if ngood == 0: raise RuntimeError("No valid samples") templates = np.vstack([np.ones(ngood), np.arange(good.size)[good]]) invcov = np.dot(templates, templates.T) cov = np.linalg.inv(invcov) proj = np.dot(templates, sig[good]) coeff = np.dot(cov, proj) sig[good] -= coeff[0] + coeff[1] * templates[1] # Then prewhiten the data. This filter will be corrected in the # PSD estimates. trend = flagged_running_average(sig, good == 0, naverage) sig[good] -= trend[good] return sig @function_timer def autocov_psd( times, signal, flags, lagmax, stationary_period, fsample, comm=None, return_cov=False, ): """Compute the sample autocovariance. Compute the sample autocovariance function and Fourier transform it for a power spectral density. The resulting power spectral densities are distributed across the communicator as tuples of (start_time, stop_time, bin_frequency, bin_value) Args: times (float): Signal time stamps. signal (float): Regularly sampled signal vector. flags (float): Signal quality flags. lagmax (int): Largest sample separation to evaluate. stationary_period (float): Length of a stationary interval in units of the times vector. fsample (float): The sampling frequency in Hz comm (MPI.Comm): The MPI communicator or None. return_cov (bool): Return also the covariance function Returns: (list): List of local tuples of (start_time, stop_time, bin_frequency, bin_value) """ return crosscov_psd( times, signal, None, flags, lagmax, stationary_period, fsample, comm, return_cov ) @function_timer def crosscov_psd( times, signal1, signal2, flags, lagmax, stationary_period, fsample, comm=None, return_cov=False, ): """Compute the sample (cross)covariance. Compute the sample (cross)covariance function and Fourier transform it for a power spectral density. The resulting power spectral densities are distributed across the communicator as tuples of (start_time, stop_time, bin_frequency, bin_value) Args: times (float): Signal time stamps. signal1 (float): Regularly sampled signal vector. signal2 (float): Regularly sampled signal vector or None. flags (float): Signal quality flags. lagmax (int): Largest sample separation to evaluate. stationary_period (float): Length of a stationary interval in units of the times vector. fsample (float): The sampling frequency in Hz comm (MPI.Comm): The MPI communicator or None. return_cov (bool): Return also the covariance function Returns: (list): List of local tuples of (start_time, stop_time, bin_frequency, bin_value) """ rank = 0 ntask = 1 time_start = times[0] time_stop = times[-1] if comm is not None: rank = comm.rank ntask = comm.size time_start = comm.bcast(times[0], root=0) time_stop = comm.bcast(times[-1], root=ntask - 1) # We apply a prewhitening filter to the signal. To accommodate the # quality flags, the filter is a moving average that only accounts # for the unflagged samples naverage = lagmax nreal = np.int64(np.ceil((time_stop - time_start) / stationary_period)) # Communicate lagmax samples from the beginning of the array # backwards in the MPI communicator nsamp = signal1.size if lagmax > nsamp: raise RuntimeError( "crosscov_psd: Communicating TOD beyond nearest neighbors is not " "implemented. Reduce lagmax or the size of the MPI communicator." ) if rank != ntask - 1: nextend = lagmax else: nextend = 0 extended_signal1 = np.zeros(nsamp + nextend, dtype=np.float64) if signal2 is not None: extended_signal2 = np.zeros(nsamp + nextend, dtype=np.float64) extended_flags = np.zeros(nsamp + nextend, dtype=bool) extended_times = np.zeros(nsamp + nextend, dtype=times.dtype) extended_signal1[:nsamp] = signal1 if signal2 is not None: extended_signal2[:nsamp] = signal2 extended_flags[:nsamp] = flags extended_times[:nsamp] = times if comm is not None: for evenodd in range(2): if rank % 2 == evenodd % 2: # Send if rank == 0: continue comm.send(signal1[:lagmax], dest=rank - 1, tag=0) if signal2 is not None: comm.send(signal1[:lagmax], dest=rank - 1, tag=3) comm.send(flags[:lagmax], dest=rank - 1, tag=1) comm.send(times[:lagmax], dest=rank - 1, tag=2) else: # Receive if rank == ntask - 1: continue extended_signal1[-lagmax:] = comm.recv(source=rank + 1, tag=0) if signal2 is not None: extended_signal1[-lagmax:] = comm.recv(source=rank + 1, tag=3) extended_flags[-lagmax:] = comm.recv(source=rank + 1, tag=1) extended_times[-lagmax:] = comm.recv(source=rank + 1, tag=2) realization = ((extended_times - time_start) / stationary_period).astype(np.int64) # Set flagged elements to zero extended_signal1[extended_flags != 0] = 0 if signal2 is not None: extended_signal2[extended_flags != 0] = 0 covs = {} for ireal in range(realization[0], realization[-1] + 1): # Evaluate the covariance realflg = realization == ireal good = extended_flags[realflg] == 0 ngood = np.sum(good) if ngood == 0: continue sig1 = extended_signal1[realflg].copy() sig1 = highpass_flagged_signal(sig1, good, naverage) # High pass filter does not work at the ends ind = slice(naverage // 2, -naverage // 2) cov_hits = np.zeros(lagmax, dtype=np.int64) cov = np.zeros(lagmax, dtype=np.float64) if signal2 is None: fod_autosums(sig1[ind], good[ind].astype(np.uint8), lagmax, cov, cov_hits) else: sig2 = extended_signal2[realflg].copy() sig2 = highpass_flagged_signal(sig2, good, lagmax) fod_crosssums( sig1[ind], sig2[ind], good[ind].astype(np.uint8), lagmax, cov, cov_hits ) covs[ireal] = (cov_hits, cov) # Collect the estimated covariance functions my_covs = {} nreal_task = np.int64(np.ceil(nreal / ntask)) if comm is None: for ireal in range(nreal): if ireal in covs: cov_hits, cov = covs[ireal] else: cov_hits = np.zeros(lagmax, dtype=np.int64) cov = np.zeros(lagmax, dtype=np.float64) my_covs[ireal] = (cov_hits, cov) else: for ireal in range(nreal): owner = ireal // nreal_task if ireal in covs: cov_hits, cov = covs[ireal] else: cov_hits = np.zeros(lagmax, dtype=np.int64) cov = np.zeros(lagmax, dtype=np.float64) cov_hits_total = np.zeros(lagmax, dtype=np.int64) cov_total = np.zeros(lagmax, dtype=np.float64) comm.Reduce(cov_hits, cov_hits_total, op=MPI.SUM, root=owner) comm.Reduce(cov, cov_total, op=MPI.SUM, root=owner) if rank == owner: my_covs[ireal] = (cov_hits_total, cov_total) # Now process the ones this task owns my_psds = [] my_cov = [] for ireal in my_covs.keys(): cov_hits, cov = my_covs[ireal] good = cov_hits != 0 cov[good] /= cov_hits[good] # Interpolate any empty bins if not np.all(good) and np.any(good): bad = cov_hits == 0 # The last bins should be left empty i = cov.size - 1 while cov_hits[i] == 0: cov[i] = 0 bad[i] = False i -= 1 nbad = np.sum(bad) if nbad > 0: good = np.logical_not(bad) lag = np.arange(lagmax) cov[bad] = np.interp(lag[bad], lag[good], cov[good]) # Fourier transform for the PSD. We symmetrize the sample # autocovariance so that the FFT is real-valued. Notice that # we are not forcing the PSD to be positive: each bin is a # noisy estimate of the true PSD. cov = np.hstack([cov, cov[:0:-1]]) # w = np.roll(hamming(cov.size), -lagmax) # cov *= w psd = np.fft.rfft(cov).real psdfreq = np.fft.rfftfreq(len(cov), d=1 / fsample) # Post process the PSD estimate: # 1) Deconvolve the prewhitening (highpass) filter arg = 2 * np.pi * np.abs(psdfreq) * naverage / fsample tf = np.ones(lagmax) ind = arg != 0 tf[ind] -= np.sin(arg[ind]) / arg[ind] psd[ind] /= tf[ind] ** 2 # 2) Apply the Hann window to reduce unnecessary noise psd = np.convolve(psd, [0.25, 0.5, 0.25], mode="same") # Transfrom the corrected PSD back to get an unbiased # covariance function smooth_cov = np.fft.irfft(psd) my_cov.append((cov_hits, smooth_cov[:lagmax])) # Set the white noise PSD normalization to sigma**2 / fsample psd /= fsample tstart = time_start + ireal * stationary_period tstop = min(tstart + stationary_period, time_stop) my_psds.append((tstart, tstop, psdfreq, psd)) if return_cov: return my_psds, my_cov else: return my_psds def smooth_with_hits(hits, cov, wbin): """Smooth the covariance function. Smooth the covariance function, taking into account the number of hits in each bin. Args: hits (array_like): The number of hits for each sample lag. cov (array_like): The time domain covariance. wbin (int): The number of samples per smoothing bin. Returns: (tuple): The (smoothed hits, smoothed covariance). """ kernel = np.ones(wbin) smooth_hits = fftconvolve(hits, kernel, mode="same") smooth_cov = fftconvolve(cov * hits, kernel, mode="same") good = smooth_hits > 0 smooth_cov[good] /= smooth_hits[good] return smooth_hits, smooth_cov
hpc4cmbREPO_NAMEtoastPATH_START.@toast_extracted@toast-main@src@toast@fod@psd_math.py@.PATH_END.py
{ "filename": "XID+_example_pyvo_prior.ipynb", "repo_name": "H-E-L-P/XID_plus", "repo_path": "XID_plus_extracted/XID_plus-master/docs/notebooks/examples/XID+_example_pyvo_prior.ipynb", "type": "Jupyter Notebook" }
```python from astropy.io import ascii, fits import astropy import pylab as plt %matplotlib inline from astropy import wcs from astropy.table import Table,Column,join,hstack from astropy.coordinates import SkyCoord from astropy import units as u import pymoc import glob from time import sleep import os import numpy as np import xidplus from xidplus import moc_routines import pickle import xidplus.catalogue as cat import sys from herschelhelp_internal.utils import inMoc,flux_to_mag from xidplus.stan_fit import SPIRE import aplpy import seaborn as sns #sns.set(color_codes=True) import pandas as pd #sns.set_style("white") import xidplus.posterior_maps as postmaps import pyvo as vo ``` WARNING: AstropyDeprecationWarning: block_reduce was moved to the astropy.nddata.blocks module. Please update your import statement. [astropy.nddata.utils] First we select the field that the sources we are considering are in. If the sources span multiple fields that each field will need to be run individually as the FIR maps from seperate fields cannot be easily combined. ```python fields = ['AKARI-NEP', 'AKARI-SEP', 'Bootes', 'CDFS-SWIRE', 'COSMOS', 'EGS', 'ELAIS-N1', 'ELAIS-N2', 'ELAIS-S1', 'GAMA-09', 'GAMA-12', 'GAMA-15', 'HDF-N', 'Herschel-Stripe-82', 'Lockman-SWIRE', 'NGP', 'SA13', 'SGP', 'SPIRE-NEP', 'SSDF', 'XMM-13hr', 'XMM-LSS', 'xFLS'] field_use = fields[6] print(field_use) ``` ELAIS-N1 Here you provide the coordinate of the objects you are planning to run XID+ on and their ID's if any If no ids are provided then they will be numbered 1-N) ```python ras = [242,243]#enter your ra here as a list of numpy array decs = [55,55] #enter your dec here as a list or numpy array object_coords = SkyCoord(ra=ras*u.degree,dec=decs*u.degree) ids = [] #add your ids here as a list or numpy array if len(ids)==0: ids = np.arange(0,len(ras),1) ``` Run the pyvo query to create a table of all help sources within the desired radius of your objects ```python #setup a connection to the HELP VO server at Sussex search_radius = 60/3600 #distance away from object that the VO query will look for galaxies in degrees #for SPIRE AND PACS we recommend 60" and for MIPS we reccomend 30" service = vo.dal.TAPService("https://herschel-vos.phys.sussex.ac.uk/__system__/tap/run/tap") for n,coords in enumerate(object_coords): ra = coords.ra dec = coords.dec query_spire_pacs = """ SELECT ra, dec, help_id, flag_optnir_det, f_mips_24 FROM herschelhelp.main WHERE ( herschelhelp.main.field = '{}' AND herschelhelp.main.falg_optnir_det>=5 AND herschelhelp.main.f_mips_24>20 ) AND WHERE CONTAINS(POINT('ICRS',ra, dec), CIRCLE('ICRS',{},{},{}))=1 """.format(field_use,ra,dec,search_radius) query_mips = """ SELECT ra, dec, help_id, flag_optnir_det, f_irac_i1, f_irac_i2, f_irac_i3, f_irac_i4 FROM herschelhelp.main WHERE ( herschelhelp.main.field = '{}' AND herschelhelp.main.falg_optnir_det>=5 AND ) AND WHERE CONTAINS(POINT('ICRS',ra, dec), CIRCLE('ICRS',{},{},{}))=1 """.format(field_use,ra,dec,search_radius) try: job = service.submit_job(query) job.run() while job.phase == "EXECUTING": print("Job running") sleep(5) print('Job finsihed') if n==0: prior_help = job.fetch_result().to_table() print('table created with {} rows'.format(len(table))) else: result = job.fetch_result().to_table() prior_help = astropy.table.vstack([result,table],join_type='outer') print('table editied, added {} rows'.format(len(result))) done_fields.append(field) except: print('VO call failed') job.delete() ``` Job running WARNING: UnknownElementWarning: None:7:166: UnknownElementWarning: Unknown element errorSummary [pyvo.utils.xml.elements] WARNING:astropy:UnknownElementWarning: None:7:166: UnknownElementWarning: Unknown element errorSummary WARNING: UnknownElementWarning: None:7:215: UnknownElementWarning: Unknown element message [pyvo.utils.xml.elements] WARNING:astropy:UnknownElementWarning: None:7:215: UnknownElementWarning: Unknown element message job finsihed VO call failed ```python print(len(prior_help)) prior_help[:5] ``` --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-18-ec3ae170ea85> in <module>() ----> 1 print(len(prior_cat)) 2 prior_cat[:5] NameError: name 'prior_cat' is not defined Run the below cell if you are running XID+ on SPIRE or PACS maps ```python cra = Column(ras,name='ra') cdec = Column(decs,name='dec') cids = Column(ids,name='help_id') cdet = Column(np.zeros(len(ras))-99,name='flag_optnir_det') cmips = Column(np.zeros(len(ras))*np.nan,name='f_mips_24') prior_new = Table() prior_new.add_columns([cra,cdec,cids,cdet,cmips]) prior_cat = vstack([prior_help,prior_new]) len(prior_cat) prior_cat[:5] ``` Run the below cells if you are running XID+ on MIPS maps ```python #provides limits on teh flat prior used in XID based on the galaxies IRAC fluxes MIPS_lower=np.full(len(prior_help),0.0) MIPS_upper=np.full(len(prior_help),1E5) for i in range(len(prior_cat)): if np.isnan(prior_cat['f_irac_i4'][i])==False: MIPS_lower[i]=prior_cat['f_irac_i4'][i]/500.0 MIPS_upper[i]=prior_cat['f_irac_i4'][i]*500.0 elif np.isnan(prior_cat['f_irac_i3'][i])==False: MIPS_lower[i]=prior_cat['f_irac_i3'][i]/500.0 MIPS_upper[i]=prior_cat['f_irac_i3'][i]*500.0 elif np.isnan(prior_cat['f_irac_i2'][i])==False: MIPS_lower[i]=prior_cat['f_irac_i2'][i]/500.0 MIPS_upper[i]=prior_cat['f_irac_i2'][i]*500.0 elif np.isnan(prior_cat['f_irac_i1'][i])==False: MIPS_lower[i]=prior_cat['f_irac_i1'][i]/500.0 MIPS_upper[i]=prior_cat['f_irac_i1'][i]*500.0 mips_lower_col = Column(MIPS_lower,name='MIPS_lower') mips_upper_col = Column(MIPS_upper,name='MIPS_upper') prior_help.add_columns([mips_lower_col,mips_upper_col]) ``` ```python #add your IRAC fluxes here, if your objects don't have IRAC fluxes then they will be set to nan i1_f = np.zeros(len(ras))*np.nan i2_f = np.zeros(len(ras))*np.nan i3_f = np.zeros(len(ras))*np.nan i4_f = np.zeros(len(ras))*np.nan cra = Column(ras,name='ra') cdec = Column(decs,name='dec') cids = Column(ids,name='help_id') cdet = Column(np.zeros(len(ras))-99,name='flag_optnir_det') ci1 = Column(i1_f,name='f_irac_i1') ci2 = Column(i2_f,name='f_irac_i2') ci3 = Column(i3_f,name='f_irac_i3') ci4 = Column(i4_f,name='f_irac_i4') MIPS_lower=np.full(len(lofar_prior),0.0) MIPS_upper=np.full(len(lofar_prior),1E5) for i in range(len(lofar_prior)): if np.isnan(lofar_prior['f_irac_i4'][i])==False: MIPS_lower[i]=lofar_prior['f_irac_i4'][i]/500.0 MIPS_upper[i]=lofar_prior['f_irac_i4'][i]*500.0 elif np.isnan(lofar_prior['f_irac_i3'][i])==False: MIPS_lower[i]=lofar_prior['f_irac_i3'][i]/500.0 MIPS_upper[i]=lofar_prior['f_irac_i3'][i]*500.0 elif np.isnan(lofar_prior['f_irac_i2'][i])==False: MIPS_lower[i]=lofar_prior['f_irac_i2'][i]/500.0 MIPS_upper[i]=lofar_prior['f_irac_i2'][i]*500.0 elif np.isnan(lofar_prior['f_irac_i1'][i])==False: MIPS_lower[i]=lofar_prior['f_irac_i1'][i]/500.0 MIPS_upper[i]=lofar_prior['f_irac_i1'][i]*500.0 mips_lower_col = Column(MIPS_lower,name='MIPS_lower') mips_upper_col = Column(MIPS_upper,name='MIPS_upper') prior_new = Table() prior_new.add_columns([cra,cdec,cids,cdet,ci1,ci2,ci3,ci4,mips_lower_col,mips_upper_col]) prior_cat = vstack([prior_help,prior_new]) len(prior_cat) ``` Now that we have created the prior we can run XID+ ## Load in the FIR maps here we load in the SPIRE maps but you can substitue this with PACS and MIPS yourself ```python #Read in the herschel images imfolder='../../../../../HELP/dmu_products/dmu19/dmu19_HELP-SPIRE-maps/data/' pswfits=imfolder+'ELAIS-N1_SPIRE250_v1.0.fits'#SPIRE 250 map pmwfits=imfolder+'ELAIS-N1_SPIRE350_v1.0.fits'#SPIRE 350 map plwfits=imfolder+'ELAIS-N1_SPIRE500_v1.0.fits'#SPIRE 500 map #-----250------------- hdulist = fits.open(pswfits) im250phdu=hdulist[0].header im250hdu=hdulist['image'].header im250=hdulist['image'].data*1.0E3 #convert to mJy nim250=hdulist['error'].data*1.0E3 #convert to mJy w_250 = wcs.WCS(hdulist['image'].header) pixsize250=3600.0*w_250.wcs.cd[1,1] #pixel size (in arcseconds) hdulist.close() #-----350------------- hdulist = fits.open(pmwfits) im350phdu=hdulist[0].header im350hdu=hdulist['image'].header im350=hdulist['image'].data*1.0E3 #convert to mJy nim350=hdulist['error'].data*1.0E3 #convert to mJy w_350 = wcs.WCS(hdulist['image'].header) pixsize350=3600.0*w_350.wcs.cd[1,1] #pixel size (in arcseconds) hdulist.close() #-----500------------- hdulist = fits.open(plwfits) im500phdu=hdulist[0].header im500hdu=hdulist['image'].header im500=hdulist['image'].data*1.0E3 #convert to mJy nim500=hdulist['error'].data*1.0E3 #convert to mJy w_500 = wcs.WCS(hdulist['image'].header) pixsize500=3600.0*w_500.wcs.cd[1,1] #pixel size (in arcseconds) hdulist.close() ``` Create a moc around each of your objects that will be used to cut doen the SPIRE image ```python moc=pymoc.util.catalog.catalog_to_moc(object_coords,search_radius,15) ``` finish initalising the prior ```python #---prior250-------- prior250=xidplus.prior(im250,nim250,im250phdu,im250hdu, moc=moc)#Initialise with map, uncertianty map, wcs info and primary header prior250.prior_cat(prior_cat['ra'],prior_cat['dec'],'prior_cat',ID=prior_cat['help_id'])#Set input catalogue prior250.prior_bkg(-5.0,5)#Set prior on background (assumes Gaussian pdf with mu and sigma) #---prior350-------- prior350=xidplus.prior(im350,nim350,im350phdu,im350hdu, moc=moc) prior350.prior_cat(prior_cat['ra'],prior_cat['dec'],'prior_cat',ID=prior_cat['help_id']) prior350.prior_bkg(-5.0,5) #---prior500-------- prior500=xidplus.prior(im500,nim500,im500phdu,im500hdu, moc=moc) prior500.prior_cat(prior_cat['ra'],prior_cat['dec'],'prior_cat',ID=prior_cat['help_id']) prior500.prior_bkg(-5.0,5) ``` ```python #pixsize array (size of pixels in arcseconds) pixsize=np.array([pixsize250,pixsize350,pixsize500]) #point response function for the three bands prfsize=np.array([18.15,25.15,36.3]) #use Gaussian2DKernel to create prf (requires stddev rather than fwhm hence pfwhm/2.355) from astropy.convolution import Gaussian2DKernel ##---------fit using Gaussian beam----------------------- prf250=Gaussian2DKernel(prfsize[0]/2.355,x_size=101,y_size=101) prf250.normalize(mode='peak') prf350=Gaussian2DKernel(prfsize[1]/2.355,x_size=101,y_size=101) prf350.normalize(mode='peak') prf500=Gaussian2DKernel(prfsize[2]/2.355,x_size=101,y_size=101) prf500.normalize(mode='peak') pind250=np.arange(0,101,1)*1.0/pixsize[0] #get 250 scale in terms of pixel scale of map pind350=np.arange(0,101,1)*1.0/pixsize[1] #get 350 scale in terms of pixel scale of map pind500=np.arange(0,101,1)*1.0/pixsize[2] #get 500 scale in terms of pixel scale of map prior250.set_prf(prf250.array,pind250,pind250)#requires PRF as 2d grid, and x and y bins for grid (in pixel scale) prior350.set_prf(prf350.array,pind350,pind350) prior500.set_prf(prf500.array,pind500,pind500) ``` ```python print('fitting '+ str(prior250.nsrc)+' sources \n') print('using ' + str(prior250.snpix)+', '+ str(prior350.snpix)+' and '+ str(prior500.snpix)+' pixels') ``` ```python prior250.get_pointing_matrix() prior350.get_pointing_matrix() prior500.get_pointing_matrix() ``` ```python prior250.upper_lim_map() prior350.upper_lim_map() prior500.upper_lim_map() ``` run XID+ and save the output ```python from xidplus.stan_fit import SPIRE fit=SPIRE.all_bands(prior250,prior350,prior500,iter=1000) ``` ```python posterior=xidplus.posterior_stan(fit,[prior250,prior350,prior500]) xidplus.save([prior250,prior350,prior500],posterior,'YOUR_FILE_NAME_HERE') ```
H-E-L-PREPO_NAMEXID_plusPATH_START.@XID_plus_extracted@XID_plus-master@docs@notebooks@examples@XID+_example_pyvo_prior.ipynb@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/graph_objs/streamtube/legendgrouptitle/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._font import Font else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import(__name__, [], ["._font.Font"])
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@graph_objs@streamtube@legendgrouptitle@__init__.py@.PATH_END.py
{ "filename": "_type.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/scattergeo/marker/gradient/_type.py", "type": "Python" }
import _plotly_utils.basevalidators class TypeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="type", parent_name="scattergeo.marker.gradient", **kwargs ): super(TypeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "style"), values=kwargs.pop("values", ["radial", "horizontal", "vertical", "none"]), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@scattergeo@marker@gradient@_type.py@.PATH_END.py
{ "filename": "_stats_py.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/scipy/py3/scipy/stats/_stats_py.py", "type": "Python" }
# Copyright 2002 Gary Strangman. All rights reserved # Copyright 2002-2016 The SciPy Developers # # The original code from Gary Strangman was heavily adapted for # use in SciPy by Travis Oliphant. The original code came with the # following disclaimer: # # This software is provided "as-is". There are no expressed or implied # warranties of any kind, including, but not limited to, the warranties # of merchantability and fitness for a given application. In no event # shall Gary Strangman be liable for any direct, indirect, incidental, # special, exemplary or consequential damages (including, but not limited # to, loss of use, data or profits, or business interruption) however # caused and on any theory of liability, whether in contract, strict # liability or tort (including negligence or otherwise) arising in any way # out of the use of this software, even if advised of the possibility of # such damage. """ A collection of basic statistical functions for Python. References ---------- .. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard Probability and Statistics Tables and Formulae. Chapman & Hall: New York. 2000. """ import warnings import math from math import gcd from collections import namedtuple import numpy as np from numpy import array, asarray, ma from numpy.lib import NumpyVersion from numpy.testing import suppress_warnings from scipy.spatial.distance import cdist from scipy.ndimage import _measurements from scipy._lib._util import (check_random_state, MapWrapper, _get_nan, rng_integers, _rename_parameter, _contains_nan) import scipy.special as special from scipy import linalg from . import distributions from . import _mstats_basic as mstats_basic from ._stats_mstats_common import (_find_repeats, linregress, theilslopes, siegelslopes) from ._stats import (_kendall_dis, _toint64, _weightedrankedtau, _local_correlations) from dataclasses import dataclass from ._hypotests import _all_partitions from ._stats_pythran import _compute_outer_prob_inside_method from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod, monte_carlo_test, permutation_test, bootstrap, _batch_generator) from ._axis_nan_policy import (_axis_nan_policy_factory, _broadcast_concatenate) from ._binomtest import _binary_search_for_binom_tst as _binary_search from scipy._lib._bunch import _make_tuple_bunch from scipy import stats from scipy.optimize import root_scalar # Functions/classes in other files should be added in `__init__.py`, not here __all__ = ['find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar', 'tmin', 'tmax', 'tstd', 'tsem', 'moment', 'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest', 'normaltest', 'jarque_bera', 'scoreatpercentile', 'percentileofscore', 'cumfreq', 'relfreq', 'obrientransform', 'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd', 'median_abs_deviation', 'sigmaclip', 'trimboth', 'trim1', 'trim_mean', 'f_oneway', 'pearsonr', 'fisher_exact', 'spearmanr', 'pointbiserialr', 'kendalltau', 'weightedtau', 'multiscale_graphcorr', 'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp', 'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel', 'kstest', 'ks_1samp', 'ks_2samp', 'chisquare', 'power_divergence', 'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare', 'rankdata', 'combine_pvalues', 'wasserstein_distance', 'energy_distance', 'brunnermunzel', 'alexandergovern', 'expectile', ] def _chk_asarray(a, axis): if axis is None: a = np.ravel(a) outaxis = 0 else: a = np.asarray(a) outaxis = axis if a.ndim == 0: a = np.atleast_1d(a) return a, outaxis def _chk2_asarray(a, b, axis): if axis is None: a = np.ravel(a) b = np.ravel(b) outaxis = 0 else: a = np.asarray(a) b = np.asarray(b) outaxis = axis if a.ndim == 0: a = np.atleast_1d(a) if b.ndim == 0: b = np.atleast_1d(b) return a, b, outaxis SignificanceResult = _make_tuple_bunch('SignificanceResult', ['statistic', 'pvalue'], []) # note that `weights` are paired with `x` @_axis_nan_policy_factory( lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, result_to_tuple=lambda x: (x,), kwd_samples=['weights']) def gmean(a, axis=0, dtype=None, weights=None): r"""Compute the weighted geometric mean along the specified axis. The weighted geometric mean of the array :math:`a_i` associated to weights :math:`w_i` is: .. math:: \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i } \right) \, , and, with equal weights, it gives: .. math:: \sqrt[n]{ \prod_{i=1}^n a_i } \, . Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int or None, optional Axis along which the geometric mean is computed. Default is 0. If None, compute over the whole array `a`. dtype : dtype, optional Type to which the input arrays are cast before the calculation is performed. weights : array_like, optional The `weights` array must be broadcastable to the same shape as `a`. Default is None, which gives each value a weight of 1.0. Returns ------- gmean : ndarray See `dtype` parameter above. See Also -------- numpy.mean : Arithmetic average numpy.average : Weighted average hmean : Harmonic mean References ---------- .. [1] "Weighted Geometric Mean", *Wikipedia*, https://en.wikipedia.org/wiki/Weighted_geometric_mean. .. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach", Archimedes Foundation, 1983 Examples -------- >>> from scipy.stats import gmean >>> gmean([1, 4]) 2.0 >>> gmean([1, 2, 3, 4, 5, 6, 7]) 3.3800151591412964 >>> gmean([1, 4, 7], weights=[3, 1, 3]) 2.80668351922014 """ a = np.asarray(a, dtype=dtype) if weights is not None: weights = np.asarray(weights, dtype=dtype) with np.errstate(divide='ignore'): log_a = np.log(a) return np.exp(np.average(log_a, axis=axis, weights=weights)) @_axis_nan_policy_factory( lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, result_to_tuple=lambda x: (x,), kwd_samples=['weights']) def hmean(a, axis=0, dtype=None, *, weights=None): r"""Calculate the weighted harmonic mean along the specified axis. The weighted harmonic mean of the array :math:`a_i` associated to weights :math:`w_i` is: .. math:: \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, , and, with equal weights, it gives: .. math:: \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, . Parameters ---------- a : array_like Input array, masked array or object that can be converted to an array. axis : int or None, optional Axis along which the harmonic mean is computed. Default is 0. If None, compute over the whole array `a`. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer `dtype` with a precision less than that of the default platform integer. In that case, the default platform integer is used. weights : array_like, optional The weights array can either be 1-D (in which case its length must be the size of `a` along the given `axis`) or of the same shape as `a`. Default is None, which gives each value a weight of 1.0. .. versionadded:: 1.9 Returns ------- hmean : ndarray See `dtype` parameter above. See Also -------- numpy.mean : Arithmetic average numpy.average : Weighted average gmean : Geometric mean Notes ----- The harmonic mean is computed over a single dimension of the input array, axis=0 by default, or all values in the array if axis=None. float64 intermediate and return values are used for integer inputs. References ---------- .. [1] "Weighted Harmonic Mean", *Wikipedia*, https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of the American Statistical Association, vol. 26, pp. 36-40, 1931 Examples -------- >>> from scipy.stats import hmean >>> hmean([1, 4]) 1.6000000000000001 >>> hmean([1, 2, 3, 4, 5, 6, 7]) 2.6997245179063363 >>> hmean([1, 4, 7], weights=[3, 1, 3]) 1.9029126213592233 """ if not isinstance(a, np.ndarray): a = np.array(a, dtype=dtype) elif dtype: # Must change the default dtype allowing array type if isinstance(a, np.ma.MaskedArray): a = np.ma.asarray(a, dtype=dtype) else: a = np.asarray(a, dtype=dtype) if np.all(a >= 0): # Harmonic mean only defined if greater than or equal to zero. if weights is not None: weights = np.asanyarray(weights, dtype=dtype) with np.errstate(divide='ignore'): return 1.0 / np.average(1.0 / a, axis=axis, weights=weights) else: raise ValueError("Harmonic mean only defined if all elements greater " "than or equal to zero") @_axis_nan_policy_factory( lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, result_to_tuple=lambda x: (x,), kwd_samples=['weights']) def pmean(a, p, *, axis=0, dtype=None, weights=None): r"""Calculate the weighted power mean along the specified axis. The weighted power mean of the array :math:`a_i` associated to weights :math:`w_i` is: .. math:: \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i } \right)^{ 1 / p } \, , and, with equal weights, it gives: .. math:: \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p } \, . When ``p=0``, it returns the geometric mean. This mean is also called generalized mean or Hölder mean, and must not be confused with the Kolmogorov generalized mean, also called quasi-arithmetic mean or generalized f-mean [3]_. Parameters ---------- a : array_like Input array, masked array or object that can be converted to an array. p : int or float Exponent. axis : int or None, optional Axis along which the power mean is computed. Default is 0. If None, compute over the whole array `a`. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer `dtype` with a precision less than that of the default platform integer. In that case, the default platform integer is used. weights : array_like, optional The weights array can either be 1-D (in which case its length must be the size of `a` along the given `axis`) or of the same shape as `a`. Default is None, which gives each value a weight of 1.0. Returns ------- pmean : ndarray, see `dtype` parameter above. Output array containing the power mean values. See Also -------- numpy.average : Weighted average gmean : Geometric mean hmean : Harmonic mean Notes ----- The power mean is computed over a single dimension of the input array, ``axis=0`` by default, or all values in the array if ``axis=None``. float64 intermediate and return values are used for integer inputs. .. versionadded:: 1.9 References ---------- .. [1] "Generalized Mean", *Wikipedia*, https://en.wikipedia.org/wiki/Generalized_mean .. [2] Norris, N., "Convexity properties of generalized mean value functions", The Annals of Mathematical Statistics, vol. 8, pp. 118-120, 1937 .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003 Examples -------- >>> from scipy.stats import pmean, hmean, gmean >>> pmean([1, 4], 1.3) 2.639372938300652 >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3) 4.157111214492084 >>> pmean([1, 4, 7], -2, weights=[3, 1, 3]) 1.4969684896631954 For p=-1, power mean is equal to harmonic mean: >>> pmean([1, 4, 7], -1, weights=[3, 1, 3]) 1.9029126213592233 >>> hmean([1, 4, 7], weights=[3, 1, 3]) 1.9029126213592233 For p=0, power mean is defined as the geometric mean: >>> pmean([1, 4, 7], 0, weights=[3, 1, 3]) 2.80668351922014 >>> gmean([1, 4, 7], weights=[3, 1, 3]) 2.80668351922014 """ if not isinstance(p, (int, float)): raise ValueError("Power mean only defined for exponent of type int or " "float.") if p == 0: return gmean(a, axis=axis, dtype=dtype, weights=weights) if not isinstance(a, np.ndarray): a = np.array(a, dtype=dtype) elif dtype: # Must change the default dtype allowing array type if isinstance(a, np.ma.MaskedArray): a = np.ma.asarray(a, dtype=dtype) else: a = np.asarray(a, dtype=dtype) if np.all(a >= 0): # Power mean only defined if greater than or equal to zero if weights is not None: weights = np.asanyarray(weights, dtype=dtype) with np.errstate(divide='ignore'): return np.float_power( np.average(np.float_power(a, p), axis=axis, weights=weights), 1/p) else: raise ValueError("Power mean only defined if all elements greater " "than or equal to zero") ModeResult = namedtuple('ModeResult', ('mode', 'count')) def _mode_result(mode, count): # When a slice is empty, `_axis_nan_policy` automatically produces # NaN for `mode` and `count`. This is a reasonable convention for `mode`, # but `count` should not be NaN; it should be zero. i = np.isnan(count) if i.shape == (): count = count.dtype(0) if i else count else: count[i] = 0 return ModeResult(mode, count) @_axis_nan_policy_factory(_mode_result, override={'vectorization': True, 'nan_propagation': False}) def mode(a, axis=0, nan_policy='propagate', keepdims=False): r"""Return an array of the modal (most common) value in the passed array. If there is more than one such value, only one is returned. The bin-count for the modal bins is also returned. Parameters ---------- a : array_like Numeric, n-dimensional array of which to find mode(s). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': treats nan as it would treat any other value * 'raise': throws an error * 'omit': performs the calculations ignoring nan values keepdims : bool, optional If set to ``False``, the `axis` over which the statistic is taken is consumed (eliminated from the output array). If set to ``True``, the `axis` is retained with size one, and the result will broadcast correctly against the input array. Returns ------- mode : ndarray Array of modal values. count : ndarray Array of counts for each mode. Notes ----- The mode is calculated using `numpy.unique`. In NumPy versions 1.21 and after, all NaNs - even those with different binary representations - are treated as equivalent and counted as separate instances of the same value. By convention, the mode of an empty array is NaN, and the associated count is zero. Examples -------- >>> import numpy as np >>> a = np.array([[3, 0, 3, 7], ... [3, 2, 6, 2], ... [1, 7, 2, 8], ... [3, 0, 6, 1], ... [3, 2, 5, 5]]) >>> from scipy import stats >>> stats.mode(a, keepdims=True) ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]])) To get mode of whole array, specify ``axis=None``: >>> stats.mode(a, axis=None, keepdims=True) ModeResult(mode=[[3]], count=[[5]]) >>> stats.mode(a, axis=None, keepdims=False) ModeResult(mode=3, count=5) """ # noqa: E501 # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy` if not np.issubdtype(a.dtype, np.number): message = ("Argument `a` is not recognized as numeric. " "Support for input that cannot be coerced to a numeric " "array was deprecated in SciPy 1.9.0 and removed in SciPy " "1.11.0. Please consider `np.unique`.") raise TypeError(message) if a.size == 0: NaN = _get_nan(a) return ModeResult(*np.array([NaN, 0], dtype=NaN.dtype)) vals, cnts = np.unique(a, return_counts=True) modes, counts = vals[cnts.argmax()], cnts.max() return ModeResult(modes[()], counts[()]) def _mask_to_limits(a, limits, inclusive): """Mask an array for values outside of given limits. This is primarily a utility function. Parameters ---------- a : array limits : (float or None, float or None) A tuple consisting of the (lower limit, upper limit). Values in the input array less than the lower limit or greater than the upper limit will be masked out. None implies no limit. inclusive : (bool, bool) A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to lower or upper are allowed. Returns ------- A MaskedArray. Raises ------ A ValueError if there are no values within the given limits. """ lower_limit, upper_limit = limits lower_include, upper_include = inclusive am = ma.MaskedArray(a) if lower_limit is not None: if lower_include: am = ma.masked_less(am, lower_limit) else: am = ma.masked_less_equal(am, lower_limit) if upper_limit is not None: if upper_include: am = ma.masked_greater(am, upper_limit) else: am = ma.masked_greater_equal(am, upper_limit) if am.count() == 0: raise ValueError("No array values within given limits") return am def tmean(a, limits=None, inclusive=(True, True), axis=None): """Compute the trimmed mean. This function finds the arithmetic mean of given values, ignoring values outside the given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None (default), then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to compute test. Default is None. Returns ------- tmean : ndarray Trimmed mean. See Also -------- trim_mean : Returns mean after trimming a proportion from both tails. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.tmean(x) 9.5 >>> stats.tmean(x, (3,17)) 10.0 """ a = asarray(a) if limits is None: return np.mean(a, axis) am = _mask_to_limits(a, limits, inclusive) mean = np.ma.filled(am.mean(axis=axis), fill_value=np.nan) return mean if mean.ndim > 0 else mean.item() def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1): """Compute the trimmed variance. This function computes the sample variance of an array of values, while ignoring values which are outside of given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tvar : float Trimmed variance. Notes ----- `tvar` computes the unbiased sample variance, i.e. it uses a correction factor ``n / (n - 1)``. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.tvar(x) 35.0 >>> stats.tvar(x, (3,17)) 20.0 """ a = asarray(a) a = a.astype(float) if limits is None: return a.var(ddof=ddof, axis=axis) am = _mask_to_limits(a, limits, inclusive) amnan = am.filled(fill_value=np.nan) return np.nanvar(amnan, ddof=ddof, axis=axis) def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'): """Compute the trimmed minimum. This function finds the miminum value of an array `a` along the specified axis, but only considering values greater than a specified lower limit. Parameters ---------- a : array_like Array of values. lowerlimit : None or float, optional Values in the input array less than the given limit will be ignored. When lowerlimit is None, then all values are used. The default value is None. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. inclusive : {True, False}, optional This flag determines whether values exactly equal to the lower limit are included. The default value is True. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- tmin : float, int or ndarray Trimmed minimum. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.tmin(x) 0 >>> stats.tmin(x, 13) 13 >>> stats.tmin(x, 13, inclusive=False) 14 """ a, axis = _chk_asarray(a, axis) am = _mask_to_limits(a, (lowerlimit, None), (inclusive, False)) contains_nan, nan_policy = _contains_nan(am, nan_policy) if contains_nan and nan_policy == 'omit': am = ma.masked_invalid(am) res = ma.minimum.reduce(am, axis).data if res.ndim == 0: return res[()] return res def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'): """Compute the trimmed maximum. This function computes the maximum value of an array along a given axis, while ignoring values larger than a specified upper limit. Parameters ---------- a : array_like Array of values. upperlimit : None or float, optional Values in the input array greater than the given limit will be ignored. When upperlimit is None, then all values are used. The default value is None. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. inclusive : {True, False}, optional This flag determines whether values exactly equal to the upper limit are included. The default value is True. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- tmax : float, int or ndarray Trimmed maximum. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.tmax(x) 19 >>> stats.tmax(x, 13) 13 >>> stats.tmax(x, 13, inclusive=False) 12 """ a, axis = _chk_asarray(a, axis) am = _mask_to_limits(a, (None, upperlimit), (False, inclusive)) contains_nan, nan_policy = _contains_nan(am, nan_policy) if contains_nan and nan_policy == 'omit': am = ma.masked_invalid(am) res = ma.maximum.reduce(am, axis).data if res.ndim == 0: return res[()] return res def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1): """Compute the trimmed sample standard deviation. This function finds the sample standard deviation of given values, ignoring values outside the given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tstd : float Trimmed sample standard deviation. Notes ----- `tstd` computes the unbiased sample standard deviation, i.e. it uses a correction factor ``n / (n - 1)``. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.tstd(x) 5.9160797830996161 >>> stats.tstd(x, (3,17)) 4.4721359549995796 """ return np.sqrt(tvar(a, limits, inclusive, axis, ddof)) def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1): """Compute the trimmed standard error of the mean. This function finds the standard error of the mean for given values, ignoring values outside the given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tsem : float Trimmed standard error of the mean. Notes ----- `tsem` uses unbiased sample standard deviation, i.e. it uses a correction factor ``n / (n - 1)``. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.tsem(x) 1.3228756555322954 >>> stats.tsem(x, (3,17)) 1.1547005383792515 """ a = np.asarray(a).ravel() if limits is None: return a.std(ddof=ddof) / np.sqrt(a.size) am = _mask_to_limits(a, limits, inclusive) sd = np.sqrt(np.ma.var(am, ddof=ddof, axis=axis)) return sd / np.sqrt(am.count()) ##################################### # MOMENTS # ##################################### def _moment_outputs(kwds): moment = np.atleast_1d(kwds.get('moment', 1)) if moment.size == 0: raise ValueError("'moment' must be a scalar or a non-empty 1D " "list/array.") return len(moment) def _moment_result_object(*args): if len(args) == 1: return args[0] return np.asarray(args) # `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual # because the number of outputs is variable. Specifically, # `result_to_tuple=lambda x: (x,)` may be surprising for a function that # can produce more than one output, but it is intended here. # When `moment is called to produce the output: # - `result_to_tuple` packs the returned array into a single-element tuple, # - `_moment_result_object` extracts and returns that single element. # However, when the input array is empty, `moment` is never called. Instead, # - `_check_empty_inputs` is used to produce an empty array with the # appropriate dimensions. # - A list comprehension creates the appropriate number of copies of this # array, depending on `n_outputs`. # - This list - which may have multiple elements - is passed into # `_moment_result_object`. # - If there is a single output, `_moment_result_object` extracts and returns # the single output from the list. # - If there are multiple outputs, and therefore multiple elements in the list, # `_moment_result_object` converts the list of arrays to a single array and # returns it. # Currently this leads to a slight inconsistency: when the input array is # empty, there is no distinction between the `moment` function being called # with parameter `moments=1` and `moments=[1]`; the latter *should* produce # the same as the former but with a singleton zeroth dimension. @_axis_nan_policy_factory( # noqa: E302 _moment_result_object, n_samples=1, result_to_tuple=lambda x: (x,), n_outputs=_moment_outputs ) def moment(a, moment=1, axis=0, nan_policy='propagate', *, center=None): r"""Calculate the nth moment about the mean for a sample. A moment is a specific quantitative measure of the shape of a set of points. It is often used to calculate coefficients of skewness and kurtosis due to its close relationship with them. Parameters ---------- a : array_like Input array. moment : int or array_like of ints, optional Order of central moment that is returned. Default is 1. axis : int or None, optional Axis along which the central moment is computed. Default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values center : float or None, optional The point about which moments are taken. This can be the sample mean, the origin, or any other be point. If `None` (default) compute the center as the sample mean. Returns ------- n-th moment about the `center` : ndarray or float The appropriate moment along the given axis or over all values if axis is None. The denominator for the moment calculation is the number of observations, no degrees of freedom correction is done. See Also -------- kurtosis, skew, describe Notes ----- The k-th moment of a data sample is: .. math:: m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - c)^k Where `n` is the number of samples, and `c` is the center around which the moment is calculated. This function uses exponentiation by squares [1]_ for efficiency. Note that, if `a` is an empty array (``a.size == 0``), array `moment` with one element (`moment.size == 1`) is treated the same as scalar `moment` (``np.isscalar(moment)``). This might produce arrays of unexpected shape. References ---------- .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms Examples -------- >>> from scipy.stats import moment >>> moment([1, 2, 3, 4, 5], moment=1) 0.0 >>> moment([1, 2, 3, 4, 5], moment=2) 2.0 """ a, axis = _chk_asarray(a, axis) # for array_like moment input, return a value for each. if not np.isscalar(moment): # Calculated the mean once at most, and only if it will be used calculate_mean = center is None and np.any(np.asarray(moment) > 1) mean = a.mean(axis, keepdims=True) if calculate_mean else None mmnt = [] for i in moment: if center is None and i > 1: mmnt.append(_moment(a, i, axis, mean=mean)) else: mmnt.append(_moment(a, i, axis, mean=center)) return np.array(mmnt) else: return _moment(a, moment, axis, mean=center) # Moment with optional pre-computed mean, equal to a.mean(axis, keepdims=True) def _moment(a, moment, axis, *, mean=None): if np.abs(moment - np.round(moment)) > 0: raise ValueError("All moment parameters must be integers") # moment of empty array is the same regardless of order if a.size == 0: return np.mean(a, axis=axis) dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64 if moment == 0 or (moment == 1 and mean is None): # By definition the zeroth moment is always 1, and the first *central* # moment is 0. shape = list(a.shape) del shape[axis] if len(shape) == 0: return dtype(1.0 if moment == 0 else 0.0) else: return (np.ones(shape, dtype=dtype) if moment == 0 else np.zeros(shape, dtype=dtype)) else: # Exponentiation by squares: form exponent sequence n_list = [moment] current_n = moment while current_n > 2: if current_n % 2: current_n = (current_n - 1) / 2 else: current_n /= 2 n_list.append(current_n) # Starting point for exponentiation by squares mean = (a.mean(axis, keepdims=True) if mean is None else np.asarray(mean, dtype=dtype)[()]) a_zero_mean = a - mean eps = np.finfo(a_zero_mean.dtype).resolution * 10 with np.errstate(divide='ignore', invalid='ignore'): rel_diff = np.max(np.abs(a_zero_mean), axis=axis, keepdims=True) / np.abs(mean) with np.errstate(invalid='ignore'): precision_loss = np.any(rel_diff < eps) n = a.shape[axis] if axis is not None else a.size if precision_loss and n > 1: message = ("Precision loss occurred in moment calculation due to " "catastrophic cancellation. This occurs when the data " "are nearly identical. Results may be unreliable.") warnings.warn(message, RuntimeWarning, stacklevel=4) if n_list[-1] == 1: s = a_zero_mean.copy() else: s = a_zero_mean**2 # Perform multiplications for n in n_list[-2::-1]: s = s**2 if n % 2: s *= a_zero_mean return np.mean(s, axis) def _var(x, axis=0, ddof=0, mean=None): # Calculate variance of sample, warning if precision is lost var = _moment(x, 2, axis, mean=mean) if ddof != 0: n = x.shape[axis] if axis is not None else x.size var *= np.divide(n, n-ddof) # to avoid error on division by zero return var @_axis_nan_policy_factory( lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1 ) def skew(a, axis=0, bias=True, nan_policy='propagate'): r"""Compute the sample skewness of a data set. For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero means that there is more weight in the right tail of the distribution. The function `skewtest` can be used to determine if the skewness value is close enough to zero, statistically speaking. Parameters ---------- a : ndarray Input array. axis : int or None, optional Axis along which skewness is calculated. Default is 0. If None, compute over the whole array `a`. bias : bool, optional If False, then the calculations are corrected for statistical bias. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- skewness : ndarray The skewness of values along an axis, returning NaN where all values are equal. Notes ----- The sample skewness is computed as the Fisher-Pearson coefficient of skewness, i.e. .. math:: g_1=\frac{m_3}{m_2^{3/2}} where .. math:: m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i is the biased sample :math:`i\texttt{th}` central moment, and :math:`\bar{x}` is the sample mean. If ``bias`` is False, the calculations are corrected for bias and the value computed is the adjusted Fisher-Pearson standardized moment coefficient, i.e. .. math:: G_1=\frac{k_3}{k_2^{3/2}}= \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}. References ---------- .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard Probability and Statistics Tables and Formulae. Chapman & Hall: New York. 2000. Section 2.2.24.1 Examples -------- >>> from scipy.stats import skew >>> skew([1, 2, 3, 4, 5]) 0.0 >>> skew([2, 8, 0, 4, 1, 9, 9, 0]) 0.2650554122698573 """ a, axis = _chk_asarray(a, axis) n = a.shape[axis] contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.skew(a, axis, bias) mean = a.mean(axis, keepdims=True) m2 = _moment(a, 2, axis, mean=mean) m3 = _moment(a, 3, axis, mean=mean) with np.errstate(all='ignore'): zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2) vals = np.where(zero, np.nan, m3 / m2**1.5) if not bias: can_correct = ~zero & (n > 2) if can_correct.any(): m2 = np.extract(can_correct, m2) m3 = np.extract(can_correct, m3) nval = np.sqrt((n - 1.0) * n) / (n - 2.0) * m3 / m2**1.5 np.place(vals, can_correct, nval) return vals[()] @_axis_nan_policy_factory( lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1 ) def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'): """Compute the kurtosis (Fisher or Pearson) of a dataset. Kurtosis is the fourth central moment divided by the square of the variance. If Fisher's definition is used, then 3.0 is subtracted from the result to give 0.0 for a normal distribution. If bias is False then the kurtosis is calculated using k statistics to eliminate bias coming from biased moment estimators Use `kurtosistest` to see if result is close enough to normal. Parameters ---------- a : array Data for which the kurtosis is calculated. axis : int or None, optional Axis along which the kurtosis is calculated. Default is 0. If None, compute over the whole array `a`. fisher : bool, optional If True, Fisher's definition is used (normal ==> 0.0). If False, Pearson's definition is used (normal ==> 3.0). bias : bool, optional If False, then the calculations are corrected for statistical bias. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Returns ------- kurtosis : array The kurtosis of values along an axis, returning NaN where all values are equal. References ---------- .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard Probability and Statistics Tables and Formulae. Chapman & Hall: New York. 2000. Examples -------- In Fisher's definition, the kurtosis of the normal distribution is zero. In the following example, the kurtosis is close to zero, because it was calculated from the dataset, not from the continuous distribution. >>> import numpy as np >>> from scipy.stats import norm, kurtosis >>> data = norm.rvs(size=1000, random_state=3) >>> kurtosis(data) -0.06928694200380558 The distribution with a higher kurtosis has a heavier tail. The zero valued kurtosis of the normal distribution in Fisher's definition can serve as a reference point. >>> import matplotlib.pyplot as plt >>> import scipy.stats as stats >>> from scipy.stats import kurtosis >>> x = np.linspace(-5, 5, 100) >>> ax = plt.subplot() >>> distnames = ['laplace', 'norm', 'uniform'] >>> for distname in distnames: ... if distname == 'uniform': ... dist = getattr(stats, distname)(loc=-2, scale=4) ... else: ... dist = getattr(stats, distname) ... data = dist.rvs(size=1000) ... kur = kurtosis(data, fisher=True) ... y = dist.pdf(x) ... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3))) ... ax.legend() The Laplace distribution has a heavier tail than the normal distribution. The uniform distribution (which has negative kurtosis) has the thinnest tail. """ a, axis = _chk_asarray(a, axis) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.kurtosis(a, axis, fisher, bias) n = a.shape[axis] mean = a.mean(axis, keepdims=True) m2 = _moment(a, 2, axis, mean=mean) m4 = _moment(a, 4, axis, mean=mean) with np.errstate(all='ignore'): zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2) vals = np.where(zero, np.nan, m4 / m2**2.0) if not bias: can_correct = ~zero & (n > 3) if can_correct.any(): m2 = np.extract(can_correct, m2) m4 = np.extract(can_correct, m4) nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0) np.place(vals, can_correct, nval + 3.0) return vals[()] - 3 if fisher else vals[()] DescribeResult = namedtuple('DescribeResult', ('nobs', 'minmax', 'mean', 'variance', 'skewness', 'kurtosis')) def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'): """Compute several descriptive statistics of the passed array. Parameters ---------- a : array_like Input data. axis : int or None, optional Axis along which statistics are calculated. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom (only for variance). Default is 1. bias : bool, optional If False, then the skewness and kurtosis calculations are corrected for statistical bias. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- nobs : int or ndarray of ints Number of observations (length of data along `axis`). When 'omit' is chosen as nan_policy, the length along each axis slice is counted separately. minmax: tuple of ndarrays or floats Minimum and maximum value of `a` along the given axis. mean : ndarray or float Arithmetic mean of `a` along the given axis. variance : ndarray or float Unbiased variance of `a` along the given axis; denominator is number of observations minus one. skewness : ndarray or float Skewness of `a` along the given axis, based on moment calculations with denominator equal to the number of observations, i.e. no degrees of freedom correction. kurtosis : ndarray or float Kurtosis (Fisher) of `a` along the given axis. The kurtosis is normalized so that it is zero for the normal distribution. No degrees of freedom are used. See Also -------- skew, kurtosis Examples -------- >>> import numpy as np >>> from scipy import stats >>> a = np.arange(10) >>> stats.describe(a) DescribeResult(nobs=10, minmax=(0, 9), mean=4.5, variance=9.166666666666666, skewness=0.0, kurtosis=-1.2242424242424244) >>> b = [[1, 2], [3, 4]] >>> stats.describe(b) DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])), mean=array([2., 3.]), variance=array([2., 2.]), skewness=array([0., 0.]), kurtosis=array([-2., -2.])) """ a, axis = _chk_asarray(a, axis) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.describe(a, axis, ddof, bias) if a.size == 0: raise ValueError("The input must not be empty.") n = a.shape[axis] mm = (np.min(a, axis=axis), np.max(a, axis=axis)) m = np.mean(a, axis=axis) v = _var(a, axis=axis, ddof=ddof) sk = skew(a, axis, bias=bias) kurt = kurtosis(a, axis, bias=bias) return DescribeResult(n, mm, m, v, sk, kurt) ##################################### # NORMALITY TESTS # ##################################### def _normtest_finish(z, alternative): """Common code between all the normality-test functions.""" if alternative == 'less': prob = distributions.norm.cdf(z) elif alternative == 'greater': prob = distributions.norm.sf(z) elif alternative == 'two-sided': prob = 2 * distributions.norm.sf(np.abs(z)) else: raise ValueError("alternative must be " "'less', 'greater' or 'two-sided'") if z.ndim == 0: z = z[()] return z, prob SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue')) def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'): r"""Test whether the skew is different from the normal distribution. This function tests the null hypothesis that the skewness of the population that the sample was drawn from is the same as that of a corresponding normal distribution. Parameters ---------- a : array The data to be tested. axis : int or None, optional Axis along which statistics are calculated. Default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the skewness of the distribution underlying the sample is different from that of the normal distribution (i.e. 0) * 'less': the skewness of the distribution underlying the sample is less than that of the normal distribution * 'greater': the skewness of the distribution underlying the sample is greater than that of the normal distribution .. versionadded:: 1.7.0 Returns ------- statistic : float The computed z-score for this test. pvalue : float The p-value for the hypothesis test. Notes ----- The sample size must be at least 8. References ---------- .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr., "A suggestion for using powerful and informative tests of normality", American Statistician 44, pp. 316-321, 1990. .. [2] Shapiro, S. S., & Wilk, M. B. (1965). An analysis of variance test for normality (complete samples). Biometrika, 52(3/4), 591-611. .. [3] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." Statistical Applications in Genetics and Molecular Biology 9.1 (2010). Examples -------- Suppose we wish to infer from measurements whether the weights of adult human males in a medical study are not normally distributed [2]_. The weights (lbs) are recorded in the array ``x`` below. >>> import numpy as np >>> x = np.array([148, 154, 158, 160, 161, 162, 166, 170, 182, 195, 236]) The skewness test from [1]_ begins by computing a statistic based on the sample skewness. >>> from scipy import stats >>> res = stats.skewtest(x) >>> res.statistic 2.7788579769903414 Because normal distributions have zero skewness, the magnitude of this statistic tends to be low for samples drawn from a normal distribution. The test is performed by comparing the observed value of the statistic against the null distribution: the distribution of statistic values derived under the null hypothesis that the weights were drawn from a normal distribution. For this test, the null distribution of the statistic for very large samples is the standard normal distribution. >>> import matplotlib.pyplot as plt >>> dist = stats.norm() >>> st_val = np.linspace(-5, 5, 100) >>> pdf = dist.pdf(st_val) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> def st_plot(ax): # we'll re-use this ... ax.plot(st_val, pdf) ... ax.set_title("Skew Test Null Distribution") ... ax.set_xlabel("statistic") ... ax.set_ylabel("probability density") >>> st_plot(ax) >>> plt.show() The comparison is quantified by the p-value: the proportion of values in the null distribution as extreme or more extreme than the observed value of the statistic. In a two-sided test, elements of the null distribution greater than the observed statistic and elements of the null distribution less than the negative of the observed statistic are both considered "more extreme". >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> st_plot(ax) >>> pvalue = dist.cdf(-res.statistic) + dist.sf(res.statistic) >>> annotation = (f'p-value={pvalue:.3f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (3, 0.005), (3.25, 0.02), arrowprops=props) >>> i = st_val >= res.statistic >>> ax.fill_between(st_val[i], y1=0, y2=pdf[i], color='C0') >>> i = st_val <= -res.statistic >>> ax.fill_between(st_val[i], y1=0, y2=pdf[i], color='C0') >>> ax.set_xlim(-5, 5) >>> ax.set_ylim(0, 0.1) >>> plt.show() >>> res.pvalue 0.005455036974740185 If the p-value is "small" - that is, if there is a low probability of sampling data from a normally distributed population that produces such an extreme value of the statistic - this may be taken as evidence against the null hypothesis in favor of the alternative: the weights were not drawn from a normal distribution. Note that: - The inverse is not true; that is, the test is not used to provide evidence for the null hypothesis. - The threshold for values that will be considered "small" is a choice that should be made before the data is analyzed [3]_ with consideration of the risks of both false positives (incorrectly rejecting the null hypothesis) and false negatives (failure to reject a false null hypothesis). Note that the standard normal distribution provides an asymptotic approximation of the null distribution; it is only accurate for samples with many observations. For small samples like ours, `scipy.stats.monte_carlo_test` may provide a more accurate, albeit stochastic, approximation of the exact p-value. >>> def statistic(x, axis): ... # get just the skewtest statistic; ignore the p-value ... return stats.skewtest(x, axis=axis).statistic >>> res = stats.monte_carlo_test(x, stats.norm.rvs, statistic) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> st_plot(ax) >>> ax.hist(res.null_distribution, np.linspace(-5, 5, 50), ... density=True) >>> ax.legend(['aymptotic approximation\n(many observations)', ... 'Monte Carlo approximation\n(11 observations)']) >>> plt.show() >>> res.pvalue 0.0062 # may vary In this case, the asymptotic approximation and Monte Carlo approximation agree fairly closely, even for our small sample. """ a, axis = _chk_asarray(a, axis) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.skewtest(a, axis, alternative) if axis is None: a = np.ravel(a) axis = 0 b2 = skew(a, axis) n = a.shape[axis] if n < 8: raise ValueError( "skewtest is not valid with less than 8 samples; %i samples" " were given." % int(n)) y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2))) beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) / ((n-2.0) * (n+5) * (n+7) * (n+9))) W2 = -1 + math.sqrt(2 * (beta2 - 1)) delta = 1 / math.sqrt(0.5 * math.log(W2)) alpha = math.sqrt(2.0 / (W2 - 1)) y = np.where(y == 0, 1, y) Z = delta * np.log(y / alpha + np.sqrt((y / alpha)**2 + 1)) return SkewtestResult(*_normtest_finish(Z, alternative)) KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue')) def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'): r"""Test whether a dataset has normal kurtosis. This function tests the null hypothesis that the kurtosis of the population from which the sample was drawn is that of the normal distribution. Parameters ---------- a : array Array of the sample data. axis : int or None, optional Axis along which to compute test. Default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the kurtosis of the distribution underlying the sample is different from that of the normal distribution * 'less': the kurtosis of the distribution underlying the sample is less than that of the normal distribution * 'greater': the kurtosis of the distribution underlying the sample is greater than that of the normal distribution .. versionadded:: 1.7.0 Returns ------- statistic : float The computed z-score for this test. pvalue : float The p-value for the hypothesis test. Notes ----- Valid only for n>20. This function uses the method described in [1]_. References ---------- .. [1] see e.g. F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983. .. [2] Shapiro, S. S., & Wilk, M. B. (1965). An analysis of variance test for normality (complete samples). Biometrika, 52(3/4), 591-611. .. [3] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." Statistical Applications in Genetics and Molecular Biology 9.1 (2010). .. [4] Panagiotakos, D. B. (2008). The value of p-value in biomedical research. The open cardiovascular medicine journal, 2, 97. Examples -------- Suppose we wish to infer from measurements whether the weights of adult human males in a medical study are not normally distributed [2]_. The weights (lbs) are recorded in the array ``x`` below. >>> import numpy as np >>> x = np.array([148, 154, 158, 160, 161, 162, 166, 170, 182, 195, 236]) The kurtosis test from [1]_ begins by computing a statistic based on the sample (excess/Fisher) kurtosis. >>> from scipy import stats >>> res = stats.kurtosistest(x) >>> res.statistic 2.3048235214240873 (The test warns that our sample has too few observations to perform the test. We'll return to this at the end of the example.) Because normal distributions have zero excess kurtosis (by definition), the magnitude of this statistic tends to be low for samples drawn from a normal distribution. The test is performed by comparing the observed value of the statistic against the null distribution: the distribution of statistic values derived under the null hypothesis that the weights were drawn from a normal distribution. For this test, the null distribution of the statistic for very large samples is the standard normal distribution. >>> import matplotlib.pyplot as plt >>> dist = stats.norm() >>> kt_val = np.linspace(-5, 5, 100) >>> pdf = dist.pdf(kt_val) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> def kt_plot(ax): # we'll re-use this ... ax.plot(kt_val, pdf) ... ax.set_title("Kurtosis Test Null Distribution") ... ax.set_xlabel("statistic") ... ax.set_ylabel("probability density") >>> kt_plot(ax) >>> plt.show() The comparison is quantified by the p-value: the proportion of values in the null distribution as extreme or more extreme than the observed value of the statistic. In a two-sided test in which the statistic is positive, elements of the null distribution greater than the observed statistic and elements of the null distribution less than the negative of the observed statistic are both considered "more extreme". >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> kt_plot(ax) >>> pvalue = dist.cdf(-res.statistic) + dist.sf(res.statistic) >>> annotation = (f'p-value={pvalue:.3f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (3, 0.005), (3.25, 0.02), arrowprops=props) >>> i = kt_val >= res.statistic >>> ax.fill_between(kt_val[i], y1=0, y2=pdf[i], color='C0') >>> i = kt_val <= -res.statistic >>> ax.fill_between(kt_val[i], y1=0, y2=pdf[i], color='C0') >>> ax.set_xlim(-5, 5) >>> ax.set_ylim(0, 0.1) >>> plt.show() >>> res.pvalue 0.0211764592113868 If the p-value is "small" - that is, if there is a low probability of sampling data from a normally distributed population that produces such an extreme value of the statistic - this may be taken as evidence against the null hypothesis in favor of the alternative: the weights were not drawn from a normal distribution. Note that: - The inverse is not true; that is, the test is not used to provide evidence for the null hypothesis. - The threshold for values that will be considered "small" is a choice that should be made before the data is analyzed [3]_ with consideration of the risks of both false positives (incorrectly rejecting the null hypothesis) and false negatives (failure to reject a false null hypothesis). Note that the standard normal distribution provides an asymptotic approximation of the null distribution; it is only accurate for samples with many observations. This is the reason we received a warning at the beginning of the example; our sample is quite small. In this case, `scipy.stats.monte_carlo_test` may provide a more accurate, albeit stochastic, approximation of the exact p-value. >>> def statistic(x, axis): ... # get just the skewtest statistic; ignore the p-value ... return stats.kurtosistest(x, axis=axis).statistic >>> res = stats.monte_carlo_test(x, stats.norm.rvs, statistic) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> kt_plot(ax) >>> ax.hist(res.null_distribution, np.linspace(-5, 5, 50), ... density=True) >>> ax.legend(['aymptotic approximation\n(many observations)', ... 'Monte Carlo approximation\n(11 observations)']) >>> plt.show() >>> res.pvalue 0.0272 # may vary Furthermore, despite their stochastic nature, p-values computed in this way can be used to exactly control the rate of false rejections of the null hypothesis [4]_. """ a, axis = _chk_asarray(a, axis) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.kurtosistest(a, axis, alternative) n = a.shape[axis] if n < 5: raise ValueError( "kurtosistest requires at least 5 observations; %i observations" " were given." % int(n)) if n < 20: warnings.warn("kurtosistest only valid for n>=20 ... continuing " "anyway, n=%i" % int(n)) b2 = kurtosis(a, axis, fisher=False) E = 3.0*(n-1) / (n+1) varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1 x = (b2-E) / np.sqrt(varb2) # [1]_ Eq. 4 # [1]_ Eq. 2: sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) / (n*(n-2)*(n-3))) # [1]_ Eq. 3: A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2))) term1 = 1 - 2/(9.0*A) denom = 1 + x*np.sqrt(2/(A-4.0)) term2 = np.sign(denom) * np.where(denom == 0.0, np.nan, np.power((1-2.0/A)/np.abs(denom), 1/3.0)) if np.any(denom == 0): msg = "Test statistic not defined in some cases due to division by " \ "zero. Return nan in that case..." warnings.warn(msg, RuntimeWarning) Z = (term1 - term2) / np.sqrt(2/(9.0*A)) # [1]_ Eq. 5 # zprob uses upper tail, so Z needs to be positive return KurtosistestResult(*_normtest_finish(Z, alternative)) NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue')) def normaltest(a, axis=0, nan_policy='propagate'): r"""Test whether a sample differs from a normal distribution. This function tests the null hypothesis that a sample comes from a normal distribution. It is based on D'Agostino and Pearson's [1]_, [2]_ test that combines skew and kurtosis to produce an omnibus test of normality. Parameters ---------- a : array_like The array containing the sample to be tested. axis : int or None, optional Axis along which to compute test. Default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- statistic : float or array ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and ``k`` is the z-score returned by `kurtosistest`. pvalue : float or array A 2-sided chi squared probability for the hypothesis test. References ---------- .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for moderate and large sample size", Biometrika, 58, 341-348 .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from normality", Biometrika, 60, 613-622 .. [3] Shapiro, S. S., & Wilk, M. B. (1965). An analysis of variance test for normality (complete samples). Biometrika, 52(3/4), 591-611. .. [4] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." Statistical Applications in Genetics and Molecular Biology 9.1 (2010). .. [5] Panagiotakos, D. B. (2008). The value of p-value in biomedical research. The open cardiovascular medicine journal, 2, 97. Examples -------- Suppose we wish to infer from measurements whether the weights of adult human males in a medical study are not normally distributed [3]_. The weights (lbs) are recorded in the array ``x`` below. >>> import numpy as np >>> x = np.array([148, 154, 158, 160, 161, 162, 166, 170, 182, 195, 236]) The normality test of [1]_ and [2]_ begins by computing a statistic based on the sample skewness and kurtosis. >>> from scipy import stats >>> res = stats.normaltest(x) >>> res.statistic 13.034263121192582 (The test warns that our sample has too few observations to perform the test. We'll return to this at the end of the example.) Because the normal distribution has zero skewness and zero ("excess" or "Fisher") kurtosis, the value of this statistic tends to be low for samples drawn from a normal distribution. The test is performed by comparing the observed value of the statistic against the null distribution: the distribution of statistic values derived under the null hypothesis that the weights were drawn from a normal distribution. For this normality test, the null distribution for very large samples is the chi-squared distribution with two degrees of freedom. >>> import matplotlib.pyplot as plt >>> dist = stats.chi2(df=2) >>> stat_vals = np.linspace(0, 16, 100) >>> pdf = dist.pdf(stat_vals) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> def plot(ax): # we'll re-use this ... ax.plot(stat_vals, pdf) ... ax.set_title("Normality Test Null Distribution") ... ax.set_xlabel("statistic") ... ax.set_ylabel("probability density") >>> plot(ax) >>> plt.show() The comparison is quantified by the p-value: the proportion of values in the null distribution greater than or equal to the observed value of the statistic. >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> pvalue = dist.sf(res.statistic) >>> annotation = (f'p-value={pvalue:.6f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (13.5, 5e-4), (14, 5e-3), arrowprops=props) >>> i = stat_vals >= res.statistic # index more extreme statistic values >>> ax.fill_between(stat_vals[i], y1=0, y2=pdf[i]) >>> ax.set_xlim(8, 16) >>> ax.set_ylim(0, 0.01) >>> plt.show() >>> res.pvalue 0.0014779023013100172 If the p-value is "small" - that is, if there is a low probability of sampling data from a normally distributed population that produces such an extreme value of the statistic - this may be taken as evidence against the null hypothesis in favor of the alternative: the weights were not drawn from a normal distribution. Note that: - The inverse is not true; that is, the test is not used to provide evidence for the null hypothesis. - The threshold for values that will be considered "small" is a choice that should be made before the data is analyzed [4]_ with consideration of the risks of both false positives (incorrectly rejecting the null hypothesis) and false negatives (failure to reject a false null hypothesis). Note that the chi-squared distribution provides an asymptotic approximation of the null distribution; it is only accurate for samples with many observations. This is the reason we received a warning at the beginning of the example; our sample is quite small. In this case, `scipy.stats.monte_carlo_test` may provide a more accurate, albeit stochastic, approximation of the exact p-value. >>> def statistic(x, axis): ... # Get only the `normaltest` statistic; ignore approximate p-value ... return stats.normaltest(x, axis=axis).statistic >>> res = stats.monte_carlo_test(x, stats.norm.rvs, statistic, ... alternative='greater') >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> ax.hist(res.null_distribution, np.linspace(0, 25, 50), ... density=True) >>> ax.legend(['aymptotic approximation (many observations)', ... 'Monte Carlo approximation (11 observations)']) >>> ax.set_xlim(0, 14) >>> plt.show() >>> res.pvalue 0.0082 # may vary Furthermore, despite their stochastic nature, p-values computed in this way can be used to exactly control the rate of false rejections of the null hypothesis [5]_. """ a, axis = _chk_asarray(a, axis) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.normaltest(a, axis) s, _ = skewtest(a, axis) k, _ = kurtosistest(a, axis) k2 = s*s + k*k return NormaltestResult(k2, distributions.chi2.sf(k2, 2)) @_axis_nan_policy_factory(SignificanceResult, default_axis=None) def jarque_bera(x, *, axis=None): r"""Perform the Jarque-Bera goodness of fit test on sample data. The Jarque-Bera test tests whether the sample data has the skewness and kurtosis matching a normal distribution. Note that this test only works for a large enough number of data samples (>2000) as the test statistic asymptotically has a Chi-squared distribution with 2 degrees of freedom. Parameters ---------- x : array_like Observations of a random variable. axis : int or None, default: 0 If an int, the axis of the input along which to compute the statistic. The statistic of each axis-slice (e.g. row) of the input will appear in a corresponding element of the output. If ``None``, the input will be raveled before computing the statistic. Returns ------- result : SignificanceResult An object with the following attributes: statistic : float The test statistic. pvalue : float The p-value for the hypothesis test. References ---------- .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality, homoscedasticity and serial independence of regression residuals", 6 Econometric Letters 255-259. .. [2] Shapiro, S. S., & Wilk, M. B. (1965). An analysis of variance test for normality (complete samples). Biometrika, 52(3/4), 591-611. .. [3] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." Statistical Applications in Genetics and Molecular Biology 9.1 (2010). .. [4] Panagiotakos, D. B. (2008). The value of p-value in biomedical research. The open cardiovascular medicine journal, 2, 97. Examples -------- Suppose we wish to infer from measurements whether the weights of adult human males in a medical study are not normally distributed [2]_. The weights (lbs) are recorded in the array ``x`` below. >>> import numpy as np >>> x = np.array([148, 154, 158, 160, 161, 162, 166, 170, 182, 195, 236]) The Jarque-Bera test begins by computing a statistic based on the sample skewness and kurtosis. >>> from scipy import stats >>> res = stats.jarque_bera(x) >>> res.statistic 6.982848237344646 Because the normal distribution has zero skewness and zero ("excess" or "Fisher") kurtosis, the value of this statistic tends to be low for samples drawn from a normal distribution. The test is performed by comparing the observed value of the statistic against the null distribution: the distribution of statistic values derived under the null hypothesis that the weights were drawn from a normal distribution. For the Jarque-Bera test, the null distribution for very large samples is the chi-squared distribution with two degrees of freedom. >>> import matplotlib.pyplot as plt >>> dist = stats.chi2(df=2) >>> jb_val = np.linspace(0, 11, 100) >>> pdf = dist.pdf(jb_val) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> def jb_plot(ax): # we'll re-use this ... ax.plot(jb_val, pdf) ... ax.set_title("Jarque-Bera Null Distribution") ... ax.set_xlabel("statistic") ... ax.set_ylabel("probability density") >>> jb_plot(ax) >>> plt.show() The comparison is quantified by the p-value: the proportion of values in the null distribution greater than or equal to the observed value of the statistic. >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> jb_plot(ax) >>> pvalue = dist.sf(res.statistic) >>> annotation = (f'p-value={pvalue:.6f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (7.5, 0.01), (8, 0.05), arrowprops=props) >>> i = jb_val >= res.statistic # indices of more extreme statistic values >>> ax.fill_between(jb_val[i], y1=0, y2=pdf[i]) >>> ax.set_xlim(0, 11) >>> ax.set_ylim(0, 0.3) >>> plt.show() >>> res.pvalue 0.03045746622458189 If the p-value is "small" - that is, if there is a low probability of sampling data from a normally distributed population that produces such an extreme value of the statistic - this may be taken as evidence against the null hypothesis in favor of the alternative: the weights were not drawn from a normal distribution. Note that: - The inverse is not true; that is, the test is not used to provide evidence for the null hypothesis. - The threshold for values that will be considered "small" is a choice that should be made before the data is analyzed [3]_ with consideration of the risks of both false positives (incorrectly rejecting the null hypothesis) and false negatives (failure to reject a false null hypothesis). Note that the chi-squared distribution provides an asymptotic approximation of the null distribution; it is only accurate for samples with many observations. For small samples like ours, `scipy.stats.monte_carlo_test` may provide a more accurate, albeit stochastic, approximation of the exact p-value. >>> def statistic(x, axis): ... # underlying calculation of the Jarque Bera statistic ... s = stats.skew(x, axis=axis) ... k = stats.kurtosis(x, axis=axis) ... return x.shape[axis]/6 * (s**2 + k**2/4) >>> res = stats.monte_carlo_test(x, stats.norm.rvs, statistic, ... alternative='greater') >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> jb_plot(ax) >>> ax.hist(res.null_distribution, np.linspace(0, 10, 50), ... density=True) >>> ax.legend(['aymptotic approximation (many observations)', ... 'Monte Carlo approximation (11 observations)']) >>> plt.show() >>> res.pvalue 0.0097 # may vary Furthermore, despite their stochastic nature, p-values computed in this way can be used to exactly control the rate of false rejections of the null hypothesis [4]_. """ x = np.asarray(x) if axis is None: x = x.ravel() axis = 0 n = x.shape[axis] if n == 0: raise ValueError('At least one observation is required.') mu = x.mean(axis=axis, keepdims=True) diffx = x - mu s = skew(diffx, axis=axis, _no_deco=True) k = kurtosis(diffx, axis=axis, _no_deco=True) statistic = n / 6 * (s**2 + k**2 / 4) pvalue = distributions.chi2.sf(statistic, df=2) return SignificanceResult(statistic, pvalue) ##################################### # FREQUENCY FUNCTIONS # ##################################### def scoreatpercentile(a, per, limit=(), interpolation_method='fraction', axis=None): """Calculate the score at a given percentile of the input sequence. For example, the score at `per=50` is the median. If the desired quantile lies between two data points, we interpolate between them, according to the value of `interpolation`. If the parameter `limit` is provided, it should be a tuple (lower, upper) of two values. Parameters ---------- a : array_like A 1-D array of values from which to extract score. per : array_like Percentile(s) at which to extract score. Values should be in range [0,100]. limit : tuple, optional Tuple of two scalars, the lower and upper limits within which to compute the percentile. Values of `a` outside this (closed) interval will be ignored. interpolation_method : {'fraction', 'lower', 'higher'}, optional Specifies the interpolation method to use, when the desired quantile lies between two data points `i` and `j` The following options are available (default is 'fraction'): * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j`` * 'lower': ``i`` * 'higher': ``j`` axis : int, optional Axis along which the percentiles are computed. Default is None. If None, compute over the whole array `a`. Returns ------- score : float or ndarray Score at percentile(s). See Also -------- percentileofscore, numpy.percentile Notes ----- This function will become obsolete in the future. For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality that `scoreatpercentile` provides. And it's significantly faster. Therefore it's recommended to use `numpy.percentile` for users that have numpy >= 1.9. Examples -------- >>> import numpy as np >>> from scipy import stats >>> a = np.arange(100) >>> stats.scoreatpercentile(a, 50) 49.5 """ # adapted from NumPy's percentile function. When we require numpy >= 1.8, # the implementation of this function can be replaced by np.percentile. a = np.asarray(a) if a.size == 0: # empty array, return nan(s) with shape matching `per` if np.isscalar(per): return np.nan else: return np.full(np.asarray(per).shape, np.nan, dtype=np.float64) if limit: a = a[(limit[0] <= a) & (a <= limit[1])] sorted_ = np.sort(a, axis=axis) if axis is None: axis = 0 return _compute_qth_percentile(sorted_, per, interpolation_method, axis) # handle sequence of per's without calling sort multiple times def _compute_qth_percentile(sorted_, per, interpolation_method, axis): if not np.isscalar(per): score = [_compute_qth_percentile(sorted_, i, interpolation_method, axis) for i in per] return np.array(score) if not (0 <= per <= 100): raise ValueError("percentile must be in the range [0, 100]") indexer = [slice(None)] * sorted_.ndim idx = per / 100. * (sorted_.shape[axis] - 1) if int(idx) != idx: # round fractional indices according to interpolation method if interpolation_method == 'lower': idx = int(np.floor(idx)) elif interpolation_method == 'higher': idx = int(np.ceil(idx)) elif interpolation_method == 'fraction': pass # keep idx as fraction and interpolate else: raise ValueError("interpolation_method can only be 'fraction', " "'lower' or 'higher'") i = int(idx) if i == idx: indexer[axis] = slice(i, i + 1) weights = array(1) sumval = 1.0 else: indexer[axis] = slice(i, i + 2) j = i + 1 weights = array([(j - idx), (idx - i)], float) wshape = [1] * sorted_.ndim wshape[axis] = 2 weights.shape = wshape sumval = weights.sum() # Use np.add.reduce (== np.sum but a little faster) to coerce data type return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval def percentileofscore(a, score, kind='rank', nan_policy='propagate'): """Compute the percentile rank of a score relative to a list of scores. A `percentileofscore` of, for example, 80% means that 80% of the scores in `a` are below the given score. In the case of gaps or ties, the exact definition depends on the optional keyword, `kind`. Parameters ---------- a : array_like Array to which `score` is compared. score : array_like Scores to compute percentiles for. kind : {'rank', 'weak', 'strict', 'mean'}, optional Specifies the interpretation of the resulting score. The following options are available (default is 'rank'): * 'rank': Average percentage ranking of score. In case of multiple matches, average the percentage rankings of all matching scores. * 'weak': This kind corresponds to the definition of a cumulative distribution function. A percentileofscore of 80% means that 80% of values are less than or equal to the provided score. * 'strict': Similar to "weak", except that only values that are strictly less than the given score are counted. * 'mean': The average of the "weak" and "strict" scores, often used in testing. See https://en.wikipedia.org/wiki/Percentile_rank nan_policy : {'propagate', 'raise', 'omit'}, optional Specifies how to treat `nan` values in `a`. The following options are available (default is 'propagate'): * 'propagate': returns nan (for each value in `score`). * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- pcos : float Percentile-position of score (0-100) relative to `a`. See Also -------- numpy.percentile scipy.stats.scoreatpercentile, scipy.stats.rankdata Examples -------- Three-quarters of the given values lie below a given score: >>> import numpy as np >>> from scipy import stats >>> stats.percentileofscore([1, 2, 3, 4], 3) 75.0 With multiple matches, note how the scores of the two matches, 0.6 and 0.8 respectively, are averaged: >>> stats.percentileofscore([1, 2, 3, 3, 4], 3) 70.0 Only 2/5 values are strictly less than 3: >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict') 40.0 But 4/5 values are less than or equal to 3: >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak') 80.0 The average between the weak and the strict scores is: >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean') 60.0 Score arrays (of any dimensionality) are supported: >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3]) array([40., 70.]) The inputs can be infinite: >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf]) array([75., 75., 100.]) If `a` is empty, then the resulting percentiles are all `nan`: >>> stats.percentileofscore([], [1, 2]) array([nan, nan]) """ a = np.asarray(a) n = len(a) score = np.asarray(score) # Nan treatment cna, npa = _contains_nan(a, nan_policy, use_summation=False) cns, nps = _contains_nan(score, nan_policy, use_summation=False) if (cna or cns) and nan_policy == 'raise': raise ValueError("The input contains nan values") if cns: # If a score is nan, then the output should be nan # (also if nan_policy is "omit", because it only applies to `a`) score = ma.masked_where(np.isnan(score), score) if cna: if nan_policy == "omit": # Don't count nans a = ma.masked_where(np.isnan(a), a) n = a.count() if nan_policy == "propagate": # All outputs should be nans n = 0 # Cannot compare to empty list ==> nan if n == 0: perct = np.full_like(score, np.nan, dtype=np.float64) else: # Prepare broadcasting score = score[..., None] def count(x): return np.count_nonzero(x, -1) # Despite using masked_array to omit nan values from processing, # the CI tests on "Azure pipelines" (but not on the other CI servers) # emits warnings when there are nan values, contrarily to the purpose # of masked_arrays. As a fix, we simply suppress the warnings. with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in less") sup.filter(RuntimeWarning, "invalid value encountered in greater") # Main computations/logic if kind == 'rank': left = count(a < score) right = count(a <= score) plus1 = left < right perct = (left + right + plus1) * (50.0 / n) elif kind == 'strict': perct = count(a < score) * (100.0 / n) elif kind == 'weak': perct = count(a <= score) * (100.0 / n) elif kind == 'mean': left = count(a < score) right = count(a <= score) perct = (left + right) * (50.0 / n) else: raise ValueError( "kind can only be 'rank', 'strict', 'weak' or 'mean'") # Re-insert nan values perct = ma.filled(perct, np.nan) if perct.ndim == 0: return perct[()] return perct HistogramResult = namedtuple('HistogramResult', ('count', 'lowerlimit', 'binsize', 'extrapoints')) def _histogram(a, numbins=10, defaultlimits=None, weights=None, printextras=False): """Create a histogram. Separate the range into several bins and return the number of instances in each bin. Parameters ---------- a : array_like Array of scores which will be put into bins. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultlimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in a is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 printextras : bool, optional If True, if there are extra points (i.e. the points that fall outside the bin limits) a warning is raised saying how many of those points there are. Default is False. Returns ------- count : ndarray Number of points (or sum of weights) in each bin. lowerlimit : float Lowest value of histogram, the lower limit of the first bin. binsize : float The size of the bins (all bins have the same size). extrapoints : int The number of points outside the range of the histogram. See Also -------- numpy.histogram Notes ----- This histogram is based on numpy's histogram but has a larger range by default if default limits is not set. """ a = np.ravel(a) if defaultlimits is None: if a.size == 0: # handle empty arrays. Undetermined range, so use 0-1. defaultlimits = (0, 1) else: # no range given, so use values in `a` data_min = a.min() data_max = a.max() # Have bins extend past min and max values slightly s = (data_max - data_min) / (2. * (numbins - 1.)) defaultlimits = (data_min - s, data_max + s) # use numpy's histogram method to compute bins hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits, weights=weights) # hist are not always floats, convert to keep with old output hist = np.array(hist, dtype=float) # fixed width for bins is assumed, as numpy's histogram gives # fixed width bins for int values for 'bins' binsize = bin_edges[1] - bin_edges[0] # calculate number of extra points extrapoints = len([v for v in a if defaultlimits[0] > v or v > defaultlimits[1]]) if extrapoints > 0 and printextras: warnings.warn("Points outside given histogram range = %s" % extrapoints) return HistogramResult(hist, defaultlimits[0], binsize, extrapoints) CumfreqResult = namedtuple('CumfreqResult', ('cumcount', 'lowerlimit', 'binsize', 'extrapoints')) def cumfreq(a, numbins=10, defaultreallimits=None, weights=None): """Return a cumulative frequency histogram, using the histogram function. A cumulative histogram is a mapping that counts the cumulative number of observations in all of the bins up to the specified bin. Parameters ---------- a : array_like Input array. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultreallimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 Returns ------- cumcount : ndarray Binned values of cumulative frequency. lowerlimit : float Lower real limit binsize : float Width of each bin. extrapoints : int Extra points. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> rng = np.random.default_rng() >>> x = [1, 4, 2, 1, 3, 1] >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5)) >>> res.cumcount array([ 1., 2., 3., 3.]) >>> res.extrapoints 3 Create a normal distribution with 1000 random values >>> samples = stats.norm.rvs(size=1000, random_state=rng) Calculate cumulative frequencies >>> res = stats.cumfreq(samples, numbins=25) Calculate space of values for x >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size, ... res.cumcount.size) Plot histogram and cumulative histogram >>> fig = plt.figure(figsize=(10, 4)) >>> ax1 = fig.add_subplot(1, 2, 1) >>> ax2 = fig.add_subplot(1, 2, 2) >>> ax1.hist(samples, bins=25) >>> ax1.set_title('Histogram') >>> ax2.bar(x, res.cumcount, width=res.binsize) >>> ax2.set_title('Cumulative histogram') >>> ax2.set_xlim([x.min(), x.max()]) >>> plt.show() """ h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) cumhist = np.cumsum(h * 1, axis=0) return CumfreqResult(cumhist, l, b, e) RelfreqResult = namedtuple('RelfreqResult', ('frequency', 'lowerlimit', 'binsize', 'extrapoints')) def relfreq(a, numbins=10, defaultreallimits=None, weights=None): """Return a relative frequency histogram, using the histogram function. A relative frequency histogram is a mapping of the number of observations in each of the bins relative to the total of observations. Parameters ---------- a : array_like Input array. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultreallimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in a is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 Returns ------- frequency : ndarray Binned values of relative frequency. lowerlimit : float Lower real limit. binsize : float Width of each bin. extrapoints : int Extra points. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> rng = np.random.default_rng() >>> a = np.array([2, 4, 1, 2, 3, 2]) >>> res = stats.relfreq(a, numbins=4) >>> res.frequency array([ 0.16666667, 0.5 , 0.16666667, 0.16666667]) >>> np.sum(res.frequency) # relative frequencies should add up to 1 1.0 Create a normal distribution with 1000 random values >>> samples = stats.norm.rvs(size=1000, random_state=rng) Calculate relative frequencies >>> res = stats.relfreq(samples, numbins=25) Calculate space of values for x >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, ... res.frequency.size) Plot relative frequency histogram >>> fig = plt.figure(figsize=(5, 4)) >>> ax = fig.add_subplot(1, 1, 1) >>> ax.bar(x, res.frequency, width=res.binsize) >>> ax.set_title('Relative frequency histogram') >>> ax.set_xlim([x.min(), x.max()]) >>> plt.show() """ a = np.asanyarray(a) h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) h = h / a.shape[0] return RelfreqResult(h, l, b, e) ##################################### # VARIABILITY FUNCTIONS # ##################################### def obrientransform(*samples): """Compute the O'Brien transform on input data (any number of arrays). Used to test for homogeneity of variance prior to running one-way stats. Each array in ``*samples`` is one level of a factor. If `f_oneway` is run on the transformed data and found significant, the variances are unequal. From Maxwell and Delaney [1]_, p.112. Parameters ---------- sample1, sample2, ... : array_like Any number of arrays. Returns ------- obrientransform : ndarray Transformed data for use in an ANOVA. The first dimension of the result corresponds to the sequence of transformed arrays. If the arrays given are all 1-D of the same length, the return value is a 2-D array; otherwise it is a 1-D array of type object, with each element being an ndarray. References ---------- .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990. Examples -------- We'll test the following data sets for differences in their variance. >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10] >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15] Apply the O'Brien transform to the data. >>> from scipy.stats import obrientransform >>> tx, ty = obrientransform(x, y) Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the transformed data. >>> from scipy.stats import f_oneway >>> F, p = f_oneway(tx, ty) >>> p 0.1314139477040335 If we require that ``p < 0.05`` for significance, we cannot conclude that the variances are different. """ TINY = np.sqrt(np.finfo(float).eps) # `arrays` will hold the transformed arguments. arrays = [] sLast = None for sample in samples: a = np.asarray(sample) n = len(a) mu = np.mean(a) sq = (a - mu)**2 sumsq = sq.sum() # The O'Brien transform. t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2)) # Check that the mean of the transformed data is equal to the # original variance. var = sumsq / (n - 1) if abs(var - np.mean(t)) > TINY: raise ValueError('Lack of convergence in obrientransform.') arrays.append(t) sLast = a.shape if sLast: for arr in arrays[:-1]: if sLast != arr.shape: return np.array(arrays, dtype=object) return np.array(arrays) @_axis_nan_policy_factory( lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, too_small=1 ) def sem(a, axis=0, ddof=1, nan_policy='propagate'): """Compute standard error of the mean. Calculate the standard error of the mean (or standard error of measurement) of the values in the input array. Parameters ---------- a : array_like An array containing the values for which the standard error is returned. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees-of-freedom. How many degrees of freedom to adjust for bias in limited samples relative to the population estimate of variance. Defaults to 1. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- s : ndarray or float The standard error of the mean in the sample(s), along the input axis. Notes ----- The default value for `ddof` is different to the default (0) used by other ddof containing routines, such as np.std and np.nanstd. Examples -------- Find standard error along the first axis: >>> import numpy as np >>> from scipy import stats >>> a = np.arange(20).reshape(5,4) >>> stats.sem(a) array([ 2.8284, 2.8284, 2.8284, 2.8284]) Find standard error across the whole array, using n degrees of freedom: >>> stats.sem(a, axis=None, ddof=0) 1.2893796958227628 """ n = a.shape[axis] s = np.std(a, axis=axis, ddof=ddof) / np.sqrt(n) return s def _isconst(x): """ Check if all values in x are the same. nans are ignored. x must be a 1d array. The return value is a 1d array with length 1, so it can be used in np.apply_along_axis. """ y = x[~np.isnan(x)] if y.size == 0: return np.array([True]) else: return (y[0] == y).all(keepdims=True) def _quiet_nanmean(x): """ Compute nanmean for the 1d array x, but quietly return nan if x is all nan. The return value is a 1d array with length 1, so it can be used in np.apply_along_axis. """ y = x[~np.isnan(x)] if y.size == 0: return np.array([np.nan]) else: return np.mean(y, keepdims=True) def _quiet_nanstd(x, ddof=0): """ Compute nanstd for the 1d array x, but quietly return nan if x is all nan. The return value is a 1d array with length 1, so it can be used in np.apply_along_axis. """ y = x[~np.isnan(x)] if y.size == 0: return np.array([np.nan]) else: return np.std(y, keepdims=True, ddof=ddof) def zscore(a, axis=0, ddof=0, nan_policy='propagate'): """ Compute the z score. Compute the z score of each value in the sample, relative to the sample mean and standard deviation. Parameters ---------- a : array_like An array like object containing the sample data. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Degrees of freedom correction in the calculation of the standard deviation. Default is 0. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Note that when the value is 'omit', nans in the input also propagate to the output, but they do not affect the z-scores computed for the non-nan values. Returns ------- zscore : array_like The z-scores, standardized by mean and standard deviation of input array `a`. See Also -------- numpy.mean : Arithmetic average numpy.std : Arithmetic standard deviation scipy.stats.gzscore : Geometric standard score Notes ----- This function preserves ndarray subclasses, and works also with matrices and masked arrays (it uses `asanyarray` instead of `asarray` for parameters). References ---------- .. [1] "Standard score", *Wikipedia*, https://en.wikipedia.org/wiki/Standard_score. .. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986 Examples -------- >>> import numpy as np >>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091, ... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508]) >>> from scipy import stats >>> stats.zscore(a) array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786, 0.6748, -1.1488, -1.3324]) Computing along a specified axis, using n-1 degrees of freedom (``ddof=1``) to calculate the standard deviation: >>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608], ... [ 0.7149, 0.0775, 0.6072, 0.9656], ... [ 0.6341, 0.1403, 0.9759, 0.4064], ... [ 0.5918, 0.6948, 0.904 , 0.3721], ... [ 0.0921, 0.2481, 0.1188, 0.1366]]) >>> stats.zscore(b, axis=1, ddof=1) array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358], [ 0.33048416, -1.37380874, 0.04251374, 1.00081084], [ 0.26796377, -1.12598418, 1.23283094, -0.37481053], [-0.22095197, 0.24468594, 1.19042819, -1.21416216], [-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]]) An example with `nan_policy='omit'`: >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15], ... [14.95, 16.06, 121.25, 94.35, 29.81]]) >>> stats.zscore(x, axis=1, nan_policy='omit') array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602], [-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]]) """ return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy) def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'): """ Compute the geometric standard score. Compute the geometric z score of each strictly positive value in the sample, relative to the geometric mean and standard deviation. Mathematically the geometric z score can be evaluated as:: gzscore = log(a/gmu) / log(gsigma) where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard deviation). Parameters ---------- a : array_like Sample data. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Degrees of freedom correction in the calculation of the standard deviation. Default is 0. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Note that when the value is 'omit', nans in the input also propagate to the output, but they do not affect the geometric z scores computed for the non-nan values. Returns ------- gzscore : array_like The geometric z scores, standardized by geometric mean and geometric standard deviation of input array `a`. See Also -------- gmean : Geometric mean gstd : Geometric standard deviation zscore : Standard score Notes ----- This function preserves ndarray subclasses, and works also with matrices and masked arrays (it uses ``asanyarray`` instead of ``asarray`` for parameters). .. versionadded:: 1.8 References ---------- .. [1] "Geometric standard score", *Wikipedia*, https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score. Examples -------- Draw samples from a log-normal distribution: >>> import numpy as np >>> from scipy.stats import zscore, gzscore >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng() >>> mu, sigma = 3., 1. # mean and standard deviation >>> x = rng.lognormal(mu, sigma, size=500) Display the histogram of the samples: >>> fig, ax = plt.subplots() >>> ax.hist(x, 50) >>> plt.show() Display the histogram of the samples standardized by the classical zscore. Distribution is rescaled but its shape is unchanged. >>> fig, ax = plt.subplots() >>> ax.hist(zscore(x), 50) >>> plt.show() Demonstrate that the distribution of geometric zscores is rescaled and quasinormal: >>> fig, ax = plt.subplots() >>> ax.hist(gzscore(x), 50) >>> plt.show() """ a = np.asanyarray(a) log = ma.log if isinstance(a, ma.MaskedArray) else np.log return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy) def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'): """ Calculate the relative z-scores. Return an array of z-scores, i.e., scores that are standardized to zero mean and unit variance, where mean and variance are calculated from the comparison array. Parameters ---------- scores : array_like The input for which z-scores are calculated. compare : array_like The input from which the mean and standard deviation of the normalization are taken; assumed to have the same dimension as `scores`. axis : int or None, optional Axis over which mean and variance of `compare` are calculated. Default is 0. If None, compute over the whole array `scores`. ddof : int, optional Degrees of freedom correction in the calculation of the standard deviation. Default is 0. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle the occurrence of nans in `compare`. 'propagate' returns nan, 'raise' raises an exception, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Note that when the value is 'omit', nans in `scores` also propagate to the output, but they do not affect the z-scores computed for the non-nan values. Returns ------- zscore : array_like Z-scores, in the same shape as `scores`. Notes ----- This function preserves ndarray subclasses, and works also with matrices and masked arrays (it uses `asanyarray` instead of `asarray` for parameters). Examples -------- >>> from scipy.stats import zmap >>> a = [0.5, 2.0, 2.5, 3] >>> b = [0, 1, 2, 3, 4] >>> zmap(a, b) array([-1.06066017, 0. , 0.35355339, 0.70710678]) """ a = np.asanyarray(compare) if a.size == 0: return np.empty(a.shape) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': if axis is None: mn = _quiet_nanmean(a.ravel()) std = _quiet_nanstd(a.ravel(), ddof=ddof) isconst = _isconst(a.ravel()) else: mn = np.apply_along_axis(_quiet_nanmean, axis, a) std = np.apply_along_axis(_quiet_nanstd, axis, a, ddof=ddof) isconst = np.apply_along_axis(_isconst, axis, a) else: mn = a.mean(axis=axis, keepdims=True) std = a.std(axis=axis, ddof=ddof, keepdims=True) if axis is None: isconst = (a.item(0) == a).all() else: isconst = (_first(a, axis) == a).all(axis=axis, keepdims=True) # Set std deviations that are 0 to 1 to avoid division by 0. std[isconst] = 1.0 z = (scores - mn) / std # Set the outputs associated with a constant input to nan. z[np.broadcast_to(isconst, z.shape)] = np.nan return z def gstd(a, axis=0, ddof=1): """ Calculate the geometric standard deviation of an array. The geometric standard deviation describes the spread of a set of numbers where the geometric mean is preferred. It is a multiplicative factor, and so a dimensionless quantity. It is defined as the exponent of the standard deviation of ``log(a)``. Mathematically the population geometric standard deviation can be evaluated as:: gstd = exp(std(log(a))) .. versionadded:: 1.3.0 Parameters ---------- a : array_like An array like object containing the sample data. axis : int, tuple or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Degree of freedom correction in the calculation of the geometric standard deviation. Default is 1. Returns ------- gstd : ndarray or float An array of the geometric standard deviation. If `axis` is None or `a` is a 1d array a float is returned. See Also -------- gmean : Geometric mean numpy.std : Standard deviation gzscore : Geometric standard score Notes ----- As the calculation requires the use of logarithms the geometric standard deviation only supports strictly positive values. Any non-positive or infinite values will raise a `ValueError`. The geometric standard deviation is sometimes confused with the exponent of the standard deviation, ``exp(std(a))``. Instead the geometric standard deviation is ``exp(std(log(a)))``. The default value for `ddof` is different to the default value (0) used by other ddof containing functions, such as ``np.std`` and ``np.nanstd``. References ---------- .. [1] "Geometric standard deviation", *Wikipedia*, https://en.wikipedia.org/wiki/Geometric_standard_deviation. .. [2] Kirkwood, T. B., "Geometric means and measures of dispersion", Biometrics, vol. 35, pp. 908-909, 1979 Examples -------- Find the geometric standard deviation of a log-normally distributed sample. Note that the standard deviation of the distribution is one, on a log scale this evaluates to approximately ``exp(1)``. >>> import numpy as np >>> from scipy.stats import gstd >>> rng = np.random.default_rng() >>> sample = rng.lognormal(mean=0, sigma=1, size=1000) >>> gstd(sample) 2.810010162475324 Compute the geometric standard deviation of a multidimensional array and of a given axis. >>> a = np.arange(1, 25).reshape(2, 3, 4) >>> gstd(a, axis=None) 2.2944076136018947 >>> gstd(a, axis=2) array([[1.82424757, 1.22436866, 1.13183117], [1.09348306, 1.07244798, 1.05914985]]) >>> gstd(a, axis=(1,2)) array([2.12939215, 1.22120169]) The geometric standard deviation further handles masked arrays. >>> a = np.arange(1, 25).reshape(2, 3, 4) >>> ma = np.ma.masked_where(a > 16, a) >>> ma masked_array( data=[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [--, --, --, --], [--, --, --, --]]], mask=[[[False, False, False, False], [False, False, False, False], [False, False, False, False]], [[False, False, False, False], [ True, True, True, True], [ True, True, True, True]]], fill_value=999999) >>> gstd(ma, axis=2) masked_array( data=[[1.8242475707663655, 1.2243686572447428, 1.1318311657788478], [1.0934830582350938, --, --]], mask=[[False, False, False], [False, True, True]], fill_value=999999) """ a = np.asanyarray(a) log = ma.log if isinstance(a, ma.MaskedArray) else np.log try: with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) return np.exp(np.std(log(a), axis=axis, ddof=ddof)) except RuntimeWarning as w: if np.isinf(a).any(): raise ValueError( 'Infinite value encountered. The geometric standard deviation ' 'is defined for strictly positive values only.' ) from w a_nan = np.isnan(a) a_nan_any = a_nan.any() # exclude NaN's from negativity check, but # avoid expensive masking for arrays with no NaN if ((a_nan_any and np.less_equal(np.nanmin(a), 0)) or (not a_nan_any and np.less_equal(a, 0).any())): raise ValueError( 'Non positive value encountered. The geometric standard ' 'deviation is defined for strictly positive values only.' ) from w elif 'Degrees of freedom <= 0 for slice' == str(w): raise ValueError(w) from w else: # Remaining warnings don't need to be exceptions. return np.exp(np.std(log(a, where=~a_nan), axis=axis, ddof=ddof)) except TypeError as e: raise ValueError( 'Invalid array input. The inputs could not be ' 'safely coerced to any supported types') from e # Private dictionary initialized only once at module level # See https://en.wikipedia.org/wiki/Robust_measures_of_scale _scale_conversions = {'raw': 1.0, 'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)} @_axis_nan_policy_factory( lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None, override={'nan_propagation': False} ) def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate', interpolation='linear', keepdims=False): r""" Compute the interquartile range of the data along the specified axis. The interquartile range (IQR) is the difference between the 75th and 25th percentile of the data. It is a measure of the dispersion similar to standard deviation or variance, but is much more robust against outliers [2]_. The ``rng`` parameter allows this function to compute other percentile ranges than the actual IQR. For example, setting ``rng=(0, 100)`` is equivalent to `numpy.ptp`. The IQR of an empty array is `np.nan`. .. versionadded:: 0.18.0 Parameters ---------- x : array_like Input array or object that can be converted to an array. axis : int or sequence of int, optional Axis along which the range is computed. The default is to compute the IQR for the entire array. rng : Two-element sequence containing floats in range of [0,100] optional Percentiles over which to compute the range. Each must be between 0 and 100, inclusive. The default is the true IQR: ``(25, 75)``. The order of the elements is not important. scale : scalar or str, optional The numerical value of scale will be divided out of the final result. The following string values are recognized: * 'raw' : No scaling, just return the raw IQR. **Deprecated!** Use ``scale=1`` instead. * 'normal' : Scale by :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`. The default is 1.0. The use of ``scale='raw'`` is deprecated infavor of ``scale=1`` and will raise an error in SciPy 1.12.0. Array-like `scale` is also allowed, as long as it broadcasts correctly to the output such that ``out / scale`` is a valid operation. The output dimensions depend on the input array, `x`, the `axis` argument, and the `keepdims` flag. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values interpolation : str, optional Specifies the interpolation method to use when the percentile boundaries lie between two data points ``i`` and ``j``. The following options are available (default is 'linear'): * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j``. * 'lower': ``i``. * 'higher': ``j``. * 'nearest': ``i`` or ``j`` whichever is nearest. * 'midpoint': ``(i + j)/2``. For NumPy >= 1.22.0, the additional options provided by the ``method`` keyword of `numpy.percentile` are also valid. keepdims : bool, optional If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array `x`. Returns ------- iqr : scalar or ndarray If ``axis=None``, a scalar is returned. If the input contains integers or floats of smaller precision than ``np.float64``, then the output data-type is ``np.float64``. Otherwise, the output data-type is the same as that of the input. See Also -------- numpy.std, numpy.var References ---------- .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile Examples -------- >>> import numpy as np >>> from scipy.stats import iqr >>> x = np.array([[10, 7, 4], [3, 2, 1]]) >>> x array([[10, 7, 4], [ 3, 2, 1]]) >>> iqr(x) 4.0 >>> iqr(x, axis=0) array([ 3.5, 2.5, 1.5]) >>> iqr(x, axis=1) array([ 3., 1.]) >>> iqr(x, axis=1, keepdims=True) array([[ 3.], [ 1.]]) """ x = asarray(x) # This check prevents percentile from raising an error later. Also, it is # consistent with `np.var` and `np.std`. if not x.size: return _get_nan(x) # An error may be raised here, so fail-fast, before doing lengthy # computations, even though `scale` is not used until later if isinstance(scale, str): scale_key = scale.lower() if scale_key not in _scale_conversions: raise ValueError(f"{scale} not a valid scale for `iqr`") if scale_key == 'raw': msg = ("The use of 'scale=\"raw\"' is deprecated infavor of " "'scale=1' and will raise an error in SciPy 1.12.0.") warnings.warn(msg, DeprecationWarning, stacklevel=2) scale = _scale_conversions[scale_key] # Select the percentile function to use based on nans and policy contains_nan, nan_policy = _contains_nan(x, nan_policy) if contains_nan and nan_policy == 'omit': percentile_func = np.nanpercentile else: percentile_func = np.percentile if len(rng) != 2: raise TypeError("quantile range must be two element sequence") if np.isnan(rng).any(): raise ValueError("range must not contain NaNs") rng = sorted(rng) if NumpyVersion(np.__version__) >= '1.22.0': pct = percentile_func(x, rng, axis=axis, method=interpolation, keepdims=keepdims) else: pct = percentile_func(x, rng, axis=axis, interpolation=interpolation, keepdims=keepdims) out = np.subtract(pct[1], pct[0]) if scale != 1.0: out /= scale return out def _mad_1d(x, center, nan_policy): # Median absolute deviation for 1-d array x. # This is a helper function for `median_abs_deviation`; it assumes its # arguments have been validated already. In particular, x must be a # 1-d numpy array, center must be callable, and if nan_policy is not # 'propagate', it is assumed to be 'omit', because 'raise' is handled # in `median_abs_deviation`. # No warning is generated if x is empty or all nan. isnan = np.isnan(x) if isnan.any(): if nan_policy == 'propagate': return np.nan x = x[~isnan] if x.size == 0: # MAD of an empty array is nan. return np.nan # Edge cases have been handled, so do the basic MAD calculation. med = center(x) mad = np.median(np.abs(x - med)) return mad def median_abs_deviation(x, axis=0, center=np.median, scale=1.0, nan_policy='propagate'): r""" Compute the median absolute deviation of the data along the given axis. The median absolute deviation (MAD, [1]_) computes the median over the absolute deviations from the median. It is a measure of dispersion similar to the standard deviation but more robust to outliers [2]_. The MAD of an empty array is ``np.nan``. .. versionadded:: 1.5.0 Parameters ---------- x : array_like Input array or object that can be converted to an array. axis : int or None, optional Axis along which the range is computed. Default is 0. If None, compute the MAD over the entire array. center : callable, optional A function that will return the central value. The default is to use np.median. Any user defined function used will need to have the function signature ``func(arr, axis)``. scale : scalar or str, optional The numerical value of scale will be divided out of the final result. The default is 1.0. The string "normal" is also accepted, and results in `scale` being the inverse of the standard normal quantile function at 0.75, which is approximately 0.67449. Array-like scale is also allowed, as long as it broadcasts correctly to the output such that ``out / scale`` is a valid operation. The output dimensions depend on the input array, `x`, and the `axis` argument. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- mad : scalar or ndarray If ``axis=None``, a scalar is returned. If the input contains integers or floats of smaller precision than ``np.float64``, then the output data-type is ``np.float64``. Otherwise, the output data-type is the same as that of the input. See Also -------- numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean, scipy.stats.tstd, scipy.stats.tvar Notes ----- The `center` argument only affects the calculation of the central value around which the MAD is calculated. That is, passing in ``center=np.mean`` will calculate the MAD around the mean - it will not calculate the *mean* absolute deviation. The input array may contain `inf`, but if `center` returns `inf`, the corresponding MAD for that data will be `nan`. References ---------- .. [1] "Median absolute deviation", https://en.wikipedia.org/wiki/Median_absolute_deviation .. [2] "Robust measures of scale", https://en.wikipedia.org/wiki/Robust_measures_of_scale Examples -------- When comparing the behavior of `median_abs_deviation` with ``np.std``, the latter is affected when we change a single value of an array to have an outlier value while the MAD hardly changes: >>> import numpy as np >>> from scipy import stats >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456) >>> x.std() 0.9973906394005013 >>> stats.median_abs_deviation(x) 0.82832610097857 >>> x[0] = 345.6 >>> x.std() 34.42304872314415 >>> stats.median_abs_deviation(x) 0.8323442311590675 Axis handling example: >>> x = np.array([[10, 7, 4], [3, 2, 1]]) >>> x array([[10, 7, 4], [ 3, 2, 1]]) >>> stats.median_abs_deviation(x) array([3.5, 2.5, 1.5]) >>> stats.median_abs_deviation(x, axis=None) 2.0 Scale normal example: >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456) >>> stats.median_abs_deviation(x) 1.3487398527041636 >>> stats.median_abs_deviation(x, scale='normal') 1.9996446978061115 """ if not callable(center): raise TypeError("The argument 'center' must be callable. The given " f"value {repr(center)} is not callable.") # An error may be raised here, so fail-fast, before doing lengthy # computations, even though `scale` is not used until later if isinstance(scale, str): if scale.lower() == 'normal': scale = 0.6744897501960817 # special.ndtri(0.75) else: raise ValueError(f"{scale} is not a valid scale value.") x = asarray(x) # Consistent with `np.var` and `np.std`. if not x.size: if axis is None: return np.nan nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis) if nan_shape == (): # Return nan, not array(nan) return np.nan return np.full(nan_shape, np.nan) contains_nan, nan_policy = _contains_nan(x, nan_policy) if contains_nan: if axis is None: mad = _mad_1d(x.ravel(), center, nan_policy) else: mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy) else: if axis is None: med = center(x, axis=None) mad = np.median(np.abs(x - med)) else: # Wrap the call to center() in expand_dims() so it acts like # keepdims=True was used. med = np.expand_dims(center(x, axis=axis), axis) mad = np.median(np.abs(x - med), axis=axis) return mad / scale ##################################### # TRIMMING FUNCTIONS # ##################################### SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper')) def sigmaclip(a, low=4., high=4.): """Perform iterative sigma-clipping of array elements. Starting from the full sample, all elements outside the critical range are removed, i.e. all elements of the input array `c` that satisfy either of the following conditions:: c < mean(c) - std(c)*low c > mean(c) + std(c)*high The iteration continues with the updated sample until no elements are outside the (updated) range. Parameters ---------- a : array_like Data array, will be raveled if not 1-D. low : float, optional Lower bound factor of sigma clipping. Default is 4. high : float, optional Upper bound factor of sigma clipping. Default is 4. Returns ------- clipped : ndarray Input array with clipped elements removed. lower : float Lower threshold value use for clipping. upper : float Upper threshold value use for clipping. Examples -------- >>> import numpy as np >>> from scipy.stats import sigmaclip >>> a = np.concatenate((np.linspace(9.5, 10.5, 31), ... np.linspace(0, 20, 5))) >>> fact = 1.5 >>> c, low, upp = sigmaclip(a, fact, fact) >>> c array([ 9.96666667, 10. , 10.03333333, 10. ]) >>> c.var(), c.std() (0.00055555555555555165, 0.023570226039551501) >>> low, c.mean() - fact*c.std(), c.min() (9.9646446609406727, 9.9646446609406727, 9.9666666666666668) >>> upp, c.mean() + fact*c.std(), c.max() (10.035355339059327, 10.035355339059327, 10.033333333333333) >>> a = np.concatenate((np.linspace(9.5, 10.5, 11), ... np.linspace(-100, -50, 3))) >>> c, low, upp = sigmaclip(a, 1.8, 1.8) >>> (c == np.linspace(9.5, 10.5, 11)).all() True """ c = np.asarray(a).ravel() delta = 1 while delta: c_std = c.std() c_mean = c.mean() size = c.size critlower = c_mean - c_std * low critupper = c_mean + c_std * high c = c[(c >= critlower) & (c <= critupper)] delta = size - c.size return SigmaclipResult(c, critlower, critupper) def trimboth(a, proportiontocut, axis=0): """Slice off a proportion of items from both ends of an array. Slice off the passed proportion of items from both ends of the passed array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and** rightmost 10% of scores). The trimmed values are the lowest and highest ones. Slice off less if proportion results in a non-integer slice index (i.e. conservatively slices off `proportiontocut`). Parameters ---------- a : array_like Data to trim. proportiontocut : float Proportion (in range 0-1) of total data set to trim of each end. axis : int or None, optional Axis along which to trim data. Default is 0. If None, compute over the whole array `a`. Returns ------- out : ndarray Trimmed version of array `a`. The order of the trimmed content is undefined. See Also -------- trim_mean Examples -------- Create an array of 10 values and trim 10% of those values from each end: >>> import numpy as np >>> from scipy import stats >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> stats.trimboth(a, 0.1) array([1, 3, 2, 4, 5, 6, 7, 8]) Note that the elements of the input array are trimmed by value, but the output array is not necessarily sorted. The proportion to trim is rounded down to the nearest integer. For instance, trimming 25% of the values from each end of an array of 10 values will return an array of 6 values: >>> b = np.arange(10) >>> stats.trimboth(b, 1/4).shape (6,) Multidimensional arrays can be trimmed along any axis or across the entire array: >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] >>> d = np.array([a, b, c]) >>> stats.trimboth(d, 0.4, axis=0).shape (1, 10) >>> stats.trimboth(d, 0.4, axis=1).shape (3, 2) >>> stats.trimboth(d, 0.4, axis=None).shape (6,) """ a = np.asarray(a) if a.size == 0: return a if axis is None: a = a.ravel() axis = 0 nobs = a.shape[axis] lowercut = int(proportiontocut * nobs) uppercut = nobs - lowercut if (lowercut >= uppercut): raise ValueError("Proportion too big.") atmp = np.partition(a, (lowercut, uppercut - 1), axis) sl = [slice(None)] * atmp.ndim sl[axis] = slice(lowercut, uppercut) return atmp[tuple(sl)] def trim1(a, proportiontocut, tail='right', axis=0): """Slice off a proportion from ONE end of the passed array distribution. If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost' 10% of scores. The lowest or highest values are trimmed (depending on the tail). Slice off less if proportion results in a non-integer slice index (i.e. conservatively slices off `proportiontocut` ). Parameters ---------- a : array_like Input array. proportiontocut : float Fraction to cut off of 'left' or 'right' of distribution. tail : {'left', 'right'}, optional Defaults to 'right'. axis : int or None, optional Axis along which to trim data. Default is 0. If None, compute over the whole array `a`. Returns ------- trim1 : ndarray Trimmed version of array `a`. The order of the trimmed content is undefined. Examples -------- Create an array of 10 values and trim 20% of its lowest values: >>> import numpy as np >>> from scipy import stats >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> stats.trim1(a, 0.2, 'left') array([2, 4, 3, 5, 6, 7, 8, 9]) Note that the elements of the input array are trimmed by value, but the output array is not necessarily sorted. The proportion to trim is rounded down to the nearest integer. For instance, trimming 25% of the values from an array of 10 values will return an array of 8 values: >>> b = np.arange(10) >>> stats.trim1(b, 1/4).shape (8,) Multidimensional arrays can be trimmed along any axis or across the entire array: >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] >>> d = np.array([a, b, c]) >>> stats.trim1(d, 0.8, axis=0).shape (1, 10) >>> stats.trim1(d, 0.8, axis=1).shape (3, 2) >>> stats.trim1(d, 0.8, axis=None).shape (6,) """ a = np.asarray(a) if axis is None: a = a.ravel() axis = 0 nobs = a.shape[axis] # avoid possible corner case if proportiontocut >= 1: return [] if tail.lower() == 'right': lowercut = 0 uppercut = nobs - int(proportiontocut * nobs) elif tail.lower() == 'left': lowercut = int(proportiontocut * nobs) uppercut = nobs atmp = np.partition(a, (lowercut, uppercut - 1), axis) sl = [slice(None)] * atmp.ndim sl[axis] = slice(lowercut, uppercut) return atmp[tuple(sl)] def trim_mean(a, proportiontocut, axis=0): """Return mean of array after trimming distribution from both tails. If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of scores. The input is sorted before slicing. Slices off less if proportion results in a non-integer slice index (i.e., conservatively slices off `proportiontocut` ). Parameters ---------- a : array_like Input array. proportiontocut : float Fraction to cut off of both tails of the distribution. axis : int or None, optional Axis along which the trimmed means are computed. Default is 0. If None, compute over the whole array `a`. Returns ------- trim_mean : ndarray Mean of trimmed array. See Also -------- trimboth tmean : Compute the trimmed mean ignoring values outside given `limits`. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = np.arange(20) >>> stats.trim_mean(x, 0.1) 9.5 >>> x2 = x.reshape(5, 4) >>> x2 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) >>> stats.trim_mean(x2, 0.25) array([ 8., 9., 10., 11.]) >>> stats.trim_mean(x2, 0.25, axis=1) array([ 1.5, 5.5, 9.5, 13.5, 17.5]) """ a = np.asarray(a) if a.size == 0: return np.nan if axis is None: a = a.ravel() axis = 0 nobs = a.shape[axis] lowercut = int(proportiontocut * nobs) uppercut = nobs - lowercut if (lowercut > uppercut): raise ValueError("Proportion too big.") atmp = np.partition(a, (lowercut, uppercut - 1), axis) sl = [slice(None)] * atmp.ndim sl[axis] = slice(lowercut, uppercut) return np.mean(atmp[tuple(sl)], axis=axis) F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue')) def _create_f_oneway_nan_result(shape, axis): """ This is a helper function for f_oneway for creating the return values in certain degenerate conditions. It creates return values that are all nan with the appropriate shape for the given `shape` and `axis`. """ axis = np.core.multiarray.normalize_axis_index(axis, len(shape)) shp = shape[:axis] + shape[axis+1:] if shp == (): f = np.nan prob = np.nan else: f = np.full(shp, fill_value=np.nan) prob = f.copy() return F_onewayResult(f, prob) def _first(arr, axis): """Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.""" return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis) def f_oneway(*samples, axis=0): """Perform one-way ANOVA. The one-way ANOVA tests the null hypothesis that two or more groups have the same population mean. The test is applied to samples from two or more groups, possibly with differing sizes. Parameters ---------- sample1, sample2, ... : array_like The sample measurements for each group. There must be at least two arguments. If the arrays are multidimensional, then all the dimensions of the array must be the same except for `axis`. axis : int, optional Axis of the input arrays along which the test is applied. Default is 0. Returns ------- statistic : float The computed F statistic of the test. pvalue : float The associated p-value from the F distribution. Warns ----- `~scipy.stats.ConstantInputWarning` Raised if all values within each of the input arrays are identical. In this case the F statistic is either infinite or isn't defined, so ``np.inf`` or ``np.nan`` is returned. `~scipy.stats.DegenerateDataWarning` Raised if the length of any input array is 0, or if all the input arrays have length 1. ``np.nan`` is returned for the F statistic and the p-value in these cases. Notes ----- The ANOVA test has important assumptions that must be satisfied in order for the associated p-value to be valid. 1. The samples are independent. 2. Each sample is from a normally distributed population. 3. The population standard deviations of the groups are all equal. This property is known as homoscedasticity. If these assumptions are not true for a given set of data, it may still be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or the Alexander-Govern test (`scipy.stats.alexandergovern`) although with some loss of power. The length of each group must be at least one, and there must be at least one group with length greater than one. If these conditions are not satisfied, a warning is generated and (``np.nan``, ``np.nan``) is returned. If all values in each group are identical, and there exist at least two groups with different values, the function generates a warning and returns (``np.inf``, 0). If all values in all groups are the same, function generates a warning and returns (``np.nan``, ``np.nan``). The algorithm is from Heiman [2]_, pp.394-7. References ---------- .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics", Chapter 14, 2014, http://vassarstats.net/textbook/ .. [2] G.W. Heiman, "Understanding research methods and statistics: An integrated introduction for psychology", Houghton, Mifflin and Company, 2001. .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA. http://www.biostathandbook.com/onewayanova.html Examples -------- >>> import numpy as np >>> from scipy.stats import f_oneway Here are some data [3]_ on a shell measurement (the length of the anterior adductor muscle scar, standardized by dividing by length) in the mussel Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon; Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a much larger data set used in McDonald et al. (1991). >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735, ... 0.0659, 0.0923, 0.0836] >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835, ... 0.0725] >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105] >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764, ... 0.0689] >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045] >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne) F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544) `f_oneway` accepts multidimensional input arrays. When the inputs are multidimensional and `axis` is not given, the test is performed along the first axis of the input arrays. For the following data, the test is performed three times, once for each column. >>> a = np.array([[9.87, 9.03, 6.81], ... [7.18, 8.35, 7.00], ... [8.39, 7.58, 7.68], ... [7.45, 6.33, 9.35], ... [6.41, 7.10, 9.33], ... [8.00, 8.24, 8.44]]) >>> b = np.array([[6.35, 7.30, 7.16], ... [6.65, 6.68, 7.63], ... [5.72, 7.73, 6.72], ... [7.01, 9.19, 7.41], ... [7.75, 7.87, 8.30], ... [6.90, 7.97, 6.97]]) >>> c = np.array([[3.31, 8.77, 1.01], ... [8.25, 3.24, 3.62], ... [6.32, 8.81, 5.19], ... [7.48, 8.83, 8.91], ... [8.59, 6.01, 6.07], ... [3.07, 9.72, 7.48]]) >>> F, p = f_oneway(a, b, c) >>> F array([1.75676344, 0.03701228, 3.76439349]) >>> p array([0.20630784, 0.96375203, 0.04733157]) """ if len(samples) < 2: raise TypeError('at least two inputs are required;' f' got {len(samples)}.') samples = [np.asarray(sample, dtype=float) for sample in samples] # ANOVA on N groups, each in its own array num_groups = len(samples) # We haven't explicitly validated axis, but if it is bad, this call of # np.concatenate will raise np.AxisError. The call will raise ValueError # if the dimensions of all the arrays, except the axis dimension, are not # the same. alldata = np.concatenate(samples, axis=axis) bign = alldata.shape[axis] # Check this after forming alldata, so shape errors are detected # and reported before checking for 0 length inputs. if any(sample.shape[axis] == 0 for sample in samples): warnings.warn(stats.DegenerateDataWarning('at least one input ' 'has length 0')) return _create_f_oneway_nan_result(alldata.shape, axis) # Must have at least one group with length greater than 1. if all(sample.shape[axis] == 1 for sample in samples): msg = ('all input arrays have length 1. f_oneway requires that at ' 'least one input has length greater than 1.') warnings.warn(stats.DegenerateDataWarning(msg)) return _create_f_oneway_nan_result(alldata.shape, axis) # Check if all values within each group are identical, and if the common # value in at least one group is different from that in another group. # Based on https://github.com/scipy/scipy/issues/11669 # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ..., # then is_const is a boolean array with shape (num_groups, ...). # It is True if the values within the groups along the axis slice are # identical. In the typical case where each input array is 1-d, is_const is # a 1-d array with length num_groups. is_const = np.concatenate( [(_first(sample, axis) == sample).all(axis=axis, keepdims=True) for sample in samples], axis=axis ) # all_const is a boolean array with shape (...) (see previous comment). # It is True if the values within each group along the axis slice are # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]). all_const = is_const.all(axis=axis) if all_const.any(): msg = ("Each of the input arrays is constant;" "the F statistic is not defined or infinite") warnings.warn(stats.ConstantInputWarning(msg)) # all_same_const is True if all the values in the groups along the axis=0 # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]). all_same_const = (_first(alldata, axis) == alldata).all(axis=axis) # Determine the mean of the data, and subtract that from all inputs to a # variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant # to a shift in location, and centering all data around zero vastly # improves numerical stability. offset = alldata.mean(axis=axis, keepdims=True) alldata -= offset normalized_ss = _square_of_sums(alldata, axis=axis) / bign sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss ssbn = 0 for sample in samples: ssbn += _square_of_sums(sample - offset, axis=axis) / sample.shape[axis] # Naming: variables ending in bn/b are for "between treatments", wn/w are # for "within treatments" ssbn -= normalized_ss sswn = sstot - ssbn dfbn = num_groups - 1 dfwn = bign - num_groups msb = ssbn / dfbn msw = sswn / dfwn with np.errstate(divide='ignore', invalid='ignore'): f = msb / msw prob = special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf # Fix any f values that should be inf or nan because the corresponding # inputs were constant. if np.isscalar(f): if all_same_const: f = np.nan prob = np.nan elif all_const: f = np.inf prob = 0.0 else: f[all_const] = np.inf prob[all_const] = 0.0 f[all_same_const] = np.nan prob[all_same_const] = np.nan return F_onewayResult(f, prob) def alexandergovern(*samples, nan_policy='propagate'): """Performs the Alexander Govern test. The Alexander-Govern approximation tests the equality of k independent means in the face of heterogeneity of variance. The test is applied to samples from two or more groups, possibly with differing sizes. Parameters ---------- sample1, sample2, ... : array_like The sample measurements for each group. There must be at least two samples. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- res : AlexanderGovernResult An object with attributes: statistic : float The computed A statistic of the test. pvalue : float The associated p-value from the chi-squared distribution. Warns ----- `~scipy.stats.ConstantInputWarning` Raised if an input is a constant array. The statistic is not defined in this case, so ``np.nan`` is returned. See Also -------- f_oneway : one-way ANOVA Notes ----- The use of this test relies on several assumptions. 1. The samples are independent. 2. Each sample is from a normally distributed population. 3. Unlike `f_oneway`, this test does not assume on homoscedasticity, instead relaxing the assumption of equal variances. Input samples must be finite, one dimensional, and with size greater than one. References ---------- .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler Approximation for ANOVA under Variance Heterogeneity." Journal of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101. JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020. Examples -------- >>> from scipy.stats import alexandergovern Here are some data on annual percentage rate of interest charged on new car loans at nine of the largest banks in four American cities taken from the National Institute of Standards and Technology's ANOVA dataset. We use `alexandergovern` to test the null hypothesis that all cities have the same mean APR against the alternative that the cities do not all have the same mean APR. We decide that a significance level of 5% is required to reject the null hypothesis in favor of the alternative. >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5] >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9] >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5] >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25, ... 11.89] >>> alexandergovern(atlanta, chicago, houston, memphis) AlexanderGovernResult(statistic=4.65087071883494, pvalue=0.19922132490385214) The p-value is 0.1992, indicating a nearly 20% chance of observing such an extreme value of the test statistic under the null hypothesis. This exceeds 5%, so we do not reject the null hypothesis in favor of the alternative. """ samples = _alexandergovern_input_validation(samples, nan_policy) if np.any([(sample == sample[0]).all() for sample in samples]): msg = "An input array is constant; the statistic is not defined." warnings.warn(stats.ConstantInputWarning(msg)) return AlexanderGovernResult(np.nan, np.nan) # The following formula numbers reference the equation described on # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other # tests that serve as the basis for equation (8) but are not needed # to perform the test. # precalculate mean and length of each sample lengths = np.array([ma.count(sample) if nan_policy == 'omit' else len(sample) for sample in samples]) means = np.array([np.mean(sample) for sample in samples]) # (1) determine standard error of the mean for each sample standard_errors = [np.std(sample, ddof=1) / np.sqrt(length) for sample, length in zip(samples, lengths)] # (2) define a weight for each sample inv_sq_se = 1 / np.square(standard_errors) weights = inv_sq_se / np.sum(inv_sq_se) # (3) determine variance-weighted estimate of the common mean var_w = np.sum(weights * means) # (4) determine one-sample t statistic for each group t_stats = (means - var_w)/standard_errors # calculate parameters to be used in transformation v = lengths - 1 a = v - .5 b = 48 * a**2 c = (a * np.log(1 + (t_stats ** 2)/v))**.5 # (8) perform a normalizing transformation on t statistic z = (c + ((c**3 + 3*c)/b) - ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) / (b**2*10 + 8*b*c**4 + 1000*b))) # (9) calculate statistic A = np.sum(np.square(z)) # "[the p value is determined from] central chi-square random deviates # with k - 1 degrees of freedom". Alexander, Govern (94) p = distributions.chi2.sf(A, len(samples) - 1) return AlexanderGovernResult(A, p) def _alexandergovern_input_validation(samples, nan_policy): if len(samples) < 2: raise TypeError(f"2 or more inputs required, got {len(samples)}") # input arrays are flattened samples = [np.asarray(sample, dtype=float) for sample in samples] for i, sample in enumerate(samples): if np.size(sample) <= 1: raise ValueError("Input sample size must be greater than one.") if sample.ndim != 1: raise ValueError("Input samples must be one-dimensional") if np.isinf(sample).any(): raise ValueError("Input samples must be finite.") contains_nan, nan_policy = _contains_nan(sample, nan_policy=nan_policy) if contains_nan and nan_policy == 'omit': samples[i] = ma.masked_invalid(sample) return samples @dataclass class AlexanderGovernResult: statistic: float pvalue: float def _pearsonr_fisher_ci(r, n, confidence_level, alternative): """ Compute the confidence interval for Pearson's R. Fisher's transformation is used to compute the confidence interval (https://en.wikipedia.org/wiki/Fisher_transformation). """ if r == 1: zr = np.inf elif r == -1: zr = -np.inf else: zr = np.arctanh(r) if n > 3: se = np.sqrt(1 / (n - 3)) if alternative == "two-sided": h = special.ndtri(0.5 + confidence_level/2) zlo = zr - h*se zhi = zr + h*se rlo = np.tanh(zlo) rhi = np.tanh(zhi) elif alternative == "less": h = special.ndtri(confidence_level) zhi = zr + h*se rhi = np.tanh(zhi) rlo = -1.0 else: # alternative == "greater": h = special.ndtri(confidence_level) zlo = zr - h*se rlo = np.tanh(zlo) rhi = 1.0 else: rlo, rhi = -1.0, 1.0 return ConfidenceInterval(low=rlo, high=rhi) def _pearsonr_bootstrap_ci(confidence_level, method, x, y, alternative): """ Compute the confidence interval for Pearson's R using the bootstrap. """ def statistic(x, y): statistic, _ = pearsonr(x, y) return statistic res = bootstrap((x, y), statistic, confidence_level=confidence_level, paired=True, alternative=alternative, **method._asdict()) # for one-sided confidence intervals, bootstrap gives +/- inf on one side res.confidence_interval = np.clip(res.confidence_interval, -1, 1) return ConfidenceInterval(*res.confidence_interval) ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high']) PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase', ['statistic', 'pvalue'], []) class PearsonRResult(PearsonRResultBase): """ Result of `scipy.stats.pearsonr` Attributes ---------- statistic : float Pearson product-moment correlation coefficient. pvalue : float The p-value associated with the chosen alternative. Methods ------- confidence_interval Computes the confidence interval of the correlation coefficient `statistic` for the given confidence level. """ def __init__(self, statistic, pvalue, alternative, n, x, y): super().__init__(statistic, pvalue) self._alternative = alternative self._n = n self._x = x self._y = y # add alias for consistency with other correlation functions self.correlation = statistic def confidence_interval(self, confidence_level=0.95, method=None): """ The confidence interval for the correlation coefficient. Compute the confidence interval for the correlation coefficient ``statistic`` with the given confidence level. If `method` is not provided, The confidence interval is computed using the Fisher transformation F(r) = arctanh(r) [1]_. When the sample pairs are drawn from a bivariate normal distribution, F(r) approximately follows a normal distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the length of the original samples along the calculation axis. When ``n <= 3``, this approximation does not yield a finite, real standard error, so we define the confidence interval to be -1 to 1. If `method` is an instance of `BootstrapMethod`, the confidence interval is computed using `scipy.stats.bootstrap` with the provided configuration options and other appropriate settings. In some cases, confidence limits may be NaN due to a degenerate resample, and this is typical for very small samples (~6 observations). Parameters ---------- confidence_level : float The confidence level for the calculation of the correlation coefficient confidence interval. Default is 0.95. method : BootstrapMethod, optional Defines the method used to compute the confidence interval. See method description for details. .. versionadded:: 1.11.0 Returns ------- ci : namedtuple The confidence interval is returned in a ``namedtuple`` with fields `low` and `high`. References ---------- .. [1] "Pearson correlation coefficient", Wikipedia, https://en.wikipedia.org/wiki/Pearson_correlation_coefficient """ if isinstance(method, BootstrapMethod): ci = _pearsonr_bootstrap_ci(confidence_level, method, self._x, self._y, self._alternative) elif method is None: ci = _pearsonr_fisher_ci(self.statistic, self._n, confidence_level, self._alternative) else: message = ('`method` must be an instance of `BootstrapMethod` ' 'or None.') raise ValueError(message) return ci def pearsonr(x, y, *, alternative='two-sided', method=None): r""" Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient [1]_ measures the linear relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. This function also performs a test of the null hypothesis that the distributions underlying the samples are uncorrelated and normally distributed. (See Kowalski [3]_ for a discussion of the effects of non-normality of the input on the distribution of the correlation coefficient.) The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Parameters ---------- x : (N,) array_like Input array. y : (N,) array_like Input array. alternative : {'two-sided', 'greater', 'less'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the correlation is nonzero * 'less': the correlation is negative (less than zero) * 'greater': the correlation is positive (greater than zero) .. versionadded:: 1.9.0 method : ResamplingMethod, optional Defines the method used to compute the p-value. If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is computed using `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the provided configuration options and other appropriate settings. Otherwise, the p-value is computed as documented in the notes. .. versionadded:: 1.11.0 Returns ------- result : `~scipy.stats._result_classes.PearsonRResult` An object with the following attributes: statistic : float Pearson product-moment correlation coefficient. pvalue : float The p-value associated with the chosen alternative. The object has the following method: confidence_interval(confidence_level, method) This computes the confidence interval of the correlation coefficient `statistic` for the given confidence level. The confidence interval is returned in a ``namedtuple`` with fields `low` and `high`. If `method` is not provided, the confidence interval is computed using the Fisher transformation [1]_. If `method` is an instance of `BootstrapMethod`, the confidence interval is computed using `scipy.stats.bootstrap` with the provided configuration options and other appropriate settings. In some cases, confidence limits may be NaN due to a degenerate resample, and this is typical for very small samples (~6 observations). Warns ----- `~scipy.stats.ConstantInputWarning` Raised if an input is a constant array. The correlation coefficient is not defined in this case, so ``np.nan`` is returned. `~scipy.stats.NearConstantInputWarning` Raised if an input is "nearly" constant. The array ``x`` is considered nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``. Numerical errors in the calculation ``x - mean(x)`` in this case might result in an inaccurate calculation of r. See Also -------- spearmanr : Spearman rank-order correlation coefficient. kendalltau : Kendall's tau, a correlation measure for ordinal data. Notes ----- The correlation coefficient is calculated as follows: .. math:: r = \frac{\sum (x - m_x) (y - m_y)} {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}} where :math:`m_x` is the mean of the vector x and :math:`m_y` is the mean of the vector y. Under the assumption that x and y are drawn from independent normal distributions (so the population correlation coefficient is 0), the probability density function of the sample correlation coefficient r is ([1]_, [2]_): .. math:: f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)} where n is the number of samples, and B is the beta function. This is sometimes referred to as the exact distribution of r. This is the distribution that is used in `pearsonr` to compute the p-value when the `method` parameter is left at its default value (None). The distribution is a beta distribution on the interval [-1, 1], with equal shape parameters a = b = n/2 - 1. In terms of SciPy's implementation of the beta distribution, the distribution of r is:: dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2) The default p-value returned by `pearsonr` is a two-sided p-value. For a given sample with correlation coefficient r, the p-value is the probability that abs(r') of a random sample x' and y' drawn from the population with zero correlation would be greater than or equal to abs(r). In terms of the object ``dist`` shown above, the p-value for a given r and length n can be computed as:: p = 2*dist.cdf(-abs(r)) When n is 2, the above continuous distribution is not well-defined. One can interpret the limit of the beta distribution as the shape parameters a and b approach a = b = 0 as a discrete distribution with equal probability masses at r = 1 and r = -1. More directly, one can observe that, given the data x = [x1, x2] and y = [y1, y2], and assuming x1 != x2 and y1 != y2, the only possible values for r are 1 and -1. Because abs(r') for any sample x' and y' with length 2 will be 1, the two-sided p-value for a sample of length 2 is always 1. For backwards compatibility, the object that is returned also behaves like a tuple of length two that holds the statistic and the p-value. References ---------- .. [1] "Pearson correlation coefficient", Wikipedia, https://en.wikipedia.org/wiki/Pearson_correlation_coefficient .. [2] Student, "Probable error of a correlation coefficient", Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310. .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution of the Sample Product-Moment Correlation Coefficient" Journal of the Royal Statistical Society. Series C (Applied Statistics), Vol. 21, No. 1 (1972), pp. 1-12. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2] >>> res = stats.pearsonr(x, y) >>> res PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286) To perform an exact permutation version of the test: >>> rng = np.random.default_rng(7796654889291491997) >>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng) >>> stats.pearsonr(x, y, method=method) PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175) To perform the test under the null hypothesis that the data were drawn from *uniform* distributions: >>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform)) >>> stats.pearsonr(x, y, method=method) PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188) To produce an asymptotic 90% confidence interval: >>> res.confidence_interval(confidence_level=0.9) ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273) And for a bootstrap confidence interval: >>> method = stats.BootstrapMethod(method='BCa', random_state=rng) >>> res.confidence_interval(confidence_level=0.9, method=method) ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443) # may vary There is a linear dependence between x and y if y = a + b*x + e, where a,b are constants and e is a random error term, assumed to be independent of x. For simplicity, assume that x is standard normal, a=0, b=1 and let e follow a normal distribution with mean zero and standard deviation s>0. >>> rng = np.random.default_rng() >>> s = 0.5 >>> x = stats.norm.rvs(size=500, random_state=rng) >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng) >>> y = x + e >>> stats.pearsonr(x, y).statistic 0.9001942438244763 This should be close to the exact value given by >>> 1/np.sqrt(1 + s**2) 0.8944271909999159 For s=0.5, we observe a high level of correlation. In general, a large variance of the noise reduces the correlation, while the correlation approaches one as the variance of the error goes to zero. It is important to keep in mind that no correlation does not imply independence unless (x, y) is jointly normal. Correlation can even be zero when there is a very simple dependence structure: if X follows a standard normal distribution, let y = abs(x). Note that the correlation between x and y is zero. Indeed, since the expectation of x is zero, cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero by symmetry. The following lines of code illustrate this observation: >>> y = np.abs(x) >>> stats.pearsonr(x, y) PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743) A non-zero correlation coefficient can be misleading. For example, if X has a standard normal distribution, define y = x if x < 0 and y = 0 otherwise. A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797..., implying a high level of correlation: >>> y = np.where(x < 0, x, 0) >>> stats.pearsonr(x, y) PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149) This is unintuitive since there is no dependence of x and y if x is larger than zero which happens in about half of the cases if we sample x and y. """ n = len(x) if n != len(y): raise ValueError('x and y must have the same length.') if n < 2: raise ValueError('x and y must have length at least 2.') x = np.asarray(x) y = np.asarray(y) if (np.issubdtype(x.dtype, np.complexfloating) or np.issubdtype(y.dtype, np.complexfloating)): raise ValueError('This function does not support complex data') # If an input is constant, the correlation coefficient is not defined. if (x == x[0]).all() or (y == y[0]).all(): msg = ("An input array is constant; the correlation coefficient " "is not defined.") warnings.warn(stats.ConstantInputWarning(msg)) result = PearsonRResult(statistic=np.nan, pvalue=np.nan, n=n, alternative=alternative, x=x, y=y) return result if isinstance(method, PermutationMethod): def statistic(y): statistic, _ = pearsonr(x, y, alternative=alternative) return statistic res = permutation_test((y,), statistic, permutation_type='pairings', alternative=alternative, **method._asdict()) return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n, alternative=alternative, x=x, y=y) elif isinstance(method, MonteCarloMethod): def statistic(x, y): statistic, _ = pearsonr(x, y, alternative=alternative) return statistic if method.rvs is None: rng = np.random.default_rng() method.rvs = rng.normal, rng.normal res = monte_carlo_test((x, y,), statistic=statistic, alternative=alternative, **method._asdict()) return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n, alternative=alternative, x=x, y=y) elif method is not None: message = ('`method` must be an instance of `PermutationMethod`,' '`MonteCarloMethod`, or None.') raise ValueError(message) # dtype is the data type for the calculations. This expression ensures # that the data type is at least 64 bit floating point. It might have # more precision if the input is, for example, np.longdouble. dtype = type(1.0 + x[0] + y[0]) if n == 2: r = dtype(np.sign(x[1] - x[0])*np.sign(y[1] - y[0])) result = PearsonRResult(statistic=r, pvalue=1.0, n=n, alternative=alternative, x=x, y=y) return result xmean = x.mean(dtype=dtype) ymean = y.mean(dtype=dtype) # By using `astype(dtype)`, we ensure that the intermediate calculations # use at least 64 bit floating point. xm = x.astype(dtype) - xmean ym = y.astype(dtype) - ymean # Unlike np.linalg.norm or the expression sqrt((xm*xm).sum()), # scipy.linalg.norm(xm) does not overflow if xm is, for example, # [-5e210, 5e210, 3e200, -3e200] normxm = linalg.norm(xm) normym = linalg.norm(ym) threshold = 1e-13 if normxm < threshold*abs(xmean) or normym < threshold*abs(ymean): # If all the values in x (likewise y) are very close to the mean, # the loss of precision that occurs in the subtraction xm = x - xmean # might result in large errors in r. msg = ("An input array is nearly constant; the computed " "correlation coefficient may be inaccurate.") warnings.warn(stats.NearConstantInputWarning(msg)) r = np.dot(xm/normxm, ym/normym) # Presumably, if abs(r) > 1, then it is only some small artifact of # floating point arithmetic. r = max(min(r, 1.0), -1.0) # As explained in the docstring, the distribution of `r` under the null # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1. ab = n/2 - 1 dist = stats.beta(ab, ab, loc=-1, scale=2) if alternative == 'two-sided': prob = 2*dist.sf(abs(r)) elif alternative == 'less': prob = dist.cdf(r) elif alternative == 'greater': prob = dist.sf(r) else: raise ValueError('alternative must be one of ' '["two-sided", "less", "greater"]') return PearsonRResult(statistic=r, pvalue=prob, n=n, alternative=alternative, x=x, y=y) def fisher_exact(table, alternative='two-sided'): """Perform a Fisher exact test on a 2x2 contingency table. The null hypothesis is that the true odds ratio of the populations underlying the observations is one, and the observations were sampled from these populations under a condition: the marginals of the resulting table must equal those of the observed table. The statistic returned is the unconditional maximum likelihood estimate of the odds ratio, and the p-value is the probability under the null hypothesis of obtaining a table at least as extreme as the one that was actually observed. There are other possible choices of statistic and two-sided p-value definition associated with Fisher's exact test; please see the Notes for more information. Parameters ---------- table : array_like of ints A 2x2 contingency table. Elements must be non-negative integers. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the odds ratio of the underlying population is not one * 'less': the odds ratio of the underlying population is less than one * 'greater': the odds ratio of the underlying population is greater than one See the Notes for more details. Returns ------- res : SignificanceResult An object containing attributes: statistic : float This is the prior odds ratio, not a posterior estimate. pvalue : float The probability under the null hypothesis of obtaining a table at least as extreme as the one that was actually observed. See Also -------- chi2_contingency : Chi-square test of independence of variables in a contingency table. This can be used as an alternative to `fisher_exact` when the numbers in the table are large. contingency.odds_ratio : Compute the odds ratio (sample or conditional MLE) for a 2x2 contingency table. barnard_exact : Barnard's exact test, which is a more powerful alternative than Fisher's exact test for 2x2 contingency tables. boschloo_exact : Boschloo's exact test, which is a more powerful alternative than Fisher's exact test for 2x2 contingency tables. Notes ----- *Null hypothesis and p-values* The null hypothesis is that the true odds ratio of the populations underlying the observations is one, and the observations were sampled at random from these populations under a condition: the marginals of the resulting table must equal those of the observed table. Equivalently, the null hypothesis is that the input table is from the hypergeometric distribution with parameters (as used in `hypergeom`) ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the input table is ``[[a, b], [c, d]]``. This distribution has support ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values in the input table, ``min(0, a - d) <= x <= a + min(b, c)``. ``x`` can be interpreted as the upper-left element of a 2x2 table, so the tables in the distribution have form:: [ x n - x ] [N - x M - (n + N) + x] For example, if:: table = [6 2] [1 4] then the support is ``2 <= x <= 7``, and the tables in the distribution are:: [2 6] [3 5] [4 4] [5 3] [6 2] [7 1] [5 0] [4 1] [3 2] [2 3] [1 4] [0 5] The probability of each table is given by the hypergeometric distribution ``hypergeom.pmf(x, M, n, N)``. For this example, these are (rounded to three significant digits):: x 2 3 4 5 6 7 p 0.0163 0.163 0.408 0.326 0.0816 0.00466 These can be computed with:: >>> import numpy as np >>> from scipy.stats import hypergeom >>> table = np.array([[6, 2], [1, 4]]) >>> M = table.sum() >>> n = table[0].sum() >>> N = table[:, 0].sum() >>> start, end = hypergeom.support(M, n, N) >>> hypergeom.pmf(np.arange(start, end+1), M, n, N) array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508, 0.004662 ]) The two-sided p-value is the probability that, under the null hypothesis, a random table would have a probability equal to or less than the probability of the input table. For our example, the probability of the input table (where ``x = 6``) is 0.0816. The x values where the probability does not exceed this are 2, 6 and 7, so the two-sided p-value is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``:: >>> from scipy.stats import fisher_exact >>> res = fisher_exact(table, alternative='two-sided') >>> res.pvalue 0.10256410256410257 The one-sided p-value for ``alternative='greater'`` is the probability that a random table has ``x >= a``, which in our example is ``x >= 6``, or ``0.0816 + 0.00466 ~= 0.08626``:: >>> res = fisher_exact(table, alternative='greater') >>> res.pvalue 0.08624708624708627 This is equivalent to computing the survival function of the distribution at ``x = 5`` (one less than ``x`` from the input table, because we want to include the probability of ``x = 6`` in the sum):: >>> hypergeom.sf(5, M, n, N) 0.08624708624708627 For ``alternative='less'``, the one-sided p-value is the probability that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example), or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``:: >>> res = fisher_exact(table, alternative='less') >>> res.pvalue 0.9953379953379957 This is equivalent to computing the cumulative distribution function of the distribution at ``x = 6``: >>> hypergeom.cdf(6, M, n, N) 0.9953379953379957 *Odds ratio* The calculated odds ratio is different from the value computed by the R function ``fisher.test``. This implementation returns the "sample" or "unconditional" maximum likelihood estimate, while ``fisher.test`` in R uses the conditional maximum likelihood estimate. To compute the conditional maximum likelihood estimate of the odds ratio, use `scipy.stats.contingency.odds_ratio`. References ---------- .. [1] Fisher, Sir Ronald A, "The Design of Experiments: Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935. .. [2] "Fisher's exact test", https://en.wikipedia.org/wiki/Fisher's_exact_test .. [3] Emma V. Low et al. "Identifying the lowest effective dose of acetazolamide for the prophylaxis of acute mountain sickness: systematic review and meta-analysis." BMJ, 345, :doi:`10.1136/bmj.e6779`, 2012. Examples -------- In [3]_, the effective dose of acetazolamide for the prophylaxis of acute mountain sickness was investigated. The study notably concluded: Acetazolamide 250 mg, 500 mg, and 750 mg daily were all efficacious for preventing acute mountain sickness. Acetazolamide 250 mg was the lowest effective dose with available evidence for this indication. The following table summarizes the results of the experiment in which some participants took a daily dose of acetazolamide 250 mg while others took a placebo. Cases of acute mountain sickness were recorded:: Acetazolamide Control/Placebo Acute mountain sickness 7 17 No 15 5 Is there evidence that the acetazolamide 250 mg reduces the risk of acute mountain sickness? We begin by formulating a null hypothesis :math:`H_0`: The odds of experiencing acute mountain sickness are the same with the acetazolamide treatment as they are with placebo. Let's assess the plausibility of this hypothesis with Fisher's test. >>> from scipy.stats import fisher_exact >>> res = fisher_exact([[7, 17], [15, 5]], alternative='less') >>> res.statistic 0.13725490196078433 >>> res.pvalue 0.0028841933752349743 Using a significance level of 5%, we would reject the null hypothesis in favor of the alternative hypothesis: "The odds of experiencing acute mountain sickness with acetazolamide treatment are less than the odds of experiencing acute mountain sickness with placebo." .. note:: Because the null distribution of Fisher's exact test is formed under the assumption that both row and column sums are fixed, the result of the test are conservative when applied to an experiment in which the row sums are not fixed. In this case, the column sums are fixed; there are 22 subjects in each group. But the number of cases of acute mountain sickness is not (and cannot be) fixed before conducting the experiment. It is a consequence. Boschloo's test does not depend on the assumption that the row sums are fixed, and consequently, it provides a more powerful test in this situation. >>> from scipy.stats import boschloo_exact >>> res = boschloo_exact([[7, 17], [15, 5]], alternative='less') >>> res.statistic 0.0028841933752349743 >>> res.pvalue 0.0015141406667567101 We verify that the p-value is less than with `fisher_exact`. """ hypergeom = distributions.hypergeom # int32 is not enough for the algorithm c = np.asarray(table, dtype=np.int64) if not c.shape == (2, 2): raise ValueError("The input `table` must be of shape (2, 2).") if np.any(c < 0): raise ValueError("All values in `table` must be nonnegative.") if 0 in c.sum(axis=0) or 0 in c.sum(axis=1): # If both values in a row or column are zero, the p-value is 1 and # the odds ratio is NaN. return SignificanceResult(np.nan, 1.0) if c[1, 0] > 0 and c[0, 1] > 0: oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1]) else: oddsratio = np.inf n1 = c[0, 0] + c[0, 1] n2 = c[1, 0] + c[1, 1] n = c[0, 0] + c[1, 0] def pmf(x): return hypergeom.pmf(x, n1 + n2, n1, n) if alternative == 'less': pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n) elif alternative == 'greater': # Same formula as the 'less' case, but with the second column. pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1]) elif alternative == 'two-sided': mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2)) pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n) pmode = hypergeom.pmf(mode, n1 + n2, n1, n) epsilon = 1e-14 gamma = 1 + epsilon if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon: return SignificanceResult(oddsratio, 1.) elif c[0, 0] < mode: plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n) if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma: return SignificanceResult(oddsratio, plower) guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n) pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n) else: pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n) if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma: return SignificanceResult(oddsratio, pupper) guess = _binary_search(pmf, pexact * gamma, 0, mode) pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n) else: msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}" raise ValueError(msg) pvalue = min(pvalue, 1.0) return SignificanceResult(oddsratio, pvalue) def spearmanr(a, b=None, axis=0, nan_policy='propagate', alternative='two-sided'): r"""Calculate a Spearman correlation coefficient with associated p-value. The Spearman rank-order correlation coefficient is a nonparametric measure of the monotonicity of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact monotonic relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. Although calculation of the p-value does not make strong assumptions about the distributions underlying the samples, it is only accurate for very large samples (>500 observations). For smaller sample sizes, consider a permutation test (see Examples section below). Parameters ---------- a, b : 1D or 2D array_like, b is optional One or two 1-D or 2-D arrays containing multiple variables and observations. When these are 1-D, each represents a vector of observations of a single variable. For the behavior in the 2-D case, see under ``axis``, below. Both arrays need to have the same length in the ``axis`` dimension. axis : int or None, optional If axis=0 (default), then each column represents a variable, with observations in the rows. If axis=1, the relationship is transposed: each row represents a variable, while the columns contain observations. If axis=None, then both arrays will be raveled. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the correlation is nonzero * 'less': the correlation is negative (less than zero) * 'greater': the correlation is positive (greater than zero) .. versionadded:: 1.7.0 Returns ------- res : SignificanceResult An object containing attributes: statistic : float or ndarray (2-D square) Spearman correlation matrix or correlation coefficient (if only 2 variables are given as parameters). Correlation matrix is square with length equal to total number of variables (columns or rows) in ``a`` and ``b`` combined. pvalue : float The p-value for a hypothesis test whose null hypothesis is that two samples have no ordinal correlation. See `alternative` above for alternative hypotheses. `pvalue` has the same shape as `statistic`. Warns ----- `~scipy.stats.ConstantInputWarning` Raised if an input is a constant array. The correlation coefficient is not defined in this case, so ``np.nan`` is returned. References ---------- .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard Probability and Statistics Tables and Formulae. Chapman & Hall: New York. 2000. Section 14.7 .. [2] Kendall, M. G. and Stuart, A. (1973). The Advanced Theory of Statistics, Volume 2: Inference and Relationship. Griffin. 1973. Section 31.18 .. [3] Kershenobich, D., Fierro, F. J., & Rojkind, M. (1970). The relationship between the free pool of proline and collagen content in human liver cirrhosis. The Journal of Clinical Investigation, 49(12), 2246-2249. .. [4] Hollander, M., Wolfe, D. A., & Chicken, E. (2013). Nonparametric statistical methods. John Wiley & Sons. .. [5] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." Statistical Applications in Genetics and Molecular Biology 9.1 (2010). .. [6] Ludbrook, J., & Dudley, H. (1998). Why permutation tests are superior to t and F tests in biomedical research. The American Statistician, 52(2), 127-132. Examples -------- Consider the following data from [3]_, which studied the relationship between free proline (an amino acid) and total collagen (a protein often found in connective tissue) in unhealthy human livers. The ``x`` and ``y`` arrays below record measurements of the two compounds. The observations are paired: each free proline measurement was taken from the same liver as the total collagen measurement at the same index. >>> import numpy as np >>> # total collagen (mg/g dry weight of liver) >>> x = np.array([7.1, 7.1, 7.2, 8.3, 9.4, 10.5, 11.4]) >>> # free proline (μ mole/g dry weight of liver) >>> y = np.array([2.8, 2.9, 2.8, 2.6, 3.5, 4.6, 5.0]) These data were analyzed in [4]_ using Spearman's correlation coefficient, a statistic sensitive to monotonic correlation between the samples. >>> from scipy import stats >>> res = stats.spearmanr(x, y) >>> res.statistic 0.7000000000000001 The value of this statistic tends to be high (close to 1) for samples with a strongly positive ordinal correlation, low (close to -1) for samples with a strongly negative ordinal correlation, and small in magnitude (close to zero) for samples with weak ordinal correlation. The test is performed by comparing the observed value of the statistic against the null distribution: the distribution of statistic values derived under the null hypothesis that total collagen and free proline measurements are independent. For this test, the statistic can be transformed such that the null distribution for large samples is Student's t distribution with ``len(x) - 2`` degrees of freedom. >>> import matplotlib.pyplot as plt >>> dof = len(x)-2 # len(x) == len(y) >>> dist = stats.t(df=dof) >>> t_vals = np.linspace(-5, 5, 100) >>> pdf = dist.pdf(t_vals) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> def plot(ax): # we'll re-use this ... ax.plot(t_vals, pdf) ... ax.set_title("Spearman's Rho Test Null Distribution") ... ax.set_xlabel("statistic") ... ax.set_ylabel("probability density") >>> plot(ax) >>> plt.show() The comparison is quantified by the p-value: the proportion of values in the null distribution as extreme or more extreme than the observed value of the statistic. In a two-sided test in which the statistic is positive, elements of the null distribution greater than the transformed statistic and elements of the null distribution less than the negative of the observed statistic are both considered "more extreme". >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> rs = res.statistic # original statistic >>> transformed = rs * np.sqrt(dof / ((rs+1.0)*(1.0-rs))) >>> pvalue = dist.cdf(-transformed) + dist.sf(transformed) >>> annotation = (f'p-value={pvalue:.4f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (2.7, 0.025), (3, 0.03), arrowprops=props) >>> i = t_vals >= transformed >>> ax.fill_between(t_vals[i], y1=0, y2=pdf[i], color='C0') >>> i = t_vals <= -transformed >>> ax.fill_between(t_vals[i], y1=0, y2=pdf[i], color='C0') >>> ax.set_xlim(-5, 5) >>> ax.set_ylim(0, 0.1) >>> plt.show() >>> res.pvalue 0.07991669030889909 # two-sided p-value If the p-value is "small" - that is, if there is a low probability of sampling data from independent distributions that produces such an extreme value of the statistic - this may be taken as evidence against the null hypothesis in favor of the alternative: the distribution of total collagen and free proline are *not* independent. Note that: - The inverse is not true; that is, the test is not used to provide evidence for the null hypothesis. - The threshold for values that will be considered "small" is a choice that should be made before the data is analyzed [5]_ with consideration of the risks of both false positives (incorrectly rejecting the null hypothesis) and false negatives (failure to reject a false null hypothesis). - Small p-values are not evidence for a *large* effect; rather, they can only provide evidence for a "significant" effect, meaning that they are unlikely to have occurred under the null hypothesis. Suppose that before performing the experiment, the authors had reason to predict a positive correlation between the total collagen and free proline measurements, and that they had chosen to assess the plausibility of the null hypothesis against a one-sided alternative: free proline has a positive ordinal correlation with total collagen. In this case, only those values in the null distribution that are as great or greater than the observed statistic are considered to be more extreme. >>> res = stats.spearmanr(x, y, alternative='greater') >>> res.statistic 0.7000000000000001 # same statistic >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> pvalue = dist.sf(transformed) >>> annotation = (f'p-value={pvalue:.6f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (3, 0.018), (3.5, 0.03), arrowprops=props) >>> i = t_vals >= transformed >>> ax.fill_between(t_vals[i], y1=0, y2=pdf[i], color='C0') >>> ax.set_xlim(1, 5) >>> ax.set_ylim(0, 0.1) >>> plt.show() >>> res.pvalue 0.03995834515444954 # one-sided p-value; half of the two-sided p-value Note that the t-distribution provides an asymptotic approximation of the null distribution; it is only accurate for samples with many observations. For small samples, it may be more appropriate to perform a permutation test: Under the null hypothesis that total collagen and free proline are independent, each of the free proline measurements were equally likely to have been observed with any of the total collagen measurements. Therefore, we can form an *exact* null distribution by calculating the statistic under each possible pairing of elements between ``x`` and ``y``. >>> def statistic(x): # explore all possible pairings by permuting `x` ... rs = stats.spearmanr(x, y).statistic # ignore pvalue ... transformed = rs * np.sqrt(dof / ((rs+1.0)*(1.0-rs))) ... return transformed >>> ref = stats.permutation_test((x,), statistic, alternative='greater', ... permutation_type='pairings') >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> ax.hist(ref.null_distribution, np.linspace(-5, 5, 26), ... density=True) >>> ax.legend(['aymptotic approximation\n(many observations)', ... f'exact \n({len(ref.null_distribution)} permutations)']) >>> plt.show() >>> ref.pvalue 0.04563492063492063 # exact one-sided p-value """ if axis is not None and axis > 1: raise ValueError("spearmanr only handles 1-D or 2-D arrays, " "supplied axis argument {}, please use only " "values 0, 1 or None for axis".format(axis)) a, axisout = _chk_asarray(a, axis) if a.ndim > 2: raise ValueError("spearmanr only handles 1-D or 2-D arrays") if b is None: if a.ndim < 2: raise ValueError("`spearmanr` needs at least 2 " "variables to compare") else: # Concatenate a and b, so that we now only have to handle the case # of a 2-D `a`. b, _ = _chk_asarray(b, axis) if axisout == 0: a = np.column_stack((a, b)) else: a = np.row_stack((a, b)) n_vars = a.shape[1 - axisout] n_obs = a.shape[axisout] if n_obs <= 1: # Handle empty arrays or single observations. res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res warn_msg = ("An input array is constant; the correlation coefficient " "is not defined.") if axisout == 0: if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all(): # If an input is constant, the correlation coefficient # is not defined. warnings.warn(stats.ConstantInputWarning(warn_msg)) res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res else: # case when axisout == 1 b/c a is 2 dim only if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all(): # If an input is constant, the correlation coefficient # is not defined. warnings.warn(stats.ConstantInputWarning(warn_msg)) res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res a_contains_nan, nan_policy = _contains_nan(a, nan_policy) variable_has_nan = np.zeros(n_vars, dtype=bool) if a_contains_nan: if nan_policy == 'omit': return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy, alternative=alternative) elif nan_policy == 'propagate': if a.ndim == 1 or n_vars <= 2: res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res else: # Keep track of variables with NaNs, set the outputs to NaN # only for those variables variable_has_nan = np.isnan(a).any(axis=axisout) a_ranked = np.apply_along_axis(rankdata, axisout, a) rs = np.corrcoef(a_ranked, rowvar=axisout) dof = n_obs - 2 # degrees of freedom # rs can have elements equal to 1, so avoid zero division warnings with np.errstate(divide='ignore'): # clip the small negative values possibly caused by rounding # errors before taking the square root t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0)) t, prob = _ttest_finish(dof, t, alternative) # For backwards compatibility, return scalars when comparing 2 columns if rs.shape == (2, 2): res = SignificanceResult(rs[1, 0], prob[1, 0]) res.correlation = rs[1, 0] return res else: rs[variable_has_nan, :] = np.nan rs[:, variable_has_nan] = np.nan res = SignificanceResult(rs, prob) res.correlation = rs return res def pointbiserialr(x, y): r"""Calculate a point biserial correlation coefficient and its p-value. The point biserial correlation is used to measure the relationship between a binary variable, x, and a continuous variable, y. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply a determinative relationship. This function may be computed using a shortcut formula but produces the same result as `pearsonr`. Parameters ---------- x : array_like of bools Input array. y : array_like Input array. Returns ------- res: SignificanceResult An object containing attributes: statistic : float The R value. pvalue : float The two-sided p-value. Notes ----- `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom. It is equivalent to `pearsonr`. The value of the point-biserial correlation can be calculated from: .. math:: r_{pb} = \frac{\overline{Y_1} - \overline{Y_0}} {s_y} \sqrt{\frac{N_0 N_1} {N (N - 1)}} Where :math:`\overline{Y_{0}}` and :math:`\overline{Y_{1}}` are means of the metric observations coded 0 and 1 respectively; :math:`N_{0}` and :math:`N_{1}` are number of observations coded 0 and 1 respectively; :math:`N` is the total number of observations and :math:`s_{y}` is the standard deviation of all the metric observations. A value of :math:`r_{pb}` that is significantly different from zero is completely equivalent to a significant difference in means between the two groups. Thus, an independent groups t Test with :math:`N-2` degrees of freedom may be used to test whether :math:`r_{pb}` is nonzero. The relation between the t-statistic for comparing two independent groups and :math:`r_{pb}` is given by: .. math:: t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}} References ---------- .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math. Statist., Vol. 20, no.1, pp. 125-126, 1949. .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25, np. 3, pp. 603-607, 1954. .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef: Statistics Reference Online (eds N. Balakrishnan, et al.), 2014. :doi:`10.1002/9781118445112.stat06227` Examples -------- >>> import numpy as np >>> from scipy import stats >>> a = np.array([0, 0, 0, 1, 1, 1, 1]) >>> b = np.arange(7) >>> stats.pointbiserialr(a, b) (0.8660254037844386, 0.011724811003954652) >>> stats.pearsonr(a, b) (0.86602540378443871, 0.011724811003954626) >>> np.corrcoef(a, b) array([[ 1. , 0.8660254], [ 0.8660254, 1. ]]) """ rpb, prob = pearsonr(x, y) # create result object with alias for backward compatibility res = SignificanceResult(rpb, prob) res.correlation = rpb return res def kendalltau(x, y, initial_lexsort=None, nan_policy='propagate', method='auto', variant='b', alternative='two-sided'): r"""Calculate Kendall's tau, a correlation measure for ordinal data. Kendall's tau is a measure of the correspondence between two rankings. Values close to 1 indicate strong agreement, and values close to -1 indicate strong disagreement. This implements two variants of Kendall's tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These differ only in how they are normalized to lie within the range -1 to 1; the hypothesis tests (their p-values) are identical. Kendall's original tau-a is not implemented separately because both tau-b and tau-c reduce to tau-a in the absence of ties. Parameters ---------- x, y : array_like Arrays of rankings, of the same shape. If arrays are not 1-D, they will be flattened to 1-D. initial_lexsort : bool, optional, deprecated This argument is unused. .. deprecated:: 1.10.0 `kendalltau` keyword argument `initial_lexsort` is deprecated as it is unused and will be removed in SciPy 1.12.0. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values method : {'auto', 'asymptotic', 'exact'}, optional Defines which method is used to calculate the p-value [5]_. The following options are available (default is 'auto'): * 'auto': selects the appropriate method based on a trade-off between speed and accuracy * 'asymptotic': uses a normal approximation valid for large samples * 'exact': computes the exact p-value, but can only be used if no ties are present. As the sample size increases, the 'exact' computation time may grow and the result may lose some precision. variant : {'b', 'c'}, optional Defines which variant of Kendall's tau is returned. Default is 'b'. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the rank correlation is nonzero * 'less': the rank correlation is negative (less than zero) * 'greater': the rank correlation is positive (greater than zero) Returns ------- res : SignificanceResult An object containing attributes: statistic : float The tau statistic. pvalue : float The p-value for a hypothesis test whose null hypothesis is an absence of association, tau = 0. See Also -------- spearmanr : Calculates a Spearman rank-order correlation coefficient. theilslopes : Computes the Theil-Sen estimator for a set of points (x, y). weightedtau : Computes a weighted version of Kendall's tau. Notes ----- The definition of Kendall's tau that is used is [2]_:: tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U)) tau_c = 2 (P - Q) / (n**2 * (m - 1) / m) where P is the number of concordant pairs, Q the number of discordant pairs, T the number of ties only in `x`, and U the number of ties only in `y`. If a tie occurs for the same pair in both `x` and `y`, it is not added to either T or U. n is the total number of samples, and m is the number of unique values in either `x` or `y`, whichever is smaller. References ---------- .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika Vol. 30, No. 1/2, pp. 81-93, 1938. .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems", Biometrika Vol. 33, No. 3, pp. 239-251. 1945. .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John Wiley & Sons, 1967. .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency tables", Software: Practice and Experience, Vol. 24, No. 3, pp. 327-336, 1994. .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition), Charles Griffin & Co., 1970. .. [6] Kershenobich, D., Fierro, F. J., & Rojkind, M. (1970). The relationship between the free pool of proline and collagen content in human liver cirrhosis. The Journal of Clinical Investigation, 49(12), 2246-2249. .. [7] Hollander, M., Wolfe, D. A., & Chicken, E. (2013). Nonparametric statistical methods. John Wiley & Sons. .. [8] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." Statistical Applications in Genetics and Molecular Biology 9.1 (2010). Examples -------- Consider the following data from [6]_, which studied the relationship between free proline (an amino acid) and total collagen (a protein often found in connective tissue) in unhealthy human livers. The ``x`` and ``y`` arrays below record measurements of the two compounds. The observations are paired: each free proline measurement was taken from the same liver as the total collagen measurement at the same index. >>> import numpy as np >>> # total collagen (mg/g dry weight of liver) >>> x = np.array([7.1, 7.1, 7.2, 8.3, 9.4, 10.5, 11.4]) >>> # free proline (μ mole/g dry weight of liver) >>> y = np.array([2.8, 2.9, 2.8, 2.6, 3.5, 4.6, 5.0]) These data were analyzed in [7]_ using Spearman's correlation coefficient, a statistic similar to to Kendall's tau in that it is also sensitive to ordinal correlation between the samples. Let's perform an analagous study using Kendall's tau. >>> from scipy import stats >>> res = stats.kendalltau(x, y) >>> res.statistic 0.5499999999999999 The value of this statistic tends to be high (close to 1) for samples with a strongly positive ordinal correlation, low (close to -1) for samples with a strongly negative ordinal correlation, and small in magnitude (close to zero) for samples with weak ordinal correlation. The test is performed by comparing the observed value of the statistic against the null distribution: the distribution of statistic values derived under the null hypothesis that total collagen and free proline measurements are independent. For this test, the null distribution for large samples without ties is approximated as the normal distribution with variance ``(2*(2*n + 5))/(9*n*(n - 1))``, where ``n = len(x)``. >>> import matplotlib.pyplot as plt >>> n = len(x) # len(x) == len(y) >>> var = (2*(2*n + 5))/(9*n*(n - 1)) >>> dist = stats.norm(scale=np.sqrt(var)) >>> z_vals = np.linspace(-1.25, 1.25, 100) >>> pdf = dist.pdf(z_vals) >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> def plot(ax): # we'll re-use this ... ax.plot(z_vals, pdf) ... ax.set_title("Kendall Tau Test Null Distribution") ... ax.set_xlabel("statistic") ... ax.set_ylabel("probability density") >>> plot(ax) >>> plt.show() The comparison is quantified by the p-value: the proportion of values in the null distribution as extreme or more extreme than the observed value of the statistic. In a two-sided test in which the statistic is positive, elements of the null distribution greater than the transformed statistic and elements of the null distribution less than the negative of the observed statistic are both considered "more extreme". >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> pvalue = dist.cdf(-res.statistic) + dist.sf(res.statistic) >>> annotation = (f'p-value={pvalue:.4f}\n(shaded area)') >>> props = dict(facecolor='black', width=1, headwidth=5, headlength=8) >>> _ = ax.annotate(annotation, (0.65, 0.15), (0.8, 0.3), arrowprops=props) >>> i = z_vals >= res.statistic >>> ax.fill_between(z_vals[i], y1=0, y2=pdf[i], color='C0') >>> i = z_vals <= -res.statistic >>> ax.fill_between(z_vals[i], y1=0, y2=pdf[i], color='C0') >>> ax.set_xlim(-1.25, 1.25) >>> ax.set_ylim(0, 0.5) >>> plt.show() >>> res.pvalue 0.09108705741631495 # approximate p-value Note that there is slight disagreement between the shaded area of the curve and the p-value returned by `kendalltau`. This is because our data has ties, and we have neglected a tie correction to the null distribution variance that `kendalltau` performs. For samples without ties, the shaded areas of our plot and p-value returned by `kendalltau` would match exactly. If the p-value is "small" - that is, if there is a low probability of sampling data from independent distributions that produces such an extreme value of the statistic - this may be taken as evidence against the null hypothesis in favor of the alternative: the distribution of total collagen and free proline are *not* independent. Note that: - The inverse is not true; that is, the test is not used to provide evidence for the null hypothesis. - The threshold for values that will be considered "small" is a choice that should be made before the data is analyzed [8]_ with consideration of the risks of both false positives (incorrectly rejecting the null hypothesis) and false negatives (failure to reject a false null hypothesis). - Small p-values are not evidence for a *large* effect; rather, they can only provide evidence for a "significant" effect, meaning that they are unlikely to have occurred under the null hypothesis. For samples without ties of moderate size, `kendalltau` can compute the p-value exactly. However, in the presence of ties, `kendalltau` resorts to an asymptotic approximation. Nonetheles, we can use a permutation test to compute the null distribution exactly: Under the null hypothesis that total collagen and free proline are independent, each of the free proline measurements were equally likely to have been observed with any of the total collagen measurements. Therefore, we can form an *exact* null distribution by calculating the statistic under each possible pairing of elements between ``x`` and ``y``. >>> def statistic(x): # explore all possible pairings by permuting `x` ... return stats.kendalltau(x, y).statistic # ignore pvalue >>> ref = stats.permutation_test((x,), statistic, ... permutation_type='pairings') >>> fig, ax = plt.subplots(figsize=(8, 5)) >>> plot(ax) >>> bins = np.linspace(-1.25, 1.25, 25) >>> ax.hist(ref.null_distribution, bins=bins, density=True) >>> ax.legend(['aymptotic approximation\n(many observations)', ... 'exact null distribution']) >>> plot(ax) >>> plt.show() >>> ref.pvalue 0.12222222222222222 # exact p-value Note that there is significant disagreement between the exact p-value calculated here and the approximation returned by `kendalltau` above. For small samples with ties, consider performing a permutation test for more accurate results. """ if initial_lexsort is not None: msg = ("'kendalltau' keyword argument 'initial_lexsort' is deprecated" " as it is unused and will be removed in SciPy 1.12.0.") warnings.warn(msg, DeprecationWarning, stacklevel=2) x = np.asarray(x).ravel() y = np.asarray(y).ravel() if x.size != y.size: raise ValueError("All inputs to `kendalltau` must be of the same " f"size, found x-size {x.size} and y-size {y.size}") elif not x.size or not y.size: # Return NaN if arrays are empty res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res # check both x and y cnx, npx = _contains_nan(x, nan_policy) cny, npy = _contains_nan(y, nan_policy) contains_nan = cnx or cny if npx == 'omit' or npy == 'omit': nan_policy = 'omit' if contains_nan and nan_policy == 'propagate': res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res elif contains_nan and nan_policy == 'omit': x = ma.masked_invalid(x) y = ma.masked_invalid(y) if variant == 'b': return mstats_basic.kendalltau(x, y, method=method, use_ties=True, alternative=alternative) else: message = ("nan_policy='omit' is currently compatible only with " "variant='b'.") raise ValueError(message) def count_rank_tie(ranks): cnt = np.bincount(ranks).astype('int64', copy=False) cnt = cnt[cnt > 1] # Python ints to avoid overflow down the line return (int((cnt * (cnt - 1) // 2).sum()), int((cnt * (cnt - 1.) * (cnt - 2)).sum()), int((cnt * (cnt - 1.) * (2*cnt + 5)).sum())) size = x.size perm = np.argsort(y) # sort on y and convert y to dense ranks x, y = x[perm], y[perm] y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp) # stable sort on x and convert x to dense ranks perm = np.argsort(x, kind='mergesort') x, y = x[perm], y[perm] x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp) dis = _kendall_dis(x, y) # discordant pairs obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True] cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False) ntie = int((cnt * (cnt - 1) // 2).sum()) # joint ties xtie, x0, x1 = count_rank_tie(x) # ties in x, stats ytie, y0, y1 = count_rank_tie(y) # ties in y, stats tot = (size * (size - 1)) // 2 if xtie == tot or ytie == tot: res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie # = con + dis + xtie + ytie - ntie con_minus_dis = tot - xtie - ytie + ntie - 2 * dis if variant == 'b': tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie) elif variant == 'c': minclasses = min(len(set(x)), len(set(y))) tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses) else: raise ValueError(f"Unknown variant of the method chosen: {variant}. " "variant must be 'b' or 'c'.") # Limit range to fix computational errors tau = min(1., max(-1., tau)) # The p-value calculation is the same for all variants since the p-value # depends only on con_minus_dis. if method == 'exact' and (xtie != 0 or ytie != 0): raise ValueError("Ties found, exact method cannot be used.") if method == 'auto': if (xtie == 0 and ytie == 0) and (size <= 33 or min(dis, tot-dis) <= 1): method = 'exact' else: method = 'asymptotic' if xtie == 0 and ytie == 0 and method == 'exact': pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative) elif method == 'asymptotic': # con_minus_dis is approx normally distributed with this variance [3]_ m = size * (size - 1.) var = ((m * (2*size + 5) - x1 - y1) / 18 + (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2))) z = con_minus_dis / np.sqrt(var) _, pvalue = _normtest_finish(z, alternative) else: raise ValueError(f"Unknown method {method} specified. Use 'auto', " "'exact' or 'asymptotic'.") # create result object with alias for backward compatibility res = SignificanceResult(tau, pvalue) res.correlation = tau return res def weightedtau(x, y, rank=True, weigher=None, additive=True): r"""Compute a weighted version of Kendall's :math:`\tau`. The weighted :math:`\tau` is a weighted version of Kendall's :math:`\tau` in which exchanges of high weight are more influential than exchanges of low weight. The default parameters compute the additive hyperbolic version of the index, :math:`\tau_\mathrm h`, which has been shown to provide the best balance between important and unimportant elements [1]_. The weighting is defined by means of a rank array, which assigns a nonnegative rank to each element (higher importance ranks being associated with smaller values, e.g., 0 is the highest possible rank), and a weigher function, which assigns a weight based on the rank to each element. The weight of an exchange is then the sum or the product of the weights of the ranks of the exchanged elements. The default parameters compute :math:`\tau_\mathrm h`: an exchange between elements with rank :math:`r` and :math:`s` (starting from zero) has weight :math:`1/(r+1) + 1/(s+1)`. Specifying a rank array is meaningful only if you have in mind an external criterion of importance. If, as it usually happens, you do not have in mind a specific rank, the weighted :math:`\tau` is defined by averaging the values obtained using the decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the behavior with default parameters. Note that the convention used here for ranking (lower values imply higher importance) is opposite to that used by other SciPy statistical functions. Parameters ---------- x, y : array_like Arrays of scores, of the same shape. If arrays are not 1-D, they will be flattened to 1-D. rank : array_like of ints or bool, optional A nonnegative rank assigned to each element. If it is None, the decreasing lexicographical rank by (`x`, `y`) will be used: elements of higher rank will be those with larger `x`-values, using `y`-values to break ties (in particular, swapping `x` and `y` will give a different result). If it is False, the element indices will be used directly as ranks. The default is True, in which case this function returns the average of the values obtained using the decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`). weigher : callable, optional The weigher function. Must map nonnegative integers (zero representing the most important element) to a nonnegative weight. The default, None, provides hyperbolic weighing, that is, rank :math:`r` is mapped to weight :math:`1/(r+1)`. additive : bool, optional If True, the weight of an exchange is computed by adding the weights of the ranks of the exchanged elements; otherwise, the weights are multiplied. The default is True. Returns ------- res: SignificanceResult An object containing attributes: statistic : float The weighted :math:`\tau` correlation index. pvalue : float Presently ``np.nan``, as the null distribution of the statistic is unknown (even in the additive hyperbolic case). See Also -------- kendalltau : Calculates Kendall's tau. spearmanr : Calculates a Spearman rank-order correlation coefficient. theilslopes : Computes the Theil-Sen estimator for a set of points (x, y). Notes ----- This function uses an :math:`O(n \log n)`, mergesort-based algorithm [1]_ that is a weighted extension of Knight's algorithm for Kendall's :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_ between rankings without ties (i.e., permutations) by setting `additive` and `rank` to False, as the definition given in [1]_ is a generalization of Shieh's. NaNs are considered the smallest possible score. .. versionadded:: 0.19.0 References ---------- .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with ties", Proceedings of the 24th international conference on World Wide Web, pp. 1166-1176, ACM, 2015. .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with Ungrouped Data", Journal of the American Statistical Association, Vol. 61, No. 314, Part 1, pp. 436-439, 1966. .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics & Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998. Examples -------- >>> import numpy as np >>> from scipy import stats >>> x = [12, 2, 1, 12, 2] >>> y = [1, 4, 7, 1, 0] >>> res = stats.weightedtau(x, y) >>> res.statistic -0.56694968153682723 >>> res.pvalue nan >>> res = stats.weightedtau(x, y, additive=False) >>> res.statistic -0.62205716951801038 NaNs are considered the smallest possible score: >>> x = [12, 2, 1, 12, 2] >>> y = [1, 4, 7, 1, np.nan] >>> res = stats.weightedtau(x, y) >>> res.statistic -0.56694968153682723 This is exactly Kendall's tau: >>> x = [12, 2, 1, 12, 2] >>> y = [1, 4, 7, 1, 0] >>> res = stats.weightedtau(x, y, weigher=lambda x: 1) >>> res.statistic -0.47140452079103173 >>> x = [12, 2, 1, 12, 2] >>> y = [1, 4, 7, 1, 0] >>> stats.weightedtau(x, y, rank=None) SignificanceResult(statistic=-0.4157652301037516, pvalue=nan) >>> stats.weightedtau(y, x, rank=None) SignificanceResult(statistic=-0.7181341329699028, pvalue=nan) """ x = np.asarray(x).ravel() y = np.asarray(y).ravel() if x.size != y.size: raise ValueError("All inputs to `weightedtau` must be " "of the same size, " "found x-size {} and y-size {}".format(x.size, y.size)) if not x.size: # Return NaN if arrays are empty res = SignificanceResult(np.nan, np.nan) res.correlation = np.nan return res # If there are NaNs we apply _toint64() if np.isnan(np.sum(x)): x = _toint64(x) if np.isnan(np.sum(y)): y = _toint64(y) # Reduce to ranks unsupported types if x.dtype != y.dtype: if x.dtype != np.int64: x = _toint64(x) if y.dtype != np.int64: y = _toint64(y) else: if x.dtype not in (np.int32, np.int64, np.float32, np.float64): x = _toint64(x) y = _toint64(y) if rank is True: tau = ( _weightedrankedtau(x, y, None, weigher, additive) + _weightedrankedtau(y, x, None, weigher, additive) ) / 2 res = SignificanceResult(tau, np.nan) res.correlation = tau return res if rank is False: rank = np.arange(x.size, dtype=np.intp) elif rank is not None: rank = np.asarray(rank).ravel() if rank.size != x.size: raise ValueError( "All inputs to `weightedtau` must be of the same size, " "found x-size {} and rank-size {}".format(x.size, rank.size) ) tau = _weightedrankedtau(x, y, rank, weigher, additive) res = SignificanceResult(tau, np.nan) res.correlation = tau return res # FROM MGCPY: https://github.com/neurodata/mgcpy class _ParallelP: """Helper function to calculate parallel p-value.""" def __init__(self, x, y, random_states): self.x = x self.y = y self.random_states = random_states def __call__(self, index): order = self.random_states[index].permutation(self.y.shape[0]) permy = self.y[order][:, order] # calculate permuted stats, store in null distribution perm_stat = _mgc_stat(self.x, permy)[0] return perm_stat def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None): r"""Helper function that calculates the p-value. See below for uses. Parameters ---------- x, y : ndarray `x` and `y` have shapes `(n, p)` and `(n, q)`. stat : float The sample test statistic. reps : int, optional The number of replications used to estimate the null when using the permutation test. The default is 1000 replications. workers : int or map-like callable, optional If `workers` is an int the population is subdivided into `workers` sections and evaluated in parallel (uses `multiprocessing.Pool <multiprocessing>`). Supply `-1` to use all cores available to the Process. Alternatively supply a map-like callable, such as `multiprocessing.Pool.map` for evaluating the population in parallel. This evaluation is carried out as `workers(func, iterable)`. Requires that `func` be pickleable. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- pvalue : float The sample test p-value. null_dist : list The approximated null distribution. """ # generate seeds for each rep (change to new parallel random number # capabilities in numpy >= 1.17+) random_state = check_random_state(random_state) random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32, size=4, dtype=np.uint32)) for _ in range(reps)] # parallelizes with specified workers over number of reps and set seeds parallelp = _ParallelP(x=x, y=y, random_states=random_states) with MapWrapper(workers) as mapwrapper: null_dist = np.array(list(mapwrapper(parallelp, range(reps)))) # calculate p-value and significant permutation map through list pvalue = (1 + (null_dist >= stat).sum()) / (1 + reps) return pvalue, null_dist def _euclidean_dist(x): return cdist(x, x) MGCResult = _make_tuple_bunch('MGCResult', ['statistic', 'pvalue', 'mgc_dict'], []) def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000, workers=1, is_twosamp=False, random_state=None): r"""Computes the Multiscale Graph Correlation (MGC) test statistic. Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for one property (e.g. cloud density), and the :math:`l`-nearest neighbors for the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is called the "scale". A priori, however, it is not know which scales will be most informative. So, MGC computes all distance pairs, and then efficiently computes the distance correlations for all scales. The local correlations illustrate which scales are relatively informative about the relationship. The key, therefore, to successfully discover and decipher relationships between disparate data modalities is to adaptively determine which scales are the most informative, and the geometric implication for the most informative scales. Doing so not only provides an estimate of whether the modalities are related, but also provides insight into how the determination was made. This is especially important in high-dimensional data, where simple visualizations do not reveal relationships to the unaided human eye. Characterizations of this implementation in particular have been derived from and benchmarked within in [2]_. Parameters ---------- x, y : ndarray If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is the number of samples and `p` and `q` are the number of dimensions, then the MGC independence test will be run. Alternatively, ``x`` and ``y`` can have shapes ``(n, n)`` if they are distance or similarity matrices, and ``compute_distance`` must be sent to ``None``. If ``x`` and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired two-sample MGC test will be run. compute_distance : callable, optional A function that computes the distance or similarity among the samples within each data matrix. Set to ``None`` if ``x`` and ``y`` are already distance matrices. The default uses the euclidean norm metric. If you are calling a custom function, either create the distance matrix before-hand or create a function of the form ``compute_distance(x)`` where `x` is the data matrix for which pairwise distances are calculated. reps : int, optional The number of replications used to estimate the null when using the permutation test. The default is ``1000``. workers : int or map-like callable, optional If ``workers`` is an int the population is subdivided into ``workers`` sections and evaluated in parallel (uses ``multiprocessing.Pool <multiprocessing>``). Supply ``-1`` to use all cores available to the Process. Alternatively supply a map-like callable, such as ``multiprocessing.Pool.map`` for evaluating the p-value in parallel. This evaluation is carried out as ``workers(func, iterable)``. Requires that `func` be pickleable. The default is ``1``. is_twosamp : bool, optional If `True`, a two sample test will be run. If ``x`` and ``y`` have shapes ``(n, p)`` and ``(m, p)``, this optional will be overridden and set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes ``(n, p)`` and a two sample test is desired. The default is ``False``. Note that this will not run if inputs are distance matrices. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- res : MGCResult An object containing attributes: statistic : float The sample MGC test statistic within `[-1, 1]`. pvalue : float The p-value obtained via permutation. mgc_dict : dict Contains additional useful results: - mgc_map : ndarray A 2D representation of the latent geometry of the relationship. - opt_scale : (int, int) The estimated optimal scale as a `(x, y)` pair. - null_dist : list The null distribution derived from the permuted matrices. See Also -------- pearsonr : Pearson correlation coefficient and p-value for testing non-correlation. kendalltau : Calculates Kendall's tau. spearmanr : Calculates a Spearman rank-order correlation coefficient. Notes ----- A description of the process of MGC and applications on neuroscience data can be found in [1]_. It is performed using the following steps: #. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and modified to be mean zero columnwise. This results in two :math:`n \times n` distance matrices :math:`A` and :math:`B` (the centering and unbiased modification) [3]_. #. For all values :math:`k` and :math:`l` from :math:`1, ..., n`, * The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs are calculated for each property. Here, :math:`G_k (i, j)` indicates the :math:`k`-smallest values of the :math:`i`-th row of :math:`A` and :math:`H_l (i, j)` indicates the :math:`l` smallested values of the :math:`i`-th row of :math:`B` * Let :math:`\circ` denotes the entry-wise matrix product, then local correlations are summed and normalized using the following statistic: .. math:: c^{kl} = \frac{\sum_{ij} A G_k B H_l} {\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}} #. The MGC test statistic is the smoothed optimal local correlation of :math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)` (which essentially set all isolated large correlations) as 0 and connected large correlations the same as before, see [3]_.) MGC is, .. math:: MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right) \right) The test statistic returns a value between :math:`(-1, 1)` since it is normalized. The p-value returned is calculated using a permutation test. This process is completed by first randomly permuting :math:`y` to estimate the null distribution and then calculating the probability of observing a test statistic, under the null, at least as extreme as the observed test statistic. MGC requires at least 5 samples to run with reliable results. It can also handle high-dimensional data sets. In addition, by manipulating the input data matrices, the two-sample testing problem can be reduced to the independence testing problem [4]_. Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n` :math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as follows: .. math:: X = [U | V] \in \mathcal{R}^{p \times (n + m)} Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)} Then, the MGC statistic can be calculated as normal. This methodology can be extended to similar tests such as distance correlation [4]_. .. versionadded:: 1.4.0 References ---------- .. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E., Maggioni, M., & Shen, C. (2019). Discovering and deciphering relationships across disparate data modalities. ELife. .. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A., Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019). mgcpy: A Comprehensive High Dimensional Independence Testing Python Package. :arXiv:`1907.02088` .. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance correlation to multiscale graph correlation. Journal of the American Statistical Association. .. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of Distance and Kernel Methods for Hypothesis Testing. :arXiv:`1806.05514` Examples -------- >>> import numpy as np >>> from scipy.stats import multiscale_graphcorr >>> x = np.arange(100) >>> y = x >>> res = multiscale_graphcorr(x, y) >>> res.statistic, res.pvalue (1.0, 0.001) To run an unpaired two-sample test, >>> x = np.arange(100) >>> y = np.arange(79) >>> res = multiscale_graphcorr(x, y) >>> res.statistic, res.pvalue # doctest: +SKIP (0.033258146255703246, 0.023) or, if shape of the inputs are the same, >>> x = np.arange(100) >>> y = x >>> res = multiscale_graphcorr(x, y, is_twosamp=True) >>> res.statistic, res.pvalue # doctest: +SKIP (-0.008021809890200488, 1.0) """ if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray): raise ValueError("x and y must be ndarrays") # convert arrays of type (n,) to (n, 1) if x.ndim == 1: x = x[:, np.newaxis] elif x.ndim != 2: raise ValueError("Expected a 2-D array `x`, found shape " "{}".format(x.shape)) if y.ndim == 1: y = y[:, np.newaxis] elif y.ndim != 2: raise ValueError("Expected a 2-D array `y`, found shape " "{}".format(y.shape)) nx, px = x.shape ny, py = y.shape # check for NaNs _contains_nan(x, nan_policy='raise') _contains_nan(y, nan_policy='raise') # check for positive or negative infinity and raise error if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0: raise ValueError("Inputs contain infinities") if nx != ny: if px == py: # reshape x and y for two sample testing is_twosamp = True else: raise ValueError("Shape mismatch, x and y must have shape [n, p] " "and [n, q] or have shape [n, p] and [m, p].") if nx < 5 or ny < 5: raise ValueError("MGC requires at least 5 samples to give reasonable " "results.") # convert x and y to float x = x.astype(np.float64) y = y.astype(np.float64) # check if compute_distance_matrix if a callable() if not callable(compute_distance) and compute_distance is not None: raise ValueError("Compute_distance must be a function.") # check if number of reps exists, integer, or > 0 (if under 1000 raises # warning) if not isinstance(reps, int) or reps < 0: raise ValueError("Number of reps must be an integer greater than 0.") elif reps < 1000: msg = ("The number of replications is low (under 1000), and p-value " "calculations may be unreliable. Use the p-value result, with " "caution!") warnings.warn(msg, RuntimeWarning) if is_twosamp: if compute_distance is None: raise ValueError("Cannot run if inputs are distance matrices") x, y = _two_sample_transform(x, y) if compute_distance is not None: # compute distance matrices for x and y x = compute_distance(x) y = compute_distance(y) # calculate MGC stat stat, stat_dict = _mgc_stat(x, y) stat_mgc_map = stat_dict["stat_mgc_map"] opt_scale = stat_dict["opt_scale"] # calculate permutation MGC p-value pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers, random_state=random_state) # save all stats (other than stat/p-value) in dictionary mgc_dict = {"mgc_map": stat_mgc_map, "opt_scale": opt_scale, "null_dist": null_dist} # create result object with alias for backward compatibility res = MGCResult(stat, pvalue, mgc_dict) res.stat = stat return res def _mgc_stat(distx, disty): r"""Helper function that calculates the MGC stat. See above for use. Parameters ---------- distx, disty : ndarray `distx` and `disty` have shapes `(n, p)` and `(n, q)` or `(n, n)` and `(n, n)` if distance matrices. Returns ------- stat : float The sample MGC test statistic within `[-1, 1]`. stat_dict : dict Contains additional useful additional returns containing the following keys: - stat_mgc_map : ndarray MGC-map of the statistics. - opt_scale : (float, float) The estimated optimal scale as a `(x, y)` pair. """ # calculate MGC map and optimal scale stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc') n, m = stat_mgc_map.shape if m == 1 or n == 1: # the global scale at is the statistic calculated at maximial nearest # neighbors. There is not enough local scale to search over, so # default to global scale stat = stat_mgc_map[m - 1][n - 1] opt_scale = m * n else: samp_size = len(distx) - 1 # threshold to find connected region of significant local correlations sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size) # maximum within the significant region stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map) stat_dict = {"stat_mgc_map": stat_mgc_map, "opt_scale": opt_scale} return stat, stat_dict def _threshold_mgc_map(stat_mgc_map, samp_size): r""" Finds a connected region of significance in the MGC-map by thresholding. Parameters ---------- stat_mgc_map : ndarray All local correlations within `[-1,1]`. samp_size : int The sample size of original data. Returns ------- sig_connect : ndarray A binary matrix with 1's indicating the significant region. """ m, n = stat_mgc_map.shape # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05 # with varying levels of performance. Threshold is based on a beta # approximation. per_sig = 1 - (0.02 / samp_size) # Percentile to consider as significant threshold = samp_size * (samp_size - 3)/4 - 1/2 # Beta approximation threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1 # the global scale at is the statistic calculated at maximial nearest # neighbors. Threshold is the maximum on the global and local scales threshold = max(threshold, stat_mgc_map[m - 1][n - 1]) # find the largest connected component of significant correlations sig_connect = stat_mgc_map > threshold if np.sum(sig_connect) > 0: sig_connect, _ = _measurements.label(sig_connect) _, label_counts = np.unique(sig_connect, return_counts=True) # skip the first element in label_counts, as it is count(zeros) max_label = np.argmax(label_counts[1:]) + 1 sig_connect = sig_connect == max_label else: sig_connect = np.array([[False]]) return sig_connect def _smooth_mgc_map(sig_connect, stat_mgc_map): """Finds the smoothed maximal within the significant region R. If area of R is too small it returns the last local correlation. Otherwise, returns the maximum within significant_connected_region. Parameters ---------- sig_connect : ndarray A binary matrix with 1's indicating the significant region. stat_mgc_map : ndarray All local correlations within `[-1, 1]`. Returns ------- stat : float The sample MGC statistic within `[-1, 1]`. opt_scale: (float, float) The estimated optimal scale as an `(x, y)` pair. """ m, n = stat_mgc_map.shape # the global scale at is the statistic calculated at maximial nearest # neighbors. By default, statistic and optimal scale are global. stat = stat_mgc_map[m - 1][n - 1] opt_scale = [m, n] if np.linalg.norm(sig_connect) != 0: # proceed only when the connected region's area is sufficiently large # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05 # with varying levels of performance if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n): max_corr = max(stat_mgc_map[sig_connect]) # find all scales within significant_connected_region that maximize # the local correlation max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect) if max_corr >= stat: stat = max_corr k, l = max_corr_index one_d_indices = k * n + l # 2D to 1D indexing k = np.max(one_d_indices) // n l = np.max(one_d_indices) % n opt_scale = [k+1, l+1] # adding 1s to match R indexing return stat, opt_scale def _two_sample_transform(u, v): """Helper function that concatenates x and y for two sample MGC stat. See above for use. Parameters ---------- u, v : ndarray `u` and `v` have shapes `(n, p)` and `(m, p)`. Returns ------- x : ndarray Concatenate `u` and `v` along the `axis = 0`. `x` thus has shape `(2n, p)`. y : ndarray Label matrix for `x` where 0 refers to samples that comes from `u` and 1 refers to samples that come from `v`. `y` thus has shape `(2n, 1)`. """ nx = u.shape[0] ny = v.shape[0] x = np.concatenate([u, v], axis=0) y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1) return x, y ##################################### # INFERENTIAL STATISTICS # ##################################### TtestResultBase = _make_tuple_bunch('TtestResultBase', ['statistic', 'pvalue'], ['df']) class TtestResult(TtestResultBase): """ Result of a t-test. See the documentation of the particular t-test function for more information about the definition of the statistic and meaning of the confidence interval. Attributes ---------- statistic : float or array The t-statistic of the sample. pvalue : float or array The p-value associated with the given alternative. df : float or array The number of degrees of freedom used in calculation of the t-statistic; this is one less than the size of the sample (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs). Methods ------- confidence_interval Computes a confidence interval around the population statistic for the given confidence level. The confidence interval is returned in a ``namedtuple`` with fields `low` and `high`. """ def __init__(self, statistic, pvalue, df, # public alternative, standard_error, estimate): # private super().__init__(statistic, pvalue, df=df) self._alternative = alternative self._standard_error = standard_error # denominator of t-statistic self._estimate = estimate # point estimate of sample mean def confidence_interval(self, confidence_level=0.95): """ Parameters ---------- confidence_level : float The confidence level for the calculation of the population mean confidence interval. Default is 0.95. Returns ------- ci : namedtuple The confidence interval is returned in a ``namedtuple`` with fields `low` and `high`. """ low, high = _t_confidence_interval(self.df, self.statistic, confidence_level, self._alternative) low = low * self._standard_error + self._estimate high = high * self._standard_error + self._estimate return ConfidenceInterval(low=low, high=high) def pack_TtestResult(statistic, pvalue, df, alternative, standard_error, estimate): # this could be any number of dimensions (including 0d), but there is # at most one unique non-NaN value alternative = np.atleast_1d(alternative) # can't index 0D object alternative = alternative[np.isfinite(alternative)] alternative = alternative[0] if alternative.size else np.nan return TtestResult(statistic, pvalue, df=df, alternative=alternative, standard_error=standard_error, estimate=estimate) def unpack_TtestResult(res): return (res.statistic, res.pvalue, res.df, res._alternative, res._standard_error, res._estimate) @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, result_to_tuple=unpack_TtestResult, n_outputs=6) def ttest_1samp(a, popmean, axis=0, nan_policy='propagate', alternative="two-sided"): """Calculate the T-test for the mean of ONE group of scores. This is a test for the null hypothesis that the expected value (mean) of a sample of independent observations `a` is equal to the given population mean, `popmean`. Parameters ---------- a : array_like Sample observation. popmean : float or array_like Expected value in null hypothesis. If array_like, then its length along `axis` must equal 1, and it must otherwise be broadcastable with `a`. axis : int or None, optional Axis along which to compute test; default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the mean of the underlying distribution of the sample is different than the given population mean (`popmean`) * 'less': the mean of the underlying distribution of the sample is less than the given population mean (`popmean`) * 'greater': the mean of the underlying distribution of the sample is greater than the given population mean (`popmean`) Returns ------- result : `~scipy.stats._result_classes.TtestResult` An object with the following attributes: statistic : float or array The t-statistic. pvalue : float or array The p-value associated with the given alternative. df : float or array The number of degrees of freedom used in calculation of the t-statistic; this is one less than the size of the sample (``a.shape[axis]``). .. versionadded:: 1.10.0 The object also has the following method: confidence_interval(confidence_level=0.95) Computes a confidence interval around the population mean for the given confidence level. The confidence interval is returned in a ``namedtuple`` with fields `low` and `high`. .. versionadded:: 1.10.0 Notes ----- The statistic is calculated as ``(np.mean(a) - popmean)/se``, where ``se`` is the standard error. Therefore, the statistic will be positive when the sample mean is greater than the population mean and negative when the sample mean is less than the population mean. Examples -------- Suppose we wish to test the null hypothesis that the mean of a population is equal to 0.5. We choose a confidence level of 99%; that is, we will reject the null hypothesis in favor of the alternative if the p-value is less than 0.01. When testing random variates from the standard uniform distribution, which has a mean of 0.5, we expect the data to be consistent with the null hypothesis most of the time. >>> import numpy as np >>> from scipy import stats >>> rng = np.random.default_rng() >>> rvs = stats.uniform.rvs(size=50, random_state=rng) >>> stats.ttest_1samp(rvs, popmean=0.5) TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49) As expected, the p-value of 0.017 is not below our threshold of 0.01, so we cannot reject the null hypothesis. When testing data from the standard *normal* distribution, which has a mean of 0, we would expect the null hypothesis to be rejected. >>> rvs = stats.norm.rvs(size=50, random_state=rng) >>> stats.ttest_1samp(rvs, popmean=0.5) TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49) Indeed, the p-value is lower than our threshold of 0.01, so we reject the null hypothesis in favor of the default "two-sided" alternative: the mean of the population is *not* equal to 0.5. However, suppose we were to test the null hypothesis against the one-sided alternative that the mean of the population is *greater* than 0.5. Since the mean of the standard normal is less than 0.5, we would not expect the null hypothesis to be rejected. >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater') TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49) Unsurprisingly, with a p-value greater than our threshold, we would not reject the null hypothesis. Note that when working with a confidence level of 99%, a true null hypothesis will be rejected approximately 1% of the time. >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng) >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1) >>> np.sum(res.pvalue < 0.01) 1 Indeed, even though all 100 samples above were drawn from the standard uniform distribution, which *does* have a population mean of 0.5, we would mistakenly reject the null hypothesis for one of them. `ttest_1samp` can also compute a confidence interval around the population mean. >>> rvs = stats.norm.rvs(size=50, random_state=rng) >>> res = stats.ttest_1samp(rvs, popmean=0) >>> ci = res.confidence_interval(confidence_level=0.95) >>> ci ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972) The bounds of the 95% confidence interval are the minimum and maximum values of the parameter `popmean` for which the p-value of the test would be 0.05. >>> res = stats.ttest_1samp(rvs, popmean=ci.low) >>> np.testing.assert_allclose(res.pvalue, 0.05) >>> res = stats.ttest_1samp(rvs, popmean=ci.high) >>> np.testing.assert_allclose(res.pvalue, 0.05) Under certain assumptions about the population from which a sample is drawn, the confidence interval with confidence level 95% is expected to contain the true population mean in 95% of sample replications. >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng) >>> res = stats.ttest_1samp(rvs, popmean=0) >>> ci = res.confidence_interval() >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1) >>> contains_pop_mean.sum() 953 """ a, axis = _chk_asarray(a, axis) n = a.shape[axis] df = n - 1 mean = np.mean(a, axis) try: popmean = np.squeeze(popmean, axis=axis) except ValueError as e: raise ValueError("`popmean.shape[axis]` must equal 1.") from e d = mean - popmean v = _var(a, axis, ddof=1) denom = np.sqrt(v / n) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(d, denom) t, prob = _ttest_finish(df, t, alternative) # when nan_policy='omit', `df` can be different for different axis-slices df = np.broadcast_to(df, t.shape)[()] # _axis_nan_policy decorator doesn't play well with strings alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative] return TtestResult(t, prob, df=df, alternative=alternative_num, standard_error=denom, estimate=mean) def _t_confidence_interval(df, t, confidence_level, alternative): # Input validation on `alternative` is already done # We just need IV on confidence_level if confidence_level < 0 or confidence_level > 1: message = "`confidence_level` must be a number between 0 and 1." raise ValueError(message) if alternative < 0: # 'less' p = confidence_level low, high = np.broadcast_arrays(-np.inf, special.stdtrit(df, p)) elif alternative > 0: # 'greater' p = 1 - confidence_level low, high = np.broadcast_arrays(special.stdtrit(df, p), np.inf) elif alternative == 0: # 'two-sided' tail_probability = (1 - confidence_level)/2 p = tail_probability, 1-tail_probability # axis of p must be the zeroth and orthogonal to all the rest p = np.reshape(p, [2] + [1]*np.asarray(df).ndim) low, high = special.stdtrit(df, p) else: # alternative is NaN when input is empty (see _axis_nan_policy) p, nans = np.broadcast_arrays(t, np.nan) low, high = nans, nans return low[()], high[()] def _ttest_finish(df, t, alternative): """Common code between all 3 t-test functions.""" # We use ``stdtr`` directly here as it handles the case when ``nan`` # values are present in the data and masked arrays are passed # while ``t.cdf`` emits runtime warnings. This way ``_ttest_finish`` # can be shared between the ``stats`` and ``mstats`` versions. if alternative == 'less': pval = special.stdtr(df, t) elif alternative == 'greater': pval = special.stdtr(df, -t) elif alternative == 'two-sided': pval = special.stdtr(df, -np.abs(t))*2 else: raise ValueError("alternative must be " "'less', 'greater' or 'two-sided'") if t.ndim == 0: t = t[()] if pval.ndim == 0: pval = pval[()] return t, pval def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative): d = mean1 - mean2 with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(d, denom) t, prob = _ttest_finish(df, t, alternative) return (t, prob) def _unequal_var_ttest_denom(v1, n1, v2, n2): vn1 = v1 / n1 vn2 = v2 / n2 with np.errstate(divide='ignore', invalid='ignore'): df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1)) # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0). # Hence it doesn't matter what df is as long as it's not NaN. df = np.where(np.isnan(df), 1, df) denom = np.sqrt(vn1 + vn2) return df, denom def _equal_var_ttest_denom(v1, n1, v2, n2): # If there is a single observation in one sample, this formula for pooled # variance breaks down because the variance of that sample is undefined. # The pooled variance is still defined, though, because the (n-1) in the # numerator should cancel with the (n-1) in the denominator, leaving only # the sum of squared differences from the mean: zero. v1 = np.where(n1 == 1, 0, v1)[()] v2 = np.where(n2 == 1, 0, v2)[()] df = n1 + n2 - 2.0 svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2)) return df, denom Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue')) def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2, equal_var=True, alternative="two-sided"): r""" T-test for means of two independent samples from descriptive statistics. This is a test for the null hypothesis that two independent samples have identical average (expected) values. Parameters ---------- mean1 : array_like The mean(s) of sample 1. std1 : array_like The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``). nobs1 : array_like The number(s) of observations of sample 1. mean2 : array_like The mean(s) of sample 2. std2 : array_like The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``). nobs2 : array_like The number(s) of observations of sample 2. equal_var : bool, optional If True (default), perform a standard independent 2 sample test that assumes equal population variances [1]_. If False, perform Welch's t-test, which does not assume equal population variance [2]_. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the means of the distributions are unequal. * 'less': the mean of the first distribution is less than the mean of the second distribution. * 'greater': the mean of the first distribution is greater than the mean of the second distribution. .. versionadded:: 1.6.0 Returns ------- statistic : float or array The calculated t-statistics. pvalue : float or array The two-tailed p-value. See Also -------- scipy.stats.ttest_ind Notes ----- The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the standard error. Therefore, the statistic will be positive when `mean1` is greater than `mean2` and negative when `mean1` is less than `mean2`. This method does not check whether any of the elements of `std1` or `std2` are negative. If any elements of the `std1` or `std2` parameters are negative in a call to this method, this method will return the same result as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``, respectively, instead; no exceptions or warnings will be emitted. References ---------- .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test Examples -------- Suppose we have the summary data for two samples, as follows (with the Sample Variance being the corrected sample variance):: Sample Sample Size Mean Variance Sample 1 13 15.0 87.5 Sample 2 11 12.0 39.0 Apply the t-test to this data (with the assumption that the population variances are equal): >>> import numpy as np >>> from scipy.stats import ttest_ind_from_stats >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13, ... mean2=12.0, std2=np.sqrt(39.0), nobs2=11) Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487) For comparison, here is the data from which those summary statistics were taken. With this data, we can compute the same result using `scipy.stats.ttest_ind`: >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26]) >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21]) >>> from scipy.stats import ttest_ind >>> ttest_ind(a, b) Ttest_indResult(statistic=0.905135809331027, pvalue=0.3751996797581486) Suppose we instead have binary data and would like to apply a t-test to compare the proportion of 1s in two independent groups:: Number of Sample Sample Size ones Mean Variance Sample 1 150 30 0.2 0.161073 Sample 2 200 45 0.225 0.175251 The sample mean :math:`\hat{p}` is the proportion of ones in the sample and the variance for a binary observation is estimated by :math:`\hat{p}(1-\hat{p})`. >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150, ... mean2=0.225, std2=np.sqrt(0.175251), nobs2=200) Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541) For comparison, we could compute the t statistic and p-value using arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above. >>> group1 = np.array([1]*30 + [0]*(150-30)) >>> group2 = np.array([1]*45 + [0]*(200-45)) >>> ttest_ind(group1, group2) Ttest_indResult(statistic=-0.5627179589855622, pvalue=0.573989277115258) """ mean1 = np.asarray(mean1) std1 = np.asarray(std1) mean2 = np.asarray(mean2) std2 = np.asarray(std2) if equal_var: df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2) else: df, denom = _unequal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2) res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative) return Ttest_indResult(*res) @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, result_to_tuple=unpack_TtestResult, n_outputs=6) def ttest_ind(a, b, axis=0, equal_var=True, nan_policy='propagate', permutations=None, random_state=None, alternative="two-sided", trim=0): """ Calculate the T-test for the means of *two independent* samples of scores. This is a test for the null hypothesis that 2 independent samples have identical average (expected) values. This test assumes that the populations have identical variances by default. Parameters ---------- a, b : array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int or None, optional Axis along which to compute test. If None, compute over the whole arrays, `a`, and `b`. equal_var : bool, optional If True (default), perform a standard independent 2 sample test that assumes equal population variances [1]_. If False, perform Welch's t-test, which does not assume equal population variance [2]_. .. versionadded:: 0.11.0 nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values The 'omit' option is not currently available for permutation tests or one-sided asympyotic tests. permutations : non-negative int, np.inf, or None (default), optional If 0 or None (default), use the t-distribution to calculate p-values. Otherwise, `permutations` is the number of random permutations that will be used to estimate p-values using a permutation test. If `permutations` equals or exceeds the number of distinct partitions of the pooled data, an exact test is performed instead (i.e. each distinct partition is used exactly once). See Notes for details. .. versionadded:: 1.7.0 random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Pseudorandom number generator state used to generate permutations (used only when `permutations` is not None). .. versionadded:: 1.7.0 alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the means of the distributions underlying the samples are unequal. * 'less': the mean of the distribution underlying the first sample is less than the mean of the distribution underlying the second sample. * 'greater': the mean of the distribution underlying the first sample is greater than the mean of the distribution underlying the second sample. .. versionadded:: 1.6.0 trim : float, optional If nonzero, performs a trimmed (Yuen's) t-test. Defines the fraction of elements to be trimmed from each end of the input samples. If 0 (default), no elements will be trimmed from either side. The number of trimmed elements from each tail is the floor of the trim times the number of elements. Valid range is [0, .5). .. versionadded:: 1.7 Returns ------- result : `~scipy.stats._result_classes.TtestResult` An object with the following attributes: statistic : float or ndarray The t-statistic. pvalue : float or ndarray The p-value associated with the given alternative. df : float or ndarray The number of degrees of freedom used in calculation of the t-statistic. This is always NaN for a permutation t-test. .. versionadded:: 1.11.0 The object also has the following method: confidence_interval(confidence_level=0.95) Computes a confidence interval around the difference in population means for the given confidence level. The confidence interval is returned in a ``namedtuple`` with fields ``low`` and ``high``. When a permutation t-test is performed, the confidence interval is not computed, and fields ``low`` and ``high`` contain NaN. .. versionadded:: 1.11.0 Notes ----- Suppose we observe two independent samples, e.g. flower petal lengths, and we are considering whether the two samples were drawn from the same population (e.g. the same species of flower or two species with similar petal characteristics) or two different populations. The t-test quantifies the difference between the arithmetic means of the two samples. The p-value quantifies the probability of observing as or more extreme values assuming the null hypothesis, that the samples are drawn from populations with the same population means, is true. A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that our observation is not so unlikely to have occurred by chance. Therefore, we do not reject the null hypothesis of equal population means. If the p-value is smaller than our threshold, then we have evidence against the null hypothesis of equal population means. By default, the p-value is determined by comparing the t-statistic of the observed data against a theoretical t-distribution. When ``1 < permutations < binom(n, k)``, where * ``k`` is the number of observations in `a`, * ``n`` is the total number of observations in `a` and `b`, and * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``), the data are pooled (concatenated), randomly assigned to either group `a` or `b`, and the t-statistic is calculated. This process is performed repeatedly (`permutation` times), generating a distribution of the t-statistic under the null hypothesis, and the t-statistic of the observed data is compared to this distribution to determine the p-value. Specifically, the p-value reported is the "achieved significance level" (ASL) as defined in 4.4 of [3]_. Note that there are other ways of estimating p-values using randomized permutation tests; for other options, see the more general `permutation_test`. When ``permutations >= binom(n, k)``, an exact test is performed: the data are partitioned between the groups in each distinct way exactly once. The permutation test can be computationally expensive and not necessarily more accurate than the analytical test, but it does not make strong assumptions about the shape of the underlying distribution. Use of trimming is commonly referred to as the trimmed t-test. At times called Yuen's t-test, this is an extension of Welch's t-test, with the difference being the use of winsorized means in calculation of the variance and the trimmed sample size in calculation of the statistic. Trimming is recommended if the underlying distribution is long-tailed or contaminated with outliers [4]_. The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where ``se`` is the standard error. Therefore, the statistic will be positive when the sample mean of `a` is greater than the sample mean of `b` and negative when the sample mean of `a` is less than the sample mean of `b`. References ---------- .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016). .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR, www.jstor.org/stable/2334299. Accessed 30 Mar. 2021. .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and Performance of the Two-Sample Trimmed t." Biometrika, vol. 60, no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550. Accessed 30 Mar. 2021. Examples -------- >>> import numpy as np >>> from scipy import stats >>> rng = np.random.default_rng() Test with sample with identical means: >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) >>> stats.ttest_ind(rvs1, rvs2) Ttest_indResult(statistic=-0.4390847099199348, pvalue=0.6606952038870015) >>> stats.ttest_ind(rvs1, rvs2, equal_var=False) Ttest_indResult(statistic=-0.4390847099199348, pvalue=0.6606952553131064) `ttest_ind` underestimates p for unequal variances: >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng) >>> stats.ttest_ind(rvs1, rvs3) Ttest_indResult(statistic=-1.6370984482905417, pvalue=0.1019251574705033) >>> stats.ttest_ind(rvs1, rvs3, equal_var=False) Ttest_indResult(statistic=-1.637098448290542, pvalue=0.10202110497954867) When ``n1 != n2``, the equal variance t-statistic is no longer equal to the unequal variance t-statistic: >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng) >>> stats.ttest_ind(rvs1, rvs4) Ttest_indResult(statistic=-1.9481646859513422, pvalue=0.05186270935842703) >>> stats.ttest_ind(rvs1, rvs4, equal_var=False) Ttest_indResult(statistic=-1.3146566100751664, pvalue=0.1913495266513811) T-test with different means, variance, and n: >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng) >>> stats.ttest_ind(rvs1, rvs5) Ttest_indResult(statistic=-2.8415950600298774, pvalue=0.0046418707568707885) >>> stats.ttest_ind(rvs1, rvs5, equal_var=False) Ttest_indResult(statistic=-1.8686598649188084, pvalue=0.06434714193919686) When performing a permutation test, more permutations typically yields more accurate results. Use a ``np.random.Generator`` to ensure reproducibility: >>> stats.ttest_ind(rvs1, rvs5, permutations=10000, ... random_state=rng) Ttest_indResult(statistic=-2.8415950600298774, pvalue=0.0052994700529947) Take these two samples, one of which has an extreme tail. >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3) >>> b = (1.1, 2.9, 4.2) Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example, using 20% trimming, ``trim=.2``, the test will reduce the impact of one (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0. >>> stats.ttest_ind(a, b, trim=.2) Ttest_indResult(statistic=3.4463884028073513, pvalue=0.01369338726499547) """ if not (0 <= trim < .5): raise ValueError("Trimming percentage should be 0 <= `trim` < .5.") NaN = _get_nan(a, b) if a.size == 0 or b.size == 0: # _axis_nan_policy decorator ensures this only happens with 1d input return TtestResult(NaN, NaN, df=NaN, alternative=NaN, standard_error=NaN, estimate=NaN) if permutations is not None and permutations != 0: if trim != 0: raise ValueError("Permutations are currently not supported " "with trimming.") if permutations < 0 or (np.isfinite(permutations) and int(permutations) != permutations): raise ValueError("Permutations must be a non-negative integer.") t, prob = _permutation_ttest(a, b, permutations=permutations, axis=axis, equal_var=equal_var, nan_policy=nan_policy, random_state=random_state, alternative=alternative) df, denom, estimate = NaN, NaN, NaN else: n1 = a.shape[axis] n2 = b.shape[axis] if trim == 0: if equal_var: old_errstate = np.geterr() np.seterr(divide='ignore', invalid='ignore') v1 = _var(a, axis, ddof=1) v2 = _var(b, axis, ddof=1) if equal_var: np.seterr(**old_errstate) m1 = np.mean(a, axis) m2 = np.mean(b, axis) else: v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis) v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis) if equal_var: df, denom = _equal_var_ttest_denom(v1, n1, v2, n2) else: df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2) t, prob = _ttest_ind_from_stats(m1, m2, denom, df, alternative) # when nan_policy='omit', `df` can be different for different axis-slices df = np.broadcast_to(df, t.shape)[()] estimate = m1-m2 # _axis_nan_policy decorator doesn't play well with strings alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative] return TtestResult(t, prob, df=df, alternative=alternative_num, standard_error=denom, estimate=estimate) def _ttest_trim_var_mean_len(a, trim, axis): """Variance, mean, and length of winsorized input along specified axis""" # for use with `ttest_ind` when trimming. # further calculations in this test assume that the inputs are sorted. # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..." a = np.sort(a, axis=axis) # `g` is the number of elements to be replaced on each tail, converted # from a percentage amount of trimming n = a.shape[axis] g = int(n * trim) # Calculate the Winsorized variance of the input samples according to # specified `g` v = _calculate_winsorized_variance(a, g, axis) # the total number of elements in the trimmed samples n -= 2 * g # calculate the g-times trimmed mean, as defined in [4] (1-1) m = trim_mean(a, trim, axis=axis) return v, m, n def _calculate_winsorized_variance(a, g, axis): """Calculates g-times winsorized variance along specified axis""" # it is expected that the input `a` is sorted along the correct axis if g == 0: return _var(a, ddof=1, axis=axis) # move the intended axis to the end that way it is easier to manipulate a_win = np.moveaxis(a, axis, -1) # save where NaNs are for later use. nans_indices = np.any(np.isnan(a_win), axis=-1) # Winsorization and variance calculation are done in one step in [4] # (1-3), but here winsorization is done first; replace the left and # right sides with the repeating value. This can be see in effect in ( # 1-3) in [4], where the leftmost and rightmost tails are replaced with # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in # array indexing. a_win[..., :g] = a_win[..., [g]] a_win[..., -g:] = a_win[..., [-g - 1]] # Determine the variance. In [4], the degrees of freedom is expressed as # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of # page 369, beginning of page 370). This is converted to NumPy's format, # `n - ddof` for use with `np.var`. The result is converted to an # array to accommodate indexing later. var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1)) # with `nan_policy='propagate'`, NaNs may be completely trimmed out # because they were sorted into the tail of the array. In these cases, # replace computed variances with `np.nan`. var_win[nans_indices] = np.nan return var_win def _permutation_distribution_t(data, permutations, size_a, equal_var, random_state=None): """Generation permutation distribution of t statistic""" random_state = check_random_state(random_state) # prepare permutation indices size = data.shape[-1] # number of distinct combinations n_max = special.comb(size, size_a) if permutations < n_max: perm_generator = (random_state.permutation(size) for i in range(permutations)) else: permutations = n_max perm_generator = (np.concatenate(z) for z in _all_partitions(size_a, size-size_a)) t_stat = [] for indices in _batch_generator(perm_generator, batch=50): # get one batch from perm_generator at a time as a list indices = np.array(indices) # generate permutations data_perm = data[..., indices] # move axis indexing permutations to position 0 to broadcast # nicely with t_stat_observed, which doesn't have this dimension data_perm = np.moveaxis(data_perm, -2, 0) a = data_perm[..., :size_a] b = data_perm[..., size_a:] t_stat.append(_calc_t_stat(a, b, equal_var)) t_stat = np.concatenate(t_stat, axis=0) return t_stat, permutations, n_max def _calc_t_stat(a, b, equal_var, axis=-1): """Calculate the t statistic along the given dimension.""" na = a.shape[axis] nb = b.shape[axis] avg_a = np.mean(a, axis=axis) avg_b = np.mean(b, axis=axis) var_a = _var(a, axis=axis, ddof=1) var_b = _var(b, axis=axis, ddof=1) if not equal_var: denom = _unequal_var_ttest_denom(var_a, na, var_b, nb)[1] else: denom = _equal_var_ttest_denom(var_a, na, var_b, nb)[1] return (avg_a-avg_b)/denom def _permutation_ttest(a, b, permutations, axis=0, equal_var=True, nan_policy='propagate', random_state=None, alternative="two-sided"): """ Calculates the T-test for the means of TWO INDEPENDENT samples of scores using permutation methods. This test is similar to `stats.ttest_ind`, except it doesn't rely on an approximate normality assumption since it uses a permutation test. This function is only called from ttest_ind when permutations is not None. Parameters ---------- a, b : array_like The arrays must be broadcastable, except along the dimension corresponding to `axis` (the zeroth, by default). axis : int, optional The axis over which to operate on a and b. permutations : int, optional Number of permutations used to calculate p-value. If greater than or equal to the number of distinct permutations, perform an exact test. equal_var : bool, optional If False, an equal variance (Welch's) t-test is conducted. Otherwise, an ordinary t-test is conducted. random_state : {None, int, `numpy.random.Generator`}, optional If `seed` is None the `numpy.random.Generator` singleton is used. If `seed` is an int, a new ``Generator`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` instance then that instance is used. Pseudorandom number generator state used for generating random permutations. Returns ------- statistic : float or array The calculated t-statistic. pvalue : float or array The p-value. """ random_state = check_random_state(random_state) t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis) na = a.shape[axis] mat = _broadcast_concatenate((a, b), axis=axis) mat = np.moveaxis(mat, axis, -1) t_stat, permutations, n_max = _permutation_distribution_t( mat, permutations, size_a=na, equal_var=equal_var, random_state=random_state) compare = {"less": np.less_equal, "greater": np.greater_equal, "two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))} # Calculate the p-values cmps = compare[alternative](t_stat, t_stat_observed) # Randomized test p-value calculation should use biased estimate; see e.g. # https://www.degruyter.com/document/doi/10.2202/1544-6115.1585/ adjustment = 1 if n_max > permutations else 0 pvalues = (cmps.sum(axis=0) + adjustment) / (permutations + adjustment) # nans propagate naturally in statistic calculation, but need to be # propagated manually into pvalues if nan_policy == 'propagate' and np.isnan(t_stat_observed).any(): if np.ndim(pvalues) == 0: pvalues = np.float64(np.nan) else: pvalues[np.isnan(t_stat_observed)] = np.nan return (t_stat_observed, pvalues) def _get_len(a, axis, msg): try: n = a.shape[axis] except IndexError: raise np.AxisError(axis, a.ndim, msg) from None return n @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, result_to_tuple=unpack_TtestResult, n_outputs=6, paired=True) def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"): """Calculate the t-test on TWO RELATED samples of scores, a and b. This is a test for the null hypothesis that two related or repeated samples have identical average (expected) values. Parameters ---------- a, b : array_like The arrays must have the same shape. axis : int or None, optional Axis along which to compute test. If None, compute over the whole arrays, `a`, and `b`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the means of the distributions underlying the samples are unequal. * 'less': the mean of the distribution underlying the first sample is less than the mean of the distribution underlying the second sample. * 'greater': the mean of the distribution underlying the first sample is greater than the mean of the distribution underlying the second sample. .. versionadded:: 1.6.0 Returns ------- result : `~scipy.stats._result_classes.TtestResult` An object with the following attributes: statistic : float or array The t-statistic. pvalue : float or array The p-value associated with the given alternative. df : float or array The number of degrees of freedom used in calculation of the t-statistic; this is one less than the size of the sample (``a.shape[axis]``). .. versionadded:: 1.10.0 The object also has the following method: confidence_interval(confidence_level=0.95) Computes a confidence interval around the difference in population means for the given confidence level. The confidence interval is returned in a ``namedtuple`` with fields `low` and `high`. .. versionadded:: 1.10.0 Notes ----- Examples for use are scores of the same set of student in different exams, or repeated sampling from the same units. The test measures whether the average score differs significantly across samples (e.g. exams). If we observe a large p-value, for example greater than 0.05 or 0.1 then we cannot reject the null hypothesis of identical average scores. If the p-value is smaller than the threshold, e.g. 1%, 5% or 10%, then we reject the null hypothesis of equal averages. Small p-values are associated with large t-statistics. The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the standard error. Therefore, the t-statistic will be positive when the sample mean of ``a - b`` is greater than zero and negative when the sample mean of ``a - b`` is less than zero. References ---------- https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples Examples -------- >>> import numpy as np >>> from scipy import stats >>> rng = np.random.default_rng() >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng)) >>> stats.ttest_rel(rvs1, rvs2) TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499) # noqa >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng) ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng)) >>> stats.ttest_rel(rvs1, rvs3) TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499) # noqa """ a, b, axis = _chk2_asarray(a, b, axis) na = _get_len(a, axis, "first argument") nb = _get_len(b, axis, "second argument") if na != nb: raise ValueError('unequal length arrays') if na == 0 or nb == 0: # _axis_nan_policy decorator ensures this only happens with 1d input NaN = _get_nan(a, b) return TtestResult(NaN, NaN, df=NaN, alternative=NaN, standard_error=NaN, estimate=NaN) n = a.shape[axis] df = n - 1 d = (a - b).astype(np.float64) v = _var(d, axis, ddof=1) dm = np.mean(d, axis) denom = np.sqrt(v / n) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(dm, denom) t, prob = _ttest_finish(df, t, alternative) # when nan_policy='omit', `df` can be different for different axis-slices df = np.broadcast_to(df, t.shape)[()] # _axis_nan_policy decorator doesn't play well with strings alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative] return TtestResult(t, prob, df=df, alternative=alternative_num, standard_error=denom, estimate=dm) # Map from names to lambda_ values used in power_divergence(). _power_div_lambda_names = { "pearson": 1, "log-likelihood": 0, "freeman-tukey": -0.5, "mod-log-likelihood": -1, "neyman": -2, "cressie-read": 2/3, } def _count(a, axis=None): """Count the number of non-masked elements of an array. This function behaves like `np.ma.count`, but is much faster for ndarrays. """ if hasattr(a, 'count'): num = a.count(axis=axis) if isinstance(num, np.ndarray) and num.ndim == 0: # In some cases, the `count` method returns a scalar array (e.g. # np.array(3)), but we want a plain integer. num = int(num) else: if axis is None: num = a.size else: num = a.shape[axis] return num def _m_broadcast_to(a, shape): if np.ma.isMaskedArray(a): return np.ma.masked_array(np.broadcast_to(a, shape), mask=np.broadcast_to(a.mask, shape)) return np.broadcast_to(a, shape, subok=True) Power_divergenceResult = namedtuple('Power_divergenceResult', ('statistic', 'pvalue')) def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None): """Cressie-Read power divergence statistic and goodness of fit test. This function tests the null hypothesis that the categorical data has the given frequencies, using the Cressie-Read power divergence statistic. Parameters ---------- f_obs : array_like Observed frequencies in each category. f_exp : array_like, optional Expected frequencies in each category. By default the categories are assumed to be equally likely. ddof : int, optional "Delta degrees of freedom": adjustment to the degrees of freedom for the p-value. The p-value is computed using a chi-squared distribution with ``k - 1 - ddof`` degrees of freedom, where `k` is the number of observed frequencies. The default value of `ddof` is 0. axis : int or None, optional The axis of the broadcast result of `f_obs` and `f_exp` along which to apply the test. If axis is None, all values in `f_obs` are treated as a single data set. Default is 0. lambda_ : float or str, optional The power in the Cressie-Read power divergence statistic. The default is 1. For convenience, `lambda_` may be assigned one of the following strings, in which case the corresponding numerical value is used: * ``"pearson"`` (value 1) Pearson's chi-squared statistic. In this case, the function is equivalent to `chisquare`. * ``"log-likelihood"`` (value 0) Log-likelihood ratio. Also known as the G-test [3]_. * ``"freeman-tukey"`` (value -1/2) Freeman-Tukey statistic. * ``"mod-log-likelihood"`` (value -1) Modified log-likelihood ratio. * ``"neyman"`` (value -2) Neyman's statistic. * ``"cressie-read"`` (value 2/3) The power recommended in [5]_. Returns ------- res: Power_divergenceResult An object containing attributes: statistic : float or ndarray The Cressie-Read power divergence test statistic. The value is a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D. pvalue : float or ndarray The p-value of the test. The value is a float if `ddof` and the return value `stat` are scalars. See Also -------- chisquare Notes ----- This test is invalid when the observed or expected frequencies in each category are too small. A typical rule is that all of the observed and expected frequencies should be at least 5. Also, the sum of the observed and expected frequencies must be the same for the test to be valid; `power_divergence` raises an error if the sums do not agree within a relative tolerance of ``1e-8``. When `lambda_` is less than zero, the formula for the statistic involves dividing by `f_obs`, so a warning or error may be generated if any value in `f_obs` is 0. Similarly, a warning or error may be generated if any value in `f_exp` is zero when `lambda_` >= 0. The default degrees of freedom, k-1, are for the case when no parameters of the distribution are estimated. If p parameters are estimated by efficient maximum likelihood then the correct degrees of freedom are k-1-p. If the parameters are estimated in a different way, then the dof can be between k-1-p and k-1. However, it is also possible that the asymptotic distribution is not a chisquare, in which case this test is not appropriate. This function handles masked arrays. If an element of `f_obs` or `f_exp` is masked, then data at that position is ignored, and does not count towards the size of the data set. .. versionadded:: 0.13.0 References ---------- .. [1] Lowry, Richard. "Concepts and Applications of Inferential Statistics". Chapter 8. https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test .. [3] "G-test", https://en.wikipedia.org/wiki/G-test .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and practice of statistics in biological research", New York: Freeman (1981) .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984), pp. 440-464. Examples -------- (See `chisquare` for more examples.) When just `f_obs` is given, it is assumed that the expected frequencies are uniform and given by the mean of the observed frequencies. Here we perform a G-test (i.e. use the log-likelihood ratio statistic): >>> import numpy as np >>> from scipy.stats import power_divergence >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood') (2.006573162632538, 0.84823476779463769) The expected frequencies can be given with the `f_exp` argument: >>> power_divergence([16, 18, 16, 14, 12, 12], ... f_exp=[16, 16, 16, 16, 16, 8], ... lambda_='log-likelihood') (3.3281031458963746, 0.6495419288047497) When `f_obs` is 2-D, by default the test is applied to each column. >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T >>> obs.shape (6, 2) >>> power_divergence(obs, lambda_="log-likelihood") (array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225])) By setting ``axis=None``, the test is applied to all data in the array, which is equivalent to applying the test to the flattened array. >>> power_divergence(obs, axis=None) (23.31034482758621, 0.015975692534127565) >>> power_divergence(obs.ravel()) (23.31034482758621, 0.015975692534127565) `ddof` is the change to make to the default degrees of freedom. >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1) (2.0, 0.73575888234288467) The calculation of the p-values is done by broadcasting the test statistic with `ddof`. >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2]) (2.0, array([ 0.84914504, 0.73575888, 0.5724067 ])) `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared statistics, we must use ``axis=1``: >>> power_divergence([16, 18, 16, 14, 12, 12], ... f_exp=[[16, 16, 16, 16, 16, 8], ... [8, 20, 20, 16, 12, 12]], ... axis=1) (array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846])) """ # Convert the input argument `lambda_` to a numerical value. if isinstance(lambda_, str): if lambda_ not in _power_div_lambda_names: names = repr(list(_power_div_lambda_names.keys()))[1:-1] raise ValueError("invalid string for lambda_: {!r}. " "Valid strings are {}".format(lambda_, names)) lambda_ = _power_div_lambda_names[lambda_] elif lambda_ is None: lambda_ = 1 f_obs = np.asanyarray(f_obs) f_obs_float = f_obs.astype(np.float64) if f_exp is not None: f_exp = np.asanyarray(f_exp) bshape = np.broadcast_shapes(f_obs_float.shape, f_exp.shape) f_obs_float = _m_broadcast_to(f_obs_float, bshape) f_exp = _m_broadcast_to(f_exp, bshape) rtol = 1e-8 # to pass existing tests with np.errstate(invalid='ignore'): f_obs_sum = f_obs_float.sum(axis=axis) f_exp_sum = f_exp.sum(axis=axis) relative_diff = (np.abs(f_obs_sum - f_exp_sum) / np.minimum(f_obs_sum, f_exp_sum)) diff_gt_tol = (relative_diff > rtol).any() if diff_gt_tol: msg = (f"For each axis slice, the sum of the observed " f"frequencies must agree with the sum of the " f"expected frequencies to a relative tolerance " f"of {rtol}, but the percent differences are:\n" f"{relative_diff}") raise ValueError(msg) else: # Ignore 'invalid' errors so the edge case of a data set with length 0 # is handled without spurious warnings. with np.errstate(invalid='ignore'): f_exp = f_obs.mean(axis=axis, keepdims=True) # `terms` is the array of terms that are summed along `axis` to create # the test statistic. We use some specialized code for a few special # cases of lambda_. if lambda_ == 1: # Pearson's chi-squared statistic terms = (f_obs_float - f_exp)**2 / f_exp elif lambda_ == 0: # Log-likelihood ratio (i.e. G-test) terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp) elif lambda_ == -1: # Modified log-likelihood ratio terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs) else: # General Cressie-Read power divergence. terms = f_obs * ((f_obs / f_exp)**lambda_ - 1) terms /= 0.5 * lambda_ * (lambda_ + 1) stat = terms.sum(axis=axis) num_obs = _count(terms, axis=axis) ddof = asarray(ddof) p = distributions.chi2.sf(stat, num_obs - 1 - ddof) return Power_divergenceResult(stat, p) def chisquare(f_obs, f_exp=None, ddof=0, axis=0): """Calculate a one-way chi-square test. The chi-square test tests the null hypothesis that the categorical data has the given frequencies. Parameters ---------- f_obs : array_like Observed frequencies in each category. f_exp : array_like, optional Expected frequencies in each category. By default the categories are assumed to be equally likely. ddof : int, optional "Delta degrees of freedom": adjustment to the degrees of freedom for the p-value. The p-value is computed using a chi-squared distribution with ``k - 1 - ddof`` degrees of freedom, where `k` is the number of observed frequencies. The default value of `ddof` is 0. axis : int or None, optional The axis of the broadcast result of `f_obs` and `f_exp` along which to apply the test. If axis is None, all values in `f_obs` are treated as a single data set. Default is 0. Returns ------- res: Power_divergenceResult An object containing attributes: chisq : float or ndarray The chi-squared test statistic. The value is a float if `axis` is None or `f_obs` and `f_exp` are 1-D. pvalue : float or ndarray The p-value of the test. The value is a float if `ddof` and the return value `chisq` are scalars. See Also -------- scipy.stats.power_divergence scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table. scipy.stats.barnard_exact : An unconditional exact test. An alternative to chi-squared test for small sample sizes. Notes ----- This test is invalid when the observed or expected frequencies in each category are too small. A typical rule is that all of the observed and expected frequencies should be at least 5. According to [3]_, the total number of samples is recommended to be greater than 13, otherwise exact tests (such as Barnard's Exact test) should be used because they do not overreject. Also, the sum of the observed and expected frequencies must be the same for the test to be valid; `chisquare` raises an error if the sums do not agree within a relative tolerance of ``1e-8``. The default degrees of freedom, k-1, are for the case when no parameters of the distribution are estimated. If p parameters are estimated by efficient maximum likelihood then the correct degrees of freedom are k-1-p. If the parameters are estimated in a different way, then the dof can be between k-1-p and k-1. However, it is also possible that the asymptotic distribution is not chi-square, in which case this test is not appropriate. References ---------- .. [1] Lowry, Richard. "Concepts and Applications of Inferential Statistics". Chapter 8. https://web.archive.org/web/20171022032306/http://vassarstats.net:80/textbook/ch8pt1.html .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test .. [3] Pearson, Karl. "On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50 (1900), pp. 157-175. .. [4] Mannan, R. William and E. Charles. Meslow. "Bird populations and vegetation characteristics in managed and old-growth forests, northeastern Oregon." Journal of Wildlife Management 48, 1219-1238, :doi:`10.2307/3801783`, 1984. Examples -------- In [4]_, bird foraging behavior was investigated in an old-growth forest of Oregon. In the forest, 44% of the canopy volume was Douglas fir, 24% was ponderosa pine, 29% was grand fir, and 3% was western larch. The authors observed the behavior of several species of birds, one of which was the red-breasted nuthatch. They made 189 observations of this species foraging, recording 43 ("23%") of observations in Douglas fir, 52 ("28%") in ponderosa pine, 54 ("29%") in grand fir, and 40 ("21%") in western larch. Using a chi-square test, we can test the null hypothesis that the proportions of foraging events are equal to the proportions of canopy volume. The authors of the paper considered a p-value less than 1% to be significant. Using the above proportions of canopy volume and observed events, we can infer expected frequencies. >>> import numpy as np >>> f_exp = np.array([44, 24, 29, 3]) / 100 * 189 The observed frequencies of foraging were: >>> f_obs = np.array([43, 52, 54, 40]) We can now compare the observed frequencies with the expected frequencies. >>> from scipy.stats import chisquare >>> chisquare(f_obs=f_obs, f_exp=f_exp) Power_divergenceResult(statistic=228.23515947653874, pvalue=3.3295585338846486e-49) The p-value is well below the chosen significance level. Hence, the authors considered the difference to be significant and concluded that the relative proportions of foraging events were not the same as the relative proportions of tree canopy volume. Following are other generic examples to demonstrate how the other parameters can be used. When just `f_obs` is given, it is assumed that the expected frequencies are uniform and given by the mean of the observed frequencies. >>> chisquare([16, 18, 16, 14, 12, 12]) Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956) With `f_exp` the expected frequencies can be given. >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8]) Power_divergenceResult(statistic=3.5, pvalue=0.62338762774958223) When `f_obs` is 2-D, by default the test is applied to each column. >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T >>> obs.shape (6, 2) >>> chisquare(obs) Power_divergenceResult(statistic=array([2. , 6.66666667]), pvalue=array([0.84914504, 0.24663415])) By setting ``axis=None``, the test is applied to all data in the array, which is equivalent to applying the test to the flattened array. >>> chisquare(obs, axis=None) Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565) >>> chisquare(obs.ravel()) Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758) `ddof` is the change to make to the default degrees of freedom. >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1) Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847) The calculation of the p-values is done by broadcasting the chi-squared statistic with `ddof`. >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0,1,2]) Power_divergenceResult(statistic=2.0, pvalue=array([0.84914504, 0.73575888, 0.5724067 ])) `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared statistics, we use ``axis=1``: >>> chisquare([16, 18, 16, 14, 12, 12], ... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]], ... axis=1) Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846])) """ # noqa return power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_="pearson") KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'], ['statistic_location', 'statistic_sign']) def _compute_dplus(cdfvals, x): """Computes D+ as used in the Kolmogorov-Smirnov test. Parameters ---------- cdfvals : array_like Sorted array of CDF values between 0 and 1 x: array_like Sorted array of the stochastic variable itself Returns ------- res: Pair with the following elements: - The maximum distance of the CDF values below Uniform(0, 1). - The location at which the maximum is reached. """ n = len(cdfvals) dplus = (np.arange(1.0, n + 1) / n - cdfvals) amax = dplus.argmax() loc_max = x[amax] return (dplus[amax], loc_max) def _compute_dminus(cdfvals, x): """Computes D- as used in the Kolmogorov-Smirnov test. Parameters ---------- cdfvals : array_like Sorted array of CDF values between 0 and 1 x: array_like Sorted array of the stochastic variable itself Returns ------- res: Pair with the following elements: - Maximum distance of the CDF values above Uniform(0, 1) - The location at which the maximum is reached. """ n = len(cdfvals) dminus = (cdfvals - np.arange(0.0, n)/n) amax = dminus.argmax() loc_max = x[amax] return (dminus[amax], loc_max) @_rename_parameter("mode", "method") def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto'): """ Performs the one-sample Kolmogorov-Smirnov test for goodness of fit. This test compares the underlying distribution F(x) of a sample against a given continuous distribution G(x). See Notes for a description of the available null and alternative hypotheses. Parameters ---------- x : array_like a 1-D array of observations of iid random variables. cdf : callable callable used to calculate the cdf. args : tuple, sequence, optional Distribution parameters, used with `cdf`. alternative : {'two-sided', 'less', 'greater'}, optional Defines the null and alternative hypotheses. Default is 'two-sided'. Please see explanations in the Notes below. method : {'auto', 'exact', 'approx', 'asymp'}, optional Defines the distribution used for calculating the p-value. The following options are available (default is 'auto'): * 'auto' : selects one of the other options. * 'exact' : uses the exact distribution of test statistic. * 'approx' : approximates the two-sided probability with twice the one-sided probability * 'asymp': uses asymptotic distribution of test statistic Returns ------- res: KstestResult An object containing attributes: statistic : float KS test statistic, either D+, D-, or D (the maximum of the two) pvalue : float One-tailed or two-tailed p-value. statistic_location : float Value of `x` corresponding with the KS statistic; i.e., the distance between the empirical distribution function and the hypothesized cumulative distribution function is measured at this observation. statistic_sign : int +1 if the KS statistic is the maximum positive difference between the empirical distribution function and the hypothesized cumulative distribution function (D+); -1 if the KS statistic is the maximum negative difference (D-). See Also -------- ks_2samp, kstest Notes ----- There are three options for the null and corresponding alternative hypothesis that can be selected using the `alternative` parameter. - `two-sided`: The null hypothesis is that the two distributions are identical, F(x)=G(x) for all x; the alternative is that they are not identical. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the alternative is that F(x) < G(x) for at least one x. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the alternative is that F(x) > G(x) for at least one x. Note that the alternative hypotheses describe the *CDFs* of the underlying distributions, not the observed values. For example, suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in x1 tend to be less than those in x2. Examples -------- Suppose we wish to test the null hypothesis that a sample is distributed according to the standard normal. We choose a confidence level of 95%; that is, we will reject the null hypothesis in favor of the alternative if the p-value is less than 0.05. When testing uniformly distributed data, we would expect the null hypothesis to be rejected. >>> import numpy as np >>> from scipy import stats >>> rng = np.random.default_rng() >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng), ... stats.norm.cdf) KstestResult(statistic=0.5001899973268688, pvalue=1.1616392184763533e-23) Indeed, the p-value is lower than our threshold of 0.05, so we reject the null hypothesis in favor of the default "two-sided" alternative: the data are *not* distributed according to the standard normal. When testing random variates from the standard normal distribution, we expect the data to be consistent with the null hypothesis most of the time. >>> x = stats.norm.rvs(size=100, random_state=rng) >>> stats.ks_1samp(x, stats.norm.cdf) KstestResult(statistic=0.05345882212970396, pvalue=0.9227159037744717) As expected, the p-value of 0.92 is not below our threshold of 0.05, so we cannot reject the null hypothesis. Suppose, however, that the random variates are distributed according to a normal distribution that is shifted toward greater values. In this case, the cumulative density function (CDF) of the underlying distribution tends to be *less* than the CDF of the standard normal. Therefore, we would expect the null hypothesis to be rejected with ``alternative='less'``: >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng) >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less') KstestResult(statistic=0.17482387821055168, pvalue=0.001913921057766743) and indeed, with p-value smaller than our threshold, we reject the null hypothesis in favor of the alternative. """ mode = method alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( alternative.lower()[0], alternative) if alternative not in ['two-sided', 'greater', 'less']: raise ValueError("Unexpected alternative %s" % alternative) if np.ma.is_masked(x): x = x.compressed() N = len(x) x = np.sort(x) cdfvals = cdf(x, *args) if alternative == 'greater': Dplus, d_location = _compute_dplus(cdfvals, x) return KstestResult(Dplus, distributions.ksone.sf(Dplus, N), statistic_location=d_location, statistic_sign=1) if alternative == 'less': Dminus, d_location = _compute_dminus(cdfvals, x) return KstestResult(Dminus, distributions.ksone.sf(Dminus, N), statistic_location=d_location, statistic_sign=-1) # alternative == 'two-sided': Dplus, dplus_location = _compute_dplus(cdfvals, x) Dminus, dminus_location = _compute_dminus(cdfvals, x) if Dplus > Dminus: D = Dplus d_location = dplus_location d_sign = 1 else: D = Dminus d_location = dminus_location d_sign = -1 if mode == 'auto': # Always select exact mode = 'exact' if mode == 'exact': prob = distributions.kstwo.sf(D, N) elif mode == 'asymp': prob = distributions.kstwobign.sf(D * np.sqrt(N)) else: # mode == 'approx' prob = 2 * distributions.ksone.sf(D, N) prob = np.clip(prob, 0, 1) return KstestResult(D, prob, statistic_location=d_location, statistic_sign=d_sign) Ks_2sampResult = KstestResult def _compute_prob_outside_square(n, h): """ Compute the proportion of paths that pass outside the two diagonal lines. Parameters ---------- n : integer n > 0 h : integer 0 <= h <= n Returns ------- p : float The proportion of paths that pass outside the lines x-y = +/-h. """ # Compute Pr(D_{n,n} >= h/n) # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... ) # / binom(2n, n) # This formulation exhibits subtractive cancellation. # Instead divide each term by binom(2n, n), then factor common terms # and use a Horner-like algorithm # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...))))) P = 0.0 k = int(np.floor(n / h)) while k >= 0: p1 = 1.0 # Each of the Ai terms has numerator and denominator with # h simple terms. for j in range(h): p1 = (n - k * h - j) * p1 / (n + k * h + j + 1) P = p1 * (1.0 - P) k -= 1 return 2 * P def _count_paths_outside_method(m, n, g, h): """Count the number of paths that pass outside the specified diagonal. Parameters ---------- m : integer m > 0 n : integer n > 0 g : integer g is greatest common divisor of m and n h : integer 0 <= h <= lcm(m,n) Returns ------- p : float The number of paths that go low. The calculation may overflow - check for a finite answer. Notes ----- Count the integer lattice paths from (0, 0) to (m, n), which at some point (x, y) along the path, satisfy: m*y <= n*x - h*g The paths make steps of size +1 in either positive x or positive y directions. We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk. Hodges, J.L. Jr., "The Significance Probability of the Smirnov Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-86. """ # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n) # B(x, y) = #{paths from (0,0) to (x,y) without # previously crossing the boundary} # = binom(x, y) - #{paths which already reached the boundary} # Multiply by the number of path extensions going from (x, y) to (m, n) # Sum. # Probability is symmetrical in m, n. Computation below assumes m >= n. if m < n: m, n = n, m mg = m // g ng = n // g # Not every x needs to be considered. # xj holds the list of x values to be checked. # Wherever n*x/m + ng*h crosses an integer lxj = n + (mg-h)//mg xj = [(h + mg * j + ng-1)//ng for j in range(lxj)] # B is an array just holding a few values of B(x,y), the ones needed. # B[j] == B(x_j, j) if lxj == 0: return special.binom(m + n, n) B = np.zeros(lxj) B[0] = 1 # Compute the B(x, y) terms for j in range(1, lxj): Bj = special.binom(xj[j] + j, j) for i in range(j): bin = special.binom(xj[j] - xj[i] + j - i, j-i) Bj -= bin * B[i] B[j] = Bj # Compute the number of path extensions... num_paths = 0 for j in range(lxj): bin = special.binom((m-xj[j]) + (n - j), n-j) term = B[j] * bin num_paths += term return num_paths def _attempt_exact_2kssamp(n1, n2, g, d, alternative): """Attempts to compute the exact 2sample probability. n1, n2 are the sample sizes g is the gcd(n1, n2) d is the computed max difference in ECDFs Returns (success, d, probability) """ lcm = (n1 // g) * n2 h = int(np.round(d * lcm)) d = h * 1.0 / lcm if h == 0: return True, d, 1.0 saw_fp_error, prob = False, np.nan try: with np.errstate(invalid="raise", over="raise"): if alternative == 'two-sided': if n1 == n2: prob = _compute_prob_outside_square(n1, h) else: prob = _compute_outer_prob_inside_method(n1, n2, g, h) else: if n1 == n2: # prob = binom(2n, n-h) / binom(2n, n) # Evaluating in that form incurs roundoff errors # from special.binom. Instead calculate directly jrange = np.arange(h) prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0)) else: with np.errstate(over='raise'): num_paths = _count_paths_outside_method(n1, n2, g, h) bin = special.binom(n1 + n2, n1) if num_paths > bin or np.isinf(bin): saw_fp_error = True else: prob = num_paths / bin except (FloatingPointError, OverflowError): saw_fp_error = True if saw_fp_error: return False, d, np.nan if not (0 <= prob <= 1): return False, d, prob return True, d, prob @_rename_parameter("mode", "method") def ks_2samp(data1, data2, alternative='two-sided', method='auto'): """ Performs the two-sample Kolmogorov-Smirnov test for goodness of fit. This test compares the underlying continuous distributions F(x) and G(x) of two independent samples. See Notes for a description of the available null and alternative hypotheses. Parameters ---------- data1, data2 : array_like, 1-Dimensional Two arrays of sample observations assumed to be drawn from a continuous distribution, sample sizes can be different. alternative : {'two-sided', 'less', 'greater'}, optional Defines the null and alternative hypotheses. Default is 'two-sided'. Please see explanations in the Notes below. method : {'auto', 'exact', 'asymp'}, optional Defines the method used for calculating the p-value. The following options are available (default is 'auto'): * 'auto' : use 'exact' for small size arrays, 'asymp' for large * 'exact' : use exact distribution of test statistic * 'asymp' : use asymptotic distribution of test statistic Returns ------- res: KstestResult An object containing attributes: statistic : float KS test statistic. pvalue : float One-tailed or two-tailed p-value. statistic_location : float Value from `data1` or `data2` corresponding with the KS statistic; i.e., the distance between the empirical distribution functions is measured at this observation. statistic_sign : int +1 if the empirical distribution function of `data1` exceeds the empirical distribution function of `data2` at `statistic_location`, otherwise -1. See Also -------- kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp Notes ----- There are three options for the null and corresponding alternative hypothesis that can be selected using the `alternative` parameter. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the alternative is that F(x) < G(x) for at least one x. The statistic is the magnitude of the minimum (most negative) difference between the empirical distribution functions of the samples. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the alternative is that F(x) > G(x) for at least one x. The statistic is the maximum (most positive) difference between the empirical distribution functions of the samples. - `two-sided`: The null hypothesis is that the two distributions are identical, F(x)=G(x) for all x; the alternative is that they are not identical. The statistic is the maximum absolute difference between the empirical distribution functions of the samples. Note that the alternative hypotheses describe the *CDFs* of the underlying distributions, not the observed values of the data. For example, suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in x1 tend to be less than those in x2. If the KS statistic is large, then the p-value will be small, and this may be taken as evidence against the null hypothesis in favor of the alternative. If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value, that is, the probability under the null hypothesis of obtaining a test statistic value as extreme as the value computed from the data. If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is used to compute an approximate p-value. If ``method='auto'``, an exact p-value computation is attempted if both sample sizes are less than 10000; otherwise, the asymptotic method is used. In any case, if an exact p-value calculation is attempted and fails, a warning will be emitted, and the asymptotic p-value will be returned. The 'two-sided' 'exact' computation computes the complementary probability and then subtracts from 1. As such, the minimum probability it can return is about 1e-16. While the algorithm itself is exact, numerical errors may accumulate for large sample sizes. It is most suited to situations in which one of the sample sizes is only a few thousand. We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_. References ---------- .. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-86. Examples -------- Suppose we wish to test the null hypothesis that two samples were drawn from the same distribution. We choose a confidence level of 95%; that is, we will reject the null hypothesis in favor of the alternative if the p-value is less than 0.05. If the first sample were drawn from a uniform distribution and the second were drawn from the standard normal, we would expect the null hypothesis to be rejected. >>> import numpy as np >>> from scipy import stats >>> rng = np.random.default_rng() >>> sample1 = stats.uniform.rvs(size=100, random_state=rng) >>> sample2 = stats.norm.rvs(size=110, random_state=rng) >>> stats.ks_2samp(sample1, sample2) KstestResult(statistic=0.5454545454545454, pvalue=7.37417839555191e-15) Indeed, the p-value is lower than our threshold of 0.05, so we reject the null hypothesis in favor of the default "two-sided" alternative: the data were *not* drawn from the same distribution. When both samples are drawn from the same distribution, we expect the data to be consistent with the null hypothesis most of the time. >>> sample1 = stats.norm.rvs(size=105, random_state=rng) >>> sample2 = stats.norm.rvs(size=95, random_state=rng) >>> stats.ks_2samp(sample1, sample2) KstestResult(statistic=0.10927318295739348, pvalue=0.5438289009927495) As expected, the p-value of 0.54 is not below our threshold of 0.05, so we cannot reject the null hypothesis. Suppose, however, that the first sample were drawn from a normal distribution shifted toward greater values. In this case, the cumulative density function (CDF) of the underlying distribution tends to be *less* than the CDF underlying the second sample. Therefore, we would expect the null hypothesis to be rejected with ``alternative='less'``: >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng) >>> stats.ks_2samp(sample1, sample2, alternative='less') KstestResult(statistic=0.4055137844611529, pvalue=3.5474563068855554e-08) and indeed, with p-value smaller than our threshold, we reject the null hypothesis in favor of the alternative. """ mode = method if mode not in ['auto', 'exact', 'asymp']: raise ValueError(f'Invalid value for mode: {mode}') alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( alternative.lower()[0], alternative) if alternative not in ['two-sided', 'less', 'greater']: raise ValueError(f'Invalid value for alternative: {alternative}') MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N if np.ma.is_masked(data1): data1 = data1.compressed() if np.ma.is_masked(data2): data2 = data2.compressed() data1 = np.sort(data1) data2 = np.sort(data2) n1 = data1.shape[0] n2 = data2.shape[0] if min(n1, n2) == 0: raise ValueError('Data passed to ks_2samp must not be empty') data_all = np.concatenate([data1, data2]) # using searchsorted solves equal data problem cdf1 = np.searchsorted(data1, data_all, side='right') / n1 cdf2 = np.searchsorted(data2, data_all, side='right') / n2 cddiffs = cdf1 - cdf2 # Identify the location of the statistic argminS = np.argmin(cddiffs) argmaxS = np.argmax(cddiffs) loc_minS = data_all[argminS] loc_maxS = data_all[argmaxS] # Ensure sign of minS is not negative. minS = np.clip(-cddiffs[argminS], 0, 1) maxS = cddiffs[argmaxS] if alternative == 'less' or (alternative == 'two-sided' and minS > maxS): d = minS d_location = loc_minS d_sign = -1 else: d = maxS d_location = loc_maxS d_sign = 1 g = gcd(n1, n2) n1g = n1 // g n2g = n2 // g prob = -np.inf if mode == 'auto': mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp' elif mode == 'exact': # If lcm(n1, n2) is too big, switch from exact to asymp if n1g >= np.iinfo(np.int32).max / n2g: mode = 'asymp' warnings.warn( f"Exact ks_2samp calculation not possible with samples sizes " f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning, stacklevel=3) if mode == 'exact': success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative) if not success: mode = 'asymp' warnings.warn(f"ks_2samp: Exact calculation unsuccessful. " f"Switching to method={mode}.", RuntimeWarning, stacklevel=3) if mode == 'asymp': # The product n1*n2 is large. Use Smirnov's asymptoptic formula. # Ensure float to avoid overflow in multiplication # sorted because the one-sided formula is not symmetric in n1, n2 m, n = sorted([float(n1), float(n2)], reverse=True) en = m * n / (m + n) if alternative == 'two-sided': prob = distributions.kstwo.sf(d, np.round(en)) else: z = np.sqrt(en) * d # Use Hodges' suggested approximation Eqn 5.3 # Requires m to be the larger of (n1, n2) expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0 prob = np.exp(expt) prob = np.clip(prob, 0, 1) return KstestResult(d, prob, statistic_location=d_location, statistic_sign=d_sign) def _parse_kstest_args(data1, data2, args, N): # kstest allows many different variations of arguments. # Pull out the parsing into a separate function # (xvals, yvals, ) # 2sample # (xvals, cdf function,..) # (xvals, name of distribution, ...) # (name of distribution, name of distribution, ...) # Returns xvals, yvals, cdf # where cdf is a cdf function, or None # and yvals is either an array_like of values, or None # and xvals is array_like. rvsfunc, cdf = None, None if isinstance(data1, str): rvsfunc = getattr(distributions, data1).rvs elif callable(data1): rvsfunc = data1 if isinstance(data2, str): cdf = getattr(distributions, data2).cdf data2 = None elif callable(data2): cdf = data2 data2 = None data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1) return data1, data2, cdf @_rename_parameter("mode", "method") def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'): """ Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for goodness of fit. The one-sample test compares the underlying distribution F(x) of a sample against a given distribution G(x). The two-sample test compares the underlying distributions of two independent samples. Both tests are valid only for continuous distributions. Parameters ---------- rvs : str, array_like, or callable If an array, it should be a 1-D array of observations of random variables. If a callable, it should be a function to generate random variables; it is required to have a keyword argument `size`. If a string, it should be the name of a distribution in `scipy.stats`, which will be used to generate random variables. cdf : str, array_like or callable If array_like, it should be a 1-D array of observations of random variables, and the two-sample test is performed (and rvs must be array_like). If a callable, that callable is used to calculate the cdf. If a string, it should be the name of a distribution in `scipy.stats`, which will be used as the cdf function. args : tuple, sequence, optional Distribution parameters, used if `rvs` or `cdf` are strings or callables. N : int, optional Sample size if `rvs` is string or callable. Default is 20. alternative : {'two-sided', 'less', 'greater'}, optional Defines the null and alternative hypotheses. Default is 'two-sided'. Please see explanations in the Notes below. method : {'auto', 'exact', 'approx', 'asymp'}, optional Defines the distribution used for calculating the p-value. The following options are available (default is 'auto'): * 'auto' : selects one of the other options. * 'exact' : uses the exact distribution of test statistic. * 'approx' : approximates the two-sided probability with twice the one-sided probability * 'asymp': uses asymptotic distribution of test statistic Returns ------- res: KstestResult An object containing attributes: statistic : float KS test statistic, either D+, D-, or D (the maximum of the two) pvalue : float One-tailed or two-tailed p-value. statistic_location : float In a one-sample test, this is the value of `rvs` corresponding with the KS statistic; i.e., the distance between the empirical distribution function and the hypothesized cumulative distribution function is measured at this observation. In a two-sample test, this is the value from `rvs` or `cdf` corresponding with the KS statistic; i.e., the distance between the empirical distribution functions is measured at this observation. statistic_sign : int In a one-sample test, this is +1 if the KS statistic is the maximum positive difference between the empirical distribution function and the hypothesized cumulative distribution function (D+); it is -1 if the KS statistic is the maximum negative difference (D-). In a two-sample test, this is +1 if the empirical distribution function of `rvs` exceeds the empirical distribution function of `cdf` at `statistic_location`, otherwise -1. See Also -------- ks_1samp, ks_2samp Notes ----- There are three options for the null and corresponding alternative hypothesis that can be selected using the `alternative` parameter. - `two-sided`: The null hypothesis is that the two distributions are identical, F(x)=G(x) for all x; the alternative is that they are not identical. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the alternative is that F(x) < G(x) for at least one x. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the alternative is that F(x) > G(x) for at least one x. Note that the alternative hypotheses describe the *CDFs* of the underlying distributions, not the observed values. For example, suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in x1 tend to be less than those in x2. Examples -------- Suppose we wish to test the null hypothesis that a sample is distributed according to the standard normal. We choose a confidence level of 95%; that is, we will reject the null hypothesis in favor of the alternative if the p-value is less than 0.05. When testing uniformly distributed data, we would expect the null hypothesis to be rejected. >>> import numpy as np >>> from scipy import stats >>> rng = np.random.default_rng() >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng), ... stats.norm.cdf) KstestResult(statistic=0.5001899973268688, pvalue=1.1616392184763533e-23) Indeed, the p-value is lower than our threshold of 0.05, so we reject the null hypothesis in favor of the default "two-sided" alternative: the data are *not* distributed according to the standard normal. When testing random variates from the standard normal distribution, we expect the data to be consistent with the null hypothesis most of the time. >>> x = stats.norm.rvs(size=100, random_state=rng) >>> stats.kstest(x, stats.norm.cdf) KstestResult(statistic=0.05345882212970396, pvalue=0.9227159037744717) As expected, the p-value of 0.92 is not below our threshold of 0.05, so we cannot reject the null hypothesis. Suppose, however, that the random variates are distributed according to a normal distribution that is shifted toward greater values. In this case, the cumulative density function (CDF) of the underlying distribution tends to be *less* than the CDF of the standard normal. Therefore, we would expect the null hypothesis to be rejected with ``alternative='less'``: >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng) >>> stats.kstest(x, stats.norm.cdf, alternative='less') KstestResult(statistic=0.17482387821055168, pvalue=0.001913921057766743) and indeed, with p-value smaller than our threshold, we reject the null hypothesis in favor of the alternative. For convenience, the previous test can be performed using the name of the distribution as the second argument. >>> stats.kstest(x, "norm", alternative='less') KstestResult(statistic=0.17482387821055168, pvalue=0.001913921057766743) The examples above have all been one-sample tests identical to those performed by `ks_1samp`. Note that `kstest` can also perform two-sample tests identical to those performed by `ks_2samp`. For example, when two samples are drawn from the same distribution, we expect the data to be consistent with the null hypothesis most of the time. >>> sample1 = stats.laplace.rvs(size=105, random_state=rng) >>> sample2 = stats.laplace.rvs(size=95, random_state=rng) >>> stats.kstest(sample1, sample2) KstestResult(statistic=0.11779448621553884, pvalue=0.4494256912629795) As expected, the p-value of 0.45 is not below our threshold of 0.05, so we cannot reject the null hypothesis. """ # to not break compatibility with existing code if alternative == 'two_sided': alternative = 'two-sided' if alternative not in ['two-sided', 'greater', 'less']: raise ValueError("Unexpected alternative %s" % alternative) xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N) if cdf: return ks_1samp(xvals, cdf, args=args, alternative=alternative, method=method) return ks_2samp(xvals, yvals, alternative=alternative, method=method) def tiecorrect(rankvals): """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests. Parameters ---------- rankvals : array_like A 1-D sequence of ranks. Typically this will be the array returned by `~scipy.stats.rankdata`. Returns ------- factor : float Correction factor for U or H. See Also -------- rankdata : Assign ranks to the data mannwhitneyu : Mann-Whitney rank test kruskal : Kruskal-Wallis H test References ---------- .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Examples -------- >>> from scipy.stats import tiecorrect, rankdata >>> tiecorrect([1, 2.5, 2.5, 4]) 0.9 >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4]) >>> ranks array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5]) >>> tiecorrect(ranks) 0.9833333333333333 """ arr = np.sort(rankvals) idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0] cnt = np.diff(idx).astype(np.float64) size = np.float64(arr.size) return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size) RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue')) @_axis_nan_policy_factory(RanksumsResult, n_samples=2) def ranksums(x, y, alternative='two-sided'): """Compute the Wilcoxon rank-sum statistic for two samples. The Wilcoxon rank-sum test tests the null hypothesis that two sets of measurements are drawn from the same distribution. The alternative hypothesis is that values in one sample are more likely to be larger than the values in the other sample. This test should be used to compare two samples from continuous distributions. It does not handle ties between measurements in x and y. For tie-handling and an optional continuity correction see `scipy.stats.mannwhitneyu`. Parameters ---------- x,y : array_like The data from the two samples. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': one of the distributions (underlying `x` or `y`) is stochastically greater than the other. * 'less': the distribution underlying `x` is stochastically less than the distribution underlying `y`. * 'greater': the distribution underlying `x` is stochastically greater than the distribution underlying `y`. .. versionadded:: 1.7.0 Returns ------- statistic : float The test statistic under the large-sample approximation that the rank sum statistic is normally distributed. pvalue : float The p-value of the test. References ---------- .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test Examples -------- We can test the hypothesis that two independent unequal-sized samples are drawn from the same distribution with computing the Wilcoxon rank-sum statistic. >>> import numpy as np >>> from scipy.stats import ranksums >>> rng = np.random.default_rng() >>> sample1 = rng.uniform(-1, 1, 200) >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution >>> ranksums(sample1, sample2) RanksumsResult(statistic=-7.887059, pvalue=3.09390448e-15) # may vary >>> ranksums(sample1, sample2, alternative='less') RanksumsResult(statistic=-7.750585297581713, pvalue=4.573497606342543e-15) # may vary >>> ranksums(sample1, sample2, alternative='greater') RanksumsResult(statistic=-7.750585297581713, pvalue=0.9999999999999954) # may vary The p-value of less than ``0.05`` indicates that this test rejects the hypothesis at the 5% significance level. """ x, y = map(np.asarray, (x, y)) n1 = len(x) n2 = len(y) alldata = np.concatenate((x, y)) ranked = rankdata(alldata) x = ranked[:n1] s = np.sum(x, axis=0) expected = n1 * (n1+n2+1) / 2.0 z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0) z, prob = _normtest_finish(z, alternative) return RanksumsResult(z, prob) KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue')) @_axis_nan_policy_factory(KruskalResult, n_samples=None) def kruskal(*samples, nan_policy='propagate'): """Compute the Kruskal-Wallis H-test for independent samples. The Kruskal-Wallis H-test tests the null hypothesis that the population median of all of the groups are equal. It is a non-parametric version of ANOVA. The test works on 2 or more independent samples, which may have different sizes. Note that rejecting the null hypothesis does not indicate which of the groups differs. Post hoc comparisons between groups are required to determine which groups are different. Parameters ---------- sample1, sample2, ... : array_like Two or more arrays with the sample measurements can be given as arguments. Samples must be one-dimensional. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- statistic : float The Kruskal-Wallis H statistic, corrected for ties. pvalue : float The p-value for the test using the assumption that H has a chi square distribution. The p-value returned is the survival function of the chi square distribution evaluated at H. See Also -------- f_oneway : 1-way ANOVA. mannwhitneyu : Mann-Whitney rank test on two samples. friedmanchisquare : Friedman test for repeated measurements. Notes ----- Due to the assumption that H has a chi square distribution, the number of samples in each group must not be too small. A typical rule is that each sample must have at least 5 measurements. References ---------- .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in One-Criterion Variance Analysis", Journal of the American Statistical Association, Vol. 47, Issue 260, pp. 583-621, 1952. .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance Examples -------- >>> from scipy import stats >>> x = [1, 3, 5, 7, 9] >>> y = [2, 4, 6, 8, 10] >>> stats.kruskal(x, y) KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) >>> x = [1, 1, 1] >>> y = [2, 2, 2] >>> z = [2, 2] >>> stats.kruskal(x, y, z) KruskalResult(statistic=7.0, pvalue=0.0301973834223185) """ samples = list(map(np.asarray, samples)) num_groups = len(samples) if num_groups < 2: raise ValueError("Need at least two groups in stats.kruskal()") for sample in samples: if sample.size == 0: NaN = _get_nan(*samples) return KruskalResult(NaN, NaN) elif sample.ndim != 1: raise ValueError("Samples must be one-dimensional.") n = np.asarray(list(map(len, samples))) if nan_policy not in ('propagate', 'raise', 'omit'): raise ValueError("nan_policy must be 'propagate', 'raise' or 'omit'") contains_nan = False for sample in samples: cn = _contains_nan(sample, nan_policy) if cn[0]: contains_nan = True break if contains_nan and nan_policy == 'omit': for sample in samples: sample = ma.masked_invalid(sample) return mstats_basic.kruskal(*samples) if contains_nan and nan_policy == 'propagate': return KruskalResult(np.nan, np.nan) alldata = np.concatenate(samples) ranked = rankdata(alldata) ties = tiecorrect(ranked) if ties == 0: raise ValueError('All numbers are identical in kruskal') # Compute sum^2/n for each group and sum j = np.insert(np.cumsum(n), 0, 0) ssbn = 0 for i in range(num_groups): ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i] totaln = np.sum(n, dtype=float) h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1) df = num_groups - 1 h /= ties return KruskalResult(h, distributions.chi2.sf(h, df)) FriedmanchisquareResult = namedtuple('FriedmanchisquareResult', ('statistic', 'pvalue')) def friedmanchisquare(*samples): """Compute the Friedman test for repeated samples. The Friedman test tests the null hypothesis that repeated samples of the same individuals have the same distribution. It is often used to test for consistency among samples obtained in different ways. For example, if two sampling techniques are used on the same set of individuals, the Friedman test can be used to determine if the two sampling techniques are consistent. Parameters ---------- sample1, sample2, sample3... : array_like Arrays of observations. All of the arrays must have the same number of elements. At least three samples must be given. Returns ------- statistic : float The test statistic, correcting for ties. pvalue : float The associated p-value assuming that the test statistic has a chi squared distribution. Notes ----- Due to the assumption that the test statistic has a chi squared distribution, the p-value is only reliable for n > 10 and more than 6 repeated samples. References ---------- .. [1] https://en.wikipedia.org/wiki/Friedman_test .. [2] P. Sprent and N.C. Smeeton, "Applied Nonparametric Statistical Methods, Third Edition". Chapter 6, Section 6.3.2. Examples -------- In [2]_, the pulse rate (per minute) of a group of seven students was measured before exercise, immediately after exercise and 5 minutes after exercise. Is there evidence to suggest that the pulse rates on these three occasions are similar? We begin by formulating a null hypothesis :math:`H_0`: The pulse rates are identical on these three occasions. Let's assess the plausibility of this hypothesis with a Friedman test. >>> from scipy.stats import friedmanchisquare >>> before = [72, 96, 88, 92, 74, 76, 82] >>> immediately_after = [120, 120, 132, 120, 101, 96, 112] >>> five_min_after = [76, 95, 104, 96, 84, 72, 76] >>> res = friedmanchisquare(before, immediately_after, five_min_after) >>> res.statistic 10.57142857142857 >>> res.pvalue 0.005063414171757498 Using a significance level of 5%, we would reject the null hypothesis in favor of the alternative hypothesis: "the pulse rates are different on these three occasions". """ k = len(samples) if k < 3: raise ValueError('At least 3 sets of samples must be given ' 'for Friedman test, got {}.'.format(k)) n = len(samples[0]) for i in range(1, k): if len(samples[i]) != n: raise ValueError('Unequal N in friedmanchisquare. Aborting.') # Rank data data = np.vstack(samples).T data = data.astype(float) for i in range(len(data)): data[i] = rankdata(data[i]) # Handle ties ties = 0 for d in data: replist, repnum = find_repeats(array(d)) for t in repnum: ties += t * (t*t - 1) c = 1 - ties / (k*(k*k - 1)*n) ssbn = np.sum(data.sum(axis=0)**2) chisq = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c return FriedmanchisquareResult(chisq, distributions.chi2.sf(chisq, k - 1)) BrunnerMunzelResult = namedtuple('BrunnerMunzelResult', ('statistic', 'pvalue')) def brunnermunzel(x, y, alternative="two-sided", distribution="t", nan_policy='propagate'): """Compute the Brunner-Munzel test on samples x and y. The Brunner-Munzel test is a nonparametric test of the null hypothesis that when values are taken one by one from each group, the probabilities of getting large values in both groups are equal. Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the assumption of equivariance of two groups. Note that this does not assume the distributions are same. This test works on two independent samples, which may have different sizes. Parameters ---------- x, y : array_like Array of samples, should be one-dimensional. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided' * 'less': one-sided * 'greater': one-sided distribution : {'t', 'normal'}, optional Defines how to get the p-value. The following options are available (default is 't'): * 't': get the p-value by t-distribution * 'normal': get the p-value by standard normal distribution. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': returns nan * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Returns ------- statistic : float The Brunner-Munzer W statistic. pvalue : float p-value assuming an t distribution. One-sided or two-sided, depending on the choice of `alternative` and `distribution`. See Also -------- mannwhitneyu : Mann-Whitney rank test on two samples. Notes ----- Brunner and Munzel recommended to estimate the p-value by t-distribution when the size of data is 50 or less. If the size is lower than 10, it would be better to use permuted Brunner Munzel test (see [2]_). References ---------- .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher problem: Asymptotic theory and a small-sample approximation". Biometrical Journal. Vol. 42(2000): 17-25. .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the non-parametric Behrens-Fisher problem". Computational Statistics and Data Analysis. Vol. 51(2007): 5192-5204. Examples -------- >>> from scipy import stats >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1] >>> x2 = [3,3,4,3,1,2,3,1,1,5,4] >>> w, p_value = stats.brunnermunzel(x1, x2) >>> w 3.1374674823029505 >>> p_value 0.0057862086661515377 """ x = np.asarray(x) y = np.asarray(y) # check both x and y cnx, npx = _contains_nan(x, nan_policy) cny, npy = _contains_nan(y, nan_policy) contains_nan = cnx or cny if npx == "omit" or npy == "omit": nan_policy = "omit" if contains_nan and nan_policy == "propagate": return BrunnerMunzelResult(np.nan, np.nan) elif contains_nan and nan_policy == "omit": x = ma.masked_invalid(x) y = ma.masked_invalid(y) return mstats_basic.brunnermunzel(x, y, alternative, distribution) nx = len(x) ny = len(y) if nx == 0 or ny == 0: return BrunnerMunzelResult(np.nan, np.nan) rankc = rankdata(np.concatenate((x, y))) rankcx = rankc[0:nx] rankcy = rankc[nx:nx+ny] rankcx_mean = np.mean(rankcx) rankcy_mean = np.mean(rankcy) rankx = rankdata(x) ranky = rankdata(y) rankx_mean = np.mean(rankx) ranky_mean = np.mean(ranky) Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0)) Sx /= nx - 1 Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0)) Sy /= ny - 1 wbfn = nx * ny * (rankcy_mean - rankcx_mean) wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy) if distribution == "t": df_numer = np.power(nx * Sx + ny * Sy, 2.0) df_denom = np.power(nx * Sx, 2.0) / (nx - 1) df_denom += np.power(ny * Sy, 2.0) / (ny - 1) df = df_numer / df_denom if (df_numer == 0) and (df_denom == 0): message = ("p-value cannot be estimated with `distribution='t' " "because degrees of freedom parameter is undefined " "(0/0). Try using `distribution='normal'") warnings.warn(message, RuntimeWarning) p = distributions.t.cdf(wbfn, df) elif distribution == "normal": p = distributions.norm.cdf(wbfn) else: raise ValueError( "distribution should be 't' or 'normal'") if alternative == "greater": pass elif alternative == "less": p = 1 - p elif alternative == "two-sided": p = 2 * np.min([p, 1-p]) else: raise ValueError( "alternative should be 'less', 'greater' or 'two-sided'") return BrunnerMunzelResult(wbfn, p) def combine_pvalues(pvalues, method='fisher', weights=None): """ Combine p-values from independent tests that bear upon the same hypothesis. These methods are intended only for combining p-values from hypothesis tests based upon continuous distributions. Each method assumes that under the null hypothesis, the p-values are sampled independently and uniformly from the interval [0, 1]. A test statistic (different for each method) is computed and a combined p-value is calculated based upon the distribution of this test statistic under the null hypothesis. Parameters ---------- pvalues : array_like, 1-D Array of p-values assumed to come from independent tests based on continuous distributions. method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'} Name of method to use to combine p-values. The available methods are (see Notes for details): * 'fisher': Fisher's method (Fisher's combined probability test) * 'pearson': Pearson's method * 'mudholkar_george': Mudholkar's and George's method * 'tippett': Tippett's method * 'stouffer': Stouffer's Z-score method weights : array_like, 1-D, optional Optional array of weights used only for Stouffer's Z-score method. Returns ------- res : SignificanceResult An object containing attributes: statistic : float The statistic calculated by the specified method. pvalue : float The combined p-value. Notes ----- If this function is applied to tests with a discrete statistics such as any rank test or contingency-table test, it will yield systematically wrong results, e.g. Fisher's method will systematically overestimate the p-value [1]_. This problem becomes less severe for large sample sizes when the discrete distributions become approximately continuous. The differences between the methods can be best illustrated by their statistics and what aspects of a combination of p-values they emphasise when considering significance [2]_. For example, methods emphasising large p-values are more sensitive to strong false and true negatives; conversely methods focussing on small p-values are sensitive to positives. * The statistics of Fisher's method (also known as Fisher's combined probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is equivalent (as a test statistics) to the product of individual p-values: :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows a :math:`\\chi^2` distribution. This method emphasises small p-values. * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_. It thus emphasises large p-values. * Mudholkar and George compromise between Fisher's and Pearson's method by averaging their statistics [4]_. Their method emphasises extreme p-values, both close to 1 and 0. * Stouffer's method [5]_ uses Z-scores and the statistic: :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the standard normal distribution. The advantage of this method is that it is straightforward to introduce weights, which can make Stouffer's method more powerful than Fisher's method when the p-values are from studies of different size [6]_ [7]_. * Tippett's method uses the smallest p-value as a statistic. (Mind that this minimum is not the combined p-value.) Fisher's method may be extended to combine p-values from dependent tests [8]_. Extensions such as Brown's method and Kost's method are not currently implemented. .. versionadded:: 0.15.0 References ---------- .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete Distributions." Journal of the American Statistical Association 57, no. 297 (1962), 10-19. .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of combining p-values." Biometrika 105.1 (2018): 239-246. .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic random variables." Metrika 30.1 (1983): 1-13. .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method .. [6] Whitlock, M. C. "Combining probability from independent tests: the weighted Z-method is superior to Fisher's approach." Journal of Evolutionary Biology 18, no. 5 (2005): 1368-1373. .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method for combining probabilities in meta-analysis." Journal of Evolutionary Biology 24, no. 8 (2011): 1836-1841. .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method """ pvalues = np.asarray(pvalues) if pvalues.ndim != 1: raise ValueError("pvalues is not 1-D") if method == 'fisher': statistic = -2 * np.sum(np.log(pvalues)) pval = distributions.chi2.sf(statistic, 2 * len(pvalues)) elif method == 'pearson': statistic = 2 * np.sum(np.log1p(-pvalues)) pval = distributions.chi2.cdf(-statistic, 2 * len(pvalues)) elif method == 'mudholkar_george': normalizing_factor = np.sqrt(3/len(pvalues))/np.pi statistic = -np.sum(np.log(pvalues)) + np.sum(np.log1p(-pvalues)) nu = 5 * len(pvalues) + 4 approx_factor = np.sqrt(nu / (nu - 2)) pval = distributions.t.sf(statistic * normalizing_factor * approx_factor, nu) elif method == 'tippett': statistic = np.min(pvalues) pval = distributions.beta.cdf(statistic, 1, len(pvalues)) elif method == 'stouffer': if weights is None: weights = np.ones_like(pvalues) elif len(weights) != len(pvalues): raise ValueError("pvalues and weights must be of the same size.") weights = np.asarray(weights) if weights.ndim != 1: raise ValueError("weights is not 1-D") Zi = distributions.norm.isf(pvalues) statistic = np.dot(weights, Zi) / np.linalg.norm(weights) pval = distributions.norm.sf(statistic) else: raise ValueError( f"Invalid method {method!r}. Valid methods are 'fisher', " "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'" ) return SignificanceResult(statistic, pval) ##################################### # STATISTICAL DISTANCES # ##################################### def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None): r""" Compute the first Wasserstein distance between two 1D distributions. This distance is also known as the earth mover's distance, since it can be seen as the minimum amount of "work" required to transform :math:`u` into :math:`v`, where "work" is measured as the amount of distribution weight that must be moved, multiplied by the distance it has to be moved. .. versionadded:: 1.0.0 Parameters ---------- u_values, v_values : array_like Values observed in the (empirical) distribution. u_weights, v_weights : array_like, optional Weight for each value. If unspecified, each value is assigned the same weight. `u_weights` (resp. `v_weights`) must have the same length as `u_values` (resp. `v_values`). If the weight sum differs from 1, it must still be positive and finite so that the weights can be normalized to sum to 1. Returns ------- distance : float The computed distance between the distributions. Notes ----- The first Wasserstein distance between the distributions :math:`u` and :math:`v` is: .. math:: l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times \mathbb{R}} |x-y| \mathrm{d} \pi (x, y) where :math:`\Gamma (u, v)` is the set of (probability) distributions on :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and :math:`v` on the first and second factors respectively. If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and :math:`v`, this distance also equals to: .. math:: l_1(u, v) = \int_{-\infty}^{+\infty} |U-V| See [2]_ for a proof of the equivalence of both definitions. The input distributions can be empirical, therefore coming from samples whose values are effectively inputs of the function, or they can be seen as generalized functions, in which case they are weighted sums of Dirac delta functions located at the specified values. References ---------- .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric .. [2] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`. Examples -------- >>> from scipy.stats import wasserstein_distance >>> wasserstein_distance([0, 1, 3], [5, 6, 8]) 5.0 >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2]) 0.25 >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4], ... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5]) 4.0781331438047861 """ return _cdf_distance(1, u_values, v_values, u_weights, v_weights) def energy_distance(u_values, v_values, u_weights=None, v_weights=None): r"""Compute the energy distance between two 1D distributions. .. versionadded:: 1.0.0 Parameters ---------- u_values, v_values : array_like Values observed in the (empirical) distribution. u_weights, v_weights : array_like, optional Weight for each value. If unspecified, each value is assigned the same weight. `u_weights` (resp. `v_weights`) must have the same length as `u_values` (resp. `v_values`). If the weight sum differs from 1, it must still be positive and finite so that the weights can be normalized to sum to 1. Returns ------- distance : float The computed distance between the distributions. Notes ----- The energy distance between two distributions :math:`u` and :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, equals to: .. math:: D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| - \mathbb E|Y - Y'| \right)^{1/2} where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are independent random variables whose probability distribution is :math:`u` (resp. :math:`v`). Sometimes the square of this quantity is referred to as the "energy distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the definition above satisfies the axioms of a distance function (metric). As shown in [2]_, for one-dimensional real-valued variables, the energy distance is linked to the non-distribution-free version of the Cramér-von Mises distance: .. math:: D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2 \right)^{1/2} Note that the common Cramér-von Mises criterion uses the distribution-free version of the distance. See [2]_ (section 2), for more details about both versions of the distance. The input distributions can be empirical, therefore coming from samples whose values are effectively inputs of the function, or they can be seen as generalized functions, in which case they are weighted sums of Dirac delta functions located at the specified values. References ---------- .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews: Computational Statistics, 8(1):27-38 (2015). .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling Green State University, Department of Mathematics and Statistics, Technical Report 02-16 (2002). .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer, Munos "The Cramer Distance as a Solution to Biased Wasserstein Gradients" (2017). :arXiv:`1705.10743`. Examples -------- >>> from scipy.stats import energy_distance >>> energy_distance([0], [2]) 2.0000000000000004 >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2]) 1.0000000000000002 >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ], ... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8]) 0.88003340976158217 """ return np.sqrt(2) * _cdf_distance(2, u_values, v_values, u_weights, v_weights) def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None): r""" Compute, between two one-dimensional distributions :math:`u` and :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the statistical distance that is defined as: .. math:: l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p} p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2 gives the energy distance. Parameters ---------- u_values, v_values : array_like Values observed in the (empirical) distribution. u_weights, v_weights : array_like, optional Weight for each value. If unspecified, each value is assigned the same weight. `u_weights` (resp. `v_weights`) must have the same length as `u_values` (resp. `v_values`). If the weight sum differs from 1, it must still be positive and finite so that the weights can be normalized to sum to 1. Returns ------- distance : float The computed distance between the distributions. Notes ----- The input distributions can be empirical, therefore coming from samples whose values are effectively inputs of the function, or they can be seen as generalized functions, in which case they are weighted sums of Dirac delta functions located at the specified values. References ---------- .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer, Munos "The Cramer Distance as a Solution to Biased Wasserstein Gradients" (2017). :arXiv:`1705.10743`. """ u_values, u_weights = _validate_distribution(u_values, u_weights) v_values, v_weights = _validate_distribution(v_values, v_weights) u_sorter = np.argsort(u_values) v_sorter = np.argsort(v_values) all_values = np.concatenate((u_values, v_values)) all_values.sort(kind='mergesort') # Compute the differences between pairs of successive values of u and v. deltas = np.diff(all_values) # Get the respective positions of the values of u and v among the values of # both distributions. u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right') v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right') # Calculate the CDFs of u and v using their weights, if specified. if u_weights is None: u_cdf = u_cdf_indices / u_values.size else: u_sorted_cumweights = np.concatenate(([0], np.cumsum(u_weights[u_sorter]))) u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1] if v_weights is None: v_cdf = v_cdf_indices / v_values.size else: v_sorted_cumweights = np.concatenate(([0], np.cumsum(v_weights[v_sorter]))) v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1] # Compute the value of the integral based on the CDFs. # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead # of about 15%. if p == 1: return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas)) if p == 2: return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas))) return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p), deltas)), 1/p) def _validate_distribution(values, weights): """ Validate the values and weights from a distribution input of `cdf_distance` and return them as ndarray objects. Parameters ---------- values : array_like Values observed in the (empirical) distribution. weights : array_like Weight for each value. Returns ------- values : ndarray Values as ndarray. weights : ndarray Weights as ndarray. """ # Validate the value array. values = np.asarray(values, dtype=float) if len(values) == 0: raise ValueError("Distribution can't be empty.") # Validate the weight array, if specified. if weights is not None: weights = np.asarray(weights, dtype=float) if len(weights) != len(values): raise ValueError('Value and weight array-likes for the same ' 'empirical distribution must be of the same size.') if np.any(weights < 0): raise ValueError('All weights must be non-negative.') if not 0 < np.sum(weights) < np.inf: raise ValueError('Weight array-like sum must be positive and ' 'finite. Set as None for an equal distribution of ' 'weight.') return values, weights return values, None ##################################### # SUPPORT FUNCTIONS # ##################################### RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts')) def find_repeats(arr): """Find repeats and repeat counts. Parameters ---------- arr : array_like Input array. This is cast to float64. Returns ------- values : ndarray The unique values from the (flattened) input that are repeated. counts : ndarray Number of times the corresponding 'value' is repeated. Notes ----- In numpy >= 1.9 `numpy.unique` provides similar functionality. The main difference is that `find_repeats` only returns repeated values. Examples -------- >>> from scipy import stats >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5]) RepeatedResults(values=array([2.]), counts=array([4])) >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]]) RepeatedResults(values=array([4., 5.]), counts=array([2, 2])) """ # Note: always copies. return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64))) def _sum_of_squares(a, axis=0): """Square each element of the input array, and return the sum(s) of that. Parameters ---------- a : array_like Input array. axis : int or None, optional Axis along which to calculate. Default is 0. If None, compute over the whole array `a`. Returns ------- sum_of_squares : ndarray The sum along the given axis for (a**2). See Also -------- _square_of_sums : The square(s) of the sum(s) (the opposite of `_sum_of_squares`). """ a, axis = _chk_asarray(a, axis) return np.sum(a*a, axis) def _square_of_sums(a, axis=0): """Sum elements of the input array, and return the square(s) of that sum. Parameters ---------- a : array_like Input array. axis : int or None, optional Axis along which to calculate. Default is 0. If None, compute over the whole array `a`. Returns ------- square_of_sums : float or ndarray The square of the sum over `axis`. See Also -------- _sum_of_squares : The sum of squares (the opposite of `square_of_sums`). """ a, axis = _chk_asarray(a, axis) s = np.sum(a, axis) if not np.isscalar(s): return s.astype(float) * s else: return float(s) * s def rankdata(a, method='average', *, axis=None, nan_policy='propagate'): """Assign ranks to data, dealing with ties appropriately. By default (``axis=None``), the data array is first flattened, and a flat array of ranks is returned. Separately reshape the rank array to the shape of the data array if desired (see Examples). Ranks begin at 1. The `method` argument controls how ranks are assigned to equal values. See [1]_ for further discussion of ranking methods. Parameters ---------- a : array_like The array of values to be ranked. method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional The method used to assign ranks to tied elements. The following methods are available (default is 'average'): * 'average': The average of the ranks that would have been assigned to all the tied values is assigned to each value. * 'min': The minimum of the ranks that would have been assigned to all the tied values is assigned to each value. (This is also referred to as "competition" ranking.) * 'max': The maximum of the ranks that would have been assigned to all the tied values is assigned to each value. * 'dense': Like 'min', but the rank of the next highest element is assigned the rank immediately after those assigned to the tied elements. * 'ordinal': All values are given a distinct rank, corresponding to the order that the values occur in `a`. axis : {None, int}, optional Axis along which to perform the ranking. If ``None``, the data array is first flattened. nan_policy : {'propagate', 'omit', 'raise'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': propagates nans through the rank calculation * 'omit': performs the calculations ignoring nan values * 'raise': raises an error .. note:: When `nan_policy` is 'propagate', the output is an array of *all* nans because ranks relative to nans in the input are undefined. When `nan_policy` is 'omit', nans in `a` are ignored when ranking the other values, and the corresponding locations of the output are nan. .. versionadded:: 1.10 Returns ------- ranks : ndarray An array of size equal to the size of `a`, containing rank scores. References ---------- .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking Examples -------- >>> import numpy as np >>> from scipy.stats import rankdata >>> rankdata([0, 2, 3, 2]) array([ 1. , 2.5, 4. , 2.5]) >>> rankdata([0, 2, 3, 2], method='min') array([ 1, 2, 4, 2]) >>> rankdata([0, 2, 3, 2], method='max') array([ 1, 3, 4, 3]) >>> rankdata([0, 2, 3, 2], method='dense') array([ 1, 2, 3, 2]) >>> rankdata([0, 2, 3, 2], method='ordinal') array([ 1, 2, 4, 3]) >>> rankdata([[0, 2], [3, 2]]).reshape(2,2) array([[1. , 2.5], [4. , 2.5]]) >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1) array([[1. , 2.5, 2.5], [2. , 1. , 3. ]]) >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate") array([nan, nan, nan, nan, nan, nan]) >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit") array([ 2., 3., 4., nan, 1., nan]) """ if method not in ('average', 'min', 'max', 'dense', 'ordinal'): raise ValueError(f'unknown method "{method}"') a = np.asarray(a) if axis is not None: if a.size == 0: # The return values of `normalize_axis_index` are ignored. The # call validates `axis`, even though we won't use it. # use scipy._lib._util._normalize_axis_index when available np.core.multiarray.normalize_axis_index(axis, a.ndim) dt = np.float64 if method == 'average' else np.int_ return np.empty(a.shape, dtype=dt) return np.apply_along_axis(rankdata, axis, a, method, nan_policy=nan_policy) arr = np.ravel(a) contains_nan, nan_policy = _contains_nan(arr, nan_policy) nan_indexes = None if contains_nan: if nan_policy == 'omit': nan_indexes = np.isnan(arr) if nan_policy == 'propagate': return np.full_like(arr, np.nan) algo = 'mergesort' if method == 'ordinal' else 'quicksort' sorter = np.argsort(arr, kind=algo) inv = np.empty(sorter.size, dtype=np.intp) inv[sorter] = np.arange(sorter.size, dtype=np.intp) if method == 'ordinal': result = inv + 1 else: arr = arr[sorter] obs = np.r_[True, arr[1:] != arr[:-1]] dense = obs.cumsum()[inv] if method == 'dense': result = dense else: # cumulative counts of each unique value count = np.r_[np.nonzero(obs)[0], len(obs)] if method == 'max': result = count[dense] if method == 'min': result = count[dense - 1] + 1 if method == 'average': result = .5 * (count[dense] + count[dense - 1] + 1) if nan_indexes is not None: result = result.astype('float64') result[nan_indexes] = np.nan return result def expectile(a, alpha=0.5, *, weights=None): r"""Compute the expectile at the specified level. Expectiles are a generalization of the expectation in the same way as quantiles are a generalization of the median. The expectile at level `alpha = 0.5` is the mean (average). See Notes for more details. Parameters ---------- a : array_like Array containing numbers whose expectile is desired. alpha : float, default: 0.5 The level of the expectile; e.g., `alpha=0.5` gives the mean. weights : array_like, optional An array of weights associated with the values in `a`. The `weights` must be broadcastable to the same shape as `a`. Default is None, which gives each value a weight of 1.0. An integer valued weight element acts like repeating the corresponding observation in `a` that many times. See Notes for more details. Returns ------- expectile : ndarray The empirical expectile at level `alpha`. See Also -------- numpy.mean : Arithmetic average numpy.quantile : Quantile Notes ----- In general, the expectile at level :math:`\alpha` of a random variable :math:`X` with cumulative distribution function (CDF) :math:`F` is given by the unique solution :math:`t` of: .. math:: \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,. Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`. This equation can be equivalently written as: .. math:: \alpha \int_t^\infty (x - t)\mathrm{d}F(x) = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,. The empirical expectile at level :math:`\alpha` (`alpha`) of a sample :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of `a`. Given sample or case weights :math:`w` (the array `weights`), it reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}` with indicator function :math:`1_{A}`. This leads to the definition of the empirical expectile at level `alpha` as the unique solution :math:`t` of: .. math:: \alpha \sum_{i=1}^n w_i (a_i - t)_+ = (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,. For :math:`\alpha=0.5`, this simplifies to the weighted average. Furthermore, the larger :math:`\alpha`, the larger the value of the expectile. As a final remark, the expectile at level :math:`\alpha` can also be written as a minimization problem. One often used choice is .. math:: \operatorname{argmin}_t E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,. References ---------- .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares Estimation and Testing," Econometrica, 55, 819-847. .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts," Journal of the American Statistical Association, 106, 746 - 762. :doi:`10.48550/arXiv.0912.0902` Examples -------- >>> import numpy as np >>> from scipy.stats import expectile >>> a = [1, 4, 2, -1] >>> expectile(a, alpha=0.5) == np.mean(a) True >>> expectile(a, alpha=0.2) 0.42857142857142855 >>> expectile(a, alpha=0.8) 2.5714285714285716 >>> weights = [1, 3, 1, 1] """ if alpha < 0 or alpha > 1: raise ValueError( "The expectile level alpha must be in the range [0, 1]." ) a = np.asarray(a) if weights is not None: weights = np.broadcast_to(weights, a.shape) # This is the empirical equivalent of Eq. (13) with identification # function from Table 9 (omitting a factor of 2) in [2] (their y is our # data a, their x is our t) def first_order(t): return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights) if alpha >= 0.5: x0 = np.average(a, weights=weights) x1 = np.amax(a) else: x1 = np.average(a, weights=weights) x0 = np.amin(a) if x0 == x1: # a has a single unique element return x0 # Note that the expectile is the unique solution, so no worries about # finding a wrong root. res = root_scalar(first_order, x0=x0, x1=x1) return res.root
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@scipy@py3@scipy@stats@_stats_py.py@.PATH_END.py
{ "filename": "polarizability.py", "repo_name": "HajimeKawahara/exojax", "repo_path": "exojax_extracted/exojax-master/src/exojax/atm/polarizability.py", "type": "Python" }
""" Gas Polarizability Notes: Originally taken from PICASO/GPLv3 picaso/rayleigh.py polarizabilities are mainly taken from CRC handbook of chemistry and physics vol. 95 unit=cm3 H3+ taken from Kawaoka & Borkman, 1971 Number density at reference conditions of refractive index measurements i.e. number density of the ideal gas at T=273.15K (=0 C) and P=1atm [cm-2], as Patm*bar_cgs / (kB * 273.15) http://refractiveindex.info n_ref_refractive = 2.6867810458916872e+19 """ polarizability = { 'H2': 0.804e-24, 'He': 0.21e-24, 'N2': 1.74e-24, 'O2': 1.57e-24, 'O3': 3.21e-24, 'H2O': 1.45e-24, 'CH4': 2.593e-24, 'C2H2': 3.33e-24, 'CO': 1.95e-24, 'CO2': 2.911e-24, 'NH3': 2.26e-24, 'HCN': 2.59e-24, 'PH3': 4.84e-24, 'SO2': 3.72e-24, 'SO3': 4.84e-24, 'C2H2': 3.33e-24, 'H2S': 3.78e-24, 'NO': 1.70e-24, 'NO2': 3.02e-24, 'H3+': 0.385e-24, 'OH': 6.965e-24, 'Na': 24.11e-24, 'K': 42.9e-24, 'Li': 24.33e-24, 'Rb': 47.39e-24, 'Cs': 59.42e-24, 'TiO': 16.9e-24, 'VO': 14.4e-24, 'AlO': 8.22e-24, 'SiO': 5.53e-24, 'CaO': 23.8e-24, 'TiH': 16.9e-24, 'MgH': 10.5e-24, 'NaH': 24.11e-24, 'AlH': 8.22e-24, 'CrH': 11.6e-24, 'FeH': 9.47e-24, 'CaH': 23.8e-24, 'BeH': 5.60e-24, 'ScH': 21.2e-24 } king_correction_factor = { "O3": 1.060000, "CO": 1.016995, "C2H2": 1.064385, "C2H6": 1.006063, "OCS": 1.138786, "CH3Cl": 1.026042, "H2S": 1.001880, "SO2": 1.062638 }
HajimeKawaharaREPO_NAMEexojaxPATH_START.@exojax_extracted@exojax-master@src@exojax@atm@polarizability.py@.PATH_END.py
{ "filename": "gaussian_noise.py", "repo_name": "keras-team/keras", "repo_path": "keras_extracted/keras-master/keras/src/layers/regularization/gaussian_noise.py", "type": "Python" }
from keras.src import backend from keras.src import layers from keras.src import ops from keras.src.api_export import keras_export @keras_export("keras.layers.GaussianNoise") class GaussianNoise(layers.Layer): """Apply additive zero-centered Gaussian noise. This is useful to mitigate overfitting (you could see it as a form of random data augmentation). Gaussian Noise (GS) is a natural choice as corruption process for real valued inputs. As it is a regularization layer, it is only active at training time. Args: stddev: Float, standard deviation of the noise distribution. seed: Integer, optional random seed to enable deterministic behavior. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode (adding noise) or in inference mode (doing nothing). """ def __init__(self, stddev, seed=None, **kwargs): super().__init__(**kwargs) if not 0 <= stddev <= 1: raise ValueError( f"Invalid value received for argument " "`stddev`. Expected a float value between 0 and 1. " f"Received: stddev={stddev}" ) self.stddev = stddev self.seed = seed if stddev > 0: self.seed_generator = backend.random.SeedGenerator(seed) self.supports_masking = True self.built = True def call(self, inputs, training=False): if training and self.stddev > 0: return inputs + backend.random.normal( shape=ops.shape(inputs), mean=0.0, stddev=self.stddev, dtype=self.compute_dtype, seed=self.seed_generator, ) return inputs def compute_output_shape(self, input_shape): return input_shape def get_config(self): base_config = super().get_config() config = { "stddev": self.stddev, "seed": self.seed, } return {**base_config, **config}
keras-teamREPO_NAMEkerasPATH_START.@keras_extracted@keras-master@keras@src@layers@regularization@gaussian_noise.py@.PATH_END.py
{ "filename": "_densitymap.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/graph_objs/_densitymap.py", "type": "Python" }
from plotly.basedatatypes import BaseTraceType as _BaseTraceType import copy as _copy class Densitymap(_BaseTraceType): # class properties # -------------------- _parent_path_str = "" _path_str = "densitymap" _valid_props = { "autocolorscale", "below", "coloraxis", "colorbar", "colorscale", "customdata", "customdatasrc", "hoverinfo", "hoverinfosrc", "hoverlabel", "hovertemplate", "hovertemplatesrc", "hovertext", "hovertextsrc", "ids", "idssrc", "lat", "latsrc", "legend", "legendgroup", "legendgrouptitle", "legendrank", "legendwidth", "lon", "lonsrc", "meta", "metasrc", "name", "opacity", "radius", "radiussrc", "reversescale", "showlegend", "showscale", "stream", "subplot", "text", "textsrc", "type", "uid", "uirevision", "visible", "z", "zauto", "zmax", "zmid", "zmin", "zsrc", } # autocolorscale # -------------- @property def autocolorscale(self): """ Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. The 'autocolorscale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["autocolorscale"] @autocolorscale.setter def autocolorscale(self, val): self["autocolorscale"] = val # below # ----- @property def below(self): """ Determines if the densitymap trace will be inserted before the layer with the specified ID. By default, densitymap traces are placed below the first layer of type symbol If set to '', the layer will be inserted above every existing layer. The 'below' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["below"] @below.setter def below(self, val): self["below"] = val # coloraxis # --------- @property def coloraxis(self): """ Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. The 'coloraxis' property is an identifier of a particular subplot, of type 'coloraxis', that may be specified as the string 'coloraxis' optionally followed by an integer >= 1 (e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.) Returns ------- str """ return self["coloraxis"] @coloraxis.setter def coloraxis(self, val): self["coloraxis"] = val # colorbar # -------- @property def colorbar(self): """ The 'colorbar' property is an instance of ColorBar that may be specified as: - An instance of :class:`plotly.graph_objs.densitymap.ColorBar` - A dict of string/value properties that will be passed to the ColorBar constructor Supported dict properties: bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: h ttps://github.com/d3/d3-format/tree/v1.4.5#d3- format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.density map.colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.dat a.densitymap.colorbar.tickformatstopdefaults), sets the default property values to use for elements of densitymap.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.densitymap.colorba r.Title` instance or dict with compatible properties titlefont Deprecated: Please use densitymap.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleside Deprecated: Please use densitymap.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. Returns ------- plotly.graph_objs.densitymap.ColorBar """ return self["colorbar"] @colorbar.setter def colorbar(self, val): self["colorbar"] = val # colorscale # ---------- @property def colorscale(self): """ Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis, YlGnBu,YlOrRd. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it. Returns ------- str """ return self["colorscale"] @colorscale.setter def colorscale(self, val): self["colorscale"] = val # customdata # ---------- @property def customdata(self): """ Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements The 'customdata' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["customdata"] @customdata.setter def customdata(self, val): self["customdata"] = val # customdatasrc # ------------- @property def customdatasrc(self): """ Sets the source reference on Chart Studio Cloud for `customdata`. The 'customdatasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["customdatasrc"] @customdatasrc.setter def customdatasrc(self, val): self["customdatasrc"] = val # hoverinfo # --------- @property def hoverinfo(self): """ Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. The 'hoverinfo' property is a flaglist and may be specified as a string containing: - Any combination of ['lon', 'lat', 'z', 'text', 'name'] joined with '+' characters (e.g. 'lon+lat') OR exactly one of ['all', 'none', 'skip'] (e.g. 'skip') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["hoverinfo"] @hoverinfo.setter def hoverinfo(self, val): self["hoverinfo"] = val # hoverinfosrc # ------------ @property def hoverinfosrc(self): """ Sets the source reference on Chart Studio Cloud for `hoverinfo`. The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hoverinfosrc"] @hoverinfosrc.setter def hoverinfosrc(self, val): self["hoverinfosrc"] = val # hoverlabel # ---------- @property def hoverlabel(self): """ The 'hoverlabel' property is an instance of Hoverlabel that may be specified as: - An instance of :class:`plotly.graph_objs.densitymap.Hoverlabel` - A dict of string/value properties that will be passed to the Hoverlabel constructor Supported dict properties: align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. Returns ------- plotly.graph_objs.densitymap.Hoverlabel """ return self["hoverlabel"] @hoverlabel.setter def hoverlabel(self, val): self["hoverlabel"] = val # hovertemplate # ------------- @property def hovertemplate(self): """ Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event-data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. The 'hovertemplate' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertemplate"] @hovertemplate.setter def hovertemplate(self, val): self["hovertemplate"] = val # hovertemplatesrc # ---------------- @property def hovertemplatesrc(self): """ Sets the source reference on Chart Studio Cloud for `hovertemplate`. The 'hovertemplatesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertemplatesrc"] @hovertemplatesrc.setter def hovertemplatesrc(self, val): self["hovertemplatesrc"] = val # hovertext # --------- @property def hovertext(self): """ Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. The 'hovertext' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertext"] @hovertext.setter def hovertext(self, val): self["hovertext"] = val # hovertextsrc # ------------ @property def hovertextsrc(self): """ Sets the source reference on Chart Studio Cloud for `hovertext`. The 'hovertextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertextsrc"] @hovertextsrc.setter def hovertextsrc(self, val): self["hovertextsrc"] = val # ids # --- @property def ids(self): """ Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. The 'ids' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ids"] @ids.setter def ids(self, val): self["ids"] = val # idssrc # ------ @property def idssrc(self): """ Sets the source reference on Chart Studio Cloud for `ids`. The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["idssrc"] @idssrc.setter def idssrc(self, val): self["idssrc"] = val # lat # --- @property def lat(self): """ Sets the latitude coordinates (in degrees North). The 'lat' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["lat"] @lat.setter def lat(self, val): self["lat"] = val # latsrc # ------ @property def latsrc(self): """ Sets the source reference on Chart Studio Cloud for `lat`. The 'latsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["latsrc"] @latsrc.setter def latsrc(self, val): self["latsrc"] = val # legend # ------ @property def legend(self): """ Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. The 'legend' property is an identifier of a particular subplot, of type 'legend', that may be specified as the string 'legend' optionally followed by an integer >= 1 (e.g. 'legend', 'legend1', 'legend2', 'legend3', etc.) Returns ------- str """ return self["legend"] @legend.setter def legend(self, val): self["legend"] = val # legendgroup # ----------- @property def legendgroup(self): """ Sets the legend group for this trace. Traces and shapes part of the same legend group hide/show at the same time when toggling legend items. The 'legendgroup' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["legendgroup"] @legendgroup.setter def legendgroup(self, val): self["legendgroup"] = val # legendgrouptitle # ---------------- @property def legendgrouptitle(self): """ The 'legendgrouptitle' property is an instance of Legendgrouptitle that may be specified as: - An instance of :class:`plotly.graph_objs.densitymap.Legendgrouptitle` - A dict of string/value properties that will be passed to the Legendgrouptitle constructor Supported dict properties: font Sets this legend group's title font. text Sets the title of the legend group. Returns ------- plotly.graph_objs.densitymap.Legendgrouptitle """ return self["legendgrouptitle"] @legendgrouptitle.setter def legendgrouptitle(self, val): self["legendgrouptitle"] = val # legendrank # ---------- @property def legendrank(self): """ Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. The 'legendrank' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["legendrank"] @legendrank.setter def legendrank(self, val): self["legendrank"] = val # legendwidth # ----------- @property def legendwidth(self): """ Sets the width (in px or fraction) of the legend for this trace. The 'legendwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["legendwidth"] @legendwidth.setter def legendwidth(self, val): self["legendwidth"] = val # lon # --- @property def lon(self): """ Sets the longitude coordinates (in degrees East). The 'lon' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["lon"] @lon.setter def lon(self, val): self["lon"] = val # lonsrc # ------ @property def lonsrc(self): """ Sets the source reference on Chart Studio Cloud for `lon`. The 'lonsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["lonsrc"] @lonsrc.setter def lonsrc(self, val): self["lonsrc"] = val # meta # ---- @property def meta(self): """ Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. The 'meta' property accepts values of any type Returns ------- Any|numpy.ndarray """ return self["meta"] @meta.setter def meta(self, val): self["meta"] = val # metasrc # ------- @property def metasrc(self): """ Sets the source reference on Chart Studio Cloud for `meta`. The 'metasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["metasrc"] @metasrc.setter def metasrc(self, val): self["metasrc"] = val # name # ---- @property def name(self): """ Sets the trace name. The trace name appears as the legend item and on hover. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["name"] @name.setter def name(self, val): self["name"] = val # opacity # ------- @property def opacity(self): """ Sets the opacity of the trace. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val # radius # ------ @property def radius(self): """ Sets the radius of influence of one `lon` / `lat` point in pixels. Increasing the value makes the densitymap trace smoother, but less detailed. The 'radius' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["radius"] @radius.setter def radius(self, val): self["radius"] = val # radiussrc # --------- @property def radiussrc(self): """ Sets the source reference on Chart Studio Cloud for `radius`. The 'radiussrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["radiussrc"] @radiussrc.setter def radiussrc(self, val): self["radiussrc"] = val # reversescale # ------------ @property def reversescale(self): """ Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. The 'reversescale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["reversescale"] @reversescale.setter def reversescale(self, val): self["reversescale"] = val # showlegend # ---------- @property def showlegend(self): """ Determines whether or not an item corresponding to this trace is shown in the legend. The 'showlegend' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlegend"] @showlegend.setter def showlegend(self, val): self["showlegend"] = val # showscale # --------- @property def showscale(self): """ Determines whether or not a colorbar is displayed for this trace. The 'showscale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showscale"] @showscale.setter def showscale(self, val): self["showscale"] = val # stream # ------ @property def stream(self): """ The 'stream' property is an instance of Stream that may be specified as: - An instance of :class:`plotly.graph_objs.densitymap.Stream` - A dict of string/value properties that will be passed to the Stream constructor Supported dict properties: maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart- studio.plotly.com/settings for more details. Returns ------- plotly.graph_objs.densitymap.Stream """ return self["stream"] @stream.setter def stream(self, val): self["stream"] = val # subplot # ------- @property def subplot(self): """ Sets a reference between this trace's data coordinates and a map subplot. If "map" (the default value), the data refer to `layout.map`. If "map2", the data refer to `layout.map2`, and so on. The 'subplot' property is an identifier of a particular subplot, of type 'map', that may be specified as the string 'map' optionally followed by an integer >= 1 (e.g. 'map', 'map1', 'map2', 'map3', etc.) Returns ------- str """ return self["subplot"] @subplot.setter def subplot(self, val): self["subplot"] = val # text # ---- @property def text(self): """ Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["text"] @text.setter def text(self, val): self["text"] = val # textsrc # ------- @property def textsrc(self): """ Sets the source reference on Chart Studio Cloud for `text`. The 'textsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textsrc"] @textsrc.setter def textsrc(self, val): self["textsrc"] = val # uid # --- @property def uid(self): """ Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. The 'uid' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["uid"] @uid.setter def uid(self, val): self["uid"] = val # uirevision # ---------- @property def uirevision(self): """ Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. The 'uirevision' property accepts values of any type Returns ------- Any """ return self["uirevision"] @uirevision.setter def uirevision(self, val): self["uirevision"] = val # visible # ------- @property def visible(self): """ Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly'] Returns ------- Any """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val # z # - @property def z(self): """ Sets the points' weight. For example, a value of 10 would be equivalent to having 10 points of weight 1 in the same spot The 'z' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["z"] @z.setter def z(self, val): self["z"] = val # zauto # ----- @property def zauto(self): """ Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. The 'zauto' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["zauto"] @zauto.setter def zauto(self, val): self["zauto"] = val # zmax # ---- @property def zmax(self): """ Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. The 'zmax' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["zmax"] @zmax.setter def zmax(self, val): self["zmax"] = val # zmid # ---- @property def zmid(self): """ Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. The 'zmid' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["zmid"] @zmid.setter def zmid(self, val): self["zmid"] = val # zmin # ---- @property def zmin(self): """ Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. The 'zmin' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["zmin"] @zmin.setter def zmin(self, val): self["zmin"] = val # zsrc # ---- @property def zsrc(self): """ Sets the source reference on Chart Studio Cloud for `z`. The 'zsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["zsrc"] @zsrc.setter def zsrc(self, val): self["zsrc"] = val # type # ---- @property def type(self): return self._props["type"] # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. below Determines if the densitymap trace will be inserted before the layer with the specified ID. By default, densitymap traces are placed below the first layer of type symbol If set to '', the layer will be inserted above every existing layer. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.densitymap.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for `customdata`. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for `hoverinfo`. hoverlabel :class:`plotly.graph_objects.densitymap.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for `hovertext`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for `ids`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. legend Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. legendgroup Sets the legend group for this trace. Traces and shapes part of the same legend group hide/show at the same time when toggling legend items. legendgrouptitle :class:`plotly.graph_objects.densitymap.Legendgrouptitl e` instance or dict with compatible properties legendrank Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. legendwidth Sets the width (in px or fraction) of the legend for this trace. lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for `meta`. name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. radius Sets the radius of influence of one `lon` / `lat` point in pixels. Increasing the value makes the densitymap trace smoother, but less detailed. radiussrc Sets the source reference on Chart Studio Cloud for `radius`. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.densitymap.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a map subplot. If "map" (the default value), the data refer to `layout.map`. If "map2", the data refer to `layout.map2`, and so on. text Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for `text`. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). z Sets the points' weight. For example, a value of 10 would be equivalent to having 10 points of weight 1 in the same spot zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. """ def __init__( self, arg=None, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lon=None, lonsrc=None, meta=None, metasrc=None, name=None, opacity=None, radius=None, radiussrc=None, reversescale=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, **kwargs, ): """ Construct a new Densitymap object Draws a bivariate kernel density estimation with a Gaussian kernel from `lon` and `lat` coordinates and optional `z` values using a colorscale. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.Densitymap` autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. below Determines if the densitymap trace will be inserted before the layer with the specified ID. By default, densitymap traces are placed below the first layer of type symbol If set to '', the layer will be inserted above every existing layer. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.densitymap.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for `customdata`. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for `hoverinfo`. hoverlabel :class:`plotly.graph_objects.densitymap.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for `hovertext`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for `ids`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. legend Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. legendgroup Sets the legend group for this trace. Traces and shapes part of the same legend group hide/show at the same time when toggling legend items. legendgrouptitle :class:`plotly.graph_objects.densitymap.Legendgrouptitl e` instance or dict with compatible properties legendrank Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. legendwidth Sets the width (in px or fraction) of the legend for this trace. lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for `meta`. name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. radius Sets the radius of influence of one `lon` / `lat` point in pixels. Increasing the value makes the densitymap trace smoother, but less detailed. radiussrc Sets the source reference on Chart Studio Cloud for `radius`. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.densitymap.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a map subplot. If "map" (the default value), the data refer to `layout.map`. If "map2", the data refer to `layout.map2`, and so on. text Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for `text`. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). z Sets the points' weight. For example, a value of 10 would be equivalent to having 10 points of weight 1 in the same spot zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. Returns ------- Densitymap """ super(Densitymap, self).__init__("densitymap") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.Densitymap constructor must be a dict or an instance of :class:`plotly.graph_objs.Densitymap`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("autocolorscale", None) _v = autocolorscale if autocolorscale is not None else _v if _v is not None: self["autocolorscale"] = _v _v = arg.pop("below", None) _v = below if below is not None else _v if _v is not None: self["below"] = _v _v = arg.pop("coloraxis", None) _v = coloraxis if coloraxis is not None else _v if _v is not None: self["coloraxis"] = _v _v = arg.pop("colorbar", None) _v = colorbar if colorbar is not None else _v if _v is not None: self["colorbar"] = _v _v = arg.pop("colorscale", None) _v = colorscale if colorscale is not None else _v if _v is not None: self["colorscale"] = _v _v = arg.pop("customdata", None) _v = customdata if customdata is not None else _v if _v is not None: self["customdata"] = _v _v = arg.pop("customdatasrc", None) _v = customdatasrc if customdatasrc is not None else _v if _v is not None: self["customdatasrc"] = _v _v = arg.pop("hoverinfo", None) _v = hoverinfo if hoverinfo is not None else _v if _v is not None: self["hoverinfo"] = _v _v = arg.pop("hoverinfosrc", None) _v = hoverinfosrc if hoverinfosrc is not None else _v if _v is not None: self["hoverinfosrc"] = _v _v = arg.pop("hoverlabel", None) _v = hoverlabel if hoverlabel is not None else _v if _v is not None: self["hoverlabel"] = _v _v = arg.pop("hovertemplate", None) _v = hovertemplate if hovertemplate is not None else _v if _v is not None: self["hovertemplate"] = _v _v = arg.pop("hovertemplatesrc", None) _v = hovertemplatesrc if hovertemplatesrc is not None else _v if _v is not None: self["hovertemplatesrc"] = _v _v = arg.pop("hovertext", None) _v = hovertext if hovertext is not None else _v if _v is not None: self["hovertext"] = _v _v = arg.pop("hovertextsrc", None) _v = hovertextsrc if hovertextsrc is not None else _v if _v is not None: self["hovertextsrc"] = _v _v = arg.pop("ids", None) _v = ids if ids is not None else _v if _v is not None: self["ids"] = _v _v = arg.pop("idssrc", None) _v = idssrc if idssrc is not None else _v if _v is not None: self["idssrc"] = _v _v = arg.pop("lat", None) _v = lat if lat is not None else _v if _v is not None: self["lat"] = _v _v = arg.pop("latsrc", None) _v = latsrc if latsrc is not None else _v if _v is not None: self["latsrc"] = _v _v = arg.pop("legend", None) _v = legend if legend is not None else _v if _v is not None: self["legend"] = _v _v = arg.pop("legendgroup", None) _v = legendgroup if legendgroup is not None else _v if _v is not None: self["legendgroup"] = _v _v = arg.pop("legendgrouptitle", None) _v = legendgrouptitle if legendgrouptitle is not None else _v if _v is not None: self["legendgrouptitle"] = _v _v = arg.pop("legendrank", None) _v = legendrank if legendrank is not None else _v if _v is not None: self["legendrank"] = _v _v = arg.pop("legendwidth", None) _v = legendwidth if legendwidth is not None else _v if _v is not None: self["legendwidth"] = _v _v = arg.pop("lon", None) _v = lon if lon is not None else _v if _v is not None: self["lon"] = _v _v = arg.pop("lonsrc", None) _v = lonsrc if lonsrc is not None else _v if _v is not None: self["lonsrc"] = _v _v = arg.pop("meta", None) _v = meta if meta is not None else _v if _v is not None: self["meta"] = _v _v = arg.pop("metasrc", None) _v = metasrc if metasrc is not None else _v if _v is not None: self["metasrc"] = _v _v = arg.pop("name", None) _v = name if name is not None else _v if _v is not None: self["name"] = _v _v = arg.pop("opacity", None) _v = opacity if opacity is not None else _v if _v is not None: self["opacity"] = _v _v = arg.pop("radius", None) _v = radius if radius is not None else _v if _v is not None: self["radius"] = _v _v = arg.pop("radiussrc", None) _v = radiussrc if radiussrc is not None else _v if _v is not None: self["radiussrc"] = _v _v = arg.pop("reversescale", None) _v = reversescale if reversescale is not None else _v if _v is not None: self["reversescale"] = _v _v = arg.pop("showlegend", None) _v = showlegend if showlegend is not None else _v if _v is not None: self["showlegend"] = _v _v = arg.pop("showscale", None) _v = showscale if showscale is not None else _v if _v is not None: self["showscale"] = _v _v = arg.pop("stream", None) _v = stream if stream is not None else _v if _v is not None: self["stream"] = _v _v = arg.pop("subplot", None) _v = subplot if subplot is not None else _v if _v is not None: self["subplot"] = _v _v = arg.pop("text", None) _v = text if text is not None else _v if _v is not None: self["text"] = _v _v = arg.pop("textsrc", None) _v = textsrc if textsrc is not None else _v if _v is not None: self["textsrc"] = _v _v = arg.pop("uid", None) _v = uid if uid is not None else _v if _v is not None: self["uid"] = _v _v = arg.pop("uirevision", None) _v = uirevision if uirevision is not None else _v if _v is not None: self["uirevision"] = _v _v = arg.pop("visible", None) _v = visible if visible is not None else _v if _v is not None: self["visible"] = _v _v = arg.pop("z", None) _v = z if z is not None else _v if _v is not None: self["z"] = _v _v = arg.pop("zauto", None) _v = zauto if zauto is not None else _v if _v is not None: self["zauto"] = _v _v = arg.pop("zmax", None) _v = zmax if zmax is not None else _v if _v is not None: self["zmax"] = _v _v = arg.pop("zmid", None) _v = zmid if zmid is not None else _v if _v is not None: self["zmid"] = _v _v = arg.pop("zmin", None) _v = zmin if zmin is not None else _v if _v is not None: self["zmin"] = _v _v = arg.pop("zsrc", None) _v = zsrc if zsrc is not None else _v if _v is not None: self["zsrc"] = _v # Read-only literals # ------------------ self._props["type"] = "densitymap" arg.pop("type", None) # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@graph_objs@_densitymap.py@.PATH_END.py
{ "filename": "_len.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/barpolar/marker/colorbar/_len.py", "type": "Python" }
import _plotly_utils.basevalidators class LenValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="len", parent_name="barpolar.marker.colorbar", **kwargs ): super(LenValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@barpolar@marker@colorbar@_len.py@.PATH_END.py
{ "filename": "radec_to_chip.py", "repo_name": "GalSim-developers/GalSim", "repo_path": "GalSim_extracted/GalSim-main/tests/roman_files/radec_to_chip.py", "type": "Python" }
# Copyright (c) 2012-2023 by the GalSim developers team on GitHub # https://github.com/GalSim-developers # # This file is part of GalSim: The modular galaxy image simulation toolkit. # https://github.com/GalSim-developers/GalSim # # GalSim is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions, and the disclaimer given in the accompanying LICENSE # file. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the disclaimer given in the documentation # and/or other materials provided with the distribution. # import numpy as np MAX_RAD_FROM_BORESIGHT = 0.009 def radec_to_chip(obsRA, obsDec, obsPA, ptRA, ptDec): """ Converted from Chris' c code. Used here to limit ra, dec catalog to objects that fall in each pointing. """ AFTA_SCA_Coords = np.array([ 0.002689724, 1.000000000, 0.181995021, -0.002070809, -1.000000000, 0.807383134, 1.000000000, 0.004769437, 1.028725015, -1.000000000, -0.000114163, -0.024579913, 0.003307633, 1.000000000, 1.203503349, -0.002719257, -1.000000000, -0.230036847, 1.000000000, 0.006091805, 1.028993582, -1.000000000, -0.000145757, -0.024586416, 0.003888409, 1.000000000, 2.205056241, -0.003335597, -1.000000000, -1.250685466, 1.000000000, 0.007389324, 1.030581048, -1.000000000, -0.000176732, -0.024624426, 0.007871078, 1.000000000, -0.101157485, -0.005906926, -1.000000000, 1.095802866, 1.000000000, 0.009147586, 2.151242511, -1.000000000, -0.004917673, -1.151541644, 0.009838715, 1.000000000, 0.926774753, -0.007965112, -1.000000000, 0.052835488, 1.000000000, 0.011913584, 2.150981875, -1.000000000, -0.006404157, -1.151413352, 0.011694346, 1.000000000, 1.935534773, -0.009927853, -1.000000000, -0.974276664, 1.000000000, 0.014630945, 2.153506744, -1.000000000, -0.007864196, -1.152784334, 0.011758070, 1.000000000, -0.527032681, -0.008410887, -1.000000000, 1.529873670, 1.000000000, 0.012002262, 3.264990040, -1.000000000, -0.008419930, -2.274065453, 0.015128555, 1.000000000, 0.510881058, -0.011918799, -1.000000000, 0.478274989, 1.000000000, 0.016194244, 3.262719942, -1.000000000, -0.011359106, -2.272508364, 0.018323436, 1.000000000, 1.530828790, -0.015281655, -1.000000000, -0.558879607, 1.000000000, 0.020320244, 3.264721809, -1.000000000, -0.014251259, -2.273955111, -0.002689724, 1.000000000, 0.181995021, 0.002070809, -1.000000000, 0.807383134, 1.000000000, -0.000114163, -0.024579913, -1.000000000, 0.004769437, 1.028725015, -0.003307633, 1.000000000, 1.203503349, 0.002719257, -1.000000000, -0.230036847, 1.000000000, -0.000145757, -0.024586416, -1.000000000, 0.006091805, 1.028993582, -0.003888409, 1.000000000, 2.205056241, 0.003335597, -1.000000000, -1.250685466, 1.000000000, -0.000176732, -0.024624426, -1.000000000, 0.007389324, 1.030581048, -0.007871078, 1.000000000, -0.101157485, 0.005906926, -1.000000000, 1.095802866, 1.000000000, -0.004917673, -1.151541644, -1.000000000, 0.009147586, 2.151242511, -0.009838715, 1.000000000, 0.926774753, 0.007965112, -1.000000000, 0.052835488, 1.000000000, -0.006404157, -1.151413352, -1.000000000, 0.011913584, 2.150981875, -0.011694346, 1.000000000, 1.935534773, 0.009927853, -1.000000000, -0.974276664, 1.000000000, -0.007864196, -1.152784334, -1.000000000, 0.014630945, 2.153506744, -0.011758070, 1.000000000, -0.527032681, 0.008410887, -1.000000000, 1.529873670, 1.000000000, -0.008419930, -2.274065453, -1.000000000, 0.012002262, 3.264990040, -0.015128555, 1.000000000, 0.510881058, 0.011918799, -1.000000000, 0.478274989, 1.000000000, -0.011359106, -2.272508364, -1.000000000, 0.016194244, 3.262719942, -0.018323436, 1.000000000, 1.530828790, 0.015281655, -1.000000000, -0.558879607, 1.000000000, -0.014251259, -2.273955111, -1.000000000, 0.020320244, 3.264721809 ]) sort = np.argsort(ptDec) ptRA = ptRA[sort] ptDec = ptDec[sort] # Crude cut of some objects more than some encircling radius away from the boresight - creates a fast dec slice. Probably not worth doing better than this. begin = np.searchsorted(ptDec, obsDec-MAX_RAD_FROM_BORESIGHT) end = np.searchsorted(ptDec, obsDec+MAX_RAD_FROM_BORESIGHT) # Position of the object in boresight coordinates mX = -np.sin(obsDec)*np.cos(ptDec[begin:end])*np.cos(obsRA-ptRA[begin:end]) + np.cos(obsDec)*np.sin(ptDec[begin:end]) mY = np.cos(ptDec[begin:end])*np.sin(obsRA-ptRA[begin:end]) xi = -(np.sin(obsPA)*mX + np.cos(obsPA)*mY) / 0.0021801102 # Image plane position in chips yi = (np.cos(obsPA)*mX - np.sin(obsPA)*mY) / 0.0021801102 SCA = np.zeros(end-begin) for i in range(18): cptr = AFTA_SCA_Coords mask = (cptr[0+12*i]*xi+cptr[1+12*i]*yi<cptr[2+12*i]) \ & (cptr[3+12*i]*xi+cptr[4+12*i]*yi<cptr[5+12*i]) \ & (cptr[6+12*i]*xi+cptr[7+12*i]*yi<cptr[8+12*i]) \ & (cptr[9+12*i]*xi+cptr[10+12*i]*yi<cptr[11+12*i]) SCA[mask] = i+1 if len(SCA) > 1: return np.pad(SCA,(begin,len(ptDec)-end),'constant',constant_values=(0, 0))[np.argsort(sort)] # Pad SCA array with zeros and resort to original indexing else: return SCA[0]
GalSim-developersREPO_NAMEGalSimPATH_START.@GalSim_extracted@GalSim-main@tests@roman_files@radec_to_chip.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "njcuk9999/apero-drs", "repo_path": "apero-drs_extracted/apero-drs-main/apero/tools/__init__.py", "type": "Python" }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # CODE NAME HERE # CODE DESCRIPTION HERE Created on 2019-01-17 at 14:31 @author: cook """ __all__ = [] # ============================================================================= # Define functions # ============================================================================= # Nothing to see here. # ============================================================================= # End of code # ============================================================================
njcuk9999REPO_NAMEapero-drsPATH_START.@apero-drs_extracted@apero-drs-main@apero@tools@__init__.py@.PATH_END.py
{ "filename": "test_cassandra.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/community/tests/integration_tests/vectorstores/test_cassandra.py", "type": "Python" }
"""Test Cassandra functionality.""" import asyncio import json import math import os import time from contextlib import asynccontextmanager, contextmanager from typing import ( Any, AsyncGenerator, Generator, Iterable, List, Optional, Tuple, Union, ) import pytest from langchain_core.documents import Document from langchain_community.vectorstores import Cassandra from tests.integration_tests.vectorstores.fake_embeddings import ( AngularTwoDimensionalEmbeddings, ConsistentFakeEmbeddings, Embeddings, ) TEST_KEYSPACE = "vector_test_keyspace" # similarity threshold definitions EUCLIDEAN_MIN_SIM_UNIT_VECTORS = 0.2 MATCH_EPSILON = 0.0001 def _strip_docs(documents: List[Document]) -> List[Document]: return [_strip_doc(doc) for doc in documents] def _strip_doc(document: Document) -> Document: return Document( page_content=document.page_content, metadata=document.metadata, ) class ParserEmbeddings(Embeddings): """Parse input texts: if they are json for a List[float], fine. Otherwise, return all zeros and call it a day. """ def __init__(self, dimension: int) -> None: self.dimension = dimension def embed_documents(self, texts: list[str]) -> list[list[float]]: return [self.embed_query(txt) for txt in texts] def embed_query(self, text: str) -> list[float]: try: vals = json.loads(text) except json.JSONDecodeError: return [0.0] * self.dimension else: assert len(vals) == self.dimension return vals @pytest.fixture def embedding_d2() -> Embeddings: return ParserEmbeddings(dimension=2) @pytest.fixture def metadata_documents() -> list[Document]: """Documents for metadata and id tests""" return [ Document( id="q", page_content="[1,2]", metadata={"ord": str(ord("q")), "group": "consonant", "letter": "q"}, ), Document( id="w", page_content="[3,4]", metadata={"ord": str(ord("w")), "group": "consonant", "letter": "w"}, ), Document( id="r", page_content="[5,6]", metadata={"ord": str(ord("r")), "group": "consonant", "letter": "r"}, ), Document( id="e", page_content="[-1,2]", metadata={"ord": str(ord("e")), "group": "vowel", "letter": "e"}, ), Document( id="i", page_content="[-3,4]", metadata={"ord": str(ord("i")), "group": "vowel", "letter": "i"}, ), Document( id="o", page_content="[-5,6]", metadata={"ord": str(ord("o")), "group": "vowel", "letter": "o"}, ), ] class CassandraSession: table_name: str session: Any def __init__(self, table_name: str, session: Any): self.table_name = table_name self.session = session @contextmanager def get_cassandra_session( table_name: str, drop: bool = True ) -> Generator[CassandraSession, None, None]: """Initialize the Cassandra cluster and session""" from cassandra.cluster import Cluster if "CASSANDRA_CONTACT_POINTS" in os.environ: contact_points = [ cp.strip() for cp in os.environ["CASSANDRA_CONTACT_POINTS"].split(",") if cp.strip() ] else: contact_points = None cluster = Cluster(contact_points) session = cluster.connect() try: session.execute( ( f"CREATE KEYSPACE IF NOT EXISTS {TEST_KEYSPACE}" " WITH replication = " "{'class': 'SimpleStrategy', 'replication_factor': 1}" ) ) if drop: session.execute(f"DROP TABLE IF EXISTS {TEST_KEYSPACE}.{table_name}") # Yield the session for usage yield CassandraSession(table_name=table_name, session=session) finally: # Ensure proper shutdown/cleanup of resources session.shutdown() cluster.shutdown() @pytest.fixture def cassandra_session( request: pytest.FixtureRequest, ) -> Generator[CassandraSession, None, None]: request_param = getattr(request, "param", {}) table_name = request_param.get("table_name", "vector_test_table") drop = request_param.get("drop", True) with get_cassandra_session(table_name, drop) as session: yield session @contextmanager def vector_store_from_texts( texts: List[str], metadatas: Optional[List[dict]] = None, embedding: Optional[Embeddings] = None, drop: bool = True, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", table_name: str = "vector_test_table", ) -> Generator[Cassandra, None, None]: if embedding is None: embedding = ConsistentFakeEmbeddings() with get_cassandra_session(table_name=table_name, drop=drop) as session: yield Cassandra.from_texts( texts, embedding=embedding, metadatas=metadatas, session=session.session, keyspace=TEST_KEYSPACE, table_name=session.table_name, metadata_indexing=metadata_indexing, ) @asynccontextmanager async def vector_store_from_texts_async( texts: List[str], metadatas: Optional[List[dict]] = None, embedding: Optional[Embeddings] = None, drop: bool = True, metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", table_name: str = "vector_test_table", ) -> AsyncGenerator[Cassandra, None]: if embedding is None: embedding = ConsistentFakeEmbeddings() with get_cassandra_session(table_name=table_name, drop=drop) as session: yield await Cassandra.afrom_texts( texts, embedding=embedding, metadatas=metadatas, session=session.session, keyspace=TEST_KEYSPACE, table_name=session.table_name, metadata_indexing=metadata_indexing, ) @pytest.fixture(scope="function") def vector_store_d2( embedding_d2: Embeddings, table_name: str = "vector_test_table_d2", ) -> Generator[Cassandra, None, None]: with get_cassandra_session(table_name=table_name) as session: yield Cassandra( embedding=embedding_d2, session=session.session, keyspace=TEST_KEYSPACE, table_name=session.table_name, ) async def test_cassandra() -> None: """Test end to end construction and search.""" texts = ["foo", "bar", "baz"] with vector_store_from_texts(texts) as vstore: output = vstore.similarity_search("foo", k=1) assert _strip_docs(output) == _strip_docs([Document(page_content="foo")]) output = await vstore.asimilarity_search("foo", k=1) assert _strip_docs(output) == _strip_docs([Document(page_content="foo")]) async def test_cassandra_with_score() -> None: """Test end to end construction and search with scores and IDs.""" texts = ["foo", "bar", "baz"] metadatas = [{"page": i} for i in range(len(texts))] with vector_store_from_texts(texts, metadatas=metadatas) as vstore: expected_docs = [ Document(page_content="foo", metadata={"page": "0.0"}), Document(page_content="bar", metadata={"page": "1.0"}), Document(page_content="baz", metadata={"page": "2.0"}), ] output = vstore.similarity_search_with_score("foo", k=3) docs = [o[0] for o in output] scores = [o[1] for o in output] assert _strip_docs(docs) == _strip_docs(expected_docs) assert scores[0] > scores[1] > scores[2] output = await vstore.asimilarity_search_with_score("foo", k=3) docs = [o[0] for o in output] scores = [o[1] for o in output] assert _strip_docs(docs) == _strip_docs(expected_docs) assert scores[0] > scores[1] > scores[2] async def test_cassandra_max_marginal_relevance_search() -> None: """ Test end to end construction and MMR search. The embedding function used here ensures `texts` become the following vectors on a circle (numbered v0 through v3): ______ v2 / \ / | v1 v3 | . | query | / v0 |______/ (N.B. very crude drawing) With fetch_k==3 and k==2, when query is at (1, ), one expects that v2 and v0 are returned (in some order). """ texts = ["-0.124", "+0.127", "+0.25", "+1.0"] metadatas = [{"page": i} for i in range(len(texts))] with vector_store_from_texts( texts, metadatas=metadatas, embedding=AngularTwoDimensionalEmbeddings(), ) as vstore: expected_set = { ("+0.25", "2.0"), ("-0.124", "0.0"), } output = vstore.max_marginal_relevance_search("0.0", k=2, fetch_k=3) output_set = { (mmr_doc.page_content, mmr_doc.metadata["page"]) for mmr_doc in output } assert output_set == expected_set output = await vstore.amax_marginal_relevance_search("0.0", k=2, fetch_k=3) output_set = { (mmr_doc.page_content, mmr_doc.metadata["page"]) for mmr_doc in output } assert output_set == expected_set def test_cassandra_add_texts() -> None: """Test end to end construction with further insertions.""" texts = ["foo", "bar", "baz"] metadatas = [{"page": i} for i in range(len(texts))] with vector_store_from_texts(texts, metadatas=metadatas) as vstore: texts2 = ["foo2", "bar2", "baz2"] metadatas2 = [{"page": i + 3} for i in range(len(texts))] vstore.add_texts(texts2, metadatas2) output = vstore.similarity_search("foo", k=10) assert len(output) == 6 async def test_cassandra_add_texts_async() -> None: """Test end to end construction with further insertions.""" texts = ["foo", "bar", "baz"] metadatas = [{"page": i} for i in range(len(texts))] async with vector_store_from_texts_async(texts, metadatas=metadatas) as vstore: texts2 = ["foo2", "bar2", "baz2"] metadatas2 = [{"page": i + 3} for i in range(len(texts))] await vstore.aadd_texts(texts2, metadatas2) output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 6 def test_cassandra_no_drop() -> None: """Test end to end construction and re-opening the same index.""" texts = ["foo", "bar", "baz"] metadatas = [{"page": i} for i in range(len(texts))] with vector_store_from_texts(texts, metadatas=metadatas) as vstore: output = vstore.similarity_search("foo", k=10) assert len(output) == 3 texts2 = ["foo2", "bar2", "baz2"] with vector_store_from_texts(texts2, metadatas=metadatas, drop=False) as vstore: output = vstore.similarity_search("foo", k=10) assert len(output) == 6 async def test_cassandra_no_drop_async() -> None: """Test end to end construction and re-opening the same index.""" texts = ["foo", "bar", "baz"] metadatas = [{"page": i} for i in range(len(texts))] async with vector_store_from_texts_async(texts, metadatas=metadatas) as vstore: output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 3 texts2 = ["foo2", "bar2", "baz2"] async with vector_store_from_texts_async( texts2, metadatas=metadatas, drop=False ) as vstore: output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 6 def test_cassandra_delete() -> None: """Test delete methods from vector store.""" texts = ["foo", "bar", "baz", "gni"] metadatas = [{"page": i, "mod2": i % 2} for i in range(len(texts))] with vector_store_from_texts([], metadatas=metadatas) as vstore: ids = vstore.add_texts(texts, metadatas) output = vstore.similarity_search("foo", k=10) assert len(output) == 4 vstore.delete_by_document_id(ids[0]) output = vstore.similarity_search("foo", k=10) assert len(output) == 3 vstore.delete(ids[1:3]) output = vstore.similarity_search("foo", k=10) assert len(output) == 1 vstore.delete(["not-existing"]) output = vstore.similarity_search("foo", k=10) assert len(output) == 1 vstore.clear() time.sleep(0.3) output = vstore.similarity_search("foo", k=10) assert len(output) == 0 vstore.add_texts(texts, metadatas) num_deleted = vstore.delete_by_metadata_filter({"mod2": 0}, batch_size=1) assert num_deleted == 2 output = vstore.similarity_search("foo", k=10) assert len(output) == 2 vstore.clear() with pytest.raises(ValueError): vstore.delete_by_metadata_filter({}) async def test_cassandra_delete_async() -> None: """Test delete methods from vector store.""" texts = ["foo", "bar", "baz", "gni"] metadatas = [{"page": i, "mod2": i % 2} for i in range(len(texts))] async with vector_store_from_texts_async([], metadatas=metadatas) as vstore: ids = await vstore.aadd_texts(texts, metadatas) output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 4 await vstore.adelete_by_document_id(ids[0]) output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 3 await vstore.adelete(ids[1:3]) output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 1 await vstore.adelete(["not-existing"]) output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 1 await vstore.aclear() await asyncio.sleep(0.3) output = vstore.similarity_search("foo", k=10) assert len(output) == 0 await vstore.aadd_texts(texts, metadatas) num_deleted = await vstore.adelete_by_metadata_filter({"mod2": 0}, batch_size=1) assert num_deleted == 2 output = await vstore.asimilarity_search("foo", k=10) assert len(output) == 2 await vstore.aclear() with pytest.raises(ValueError): await vstore.adelete_by_metadata_filter({}) def test_cassandra_metadata_indexing() -> None: """Test comparing metadata indexing policies.""" texts = ["foo"] metadatas = [{"field1": "a", "field2": "b"}] with vector_store_from_texts(texts, metadatas=metadatas) as vstore_all: with vector_store_from_texts( texts, metadatas=metadatas, metadata_indexing=("allowlist", ["field1"]), table_name="vector_test_table_indexing", embedding=ConsistentFakeEmbeddings(), ) as vstore_f1: output_all = vstore_all.similarity_search("bar", k=2) output_f1 = vstore_f1.similarity_search("bar", filter={"field1": "a"}, k=2) output_f1_no = vstore_f1.similarity_search( "bar", filter={"field1": "Z"}, k=2 ) assert len(output_all) == 1 assert output_all[0].metadata == metadatas[0] assert len(output_f1) == 1 assert output_f1[0].metadata == metadatas[0] assert len(output_f1_no) == 0 with pytest.raises(ValueError): # "Non-indexed metadata fields cannot be used in queries." vstore_f1.similarity_search("bar", filter={"field2": "b"}, k=2) class TestCassandraVectorStore: @pytest.mark.parametrize( "page_contents", [ [ "[1,2]", "[3,4]", "[5,6]", "[7,8]", "[9,10]", "[11,12]", ], ], ) def test_cassandra_vectorstore_from_texts_sync( self, *, cassandra_session: CassandraSession, embedding_d2: Embeddings, page_contents: list[str], ) -> None: """from_texts methods and the associated warnings.""" v_store = Cassandra.from_texts( texts=page_contents[0:2], metadatas=[{"m": 1}, {"m": 3}], ids=["ft1", "ft3"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) search_results_triples_0 = v_store.similarity_search_with_score_id( page_contents[1], k=1, ) assert len(search_results_triples_0) == 1 res_doc_0, _, res_id_0 = search_results_triples_0[0] assert res_doc_0.page_content == page_contents[1] assert res_doc_0.metadata == {"m": "3.0"} assert res_id_0 == "ft3" Cassandra.from_texts( texts=page_contents[2:4], metadatas=[{"m": 5}, {"m": 7}], ids=["ft5", "ft7"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) search_results_triples_1 = v_store.similarity_search_with_score_id( page_contents[3], k=1, ) assert len(search_results_triples_1) == 1 res_doc_1, _, res_id_1 = search_results_triples_1[0] assert res_doc_1.page_content == page_contents[3] assert res_doc_1.metadata == {"m": "7.0"} assert res_id_1 == "ft7" v_store_2 = Cassandra.from_texts( texts=page_contents[4:6], metadatas=[{"m": 9}, {"m": 11}], ids=["ft9", "ft11"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) search_results_triples_2 = v_store_2.similarity_search_with_score_id( page_contents[5], k=1, ) assert len(search_results_triples_2) == 1 res_doc_2, _, res_id_2 = search_results_triples_2[0] assert res_doc_2.page_content == page_contents[5] assert res_doc_2.metadata == {"m": "11.0"} assert res_id_2 == "ft11" v_store_2.clear() @pytest.mark.parametrize( "page_contents", [ ["[1,2]", "[3,4]"], ], ) def test_cassandra_vectorstore_from_documents_sync( self, *, cassandra_session: CassandraSession, embedding_d2: Embeddings, page_contents: list[str], ) -> None: """from_documents, esp. the various handling of ID-in-doc vs external.""" pc1, pc2 = page_contents # no IDs. v_store = Cassandra.from_documents( [ Document(page_content=pc1, metadata={"m": 1}), Document(page_content=pc2, metadata={"m": 3}), ], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) hits = v_store.similarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} v_store.clear() # IDs passed separately. with pytest.warns(DeprecationWarning) as rec_warnings: v_store_2 = Cassandra.from_documents( [ Document(page_content=pc1, metadata={"m": 1}), Document(page_content=pc2, metadata={"m": 3}), ], ids=["idx1", "idx3"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) f_rec_warnings = [ wrn for wrn in rec_warnings if issubclass(wrn.category, DeprecationWarning) ] assert len(f_rec_warnings) == 1 hits = v_store_2.similarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} assert hits[0].id == "idx3" v_store_2.clear() # IDs in documents. v_store_3 = Cassandra.from_documents( [ Document(page_content=pc1, metadata={"m": 1}, id="idx1"), Document(page_content=pc2, metadata={"m": 3}, id="idx3"), ], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) hits = v_store_3.similarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} assert hits[0].id == "idx3" v_store_3.clear() # IDs both in documents and aside. with pytest.warns(DeprecationWarning) as rec_warnings: v_store_4 = Cassandra.from_documents( [ Document(page_content=pc1, metadata={"m": 1}), Document(page_content=pc2, metadata={"m": 3}, id="idy3"), ], ids=["idx1", "idx3"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) f_rec_warnings = [ wrn for wrn in rec_warnings if issubclass(wrn.category, DeprecationWarning) ] hits = v_store_4.similarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} assert hits[0].id == "idx3" v_store_4.clear() @pytest.mark.parametrize( "page_contents", [ [ "[1,2]", "[3,4]", "[5,6]", "[7,8]", "[9,10]", "[11,12]", ], ], ) async def test_cassandra_vectorstore_from_texts_async( self, *, cassandra_session: CassandraSession, embedding_d2: Embeddings, page_contents: list[str], ) -> None: """from_texts methods and the associated warnings, async version.""" v_store = await Cassandra.afrom_texts( texts=page_contents[0:2], metadatas=[{"m": 1}, {"m": 3}], ids=["ft1", "ft3"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) search_results_triples_0 = await v_store.asimilarity_search_with_score_id( page_contents[1], k=1, ) assert len(search_results_triples_0) == 1 res_doc_0, _, res_id_0 = search_results_triples_0[0] assert res_doc_0.page_content == page_contents[1] assert res_doc_0.metadata == {"m": "3.0"} assert res_id_0 == "ft3" await Cassandra.afrom_texts( texts=page_contents[2:4], metadatas=[{"m": 5}, {"m": 7}], ids=["ft5", "ft7"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) search_results_triples_1 = await v_store.asimilarity_search_with_score_id( page_contents[3], k=1, ) assert len(search_results_triples_1) == 1 res_doc_1, _, res_id_1 = search_results_triples_1[0] assert res_doc_1.page_content == page_contents[3] assert res_doc_1.metadata == {"m": "7.0"} assert res_id_1 == "ft7" v_store_2 = await Cassandra.afrom_texts( texts=page_contents[4:6], metadatas=[{"m": 9}, {"m": 11}], ids=["ft9", "ft11"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) search_results_triples_2 = await v_store_2.asimilarity_search_with_score_id( page_contents[5], k=1, ) assert len(search_results_triples_2) == 1 res_doc_2, _, res_id_2 = search_results_triples_2[0] assert res_doc_2.page_content == page_contents[5] assert res_doc_2.metadata == {"m": "11.0"} assert res_id_2 == "ft11" await v_store_2.aclear() @pytest.mark.parametrize( "page_contents", [ ["[1,2]", "[3,4]"], ], ) async def test_cassandra_vectorstore_from_documents_async( self, *, cassandra_session: CassandraSession, embedding_d2: Embeddings, page_contents: list[str], ) -> None: """ from_documents, esp. the various handling of ID-in-doc vs external. Async version. """ pc1, pc2 = page_contents # no IDs. v_store = await Cassandra.afrom_documents( [ Document(page_content=pc1, metadata={"m": 1}), Document(page_content=pc2, metadata={"m": 3}), ], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) hits = await v_store.asimilarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} await v_store.aclear() # IDs passed separately. with pytest.warns(DeprecationWarning) as rec_warnings: v_store_2 = await Cassandra.afrom_documents( [ Document(page_content=pc1, metadata={"m": 1}), Document(page_content=pc2, metadata={"m": 3}), ], ids=["idx1", "idx3"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) f_rec_warnings = [ wrn for wrn in rec_warnings if issubclass(wrn.category, DeprecationWarning) ] assert len(f_rec_warnings) == 1 hits = await v_store_2.asimilarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} assert hits[0].id == "idx3" await v_store_2.aclear() # IDs in documents. v_store_3 = await Cassandra.afrom_documents( [ Document(page_content=pc1, metadata={"m": 1}, id="idx1"), Document(page_content=pc2, metadata={"m": 3}, id="idx3"), ], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) hits = await v_store_3.asimilarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} assert hits[0].id == "idx3" await v_store_3.aclear() # IDs both in documents and aside. with pytest.warns(DeprecationWarning) as rec_warnings: v_store_4 = await Cassandra.afrom_documents( [ Document(page_content=pc1, metadata={"m": 1}), Document(page_content=pc2, metadata={"m": 3}, id="idy3"), ], ids=["idx1", "idx3"], table_name=cassandra_session.table_name, session=cassandra_session.session, keyspace=TEST_KEYSPACE, embedding=embedding_d2, ) f_rec_warnings = [ wrn for wrn in rec_warnings if issubclass(wrn.category, DeprecationWarning) ] assert len(f_rec_warnings) == 1 hits = await v_store_4.asimilarity_search(pc2, k=1) assert len(hits) == 1 assert hits[0].page_content == pc2 assert hits[0].metadata == {"m": "3.0"} assert hits[0].id == "idx3" await v_store_4.aclear() def test_cassandra_vectorstore_crud_sync( self, vector_store_d2: Cassandra, ) -> None: """Add/delete/update behaviour.""" vstore = vector_store_d2 res0 = vstore.similarity_search("[-1,-1]", k=2) assert res0 == [] # write and check again added_ids = vstore.add_texts( texts=["[1,2]", "[3,4]", "[5,6]"], metadatas=[ {"k": "a", "ord": 0}, {"k": "b", "ord": 1}, {"k": "c", "ord": 2}, ], ids=["a", "b", "c"], ) # not requiring ordered match (elsewhere it may be overwriting some) assert set(added_ids) == {"a", "b", "c"} res1 = vstore.similarity_search("[-1,-1]", k=5) assert {doc.page_content for doc in res1} == {"[1,2]", "[3,4]", "[5,6]"} res2 = vstore.similarity_search("[3,4]", k=1) assert len(res2) == 1 assert res2[0].page_content == "[3,4]" assert res2[0].metadata == {"k": "b", "ord": "1.0"} assert res2[0].id == "b" # partial overwrite and count total entries added_ids_1 = vstore.add_texts( texts=["[5,6]", "[7,8]"], metadatas=[ {"k": "c_new", "ord": 102}, {"k": "d_new", "ord": 103}, ], ids=["c", "d"], ) # not requiring ordered match (elsewhere it may be overwriting some) assert set(added_ids_1) == {"c", "d"} res2 = vstore.similarity_search("[-1,-1]", k=10) assert len(res2) == 4 # pick one that was just updated and check its metadata res3 = vstore.similarity_search_with_score_id( query="[5,6]", k=1, filter={"k": "c_new"} ) doc3, _, id3 = res3[0] assert doc3.page_content == "[5,6]" assert doc3.metadata == {"k": "c_new", "ord": "102.0"} assert id3 == "c" # delete and count again del1_res = vstore.delete(["b"]) assert del1_res is True del2_res = vstore.delete(["a", "c", "Z!"]) assert del2_res is True # a non-existing ID was supplied assert len(vstore.similarity_search("[-1,-1]", k=10)) == 1 # clear store vstore.clear() assert vstore.similarity_search("[-1,-1]", k=2) == [] # add_documents with "ids" arg passthrough vstore.add_documents( [ Document(page_content="[9,10]", metadata={"k": "v", "ord": 204}), Document(page_content="[11,12]", metadata={"k": "w", "ord": 205}), ], ids=["v", "w"], ) assert len(vstore.similarity_search("[-1,-1]", k=10)) == 2 res4 = vstore.similarity_search("[11,12]", k=1, filter={"k": "w"}) assert res4[0].metadata["ord"] == "205.0" assert res4[0].id == "w" # add_texts with "ids" arg passthrough vstore.add_texts( texts=["[13,14]", "[15,16]"], metadatas=[{"k": "r", "ord": 306}, {"k": "s", "ord": 307}], ids=["r", "s"], ) assert len(vstore.similarity_search("[-1,-1]", k=10)) == 4 res4 = vstore.similarity_search("[-1,-1]", k=1, filter={"k": "s"}) assert res4[0].metadata["ord"] == "307.0" assert res4[0].id == "s" # delete_by_document_id vstore.delete_by_document_id("s") assert len(vstore.similarity_search("[-1,-1]", k=10)) == 3 async def test_cassandra_vectorstore_crud_async( self, vector_store_d2: Cassandra, ) -> None: """Add/delete/update behaviour, async version.""" vstore = vector_store_d2 res0 = await vstore.asimilarity_search("[-1,-1]", k=2) assert res0 == [] # write and check again added_ids = await vstore.aadd_texts( texts=["[1,2]", "[3,4]", "[5,6]"], metadatas=[ {"k": "a", "ord": 0}, {"k": "b", "ord": 1}, {"k": "c", "ord": 2}, ], ids=["a", "b", "c"], ) # not requiring ordered match (elsewhere it may be overwriting some) assert set(added_ids) == {"a", "b", "c"} res1 = await vstore.asimilarity_search("[-1,-1]", k=5) assert {doc.page_content for doc in res1} == {"[1,2]", "[3,4]", "[5,6]"} res2 = await vstore.asimilarity_search("[3,4]", k=1) assert len(res2) == 1 assert res2[0].page_content == "[3,4]" assert res2[0].metadata == {"k": "b", "ord": "1.0"} assert res2[0].id == "b" # partial overwrite and count total entries added_ids_1 = await vstore.aadd_texts( texts=["[5,6]", "[7,8]"], metadatas=[ {"k": "c_new", "ord": 102}, {"k": "d_new", "ord": 103}, ], ids=["c", "d"], ) # not requiring ordered match (elsewhere it may be overwriting some) assert set(added_ids_1) == {"c", "d"} res2 = await vstore.asimilarity_search("[-1,-1]", k=10) assert len(res2) == 4 # pick one that was just updated and check its metadata res3 = await vstore.asimilarity_search_with_score_id( query="[5,6]", k=1, filter={"k": "c_new"} ) doc3, _, id3 = res3[0] assert doc3.page_content == "[5,6]" assert doc3.metadata == {"k": "c_new", "ord": "102.0"} assert id3 == "c" # delete and count again del1_res = await vstore.adelete(["b"]) assert del1_res is True del2_res = await vstore.adelete(["a", "c", "Z!"]) assert del2_res is True # a non-existing ID was supplied assert len(await vstore.asimilarity_search("[-1,-1]", k=10)) == 1 # clear store await vstore.aclear() assert await vstore.asimilarity_search("[-1,-1]", k=2) == [] # add_documents with "ids" arg passthrough await vstore.aadd_documents( [ Document(page_content="[9,10]", metadata={"k": "v", "ord": 204}), Document(page_content="[11,12]", metadata={"k": "w", "ord": 205}), ], ids=["v", "w"], ) assert len(await vstore.asimilarity_search("[-1,-1]", k=10)) == 2 res4 = await vstore.asimilarity_search("[11,12]", k=1, filter={"k": "w"}) assert res4[0].metadata["ord"] == "205.0" assert res4[0].id == "w" # add_texts with "ids" arg passthrough await vstore.aadd_texts( texts=["[13,14]", "[15,16]"], metadatas=[{"k": "r", "ord": 306}, {"k": "s", "ord": 307}], ids=["r", "s"], ) assert len(await vstore.asimilarity_search("[-1,-1]", k=10)) == 4 res4 = await vstore.asimilarity_search("[-1,-1]", k=1, filter={"k": "s"}) assert res4[0].metadata["ord"] == "307.0" assert res4[0].id == "s" # delete_by_document_id await vstore.adelete_by_document_id("s") assert len(await vstore.asimilarity_search("[-1,-1]", k=10)) == 3 def test_cassandra_vectorstore_massive_insert_replace_sync( self, vector_store_d2: Cassandra, ) -> None: """Testing the insert-many-and-replace-some patterns thoroughly.""" full_size = 300 first_group_size = 150 second_group_slicer = [30, 100, 2] all_ids = [f"doc_{idx}" for idx in range(full_size)] all_texts = [f"[0,{idx + 1}]" for idx in range(full_size)] # massive insertion on empty group0_ids = all_ids[0:first_group_size] group0_texts = all_texts[0:first_group_size] inserted_ids0 = vector_store_d2.add_texts( texts=group0_texts, ids=group0_ids, ) assert set(inserted_ids0) == set(group0_ids) # massive insertion with many overwrites scattered through # (we change the text to later check on DB for successful update) _s, _e, _st = second_group_slicer group1_ids = all_ids[_s:_e:_st] + all_ids[first_group_size:full_size] group1_texts = [ txt.upper() for txt in (all_texts[_s:_e:_st] + all_texts[first_group_size:full_size]) ] inserted_ids1 = vector_store_d2.add_texts( texts=group1_texts, ids=group1_ids, ) assert set(inserted_ids1) == set(group1_ids) # final read (we want the IDs to do a full check) expected_text_by_id = { **dict(zip(group0_ids, group0_texts)), **dict(zip(group1_ids, group1_texts)), } full_results = vector_store_d2.similarity_search_with_score_id_by_vector( embedding=[1.0, 1.0], k=full_size, ) for doc, _, doc_id in full_results: assert doc.page_content == expected_text_by_id[doc_id] async def test_cassandra_vectorstore_massive_insert_replace_async( self, vector_store_d2: Cassandra, ) -> None: """ Testing the insert-many-and-replace-some patterns thoroughly. Async version. """ full_size = 300 first_group_size = 150 second_group_slicer = [30, 100, 2] all_ids = [f"doc_{idx}" for idx in range(full_size)] all_texts = [f"[0,{idx + 1}]" for idx in range(full_size)] all_embeddings = [[0, idx + 1] for idx in range(full_size)] # massive insertion on empty group0_ids = all_ids[0:first_group_size] group0_texts = all_texts[0:first_group_size] inserted_ids0 = await vector_store_d2.aadd_texts( texts=group0_texts, ids=group0_ids, ) assert set(inserted_ids0) == set(group0_ids) # massive insertion with many overwrites scattered through # (we change the text to later check on DB for successful update) _s, _e, _st = second_group_slicer group1_ids = all_ids[_s:_e:_st] + all_ids[first_group_size:full_size] group1_texts = [ txt.upper() for txt in (all_texts[_s:_e:_st] + all_texts[first_group_size:full_size]) ] inserted_ids1 = await vector_store_d2.aadd_texts( texts=group1_texts, ids=group1_ids, ) assert set(inserted_ids1) == set(group1_ids) # final read (we want the IDs to do a full check) expected_text_by_id = dict(zip(all_ids, all_texts)) full_results = await vector_store_d2.asimilarity_search_with_score_id_by_vector( embedding=[1.0, 1.0], k=full_size, ) for doc, _, doc_id in full_results: assert doc.page_content == expected_text_by_id[doc_id] expected_embedding_by_id = dict(zip(all_ids, all_embeddings)) full_results_with_embeddings = ( await vector_store_d2.asimilarity_search_with_embedding_id_by_vector( embedding=[1.0, 1.0], k=full_size, ) ) for doc, embedding, doc_id in full_results_with_embeddings: assert doc.page_content == expected_text_by_id[doc_id] assert embedding == expected_embedding_by_id[doc_id] def test_cassandra_vectorstore_delete_by_metadata_sync( self, vector_store_d2: Cassandra, ) -> None: """Testing delete_by_metadata_filter.""" full_size = 400 # one in ... will be deleted deletee_ratio = 3 documents = [ Document( page_content="[1,1]", metadata={"deletee": doc_i % deletee_ratio == 0} ) for doc_i in range(full_size) ] num_deletees = len([doc for doc in documents if doc.metadata["deletee"]]) inserted_ids0 = vector_store_d2.add_documents(documents) assert len(inserted_ids0) == len(documents) d_result0 = vector_store_d2.delete_by_metadata_filter({"deletee": True}) assert d_result0 == num_deletees count_on_store0 = len( vector_store_d2.similarity_search("[1,1]", k=full_size + 1) ) assert count_on_store0 == full_size - num_deletees with pytest.raises(ValueError, match="does not accept an empty"): vector_store_d2.delete_by_metadata_filter({}) count_on_store1 = len( vector_store_d2.similarity_search("[1,1]", k=full_size + 1) ) assert count_on_store1 == full_size - num_deletees async def test_cassandra_vectorstore_delete_by_metadata_async( self, vector_store_d2: Cassandra, ) -> None: """Testing delete_by_metadata_filter, async version.""" full_size = 400 # one in ... will be deleted deletee_ratio = 3 documents = [ Document( page_content="[1,1]", metadata={"deletee": doc_i % deletee_ratio == 0} ) for doc_i in range(full_size) ] num_deletees = len([doc for doc in documents if doc.metadata["deletee"]]) inserted_ids0 = await vector_store_d2.aadd_documents(documents) assert len(inserted_ids0) == len(documents) d_result0 = await vector_store_d2.adelete_by_metadata_filter({"deletee": True}) assert d_result0 == num_deletees count_on_store0 = len( await vector_store_d2.asimilarity_search("[1,1]", k=full_size + 1) ) assert count_on_store0 == full_size - num_deletees with pytest.raises(ValueError, match="does not accept an empty"): await vector_store_d2.adelete_by_metadata_filter({}) count_on_store1 = len( await vector_store_d2.asimilarity_search("[1,1]", k=full_size + 1) ) assert count_on_store1 == full_size - num_deletees def test_cassandra_replace_metadata(self) -> None: """Test of replacing metadata.""" N_DOCS = 100 REPLACE_RATIO = 2 # one in ... will have replaced metadata BATCH_SIZE = 3 with vector_store_from_texts( texts=[], metadata_indexing=("allowlist", ["field1", "field2"]), table_name="vector_test_table_indexing", ) as vstore_f1: orig_documents = [ Document( page_content=f"doc_{doc_i}", id=f"doc_id_{doc_i}", metadata={"field1": f"f1_{doc_i}", "otherf": "pre"}, ) for doc_i in range(N_DOCS) ] vstore_f1.add_documents(orig_documents) ids_to_replace = [ f"doc_id_{doc_i}" for doc_i in range(N_DOCS) if doc_i % REPLACE_RATIO == 0 ] # various kinds of replacement at play here: def _make_new_md(mode: int, doc_id: str) -> dict[str, str]: if mode == 0: return {} elif mode == 1: return {"field2": f"NEW_{doc_id}"} elif mode == 2: return {"field2": f"NEW_{doc_id}", "ofherf2": "post"} else: return {"ofherf2": "post"} ids_to_new_md = { doc_id: _make_new_md(rep_i % 4, doc_id) for rep_i, doc_id in enumerate(ids_to_replace) } vstore_f1.replace_metadata(ids_to_new_md, batch_size=BATCH_SIZE) # thorough check expected_id_to_metadata: dict[str, dict] = { **{ (document.id or ""): document.metadata for document in orig_documents }, **ids_to_new_md, } for hit in vstore_f1.similarity_search("doc", k=N_DOCS + 1): assert hit.id is not None assert hit.metadata == expected_id_to_metadata[hit.id] async def test_cassandra_replace_metadata_async(self) -> None: """Test of replacing metadata.""" N_DOCS = 100 REPLACE_RATIO = 2 # one in ... will have replaced metadata BATCH_SIZE = 3 async with vector_store_from_texts_async( texts=[], metadata_indexing=("allowlist", ["field1", "field2"]), table_name="vector_test_table_indexing", embedding=ConsistentFakeEmbeddings(), ) as vstore_f1: orig_documents = [ Document( page_content=f"doc_{doc_i}", id=f"doc_id_{doc_i}", metadata={"field1": f"f1_{doc_i}", "otherf": "pre"}, ) for doc_i in range(N_DOCS) ] await vstore_f1.aadd_documents(orig_documents) ids_to_replace = [ f"doc_id_{doc_i}" for doc_i in range(N_DOCS) if doc_i % REPLACE_RATIO == 0 ] # various kinds of replacement at play here: def _make_new_md(mode: int, doc_id: str) -> dict[str, str]: if mode == 0: return {} elif mode == 1: return {"field2": f"NEW_{doc_id}"} elif mode == 2: return {"field2": f"NEW_{doc_id}", "ofherf2": "post"} else: return {"ofherf2": "post"} ids_to_new_md = { doc_id: _make_new_md(rep_i % 4, doc_id) for rep_i, doc_id in enumerate(ids_to_replace) } await vstore_f1.areplace_metadata(ids_to_new_md, concurrency=BATCH_SIZE) # thorough check expected_id_to_metadata: dict[str, dict] = { **{ (document.id or ""): document.metadata for document in orig_documents }, **ids_to_new_md, } for hit in await vstore_f1.asimilarity_search("doc", k=N_DOCS + 1): assert hit.id is not None assert hit.metadata == expected_id_to_metadata[hit.id] def test_cassandra_vectorstore_mmr_sync( self, vector_store_d2: Cassandra, ) -> None: """MMR testing. We work on the unit circle with angle multiples of 2*pi/20 and prepare a store with known vectors for a controlled MMR outcome. """ def _v_from_i(i: int, n: int) -> str: angle = 2 * math.pi * i / n vector = [math.cos(angle), math.sin(angle)] return json.dumps(vector) i_vals = [0, 4, 5, 13] n_val = 20 vector_store_d2.add_texts( [_v_from_i(i, n_val) for i in i_vals], metadatas=[{"i": i} for i in i_vals] ) res1 = vector_store_d2.max_marginal_relevance_search( _v_from_i(3, n_val), k=2, fetch_k=3, ) res_i_vals = {doc.metadata["i"] for doc in res1} assert res_i_vals == {"0.0", "4.0"} async def test_cassandra_vectorstore_mmr_async( self, vector_store_d2: Cassandra, ) -> None: """MMR testing. We work on the unit circle with angle multiples of 2*pi/20 and prepare a store with known vectors for a controlled MMR outcome. Async version. """ def _v_from_i(i: int, n: int) -> str: angle = 2 * math.pi * i / n vector = [math.cos(angle), math.sin(angle)] return json.dumps(vector) i_vals = [0, 4, 5, 13] n_val = 20 await vector_store_d2.aadd_texts( [_v_from_i(i, n_val) for i in i_vals], metadatas=[{"i": i} for i in i_vals], ) res1 = await vector_store_d2.amax_marginal_relevance_search( _v_from_i(3, n_val), k=2, fetch_k=3, ) res_i_vals = {doc.metadata["i"] for doc in res1} assert res_i_vals == {"0.0", "4.0"} def test_cassandra_vectorstore_metadata_filter( self, vector_store_d2: Cassandra, metadata_documents: list[Document], ) -> None: """Metadata filtering.""" vstore = vector_store_d2 vstore.add_documents(metadata_documents) # no filters res0 = vstore.similarity_search("[-1,-1]", k=10) assert {doc.metadata["letter"] for doc in res0} == set("qwreio") # single filter res1 = vstore.similarity_search( "[-1,-1]", k=10, filter={"group": "vowel"}, ) assert {doc.metadata["letter"] for doc in res1} == set("eio") # multiple filters res2 = vstore.similarity_search( "[-1,-1]", k=10, filter={"group": "consonant", "ord": str(ord("q"))}, ) assert {doc.metadata["letter"] for doc in res2} == set("q") # excessive filters res3 = vstore.similarity_search( "[-1,-1]", k=10, filter={"group": "consonant", "ord": str(ord("q")), "case": "upper"}, ) assert res3 == [] def test_cassandra_vectorstore_metadata_search_sync( self, vector_store_d2: Cassandra, metadata_documents: list[Document], ) -> None: """Metadata Search""" vstore = vector_store_d2 vstore.add_documents(metadata_documents) # no filters res0 = vstore.metadata_search(filter={}, n=10) assert {doc.metadata["letter"] for doc in res0} == set("qwreio") # single filter res1 = vstore.metadata_search( n=10, filter={"group": "vowel"}, ) assert {doc.metadata["letter"] for doc in res1} == set("eio") # multiple filters res2 = vstore.metadata_search( n=10, filter={"group": "consonant", "ord": str(ord("q"))}, ) assert {doc.metadata["letter"] for doc in res2} == set("q") # excessive filters res3 = vstore.metadata_search( n=10, filter={"group": "consonant", "ord": str(ord("q")), "case": "upper"}, ) assert res3 == [] async def test_cassandra_vectorstore_metadata_search_async( self, vector_store_d2: Cassandra, metadata_documents: list[Document], ) -> None: """Metadata Search""" vstore = vector_store_d2 await vstore.aadd_documents(metadata_documents) # no filters res0 = await vstore.ametadata_search(filter={}, n=10) assert {doc.metadata["letter"] for doc in res0} == set("qwreio") # single filter res1 = vstore.metadata_search( n=10, filter={"group": "vowel"}, ) assert {doc.metadata["letter"] for doc in res1} == set("eio") # multiple filters res2 = await vstore.ametadata_search( n=10, filter={"group": "consonant", "ord": str(ord("q"))}, ) assert {doc.metadata["letter"] for doc in res2} == set("q") # excessive filters res3 = await vstore.ametadata_search( n=10, filter={"group": "consonant", "ord": str(ord("q")), "case": "upper"}, ) assert res3 == [] def test_cassandra_vectorstore_get_by_document_id_sync( self, vector_store_d2: Cassandra, metadata_documents: list[Document], ) -> None: """Get by document_id""" vstore = vector_store_d2 vstore.add_documents(metadata_documents) # invalid id invalid = vstore.get_by_document_id(document_id="z") assert invalid is None # valid id valid = vstore.get_by_document_id(document_id="q") assert isinstance(valid, Document) assert valid.id == "q" assert valid.page_content == "[1,2]" assert valid.metadata["group"] == "consonant" assert valid.metadata["letter"] == "q" async def test_cassandra_vectorstore_get_by_document_id_async( self, vector_store_d2: Cassandra, metadata_documents: list[Document], ) -> None: """Get by document_id""" vstore = vector_store_d2 await vstore.aadd_documents(metadata_documents) # invalid id invalid = await vstore.aget_by_document_id(document_id="z") assert invalid is None # valid id valid = await vstore.aget_by_document_id(document_id="q") assert isinstance(valid, Document) assert valid.id == "q" assert valid.page_content == "[1,2]" assert valid.metadata["group"] == "consonant" assert valid.metadata["letter"] == "q" @pytest.mark.parametrize( ("texts", "query"), [ ( ["[1,1]", "[-1,-1]"], "[0.99999,1.00001]", ), ], ) def test_cassandra_vectorstore_similarity_scale_sync( self, *, vector_store_d2: Cassandra, texts: list[str], query: str, ) -> None: """Scale of the similarity scores.""" vstore = vector_store_d2 vstore.add_texts( texts=texts, ids=["near", "far"], ) res1 = vstore.similarity_search_with_score( query, k=2, ) scores = [sco for _, sco in res1] sco_near, sco_far = scores assert sco_far >= 0 assert abs(1 - sco_near) < MATCH_EPSILON assert sco_far < EUCLIDEAN_MIN_SIM_UNIT_VECTORS + MATCH_EPSILON @pytest.mark.parametrize( ("texts", "query"), [ ( ["[1,1]", "[-1,-1]"], "[0.99999,1.00001]", ), ], ) async def test_cassandra_vectorstore_similarity_scale_async( self, *, vector_store_d2: Cassandra, texts: list[str], query: str, ) -> None: """Scale of the similarity scores, async version.""" vstore = vector_store_d2 await vstore.aadd_texts( texts=texts, ids=["near", "far"], ) res1 = await vstore.asimilarity_search_with_score( query, k=2, ) scores = [sco for _, sco in res1] sco_near, sco_far = scores assert sco_far >= 0 assert abs(1 - sco_near) < MATCH_EPSILON assert sco_far < EUCLIDEAN_MIN_SIM_UNIT_VECTORS + MATCH_EPSILON def test_cassandra_vectorstore_massive_delete( self, vector_store_d2: Cassandra, ) -> None: """Larger-scale bulk deletes.""" vstore = vector_store_d2 m = 150 texts = [f"[0,{i + 1 / 7.0}]" for i in range(2 * m)] ids0 = [f"doc_{i}" for i in range(m)] ids1 = [f"doc_{i + m}" for i in range(m)] ids = ids0 + ids1 vstore.add_texts(texts=texts, ids=ids) # deleting a bunch of these del_res0 = vstore.delete(ids0) assert del_res0 is True # deleting the rest plus a fake one del_res1 = vstore.delete([*ids1, "ghost!"]) assert del_res1 is True # ensure no error # nothing left assert vstore.similarity_search("[-1,-1]", k=2 * m) == []
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@tests@integration_tests@vectorstores@test_cassandra.py@.PATH_END.py
{ "filename": "drs_lang.py", "repo_name": "njcuk9999/apero-drs", "repo_path": "apero-drs_extracted/apero-drs-main/apero/lang/core/drs_lang.py", "type": "Python" }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Language database functionality Created on 2020-11-2020-11-13 10:41 @author: cook # import rules only from: - apero.base.base - apero.base.drs_base - apero.base.drs_db """ import os import shutil from typing import Any, Dict, List, Union import numpy as np import pandas as pd from apero.base import base from apero.base import drs_base from apero.base import drs_db # ============================================================================= # Define variables # ============================================================================= __NAME__ = 'apero.lang.drs_lang.py' __PACKAGE__ = base.__PACKAGE__ __INSTRUMENT__ = 'None' __version__ = base.__version__ __author__ = base.__author__ __date__ = base.__date__ __release__ = base.__release__ # get language from base DEFAULT_LANG = base.DEFAULT_LANG LANG = base.IPARAMS.get('LANGUAGE', DEFAULT_LANG) # get and load the language database once # noinspection PyBroadException try: langdbm = drs_db.LanguageDatabase() # load database langdbm.load_db() # if we can't access straight away go to proxy langdbm.database.tries = 1 # Can be the case that we have the database but we are yet to # create the language table - in this case we need to use the proxy # dictionary instead - else we get the dictionary from the langauage # database table if langdbm.database.tname in langdbm.database.tables: langdict = langdbm.get_dict(language=LANG) else: langdict = drs_base.lang_db_proxy() # if we can't then we have no language database except Exception as _: langdict = drs_base.lang_db_proxy() # define the database path relative to package DATABASE_PATH = base.LANG_DEFAULT_PATH # define the backup path relative to package BACKUP_PATH = base.LANG_BACKUP_PATH # define the database (xls file) DATABASE_FILE = base.LANG_XLS_FILE # ============================================================================= # Define classes # ============================================================================= class LanguageException(Exception): """ Base language exception class """ pass class LanguageError(LanguageException): def __init__(self, message: Union[str, None] = None, errorobj: Any = None, func_name: Union[str, None] = None): """ Construct the Database Error instance :param message: str a mesage to pass / print :param errorobj: the error instance (or anything else) :param func_name: str, the function name where error occured """ self.message = message self.errorobj = errorobj self.func_name = func_name # call super class super().__init__(message) def __getstate__(self) -> dict: """ For when we have to pickle the class :return: """ # set state to __dict__ state = dict(self.__dict__) # return dictionary state (for pickle) return state def __setstate__(self, state): """ For when we have to unpickle the class :param state: dictionary from pickle :return: """ # update dict with state self.__dict__.update(state) def __str__(self): """ Standard __str__ return (used in raising as Exception) :return: """ emsg = 'Language Error: {0}'.format(self.message) return emsg class Text(str): """ Special text container (so we can store text entry key) """ def __init__(self, *args, **kwargs): str.__init__(*args, **kwargs) self.tkey = None self.tvalue = str(args[0]) self.targs = None self.tkwargs = None self.t_short = '' self.formatted = False def __getstate__(self) -> dict: """ For when we have to pickle the class :return: """ # set state to __dict__ state = dict(self.__dict__) # return dictionary state (for pickle) return state def __setstate__(self, state): """ For when we have to unpickle the class :param state: dictionary from pickle :return: """ # update dict with state self.__dict__.update(state) def __add__(self, other: Union['Text', str]): """ string-like addition (returning a Text instance) Equivalent to x + y :param other: Text or str, add 'other' (y) to end of self (x) :return: combined string (x + y) (self + other) """ # must merge changes from other if Text instance if isinstance(other, Text): othertext = other.get_text() else: othertext = str(other) # make new object msg = Text(self.get_text() + othertext) # set text properties msg.set_text_props(self.tkey) return msg def __radd__(self, other: Union['Text', str]): """ string-like addition (returning a Text instance) Equivalent to y + x :param other: Text or str, add 'other' (y) to start of self (x) :return: combined string (y + x) (other + self) """ # must merge changes from other if Text instance if isinstance(other, Text): othertext = other.get_text() else: othertext = str(other) # make new object msg = Text(othertext + self.get_text()) # set text properties msg.set_text_props(self.tkey) return msg def __mul__(self, other: Any) -> Any: """ Do not allow multiplication :param other: Any, anything else to multiple by :return: """ NotImplemented('Multiply in {0}.Text not implemented'.format(__NAME__)) def __repr__(self) -> str: """ String representation of Text class :return: str, the string representation of the Text class """ if not self.formatted: self.get_formatting() return str(self.tvalue) def __str__(self) -> str: """ String representation of Text class :return: str, the string representation of the Text class """ if not self.formatted: self.get_formatting() return str(self.tvalue) def set_text_props(self, key: str, args: Union[List[Any], str, None] = None, kwargs: Union[Dict[str, Any], None] = None): """ Add the text properties to the Text (done so init is like str) :param key: str, the key (code id) for the language database :param args: if set a list of arguments to pass to the formatter i.e. value.format(*args) :param kwargs: if set a dictionary of keyword arguments to pass to the formatter (i.e. value.format(**kwargs) :return: None - updates tkey, tvalue, targs, tkwargs """ self.tkey = str(key) # deal with arguments if args is not None: if isinstance(args, list): self.targs = list(args) else: self.targs = [str(args)] # deal with kwargs if kwargs is not None: self.tkwargs = dict(kwargs) def get_text(self, report: bool = False, reportlevel: Union[str, None] = None) -> str: """ Return the full text (with reporting if requested) for this Text instance - this is returned as a string instance if report = True: "X[##-###-#####]: msg.format(*self.targs, **self.tkwargs)" else: "msg.format(*self.targs, **self.tkwargs)" :param report: bool, - if true reports the code id of this text entry in format X[##-###-#####] where X is the first character in reportlevel :param reportlevel: str, single character describing the reporting i.e. E for Error, W for Warning etc :return: string representation of the Text instance """ # --------------------------------------------------------------------- # deal with report level character if isinstance(reportlevel, str): reportlevel = reportlevel[0].upper() else: reportlevel = self.t_short # --------------------------------------------------------------------- # make sure tvalue is up-to-date self.get_formatting() # --------------------------------------------------------------------- vargs = [reportlevel, self.tkey, self.tvalue] # deal with report if report and (self.tkey != self.tvalue): valuestr = '{0}[{1}]: {2}'.format(*vargs) else: valuestr = '{2}'.format(*vargs) # --------------------------------------------------------------------- return valuestr def get_formatting(self, force=False): """ set the formatting (of self.tvalue) based on self.tkwargs and self.targs :param force: bool, if True then override the condition that the text is already formated (self.formatted) :return: None, updates self.tvalue """ # don't bother if already formatted if not force and self.formatted: return # set that we have formatted (so we don't do it again) self.formatted = True # --------------------------------------------------------------------- # deal with no value if self.tvalue is None: value = str(self) else: value = self.tvalue # --------------------------------------------------------------------- # deal with no args if self.targs is None and self.tkwargs is None: self.tvalue = value elif self.tkwargs is None and self.targs is not None: self.tvalue = value.format(*self.targs) elif self.targs is None and self.tkwargs is not None: self.tvalue = value.format(**self.tkwargs) else: self.tvalue = value.format(*self.targs, **self.tkwargs) def textentry(key: str, args: Union[List[Any], str, None] = None, kwargs: Union[Dict[str, Any], None] = None) -> Text: """ Get text from a database This is the only function that can use langdict and expect it to be populated :param key: str, the code by which to find the text in the language dictionary :param args: dict, arguments passed to text.format :param kwargs: dict, keyword arguments passed to text.format :return: Text class, the text taken from langdict[key] in Text class format """ # set function name _ = __NAME__ + '.textentry()' # deal with no entries if key not in langdict: message = key else: message = langdict[key] # deal with args if isinstance(args, str): args = [args] # create Text class for message msg_obj = Text(message) msg_obj.set_text_props(key, args, kwargs) # return msg_obj return msg_obj # noinspection PyUnresolvedReferences def read_xls(xls_file: str) -> pd.io.excel.ExcelFile: """ Read a Excel file :param xls_file: str, the excel absolute path :return: a pandas representation of the excel file """ # set function name _ = __NAME__ + '.read_xls()' # report progress: Loading database from file wcode = '40-001-00026' wmsg = drs_base.BETEXT[wcode] drs_base.base_printer(wcode, wmsg, '', args=[xls_file]) try: xls = pd.ExcelFile(xls_file) except Exception as e: ecode = '00-002-00026' emsg = drs_base.BETEXT(ecode) eargs = [xls_file, str(e), e] raise drs_base.base_error(ecode, emsg, 'error', args=eargs, exception=LanguageError) return xls # noinspection PyUnresolvedReferences def convert_csv(xls: pd.io.excel.ExcelFile, out_dir: str): """ Use the pandas excel file to write the reset files (one default one and one for each instrument) :param xls: a pandas representation of the excel file :param out_dir: str, the output directory for the reset files :return: None - writes the reset files """ # set function name func_name = __NAME__ + '.convert_csv()' # create sheet names sheet_names = ['HELP', 'TEXT'] instruments = ['NONE', 'NONE'] dataframes = dict(NONE=pd.DataFrame()) reset_paths = dict(NONE=base.LANG_DB_RESET) # loop around instruments for instrument in base.INSTRUMENTS: # ignore None cond1 = drs_base.base_func(drs_base.base_null_text, func_name, instrument, ['None', '', 'NULL']) if cond1: continue # add help sheet sheet_names.append('HELP_{0}'.format(instrument.upper())) instruments.append(instrument) # add text sheet sheet_names.append('TEXT_{0}'.format(instrument.upper())) instruments.append(instrument) # add to dataframes dataframes[instrument] = pd.DataFrame() # add to reset paths reset_paths[instrument] = base.LANG_DB_RESET_INST.format(instrument) # get sheets for it, sheet in enumerate(sheet_names): # print progress: Analyzing sheet wcode = '40-001-00027' wmsg = drs_base.BETEXT[wcode] drs_base.base_printer(wcode, wmsg, '', args=[sheet]) # skip other sheets if sheet not in xls.sheet_names: continue # get xls sheet pdsheet = xls.parse(sheet) # add to correct dataframe dflist = [dataframes[instruments[it]], pdsheet] dataframes[instruments[it]] = pd.concat(dflist, sort=True) # push dataframes into csv files for reset for instrument in dataframes: # get dataframe df = dataframes[instrument] # get reset path rpath = os.path.join(out_dir, reset_paths[instrument]) # write path to log: Saving reset file wcode = '40-001-00028' wmsg = drs_base.BETEXT[wcode] drs_base.base_printer(wcode, wmsg, '', args=[rpath]) # remove non utf-8 characters for column in df.columns: # change encoding values = df[column].str.encode('ascii', 'ignore') values = values.str.decode('ascii') # add back to columns df[column] = values # save to csv # noinspection PyTypeChecker df.to_csv(rpath, sep=',', quoting=2, index=False, encoding='utf-8') def make_reset_csvs(): """ Makes the reset csvs based on paths given :return: None, re-writes reset csv files for language datse """ # ---------------------------------------------------------------------- # get abspath from relative path database_path = drs_base.base_get_relative_folder(__PACKAGE__, DATABASE_PATH) backup_path = drs_base.base_get_relative_folder(__PACKAGE__, BACKUP_PATH) # ---------------------------------------------------------------------- # get database abspath dabspath = os.path.join(database_path, DATABASE_FILE) babspath = os.path.join(backup_path, DATABASE_FILE) # ---------------------------------------------------------------------- # check that we have database file in files if not os.path.exists(dabspath): ecode = '00-002-00027' emsg = drs_base.BETEXT[ecode] eargs = [DATABASE_FILE, database_path] raise drs_base.base_error(ecode, emsg, 'error', args=eargs, exception=LanguageError) # ---------------------------------------------------------------------- # create a backup of the database: Backing up database wcode = '40-001-00029' wmsg = drs_base.BETEXT[wcode] drs_base.base_printer(wcode, wmsg, '', args=[babspath]) shutil.copy(dabspath, babspath) # ---------------------------------------------------------------------- # first get contents of database directory files = np.sort(os.listdir(database_path)) # ---------------------------------------------------------------------- # clear files from database (other than database) for filename in files: abspath = os.path.join(database_path, filename) if os.path.isdir(abspath): continue if filename != DATABASE_FILE: # log message: Removing file wcode = '40-001-00030' wmsg = drs_base.BETEXT[wcode] drs_base.base_printer(wcode, wmsg, '', args=[filename]) os.remove(abspath) # ---------------------------------------------------------------------- # read the database file xls_instance = read_xls(dabspath) # convert to csv and save convert_csv(xls_instance, database_path) # ============================================================================= # Start of code # ============================================================================= if __name__ == "__main__": print('Hello World') # ============================================================================= # End of code # =============================================================================
njcuk9999REPO_NAMEapero-drsPATH_START.@apero-drs_extracted@apero-drs-main@apero@lang@core@drs_lang.py@.PATH_END.py
{ "filename": "mu_velfields.py", "repo_name": "kapteyn-astro/kapteyn", "repo_path": "kapteyn_extracted/kapteyn-master/doc/source/EXAMPLES/mu_velfields.py", "type": "Python" }
#!/usr/bin/env python from kapteyn import wcsgrat, maputils from matplotlib import pylab as plt import numpy # Create a maputils FITS object from a FITS file on disk fitsobject = maputils.FITSimage(promptfie=maputils.prompt_fitsfile) fitsobject.set_imageaxes(promptfie=maputils.prompt_imageaxes) fitsobject.set_limits(promptfie=maputils.prompt_box) fitsobject.set_skyout(promptfie=maputils.prompt_skyout) clipmin, clipmax = maputils.prompt_dataminmax(fitsobject) # Get connected to Matplotlib fig = plt.figure() frame = fig.add_subplot(1,1,1) # Create an image to be used in Matplotlib annim = fitsobject.Annotatedimage(frame, clipmin=clipmin, clipmax=clipmax) annim.Image() annim.Colorbar() levs = numpy.arange(clipmin, clipmax, 20) print(levs) levs = [6, 26, 46, 66, 86, 106, 126, 146, 166, 186, 206, 226, 246] levs = list(range(-154, 265, 20)) annim.Contours(levels=levs) #annim.Graticule() annim.plot() annim.interact_toolbarinfo() annim.interact_imagecolors() annim.interact_writepos() plt.show()
kapteyn-astroREPO_NAMEkapteynPATH_START.@kapteyn_extracted@kapteyn-master@doc@source@EXAMPLES@mu_velfields.py@.PATH_END.py
{ "filename": "_side.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/scatterpolargl/marker/colorbar/title/_side.py", "type": "Python" }
import _plotly_utils.basevalidators class SideValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="side", parent_name="scatterpolargl.marker.colorbar.title", **kwargs ): super(SideValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "style"), values=kwargs.pop("values", ["right", "top", "bottom"]), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@scatterpolargl@marker@colorbar@title@_side.py@.PATH_END.py
{ "filename": "test_RHT_timings.py", "repo_name": "mjuvela/ISM", "repo_path": "ISM_extracted/ISM-master/TM/test_RHT_timings.py", "type": "Python" }
import os, sys ISM_DIRECTORY = os.path.expanduser('~/GITHUB') try: ISM_DIRECTORY = os.environ(['ISM_DIRECTORY']) except: pass sys.path.append(ISM_DIRECTORY) import ISM.Defs from ISM.FITS.FITS import * from scipy.ndimage import zoom from ISM.TM.Pattern import RollingHoughTransformBasic # set the directory where code from http://seclark.github.io/RHT/ is installed RHT_DIRECTORY = '/home/mika/IN/seclark-RHT-f8b1f3e' DK = 11 DW = 55 TH = 0.70 SIZES = logspace(log10(100.0), log10(2000.0), 7) # SIZES = logspace(log10(100.0), log10(200.0), 3) TIME = zeros((len(SIZES), 4), float32) for isize in range(len(SIZES)): F = pyfits.open('PSW.fits') kzoom = SIZES[isize]/float(F[0].data.shape[0]) F[0].data = zoom(F[0].data.copy(), kzoom) F.verify('fix') F.writeto('test.fits', overwrite=True) # t0 = time.time() os.system('python %s/rht.py -f -w %.0f -s %.0f -t %.3f test.fits' % (RHT_DIRECTORY, DW, DK, TH)) TIME[isize,0] = time.time()-t0 # t0 = time.time() RollingHoughTransformBasic(F, DK, DW, TH, GPU=0) TIME[isize,1] = time.time()-t0 # t0 = time.time() RollingHoughTransformBasic(F, DK, DW, TH, GPU=1, platforms=[0,]) TIME[isize,2] = time.time()-t0 # t0 = time.time() RollingHoughTransformBasic(F, DK, DW, TH, GPU=1, platforms=[1,]) TIME[isize,3] = time.time()-t0 loglog(SIZES, TIME[:,0], 'ks-', label='Python') loglog(SIZES, TIME[:,1], 'bo-', label='OpenCL/CPU') loglog(SIZES, TIME[:,2], 'go-', label='OpenCL/GPU1') loglog(SIZES, TIME[:,3], 'ro-', label='OpenCL/GPU2') legend(loc='upper left') xlabel('Size (pixels)') ylabel('Time (s)') savefig('test_RHT_timings.png') show()
mjuvelaREPO_NAMEISMPATH_START.@ISM_extracted@ISM-master@TM@test_RHT_timings.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "AMReX-Astro/Castro", "repo_path": "Castro_extracted/Castro-main/Exec/science/flame/flame_wave_tests/triple_alpha_plus_cago/README.md", "type": "Markdown" }
These files go together with the boosted flame for the `flame_wave` problem. You should compile with the `triple_alpha_plus_cago` network.
AMReX-AstroREPO_NAMECastroPATH_START.@Castro_extracted@Castro-main@Exec@science@flame@flame_wave_tests@triple_alpha_plus_cago@README.md@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "sibirrer/lenstronomy", "repo_path": "lenstronomy_extracted/lenstronomy-main/lenstronomy/LensModel/LineOfSight/LOSModels/__init__.py", "type": "Python" }
sibirrerREPO_NAMElenstronomyPATH_START.@lenstronomy_extracted@lenstronomy-main@lenstronomy@LensModel@LineOfSight@LOSModels@__init__.py@.PATH_END.py
{ "filename": "releases.py", "repo_name": "sdss/marvin", "repo_path": "marvin_extracted/marvin-main/python/marvin/utils/datamodel/vacs/releases.py", "type": "Python" }
# !usr/bin/env python # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2018-07-17 23:36:37 # @Last modified by: Brian Cherinka # @Last Modified time: 2018-07-19 15:44:42 from __future__ import print_function, division, absolute_import from collections import defaultdict from marvin.utils.datamodel.drp import datamodel from marvin.contrib.vacs.base import VACMixIn from .base import VACList, VACDataModel subvacs = VACMixIn.__subclasses__() vacdms = [] # create a dictionary of VACs by release vacdict = defaultdict(list) for sv in subvacs: # skip hidden VACs if sv._hidden: continue # add versions to dictionary for k in sv.version.keys(): vacdict[k].append(sv) # create VAC datamodels for release, vacs in vacdict.items(): vc = VACList(vacs) dm = datamodel[release] if release in datamodel else None aliases = dm.aliases if dm else None vacdm = VACDataModel(release, vacs=vc, aliases=aliases) vacdms.append(vacdm)
sdssREPO_NAMEmarvinPATH_START.@marvin_extracted@marvin-main@python@marvin@utils@datamodel@vacs@releases.py@.PATH_END.py
{ "filename": "_variant.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/funnel/outsidetextfont/_variant.py", "type": "Python" }
import _plotly_utils.basevalidators class VariantValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="variant", parent_name="funnel.outsidetextfont", **kwargs ): super(VariantValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), values=kwargs.pop( "values", [ "normal", "small-caps", "all-small-caps", "all-petite-caps", "petite-caps", "unicase", ], ), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@funnel@outsidetextfont@_variant.py@.PATH_END.py
{ "filename": "class_lmv.py", "repo_name": "radio-astro-tools/spectral-cube", "repo_path": "spectral-cube_extracted/spectral-cube-master/spectral_cube/io/class_lmv.py", "type": "Python" }
import numpy as np import struct import warnings import string from astropy import log from astropy.io import registry as io_registry from ..spectral_cube import BaseSpectralCube from .fits import load_fits_cube """ .. TODO:: When any section length is zero, that means the following values are to be ignored. No warning is needed. """ # Constant: r2deg = 180/np.pi # see sicfits.f90 _ctype_dict={'LII':'GLON', 'BII':'GLAT', 'VELOCITY':'VELO', 'RA':'RA', 'DEC':'DEC', 'FREQUENCY': 'FREQ', } _cunit_dict = {'LII':'deg', 'BII':'deg', 'VELOCITY':'km s-1', 'RA':'deg', 'DEC':'deg', 'FREQUENCY': 'MHz', } cel_types = ('RA','DEC','GLON','GLAT') # CLASS apparently defaults to an ARC (zenithal equidistant) projection; this # is what is output in case the projection # is zero when exporting from CLASS _proj_dict = {0:'ARC', 1:'TAN', 2:'SIN', 3:'AZP', 4:'STG', 5:'ZEA', 6:'AIT', 7:'GLS', 8:'SFL', } _bunit_dict = {'k (tmb)': 'K'} def is_lmv(origin, filepath, fileobj, *args, **kwargs): """ Determine whether input is in GILDAS CLASS lmv format """ return filepath is not None and filepath.lower().endswith('.lmv') def read_lmv(lf): """ Read an LMV cube file Specification is primarily in GILDAS image_def.f90 """ log.warning("CLASS LMV cube reading is tentatively supported. " "Please post bug reports at the first sign of danger!") # lf for "LMV File" filetype = _read_string(lf, 12) #!--------------------------------------------------------------------- #! @ private #! SYCODE system code #! '-' IEEE #! '.' EEEI (IBM like) #! '_' VAX #! IMCODE file code #! '<' IEEE 64 bits (Little Endian, 99.9 % of recent computers) #! '>' EEEI 64 bits (Big Endian, HPUX, IBM-RISC, and SPARC ...) #!--------------------------------------------------------------------- imcode = filetype[6] if filetype[:6] != 'GILDAS' or filetype[7:] != 'IMAGE': raise TypeError("File is not a GILDAS Image file") if imcode in ('<','>'): if imcode =='>': log.warning("Swap the endianness first...") return read_lmv_type2(lf) else: return read_lmv_type1(lf) def read_lmv_type1(lf): header = {} # fmt probably matters! Default is "r4", i.e. float32 data, but could be float64 fmt = np.fromfile(lf, dtype='int32', count=1) # 4 # number of data blocks ndb = np.fromfile(lf, dtype='int32', count=1) # 5 gdf_type = np.fromfile(lf, dtype='int32', count=1) # 6 # Reserved Space reserved_fill = np.fromfile(lf, dtype='int32', count=4) # 7 general_section_length = np.fromfile(lf, dtype='int32', count=1) # 11 #print "Format: ",fmt," ndb: ",ndb, " fill: ",fill," other: ",unknown # pos 12 naxis,naxis1,naxis2,naxis3,naxis4 = np.fromfile(lf,count=5,dtype='int32') header['NAXIS'] = naxis header['NAXIS1'] = naxis1 header['NAXIS2'] = naxis2 header['NAXIS3'] = naxis3 header['NAXIS4'] = naxis4 # We are indexing bytes from here; CLASS indices are higher by 12 # pos 17 header['CRPIX1'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CRVAL1'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CDELT1'] = np.fromfile(lf,count=1,dtype='float64')[0] * r2deg header['CRPIX2'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CRVAL2'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CDELT2'] = np.fromfile(lf,count=1,dtype='float64')[0] * r2deg header['CRPIX3'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CRVAL3'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CDELT3'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CRPIX4'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CRVAL4'] = np.fromfile(lf,count=1,dtype='float64')[0] header['CDELT4'] = np.fromfile(lf,count=1,dtype='float64')[0] # pos 41 #print "Post-crval",lf.tell() blank_section_length = np.fromfile(lf,count=1,dtype='int32') if blank_section_length != 8: warnings.warn("Invalid section length found for blanking section") bval = np.fromfile(lf,count=1,dtype='float32')[0] # 42 header['TOLERANC'] = np.fromfile(lf,count=1,dtype='int32')[0] # 43 eval = tolerance extrema_section_length = np.fromfile(lf,count=1,dtype='int32')[0] # 44 if extrema_section_length != 40: warnings.warn("Invalid section length found for extrema section") vmin,vmax = np.fromfile(lf,count=2,dtype='float32') # 45 xmin,xmax,ymin,ymax,zmin,zmax = np.fromfile(lf,count=6,dtype='int32') # 47 wmin,wmax = np.fromfile(lf,count=2,dtype='int32') # 53 description_section_length = np.fromfile(lf,count=1,dtype='int32')[0] # 55 if description_section_length != 72: warnings.warn("Invalid section length found for description section") #strings = lf.read(description_section_length) # 56 header['BUNIT'] = _read_string(lf, 12) # 56 header['CTYPE1'] = _read_string(lf, 12) # 59 header['CTYPE2'] = _read_string(lf, 12) # 62 header['CTYPE3'] = _read_string(lf, 12) # 65 header['CTYPE4'] = _read_string(lf, 12) # 68 header['CUNIT1'] = _cunit_dict[header['CTYPE1'].strip()] header['CUNIT2'] = _cunit_dict[header['CTYPE2'].strip()] header['CUNIT3'] = _cunit_dict[header['CTYPE3'].strip()] header['COOSYS'] = _read_string(lf, 12) # 71 position_section_length = np.fromfile(lf,count=1,dtype='int32') # 74 if position_section_length != 48: warnings.warn("Invalid section length found for position section") header['OBJNAME'] = _read_string(lf, 4*3) # 75 header['RA'] = np.fromfile(lf, count=1, dtype='float64')[0] * r2deg # 78 header['DEC'] = np.fromfile(lf, count=1, dtype='float64')[0] * r2deg # 80 header['GLON'] = np.fromfile(lf, count=1, dtype='float64')[0] * r2deg # 82 header['GLAT'] = np.fromfile(lf, count=1, dtype='float64')[0] * r2deg # 84 header['EQUINOX'] = np.fromfile(lf,count=1,dtype='float32')[0] # 86 header['PROJWORD'] = _read_string(lf, 4) # 87 header['PTYP'] = np.fromfile(lf,count=1,dtype='int32')[0] # 88 header['A0'] = np.fromfile(lf,count=1,dtype='float64')[0] # 89 header['D0'] = np.fromfile(lf,count=1,dtype='float64')[0] # 91 header['PANG'] = np.fromfile(lf,count=1,dtype='float64')[0] # 93 header['XAXI'] = np.fromfile(lf,count=1,dtype='float32')[0] # 95 header['YAXI'] = np.fromfile(lf,count=1,dtype='float32')[0] # 96 spectroscopy_section_length = np.fromfile(lf,count=1,dtype='int32') # 97 if spectroscopy_section_length != 48: warnings.warn("Invalid section length found for spectroscopy section") header['RECVR'] = _read_string(lf, 12) # 98 header['FRES'] = np.fromfile(lf,count=1,dtype='float64')[0] # 101 header['IMAGFREQ'] = np.fromfile(lf,count=1,dtype='float64')[0] # 103 "FIMA" header['REFFREQ'] = np.fromfile(lf,count=1,dtype='float64')[0] # 105 header['VRES'] = np.fromfile(lf,count=1,dtype='float32')[0] # 107 header['VOFF'] = np.fromfile(lf,count=1,dtype='float32')[0] # 108 header['FAXI'] = np.fromfile(lf,count=1,dtype='int32')[0] # 109 resolution_section_length = np.fromfile(lf,count=1,dtype='int32')[0] # 110 if resolution_section_length != 12: warnings.warn("Invalid section length found for resolution section") #header['DOPP'] = np.fromfile(lf,count=1,dtype='float16')[0] # 110a ??? #header['VTYP'] = np.fromfile(lf,count=1,dtype='int16')[0] # 110b # integer, parameter :: vel_unk = 0 ! Unsupported referential :: planetary...) # integer, parameter :: vel_lsr = 1 ! LSR referential # integer, parameter :: vel_hel = 2 ! Heliocentric referential # integer, parameter :: vel_obs = 3 ! Observatory referential # integer, parameter :: vel_ear = 4 ! Earth-Moon barycenter referential # integer, parameter :: vel_aut = -1 ! Take referential from data header['BMAJ'] = np.fromfile(lf,count=1,dtype='float32')[0] # 111 header['BMIN'] = np.fromfile(lf,count=1,dtype='float32')[0] # 112 header['BPA'] = np.fromfile(lf,count=1,dtype='float32')[0] # 113 noise_section_length = np.fromfile(lf,count=1,dtype='int32') if noise_section_length != 0: warnings.warn("Invalid section length found for noise section") header['NOISE'] = np.fromfile(lf,count=1,dtype='float32')[0] # 115 header['RMS'] = np.fromfile(lf,count=1,dtype='float32')[0] # 116 astrometry_section_length = np.fromfile(lf,count=1,dtype='int32') if astrometry_section_length != 0: warnings.warn("Invalid section length found for astrometry section") header['MURA'] = np.fromfile(lf,count=1,dtype='float32')[0] # 118 header['MUDEC'] = np.fromfile(lf,count=1,dtype='float32')[0] # 119 header['PARALLAX'] = np.fromfile(lf,count=1,dtype='float32')[0] # 120 # Apparently CLASS headers aren't required to fill the 'value at # reference pixel' column if (header['CTYPE1'].strip() == 'RA' and header['CRVAL1'] == 0 and header['RA'] != 0): header['CRVAL1'] = header['RA'] header['CRVAL2'] = header['DEC'] # Copied from the type 2 reader: # Use the appropriate projection type ptyp = header['PTYP'] for kw in header: if 'CTYPE' in kw: if header[kw].strip() in cel_types: n_dashes = 5-len(header[kw].strip()) header[kw] = header[kw].strip()+ '-'*n_dashes + _proj_dict[ptyp] other_info = np.fromfile(lf, count=7, dtype='float32') # 121-end if not np.all(other_info == 0): warnings.warn("Found additional information in the last 7 bytes") endpoint = 508 if lf.tell() != endpoint: raise ValueError("Header was not parsed correctly") data = np.fromfile(lf, count=naxis1*naxis2*naxis3, dtype='float32') data[data == bval] = np.nan # for no apparent reason, y and z are 1-indexed and x is zero-indexed if (wmin-1,zmin-1,ymin-1,xmin) != np.unravel_index(np.nanargmin(data), [naxis4,naxis3,naxis2,naxis1]): warnings.warn("Data min location does not match that on file. " "Possible error reading data.") if (wmax-1,zmax-1,ymax-1,xmax) != np.unravel_index(np.nanargmax(data), [naxis4,naxis3,naxis2,naxis1]): warnings.warn("Data max location does not match that on file. " "Possible error reading data.") if np.nanmax(data) != vmax: warnings.warn("Data max does not match that on file. " "Possible error reading data.") if np.nanmin(data) != vmin: warnings.warn("Data min does not match that on file. " "Possible error reading data.") return data.reshape([naxis4,naxis3,naxis2,naxis1]),header # debug #return data.reshape([naxis3,naxis2,naxis1]), header, hdr_f, hdr_s, hdr_i, hdr_d, hdr_d_2 def read_lmv_tofits(fileobj): from astropy.io import fits data,header = read_lmv(fileobj) # LMV may contain extra dimensions that are improperly labeled data = data.squeeze() bad_kws = ['NAXIS4','CRVAL4','CRPIX4','CDELT4','CROTA4','CUNIT4','CTYPE4'] cards = [fits.header.Card(keyword=k, value=v[0], comment=v[1]) if isinstance(v, tuple) else fits.header.Card(''.join(s for s in k if s in string.printable), ''.join(s for s in v if s in string.printable) if isinstance(v, str) else v) for k,v in header.items() if k not in bad_kws] Header = fits.Header(cards) hdu = fits.PrimaryHDU(data=data, header=Header) return hdu def load_lmv_cube(fileobj, target_cls=None, use_dask=None): hdu = read_lmv_tofits(fileobj) meta = {'filename':fileobj.name} return load_fits_cube(hdu, meta=meta, use_dask=use_dask) def _read_byte(f): '''Read a single byte (from idlsave)''' return np.uint8(struct.unpack('=B', f.read(4)[:1])[0]) def _read_int16(f): '''Read a signed 16-bit integer (from idlsave)''' return np.int16(struct.unpack('=h', f.read(4)[2:4])[0]) def _read_int32(f): '''Read a signed 32-bit integer (from idlsave)''' return np.int32(struct.unpack('=i', f.read(4))[0]) def _read_int64(f): '''Read a signed 64-bit integer ''' return np.int64(struct.unpack('=q', f.read(8))[0]) def _read_float32(f): '''Read a 32-bit float (from idlsave)''' return np.float32(struct.unpack('=f', f.read(4))[0]) def _read_string(f, size): '''Read a string of known maximum length''' return f.read(size).decode('utf-8').strip() def _read_float64(f): '''Read a 64-bit float (from idlsave)''' return np.float64(struct.unpack('=d', f.read(8))[0]) def _check_val(name, got,expected): if got != expected: log.warning("{2} = {0} instead of {1}".format(got, expected, name)) def read_lmv_type2(lf): """ See image_def.f90 """ header = {} lf.seek(12) # DONE before integer(kind=4) :: ijtyp(3) = 0 ! 1 Image Type # fmt probably matters! Default is "r4", i.e. float32 data, but could be float64 fmt = _read_int32(lf) # 4 # number of data blocks ndb = _read_int64(lf) # 5 nhb = _read_int32(lf) # 7 ntb = _read_int32(lf) # 8 version_gdf = _read_int32(lf) # 9 if version_gdf != 20: raise TypeError("Trying to read a version-2 file, but the version" " number is {0} (should be 20)".format(version_gdf)) type_gdf = _read_int32(lf) # 10 dim_start = _read_int32(lf) # 11 pad_trail = _read_int32(lf) # 12 if dim_start % 2 == 0: log.warning("Got even dim_start in lmv cube: this is not expected.") if dim_start > 17: log.warning("dim_start > 17 in lmv cube: this is not expected.") lf.seek(16*4) gdf_maxdims=7 dim_words = _read_int32(lf) # 17 if dim_words != 2*gdf_maxdims+2: log.warning("dim_words = {0} instead of {1}".format(dim_words, gdf_maxdims*2+2)) blan_start = _read_int32(lf) # 18 if blan_start != dim_start+dim_words+2: log.warning("blan_star = {0} instead of {1}".format(blan_start, dim_start+dim_words+2)) mdim = _read_int32(lf) # 19 ndim = _read_int32(lf) # 20 dims = np.fromfile(lf, count=gdf_maxdims, dtype='int64') if np.count_nonzero(dims) != ndim: raise ValueError("Disagreement between ndims and number of nonzero dims.") header['NAXIS'] = ndim valid_dims = [] for ii,dim in enumerate(dims): if dim != 0: header['NAXIS{0}'.format(ii+1)] = dim valid_dims.append(ii) blan_words = _read_int32(lf) if blan_words != 2: log.warning("blan_words = {0} instead of 2".format(blan_words)) extr_start = _read_int32(lf) bval = _read_float32(lf) # blanking value bval_tol = _read_float32(lf) # eval = tolerance # FITS requires integer BLANKs #header['BLANK'] = bval extr_words = _read_int32(lf) if extr_words != 6: log.warning("extr_words = {0} instead of 6".format(extr_words)) coor_start = _read_int32(lf) if coor_start != extr_start+extr_words+2: log.warning("coor_start = {0} instead of {1}".format(coor_start, extr_start+extr_words+2)) rmin = _read_float32(lf) rmax = _read_float32(lf) # position 168 minloc = _read_int64(lf) maxloc = _read_int64(lf) # lf.seek(184) coor_words = _read_int32(lf) if coor_words != gdf_maxdims*6: log.warning("coor_words = {0} instead of {1}".format(coor_words, gdf_maxdims*6)) desc_start = _read_int32(lf) if desc_start != coor_start+coor_words+2: log.warning("desc_start = {0} instead of {1}".format(desc_start, coor_start+coor_words+2)) convert = np.fromfile(lf, count=3*gdf_maxdims, dtype='float64').reshape([gdf_maxdims,3]) # conversion of "convert" to CRPIX/CRVAL/CDELT below desc_words = _read_int32(lf) if desc_words != 3*(gdf_maxdims+1): log.warning("desc_words = {0} instead of {1}".format(desc_words, 3*(gdf_maxdims+1))) null_start = _read_int32(lf) if null_start != desc_start+desc_words+2: log.warning("null_start = {0} instead of {1}".format(null_start, desc_start+desc_words+2)) ijuni = _read_string(lf, 12) # data unit ijcode = [_read_string(lf, 12) for ii in range(gdf_maxdims)] pad_desc = _read_int32(lf) if ijuni.lower() in _bunit_dict: header['BUNIT'] = (_bunit_dict[ijuni.lower()], ijuni) else: header['BUNIT'] = ijuni #! The first block length is thus #! s_dim-1 + (2*mdim+4) + (4) + (8) + (6*mdim+2) + (3*mdim+5) #! = s_dim-1 + mdim*(2+6+3) + (4+4+2+5+8) #! = s_dim-1 + 11*mdim + 23 #! With mdim = 7, s_dim=11, this is 110 spaces #! With mdim = 8, s_dim=11, this is 121 spaces #! MDIM > 8 would NOT fit in one block... #! #! Block 2: Ancillary information #! #! The same logic of Length + Pointer is used there too, although the #! length are fixed. Note rounding to even number for the pointer offsets #! in order to preserve alignement... #! lf.seek(512) posi_words = _read_int32(lf) _check_val('posi_words', posi_words, 15) proj_start = _read_int32(lf) source_name = _read_string(lf, 12) header['OBJECT'] = source_name coordinate_system = _read_string(lf, 12) header['RA'] = _read_float64(lf) header['DEC'] = _read_float64(lf) header['LII'] = _read_float64(lf) header['BII'] = _read_float64(lf) header['EPOCH'] = _read_float32(lf) #pad_posi = _read_float32(lf) #print pad_posi #raise ValueError("pad_posi should probably be 0?") #! PROJECTION #integer(kind=4) :: proj_words = 9 ! Projection length: 9 used + 1 padding #integer(kind=4) :: spec_start !! = proj_start + 12 #real(kind=8) :: a0 = 0.d0 ! 89 X of projection center #real(kind=8) :: d0 = 0.d0 ! 91 Y of projection center #real(kind=8) :: pang = 0.d0 ! 93 Projection angle #integer(kind=4) :: ptyp = p_none ! 88 Projection type (see p_... codes) #integer(kind=4) :: xaxi = 0 ! 95 X axis #integer(kind=4) :: yaxi = 0 ! 96 Y axis #integer(kind=4) :: pad_proj #! proj_words = _read_int32(lf) spec_start = _read_int32(lf) _check_val('spec_start', spec_start, proj_start+proj_words+2) if proj_words == 9: header['PROJ_A0'] = _read_float64(lf) header['PROJ_D0'] = _read_float64(lf) header['PROJPANG'] = _read_float64(lf) ptyp = _read_int32(lf) header['PROJXAXI'] = _read_int32(lf) header['PROJYAXI'] = _read_int32(lf) elif proj_words != 0: raise ValueError("Invalid # of projection keywords") for kw in header: if 'CTYPE' in kw: if header[kw].strip() in cel_types: n_dashes = 5-len(header[kw].strip()) header[kw] = header[kw].strip()+ '-'*n_dashes + _proj_dict[ptyp] for ii,((ref,val,inc),code) in enumerate(zip(convert,ijcode)): if ii in valid_dims: # jul14a gio/to_imfits.f90 line 284-313 if ptyp != 0 and (ii+1) in (header['PROJXAXI'], header['PROJYAXI']): #! Compute reference pixel so that VAL(REF) = 0 ref = ref - val/inc if (ii+1) == header['PROJXAXI']: val = header['PROJ_A0'] elif (ii+1) == header['PROJYAXI']: val = header['PROJ_D0'] else: raise ValueError("Impossible state - code bug.") val = val*r2deg inc = inc*r2deg rota = r2deg*header['PROJPANG'] elif code in ('RA', 'L', 'B', 'DEC', 'LII', 'BII', 'GLAT', 'GLON', 'LAT', 'LON'): val = val*r2deg inc = inc*r2deg rota = 0.0 # These are not implemented: prefer to maintain original units (we're # reading in to spectral_cube after all, no need to change units until the # output step) #elseif (code.eq.'FREQUENCY') then #val = val*1.0d6 ! MHz to Hz #inc = inc*1.0d6 #elseif (code.eq.'VELOCITY') then #code = 'VRAD' ! force VRAD instead of VELOCITY for CASA #val = val*1.0d3 ! km/s to m/s #inc = inc*1.0d3 header['CRPIX{0}'.format(ii+1)] = ref header['CRVAL{0}'.format(ii+1)] = val header['CDELT{0}'.format(ii+1)] = inc for ii,ctype in enumerate(ijcode): if ii in valid_dims: header['CTYPE{0}'.format(ii+1)] = _ctype_dict[ctype] header['CUNIT{0}'.format(ii+1)] = _cunit_dict[ctype] spec_words = _read_int32(lf) reso_start = _read_int32(lf) _check_val('reso_start', reso_start, proj_start+proj_words+2+spec_words+2) if spec_words == 14: header['FRES'] = _read_float64(lf) header['FIMA'] = _read_float64(lf) header['FREQ'] = _read_float64(lf) header['VRES'] = _read_float32(lf) header['VOFF'] = _read_float32(lf) header['DOPP'] = _read_float32(lf) header['FAXI'] = _read_int32(lf) header['LINENAME'] = _read_string(lf, 12) header['VTYPE'] = _read_int32(lf) elif spec_words != 0: raise ValueError("Invalid # of spectroscopic keywords") #! SPECTROSCOPY #integer(kind=4) :: spec_words = 14 ! Spectroscopy length: 14 used #integer(kind=4) :: reso_start !! = spec_words + 16 #real(kind=8) :: fres = 0.d0 !101 Frequency resolution #real(kind=8) :: fima = 0.d0 !103 Image frequency #real(kind=8) :: freq = 0.d0 !105 Rest Frequency #real(kind=4) :: vres = 0.0 !107 Velocity resolution #real(kind=4) :: voff = 0.0 !108 Velocity offset #real(kind=4) :: dopp = 0.0 ! Doppler factor #integer(kind=4) :: faxi = 0 !109 Frequency axis #integer(kind=4) :: ijlin(3) = 0 ! 98 Line name #integer(kind=4) :: vtyp = vel_unk ! Velocity type (see vel_... codes) reso_words = _read_int32(lf) nois_start = _read_int32(lf) _check_val('nois_start', nois_start, proj_start+proj_words+2+spec_words+2+reso_words+2) if reso_words == 3: header['BMAJ'] = _read_float32(lf) header['BMIN'] = _read_float32(lf) header['BPA'] = _read_float32(lf) #pad_reso = _read_float32(lf) elif reso_words != 0: raise ValueError("Invalid # of resolution keywords") #! RESOLUTION #integer(kind=4) :: reso_words = 3 ! Resolution length: 3 used + 1 padding #integer(kind=4) :: nois_start !! = reso_words + 6 #real(kind=4) :: majo = 0.0 !111 Major axis #real(kind=4) :: mino = 0.0 !112 Minor axis #real(kind=4) :: posa = 0.0 !113 Position angle #real(kind=4) :: pad_reso nois_words = _read_int32(lf) astr_start = _read_int32(lf) _check_val('astr_start', astr_start, proj_start+proj_words+2+spec_words+2+reso_words+2+nois_words+2) if nois_words == 2: header['NOISE_T'] = (_read_float32(lf), "Theoretical Noise") header['NOISERMS'] = (_read_float32(lf), "Measured (RMS) noise") elif nois_words != 0: raise ValueError("Invalid # of noise keywords") #! NOISE #integer(kind=4) :: nois_words = 2 ! Noise section length: 2 used #integer(kind=4) :: astr_start !! = s_nois + 4 #real(kind=4) :: noise = 0.0 ! 115 Theoretical noise #real(kind=4) :: rms = 0.0 ! 116 Actual noise astr_words = _read_int32(lf) uvda_start = _read_int32(lf) _check_val('uvda_start', uvda_start, proj_start+proj_words+2+spec_words+2+reso_words+2+nois_words+2+astr_words+2) if astr_words == 3: header['MURA'] = _read_float32(lf) header['MUDEC'] = _read_float32(lf) header['PARALLAX'] = _read_float32(lf) elif astr_words != 0: raise ValueError("Invalid # of astrometry keywords") #! ASTROMETRY #integer(kind=4) :: astr_words = 3 ! Proper motion section length: 3 used + 1 padding #integer(kind=4) :: uvda_start !! = s_astr + 4 #real(kind=4) :: mura = 0.0 ! 118 along RA, in mas/yr #real(kind=4) :: mudec = 0.0 ! 119 along Dec, in mas/yr #real(kind=4) :: parallax = 0.0 ! 120 in mas #real(kind=4) :: pad_astr #! real(kind=4) :: pepoch = 2000.0 ! 121 in yrs ? code_uvt_last=25 uvda_words = _read_int32(lf) void_start = _read_int32(lf) _check_val('void_start', void_start, proj_start + proj_words + 2 + spec_words + 2 + reso_words + 2 + nois_words + 2 + astr_words + 2 + uvda_words + 2) if uvda_words == 18+2*code_uvt_last: version_uv = _read_int32(lf) nchan = _read_int32(lf) nvisi = _read_int64(lf) nstokes = _read_int32(lf) natom = _read_int32(lf) basemin = _read_float32(lf) basemax = _read_float32(lf) fcol = _read_int32(lf) lcol = _read_int32(lf) nlead = _read_int32(lf) ntrail = _read_int32(lf) column_pointer = np.fromfile(lf, count=code_uvt_last, dtype='int32') column_size = np.fromfile(lf, count=code_uvt_last, dtype='int32') column_codes = np.fromfile(lf, count=nlead+ntrail, dtype='int32') column_types = np.fromfile(lf, count=nlead+ntrail, dtype='int32') order = _read_int32(lf) nfreq = _read_int32(lf) atoms = np.fromfile(lf, count=4, dtype='int32') elif uvda_words != 0: raise ValueError("Invalid # of UV data keywords") #! UV_DATA information #integer(kind=4) :: uvda_words = 18+2*code_uvt_last ! Length of section: 14 used #integer(kind=4) :: void_start !! = s_uvda + l_uvda + 2 #integer(kind=4) :: version_uv = code_version_uvt_current ! 1 version number. Will allow us to change the data format #integer(kind=4) :: nchan = 0 ! 2 Number of channels #integer(kind=8) :: nvisi = 0 ! 3-4 Independent of the transposition status #integer(kind=4) :: nstokes = 0 ! 5 Number of polarizations #integer(kind=4) :: natom = 0 ! 6. 3 for real, imaginary, weight. 1 for real. #real(kind=4) :: basemin = 0. ! 7 Minimum Baseline #real(kind=4) :: basemax = 0. ! 8 Maximum Baseline #integer(kind=4) :: fcol ! 9 Column of first channel #integer(kind=4) :: lcol ! 10 Column of last channel #! The number of information per channel can be obtained by #! (lcol-fcol+1)/(nchan*natom) #! so this could allow to derive the number of Stokes parameters #! Leading data at start of each visibility contains specific information #integer(kind=4) :: nlead = 7 ! 11 Number of leading informations (at lest 7) #! Trailing data at end of each visibility may hold additional information #integer(kind=4) :: ntrail = 0 ! 12 Number of trailing informations #! #! Leading / Trailing information codes have been specified before #integer(kind=4) :: column_pointer(code_uvt_last) = code_null ! Back pointer to the columns... #integer(kind=4) :: column_size(code_uvt_last) = 0 ! Number of columns for each #! In the data, we instead have the codes for each column #! integer(kind=4) :: column_codes(nlead+ntrail) ! Start column for each ... #! integer(kind=4) :: column_types(nlead+ntrail) /0,1,2/ ! Number of columns for each: 1 real*4, 2 real*8 #! Leading / Trailing information codes #! #integer(kind=4) :: order = 0 ! 13 Stoke/Channel ordering #integer(kind=4) :: nfreq = 0 ! 14 ! 0 or = nchan*nstokes #integer(kind=4) :: atoms(4) ! 15-18 Atom description #! #real(kind=8), pointer :: freqs(:) => null() ! (nchan*nstokes) = 0d0 #integer(kind=4), pointer :: stokes(:) => null() ! (nchan*nstokes) or (nstokes) = code_stoke #! #real(kind=8), pointer :: ref(:) => null() #real(kind=8), pointer :: val(:) => null() #real(kind=8), pointer :: inc(:) => null() lf.seek(1024) real_dims = dims[:ndim] data = np.fromfile(lf, count=np.prod(real_dims), dtype='float32').reshape(real_dims[::-1]) data[data==bval] = np.nan return data,header io_registry.register_reader('lmv', BaseSpectralCube, load_lmv_cube) io_registry.register_reader('class_lmv', BaseSpectralCube, load_lmv_cube) io_registry.register_identifier('lmv', BaseSpectralCube, is_lmv)
radio-astro-toolsREPO_NAMEspectral-cubePATH_START.@spectral-cube_extracted@spectral-cube-master@spectral_cube@io@class_lmv.py@.PATH_END.py
{ "filename": "conf.py", "repo_name": "ajshajib/dolphin", "repo_path": "dolphin_extracted/dolphin-main/docs_test/conf.py", "type": "Python" }
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = "dolphin" copyright = "2020, Anowar J. Shajib" author = "Anowar J. Shajib" # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.file_type.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"]
ajshajibREPO_NAMEdolphinPATH_START.@dolphin_extracted@dolphin-main@docs_test@conf.py@.PATH_END.py
{ "filename": "mntes.py", "repo_name": "tijmen/dfmux_calc", "repo_path": "dfmux_calc_extracted/dfmux_calc-main/mntes.py", "type": "Python" }
""" Electro-thermal solution for Transition Edge Sensors (TES) read out with DfMux. Author: Tijmen de Haan Email: <tijmen.dehaan@gmail.com> Date: 15 May 2024 This module provides functions for simulating the thermal and electrical behavior of Transition Edge Sensors (TES) based on the MNTES model. As of May 2024, this is being drafted as a paper for the SPIE Astronomical Telescopes and Instrumentation conference proceedings. Functions: - r_frac: fractional resistance as a function of temperature - r: resistance as a function of temperature - alpha: logarithmic temperature sensitivity of the resistance - loop_gain: Computes the ETF loop gain using the MNTES model. - responsivity: Computes the responsivity of the TES using the MNTES model. - power_balance_eq: Calculates the deviation from power balance. This should be zeroed to find the equilibrium temperature of the TES. - calc_tes: Computes various TES parameters given input parameters. - calc_nonlinearity: Computes TES nonlinearity. Usage: - The `calc_tes` function is the main entry point for solving the power balance equation. - The `calc_nonlinearity` function can be used to get the leading-order nonlinearity by finite difference. Dependencies: - numpy - scipy.optimize - numba """ import numpy as np from scipy.optimize import brentq from numba import jit @jit(nopython=True) def r_frac(temperature, t_c, transition_width): return (np.arctan((temperature - t_c) / (transition_width / 2.0)) / (np.pi / 2) + 1) / 2 @jit(nopython=True) def r(temperature, r_normal, t_c, transition_width): return r_normal * r_frac(temperature, t_c, transition_width) @jit(nopython=True) def alpha(temperature, r_normal, t_c, transition_width): return temperature / r(temperature, r_normal, t_c, transition_width) * ( r_normal * (transition_width / 2.0) / (np.pi * ((temperature - t_c) ** 2 + (transition_width / 2.0) ** 2)) ) @jit(nopython=True) def loop_gain(v_thev, k, n_index, t, r_t, z_thev, alpha_t, beta_t=0): """ Implements the loop gain equation from the MNTES paper. $\mathcal{L} = \frac{\alpha V_\mathrm{Th\acute{e}v}^2}{K n T^n R} \frac{R^2 \left( R^2 - \left| z_\mathrm{Th\acute{e}v} \right |^2 \right)}{\left| R + z_\mathrm{Th\acute{e}v} \right|^2 \left( \left| R + z_\mathrm{Th\acute{e}v} \right|^2 + \beta R (R + \Re{(z_\mathrm{Th\acute{e}v})}) \right) }$ """ loop_gain_ideal = alpha_t*v_thev**2/(k*n_index*t**n_index*r_t) abs_z_thev = np.sqrt(z_thev.real**2 + z_thev.imag**2) abs_z_total = np.sqrt((r_t + z_thev.real)**2 + z_thev.imag**2) loop_gain_excess_numerator = r_t**2 * (r_t**2 - abs_z_thev**2) loop_gain_excess_denominator = abs_z_total**2 * (abs_z_total**2 + beta_t * r_t * (r_t + z_thev.real)) return loop_gain_ideal * loop_gain_excess_numerator / loop_gain_excess_denominator @jit(nopython=True) def responsivity(v_thev, loop_gain, r_t, z_thev): """ Implements the responsivity equation from the MNTES paper. S \equiv \frac{\delta I}{\delta P_\mathrm{opt}} = - \frac{\sqrt{2}}{V_\mathrm{Th\acute{e}v}} \frac{\mathcal{L}}{\mathcal{L} + 1} \left( 1 + 2 z_\mathrm{Th\acute{e}v}^\star \frac{R + \Re{(z_\mathrm{Th\acute{e}v})}}{R^2 - \left| z_\mathrm{Th\acute{e}v} \right|^2 } \right) } \ . """ abs_z_thev_squared = z_thev.real**2 + z_thev.imag**2 responsivity_factor = -1 / v_thev * loop_gain / (loop_gain + 1) responsivity_excess = 1 + 2 * z_thev.conjugate() * (r_t + z_thev.real) / (r_t**2 - abs_z_thev_squared) return responsivity_factor * responsivity_excess @jit(nopython=True) def power_balance_eq(temperature, p_loading, v_thev, k, n_index, t_bath, r_normal, t_c, transition_width, z_thev): r_t = r(temperature, r_normal, t_c, transition_width) return ( p_loading + r_t * v_thev**2 / np.abs(r_t + z_thev) ** 2 - k * (temperature**n_index - t_bath**n_index) ) def calc_tes( t_c=180e-3, transition_width=0.001143, r_normal=1.0, p_loading=0.5e-12, t_bath=100e-3, z_thev=0.05 + 0.05j, n_index=3.6, v_thev=0.8e-6, p_sat_for_g=1.25e-12, debug=False, ): k = p_sat_for_g / (t_c**n_index - t_bath**n_index) def power_balance_eq_wrapper(temperature): return power_balance_eq(temperature, p_loading, v_thev, k, n_index, t_bath, r_normal, t_c, transition_width, z_thev) t_0 = brentq(power_balance_eq_wrapper, t_c, 2*t_c) r_0 = r(t_0, r_normal, t_c, transition_width) I_0 = v_thev / (r_0 + z_thev) alpha_0 = alpha(t_0, r_normal, t_c, transition_width) loop_gain_0 = loop_gain(v_thev, k, n_index, t_0, r_0, z_thev, alpha_0) responsivity_0 = responsivity(v_thev, loop_gain_0, r_0, z_thev) p_electrical = r_0 * v_thev**2 / np.abs(r_0 + z_thev) ** 2 if debug: # Add debugging code here if needed pass return { "t": t_0, "r": r_0, "i": I_0, "l": loop_gain_0, "s": responsivity_0, "p_electrical": p_electrical, "p_sat_for_g": p_sat_for_g, "alpha": alpha_0, "k": k, } def calc_nonlinearity(param, value, fiducial_params, r_frac): params = fiducial_params.copy() if param.startswith('z_thev'): z_real, z_imag = params['z_thev'].real, params['z_thev'].imag params['z_thev'] = complex(value if param == 'z_thev_real' else z_real, value if param == 'z_thev_imag' else z_imag) else: params[param] = value v = 1e-6 r = calc_tes(v_thev=v, **params)['r'] r_target = r_frac * params['r_normal'] while r > r_target: v -= 0.1e-9 r = calc_tes(v_thev=v, **params)['r'] delta_p = 0.03 * 5e-13 S0 = calc_tes(v_thev=v, **params)['s'] params['p_loading'] += delta_p S1 = calc_tes(v_thev=v, **params)['s'] return S0, (S1 - S0) / delta_p if __name__ == "__main__": print(calc_tes(debug=True))
tijmenREPO_NAMEdfmux_calcPATH_START.@dfmux_calc_extracted@dfmux_calc-main@mntes.py@.PATH_END.py
{ "filename": "dunne2009.py", "repo_name": "mirochaj/ares", "repo_path": "ares_extracted/ares-main/input/litdata/dunne2009.py", "type": "Python" }
""" Dunne, L., et al. 2009, MNRAS, 394, 3 http://arxiv.org/abs/0808.3139v2 For ssfr, values are corrected as seen in Behroozi et al. 2013 (http://arxiv.org/abs/1207.6105), Table 4, for I (Initial Mass Function) corrections. """ import numpy as np info = \ { 'reference':'Dunne, L., et al. 2009, MNRAS, 394, 3', 'data': 'Behroozi, Table 4', 'imf': ('chabrier, 2003', (0.1, 100.)), } redshifts = [0.5, 0.95, 1.4, 1.85] wavelength = 1600. ULIM = -1e10 fits = {} # Table 1 tmp_data = {} tmp_data['ssfr'] = \ { 0.5: {'M': [9.3229011E+08, 2.3418069E+09, 5.8823529E+09, 1.4775803E+10, 2.9481602E+10, 5.8823529E+10], 'phi': [-9.52287874528034, -9.52287874528034, -9.60205999132796, -9.69897000433602, -9.76955107862172, -9.82390874094432], 'err': [(0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3)] }, 0.95: {'M': [3.7115138E+09, 5.8823529E+09, 1.4775803E+10, 2.9481602E+10, 7.4054436E+10], 'phi': [-9.0, -9.09691001300805, -9.15490195998574, -9.22184874961636, -9.15490195998574], 'err': [(0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3)] }, 1.4: {'M': [4.6725190E+09, 9.3229011E+09, 1.4775803E+10, 2.9481602E+10, 7.4054436E+10], 'phi': [-8.69897000433602, -8.74472749489669, -8.79588001734407, -8.82390874094432, -8.85387196432176], 'err': [(0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3)] }, 1.85: {'M': [9.3229011E+09, 1.4775803E+10, 3.3078901E+10, 7.4054436E+10], 'phi': [-8.39794000867204, -8.45593195564972, -8.52287874528034, -8.52287874528034], 'err': [(0.3, 0.3), (0.3, 0.3), (0.3, 0.3), (0.3, 0.3)] }, } units = {'ssfr': '1.'} data = {} data['ssfr'] = {} for group in ['ssfr']: for key in tmp_data[group]: if key not in tmp_data[group]: continue subdata = tmp_data[group] mask = [] for element in subdata[key]['err']: if element == ULIM: mask.append(1) else: mask.append(0) mask = np.array(mask) data[group][key] = {} data[group][key]['M'] = np.ma.array(subdata[key]['M'], mask=mask) data[group][key]['phi'] = np.ma.array(subdata[key]['phi'], mask=mask) data[group][key]['err'] = tmp_data[group][key]['err']
mirochajREPO_NAMEaresPATH_START.@ares_extracted@ares-main@input@litdata@dunne2009.py@.PATH_END.py
{ "filename": "test_flexionfg.py", "repo_name": "sibirrer/lenstronomy", "repo_path": "lenstronomy_extracted/lenstronomy-main/test/test_LensModel/test_Profiles/test_flexionfg.py", "type": "Python" }
__author__ = "ylilan" from lenstronomy.LensModel.Profiles.flexionfg import Flexionfg from lenstronomy.LensModel.lens_model import LensModel import numpy as np import numpy.testing as npt import pytest class TestFlexionfg(object): """Tests the Gaussian methods.""" def setup_method(self): self.flex = Flexionfg() F1, F2, G1, G2 = 0.02, 0.03, -0.04, -0.05 self.kwargs_lens = {"F1": F1, "F2": F2, "G1": G1, "G2": G2} def test_transform_fg(self): values = self.flex.transform_fg(**self.kwargs_lens) g1, g2, g3, g4 = 0.01, 0.02, 0.03, 0.04 npt.assert_almost_equal(values[0], g1, decimal=5) npt.assert_almost_equal(values[1], g2, decimal=5) npt.assert_almost_equal(values[2], g3, decimal=5) npt.assert_almost_equal(values[3], g4, decimal=5) def test_function(self): x = np.array([1]) y = np.array([2]) values = self.flex.function(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0], 0.135, decimal=5) x = np.array([0]) y = np.array([0]) values = self.flex.function(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0], 0, decimal=5) x = np.array([2, 3, 4]) y = np.array([1, 1, 1]) values = self.flex.function(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0], 0.09, decimal=5) npt.assert_almost_equal(values[1], 0.18666666666666668, decimal=5) def test_derivatives(self): x = np.array([1]) y = np.array([2]) f_x, f_y = self.flex.derivatives(x, y, **self.kwargs_lens) npt.assert_almost_equal(f_x[0], 0.105, decimal=5) npt.assert_almost_equal(f_y[0], 0.15, decimal=5) x = np.array([1, 3, 4]) y = np.array([2, 1, 1]) values = self.flex.derivatives(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0][0], 0.105, decimal=5) npt.assert_almost_equal(values[1][0], 0.15, decimal=5) def test_hessian(self): x = np.array(1) y = np.array(2) f_xx, f_xy, f_yx, f_yy = self.flex.hessian(x, y, **self.kwargs_lens) npt.assert_almost_equal(f_xx, 0.05, decimal=5) npt.assert_almost_equal(f_yy, 0.11, decimal=5) npt.assert_almost_equal(f_xy, 0.08, decimal=5) npt.assert_almost_equal(f_xy, f_yx, decimal=8) x = np.array([1, 3, 4]) y = np.array([2, 1, 1]) values = self.flex.hessian(x, y, **self.kwargs_lens) npt.assert_almost_equal(values[0][0], 0.05, decimal=5) npt.assert_almost_equal(values[3][0], 0.11, decimal=5) npt.assert_almost_equal(values[1][0], 0.08, decimal=5) def test_flexion(self): x = np.array(0) y = np.array(2) flex = LensModel(["FLEXIONFG"]) f_xxx, f_xxy, f_xyy, f_yyy = flex.flexion(x, y, [self.kwargs_lens]) _g1, _g2, _g3, _g4 = self.flex.transform_fg(**self.kwargs_lens) npt.assert_almost_equal(f_xxx, _g1, decimal=9) npt.assert_almost_equal(f_xxy, _g2, decimal=9) npt.assert_almost_equal(f_xyy, _g3, decimal=9) npt.assert_almost_equal(f_yyy, _g4, decimal=9) def test_magnification(self): ra_0, dec_0 = 1, -1 flex = LensModel(["FLEXIONFG"]) F1, F2, G1, G2 = 0.02, 0.03, -0.04, -0.05 kwargs = {"F1": F1, "F2": F2, "G1": G1, "G2": G2, "ra_0": ra_0, "dec_0": dec_0} mag = flex.magnification(ra_0, dec_0, [kwargs]) npt.assert_almost_equal(mag, 1, decimal=8) if __name__ == "__main__": pytest.main()
sibirrerREPO_NAMElenstronomyPATH_START.@lenstronomy_extracted@lenstronomy-main@test@test_LensModel@test_Profiles@test_flexionfg.py@.PATH_END.py
{ "filename": "binding.py", "repo_name": "amusecode/amuse", "repo_path": "amuse_extracted/amuse-main/src/amuse/datamodel/binding.py", "type": "Python" }
amusecodeREPO_NAMEamusePATH_START.@amuse_extracted@amuse-main@src@amuse@datamodel@binding.py@.PATH_END.py
{ "filename": "_tickcolor.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/heatmap/colorbar/_tickcolor.py", "type": "Python" }
import _plotly_utils.basevalidators class TickcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="tickcolor", parent_name="heatmap.colorbar", **kwargs ): super(TickcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@heatmap@colorbar@_tickcolor.py@.PATH_END.py
{ "filename": "acb.py", "repo_name": "bcalden/ClusterPyXT", "repo_path": "ClusterPyXT_extracted/ClusterPyXT-master/acb.py", "type": "Python" }
import cluster import pypeline_io as io import numpy as np import time import argparse import data_operations as do from astropy.io import fits import multiprocessing as mp import ciao_contrib.runtool as rt import ciao from tqdm import tqdm def get_arguments(): help_str = """ This part of the pypeline creates all of the adaptive circular binned (acb) files needed to do the spectral fitting. This fitting should likely be offloaded onto a high performance computer. Sample call (with the ciao environment running): python acb.py --cluster_config_file /data_dir/A115/A115_pypeline_config.ini --resolution 2 python acb.py --cluster_config_file /data/dir/A115/A115_pypeline_config.ini --temperature_map """ prog = 'python acb.py' # logger.debug("Getting commandline arguments.") parser = argparse.ArgumentParser(description=help_str, prog=prog) parser.add_argument("--cluster_config_file", "-c", dest="cluster_config", action="store", default=None, help="Path to the cluster configuration file") # parser.add_argument("--parallel", "-p", dest="parallel", # action="store_true", default=False, # help='Run in parallel (default False)') parser.add_argument("--temperature_map", "-t", dest='temperature_map', action="store_true", default=False, help="Create a temperature map after the spectral fitting process.") parser.add_argument("--resolution", "-r", dest='resolution', action='store', default=2, type=int, help='Generate a low, medium, or high resolution temperature map. Low = 1, Med = 2, High = 3. ' 'High resolution is a fit for every pixel, medium pixels are 3x3, low pixels are 5x5.') parser.add_argument('--make_fitting_commands', dest='commands', action='store_true', default=False) parser.add_argument('--eff_times_to_fits', dest='eff_times_fits', action='store_true', default=False) parser.add_argument('--make_pressure_map', dest='pressure', action='store_true', default=False) parser.add_argument('--make_entropy_map', dest='entropy', action='store_true', default=False) parser.add_argument('--shock_finder', dest='shock', action='store_true', default=False) args = parser.parse_args() return args, parser n = 6700 full_x_max = n full_y_max = n YY, XX = np.meshgrid(np.arange(full_y_max * 2), np.arange(full_x_max * 2)) big_mask = np.sqrt((full_x_max - XX) ** 2 + (full_y_max - YY) ** 2) def generate_radius_map(x, y, x_max, y_max): x_start = full_x_max - x y_start = full_y_max - y x_stop = x_start + x_max y_stop = y_start + y_max return big_mask[x_start:x_stop, y_start:y_stop] def create_circle_regions_in_parallel(cluster: cluster.ClusterObj, num_cpus=1): start_time = time.time() observation_lists = cluster.parallel_observation_lists(num_cpus) for observation_list in observation_lists: processes = [mp.Process(target=create_circle_region_for, args=(observation,)) for observation in observation_list] for process in processes: process.start() for process in processes: process.join() end_time = time.time() print("Time elapsed making regions for fit: {:0.2f} (s)".format(end_time-start_time)) def create_circle_region_for(observation: cluster.Observation): mask_fits = fits.open(observation.cluster.combined_mask) region_map = observation.cluster.scale_map_region_index scale_map = observation.cluster.scale_map mask = mask_fits[0].data bounds = scale_map.shape xvals = np.arange(bounds[1]) yvals = np.arange(bounds[0]) print("Making circular fitting regions for observation {}".format(observation.id)) image_fits = fits.open(observation.acisI_comb_img) image_header = image_fits[0].header cdelt1p = image_header['CDELT1P'] cdelt2p = image_header['CDELT2P'] crval1p = image_header['CRVAL1P'] crval2p = image_header['CRVAL2P'] crpix1p = image_header['CRPIX1P'] crpix2p = image_header['CRPIX2P'] radii = mask * scale_map * cdelt1p newx = ((xvals + 1 - crpix1p) * cdelt1p) + crval1p newy = ((yvals + 1 - crpix2p) * cdelt2p) + crval2p xx, yy = np.meshgrid(newx, newy) non_zero_indices = np.nonzero(radii) nz_rad = radii[non_zero_indices] nz_x = xx[non_zero_indices] nz_y = yy[non_zero_indices] obs_regions = region_map[non_zero_indices] region_array = np.array([(i, j, k, l) for i, j, k, l in zip(nz_x, nz_y, nz_rad, obs_regions)]) regions = [["circle({x},{y},{rad})".format(x=x[0], y=x[1], rad=x[2]), int(x[3])] for x in region_array] observation.scale_map_region_list = regions def create_circle_regions(cluster): start_time = time.time() scale_map_fits = fits.open(cluster.scale_map_file) mask_fits = fits.open(cluster.combined_mask) region_map = cluster.scale_map_region_index scale_map = scale_map_fits[0].data mask = mask_fits[0].data bounds = scale_map.shape xvals = np.arange(bounds[1]) yvals = np.arange(bounds[0]) for observation in cluster.observations: print("Making circular fitting regions for observation {}".format(observation.id)) image_fits = fits.open(observation.acisI_comb_img) image_header = image_fits[0].header cdelt1p = image_header['CDELT1P'] cdelt2p = image_header['CDELT2P'] crval1p = image_header['CRVAL1P'] crval2p = image_header['CRVAL2P'] crpix1p = image_header['CRPIX1P'] crpix2p = image_header['CRPIX2P'] radii = mask * scale_map * cdelt1p newx = ((xvals + 1 - crpix1p) * cdelt1p) + crval1p newy = ((yvals + 1 - crpix2p) * cdelt2p) + crval2p xx, yy = np.meshgrid(newx, newy) non_zero_indices = np.nonzero(radii) nz_rad = radii[non_zero_indices] nz_x = xx[non_zero_indices] nz_y = yy[non_zero_indices] obs_regions = region_map[non_zero_indices] region_array = np.array([(i, j, k, l) for i, j, k, l in zip(nz_x, nz_y, nz_rad, obs_regions)]) regions = [["circle({x},{y},{rad})".format(x=x[0], y=x[1], rad=x[2]), int(x[3])] for x in region_array] observation.scale_map_region_list = regions end_time = time.time() print("Time elapsed making regions for fit: {:0.2f} (s)".format(end_time-start_time)) def create_region_index_map(cluster): mask_fits = fits.open(cluster.combined_mask) mask = mask_fits[0].data sz = mask.shape nx = sz[0] ny = sz[1] indexmap = np.zeros(sz) position = 0 region_string = [] for ci in range(nx): for cj in range(ny): if mask[ci,cj] == 1: if ci % 3 == 0 and cj % 3 == 0: # makes it a lower resolution image than it needs to be. region_string.append(str(position)) indexmap[ci,cj] = position position += 1 region_string = '\n'.join(region_string) with open(cluster.region_list, 'w') as f: f.write(region_string) region_file = mask_fits region_file[0].data = indexmap region_file[0].writeto(cluster.region_to_index, overwrite=True) def create_scale_map_region_index(cluster: cluster.ClusterObj): scale_map = cluster.scale_map scale_map_regions = np.zeros(scale_map.shape) sx = scale_map.shape[0] sy = scale_map.shape[1] region_num = 1 for x in range(sx): for y in range(sy): if scale_map[x,y] != 0: scale_map_regions[x,y] = region_num region_num += 1 else: scale_map_regions[x,y] = np.nan fits.writeto(cluster.scale_map_region_file, # filename scale_map_regions, # data to write cluster.scale_map_header, # header so coordinate information is written overwrite=True) # self explanatory def _update_completed_things(current, max_num, thing): io.clear_line() io.write("{current} out of {max} {thing} complete. ".format( current=current, max=max_num, thing=thing )) io.flush() def _source_free_region(counter, current, max_num): io.clear_line() io.write("Encountered a source-free region -- recalculating...{counter} - {current}/{max} complete".format( counter=counter, current=current, max=max_num )) io.flush() def _update_effective_exposure_time(obsid, current_region, number_regions, time_elapsed): #io.clear_line() #io.write("{current_region} of {num_regions} complete. Time elapsed: {time}".format( print("ObsID {obsid} -\t{current_region} of {num_regions} complete. Time elapsed: {time}".format( obsid=obsid, current_region=current_region, num_regions=number_regions, time=time_elapsed )) io.flush() def create_scale_map_in_parallel(cluster: cluster.ClusterObj): mask = cluster.combined_mask_data cts_image = np.zeros(mask.shape) back_rescale = np.zeros(mask.shape) for obs in cluster.observations: cts_image += obs.acisI_combined_image t_obs = obs.acisI_combined_image_header['EXPOSURE'] t_back = obs.backI_combined_image_header['EXPOSURE'] back_rescale += (t_obs / t_back) * obs.backI_combined_image signal = cts_image - back_rescale signal[np.where(signal < 0)] = 0 sz = signal.shape max_x = sz[0] max_y = sz[1] io.make_directory(cluster.acb_dir) cluster.initialize_scale_map_csv() pix_x = np.zeros(sz) pix_y = np.zeros(sz) for j in range(max_y): for i in range(max_x): pix_x[i, j] = float(i) pix_y[i, j] = float(j) num_pix = max_x * max_y start_time = time.time() indices = np.vstack(np.where(mask==1)).T num_index_lists = (indices.shape[0] // mp.cpu_count()) index_lists = np.array_split(indices, num_index_lists) num_iterations = len(index_lists) for i, index_list in enumerate(index_lists): if i % 100 == 0: print("{} of {} iterations complete.".format(i, num_iterations)) processes = [mp.Process(target=calculate_radius_at_index, args=(index, cluster, pix_x, pix_y, cts_image, num_pix, back_rescale)) for index in index_list] for process in processes: process.start() for process in processes: process.join() cluster.write_scale_map_csv_to_fits() end_time = time.time() print("Time elapsed {:0.2f} seconds.".format(end_time - start_time)) def calculate_radius_at_index(index, cluster: cluster.ClusterObj, pix_x: np.ndarray, pix_y: np.ndarray, counts_image: np.ndarray, num_pix: int, back_rescale: np.ndarray): x_index = index[0] y_index = index[1] #print("Working on region at x:{} y:{}".format(x_index, y_index)) delta_x = x_index-pix_x delta_y = y_index-pix_y radius = np.sqrt(delta_x**2 + delta_y**2) dr = 24.0 min_dr = 0.125 hilo = 0 niter = 0 max_radius = 100 r = max_radius + 1 # potentially a IDL vestige counter = 0 signal_to_noise = 0 scale_map_radius = 0 while (dr > min_dr) and (niter < 100): indices = np.where(radius <= r) counts_map_total = np.sum(counts_image[indices]) if counts_map_total == 0: counter += 1 _source_free_region(counter, x_index*y_index, num_pix) sn_val = 0 hilo = -1 else: backmap_tot = np.sum(back_rescale[indices]) signal_total = counts_map_total - backmap_tot noise_total = np.sqrt(counts_map_total + backmap_tot) sn_val = signal_total / noise_total if float(sn_val) < float(cluster.target_sn): if r > max_radius: r = max_radius + 1 niter = 110 # exit by setting niter=110. # (niter=100 means niter hit max niter. # niter=110 means radius hit max radius) signal_to_noise = 0 scale_map_radius = 0 else: if hilo == 1: dr *= 0.5 r += dr hilo = -1 else: snmapval = signal_to_noise if (sn_val < snmapval) or (snmapval == 0.0): signal_to_noise = sn_val scale_map_radius = r if hilo == -1: dr *= 0.5 r -= dr hilo = 1 niter += 1 #print("x:{} y:{} -> radius: {}.".format(x_index, y_index, scale_map_radius)) cluster.write_scale_map_radius(x_index, y_index, scale_map_radius, signal_to_noise) # def binary_search_radii(arguments): # cluster, index = arguments # radii = np.arange(start=1, stop=101, step=0.125) # left = 0 # right = radii.shape[0] # nx, ny = cluster.combined_mask_data.shape # x, y = index # radius = generate_radius_map(x, y, nx, ny) # if np.sum(cluster.counts_image[radius<=radii[-1]]) == 0: # radii[-1] == max bin radius # update_stuff() # print("None @ {index}".format(index=index)) # cluster.write_scale_map_radius(x, y, 0, 0) # no radius, no S/N ratio # return # while left < right: # middle = int((left+right)/2) # r = radii[middle] # #indices_within_r = np.where(radius<=r) # indices_within_r = radius<=r # total_counts = np.sum(cluster.counts_image[indices_within_r]) # back_map_total = np.sum(cluster.back_rescale[indices_within_r]) # signal_total = total_counts - back_map_total # noise_total = np.sqrt(total_counts + back_map_total) # signal_to_noise = signal_total / noise_total # if signal_to_noise < cluster.target_sn: # left = middle + 1 # else: # right = middle # update_stuff() # if r <= 100: # cluster.write_scale_map_radius(x, y, r, signal_to_noise) # else: # cluster.write_scale_map_radius(x, y, 0, 0) update_counter = 0 def update_stuff(): global update_counter update_counter += 1 if update_counter % 1000 == 0: io.clear_line() count = update_counter * mp.cpu_count() io.write("{count} regions finished.".format(count=count)) io.flush() def binary_search_radii_wrapper(args): image, index, search_radii, s_to_n = args return binary_search_radii(image, index, search_radii, float(s_to_n)) def binary_search_radii(image=np.zeros(0), index=(0,0), search_radii=np.arange(1,100.125,0.125), s_to_n=40): """Use a binary search algorithm to find the smallest radius circular bin, centered at the given index, that affords the desired signal to noise ratio. Keyword arguments: image -- The image you are binning (2d numpy array) index -- The pixel within the image the circular bin is centered on (e.g. [0,0]) search_radii -- The various radii to search through in an effort to find the smallest (1D numpy array) s_to_n -- The desired signal to noise ratio each bin must achieve. returns -- x,y (the seperated index argument), bin radius, signal to noise """ radii = search_radii left = 0 right = radii.shape[0] nx, ny = image.shape x, y = index max_radii = search_radii[-1] buff_radius = int(max_radii+2) x1 = x - buff_radius x1 = 0 if x1 < 0 else x1 x2 = x + buff_radius x2 = nx if x2 > nx else x2 y1 = y - buff_radius y1 = 0 if y1 < 0 else y1 y2 = y + buff_radius y2 = ny if y2 > ny else y2 small_image = image[x1:x2, y1:y2] radius = generate_radius_map(x, y, nx, ny)[x1:x2, y1:y2] if np.sum(small_image[radius<=radii[-1]]) == 0: return x,y,0,0 last_good_radii = None last_good_s_to_n = 0 while left < right: middle = int((left+right)/2) r = radii[middle] indices_within_r = radius<=r total_counts = np.sum(small_image[indices_within_r]) noise_total = np.sqrt(total_counts) signal_to_noise = total_counts / noise_total if signal_to_noise < s_to_n: left = middle + 1 else: last_good_radii=r last_good_s_to_n = signal_to_noise right = middle if r <= 100: return x,y,last_good_radii,last_good_s_to_n else: counter += 1 return x,y,0,0 def generate_acb_scale_map_for(indices=None, image=np.zeros(0), max_bin_radius=100, step_size=0.125, s_to_n=40, num_processes=20): """Generate an adaptive circular bin map for the given image. Keyword arguments: image -- The image you want an adaptive circular bin map for (2D numpy array) max_bin_radius -- The maximum bin radius for each circular bin (int) step_size -- The step size between different radii. (float) s_to_n -- The desired signal to noise ratio for each bin (int although can be float) num_processes -- The number of processes you want to use for your multiprocessing pool (int) returns -- The adaptive circular bin map and the signal to noise map (both 2D numpy arrays) """ # indices = np.vstack(np.where(~np.isnan(image))).T radii_to_search = np.arange(start=1, stop=max_bin_radius+step_size, step=step_size) acb_scale_map = np.zeros(image.shape) s_to_n_map = np.zeros(image.shape) arguments = [[image, index, radii_to_search, s_to_n] for index in indices] with mp.Pool(num_processes) as pool: results = list(tqdm(pool.imap(binary_search_radii_wrapper, arguments), total=len(arguments), desc="Calculating ACB Map")) np_res = np.array(results) print(np_res.shape) x = np_res[:,0].astype(int) y = np_res[:,1].astype(int) acb_scale_map[x,y] = np_res[:,2] s_to_n_map[x,y] = np_res[:,3] return acb_scale_map, s_to_n_map def fast_acb_creation_parallel(cluster: cluster.ClusterObj, num_cpus=mp.cpu_count()): start_time = time.time() indices = cluster.scale_map_indices print("Calculating {num_regions} regions".format(num_regions=indices.shape[0])) cluster.initialize_scale_map_csv() cluster.back_rescale cluster.counts_image cluster.combined_mask_data scale_map, s_to_n_map = generate_acb_scale_map_for(indices, cluster.counts_image, num_processes=num_cpus, s_to_n=cluster.signal_to_noise) io.write_numpy_array_to_fits(scale_map, cluster.scale_map_file, cluster.xray_surface_brightness_nosrc_cropped_header) io.write_numpy_array_to_fits(s_to_n_map, f'{cluster.acb_dir}/{cluster.name}_signal_to_noise_map.fits', cluster.xray_surface_brightness_nosrc_cropped_header) end_time = time.time() print("Time elapsed {:0.2f} seconds.".format(end_time - start_time)) def fast_acb_creation_serial(cluster: cluster.ClusterObj): start_time = time.time() indices = cluster.scale_map_indices print("Calculating {num_regions} regions".format(num_regions=indices.shape[0])) cluster.initialize_scale_map_csv() for index in indices: binary_search_radii((cluster, index)) cluster.write_scale_map_csv_to_fits() end_time = time.time() print("Time elapsed {elapsed:0.2f} seconds.".format(elapsed=end_time - start_time)) def prepare_efftime_circle_parallel(cluster: cluster.ClusterObj, num_cpus=1): try: from ciao_contrib import runtool as rt except ImportError: print("Failed to import CIAO python scripts. ") raise observation_lists = cluster.parallel_observation_lists(num_cpus) for observation_list in observation_lists: print("Preparing for effective time calculations in parallel.") processes = [mp.Process(target=prepare_effective_time_circles_for, args=(observation,)) for observation in observation_list] for process in processes: process.start() for process in processes: process.join() def prepare_effective_time_circles_for(observation: cluster.Observation): io.delete_if_exists(observation.effbtime) io.delete_if_exists(observation.effdtime) if not io.file_exists(observation.acisI_nosrc_combined_mask_file): print("Removing point sources from the observations combined mask file.") print("dmcopy infile='{}[exclude sky=region({})]' outfile={} clobber=True".format( observation.acisI_combined_mask_file, observation.cluster.sources_file, observation.acisI_nosrc_combined_mask_file )) rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[exclude sky=region({source_file})]".format( fits_file=observation.acisI_combined_mask_file, source_file=observation.cluster.sources_file ), outfile=observation.acisI_nosrc_combined_mask_file, clobber=True ) else: print("{acis} already exists.".format( acis=observation.acisI_nosrc_combined_mask_file )) # if not io.file_exists(observation.acisI_high_energy_combined_image_file): print("Creating high band (9.5-12 keV) source image cropped to combined region.") rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[sky=region({crop_file})]".format( fits_file=observation.clean, crop_file=observation.cluster.master_crop_file ), outfile=observation.acisI_high_energy_temp_image, clobber=True ) ##########need to change to obs specific rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[EVENTS][bin sky=4][energy=9500:12000]".format( fits_file=observation.acisI_high_energy_temp_image ), outfile=observation.acisI_high_energy_combined_image_file, option="image", clobber=True ) io.delete_if_exists(observation.acisI_high_energy_temp_image) print("Creating high band (9.5-12 keV) background image cropped to combined region.") rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[sky=region({crop_file})]".format( fits_file=observation.back, crop_file=observation.cluster.master_crop_file ), outfile=observation.backI_high_energy_temp_image, clobber=True ) rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[EVENTS][bin sky=4][energy=9500:12000]".format( fits_file=observation.backI_high_energy_temp_image ), outfile=observation.backI_high_energy_combined_image_file, option="image", clobber=True ) io.delete_if_exists(observation.backI_high_energy_temp_image) def prepare_efftime_circle(cluster): try: from ciao_contrib import runtool as rt except ImportError: print("Failed to import CIAO python scripts. ") raise for observation in cluster.observations: io.delete_if_exists(observation.effbtime) io.delete_if_exists(observation.effdtime) if not io.file_exists(observation.acisI_nosrc_combined_mask_file): print("Removing point sources from the observations combined mask file.") print("dmcopy infile='{}[exclude sky=region({})]' outfile={} clobber=True".format( observation.acisI_combined_mask_file, cluster.sources_file, observation.acisI_nosrc_combined_mask_file )) rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[exclude sky=region({source_file})]".format( fits_file=observation.acisI_combined_mask_file, source_file=cluster.sources_file ), outfile=observation.acisI_nosrc_combined_mask_file, clobber=True ) else: print("{acis} already exists.".format( acis=observation.acisI_nosrc_combined_mask_file )) if not io.file_exists(observation.acisI_high_energy_combined_image_file): print("Creating high band (9.5-12 keV) source image cropped to combined region.") rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[sky=region({crop_file})]".format( fits_file=observation.clean, crop_file=cluster.master_crop_file ), outfile=observation.acisI_high_energy_temp_image, clobber=True ) rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[EVENTS][bin sky=4][energy=9500:12000]".format( fits_file=observation.acisI_high_energy_temp_image ), outfile=observation.acisI_high_energy_combined_image_file, option="image", clobber=True ) else: print("{fits_file} already exists.".format( fits_file=observation.acisI_high_energy_combined_image_file )) io.delete_if_exists(observation.acisI_high_energy_temp_image) if not io.file_exists(observation.backI_high_energy_combined_image_file): print("Creating high band (9.5-12 keV) background image cropped to combined region.") rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[sky=region({crop_file})]".format( fits_file=observation.back, crop_file=cluster.master_crop_file ), outfile=observation.backI_high_energy_temp_image, clobber=True ) rt.dmcopy.punlearn() rt.dmcopy( infile="{fits_file}[EVENTS][bin sky=4][energy=9500:12000]".format( fits_file=observation.backI_high_energy_temp_image ), outfile=observation.backI_high_energy_combined_image_file, option="image", clobber=True ) else: print("{fits_file} already exists.".format( fits_file=observation.backI_high_energy_combined_image_file )) io.delete_if_exists(observation.backI_high_energy_temp_image) def calculate_effective_times(cluster: cluster.ClusterObj): start_time = time.time() scale_map = cluster.scale_map number_of_regions = cluster.number_of_regions nx = scale_map.shape[0] ny = scale_map.shape[1] effective_data_times = np.zeros(scale_map.shape) effective_background_times = np.zeros(scale_map.shape) for observation in cluster.observations: print("Starting observation {obs}".format(obs=observation.id)) high_energy_data = observation.acisI_high_energy_combined_image background = observation.backI_high_energy_combined_image sum_acis_high_energy = np.sum(high_energy_data) # get the total counts in the high energy image sum_back_high_energy = np.sum(background) bg_to_data_ratio = sum_back_high_energy / sum_acis_high_energy source_subtracted_data = observation.acisI_nosrc_combined_mask exposure_time = observation.acisI_high_energy_combined_image_header['EXPOSURE'] YY, XX = np.meshgrid(np.arange(ny), np.arange(nx)) counter = 0 print("Starting effective exposure time calculations...") for x in range(nx): for y in range(ny): if scale_map[x,y] >= 1: radius = np.sqrt((x - XX)**2 + (y - YY)**2) region = np.where(radius <= scale_map[x, y]) source_subtracted_area = np.sum(source_subtracted_data[region]) total_area = source_subtracted_data[region].size fractional_area = source_subtracted_area / total_area fractional_exposure_time = fractional_area * exposure_time effective_data_times[x, y] = fractional_exposure_time effective_background_times[x, y] = fractional_exposure_time * bg_to_data_ratio counter += 1 if counter % 1000 == 0 or counter == number_of_regions or counter == 1: time_elapsed = time.strftime("%H hours %M minutes %S seconds.", time.gmtime(time.time()-start_time)) _update_effective_exposure_time(obsid=observation.id, current_region=counter, number_regions=number_of_regions, time_elapsed=time_elapsed ) observation.effective_data_time = effective_data_times observation.effective_background_time = effective_background_times def calculate_effective_times_in_parallel(cluster: cluster.ClusterObj, num_cpus=1): observation_lists = cluster.parallel_observation_lists(num_cpus) print('Calculating effective times in parallel using {} processes.'.format(num_cpus)) for observation_list in observation_lists: processes = [mp.Process(target=calculate_effective_time_for, args=(observation,)) for observation in observation_list] for process in processes: process.start() for process in processes: process.join() def calculate_effective_times_in_parallel_map(cluster: cluster.ClusterObj, num_cpus=1): with mp.Pool(num_cpus) as pool: result = pool.map(calculate_effective_time_for, cluster.observations) return result def calculate_effective_times_in_serial(cluster: cluster.ClusterObj): for observation in cluster.observations: calculate_effective_time_for(observation) def calculate_effective_time_for(observation: cluster.Observation): """This function returns 2 image maps, data and background, of the cluster representing the same area of the cluster the scale map represents. Each pixel of the map represents the effective time observed for each of the ACB regions. The effective observed time is essentially the integrated observing time for each acb region. This is value differs from a simple, area of region * exposure time as some parts of the region may be masked (i.e. a removed point source within the ACB region).""" print("Starting observation {obs}".format(obs=observation.id)) start_time = time.time() scale_map = observation.cluster.scale_map nx = scale_map.shape[0] ny = scale_map.shape[1] effective_data_times = np.zeros(scale_map.shape) effective_background_times = np.zeros(scale_map.shape) if observation.acisI_nosrc_combined_mask.shape != scale_map.shape: observation.reproject_nosrc_combined_mask(observation.cluster.scale_map_file) if observation.acisI_combined_mask.shape != scale_map.shape: observation.reproject_combined_mask(observation.cluster.scale_map_file) high_energy_data = observation.acisI_high_energy_combined_image background = observation.backI_high_energy_combined_image sum_acis_high_energy = np.sum(high_energy_data) # get the total counts in the high energy image sum_back_high_energy = np.sum(background) bg_to_data_ratio = sum_back_high_energy / sum_acis_high_energy source_subtracted_mask = observation.acisI_nosrc_combined_mask exposure_time = observation.acisI_high_energy_combined_image_header['EXPOSURE'] indices = np.vstack(np.where(observation.acisI_combined_mask * scale_map > 0)).T total = len(indices) counter = 1 for index in indices: x,y = index if counter % 5000 == 0: time_elapsed = time.strftime("%H h %M m %S s", time.gmtime(time.time() - start_time)) print("ObsID {}\t {} of {} regions calculated. Time elapsed: {}. Avg {:2f} ms/region".format( observation.id, counter, total, time_elapsed, ((time.time() - start_time)/counter)*1000)) io.flush() radius_map = generate_radius_map(x, y, nx, ny) circle_mask = radius_map <= scale_map[x, y] source_subtracted_area = np.sum(source_subtracted_mask[circle_mask]) total_area = source_subtracted_mask[circle_mask].size fractional_area = source_subtracted_area / total_area fractional_exposure_time = fractional_area * exposure_time effective_data_times[x, y] = fractional_exposure_time effective_background_times[x, y] = fractional_exposure_time * bg_to_data_ratio counter += 1 observation.effective_data_time = effective_data_times observation.effective_background_time = effective_background_times time_elapsed = time.strftime("%H hours %M minutes %S seconds.", time.gmtime(time.time() - start_time)) print("ObsID {} complete. Time elapsed: {}".format(observation.id, time_elapsed)) def prepare_for_spec(cluster_obj: cluster.ClusterObj): try: import ciao except ImportError: print("Must be running CIAO before running prepare_for_spec.") raise io.make_directory(cluster_obj.super_comp_dir) cluster_obj.initialize_best_fits_file() print("Preparing files for spectral analysis and copying to {super_comp_dir} for offloading computation.".format( super_comp_dir=cluster_obj.super_comp_dir )) io.copy(cluster_obj.configuration_filename, cluster_obj.super_comp_cluster_config) for observation in cluster_obj.observations: print("Copying files for {obsid}".format(obsid=observation.id)) io.copy(observation.clean, cluster_obj.acisI_clean_obs(observation.id)) io.copy(observation.back, cluster_obj.backI_clean_obs(observation.id)) io.copy(observation.aux_response_file, observation.arf_sc) io.copy(observation.redistribution_matrix_file, observation.rmf_sc) io.copy(observation.acis_mask, observation.acis_mask_sc) exposure = ciao.get_exposure(observation.clean) io.write_contents_to_file(exposure, observation.exposure_time_file, binary=False) def make_commands_lis(cluster: cluster.ClusterObj, resolution): print("Creating {}".format(cluster.command_lis)) offset = [None, 5, 3, 1][resolution] start_time = time.time() region_list = cluster.scale_map_regions_to_fit(resolution) command_string = [] pypeline_dir = io.get_user_input("Enter the directory containing the pix2pix.py portion of the pypeline on the remote machine: ") pix2pix_path = "{pypeline_dir}/pix2pix.py".format(pypeline_dir=pypeline_dir) data_dir = io.get_user_input("Enter the directory containing the cluster data on the remote machine:\n" "For example: /home/user/data/clustername/\n") for region in region_list: new_command = "python {pix2pix} {cluster_config} {region}".format( pix2pix=pix2pix_path, cluster_config="{data_dir}/{name}_pypeline_config.ini".format( data_dir=data_dir, name=cluster.name ), region=region ) command_string.append(new_command) command_lis = "\n".join(command_string) region_string = '\n'.join([str(x) for x in region_list]) io.write_contents_to_file(command_lis, cluster.command_lis, binary=False) io.write_contents_to_file(region_string, cluster.filtered_region_list, binary=False) end_time = time.time() print("Time elapsed: {time:0.2f} sec".format(time=(end_time-start_time))) def make_temperature_map(cluster: cluster.ClusterObj, resolution, average=False): #coordinates = get_pixel_coordinates(cluster) # indices of this array are the region number minus 1 # that is, region number 1 is coordinate array index 0 # region 100 = coordinates[99] # high_res_offset = 0 # med_res_offset = 1 # low_res_offset = 2 io.make_directory(cluster.output_dir) offset = [None, 2, 1, 0][resolution] mask_fits = fits.open(cluster.combined_mask) mask = mask_fits[0].data scale_map_regions = cluster.scale_map_region_index temps_with_errors = cluster.average_temperature_fits if average else cluster.temperature_fits temperature_map = np.zeros(mask.shape) temperature_error_map = np.zeros(mask.shape) temperature_fractional_error_map = np.zeros(mask.shape) regions = temps_with_errors['region'] temperatures = temps_with_errors['temperature'] temp_error_plus = temps_with_errors['temp_err_plus'] temp_error_minus = temps_with_errors['temp_err_minus'] for i, region in enumerate(regions): if i % 1000 == 0: _update_completed_things(i, len(regions), "regions") coordinates = cluster.coordinates_for_scale_map_region(region, scale_map_regions) x = int(coordinates[0]) y = int(coordinates[1]) low_x = x - offset high_x = x + offset + 1 low_y = y - offset high_y = y + offset + 1 temperature_map[low_x:high_x, low_y:high_y] = temperatures[i] temperature_error_map[low_x:high_x, low_y:high_y] = (np.abs(temp_error_plus[i] - temp_error_minus[i]))/2 temperature_fractional_error_map[low_x:high_x, low_y:high_y] = \ (temperature_error_map[x,y]/temperature_map[x,y]) if i: _update_completed_things(i, len(regions), "regions") header = mask_fits[0].header # This header contains all coordinate information needed fits.writeto(cluster.temperature_map_filename, temperature_map, header, overwrite=True) fits.writeto(cluster.temperature_error_map_filename, temperature_error_map, header, overwrite=True) fits.writeto(cluster.temperature_fractional_error_map_filename, temperature_fractional_error_map, header, overwrite=True) def make_fit_map(cluster: cluster.ClusterObj, fit_type='Norm', resolution=2): io.make_directory(cluster.output_dir) offset = [None, 2, 1, 0][resolution] mask_fits = fits.open(cluster.combined_mask) mask = mask_fits[0].data scale_map_regions = cluster.scale_map_region_index fits_with_errors = cluster.get_fits_from_file_for(fit_type) fit_map = np.zeros(mask.shape) fit_error_map = np.zeros(mask.shape) fit_fractional_error_map = np.zeros(mask.shape) err_high = "{fit_type}_err_+".format(fit_type=fit_type) err_low = "{fit_type}_err_-".format(fit_type=fit_type) regions = fits_with_errors['region'] actual_fits = fits_with_errors[fit_type] fit_err_plus = fits_with_errors[err_high] fit_err_low = fits_with_errors[err_low] for i, region in enumerate(regions): if i% 1000 == 0: _update_completed_things(i, len(regions), 'regions') coordinates = cluster.coordinates_for_scale_map_region(region, scale_map_regions) x = int(coordinates[0]) y = int(coordinates[1]) low_x = x - offset high_x = x + offset + 1 low_y = y - offset high_y = y + offset + 1 fit_map[low_x:high_x, low_y:high_y] = actual_fits[i] fit_error_map[low_x:high_x, low_y:high_y] = (np.abs(fit_err_plus[i] - fit_err_low[i]))/2 fit_fractional_error_map[low_x:high_x, low_y:high_y] = \ (fit_error_map[x,y]/fit_map[x,y]) try: if i: _update_completed_things(i, len(regions), 'regions') except ValueError: io.print_red("Error trying to load the file, {spec_fits_file}".format(spec_fits_file=cluster.spec_fits_file)) raise header = mask_fits[0].header fits.writeto(cluster.fit_map_filename(fit_type), fit_map, header, overwrite=True ) fits.writeto(cluster.fit_error_map_filename(fit_type), fit_error_map, header, overwrite=True) fits.writeto(cluster.fit_fractional_error_map_filename(fit_type), fit_fractional_error_map, header, overwrite=True) def fitting_preparation(clstr, args=None, num_cpus=None): if args is None: resolution = 2 cpu_count = mp.cpu_count() else: resolution = args.resolution cpu_count = args.num_cpus if num_cpus: cpu_count = num_cpus print("Creating the scale map.") #create_scale_map_in_parallel(clstr) fast_acb_creation_parallel(clstr, num_cpus=cpu_count) print("Creating the region index map.") create_scale_map_region_index(clstr) print("Preparing the high-energy images and backgrounds.") prepare_efftime_circle_parallel(clstr, cpu_count) print("Calculating effective times.") #calculate_effective_times_in_parallel(clstr, cpu_count) #calculate_effective_times_in_serial(clstr) calculate_effective_times_in_parallel_map(clstr, cpu_count) print("Creating circular fitting regions.") create_circle_regions_in_parallel(clstr, cpu_count) print("Preparing for the spectral fits.") prepare_for_spec(clstr) #print("Making the command list for use with mpiexec.") #make_commands_lis(clstr, resolution) # 3 for high_res, 2 for medium res, # 1 for low res print("Finished all of the preparation for the spectral fits. At this point you should copy\n" "the data folder over to a high performance computer. If speed and space aren't an issue,\n" "copy the entire cluster folder over. The only files really needed are the configuration\n" "file [cluster_pypeline_config.ini] and the acb folder (maintaining the original directory\n" "structure).") print("\nNext, you can either run wrapper.py directly or create a small bash file for scheduled\n" "running. If you need to create the bash file to call wrapper.py, make sure you setup the\n" "ciao environment in the bash file before calling python wrapper.py --configfile --etc.") def eff_times_to_fits(clstr: cluster.ClusterObj): for observation in clstr.observations: effbt = observation.effective_background_time effdt = observation.effective_data_time temp = fits.open(clstr.scale_map_file) temp[0].data = effbt print(io.get_path("writing {}/{}_{}_eff_bkg_time.fits".format(clstr.directory, clstr.name, observation.id))) temp.writeto(io.get_path('{}/{}_{}_eff_bkg_time.fits'.format(clstr.directory, clstr.name, observation.id))) temp[0].data = effdt print(io.get_path('writing {}/{}_{}_eff_data_time.fits'.format(clstr.directory, clstr.name, observation.id))) temp.writeto(io.get_path('{}/{}_{}_eff_data_time.fits'.format(clstr.directory, clstr.name, observation.id))) def make_density_map(clstr: cluster.ClusterObj): xray_sb_fits = fits.open(clstr.smoothed_xray_sb_cropped_nosrc_filename) xray_sb_header = xray_sb_fits[0].header xray_sb = xray_sb_fits[0].data # xray surface brightness is proportional to density squared. # therefore, relative density is the square root of the xray surface brightness n = np.sqrt(xray_sb) fits.writeto(clstr.density_map_filename, n, header=xray_sb_header, overwrite=True) return n def reproject_density_map(clstr: cluster.ClusterObj): import ciao print("Reprojecting density map.") ciao.reproject(infile=clstr.density_map_filename, matchfile=clstr.combined_mask, outfile=clstr.density_map_temp_filename) io.move(clstr.density_map_temp_filename, clstr.density_map_filename) return clstr.density_map def reproject_temperature_map(clstr: cluster.ClusterObj): import ciao print("Reprojecting Temperature map.") ciao.reproject(infile=clstr.temperature_map_filename, matchfile=clstr.combined_mask, outfile=clstr.temperature_map_temp_filename) io.move(clstr.temperature_map_temp_filename, clstr.temperature_map_filename) return clstr.temperature_map def get_matching_density_and_temperature_maps(clstr: cluster.ClusterObj): if not io.file_exists(clstr.density_map_filename): make_density_map(clstr) n, T = make_sizes_match(input_image=clstr.density_map_filename, second_image=clstr.temperature_map_filename) # n = clstr.density_map # T = clstr.temperature_map # n, T = make_sizes_match(n, T) return n, T def make_pressure_map(clstr: cluster.ClusterObj): n, T = get_matching_density_and_temperature_maps(clstr) P = n*T norm_P = do.normalize_data(P) fits.writeto(clstr.pressure_map_filename, norm_P, header=clstr.temperature_map_header, overwrite=True) def make_pressure_error_maps(clstr: cluster.ClusterObj): pass def make_entropy_map(clstr: cluster.ClusterObj): n, T = get_matching_density_and_temperature_maps(clstr) K = np.zeros(n.shape) nonzero_indices = np.nonzero(n) K[nonzero_indices] = T[nonzero_indices] * ((n[nonzero_indices])**(-2/3)) norm_K = do.normalize_data(K) fits.writeto(clstr.entropy_map_filename, norm_K, header=clstr.temperature_map_header, overwrite=True) def reproject(infile=None, matchfile=None, outfile=None, overwrite=False): rt.reproject_image.punlearn() rt.reproject_image(infile=infile, matchfile=matchfile, outfile=outfile, clobber=overwrite) def repro_filename(original_filename): split_filename = original_filename.split('.') split_filename[-2] += "_repro" return ".".join(split_filename) def make_smoothed_xray_map(clstr: cluster.ClusterObj): scale_map = clstr.scale_map_file sb_map = clstr.xray_surface_brightness_nosrc_cropped_filename print("Using {acb_map_file} and {xray_sb_map_file}".format( acb_map_file=clstr.scale_map_file, xray_sb_map_file=clstr.xray_surface_brightness_nosrc_cropped_filename )) sb_map, scale_map = make_sizes_match(input_image=clstr.xray_surface_brightness_nosrc_cropped_filename, second_image=clstr.scale_map_file) #sb_map, scale_map = do.make_sizes_match(sb_map, scale_map) max_x, max_y = sb_map.shape new_map = np.zeros(scale_map.shape) for x in range(max_x): print(f'{x} out of {max_x}') for y in range(max_y): if scale_map[x,y]: radius_map = generate_radius_map(x, y, max_x, max_y) radius_mask = radius_map <= scale_map[x,y] new_map[x,y] = sb_map[radius_mask].mean() fits.writeto(clstr.smoothed_xray_sb_cropped_nosrc_filename, new_map, header=clstr.scale_map_header, overwrite=True) print("{smoothed_filename} written. X-ray SB ACB map complete.".format( smoothed_filename=clstr.smoothed_xray_sb_cropped_nosrc_filename )) def calc_acb_val_for(args): index, sb_map, scale_map = args x, y = index max_x, max_y = sb_map.shape if scale_map[x,y]: radius_map = generate_radius_map(x, y, max_x, max_y) radius_mask = radius_map <= scale_map[x,y] return [x,y, sb_map[radius_mask].mean()] return [x,y, 0] def make_smoothed_xray_map_parallel(clstr: cluster.ClusterObj): scale_map = clstr.scale_map_file sb_map = clstr.xray_surface_brightness_nosrc_cropped_filename sb_map, scale_map = make_sizes_match( input_image=clstr.xray_surface_brightness_nosrc_cropped_filename, second_image=clstr.scale_map_file) new_map = np.zeros(scale_map.shape) indices = np.array(list(np.ndindex(*new_map.shape))) args = [[i, sb_map, scale_map] for i in indices] with mp.Pool() as p: # results = list(tqdm(p.imap(calc_acb_val_for, args), total=len(args))) results = p.map(calc_acb_val_for, args) results = np.array(results) x = results[:,0].astype(int) y = results[:,1].astype(int) vals = results[:,2] new_map[x,y] = vals fits.writeto(clstr.smoothed_xray_sb_cropped_nosrc_filename, new_map, header=clstr.scale_map_header, overwrite=True) print(f"{clstr.smoothed_xray_sb_cropped_nosrc_filename} written. X-ray SB ACB map complete.") def make_sizes_match(input_image, second_image): input_data = fits.open(input_image)[0].data second_data = fits.open(second_image)[0].data if input_data.shape != second_data.shape: if input_data.size > second_data.size: reprojected_filename = repro_filename(second_image) reproject(infile=second_image, matchfile=input_image, outfile=reprojected_filename, overwrite=True) second_data = fits.open(reprojected_filename)[0].data else: reprojected_filename = repro_filename(input_image) reproject(infile=input_image, matchfile=second_image, outfile=reprojected_filename, overwrite=True) input_data = fits.open(reprojected_filename)[0].data return input_data, second_data if __name__ == '__main__': args, parser = get_arguments() if args.cluster_config is not None: clstr = cluster.load_cluster(args.cluster_config) if args.commands: make_commands_lis(clstr, args.resolution) if args.eff_times_fits: eff_times_to_fits(clstr) elif args.temperature_map: print("Creating temperature map.") make_temperature_map(clstr, args.resolution) elif args.pressure: make_pressure_map(clstr) elif args.entropy: make_entropy_map(clstr) elif args.shock: import shockfinder if io.check_yes_no("This is likely not going to work. Continue?"): shockfinder.find_shock_in(clstr) else: fitting_preparation(clstr, args) else: parser.print_help() # a115 = cluster.load_cluster('A115') # fast_acb_creation_parallel(a115) #fast_acb_creation_serial(a115)
bcaldenREPO_NAMEClusterPyXTPATH_START.@ClusterPyXT_extracted@ClusterPyXT-master@acb.py@.PATH_END.py
{ "filename": "plot.py", "repo_name": "ConorMacBride/mcalf", "repo_path": "mcalf_extracted/mcalf-main/src/mcalf/utils/plot.py", "type": "Python" }
import astropy.units import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from packaging import version __all__ = ['hide_existing_labels', 'calculate_axis_extent', 'calculate_extent', 'class_cmap'] def _get_mpl_cmap(name): if version.parse(mpl.__version__) >= version.parse("3.5"): return mpl.colormaps[name] else: return mpl.cm.get_cmap(name) def hide_existing_labels(plot_settings, axes=None, fig=None): """Hides labels for each dictionary provided if label already exists in legend. Parameters ---------- plot_settings : dict of {str: dict} Dictionary of lines to be plotted. Values must be dictionaries with a 'label' entry that this function my append with a '_' to hide the label. axes : list of matplotlib.axes.Axes, optional, default=None List of axes to extract lines labels from. Extracts axes from `fig` if omitted. fig : matplotlib.figure.Figure, optional, default=None Figure to take line labels from. Uses current figure if omitted. Notes ----- Only the ``plot_settings[*]['label']`` values are uses to assess if a label has already been used. Other `plot_settings` parameters such as `color` are ignored. Examples -------- Import plotting package: >>> import matplotlib.pyplot as plt Define various plot settings: >>> plot_settings = { ... 'LineA': {'color': 'r', 'label': 'A'}, ... 'LineB': {'color': 'g', 'label': 'B'}, ... 'LineC': {'color': 'b', 'label': 'C'}, ... } Create a figure and plot two lines on the first axes: >>> fig, axes = plt.subplots(1, 2) >>> axes[0].plot([0, 1], [0, 1], **plot_settings['LineA']) # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at 0x...>] >>> axes[0].plot([0, 1], [1, 0], **plot_settings['LineB']) # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at 0x...>] Set labels already used to be hidden if used again: >>> hide_existing_labels(plot_settings) Anything already used will have an underscore prepended: >>> [x['label'] for x in plot_settings.values()] ['_A', '_B', 'C'] Plot two lines on the second axes: >>> axes[1].plot([0, 1], [0, 1], **plot_settings['LineB']) # Label hidden # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at 0x...>] >>> axes[1].plot([0, 1], [1, 0], **plot_settings['LineC']) # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at 0x...>] Show the figure with the legend: >>> fig.legend(ncol=3, loc='upper center') # doctest: +ELLIPSIS <matplotlib.legend.Legend object at 0x...> >>> plt.show() # doctest: +SKIP >>> plt.close() """ # Get axes: if axes is None: if fig is None: fig = plt.gcf() axes = fig.get_axes() # Get plotted labels: lines = [] for ax in axes: lines.extend(ax.get_lines()) existing = [line.get_label() for line in lines] # Hide labels already plotted: for name in plot_settings: if plot_settings[name]['label'] in existing: plot_settings[name]['label'] = '_' + plot_settings[name]['label'] def calculate_axis_extent(resolution, px, offset=0, unit="Mm"): """Calculate the extent from a resolution value along a particular axis. Parameters ---------- resolution : float or astropy.units.quantity.Quantity Length of each pixel. Unit defaults to `unit` is not an astropy quantity. px : int Number of pixels extent is being calculated for. offset : int or float, default=0 Number of pixels from the 0 pixel to the first pixel. Defaults to the first pixel being at 0 length units. For example, in a 1000 pixel wide dataset, setting offset to -500 would place the 0 Mm location at the centre. unit : str, default="Mm" Default unit string to use if `resolution` is not an astropy quantity. Returns ------- first : float First extent value. last : float Last extent value. unit : str Unit of extent values. """ # Ensure a valid spatial and pixel resolution is provided if not isinstance(resolution, (float, astropy.units.quantity.Quantity)): raise TypeError('`resolution` values must be either floats or astropy quantities' f', got {type(resolution)}.') if not isinstance(px, (int, np.integer)): raise TypeError(f'`px` must be an integer, got {type(px)}.') if not isinstance(offset, (float, int, np.integer)): raise TypeError(f'`offset` must be an float or integer, got {type(offset)}.') # Update the default unit if a quantity is provided if isinstance(resolution, astropy.units.quantity.Quantity): unit = resolution.unit.to_string(astropy.units.format.LatexInline) resolution = float(resolution.value) # Remove the unit # Calculate the extent values first = offset * resolution last = (px + offset) * resolution return first, last, unit def calculate_extent(shape, resolution, offset=(0, 0), ax=None, dimension=None, **kwargs): """Calculate the extent from a particular data shape and resolution. This function assumes a lower origin is being used with matplotlib. Parameters ---------- shape : tuple[int] Shape (y, x) of the :class:`numpy.ndarray` of the data being plotted. First integer corresponds to the y-axis and the second integer is for the x-axis. resolution : tuple[float] or astropy.units.quantity.Quantity A 2-tuple (x, y) containing the length of each pixel in the x and y direction respectively. If a value has type :class:`astropy.units.quantity.Quantity`, its axis label will include its attached unit, otherwise the unit will default to Mm. The `ax` parameter must be specified to set its labels. If `resolution` is None, this function will immediately return None. offset : tuple[float] or int, length=2, optional, default=(0, 0) Two offset values (x, y) for the x and y axis respectively. Number of pixels from the 0 pixel to the first pixel. Defaults to the first pixel being at 0 length units. For example, in a 1000 pixel wide dataset, setting offset to -500 would place the 0 Mm location at the centre. ax : matplotlib.axes.Axes, optional, default=None Axes into which axis labels will be plotted. Defaults to not printing axis labels. dimension : str or tuple[str] or list[str], length=2, optional, default=None If an `ax` (and `resolution`) is provided, use this string as the `dimension name` that appears before the ``(unit)`` in the axis label. A 2-tuple (x, y) or list [x, y] can instead be given to provide a different name for the x-axis and y-axis respectively. Defaults is equivalent to ``dimension=('x-axis', 'y-axis')``. **kwargs Extra keyword arguments to pass to :func:`calculate_axis_extent`. Returns ------- extent : tuple[float], length=4 The extent value that will be passed to matplotlib functions with a lower origin. Will return None if `resolution` is None. """ # Calculate a specific extent if a resolution is specified if resolution is not None: # Validate relevant parameters for n, v in (('shape', shape), ('resolution', resolution), ('offset', offset)): if not isinstance(v, tuple) or len(v) != 2: raise TypeError(f'`{n}` must be a tuple of length 2.') # Calculate extent values, and extract units ypx, xpx = shape l, r, x_unit = calculate_axis_extent(resolution[0], xpx, offset=offset[0], **kwargs) b, t, y_unit = calculate_axis_extent(resolution[1], ypx, offset=offset[1], **kwargs) # Optionally set the axis labels if ax is not None: # Extract the dimension name if isinstance(dimension, (tuple, list)): # different value for each dimension if len(dimension) != 2: raise TypeError('`dimension` must be a tuple or list of length 2.') x_dim = str(dimension[0]) y_dim = str(dimension[1]) elif dimension is None: # default values x_dim, y_dim = 'x-axis', 'y-axis' elif isinstance(dimension, str): # single value for both dimensions x_dim = y_dim = str(dimension) else: raise TypeError('`dimension` must be a tuple or list of length 2.') ax.set_xlabel(f'{x_dim} ({x_unit})') ax.set_ylabel(f'{y_dim} ({y_unit})') return l, r, b, t # extent return None # default extent def class_cmap(style, n): """Create a listed colormap for a specific number of classifications. Parameters ---------- style : str The named matplotlib colormap to extract a :class:`~matplotlib.colors.ListedColormap` from. Colours are selected from `vmin` to `vmax` at equidistant values in the range [0, 1]. The :class:`~matplotlib.colors.ListedColormap` produced will also show bad classifications and classifications out of range in grey. The 'original' style is a special case used since early versions of this code. It is a hardcoded list of 5 colours. When the number of classifications exceeds 5, ``style='viridis'`` will be used. n : int Number of colours (i.e., number of classifications) to include in the colormap. Returns ------- cmap : matplotlib.colors.ListedColormap Colormap generated for classifications. """ # Validate `n` if not isinstance(n, (int, np.integer)): raise TypeError(f'`n` must be an integer, got {type(n)}.') # Choose colours if style == 'original' and n <= 5: # original colours cmap_colors = np.array(['#0072b2', '#56b4e9', '#009e73', '#e69f00', '#d55e00'])[:n] else: if style == 'original': style = 'viridis' # fallback for >5 classifications c = _get_mpl_cmap(style) # query in equal intervals from [0, 1] cmap_colors = np.array([c(i / (n - 1)) for i in range(n)]) # Generate colormap cmap = mpl.colors.ListedColormap(cmap_colors) cmap.set_over(color='#999999', alpha=1) cmap.set_under(color='#999999', alpha=1) return cmap
ConorMacBrideREPO_NAMEmcalfPATH_START.@mcalf_extracted@mcalf-main@src@mcalf@utils@plot.py@.PATH_END.py
{ "filename": "_opacity.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/barpolar/_opacity.py", "type": "Python" }
import _plotly_utils.basevalidators class OpacityValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="opacity", parent_name="barpolar", **kwargs): super(OpacityValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), max=kwargs.pop("max", 1), min=kwargs.pop("min", 0), role=kwargs.pop("role", "style"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@barpolar@_opacity.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "waynebhayes/SpArcFiRe", "repo_path": "SpArcFiRe_extracted/SpArcFiRe-master/scripts/SpArcFiRe-pyvenv/lib/python2.7/site-packages/astropy/vo/validator/__init__.py", "type": "Python" }
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os from ... import config as _config from ...utils.data import get_pkg_data_contents # NOTE: This is deprecated along with other Cone Search stuff, but it feels # weird for config item to be issuing deprecation warnings. class Conf(_config.ConfigNamespace): """ Configuration parameters for `astropy.vo.validator`. """ conesearch_master_list = _config.ConfigItem( 'http://vao.stsci.edu/directory/NVORegInt.asmx/VOTCapabilityPredOpt?' 'predicate=1%3D1&capability=conesearch&VOTStyleOption=2', 'URL to the cone search services master list for validation.', aliases=['astropy.vo.validator.validate.cs_mstr_list'] ) conesearch_urls = _config.ConfigItem( get_pkg_data_contents( os.path.join('data', 'conesearch_urls.txt')).split(), 'A list of conesearch URLs to validate.', 'list', aliases=['astropy.vo.validator.validate.cs_urls']) noncritical_warnings = _config.ConfigItem( ['W03', 'W06', 'W07', 'W09', 'W10', 'W15', 'W17', 'W20', 'W21', 'W22', 'W27', 'W28', 'W29', 'W41', 'W42', 'W48', 'W50'], 'A list of `astropy.io.votable` warning codes that are considered ' 'non-critical.', 'list', aliases=['astropy.vo.validator.validate.noncrit_warnings']) conf = Conf()
waynebhayesREPO_NAMESpArcFiRePATH_START.@SpArcFiRe_extracted@SpArcFiRe-master@scripts@SpArcFiRe-pyvenv@lib@python2.7@site-packages@astropy@vo@validator@__init__.py@.PATH_END.py
{ "filename": "base_pipeline.py", "repo_name": "MichelleLochner/astronomaly", "repo_path": "astronomaly_extracted/astronomaly-main/astronomaly/base/base_pipeline.py", "type": "Python" }
from astronomaly.base import logging_tools from os import path import pandas as pd import numpy as np from pandas.util import hash_pandas_object import time class PipelineStage(object): def __init__(self, *args, **kwargs): """ Base class defining functionality for all pipeline stages. To contribute a new pipeline stage to Astronomaly, create a new class and inherit PipelineStage. Always start by calling "super().__init__()" and pass it all the arguments of the init function in your new class. The only other function that needs to be changed is `_execute_function` which should actually implement pipeline stage functionality. The base class will take care of automatic logging, deciding whether or not a function has already been run on this data, saving and loading of files and error checking of inputs and outputs. Parameters ---------- force_rerun : bool If True will force the function to run over all data, even if it has been called before. save_output : bool If False will not save and load any files. Only use this if functions are very fast to rerun or if you cannot write to disk. output_dir : string Output directory where all outputs will be stored. Defaults to current working directory. file_format : string Format to save the output of this pipeline stage to. Accepted values are: parquet drop_nans : bool If true, will drop any NaNs from the input before passing it to the function """ # This will be the name of the child class, not the parent. self.class_name = type(locals()['self']).__name__ self.function_call_signature = \ logging_tools.format_function_call(self.class_name, *args, **kwargs) # Disables the automatic saving of intermediate outputs if 'save_output' in kwargs and kwargs['save_output'] is False: self.save_output = False else: self.save_output = True # Handles automatic file reading and writing if 'output_dir' in kwargs: self.output_dir = kwargs['output_dir'] else: self.output_dir = './' if 'drop_nans' in kwargs and kwargs['drop_nans'] is False: self.drop_nans = False else: self.drop_nans = True # This allows the automatic logging every time this class is # instantiated (i.e. every time this pipeline stage # is run). That means any class that inherits from this base class # will have automated logging. logging_tools.setup_logger(log_directory=self.output_dir, log_filename='astronomaly.log') if 'force_rerun' in kwargs and kwargs['force_rerun']: self.args_same = False self.checksum = '' else: self.args_same, self.checksum = \ logging_tools.check_if_inputs_same(self.class_name, locals()['kwargs']) if 'file_format' in kwargs: self.file_format = kwargs['file_format'] else: self.file_format = 'parquet' self.output_file = path.join(self.output_dir, self.class_name + '_output') if self.file_format == 'parquet': if '.parquet' not in self.output_file: self.output_file += '.parquet' if path.exists(self.output_file) and self.args_same: self.previous_output = self.load(self.output_file) else: self.previous_output = pd.DataFrame(data=[]) self.labels = [] def save(self, output, filename, file_format=''): """ Saves the output of this pipeline stage. Parameters ---------- output : pd.DataFrame Whatever the output is of this stage. filename : str File name of the output file. file_format : str, optional File format can be provided to override the class's file format """ if len(file_format) == 0: file_format = self.file_format if self.save_output: # Parquet needs strings as column names # (which is good practice anyway) output.columns = output.columns.astype('str') if file_format == 'parquet': if '.parquet' not in filename: filename += '.parquet' output.to_parquet(filename) elif file_format == 'csv': if '.csv' not in filename: filename += '.csv' output.to_csv(filename) def load(self, filename, file_format=''): """ Loads previous output of this pipeline stage. Parameters ---------- filename : str File name of the output file. file_format : str, optional File format can be provided to override the class's file format Returns ------- output : pd.DataFrame Whatever the output is of this stage. """ if len(file_format) == 0: file_format = self.file_format if file_format == 'parquet': if '.parquet' not in filename: filename += '.parquet' output = pd.read_parquet(filename) elif file_format == 'csv': if '.csv' not in filename: filename += '.csv' output = pd.read_csv(filename) return output def hash_data(self, data): """ Returns a checksum on the first few rows of a DataFrame to allow checking if the input changed. Parameters ---------- data : pd.DataFrame or similar The input data on which to compute the checksum Returns ------- checksum : str The checksum """ try: hash_per_row = hash_pandas_object(data) total_hash = hash_pandas_object(pd.DataFrame( [hash_per_row.values])) except TypeError: # Input data is not already a pandas dataframe # Most likely it's an image (np.array) # In order to hash, it has to be converted to a DataFrame so must # be a 2d array try: if len(data.shape) > 2: data = data.ravel() total_hash = hash_pandas_object(pd.DataFrame(data)) except (AttributeError, ValueError) as e: # I'm not sure this could ever happen but just in case logging_tools.log("""Data must be either a pandas dataframe or numpy array""", level='ERROR') raise e return int(total_hash.values[0]) def run(self, data): """ This is the external-facing function that should always be called (rather than _execute_function). This function will automatically check if this stage has already been run with the same arguments and on the same data. This can allow a much faster user experience avoiding rerunning functions unnecessarily. Warning - all columns in data not 'human_label' or 'score' are assumed to be features. Parameters ---------- data : pd.DataFrame Input data on which to run this pipeline stage on. Returns ------- pd.DataFrame Output """ new_checksum = self.hash_data(data) if self.args_same and new_checksum == self.checksum: # This means we've already run this function for all instances in # the input and with the same arguments msg = "Pipeline stage %s previously called " \ "with same arguments and same data. Loading from file. " \ "Use 'force_rerun=True' in init args to override this " \ "behavior." % self.class_name logging_tools.log(msg, level='WARNING') return self.previous_output else: msg_string = self.function_call_signature + ' - checksum: ' + \ (str)(new_checksum) # print(msg_string) logging_tools.log(msg_string) print('Running', self.class_name, '...') t1 = time.time() if self.drop_nans: # This is ok here because everything after feature extraction # is always a DataFrame output = self._execute_function(data.dropna()) else: output = self._execute_function(data) self.save(output, self.output_file) print('Done! Time taken:', (time.time() - t1), 's') return output def run_on_dataset(self, dataset=None): """ This function should be called for pipeline stages that perform feature extraction so require taking a Dataset object as input. This is an external-facing function that should always be called (rather than _execute_function). This function will automatically check if this stage has already been run with the same arguments and on the same data. This can allow a much faster user experience avoiding rerunning functions unnecessarily. Parameters ---------- dataset : Dataset The Dataset object on which to run this feature extraction function, by default None Returns ------- pd.Dataframe Output """ # *** WARNING: this has not been tested against adding new data and # *** ensuring the function is called for new data only dat = dataset.get_sample(dataset.index[0]) new_checksum = self.hash_data(dat) if not self.args_same or new_checksum != self.checksum: # If the arguments have changed we rerun everything msg_string = self.function_call_signature + ' - checksum: ' + \ (str)(new_checksum) logging_tools.log(msg_string) else: # Otherwise we only run instances not already in the output msg = "Pipeline stage %s previously called " \ "with same arguments. Loading from file. Will only run " \ "for new samples. Use 'force_rerun=True' in init args " \ "to override this behavior." % self.class_name logging_tools.log(msg, level='WARNING') print('Extracting features using', self.class_name, '...') t1 = time.time() logged_nan_msg = False nan_msg = "NaNs detected in some input data." \ "NaNs will be set to zero. You can change " \ "behaviour by setting drop_nan=False" new_index = [] output = [] n = 0 for i in dataset.index: if i not in self.previous_output.index or not self.args_same: if n % 100 == 0: print(n, 'instances completed') input_instance = dataset.get_sample(i) # Drop any object that's all zeros or all NaNs since it # contains no data try: all_same = np.all(input_instance == input_instance[0]) all_nan = np.all(np.isnan(input_instance)) except KeyError: # This is a dataframe not an array all_same = np.all(input_instance == input_instance.iloc[0]) all_nan = np.all(pd.isna(input_instance)) if all_same or all_nan: input_instance = None if input_instance is None: none_msg = "Input sample is None, skipping sample" logging_tools.log(none_msg, level='WARNING') continue if self.drop_nans: found_nans = False try: if np.any(np.isnan(input_instance)): input_instance = np.nan_to_num(input_instance) found_nans = True except TypeError: # So far I've only found this happens when there are # strings in a DataFrame for col in input_instance.columns: try: if np.any(np.isnan(input_instance[col])): input_instance[col] = \ np.nan_to_num(input_instance[col]) found_nans = True except TypeError: # Probably just a column of strings pass if not logged_nan_msg and found_nans: print(nan_msg) logging_tools.log(nan_msg, level='WARNING') logged_nan_msg = True out = self._execute_function(input_instance) if np.any(np.isnan(out)): logging_tools.log("Feature extraction failed for id " + i) output.append(out) new_index.append(i) n += 1 new_output = pd.DataFrame(data=output, index=new_index, columns=self.labels) index_same = new_output.index.equals(self.previous_output.index) if self.args_same and not index_same: output = pd.concat((self.previous_output, new_output)) else: output = new_output if self.save_output: self.save(output, self.output_file) print('Done! Time taken: ', (time.time() - t1), 's') return output def _execute_function(self, data): """ This is the main function of the PipelineStage and is what should be implemented when inheriting from this class. Parameters ---------- data : Dataset object, pd.DataFrame Data type depends on whether this is feature extraction stage (so runs on a Dataset) or any other stage (e.g. anomaly detection) Raises ------ NotImplementedError This function must be implemented when inheriting this class. """ raise NotImplementedError
MichelleLochnerREPO_NAMEastronomalyPATH_START.@astronomaly_extracted@astronomaly-main@astronomaly@base@base_pipeline.py@.PATH_END.py
{ "filename": "test_simulation.py", "repo_name": "dmentipl/plonk", "repo_path": "plonk_extracted/plonk-main/tests/test_simulation.py", "type": "Python" }
"""Testing Simulation.""" from pathlib import Path import numpy as np import pytest import plonk DIR_PATH = Path(__file__).parent / 'data/phantom' PREFIX = 'dustseparate' TS_FILENAME = 'dustseparate01.ev' def test_init_simulation(): """Testing initialising simulation.""" plonk.load_simulation(prefix=PREFIX, directory=DIR_PATH) with pytest.raises(ValueError): plonk.load_simulation( prefix=PREFIX, directory=DIR_PATH, data_source='not_available' ) with pytest.raises(FileNotFoundError): plonk.load_simulation(prefix='does_not_exist', directory=DIR_PATH) def test_sim_data(): """Testing data in simulation.""" sim = plonk.load_simulation(prefix=PREFIX, directory=DIR_PATH) snaps = sim.snaps assert len(snaps) == 1 assert len(snaps[0]) == 2000 properties = { 'adiabatic_index': 1.0, 'dust_method': 'dust as separate sets of particles', 'equation_of_state': 'locally isothermal disc', 'grain_density': [3000.0] * plonk.units('kg/m^3'), 'grain_size': [0.01] * plonk.units('m'), 'smoothing_length_factor': 1.0, 'time': [0.0] * plonk.units('s'), } for key, val in sim.properties.items(): if isinstance(val, plonk._units.Quantity): assert np.allclose(val.m, properties[key].m) else: assert sim.properties[key] == properties[key] assert sim.paths['time_series_global'][0].name == TS_FILENAME def test_simulation_visualization(): """Test simulation visualization.""" sim = plonk.load_simulation(prefix=PREFIX, directory=DIR_PATH) viz = sim.visualize(kind='particle', x='x', y='y') viz.next() viz.prev() def test_to_array(): """Testing to_array method.""" sim = plonk.load_simulation(prefix=PREFIX, directory=DIR_PATH) sim.to_array(quantity='density', indices=[0, 1, 2]) def test_set_units_time_series(): """Test set/unset units time series.""" sim = plonk.load_simulation(prefix=PREFIX, directory=DIR_PATH) sim.unset_units_on_time_series() sim.set_units_on_time_series()
dmentiplREPO_NAMEplonkPATH_START.@plonk_extracted@plonk-main@tests@test_simulation.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/histogram/insidetextfont/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._weight import WeightValidator from ._variant import VariantValidator from ._textcase import TextcaseValidator from ._style import StyleValidator from ._size import SizeValidator from ._shadow import ShadowValidator from ._lineposition import LinepositionValidator from ._family import FamilyValidator from ._color import ColorValidator else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name__, [], [ "._weight.WeightValidator", "._variant.VariantValidator", "._textcase.TextcaseValidator", "._style.StyleValidator", "._size.SizeValidator", "._shadow.ShadowValidator", "._lineposition.LinepositionValidator", "._family.FamilyValidator", "._color.ColorValidator", ], )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@histogram@insidetextfont@__init__.py@.PATH_END.py
{ "filename": "flatiter.py", "repo_name": "numpy/numpy", "repo_path": "numpy_extracted/numpy-main/numpy/typing/tests/data/pass/flatiter.py", "type": "Python" }
import numpy as np a = np.empty((2, 2)).flat a.base a.copy() a.coords a.index iter(a) next(a) a[0] a[[0, 1, 2]] a[...] a[:] a.__array__() a.__array__(np.dtype(np.float64))
numpyREPO_NAMEnumpyPATH_START.@numpy_extracted@numpy-main@numpy@typing@tests@data@pass@flatiter.py@.PATH_END.py
{ "filename": "cde_loss.py", "repo_name": "lee-group-cmu/cdetools", "repo_path": "cdetools_extracted/cdetools-master/python/src/cdetools/cde_loss.py", "type": "Python" }
import numpy as np from scipy.spatial import KDTree def cde_loss(cde_estimates, z_grid, z_test): """ Calculates conditional density estimation loss on holdout data @param cde_estimates: a numpy array where each row is a density estimate on z_grid @param z_grid: a numpy array of the grid points at which cde_estimates is evaluated @param z_test: a numpy array of the true z values corresponding to the rows of cde_estimates @returns The CDE loss (up to a constant) for the CDE estimator on the holdout data and the SE error """ if len(z_test.shape) == 1: z_test = z_test.reshape(-1, 1) if len(z_grid.shape) == 1: z_grid = z_grid.reshape(-1, 1) n_obs, n_grid = cde_estimates.shape n_samples, feats_samples = z_test.shape n_grid_points, feats_grid = z_grid.shape if n_obs != n_samples: raise ValueError("Number of samples in CDEs should be the same as in z_test." "Currently %s and %s." % (n_obs, n_samples)) if n_grid != n_grid_points: raise ValueError("Number of grid points in CDEs should be the same as in z_grid." "Currently %s and %s." % (n_grid, n_grid_points)) if feats_samples != feats_grid: raise ValueError("Dimensionality of test points and grid points need to coincise." "Currently %s and %s." % (feats_samples, feats_grid)) z_min = np.min(z_grid, axis=0) z_max = np.max(z_grid, axis=0) z_delta = (z_max - z_min)/(n_grid_points-1) integrals = z_delta * np.sum(cde_estimates**2, axis=1) kdtree = KDTree(z_grid) nn_ids = np.array( [kdtree.query(z_test[ii, :])[1] for ii in range(n_samples)]).reshape(-1,) likeli = cde_estimates[(tuple(np.arange(n_samples)), tuple(nn_ids))] losses = integrals - 2 * likeli loss = np.mean(losses) se_error = np.std(losses, axis=0) / (n_obs ** 0.5) return loss, se_error
lee-group-cmuREPO_NAMEcdetoolsPATH_START.@cdetools_extracted@cdetools-master@python@src@cdetools@cde_loss.py@.PATH_END.py
{ "filename": "test_jplspec_remote.py", "repo_name": "astropy/astroquery", "repo_path": "astroquery_extracted/astroquery-main/astroquery/jplspec/tests/test_jplspec_remote.py", "type": "Python" }
import pytest from astropy import units as u from astropy.table import Table from ...jplspec import JPLSpec @pytest.mark.remote_data def test_remote(): tbl = JPLSpec.query_lines(min_frequency=500 * u.GHz, max_frequency=1000 * u.GHz, min_strength=-500, molecule="18003 H2O") assert isinstance(tbl, Table) assert len(tbl) == 36 assert set(tbl.keys()) == set(['FREQ', 'ERR', 'LGINT', 'DR', 'ELO', 'GUP', 'TAG', 'QNFMT', 'QN\'', 'QN"']) assert tbl['FREQ'][0] == 503568.5200 assert tbl['ERR'][0] == 0.0200 assert tbl['LGINT'][0] == -4.9916 assert tbl['ERR'][7] == 12.4193 assert tbl['FREQ'][35] == 987926.7590 @pytest.mark.remote_data def test_remote_regex(): tbl = JPLSpec.query_lines(min_frequency=500 * u.GHz, max_frequency=1000 * u.GHz, min_strength=-500, molecule=("28001", "28002", "28003")) assert isinstance(tbl, Table) assert len(tbl) == 16 assert set(tbl.keys()) == set(['FREQ', 'ERR', 'LGINT', 'DR', 'ELO', 'GUP', 'TAG', 'QNFMT', 'QN\'', 'QN"']) assert tbl['FREQ'][0] == 576267.9305 assert tbl['ERR'][0] == .0005 assert tbl['LGINT'][0] == -3.0118 assert tbl['ERR'][7] == 8.3063 assert tbl['FREQ'][15] == 946175.3151
astropyREPO_NAMEastroqueryPATH_START.@astroquery_extracted@astroquery-main@astroquery@jplspec@tests@test_jplspec_remote.py@.PATH_END.py
{ "filename": "_tickvals.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/layout/coloraxis/colorbar/_tickvals.py", "type": "Python" }
import _plotly_utils.basevalidators class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__( self, plotly_name="tickvals", parent_name="layout.coloraxis.colorbar", **kwargs ): super(TickvalsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), role=kwargs.pop("role", "data"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@layout@coloraxis@colorbar@_tickvals.py@.PATH_END.py
{ "filename": "calc_k_coeffs.py", "repo_name": "ideasrule/platon", "repo_path": "platon_extracted/platon-master/misc/calc_k_coeffs.py", "type": "Python" }
import scipy.special import numpy as np import sys import matplotlib.pyplot as plt def get_k_coeffs(absorb_coeffs, binsize=200, n_gauss=10): points, weights = scipy.special.roots_legendre(n_gauss) percentiles = 100 * (points + 1) / 2 k_coeffs = [] for i in range(absorb_coeffs.shape[2] // binsize): vals = absorb_coeffs[:,:,i*binsize : (i+1)*binsize] k_coeffs.append(np.percentile(vals, percentiles, axis=2)) k_coeffs = np.array(k_coeffs) k_coeffs = k_coeffs.reshape((k_coeffs.shape[0] * k_coeffs.shape[1], k_coeffs.shape[2], k_coeffs.shape[3])) k_coeffs = k_coeffs.transpose((1,2,0)) return k_coeffs print(k_coeffs.shape) plt.loglog(k_coeffs[20,7]) plt.show() wavelengths = 1e-6 * np.exp(np.arange(np.log(0.2), np.log(30), 1./20000)) k_wavelengths = np.repeat(wavelengths[::200][:-1], 10) for filename in sys.argv[1:]: output_filename = filename.replace("absorb_coeffs_", "k_coeffs_") absorb_coeffs = np.load(filename) k_coeffs = get_k_coeffs(absorb_coeffs) np.save("k_wavelengths.npy", k_wavelengths) np.save(output_filename, k_coeffs)
ideasruleREPO_NAMEplatonPATH_START.@platon_extracted@platon-master@misc@calc_k_coeffs.py@.PATH_END.py
{ "filename": "_variant.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/image/hoverlabel/font/_variant.py", "type": "Python" }
import _plotly_utils.basevalidators class VariantValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="variant", parent_name="image.hoverlabel.font", **kwargs ): super(VariantValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), values=kwargs.pop( "values", [ "normal", "small-caps", "all-small-caps", "all-petite-caps", "petite-caps", "unicase", ], ), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@image@hoverlabel@font@_variant.py@.PATH_END.py
{ "filename": "evolution.py", "repo_name": "astropy/SPISEA", "repo_path": "SPISEA_extracted/SPISEA-main/spisea/evolution.py", "type": "Python" }
import math import logging from numpy import genfromtxt import numpy as np import os import glob import pdb import warnings from astropy.table import Table, vstack, Column from scipy import interpolate import pylab as py from spisea.utils import objects from spisea import exceptions logger = logging.getLogger('evolution') # Fetch root directory of evolution models. try: models_dir = os.environ['SPISEA_MODELS'] models_dir += '/evolution/' except KeyError: warnings.warn("SPISEA_MODELS is undefined; functionality " "will be SEVERELY crippled.") models_dir = '' # Function to get installed evo grid number def get_installed_grid_num(input_models_dir): """ Get installed grid number """ # Define the installed model grid number file_name = input_models_dir + '/grid_version.txt' # Read in the file. In the case where it doesn't # exist, then grid version is assumed to be 1.0 # (since this didn't always exist) try: file1 = open(file_name, 'r') read = file1.readlines() evo_grid_num = float(read[1]) file1.close() except FileNotFoundError: evo_grid_num = 1.0 return evo_grid_num # Function to check evo grid version number def check_evo_grid_number(required_num, input_models_dir): """ Check if installed grid meets the required grid version number. Installed grid number must be greater than or equal to this number """ # Get installed gridnumber grid_num = get_installed_grid_num(input_models_dir) # Check: is installed grid number < required_num? # If not, raise mismatch error if grid_num < required_num: raise exceptions.ModelMismatch(required_num, grid_num, 'evolution') return grid_num class StellarEvolution(object): """ Base Stellar evolution class. Parameters ---------- model_dir: path Directory path to evolution model files age_list: list List of ages mass_list: list List of masses z_list: list List of metallicities """ def __init__(self, model_dir, age_list, mass_list, z_list): self.model_dir = model_dir self.z_list = z_list self.mass_list = mass_list self.age_list = age_list return class Geneva(StellarEvolution): def __init__(self): r""" Define intrinsic properties for Geneva stellar models. """ # populate list of model masses (in solar masses) mass_list = [(0.1 + i*0.005) for i in range(181)] # define metallicity parameters for Geneva models z_list = [0.01, 0.02, 0.03] # populate list of isochrone ages (log scale) age_list = [round(5.5 + 0.01*i, 2) for i in range(190)] age_list += [round(7.4 + 0.05*i, 2) for i in range(12)] age_list += [round(math.log10(1.e8*x), 2) for x in range(1, 10)] age_list += [round(math.log10(1.e9*x), 2) for x in range(1, 10)] age_list = age_list # specify location of model files model_dir = models_dir + 'geneva/' StellarEvolution.__init__(self, model_dir, age_list, mass_list, z_list) self.z_solar = 0.02 self.z_file_map = {0.01: 'z01/', 0.02: 'z02/', 0.03: 'z03/'} # Define required evo_grid number self.evo_grid_min = 1.0 def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Geneva collection. """ # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # convert age (in yrs) to log scale and find nearest value in grid log_age = np.log10(age) age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_' + str(self.age_list[age_idx]) + '.fits' # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + 'iso/' + z_dir + iso_file # return isochrone data return genfromtxt(full_iso_file, comments='#') #---------------------------------------# # Now for the Ekstrom+12 Geneva models #---------------------------------------# class Ekstrom12(StellarEvolution): """ Evolution models from `Ekstrom et al. 2012 <https://ui.adsabs.harvard.edu/abs/2012A%26A...537A.146E/abstract>`_. Downloaded from `website <http://obswww.unige.ch/Recherche/evoldb/index/Isochrone/>`_. Parameters ---------- rot: boolean, optional If true, then use rotating Ekstrom models. Default is true. """ def __init__(self, rot=True): # define metallicity parameters for Ekstrom+12 models self.z_list = [0.014] # populate list of isochrone ages (log scale) self.age_list = np.arange(6.0, 8.0+0.005, 0.01) # Specify location of model files self.model_dir = models_dir+'Ekstrom2012/' # Specifying metallicity self.z_solar = 0.014 self.z_file_map = {0.014: 'z014/'} # Specify rotation or not self.rot = rot # Define required evo_grid number self.evo_grid_min = 1.0 def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Ekstrom+12 Geneva collection. """ # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string if self.rot: full_iso_file = self.model_dir + 'iso/' + z_dir + 'rot/' + iso_file else: full_iso_file = self.model_dir + 'iso/' + z_dir + 'norot/' + iso_file # Return isochrone data iso = Table.read(full_iso_file, format='fits') iso.rename_column('col4', 'Z') iso.rename_column('col1', 'logAge') iso.rename_column('col3', 'mass') iso.rename_column('col6', 'mass_current') iso.rename_column('col7', 'logL') iso.rename_column('col8', 'logT') iso.rename_column('col22', 'logg') iso.rename_column('col9', 'logT_WR') # Add isWR column isWR = Column([False] * len(iso), name='isWR') idx_WR = np.where(iso['logT'] != iso['logT_WR']) isWR[idx_WR] = True iso.add_column(isWR) # Add a phase column... everything is just a star. iso.add_column( Column(np.ones(len(iso)), name = 'phase')) iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso def format_isochrones(input_iso_dir): r""" Parse iso.fits (filename hardcoded) file downloaded from Ekstrom+12 models, create individual isochrone files for the different ages. input_iso_directory should lead to Ekstrom2012/iso/<metallicity> directory, where iso.fits file should be located. Creates two new directories, rot and norot, which contain their respective isochrones. """ # Store current directory for later start_dir = os.getcwd() # Move into metallicity direcotry, read iso.fits file os.chdir(input_iso_dir) print( 'Read Input: this is slow') iso = Table.read('iso.fits') print( 'Done' ) ages_all = iso['col1'] # Extract the unique ages age_arr = np.unique(ages_all) # For each unique age, extract the proper rows and make corresponding # table. Be sure to separate rotating from non-rotating, and put in # separate subdirectories # First make the rot and norot directories, if they don't exit if os.path.exists('rot'): pass else: os.mkdir('rot') os.mkdir('norot') print( 'Making individual isochrone files') for age in age_arr: good = np.where(ages_all == age) # Identify rot vs. non-rot idx_r = np.where(iso[good]['col2'] == 'r') idx_n = np.where(iso[good]['col2'] == 'n') tmp_r = iso[good][idx_r] tmp_n = iso[good][idx_n] # Write tables tmp_r.write('rot/iso_{0:4.2f}.fits'.format(age)) tmp_n.write('norot/iso_{0:4.2f}.fits'.format(age)) # Return to starting directory os.chdir(start_dir) return def create_iso(fileList, ageList, rot=True): """ Given a set of isochrone files downloaded from the server, put in correct iso.fits format for parse_iso code. fileList: list of downloaded isochrone files (could be one) ageList: list of lists of ages associated with each file in filelist. MUST BE IN SAME ORDER AS ISOCHRONES IN FILE! Also needs to be in logAge rot = TRUE: assumes that models are rotating, will add appropriate column This code writes the individual files, which is then easiest to combine by hand in aquamacs """ # Read each file in fileList individually, add necessary columns for i in range(len(fileList)): t = Table.read(fileList[i],format='ascii') ages = ageList[i] # Find places where new models start; mass here is assumed to be 0.8 start = np.where(t['M_ini'] == 0.8) # Now, each identified start is assumed to be associated with the # corresponding age in ages if len(start[0]) != len(ages): print( 'Ages mismatched in file! Quitting...') return age_arr = np.zeros(len(t)) for j in range(len(start[0])): low_ind = start[0][j] # Deal with case at end of file if (j == len(start[0])-1): high_ind = len(t) else: high_ind = start[0][j+1] ind = np.arange(low_ind, high_ind, 1) age_arr[ind] = ages[j] # Add ages_arr column to column 1 in ischrone, as well as column # signifying rotation col_age = Column(age_arr, name = 'logAge') rot_val = np.chararray(len(t)) rot_val[:] = 'r' if not rot: rot_val[:] = 'n' col_rot = Column(rot_val, name='Rot') t.add_column(col_rot, index=0) t.add_column(col_age, index=0) t.write('tmp'+str(i)+'.fits') return #---------------------------------------# # Now for the Parsec version 1.2s models #---------------------------------------# class Parsec(StellarEvolution): """ Evolution models from `Bressan et al. 2012 <https://ui.adsabs.harvard.edu/abs/2012MNRAS.427..127B/abstract>`_, version 1.2s. Downloaded from `here <http://stev.oapd.inaf.it/cgi-bin/cmd>_` Notes ----- Evolution model parameters used in download: * n_Reimers parameter (mass loss on RGB) = 0.2 * photometric system: HST/WFC3 IR channel * bolometric corrections OBC from Girardi+08, based on ATLAS9 ODFNEW models * Carbon star bolometric corrections from Aringer+09 * no dust * no extinction * Chabrier+01 mass function """ def __init__(self): r""" Define intrinsic properties for the Parsec version 1.2s stellar models. """ # populate list of model masses (in solar masses) #mass_list = [(0.1 + i*0.005) for i in range(181)] # define metallicity parameters for Parsec models self.z_list = [0.005, 0.015, 0.04] # populate list of isochrone ages (log scale) self.age_list = np.arange(6.6, 10.12+0.005, 0.01) self.age_list = np.append(6.40, self.age_list) # Specify location of model files self.model_dir = models_dir+'ParsecV1.2s/' # Specifying metallicity self.z_solar = 0.015 self.z_file_map = {0.005: 'z005/', 0.015: 'z015/', 0.04: 'z04/'} # Define required evo_grid number self.evo_grid_min = 1.0 def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Parsec version 1.2s collection. """ # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + 'iso/' + z_dir + iso_file # return isochrone data iso = Table.read(full_iso_file, format='fits') iso.rename_column('col1', 'Z') iso.rename_column('col2', 'logAge') iso.rename_column('col3', 'mass') iso.rename_column('col4', 'mass_current') iso.rename_column('col5', 'logL') iso.rename_column('col6', 'logT') iso.rename_column('col7', 'logg') iso.rename_column('col15', 'phase') iso['logT_WR'] = iso['logT'] # Parsec doesn't identify WR stars, so identify all as "False" isWR = Column([False] * len(iso), name='isWR') iso.add_column(isWR) iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso def format_isochrones(input_iso_dir, metallicity_list): r""" Parse isochrone file downloaded from Parsec version 1.2 for different metallicities, create individual isochrone files for the different ages. input_iso_dir: points to ParsecV1.2s/iso directory. Assumes metallicity subdirectories already exist with isochrone files downloaded in them (isochrones files expected to start with "output*") metallicity_list format: absolute (vs. relative to solar), z + <digits after decimal>: e.g. Z = 0.014 --> z014 """ # Store current directory for later start_dir = os.getcwd() # Move into isochrone directory os.chdir(input_iso_dir) # Work on each metallicity isochrones individually for metal in metallicity_list: # More into metallicity directory, read isochrone file os.chdir(metal) isoFile = glob.glob('output*') print( 'Read Input: this is slow') iso = Table.read(isoFile[0], format='fits') print( 'Done') ages_all = iso['col2'] # Extract the unique ages age_arr = np.unique(ages_all) # For each unique age, extract the proper rows and make corresponding # table print( 'Making individual isochrone files') for age in age_arr: good = np.where(ages_all == age) tmp = iso[good] #Write table tmp.write('iso_{0:4.2f}.fits'.format(age)) # Move back into iso directory os.chdir('..') # Return to starting directory os.chdir(start_dir) return #---------------------------------------# # Now for the Pisa (Tognelli+11) models #---------------------------------------# class Pisa(StellarEvolution): """ Evolution models from `Tognelli et al. 2011 <https://ui.adsabs.harvard.edu/abs/2011A%26A...533A.109T/abstract>`_. Downloaded `online <http://astro.df.unipi.it/stellar-models/index.php?m=1>`_ Notes ------ Parameters used in download: * Y = middle value of 3 provided (changes for different metallicities) * mixing length = 1.68 * Deuterium fraction: 2*10^-5 for Z = 0.015, 0.03; 4*10^-4 for 0.005 """ def __init__(self): r""" Define intrinsic properties for the Pisa (Tognelli+11) stellar models. """ # define metallicity parameters for Pisa models self.z_list = [0.015] # populate list of isochrone ages (log scale) self.age_list = np.arange(6.0, 8.01+0.005, 0.01) # Specify location of model files self.model_dir = models_dir+'Pisa2011/' # Specifying metallicity self.z_solar = 0.015 self.z_file_map = {0.015: 'z015/'} # Define required evo_grid number self.evo_grid_min = 1.0 def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Pisa (Tognelli+11) collection. """ # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds for evolution model. Available z-vals: {1}.'.format(z_defined, self.z_list)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + 'iso/' + z_dir + iso_file # return isochrone data iso = Table.read(full_iso_file, format='fits') iso.rename_column('col1', 'logL') iso.rename_column('col2', 'logT') iso.rename_column('col3', 'mass') iso.rename_column('col4', 'logg') iso['logT_WR'] = iso['logT'] # Pisa models are too low for WR phase, add WR column with all False isWR = Column([False] * len(iso), name='isWR') iso.add_column(isWR) # Add columns for current mass and phase. iso.add_column( Column(np.zeros(len(iso)), name = 'phase')) iso.add_column( Column(iso['mass'], name = 'mass_current')) iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso def format_isochrones(input_iso_dir, metallicity_list): r""" Rename the isochrone files extracted from Pisa (Tognelli+11) to fit naming/directory scheme input_iso_dir: points to Pisa2011/iso directory. Individual metallicity directories with the downloaded isochrones are expected to already exist there metallicity_list is the list of metallicities on which function is to be run. format for metallicity_list : absolute (vs. relative to sun) 'z' + <digits after decimal>, e.g Z = 0.015 --> z015. """ # Store current directory for later start_dir = os.getcwd() # Move into isochrone directory os.chdir(input_iso_dir) # Work on each metallicity directory individually for metal in metallicity_list: # Move into directory, check to see if files are already formatted os.chdir(metal) if os.path.exists('iso_6.00.fits'): print( 'Files in {0:s} already formatted'.format(metal)) else: # Create a ReadMe with the original file names to preserve the # model details cmd = "ls *.FITS > ReadMe" os.system(cmd) # Collect all filenames in a list, rename files one # by one isoFile_list = glob.glob('*.FITS') for File in isoFile_list: name = File.split('_') # Extract iso age from filename age = float(name[1][1:]) logAge = np.log10(age * 10**6) cmd = "mv {0:s} iso_{1:4.2f}.fits".format(File, logAge) os.system(cmd) # Return to overhead directory os.chdir('..') # Return to starting directory os.chdir(start_dir) return def make_isochrone_grid(metallicity=0.015): """ Create isochrone grid of given metallicity with time sampling = 0.01 in logAge (hardcoded). This interpolates the downloaded isochrones when necessary. Builds upon the online iscohrone grid. Note: format of metallicity is important. After decimal point, must match the format of the metallcity directory (i.e., 0.015 matches directory z015, while 0.0150 would not) """ logAge_arr = np.arange(6.0, 8.0+0.005, 0.01) count = 0 for logAge in logAge_arr: # Could interpolate using evolutionary tracks, but less accurate. make_isochrone_pisa_interp(logAge, metallicity=metallicity) count += 1 print( 'Done {0} of {1} models'.format(count, (len(logAge_arr)))) return #==============================# # Baraffe+15 models #==============================# class Baraffe15(StellarEvolution): """ Evolution models published in `Baraffe et al. 2015 <https://ui.adsabs.harvard.edu/abs/2015A%26A...577A..42B/abstract>`_. Downloaded from `BHAC15 site <http://perso.ens-lyon.fr/isabelle.baraffe/BHAC15dir/BHAC15_tracks>`_. """ def __init__(self): # define metallicity parameters for Baraffe models self.z_list = [0.015] # populate list of isochrone ages (log scale) self.age_list = np.arange(6.0, 8.0+0.005, 0.01) # Specify location of model files self.model_dir = models_dir+'Baraffe15/' # Specifying metallicity self.z_solar = 0.015 self.z_file_map = {0.015: 'z015/'} # Define required evo_grid number self.evo_grid_min = 1.0 def isochrone(self, age=5.e7, metallicity=0.0): r""" Extract an individual isochrone from the Baraffe+15 collection. """ # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + 'iso/' + z_dir + iso_file # Read isochrone, get in proper format iso = Table.read(full_iso_file, format='fits') iso.rename_column('Mass', 'mass') iso.rename_column('logG', 'logg') iso['logT'] = np.log10(iso['Teff']) # Pisa models are too low for WR phase, add WR column with all False iso['logT_WR'] = iso['logT'] isWR = Column([False] * len(iso), name='isWR') iso.add_column(isWR) # Add columns for current mass and phase. iso.add_column( Column(np.zeros(len(iso)), name = 'phase')) iso.add_column( Column(iso['mass'], name = 'mass_current')) iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso def tracks_to_isochrones(self, tracksFile): r""" Create isochrones at desired age sampling (6.0 < logAge < 8.0, steps of 0.01; hardcoded) from the Baraffe+15 tracks downloaded online. tracksFile: tracks.dat file downloaded from Baraffe+15, with format modified to be read in python Writes isochrones in iso/ subdirectory off of work directory. Will create this subdirectory if it doesn't already exist """ tracks = Table.read(tracksFile, format='ascii') age_arr = np.arange(6.0, 8.0+0.005, 0.01) #age_arr = [6.28] # Loop through the masses, interpolating track over time at each. # Resample track properties at hardcoded ages masses = np.unique(tracks['col1']) mass_interp = [] age_interp = [] Teff_interp = [] logL_interp = [] logG_interp = [] print( 'Begin looping over masses') cnt=0 for mass in masses: idx = np.where(tracks['col1'] == mass) tmp = tracks[idx] # First, extract Teff, logL, and logG, eliminating # duplicated inputs (these crash the interpolator) good_Teff = np.where( np.diff(tmp['col3']) != 0 ) good_logG = np.where( np.diff(tmp['col5']) != 0 ) good_logL = np.where( np.diff(tmp['col4']) != 0 ) # Interpolate Teff, logL, and logG using linear interpolator tck_Teff = interpolate.interp1d(tmp['col2'], tmp['col3']) tck_logL = interpolate.interp1d(tmp['col2'], tmp['col4']) tck_logG = interpolate.interp1d(tmp['col2'], tmp['col5']) Teff = tck_Teff(age_arr) logL = tck_logL(age_arr) logG = tck_logG(age_arr) # Test interpolation if desired test=False if test: py.figure(1, figsize=(10,10)) py.clf() py.plot(tmp['col2'], tmp['col3'], 'k.', ms=8) py.plot(age_arr, Teff, 'r-', linewidth=2) py.xlabel('logAge') py.ylabel('Teff') py.savefig('test_Teff.png') py.figure(2, figsize=(10,10)) py.clf() py.plot(tmp['col2'], tmp['col4'], 'k.', ms=8) py.plot(age_arr, logL, 'r-', linewidth=2) py.xlabel('logAge') py.ylabel('logL') py.savefig('test_logL.png') py.figure(3, figsize=(10,10)) py.clf() py.plot(tmp['col2'], tmp['col5'], 'k.', ms=8) py.plot(age_arr, logG, 'r-', linewidth=2) py.xlabel('logAge') py.ylabel('logG') py.savefig('test_logG.png') pdb.set_trace() # Build upon arrays of interpolated values mass_interp = np.concatenate((mass_interp, np.ones(len(Teff)) * mass)) age_interp = np.concatenate((age_interp, age_arr)) Teff_interp = np.concatenate((Teff_interp, Teff)) logL_interp = np.concatenate((logL_interp, logL)) logG_interp = np.concatenate((logG_interp, logG)) print( 'Done {0} of {1}'.format(cnt, len(masses))) cnt+=1 # Now, construct the iso_*.fits files for each age, write files # to iso subdirectory # First check to see if subdirectory exists if not os.path.exists('iso/'): os.mkdir('iso') # Now for the loop ages = np.unique(age_interp) print( 'Writing iso files') for age in ages: good = np.where( age_interp == age) t = Table( (mass_interp[good], Teff_interp[good], logL_interp[good], logG_interp[good]), names=('Mass', 'Teff', 'logL', 'logG') ) # Write out as fits table name = 'iso_{0:3.2f}.fits'.format(age) t.write('iso/'+name, format='fits', overwrite=True) return def test_age_interp(self, onlineIso, interpIso): r""" Compare one of our interpolated ischrones with one of the isochrones provided online by Baraffe+15. """ true_iso = Table.read(onlineIso, format='ascii') our_iso = Table.read(interpIso, format='fits') # Compare the two isochrones using plots. Look at mass vs. Teff, # mass vs. logG, mass vs. logL. Ideally these isochrones should # be identical py.figure(1, figsize=(10,10)) py.clf() py.plot(true_iso['col1'], true_iso['col2'], 'k.', ms = 10) py.plot(our_iso['Mass'], our_iso['Teff'], 'r.', ms = 10) py.xlabel('Mass') py.ylabel('Teff') py.savefig('interp_test1.png') py.figure(2, figsize=(10,10)) py.clf() py.plot(true_iso['col1'], true_iso['col3'], 'k.', ms = 10) py.plot(our_iso['Mass'], our_iso['logL'], 'r.', ms = 10) py.xlabel('Mass') py.ylabel('logL') py.savefig('interp_test2.png') py.figure(3, figsize=(10,10)) py.clf() py.plot(true_iso['col1'], true_iso['col4'], 'k.', ms = 10) py.plot(our_iso['Mass'], our_iso['logG'], 'r.', ms = 10) py.xlabel('Mass') py.ylabel('logG') py.savefig('interp_test3.png') # Look at the difference between values (assumes the masses are lined up) Teff_diff = np.mean(abs(true_iso['col2'][7:] - our_iso['Teff'])) logL_diff = np.mean(abs(true_iso['col3'][7:] - our_iso['logL'])) logG_diff = np.mean(abs(true_iso['col4'][7:] - our_iso['logG'])) print( 'Average abs difference in Teff: {0}'.format(Teff_diff)) print( 'Average abs difference in logL: {0}'.format(logL_diff)) print( 'Average abs difference in logg: {0}'.format(logG_diff)) return def compare_Baraffe_Pisa(BaraffeIso, PisaIso): """ Compare the Baraffe isochrones to the Pisa isochrones, since they overlap over a significant portion of mass space. """ b = Table.read(BaraffeIso, format='fits') p = Table.read(PisaIso, format='ascii') name = BaraffeIso.split('_') age = name[1][:4] # Extract paramters we need b_mass = b['Mass'] b_logT = np.log10(b['Teff']) b_logL = b['logL'] b_logG = b['logG'] p_mass = p['col3'] p_logT = p['col2'] p_logL = p['col1'] p_logG = p['col4'] m05_b = np.where( abs(b_mass - 0.5) == min(abs(b_mass - 0.5)) ) m05_p = np.where( abs(p_mass - 0.5) == min(abs(p_mass - 0.5)) ) # Comparison plots py.figure(1, figsize=(10,10)) py.clf() py.plot(b_logT, b_logL, 'k-', linewidth=2, label='Baraffe+15') py.plot(b_logT[m05_b], b_logL[m05_b], 'k.', ms=10) py.plot(p_logT, p_logL, 'r', linewidth=2, label='Pisa') py.plot(p_logT[m05_p], p_logL[m05_p], 'r.', ms=10) py.xlabel('logT') py.ylabel('logL') py.title(age) py.axis([4.4, 3.4, -3, 4]) #py.gca().invert_xaxis() py.legend() py.savefig('BaraffePisa_comp_{0}.png'.format(age)) py.figure(2, figsize=(10,10)) py.clf() py.plot(b_mass, b_logL, 'k-', linewidth=2, label='Baraffe+15') py.plot(b_mass[m05_b], b_logL[m05_b], 'k.', ms=10) py.plot(p_mass, p_logL, 'r', linewidth=2, label='Pisa') py.plot(p_mass[m05_p], p_logL[m05_p], 'r.', ms=10) py.xlabel('Mass') py.ylabel('logL') py.title(age) #py.axis([4.4, 3.4, -3, 4]) #py.gca().invert_xaxis() py.legend() py.savefig('BaraffePisa_comp_mass_{0}.png'.format(age)) return #===============================# # MIST v.1 (Choi+16) #===============================# class MISTv1(StellarEvolution): """ Define intrinsic properties for the MIST v1 stellar models. Models originally downloaded from `online server <http://waps.cfa.harvard.edu/MIST/interp_isos.html>`_. Parameters ---------- version: '1.0' or '1.2', optional Specify which version of MIST models you want. Version 1.0 was downloaded from MIST website on 2/2017, while Version 1.2 was downloaded on 8/2018 (solar metallicity) and 4/2019 (other metallicities). Default is 1.2. """ def __init__(self, version=1.2): # define metallicity parameters for MIST models self.z_list = [0.0000014, # [Fe/H] = -4.00 0.0000045, # [Fe/H] = -3.50 0.000014, # [Fe/H] = -3.00 0.000045, # [Fe/H] = -2.50 0.00014, # [Fe/H] = -2.00 0.00025, # [Fe/H] = -1.75 0.00045, # [Fe/H] = -1.50 0.00080, # [Fe/H] = -1.25 0.0014, # [Fe/H] = -1.00 0.0025, # [Fe/H] = -0.75 0.0045, # [Fe/H] = -0.50 0.0080, # [Fe/H] = -0.25 0.014, # [Fe/H] = 0.00 0.025, # [Fe/H] = 0.25 0.045] # [Fe/H] = 0.50 # populate list of isochrone ages (log scale) self.age_list = np.arange(5.01, 10.30+0.005, 0.01) # Set version directory self.version = version if self.version == 1.0: version_dir = 'v1.0/' elif self.version == 1.2: version_dir = 'v1.2/' else: raise ValueError('Version {0} not supported for MIST isochrones'.format(version)) # Specify location of model files self.model_dir = models_dir+'MISTv1/' + version_dir # Specifying metallicity self.z_solar = 0.0142 self.z_file_map = {0.0000014: 'z0000014/', 0.0000045: 'z0000045/', 0.000014: 'z000014/', 0.000045: 'z000045/', 0.00014: 'z00014/', 0.00025: 'z00025/', 0.00045: 'z00045/', 0.00080: 'z00080/', 0.0014: 'z0014/', 0.0025: 'z0025/', 0.0045: 'z0045/', 0.0080: 'z0080/', 0.014: 'z014/', 0.025: 'z025/', 0.045: 'z045/'} # Define required evo_grid number self.evo_grid_min = 1.1 def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the MISTv1 collection. """ # First, error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar * (10.**metallicity) log_age = math.log10(age) # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + 'iso/' + z_dir + iso_file # return isochrone data. Column locations depend on # version iso = Table.read(full_iso_file, format='fits') if self.version == 1.0: iso.rename_column('col7', 'Z') iso.rename_column('col2', 'logAge') iso.rename_column('col3', 'mass') iso.rename_column('col4', 'logT') iso.rename_column('col5', 'logg') iso.rename_column('col6', 'logL') iso.rename_column('col65', 'phase') elif self.version == 1.2: iso.rename_column('col2', 'logAge') iso.rename_column('col3', 'mass') iso.rename_column('col4', 'mass_current') iso.rename_column('col9', 'logL') iso.rename_column('col14', 'logT') iso.rename_column('col17', 'logg') iso.rename_column('col79', 'phase') # For MIST isochrones, anything with phase = 6 is a WD. # Following our IFMR convention, change the phase designation # to 101 isWD = np.where(iso['phase'] == 6)[0] iso['phase'][isWD] = 101 # Define "isWR" column based on phase info isWR = Column([False] * len(iso), name='isWR') idx_WR = np.where(iso['phase'] == 9)[0] isWR[idx_WR] = True iso.add_column(isWR) iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso def format_isochrones(self): r""" Parse isochrone file downloaded from MIST web server, create individual isochrone files for the different ages. Assumes all files start with MIST_iso* Parameters: ----------- input_iso_dir: path Points to MISTv1/<version>/iso directory. metallicity_list: array List of metallicity directories to check (i.e. z015 is solar) """ # Get input iso dir, metallicity list from evo object input_iso_dir = '{0}/iso'.format(self.model_dir) metallicity_list = list(self.z_file_map.values()) # Store current directory for later start_dir = os.getcwd() # Move into isochrone directory os.chdir(input_iso_dir) # Work on each metallicity isochrones individually for metal in metallicity_list: # More into metallicity directory, read isochrone file os.chdir(metal) # Read all available iso files, stack them together isoFile = glob.glob('MIST_iso*') print( 'Read Input: this is slow') iso_f = Table() for ii in isoFile: tmp = Table.read(ii, format='ascii') iso_f = vstack([iso_f, tmp]) print( 'Done') # Extract the unique ages ages_all = iso_f['col2'] age_arr = np.unique(ages_all) # For each unique age, extract the proper rows and make corresponding # table print( 'Making individual isochrone files') for age in age_arr: good = np.where(ages_all == age) tmp = iso_f[good] # Need to make sure the tables are unmasked...this causes # problems later tmp2 = Table(tmp, masked=False) #Write table tmp2.write('iso_{0:4.2f}.fits'.format(age)) # Move back into iso directory os.chdir('..') # Return to starting directory os.chdir(start_dir) return #==============================# # Merged model classes #==============================# class MergedBaraffePisaEkstromParsec(StellarEvolution): """ This is a combination of several different evolution models: * Baraffe (`Baraffe et al. 2015 <https://ui.adsabs.harvard.edu/abs/2015A%26A...577A..42B/abstract>`_) * Pisa (`Tognelli et al. 2011 <https://ui.adsabs.harvard.edu/abs/2011A%26A...533A.109T/abstract>`_) * Geneva (`Ekstrom et al. 2012 <https://ui.adsabs.harvard.edu/abs/2012A%26A...537A.146E/abstract>`_) * Parsec (version 1.2s, `Bressan+12 <https://ui.adsabs.harvard.edu/abs/2012MNRAS.427..127B/abstract>`_) The model used depends on the age of the population and what stellar masses are being modeled: For logAge < 7.4: * Baraffe: 0.08 - 0.4 M_sun * Baraffe/Pisa transition: 0.4 - 0.5 M_sun * Pisa: 0.5 M_sun to the highest mass in Pisa isochrone (typically 5 - 7 Msun) * Geneva: Highest mass of Pisa models to 120 M_sun For logAge > 7.4: * Parsec v1.2s: full mass range Parameters ---------- rot: boolean, optional If true, then use rotating Ekstrom models. Default is true. """ def __init__(self, rot=True): # populate list of model masses (in solar masses) mass_list = [(0.1 + i*0.005) for i in range(181)] # define metallicity parameters for Geneva models z_list = [0.015] # populate list of isochrone ages (log scale) age_list = np.arange(6.0, 10.091, 0.01).tolist() # specify location of model files model_dir = models_dir + 'merged/baraffe_pisa_ekstrom_parsec/' StellarEvolution.__init__(self, model_dir, age_list, mass_list, z_list) self.z_solar = 0.015 # Switch to specify rotating/non-rotating models if rot: self.z_file_map = {0.015: 'z015_rot/'} else: self.z_file_map = {0.015: 'z015_norot/'} # Define required evo_grid number self.evo_grid_min = 1.0 def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Baraffe-Pisa-Ekstrom-Parsec collection """ # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if ((log_age < np.min(self.age_list)) or (log_age > np.max(self.age_list))): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if ((z_defined < np.min(self.z_list)) or (z_defined > np.max(self.z_list))): logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + z_dir + iso_file # return isochrone data iso = Table.read(full_iso_file, format='fits') iso.rename_column('col1', 'mass') iso.rename_column('col2', 'logT') iso.rename_column('col3', 'logL') iso.rename_column('col4', 'logg') iso.rename_column('col5', 'logT_WR') iso.rename_column('col6', 'mass_current') iso.rename_column('col7', 'phase') iso.rename_column('col8', 'model_ref') # Define "isWR" column based on phase info isWR = Column([False] * len(iso), name='isWR') idx_WR = np.where(iso['logT'] != iso['logT_WR']) isWR[idx_WR] = True iso.add_column(isWR) iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso class MergedPisaEkstromParsec(StellarEvolution): """ Same as MergedBaraffePisaEkstromParsec, but without the Baraffe models. Parameters ---------- rot: boolean, optional If true, then use rotating Ekstrom models. Default is true. """ def __init__(self, rot=True): # populate list of model masses (in solar masses) mass_list = [(0.1 + i*0.005) for i in range(181)] # define metallicity parameters for Geneva models z_list = [0.015] # populate list of isochrone ages (log scale) age_list = np.arange(6.0, 8.001, 0.01).tolist() # specify location of model files model_dir = models_dir + 'merged/pisa_ekstrom_parsec/' StellarEvolution.__init__(self, model_dir, age_list, mass_list, z_list) self.z_solar = 0.015 #Switch to specify rot/notot if rot: self.z_file_map = {0.015: 'z015_rot/'} else: self.z_file_map = {0.015: 'z015_norot/'} # Define required evo_grid number self.evo_grid_min = 1.0 # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Pisa-Ekstrom-Parsec collection. """ # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if (log_age < self.age_list[0]) or (log_age > self.age_list[-1]): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if not z_defined in self.z_list: logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + z_dir + iso_file # return isochrone data iso = Table.read(full_iso_file, format='fits') iso.rename_column('col1', 'mass') iso.rename_column('col2', 'logT') iso.rename_column('col3', 'logL') iso.rename_column('col4', 'logg') iso.rename_column('col5', 'logT_WR') iso.rename_column('col6', 'model_ref') iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso class MergedSiessGenevaPadova(StellarEvolution): """ This is a combination of several different evolution models. The model used depends on the age of the population and what stellar masses are being modeled: * Siess (`Siess et al. 2000 <https://ui.adsabs.harvard.edu/abs/2000A%26A...358..593S/abstractt>`_) * Geneva (`Meynet & Maeder 2003 <https://ui.adsabs.harvard.edu/abs/2003A%26A...404..975M/abstract>`_) * Padova (`Marigo et al. 2008 <https://ui.adsabs.harvard.edu/abs/2008A%26A...482..883M/abstract>`_) For logAge < 7.4: * Siess: 0.1 - 7 M_sun * Siess/Geneva transition: 7 - 9 M_sun * Geneva: > 9 M_sun For logAge > 7.4: * Padova: full mass range """ def __init__(self): """ Define intrinsic properties for merged Siess-meynetMaeder-Padova stellar models. """ # populate list of model masses (in solar masses) mass_list = [(0.1 + i*0.005) for i in range(181)] # define metallicity parameters for Geneva models z_list = [0.02] # populate list of isochrone ages (log scale) age_list = np.arange(5.5, 7.41, 0.01).tolist() age_list.append(7.48) idx = np.arange(7.50, 8.01, 0.05) for ii in idx: age_list.append(ii) age_list.append(8.30) age_list.append(8.48) age_list.append(8.60) age_list.append(8.70) age_list.append(8.78) age_list.append(8.85) age_list.append(8.90) age_list.append(8.95) age_list.append(9.00) age_list.append(9.30) age_list.append(9.60) age_list.append(9.70) age_list.append(9.78) # specify location of model files model_dir = models_dir + 'merged/siess_meynetMaeder_padova/' StellarEvolution.__init__(self, model_dir, age_list, mass_list, z_list) self.z_solar = 0.02 # Metallicity map self.z_file_map = {0.02: 'z02/'} # Define required evo_grid number self.evo_grid_min = 1.0 # Error check to see if installed evolution model # grid is compatible with code version. Also return # current grid num self.evo_grid_num = check_evo_grid_number(self.evo_grid_min, models_dir) def isochrone(self, age=1.e8, metallicity=0.0): r""" Extract an individual isochrone from the Siess-Geneva-Padova collection. """ # convert metallicity to mass fraction z_defined = self.z_solar*10.**metallicity log_age = math.log10(age) # check age and metallicity are within bounds if (log_age < self.age_list[0]) or (log_age > self.age_list[-1]): logger.error('Requested age {0} is out of bounds.'.format(log_age)) if not z_defined in self.z_list: logger.error('Requested metallicity {0} is out of bounds.'.format(z_defined)) # Find nearest age in grid to input grid age_idx = np.where(abs(np.array(self.age_list) - log_age) == min(abs(np.array(self.age_list) - log_age)) )[0][0] iso_file = 'iso_{0:.2f}.fits'.format(self.age_list[age_idx]) # find closest metallicity value z_idx = np.where(abs(np.array(self.z_list) - z_defined) == min(abs(np.array(self.z_list) - z_defined)) )[0][0] z_dir = self.z_file_map[self.z_list[z_idx]] # generate isochrone file string full_iso_file = self.model_dir + z_dir + iso_file # return isochrone data iso = Table.read(full_iso_file, format='ascii') iso.rename_column('col1', 'mass') iso.rename_column('col2', 'logT') iso.rename_column('col3', 'logL') iso.rename_column('col4', 'logg') iso.rename_column('col5', 'logT_WR') iso.rename_column('col6', 'model_ref') iso.meta['log_age'] = log_age iso.meta['metallicity_in'] = metallicity iso.meta['metallicity_act'] = np.log10(self.z_list[z_idx] / self.z_solar) return iso #================================================# def make_isochrone_pisa_interp(log_age, metallicity=0.015, tracks=None, test=False): """ Read in a set of isochrones and generate an isochrone at log_age that is well sampled at the full range of masses. Puts isochrones is Pisa2011/iso/<metal>/ """ # If logage > 8.0, quit immediately...grid doesn't go that high if log_age > 8.0: print( 'Age too high for Pisa grid (max logAge = 8.0)') return # Directory with where the isochrones will go (both downloaded and interpolated) rootDir = models_dir + '/Pisa2011/iso/' metSuffix = 'z' + str(metallicity).split('.')[-1] rootDir += metSuffix + '/' # Can we find the isochrone directory? if not os.path.exists(rootDir): print( 'Failed to find Pisa PMS isochrones for metallicity = ' + metSuffix) return # Check to see if isochrone at given age already exists. If so, quit if os.path.exists(rootDir+'iso_{0:3.2f}.fits'.format(log_age)): print( 'Isochrone at logAge = {0:3.2f} already exists'.format(log_age)) return # Name/directory for interpolated isochrone isoFile = rootDir+'iso_%3.2f.fits' % log_age outSuffix = '_%.2f' % (log_age) print( '*** Generating Pisa isochrone for log t = %3.2f and Z = %.3f' % \ (log_age, metallicity)) print( time.asctime(), 'Getting original Pisa isochrones.') iso = get_orig_pisa_isochrones(metallicity=metallicity) # First thing is to find the isochrones immediately above and below desired # age iso_log_ages = iso.log_ages tmp = np.append(iso_log_ages, log_age) # Find desired age in ordered sequence; isolate model younger and older tmp.sort() good = np.where(tmp == log_age) young_model_logage = tmp[good[0]-1] old_model_logage = tmp[good[0]+1] # Isolate younger/older isochrones young_ind = np.where(iso.log_ages == young_model_logage) old_ind = np.where(iso.log_ages == old_model_logage) young_iso = iso.isochrones[young_ind[0]] old_iso = iso.isochrones[old_ind[0]] # Need both younger and older model on same temperature grid for time # interpolation. Will adopt mass grid of whichever model is closer in time if abs(young_model_logage - log_age) <= abs(old_model_logage - log_age): # Use young model mass grid young_iso, old_iso = interpolate_iso_tempgrid(young_iso, old_iso) else: # Use old model mass grid old_iso, young_iso = interpolate_iso_tempgrid(old_iso, young_iso) # Now, can interpolate in time over the two models. Do this star by star. # Work in linear time here!! numStars = len(young_iso.M) interp_iso = Isochrone(log_age) interp_iso.log_Teff = np.zeros(numStars, dtype=float) interp_iso.log_L = np.zeros(numStars, dtype=float) interp_iso.log_g = np.zeros(numStars, dtype=float) interp_iso.M = young_iso.M # Since mass grids should already be matched for i in range(numStars): # Do interpolations in linear space model_ages = [10**young_model_logage[0], 10**old_model_logage[0]] target_age = 10**log_age #model_ages = [young_model_logage[0], old_model_logage[0]] #target_age = log_age # Build interpolation functions Teff_arr = [10**young_iso.log_Teff[i], 10**old_iso.log_Teff[i]] logL_arr = [10**young_iso.log_L[i], 10**old_iso.log_L[i]] logg_arr = [10**young_iso.log_g[i], 10**old_iso.log_g[i]] f_log_Teff = interpolate.interp1d(model_ages, Teff_arr, kind='linear') f_log_L = interpolate.interp1d(model_ages, logL_arr, kind='linear') f_log_g = interpolate.interp1d(model_ages, logg_arr, kind='linear') interp_iso.log_Teff[i] = np.log10(f_log_Teff(target_age)) interp_iso.log_L[i] = np.log10(f_log_L(target_age)) interp_iso.log_g[i] = np.log10(f_log_g(target_age)) # If indicated, plot new isochrone along with originals it was interpolated # from if test: py.figure(1) py.clf() py.plot(interp_iso.log_Teff, interp_iso.log_L, 'k-', label = 'Interp') py.plot(young_iso.log_Teff, young_iso.log_L, 'b-', label = 'log Age = {0:3.2f}'.format(young_model_logage[0])) py.plot(old_iso.log_Teff, old_iso.log_L, 'r-', label = 'log Age = {0:3.2f}'.format(old_model_logage[0])) rng = py.axis() py.xlim(rng[1], rng[0]) py.xlabel('log Teff') py.ylabel('log L') py.legend() py.title('Pisa 2011 Isochrone at log t = %.2f' % log_age) py.savefig(rootDir + 'plots/interp_isochrone_at' + outSuffix + '.png') print( time.asctime(), 'Finished.') # Write output to file, MUST BE IN SAME ORDER AS ORIG FILES _out = open(isoFile, 'w') _out.write('%10s %10s %10s %10s\n' % ('# log L', 'log Teff', 'Mass', 'log g')) _out.write('%10s %10s %10s %10s\n' % ('# (Lsun)', '(Kelvin)', '(Msun)', '(cgs)')) for ii in range(len(interp_iso.M)): _out.write('%10.4f %10.4f %10.4f %10.4f\n' % (interp_iso.log_L[ii], interp_iso.log_Teff[ii], interp_iso.M[ii], interp_iso.log_g[ii])) _out.close() return def get_orig_pisa_isochrones(metallicity=0.015): """ Helper code to get the original pisa isochrones at given metallicity. These are downloaded online """ pms_dir = models_dir + '/Pisa2011/iso/iso_orig/' metSuffix = 'z' + str(metallicity).split('.')[-1] pms_dir += metSuffix + '/' if not os.path.exists(pms_dir): print( 'Failed to find Siess PMS isochrones for metallicity = ' + metSuffix) return # Collect the isochrones files = glob.glob(pms_dir + '*.dat') count = len(files) data = objects.DataHolder() data.isochrones = [] data.log_ages = [] # Extract useful params from isochrones for ff in range(len(files)): d = Table.read(files[ff], format='ascii') # Extract logAge from filename log_age = float(files[ff].split('_')[2][:-4]) # Create an isochrone object iso = Isochrone(log_age) iso.M = d['col3'] iso.log_Teff = d['col2'] iso.log_L = d['col1'] # If a log g column exist, extract it. Otherwise, calculate # log g from T and L and add column at end if len(d.keys()) == 3: # Calculate log g from T and L L_sun = 3.8 * 10**33 #cgs SB_sig = 5.67 * 10**-5 #cgs M_sun = 2. * 10**33 #cgs G_const = 6.67 * 10**-8 #cgs radius = np.sqrt( (10**d['col1'] * L_sun) / (4 * np.pi * SB_sig * (10**d['col2'])**4) ) g = (G_const * d['col3'] * M_sun) / radius**2 iso.log_g = np.log10(g.astype(np.float)) else: iso.log_g = d['col4'] data.isochrones.append(iso) data.log_ages.append(log_age) # If it doesn't already exist, add a column with logg vals. This will # be appended at the end if len(d.keys()) == 3: logg_col = Column(iso.log_g, name = 'col4') d.add_column(logg_col, index=3) d.write(files[ff],format='ascii') data.log_ages = np.array(data.log_ages) # Resort so that everything is in order of increasing age sdx = data.log_ages.argsort() data.masses = data.log_ages[sdx] data.isochrones = [data.isochrones[ss] for ss in sdx] return data class Isochrone(object): def __init__(self, log_age): self.log_age = log_age
astropyREPO_NAMESPISEAPATH_START.@SPISEA_extracted@SPISEA-main@spisea@evolution.py@.PATH_END.py
{ "filename": "ConcurrentMpiCosmoHammerSampler.py", "repo_name": "JulianBMunoz/21cmvFAST", "repo_path": "21cmvFAST_extracted/21cmvFAST-master/public_21CMvFAST_MC/Programs/CosmoHammer_21CMMC/sampler/ConcurrentMpiCosmoHammerSampler.py", "type": "Python" }
from .MpiCosmoHammerSampler import MpiCosmoHammerSampler import multiprocessing class ConcurrentMpiCosmoHammerSampler(MpiCosmoHammerSampler): """ A sampler implementation extending the mpi sampler in order to allow to distribute the computation with MPI and using multiprocessing on a single node. :param threads: (optional) The number of threads to use for parallelization. If ``threads == 1``, then the ``multiprocessing`` module is not used but if ``threads > 1``, then a ``Pool`` object is created :param kwargs: key word arguments passed to the CosmoHammerSampler """ def __init__(self, threads=1, **kwargs): """ CosmoHammer sampler implementation """ self.threads = threads super(ConcurrentMpiCosmoHammerSampler, self).__init__(**kwargs) def _getMapFunction(self): if self.threads > 1: pool = multiprocessing.Pool(self.threads) return pool.map else: return map
JulianBMunozREPO_NAME21cmvFASTPATH_START.@21cmvFAST_extracted@21cmvFAST-master@public_21CMvFAST_MC@Programs@CosmoHammer_21CMMC@sampler@ConcurrentMpiCosmoHammerSampler.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "ratt-ru/montblanc", "repo_path": "montblanc_extracted/montblanc-master/montblanc/impl/rime/tensorflow/helpers/__init__.py", "type": "Python" }
ratt-ruREPO_NAMEmontblancPATH_START.@montblanc_extracted@montblanc-master@montblanc@impl@rime@tensorflow@helpers@__init__.py@.PATH_END.py
{ "filename": "_lineposition.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/densitymap/colorbar/title/font/_lineposition.py", "type": "Python" }
import _plotly_utils.basevalidators class LinepositionValidator(_plotly_utils.basevalidators.FlaglistValidator): def __init__( self, plotly_name="lineposition", parent_name="densitymap.colorbar.title.font", **kwargs, ): super(LinepositionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), extras=kwargs.pop("extras", ["none"]), flags=kwargs.pop("flags", ["under", "over", "through"]), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@densitymap@colorbar@title@font@_lineposition.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "scikit-learn/scikit-learn", "repo_path": "scikit-learn_extracted/scikit-learn-main/sklearn/semi_supervised/tests/__init__.py", "type": "Python" }
scikit-learnREPO_NAMEscikit-learnPATH_START.@scikit-learn_extracted@scikit-learn-main@sklearn@semi_supervised@tests@__init__.py@.PATH_END.py
{ "filename": "test_filestorage_io.py", "repo_name": "itseez/opencv", "repo_path": "opencv_extracted/opencv-master/modules/python/test/test_filestorage_io.py", "type": "Python" }
#!/usr/bin/env python """Algorithm serialization test.""" from __future__ import print_function import base64 import json import tempfile import os import cv2 as cv import numpy as np from tests_common import NewOpenCVTests class MyData: def __init__(self): self.A = 97 self.X = np.pi self.name = 'mydata1234' def write(self, fs, name): fs.startWriteStruct(name, cv.FileNode_MAP|cv.FileNode_FLOW) fs.write('A', self.A) fs.write('X', self.X) fs.write('name', self.name) fs.endWriteStruct() def read(self, node): if (not node.empty()): self.A = int(node.getNode('A').real()) self.X = node.getNode('X').real() self.name = node.getNode('name').string() else: self.A = self.X = 0 self.name = '' class filestorage_io_test(NewOpenCVTests): strings_data = ['image1.jpg', 'Awesomeness', '../data/baboon.jpg'] R0 = np.eye(3,3) T0 = np.zeros((3,1)) def write_data(self, fname): fs = cv.FileStorage(fname, cv.FileStorage_WRITE) R = self.R0 T = self.T0 m = MyData() fs.write('iterationNr', 100) fs.startWriteStruct('strings', cv.FileNode_SEQ) for elem in self.strings_data: fs.write('', elem) fs.endWriteStruct() fs.startWriteStruct('Mapping', cv.FileNode_MAP) fs.write('One', 1) fs.write('Two', 2) fs.endWriteStruct() fs.write('R_MAT', R) fs.write('T_MAT', T) m.write(fs, 'MyData') fs.release() def read_data_and_check(self, fname): fs = cv.FileStorage(fname, cv.FileStorage_READ) n = fs.getNode('iterationNr') itNr = int(n.real()) self.assertEqual(itNr, 100) n = fs.getNode('strings') self.assertTrue(n.isSeq()) self.assertEqual(n.size(), len(self.strings_data)) for i in range(n.size()): self.assertEqual(n.at(i).string(), self.strings_data[i]) n = fs.getNode('Mapping') self.assertEqual(int(n.getNode('Two').real()), 2) self.assertEqual(int(n.getNode('One').real()), 1) R = fs.getNode('R_MAT').mat() T = fs.getNode('T_MAT').mat() self.assertEqual(cv.norm(R, self.R0, cv.NORM_INF), 0) self.assertEqual(cv.norm(T, self.T0, cv.NORM_INF), 0) m0 = MyData() m = MyData() m.read(fs.getNode('MyData')) self.assertEqual(m.A, m0.A) self.assertEqual(m.X, m0.X) self.assertEqual(m.name, m0.name) n = fs.getNode('NonExisting') self.assertTrue(n.isNone()) fs.release() def run_fs_test(self, ext): fd, fname = tempfile.mkstemp(prefix="opencv_python_sample_filestorage", suffix=ext) os.close(fd) self.write_data(fname) self.read_data_and_check(fname) os.remove(fname) def test_xml(self): self.run_fs_test(".xml") def test_yml(self): self.run_fs_test(".yml") def test_json(self): self.run_fs_test(".json") def test_base64(self): fd, fname = tempfile.mkstemp(prefix="opencv_python_sample_filestorage_base64", suffix=".json") os.close(fd) np.random.seed(42) self.write_base64_json(fname) os.remove(fname) @staticmethod def get_normal_2d_mat(): rows = 10 cols = 20 cn = 3 image = np.zeros((rows, cols, cn), np.uint8) image[:] = (1, 2, 127) for i in range(rows): for j in range(cols): image[i, j, 1] = (i + j) % 256 return image @staticmethod def get_normal_nd_mat(): shape = (2, 2, 1, 2) cn = 4 image = np.zeros(shape + (cn,), np.float64) image[:] = (0.888, 0.111, 0.666, 0.444) return image @staticmethod def get_empty_2d_mat(): shape = (0, 0) cn = 1 image = np.zeros(shape + (cn,), np.uint8) return image @staticmethod def get_random_mat(): rows = 8 cols = 16 cn = 1 image = np.random.rand(rows, cols, cn) return image @staticmethod def decode(data): # strip $base64$ encoded = data[8:] if len(encoded) == 0: return b'' # strip info about datatype and padding return base64.b64decode(encoded)[24:] def write_base64_json(self, fname): fs = cv.FileStorage(fname, cv.FileStorage_WRITE_BASE64) mats = {'normal_2d_mat': self.get_normal_2d_mat(), 'normal_nd_mat': self.get_normal_nd_mat(), 'empty_2d_mat': self.get_empty_2d_mat(), 'random_mat': self.get_random_mat()} for name, mat in mats.items(): fs.write(name, mat) fs.release() data = {} with open(fname) as file: data = json.load(file) for name, mat in mats.items(): buffer = b'' if mat.size != 0: if hasattr(mat, 'tobytes'): buffer = mat.tobytes() else: buffer = mat.tostring() self.assertEqual(buffer, self.decode(data[name]['data'])) if __name__ == '__main__': NewOpenCVTests.bootstrap()
itseezREPO_NAMEopencvPATH_START.@opencv_extracted@opencv-master@modules@python@test@test_filestorage_io.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/tools/json/__init__.py", "type": "Python" }
"""Tools for interacting with a JSON file."""
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@tools@json@__init__.py@.PATH_END.py
{ "filename": "conf.py", "repo_name": "martenlourens/pySDR", "repo_path": "pySDR_extracted/pySDR-master/python/sphinx/source/conf.py", "type": "Python" }
# If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. import pathlib import sys sys.path.insert(1, pathlib.Path(__file__).parents[2].resolve().as_posix()) # Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information project = 'pySDR' copyright = '2023, Marten Lourens' author = 'Marten Lourens' release = '0.1' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', ] templates_path = ['_templates'] exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'sphinx_rtd_theme' html_static_path = ['_static']
martenlourensREPO_NAMEpySDRPATH_START.@pySDR_extracted@pySDR-master@python@sphinx@source@conf.py@.PATH_END.py
{ "filename": "compiler.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/ipykernel/py3/ipykernel/compiler.py", "type": "Python" }
"""Compiler helpers for the debugger.""" import os import sys import tempfile from IPython.core.compilerop import CachingCompiler def murmur2_x86(data, seed): """Get the murmur2 hash.""" m = 0x5BD1E995 data = [chr(d) for d in str.encode(data, "utf8")] length = len(data) h = seed ^ length rounded_end = length & 0xFFFFFFFC for i in range(0, rounded_end, 4): k = ( (ord(data[i]) & 0xFF) | ((ord(data[i + 1]) & 0xFF) << 8) | ((ord(data[i + 2]) & 0xFF) << 16) | (ord(data[i + 3]) << 24) ) k = (k * m) & 0xFFFFFFFF k ^= k >> 24 k = (k * m) & 0xFFFFFFFF h = (h * m) & 0xFFFFFFFF h ^= k val = length & 0x03 k = 0 if val == 3: k = (ord(data[rounded_end + 2]) & 0xFF) << 16 if val in [2, 3]: k |= (ord(data[rounded_end + 1]) & 0xFF) << 8 if val in [1, 2, 3]: k |= ord(data[rounded_end]) & 0xFF h ^= k h = (h * m) & 0xFFFFFFFF h ^= h >> 13 h = (h * m) & 0xFFFFFFFF h ^= h >> 15 return h convert_to_long_pathname = lambda filename: filename # noqa: E731 if sys.platform == "win32": try: import ctypes from ctypes.wintypes import DWORD, LPCWSTR, LPWSTR, MAX_PATH _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW _GetLongPathName.argtypes = [LPCWSTR, LPWSTR, DWORD] _GetLongPathName.restype = DWORD def _convert_to_long_pathname(filename): buf = ctypes.create_unicode_buffer(MAX_PATH) rv = _GetLongPathName(filename, buf, MAX_PATH) if rv != 0 and rv <= MAX_PATH: filename = buf.value return filename # test that it works so if there are any issues we fail just once here _convert_to_long_pathname(__file__) except Exception: pass else: convert_to_long_pathname = _convert_to_long_pathname def get_tmp_directory(): """Get a temp directory.""" tmp_dir = convert_to_long_pathname(tempfile.gettempdir()) pid = os.getpid() return tmp_dir + os.sep + "ipykernel_" + str(pid) def get_tmp_hash_seed(): """Get a temp hash seed.""" return 0xC70F6907 def get_file_name(code): """Get a file name.""" cell_name = os.environ.get("IPYKERNEL_CELL_NAME") if cell_name is None: name = murmur2_x86(code, get_tmp_hash_seed()) cell_name = get_tmp_directory() + os.sep + str(name) + ".py" return cell_name class XCachingCompiler(CachingCompiler): """A custom caching compiler.""" def __init__(self, *args, **kwargs): """Initialize the compiler.""" super().__init__(*args, **kwargs) self.log = None def get_code_name(self, raw_code, code, number): """Get the code name.""" return get_file_name(raw_code)
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@ipykernel@py3@ipykernel@compiler.py@.PATH_END.py