jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_anisotropic_hernquist_dMdE_betap05():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = constantbetaHernquistdf(pot=pot, beta=0.5)
    tol = 1e-10

    def dMdE_betap05_analytic(E, dfh):
        if not hasattr(dfh, "_rphi"):
            dfh._rphi = dfh._setup_rphi_interpolator()
        rE = dfh._rphi(E)
        return 4.0 * numpy.pi**3.0 * rE**2.0 * dfh.fE(E)

    E = numpy.linspace(0.99 * pot(0, 0), pot(numpy.inf, 0) + 1e-6, 1001)
    assert numpy.all(
        numpy.fabs(dMdE_betap05_analytic(E, dfh) - dfh.dMdE(E)) < tol
    ), "Anisotropic Hernquist DF dMdE for beta=0.5 does not agree with analytic expression"
    return None
//  [python]
def test_anisotropic_hernquist_energyoutofbounds():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    betas = [-0.7, -0.5, -0.4, 0.0, 0.3, 0.5]
    for beta in betas:
        dfh = constantbetaHernquistdf(pot=pot, beta=beta)
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the anisotropic Hernquist DF at E > 0 does not give zero"
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-4, 1.1))) < 1e-8
        ), "Evaluating the anisotropic Hernquist DF at E < -GM/a does not give zero"
    return None
//  [python]
def test_anisotropic_hernquist_energyoutofbounds():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    betas = [-0.7, -0.5, -0.4, 0.0, 0.3, 0.5]
    for beta in betas:
        dfh = constantbetaHernquistdf(pot=pot, beta=beta)
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the anisotropic Hernquist DF at E > 0 does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-4, 1.1))) < 1e-8
        ), "Evaluating the anisotropic Hernquist DF at E < -GM/a does not give zero"
    return None
//  [python]
def test_osipkovmerritt_hernquist_Qoutofbounds():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    ras = [0.3, 2.3, 5.7]
    for ra in ras:
        dfh = osipkovmerrittHernquistdf(pot=pot, ra=ra)
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt Hernquist DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt Hernquist DF at E < -GM/a does not give zero"
        assert n.all(
            n.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt Hernquist DF at Q < 0 does not give zero"
    return None
//  [python]
def test_osipkovmerritt_hernquist_Qoutofbounds():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    ras = [0.3, 2.3, 5.7]
    for ra in ras:
        dfh = osipkovmerrittHernquistdf(pot=pot, ra=ra)
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt Hernquist DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt Hernquist DF at E < -GM/a does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt Hernquist DF at Q < 0 does not give zero"
    return None
//  [python]
def test_isotropic_nfw_energyoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    dfp = isotropicNFWdf(pot=pot)
    assert n.all(
        n.fabs(dfp((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E > 0 does not give zero"
    assert n.all(
        n.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_nfw_energyoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    dfp = isotropicNFWdf(pot=pot)
    assert numpy.all(
        numpy.fabs(dfp((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E > 0 does not give zero"
    assert numpy.all(
        numpy.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_plummer_energyoutofbounds():
    pot = potential.PlummerPotential(amp=2.3, b=1.3)
    dfp = isotropicPlummerdf(pot=pot)
    assert n.all(
        n.fabs(dfp((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the isotropic Plummer DF at E > 0 does not give zero"
    assert n.all(
        n.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic Plummer DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_plummer_energyoutofbounds():
    pot = potential.PlummerPotential(amp=2.3, b=1.3)
    dfp = isotropicPlummerdf(pot=pot)
    assert numpy.all(
        numpy.fabs(dfp((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the isotropic Plummer DF at E > 0 does not give zero"
    assert numpy.all(
        numpy.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic Plummer DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_hernquist_phasespacesamples_vs_orbitsamples():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    samp_orbits = dfh.sample(n=1000)
    # Reset seed such that we should get the same
    numpy.random.seed(10)
    samp_RvR = dfh.sample(n=1000, return_orbit=False)
    assert n.all(
        n.fabs(samp_orbits.R() - samp_RvR[0]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert n.all(
        n.fabs(samp_orbits.vR() - samp_RvR[1]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert n.all(
        n.fabs(samp_orbits.vT() - samp_RvR[2]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert n.all(
        n.fabs(samp_orbits.z() - samp_RvR[3]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert n.all(
        n.fabs(samp_orbits.vz() - samp_RvR[4]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert n.all(
        n.fabs(samp_orbits.phi() - samp_RvR[5]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    return None
//  [python]
def test_isotropic_hernquist_phasespacesamples_vs_orbitsamples():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    samp_orbits = dfh.sample(n=1000)
    # Reset seed such that we should get the same
    numpy.random.seed(10)
    samp_RvR = dfh.sample(n=1000, return_orbit=False)
    assert numpy.all(
        numpy.fabs(samp_orbits.R() - samp_RvR[0]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert numpy.all(
        numpy.fabs(samp_orbits.vR() - samp_RvR[1]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert numpy.all(
        numpy.fabs(samp_orbits.vT() - samp_RvR[2]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert numpy.all(
        numpy.fabs(samp_orbits.z() - samp_RvR[3]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert numpy.all(
        numpy.fabs(samp_orbits.vz() - samp_RvR[4]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    assert numpy.all(
        numpy.fabs(samp_orbits.phi() - samp_RvR[5]) < 1e-8
    ), "Sampling R,vR,... from spherical DF does not give the same as sampling equivalent orbits"
    return None
//  [python]
def test_osipkovmerritt_nfw_Qoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    ras = [2.3, 5.7]
    for ra in ras:
        dfh = osipkovmerrittNFWdf(pot=pot, ra=ra)
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt NFW DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt NFW DF at E < -GM/a does not give zero"
        assert n.all(
            n.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt NFW DF at Q < 0 does not give zero"
    return None
//  [python]
def test_osipkovmerritt_nfw_Qoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    ras = [2.3, 5.7]
    for ra in ras:
        dfh = osipkovmerrittNFWdf(pot=pot, ra=ra)
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt NFW DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt NFW DF at E < -GM/a does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt NFW DF at Q < 0 does not give zero"
    return None
//  [python]
def test_isotropic_nfw_widrow_against_improved():
    # Test that using the Widrow (2000) prescription gives almost the same f(E)
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    dfp = isotropicNFWdf(pot=pot)
    dfpw = isotropicNFWdf(pot=pot, widrow=True)
    Es = numpy.linspace(-dfp._Etildemax * 0.999, 0, 101, endpoint=False)
    assert n.all(
        n.fabs(1.0 - dfp.fE(Es) / dfpw.fE(Es)) < 1e-2
    ), "isotropic NFW with widrow=True does not agree on f(E) with widrow=False"
    return None
//  [python]
def test_isotropic_nfw_widrow_against_improved():
    # Test that using the Widrow (2000) prescription gives almost the same f(E)
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    dfp = isotropicNFWdf(pot=pot)
    dfpw = isotropicNFWdf(pot=pot, widrow=True)
    Es = numpy.linspace(-dfp._Etildemax * 0.999, 0, 101, endpoint=False)
    assert numpy.all(
        numpy.fabs(1.0 - dfp.fE(Es) / dfpw.fE(Es)) < 1e-2
    ), "isotropic NFW with widrow=True does not agree on f(E) with widrow=False"
    return None
//  [python]
def test_isotropic_eddington_selfconsist_dehnencore_energyoutofbounds():
    pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    dfp = eddingtondf(pot=pot)
    assert n.all(
        n.fabs(dfp((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the eddington DF at E > 0 does not give zero"
    assert n.all(
        n.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_eddington_selfconsist_dehnencore_energyoutofbounds():
    pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    dfp = eddingtondf(pot=pot)
    assert numpy.all(
        numpy.fabs(dfp((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the eddington DF at E > 0 does not give zero"
    assert numpy.all(
        numpy.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_eddington_dehnencore_in_nfw_energyoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    dfp = eddingtondf(pot=pot, denspot=denspot)
    assert n.all(
        n.fabs(dfp((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E > 0 does not give zero"
    assert n.all(
        n.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_isotropic_eddington_dehnencore_in_nfw_energyoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    dfp = eddingtondf(pot=pot, denspot=denspot)
    assert numpy.all(
        numpy.fabs(dfp((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E > 0 does not give zero"
    assert numpy.all(
        numpy.fabs(dfp((pot(0, 0) - 1e-4, 1.1))) < 1e-8
    ), "Evaluating the isotropic NFW DF at E < Phi(0) does not give zero"
    return None
//  [python]
def test_eddington_hernquist_dMdE():
    # Test that dMdE for an isotropic Hernquist model is correct by comparing to the exact solution in isotropicHernquist
    pot = potential.HernquistPotential(amp=1.3, a=2.3)
    dfe = eddingtondf(pot=pot)
    dfi = isotropicHernquistdf(pot)
    Emin = pot(0.0, 0.0)
    Emax = pot(numpy.inf, 0.0)
    E = numpy.linspace(0.99 * Emin, Emax - 0.001, 1001)
    assert n.all(
        n.fabs(dfe.dMdE(E) / dfi.dMdE(E) - 1.0) < 1e-4
    ), "dMdE for isotropic Hernquist DF does not agree with exact solution"
    return None
//  [python]
def test_eddington_hernquist_dMdE():
    # Test that dMdE for an isotropic Hernquist model is correct by comparing to the exact solution in isotropicHernquist
    pot = potential.HernquistPotential(amp=1.3, a=2.3)
    dfe = eddingtondf(pot=pot)
    dfi = isotropicHernquistdf(pot)
    Emin = pot(0.0, 0.0)
    Emax = pot(numpy.inf, 0.0)
    E = numpy.linspace(0.99 * Emin, Emax - 0.001, 1001)
    assert numpy.all(
        numpy.fabs(dfe.dMdE(E) / dfi.dMdE(E) - 1.0) < 1e-4
    ), "dMdE for isotropic Hernquist DF does not agree with exact solution"
    return None
//  [python]
def test_osipkovmerritt_selfconsist_dehnencore_Qoutofbounds():
    pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    ras = [2.3, 5.7]
    for ra, dfh in zip(ras, osipkovmerritt_dfs_selfconsist):
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E < -GM/a does not give zero"
        assert n.all(
            n.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at Q < 0 does not give zero"
    return None
//  [python]
def test_osipkovmerritt_selfconsist_dehnencore_Qoutofbounds():
    pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    ras = [2.3, 5.7]
    for ra, dfh in zip(ras, osipkovmerritt_dfs_selfconsist):
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E < -GM/a does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at Q < 0 does not give zero"
    return None
//  [python]
def test_osipkovmerritt_dehnencore_in_nfw_Qoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    ras = [2.3, 5.7]
    for ra, dfh in zip(ras, osipkovmerritt_dfs_dehnencore_in_nfw):
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E < -GM/a does not give zero"
        assert n.all(
            n.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at Q < 0 does not give zero"
    return None
//  [python]
def test_osipkovmerritt_dehnencore_in_nfw_Qoutofbounds():
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    ras = [2.3, 5.7]
    for ra, dfh in zip(ras, osipkovmerritt_dfs_dehnencore_in_nfw):
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at E < -GM/a does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the Osipkov-Merritt DF at Q < 0 does not give zero"
    return None
//  [python]
def check_dens_directint(dfi, pot, tol, dens, rmin=None, rmax=None, bins=31):
    """Check that the density obtained from integrating over the DF agrees
    with the expected density"""
    rs = numpy.linspace(rmin, rmax, bins)
    intdens = numpy.array([dfi.vmomentdensity(r, 0, 0) for r in rs])
    expdens = numpy.array([dens(r) for r in rs])
    assert n.all(
        n.fabs(intdens / expdens - 1.0) < tol
    ), "Density from direct integration is not equal to the expected value"
    return None
//  [python]
def check_dens_directint(dfi, pot, tol, dens, rmin=None, rmax=None, bins=31):
    """Check that the density obtained from integrating over the DF agrees
    with the expected density"""
    rs = numpy.linspace(rmin, rmax, bins)
    intdens = numpy.array([dfi.vmomentdensity(r, 0, 0) for r in rs])
    expdens = numpy.array([dens(r) for r in rs])
    assert numpy.all(
        numpy.fabs(intdens / expdens - 1.0) < tol
    ), "Density from direct integration is not equal to the expected value"
    return None
//  [python]
def check_meanvr_directint(dfi, pot, tol, beta=0.0, rmin=None, rmax=None, bins=31):
    """Check that the mean v_r(r) obtained from integrating over the DF agrees
    with the expected zero"""
    rs = numpy.linspace(rmin, rmax, bins)
    intmvr = numpy.array(
        [dfi.vmomentdensity(r, 1, 0) / dfi.vmomentdensity(r, 0, 0) for r in rs]
    )
    assert n.all(
        n.fabs(intmvr) < tol
    ), "mean v_r(r) from direct integration is not zero"
    return None
//  [python]
def check_meanvr_directint(dfi, pot, tol, beta=0.0, rmin=None, rmax=None, bins=31):
    """Check that the mean v_r(r) obtained from integrating over the DF agrees
    with the expected zero"""
    rs = numpy.linspace(rmin, rmax, bins)
    intmvr = numpy.array(
        [dfi.vmomentdensity(r, 1, 0) / dfi.vmomentdensity(r, 0, 0) for r in rs]
    )
    assert numpy.all(
        numpy.fabs(intmvr) < tol
    ), "mean v_r(r) from direct integration is not zero"
    return None
//  [python]
def test_constantbeta_dehnencore_in_nfw_Qoutofbounds():
    if WIN32:
        return None  # skip on Windows, because no JAX
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    betas = [0.25]
    for beta, dfh in zip(betas, constantbeta_dfs_dehnencore_in_nfw):
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the constantbeta DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the constantbeta DF at E < -GM/a does not give zero"
        assert n.all(
            n.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the constantbeta DF at Q < 0 does not give zero"
    return None
//  [python]
def test_constantbeta_dehnencore_in_nfw_Qoutofbounds():
    if WIN32:
        return None  # skip on Windows, because no JAX
    pot = potential.NFWPotential(amp=2.3, a=1.3)
    denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    betas = [0.25]
    for beta, dfh in zip(betas, constantbeta_dfs_dehnencore_in_nfw):
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the constantbeta DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the constantbeta DF at E < -GM/a does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the constantbeta DF at Q < 0 does not give zero"
    return None
//  [python]
def test_constantbeta_selfconsist_dehnencore_Qoutofbounds(
    setup_constantbeta_dfs_selfconsist,
):
    if WIN32:
        return None  # skip on Windows, because no JAX
    pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    twobetas = [-1]
    constantbeta_dfs_selfconsist = setup_constantbeta_dfs_selfconsist
    for twobeta, dfh in zip(twobetas, constantbeta_dfs_selfconsist):
        assert n.all(
            n.fabs(dfh((n.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the constant-beta DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert n.all(
            n.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the constant-beta DF at E < -GM/a does not give zero"
        assert n.all(
            n.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the constantbeta DF at Q < 0 does not give zero"
    return None
//  [python]
def test_constantbeta_selfconsist_dehnencore_Qoutofbounds(
    setup_constantbeta_dfs_selfconsist,
):
    if WIN32:
        return None  # skip on Windows, because no JAX
    pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
    twobetas = [-1]
    constantbeta_dfs_selfconsist = setup_constantbeta_dfs_selfconsist
    for twobeta, dfh in zip(twobetas, constantbeta_dfs_selfconsist):
        assert numpy.all(
            numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1), 1.1))) < 1e-8
        ), "Evaluating the constant-beta DF at E > 0 does not give zero"
        # The next one is not actually a physical orbit...
        assert numpy.all(
            numpy.fabs(dfh((pot(0, 0) - 1e-1, 0.1))) < 1e-8
        ), "Evaluating the constant-beta DF at E < -GM/a does not give zero"
        assert numpy.all(
            numpy.fabs(dfh((-1e-4, 1.1))) < 1e-8
        ), "Evaluating the constantbeta DF at Q < 0 does not give zero"
    return None
//  [python]
def check_sigmar_against_jeans_directint(
    dfi, pot, tol, beta=0.0, dens=None, rmin=None, rmax=None, bins=31
):
    """Check that sigma_r(r) obtained from integrating over the DF agrees
    with that coming from the Jeans equation"""
    rs = numpy.linspace(rmin, rmax, bins)
    intsr = numpy.array([dfi.sigmar(r, use_physical=False) for r in rs])
    jeanssr = numpy.array(
        [jeans.sigmar(pot, r, beta=beta, dens=dens, use_physical=False) for r in rs]
    )
    assert n.all(
        n.fabs(intsr / jeanssr - 1) < tol
    ), "sigma_r(r) from direct integration does not agree with that obtained from the Jeans equation"
    return None
//  [python]
def check_sigmar_against_jeans_directint(
    dfi, pot, tol, beta=0.0, dens=None, rmin=None, rmax=None, bins=31
):
    """Check that sigma_r(r) obtained from integrating over the DF agrees
    with that coming from the Jeans equation"""
    rs = numpy.linspace(rmin, rmax, bins)
    intsr = numpy.array([dfi.sigmar(r, use_physical=False) for r in rs])
    jeanssr = numpy.array(
        [jeans.sigmar(pot, r, beta=beta, dens=dens, use_physical=False) for r in rs]
    )
    assert numpy.all(
        numpy.fabs(intsr / jeanssr - 1) < tol
    ), "sigma_r(r) from direct integration does not agree with that obtained from the Jeans equation"
    return None
//  [python]
def test_imread_against_scipy_misc():
    try:
        import scipy.misc
    except ImportError:
        pytest.skip('scipy.misc not installed')

    for filename in all_test_images:
        a = scipy.misc.imread(filename)
        b = qimage2ndarray.imread(filename)
        assert a.shape == b.shape
        assert numpy.alltrue(a == b)
//  [python]
def test_imread_against_scipy_misc():
    try:
        import scipy.misc
    except ImportError:
        pytest.skip('scipy.misc not installed')

    for filename in all_test_images:
        a = scipy.misc.imread(filename)
        b = qimage2ndarray.imread(filename)
        assert a.shape == b.shape
        assert numpy.all(a == b)
//  [python]
def test_imread_against_scipy_ndimage():
    try:
        import scipy.ndimage
    except ImportError:
        pytest.skip('scipy.ndimage not installed')

    for filename in all_test_images:
        a = scipy.ndimage.imread(filename)
        b = qimage2ndarray.imread(filename)
        assert a.shape == b.shape
        assert numpy.all(a == b)
//  [python]
def check_beta_directint(dfi, tol, beta=0.0, rmin=None, rmax=None, bins=31):
    """Check that beta(r) obtained from integrating over the DF agrees
    with the expected behavior"""
    rs = numpy.linspace(rmin, rmax, bins)
    intbeta = numpy.array([dfi.beta(r) for r in rs])
    if not callable(beta):
        beta_func = lambda r: beta
    else:
        beta_func = beta
    assert n.all(
        n.fabs(intbeta - beta_func(rs)) < tol
    ), "beta(r) from direct integration does not agree with the expected value"
    return None
//  [python]
def check_beta_directint(dfi, tol, beta=0.0, rmin=None, rmax=None, bins=31):
    """Check that beta(r) obtained from integrating over the DF agrees
    with the expected behavior"""
    rs = numpy.linspace(rmin, rmax, bins)
    intbeta = numpy.array([dfi.beta(r) for r in rs])
    if not callable(beta):
        beta_func = lambda r: beta
    else:
        beta_func = beta
    assert numpy.all(
        numpy.fabs(intbeta - beta_func(rs)) < tol
    ), "beta(r) from direct integration does not agree with the expected value"
    return None
//  [python]
def test_imread_against_matplotlib():
    try:
        import matplotlib.pyplot
    except ImportError:
        pytest.skip('matplotlib not installed')

    for filename in all_test_images:
        a = matplotlib.pyplot.imread(filename)
        b = qimage2ndarray.imread(filename)
        assert a.shape == b.shape
        if a.max() == 1.0: # strange MPL API: only the PNG has 0..1.0 range
            a *= 255
        assert numpy.alltrue(numpy.abs(a - b) < 1e-8)
//  [python]
def test_imread_against_matplotlib():
    try:
        import matplotlib.pyplot
    except ImportError:
        pytest.skip('matplotlib not installed')

    for filename in all_test_images:
        a = matplotlib.pyplot.imread(filename)
        b = qimage2ndarray.imread(filename)
        assert a.shape == b.shape
        if a.max() == 1.0: # strange MPL API: only the PNG has 0..1.0 range
            a *= 255
        assert numpy.all(numpy.abs(a - b) < 1e-8)
//  [python]
def check_sigmar_against_jeans_directint_forcevmoment(
    dfi, pot, tol, beta=0.0, rmin=None, rmax=None, bins=31
):
    """Check that sigma_r(r) obtained from integrating over the DF agrees
    with that coming from the Jeans equation, using the general sphericaldf
    class' vmomentdensity"""
    from galpy.df.sphericaldf import sphericaldf
    import numpy as n

    rs = n.linspace(rmin, rmax, bins)
    intsr = n.array(
        [
            n.sqrt(
                sphericaldf._vmomentdensity(dfi, r, 2, 0)
                / sphericaldf._vmomentdensity(dfi, r, 0, 0)
            )
            for r in rs
        ]
    )
    jeanssr = n.array(
        [jeans.sigmar(pot, r, beta=beta, use_physical=False) for r in rs]
    )
    assert n.all(
        n.fabs(intsr / jeanssr - 1) < tol
    ), "sigma_r(r) from direct integration does not agree with that obtained from the Jeans equation"
    return None
//  [python]
def check_sigmar_against_jeans_directint_forcevmoment(
    dfi, pot, tol, beta=0.0, rmin=None, rmax=None, bins=31
):
    """Check that sigma_r(r) obtained from integrating over the DF agrees
    with that coming from the Jeans equation, using the general sphericaldf
    class' vmomentdensity"""
    from galpy.df.sphericaldf import sphericaldf

    rs = numpy.linspace(rmin, rmax, bins)
    intsr = numpy.array(
        [
            numpy.sqrt(
                sphericaldf._vmomentdensity(dfi, r, 2, 0)
                / sphericaldf._vmomentdensity(dfi, r, 0, 0)
            )
            for r in rs
        ]
    )
    jeanssr = numpy.array(
        [jeans.sigmar(pot, r, beta=beta, use_physical=False) for r in rs]
    )
    assert numpy.all(
        numpy.fabs(intsr / jeanssr - 1) < tol
    ), "sigma_r(r) from direct integration does not agree with that obtained from the Jeans equation"
    return None
//  [python]
def test_basic(self):
        A = np.array([[1, 2], [3, 4]])
        mA = matrix(A)
        assert_(np.all(mA.A == A))

        B = bmat("A,A;A,A")
        C = bmat([[A, A], [A, A]])
        D = np.array([[1, 2, 1, 2],
                      [3, 4, 3, 4],
                      [1, 2, 1, 2],
                      [3, 4, 3, 4]])
        assert_(np.all(B.A == D))
        assert_(np.all(C.A == D))

        E = np.array([[5, 6], [7, 8]])
        AEresult = matrix([[1, 2, 5, 6], [3, 4, 7, 8]])
        assert_(np.all(bmat([A, E]) == AEresult))

        vec = np.arange(5)
        mvec = matrix(vec)
        assert_(mvec.shape == (1, 5))
//  [python]
def test_ptp(self):
        x = np.arange(4).reshape((2, 2))
        assert_(x.ptp() == 3)
        assert_(x.ptp(0).all() == np.array([2, 2]).all())
        assert_(x.ptp(1).all() == np.array([1, 1]).all())
//  [python]
def test_ptp(self):
        x = np.arange(4).reshape((2, 2))
        assert_(x.ptp() == 3)
        assert_(np.all(x.ptp(0) == np.array([2, 2])))
        assert_(np.all(x.ptp(1) == np.array([1, 1])))
//  [python]
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.],
                      [3., 4.]])
        mA = matrix(A)
        assert_(np.allclose(linalg.inv(A), mA.I))
        assert_(n.all(np.array(np.transpose(A) == mA.T)))
        assert_(n.all(np.array(np.transpose(A) == mA.H)))
        assert_(n.all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(np.allclose(linalg.inv(B), mB.I))
        assert_(n.all(np.array(np.transpose(B) == mB.T)))
        assert_(n.all(np.array(np.transpose(B).conj() == mB.H)))
//  [python]
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.],
                      [3., 4.]])
        mA = matrix(A)
        assert_(np.allclose(linalg.inv(A), mA.I))
        assert_(np.all(np.array(np.transpose(A) == mA.T)))
        assert_(np.all(np.array(np.transpose(A) == mA.H)))
        assert_(np.all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(np.allclose(linalg.inv(B), mB.I))
        assert_(np.all(np.array(np.transpose(B) == mB.T)))
        assert_(np.all(np.array(np.transpose(B).conj() == mB.H)))
//  [python]
def test_bmat_nondefault_str(self):
        A = np.array([[1, 2], [3, 4]])
        B = np.array([[5, 6], [7, 8]])
        Aresult = np.array([[1, 2, 1, 2],
                            [3, 4, 3, 4],
                            [1, 2, 1, 2],
                            [3, 4, 3, 4]])
        mixresult = np.array([[1, 2, 5, 6],
                              [3, 4, 7, 8],
                              [5, 6, 1, 2],
                              [7, 8, 3, 4]])
        assert_(n.all(bmat("A,A;A,A") == Aresult))
        assert_(n.all(bmat("A,A;A,A", ldict={'A':B}) == Aresult))
        assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A':B})
        assert_(
            n.all(bmat("A,A;A,A", ldict={'A':A}, gdict={'A':B}) == Aresult))
        b2 = bmat("A,B;C,D", ldict={'A':A,'B':B}, gdict={'C':B,'D':A})
        assert_(n.all(b2 == mixresult))
//  [python]
def test_bmat_nondefault_str(self):
        A = np.array([[1, 2], [3, 4]])
        B = np.array([[5, 6], [7, 8]])
        Aresult = np.array([[1, 2, 1, 2],
                            [3, 4, 3, 4],
                            [1, 2, 1, 2],
                            [3, 4, 3, 4]])
        mixresult = np.array([[1, 2, 5, 6],
                              [3, 4, 7, 8],
                              [5, 6, 1, 2],
                              [7, 8, 3, 4]])
        assert_(np.all(bmat("A,A;A,A") == Aresult))
        assert_(np.all(bmat("A,A;A,A", ldict={'A':B}) == Aresult))
        assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A':B})
        assert_(
            np.all(bmat("A,A;A,A", ldict={'A':A}, gdict={'A':B}) == Aresult))
        b2 = bmat("A,B;C,D", ldict={'A':A,'B':B}, gdict={'C':B,'D':A})
        assert_(np.all(b2 == mixresult))
//  [python]
def test_basic(self):
        A = np.arange(100).reshape(10, 10)
        mA = matrix(A)

        mB = mA.copy()
        O = np.ones((10, 10), np.float64) * 0.1
        mB = mB + O
        assert_(mB.dtype.type == np.float64)
        assert_(not np.any(mA == mB))
        assert_(not np.any(mB != mA+0.1))

        mC = mA.copy()
        O = np.ones((10, 10), np.complex128)
        mC = mC * O
        assert_(mC.dtype.type == np.complex128)
        assert_(not np.any(mA == mB))
//  [python]
def test_basic(self):
        A = np.arange(100).reshape(10, 10)
        mA = matrix(A)

        mB = mA.copy()
        O = np.ones((10, 10), np.float64) * 0.1
        mB = mB + O
        assert_(mB.dtype.type == np.float64)
        assert_(np.all(mA != mB))
        assert_(np.all(mB == mA+0.1))

        mC = mA.copy()
        O = np.ones((10, 10), np.complex128)
        mC = mC * O
        assert_(mC.dtype.type == np.complex128)
        assert_(np.all(mA != mB))
//  [python]
def test_devicearray_partition(self):
        N = 100
        array = np.arange(N, dtype=np.int32)
        original = array.copy()
        gpumem = cuda.to_device(array)
        left, right = gpumem.split(N // 2)

        array[:] = 0

        self.assertTrue(n.all(array == 0))

        right.copy_to_host(array[N // 2:])
        left.copy_to_host(array[:N // 2])

        self.assertTrue(n.all(array == original))
//  [python]
def test_devicearray_partition(self):
        N = 100
        array = np.arange(N, dtype=np.int32)
        original = array.copy()
        gpumem = cuda.to_device(array)
        left, right = gpumem.split(N // 2)

        array[:] = 0

        self.assertTrue(np.all(array == 0))

        right.copy_to_host(array[N // 2:])
        left.copy_to_host(array[:N // 2])

        self.assertTrue(np.all(array == original))
//  [python]
def test_comparisons(self):
        A = np.arange(100).reshape(10, 10)
        mA = matrix(A)
        mB = matrix(A) + 0.1
        assert_(n.all(mB == A+0.1))
        assert_(n.all(mB == matrix(A+0.1)))
        assert_(not n.any(mB == matrix(A-0.1)))
        assert_(n.all(mA < mB))
        assert_(n.all(mA <= mB))
        assert_(n.all(mA <= mA))
        assert_(not n.any(mA < mA))

        assert_(not n.any(mB < mA))
        assert_(n.all(mB >= mA))
        assert_(n.all(mB >= mB))
        assert_(not n.any(mB > mB))

        assert_(n.all(mA == mA))
        assert_(not n.any(mA == mB))
        assert_(n.all(mB != mA))

        assert_(not n.all(abs(mA) > 0))
        assert_(n.all(abs(mB > 0)))
//  [python]
def test_comparisons(self):
        A = np.arange(100).reshape(10, 10)
        mA = matrix(A)
        mB = matrix(A) + 0.1
        assert_(np.all(mB == A+0.1))
        assert_(np.all(mB == matrix(A+0.1)))
        assert_(not np.any(mB == matrix(A-0.1)))
        assert_(np.all(mA < mB))
        assert_(np.all(mA <= mB))
        assert_(np.all(mA <= mA))
        assert_(not np.any(mA < mA))

        assert_(not np.any(mB < mA))
        assert_(np.all(mB >= mA))
        assert_(np.all(mB >= mB))
        assert_(not np.any(mB > mB))

        assert_(np.all(mA == mA))
        assert_(not np.any(mA == mB))
        assert_(np.all(mB != mA))

        assert_(not np.all(abs(mA) > 0))
        assert_(np.all(abs(mB > 0)))
//  [python]
def test_devicearray_transpose_identity(self):
        # any-shape identities should work
        original = np.array(np.arange(24)).reshape(3, 4, 2)
        array = np.transpose(cuda.to_device(original),
                             axes=(0, 1, 2)).copy_to_host()
        self.assertTrue(np.all(array == original))
//  [python]
def set_weight(
        self,
        weight: Optional[_LGBM_WeightType],
    ) -> "Dataset":
        """Set weight of each instance.

        Parameters
        ----------
        weight : list, numpy 1-D array, pandas Series, pyarrow Array, pyarrow ChunkedArray or None
            Weight to be set for each data point. Weights should be non-negative.

        Returns
        -------
        self : Dataset
            Dataset with set weight.
        """
        # Check if the weight contains values other than one
        if weight is not None:
            if _is_pyarrow_array(weight):
                if pa_compute.all(pa_compute.equal(weight, 1)).as_py():
                    weight = None
            elif np.all(weight == 1):
                weight = None
        self.weight = weight

        # Set field
        if self._handle is not None and weight is not None:
            if not _is_pyarrow_array(weight):
                weight = _list_to_1d_numpy(weight, dtype=np.float32, name="weight")
            self.set_field("weight", weight)
            self.weight = self.get_field("weight")  # original values can be modified at cpp side
        return self
//  [python]
def test_devicearray_transpose_ok(self):
        original = np.array(np.arange(12)).reshape(3, 4)
        array = np.transpose(cuda.to_device(original)).copy_to_host()
        self.assertTrue(np.all(array == original.T))
//  [python]
def test_devicearray_transpose_T(self):
        original = np.array(np.arange(12)).reshape(3, 4)
        array = cuda.to_device(original).T.copy_to_host()
        self.assertTrue(np.all(array == original.T))
//  [python]
def __new__(subtype, data, mask=numpy.ma.nomask, mask_corners=True, 
                data_folded=None, check_folding=True, dtype=float, copy=True, 
                fill_value=numpy.nan, keep_mask=True, shrink=True, 
                pop_ids=None, extrap_x=None):
        data = numpy.asanyarray(data)

        if mask is numpy.ma.nomask:
            mask = numpy.ma.make_mask_none(data.shape)

        subarr = numpy.ma.masked_array(data, mask=mask, dtype=dtype, copy=copy,
                                       fill_value=numpy.nan, keep_mask=True, 
                                       shrink=True)
        subarr = subarr.view(subtype)

        if hasattr(data, 'folded'):
            if data_folded is None or data_folded == data.folded:
                subarr.folded = data.folded
            elif data_folded != data.folded:
                raise ValueError('Data does not have same folding status as '
                                 'was called for in Spectrum constructor.')
        elif data_folded is not None:
            subarr.folded = data_folded
        else:
            subarr.folded = False

        # Check that if we're declaring that the input data is folded, it
        # actually is, and the mask reflects this.
        if data_folded:
            total_samples = numpy.sum(subarr.sample_sizes)
            total_per_entry = subarr._total_per_entry()
            # Which entries are nonsense in the folded fs.
            where_folded_out = total_per_entry > int(total_samples/2)
            if check_folding\
               and not n.all(subarr.data[where_folded_out] == 0):
                logger.warn('Creating Spectrum with data_folded = True, but '
                            'data has non-zero values in entries which are '
                            'nonsensical for a folded Spectrum.')
            if check_folding\
               and not n.all(subarr.mask[where_folded_out]):
                logger.warn('Creating Spectrum with data_folded = True, but '
                            'mask is not True for all entries which are '
                            'nonsensical for a folded Spectrum.')

        if hasattr(data, 'pop_ids'):
            if pop_ids is None or pop_ids == data.pop_ids:
                subarr.pop_ids = data.pop_ids
            elif pop_ids != data.pop_ids:
                logger.warn('Changing population labels in construction of new '
                            'Spectrum.')
                if len(pop_ids) != subarr.ndim:
                    raise ValueError('pop_ids must be of length equal to '
                                     'dimensionality of Spectrum.')
                subarr.pop_ids = pop_ids
        else:
            if pop_ids is not None and len(pop_ids) != subarr.ndim:
                raise ValueError('pop_ids must be of length equal to '
                                 'dimensionality of Spectrum.')
            subarr.pop_ids = pop_ids

        if mask_corners:
            subarr.mask_corners()

        subarr.extrap_x = extrap_x

        return subarr
//  [python]
def __new__(subtype, data, mask=numpy.ma.nomask, mask_corners=True, 
                data_folded=None, check_folding=True, dtype=float, copy=True, 
                fill_value=numpy.nan, keep_mask=True, shrink=True, 
                pop_ids=None, extrap_x=None):
        data = numpy.asanyarray(data)

        if mask is numpy.ma.nomask:
            mask = numpy.ma.make_mask_none(data.shape)

        subarr = numpy.ma.masked_array(data, mask=mask, dtype=dtype, copy=copy,
                                       fill_value=numpy.nan, keep_mask=True, 
                                       shrink=True)
        subarr = subarr.view(subtype)

        if hasattr(data, 'folded'):
            if data_folded is None or data_folded == data.folded:
                subarr.folded = data.folded
            elif data_folded != data.folded:
                raise ValueError('Data does not have same folding status as '
                                 'was called for in Spectrum constructor.')
        elif data_folded is not None:
            subarr.folded = data_folded
        else:
            subarr.folded = False

        # Check that if we're declaring that the input data is folded, it
        # actually is, and the mask reflects this.
        if data_folded:
            total_samples = numpy.sum(subarr.sample_sizes)
            total_per_entry = subarr._total_per_entry()
            # Which entries are nonsense in the folded fs.
            where_folded_out = total_per_entry > int(total_samples/2)
            if check_folding\
               and not numpy.all(subarr.data[where_folded_out] == 0):
                logger.warn('Creating Spectrum with data_folded = True, but '
                            'data has non-zero values in entries which are '
                            'nonsensical for a folded Spectrum.')
            if check_folding\
               and not numpy.all(subarr.mask[where_folded_out]):
                logger.warn('Creating Spectrum with data_folded = True, but '
                            'mask is not True for all entries which are '
                            'nonsensical for a folded Spectrum.')

        if hasattr(data, 'pop_ids'):
            if pop_ids is None or pop_ids == data.pop_ids:
                subarr.pop_ids = data.pop_ids
            elif pop_ids != data.pop_ids:
                logger.warn('Changing population labels in construction of new '
                            'Spectrum.')
                if len(pop_ids) != subarr.ndim:
                    raise ValueError('pop_ids must be of length equal to '
                                     'dimensionality of Spectrum.')
                subarr.pop_ids = pop_ids
        else:
            if pop_ids is not None and len(pop_ids) != subarr.ndim:
                raise ValueError('pop_ids must be of length equal to '
                                 'dimensionality of Spectrum.')
            subarr.pop_ids = pop_ids

        if mask_corners:
            subarr.mask_corners()

        subarr.extrap_x = extrap_x

        return subarr
//  [python]
def _test_devicearray_contiguous_host_copy(self, a_c, a_f):
        """
        Checks host->device memcpys
        """
        self.assertTrue(a_c.flags.c_contiguous)
        self.assertTrue(a_f.flags.f_contiguous)

        for original, copy in [
            (a_f, a_f),
            (a_f, a_c),
            (a_c, a_f),
            (a_c, a_c),
        ]:
            msg = '%s => %s' % (
                'C' if original.flags.c_contiguous else 'F',
                'C' if copy.flags.c_contiguous else 'F',
            )

            d = cuda.to_device(original)
            d.copy_to_device(copy)
            self.assertTrue(n.all(d.copy_to_host() == a_c), msg=msg)
            self.assertTrue(n.all(d.copy_to_host() == a_f), msg=msg)
//  [python]
def _test_devicearray_contiguous_host_copy(self, a_c, a_f):
        """
        Checks host->device memcpys
        """
        self.assertTrue(a_c.flags.c_contiguous)
        self.assertTrue(a_f.flags.f_contiguous)

        for original, copy in [
            (a_f, a_f),
            (a_f, a_c),
            (a_c, a_f),
            (a_c, a_c),
        ]:
            msg = '%s => %s' % (
                'C' if original.flags.c_contiguous else 'F',
                'C' if copy.flags.c_contiguous else 'F',
            )

            d = cuda.to_device(original)
            d.copy_to_device(copy)
            self.assertTrue(np.all(d.copy_to_host() == a_c), msg=msg)
            self.assertTrue(np.all(d.copy_to_host() == a_f), msg=msg)
//  [python]
def test_einsum(backend):
    tb = pyhf.tensorlib
    x = np.arange(20).reshape(5, 4).tolist()

    assert np.all(
        tb.tolist(tb.einsum('ij->ji', tb.astensor(x))) == np.asarray(x).T.tolist()
    )
    assert (
        tb.tolist(tb.einsum('i,j->ij', tb.astensor([1, 1, 1]), tb.astensor([1, 2, 3])))
        == [[1, 2, 3]] * 3
    )
//  [python]
def test_structured_equal(self):
        # https://github.com/numpy/numpy/issues/4855

        class MyA(np.ndarray):
            def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
                return getattr(ufunc, method)(*(input.view(np.ndarray)
                                              for input in inputs), **kwargs)
        a = np.arange(12.).reshape(4,3)
        ra = a.view(dtype=('f8,f8,f8')).squeeze()
        mra = ra.view(MyA)

        target = np.array([ True, False, False, False], dtype=bool)
        assert_equal(np.all(target == (mra == ra[0])), True)
//  [python]
def test_devicearray_contiguous_copy_device(self):
        a_c = np.arange(5 * 5 * 5).reshape(5, 5, 5)
        a_f = np.array(a_c, order='F')
        self.assertTrue(a_c.flags.c_contiguous)
        self.assertTrue(a_f.flags.f_contiguous)

        d = cuda.to_device(a_c)

        with self.assertRaises(ValueError) as e:
            d.copy_to_device(cuda.to_device(a_f))
        self.assertEqual(
            "incompatible strides: {} vs. {}".format(a_c.strides, a_f.strides),
            str(e.exception))

        d.copy_to_device(cuda.to_device(a_c))
        self.assertTrue(np.all(d.copy_to_host() == a_c))

        d = cuda.to_device(a_f)

        with self.assertRaises(ValueError) as e:
            d.copy_to_device(cuda.to_device(a_c))
        self.assertEqual(
            "incompatible strides: {} vs. {}".format(a_f.strides, a_c.strides),
            str(e.exception))

        d.copy_to_device(cuda.to_device(a_f))
        self.assertTrue(np.all(d.copy_to_host() == a_f))
//  [python]
def set_weight(self, weight):
        """Set weight of each instance.

        Parameters
        ----------
        weight : list, numpy 1-D array, pandas Series or None
            Weight to be set for each data point.

        Returns
        -------
        self : Dataset
            Dataset with set weight.
        """
        if weight is not None and n.all(weight == 1):
            weight = None
        self.weight = weight
        if self.handle is not None and weight is not None:
            weight = list_to_1d_numpy(weight, name='weight')
            self.set_field('weight', weight)
            self.weight = self.get_field('weight')  # original values can be modified at cpp side
        return self