jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_nan_sentinels(self):
        all_dtypes = [np.dtype(c) for c in rt.rt_enum.NumpyCharTypes.All]
        nan_dtypes = [
            dt
            for dt in all_dtypes
            if (
                dt.num in rt.rt_enum.INVALID_DICT
                and dt.char not in rt.rt_enum.NumpyCharTypes.Unsupported
                and dt.char != "?"  # bool nan is broken (neither supported nor unsupported)
            )
        ]
        ops = {
            True: ["isnan", "isnanorzero", "isnotfinite"],
            False: ["isnotnan", "isfinite"],
        }

        for dt in nan_dtypes:
            arr = rt.FA([rt.rt_enum.INVALID_DICT[dt.num], 1], dtype=dt)
            try:
                is_nan = isnan(INVALID_DICT[arr.dtype.num])
            except:
                is_nan = False
            if not is_nan:
                self.assertEqual(INVALID_DICT[arr.dtype.num], arr[0], msg=f"failed for {dt!r}")

            for expected, names in ops.items():
                correct = [expected, not expected]

                for name in names:
                    # test the fa.xxx() variant
                    fn = getattr(arr, name)
                    result = fn()
                    self.assertTrue(
                        bool(np.all(result == correct)),
                        msg=f"fa.{name} failed for dtype {dt!r}",
                    )

                    # test the rt.xxx(fa) variant
                    fn = getattr(rt, name)
                    result = fn(arr)
                    self.assertTrue(
                        bool(np.all(result == correct)),
                        msg=f"rt.{name} failed for dtype {dt!r}",
                    )
//  [python]
def test_isclose(self):
        a = FastArray([1, 2, 3, 999], dtype="f8")
        a[1] = np.nan
        x = np.isclose(a, 999)
        self.assertTrue(n.all(x == [False, False, False, True]))
//  [python]
def test_isclose(self):
        a = FastArray([1, 2, 3, 999], dtype="f8")
        a[1] = np.nan
        x = np.isclose(a, 999)
        self.assertTrue(np.all(x == [False, False, False, True]))
//  [python]
def test_twodim(self):
        a = np.asarray(
            [
                [
                    1,
                    2,
                ],
                [3, 4],
            ]
        ).copy(order="F")
        b = np.asarray([[2, 2], [2, 2]]).copy(order="F")
        x = a == b
        y = FastArray(a) == FastArray(b)
        self.assertTrue(x.flags == y.flags)
        self.assertTrue(np.all(x == y._np))
//  [python]
def mse_model(self):
        """
        Mean squared error the model.

        The explained sum of squares divided by the model degrees of freedom.
        """
        if np.all(self.df_model == 0.0):
            return np.full_like(self.ess, np.nan)
        return self.ess/self.df_model
//  [python]
def test_int64_comparisons(self):
        x = 701389446541966656
        y = rt.asarray([x - 1, x, x + 1, x, x, x]).astype(np.uint64)
        z = rt.asarray([-x - 1, -x, -x + 1, x - 1, x, x + 1]).astype(np.int64)
        r = y > z
        self.assertTrue(n.all(r == [True, True, True, True, False, False]))
        r = y >= z
        self.assertTrue(n.all(r == [True, True, True, True, True, False]))
        r = z < y
        self.assertTrue(n.all(r == [True, True, True, True, False, False]))
        r = z == y
        self.assertTrue(n.all(r == [False, False, False, False, True, False]))
//  [python]
def test_int64_comparisons(self):
        x = 701389446541966656
        y = rt.asarray([x - 1, x, x + 1, x, x, x]).astype(np.uint64)
        z = rt.asarray([-x - 1, -x, -x + 1, x - 1, x, x + 1]).astype(np.int64)
        r = y > z
        self.assertTrue(np.all(r == [True, True, True, True, False, False]))
        r = y >= z
        self.assertTrue(np.all(r == [True, True, True, True, True, False]))
        r = z < y
        self.assertTrue(np.all(r == [True, True, True, True, False, False]))
        r = z == y
        self.assertTrue(np.all(r == [False, False, False, False, True, False]))
//  [python]
def mse_resid(self):
        """
        Mean squared error of the residuals.

        The sum of squared residuals divided by the residual degrees of
        freedom.
        """
        if np.all(self.df_resid == 0.0):
            return np.full_like(self.ssr, np.nan)
        return self.ssr/self.df_resid
//  [python]
def mse_total(self):
        """
        Total mean squared error.

        The uncentered total sum of squares divided by the number of
        observations.
        """
        if np.all(self.df_resid + self.df_model == 0.0):
            return np.full_like(self.centered_tss, np.nan)
        if self.k_constant:
            return self.centered_tss / (self.df_resid + self.df_model)
        else:
            return self.uncentered_tss / (self.df_resid + self.df_model)
//  [python]
def test_reduction_with_identity_for_empty(self):
        """Test reductions which are well-defined for empty inputs."""
        assert 0 == rt.FA([], dtype=np.int32).sum()
        assert 0 == rt.FA([], dtype=np.uint8).nansum()
        assert 0 == rt.FA([], dtype=np.float64).nansum()
        assert not rt.FA([], dtype=np.int16).any()
        assert rt.FA([], dtype=np.float32).all()

        # Test cases where dtype explicitly specified.
        assert 0 == rt.FA([], dtype=np.int32).sum(dtype=np.int64)
        assert 0 == rt.FA([], dtype=np.uint8).nansum(dtype=np.int32)
        assert 0 == rt.FA([], dtype=np.float64).nansum(dtype=np.float64)

        # Test the module form (which goes through the ufunc or array_function dispatcher).
        assert 0 == np.sum(rt.FA([], dtype=np.int32))
        assert 0 == np.nansum(rt.FA([], dtype=np.uint8))
        assert 0 == np.nansum(rt.FA([], dtype=np.float64))
        assert not np.any(rt.FA([], dtype=np.int16))
        assert np.all(rt.FA([], dtype=np.float32))

        # Test cases for module form where dtype explicitly specified.
        assert 0 == np.sum(rt.FA([], dtype=np.int32), dtype=np.int64)
        assert 0 == np.nansum(rt.FA([], dtype=np.uint8), dtype=np.int32)
        assert 0 == np.nansum(rt.FA([], dtype=np.float64), dtype=np.float64)
//  [python]
def test_actionAngleTorus_hessian_symm():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    h = aAT.hessianFreqs(jr, jphi, jz, tol=0.0001, nosym=True)[0]
    assert n.all(
        n.fabs((h - h.T) / h) < 0.03
    ), "actionAngleTorus Hessian is not symmetric"
    return None
//  [python]
def test_actionAngleTorus_hessian_symm():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    h = aAT.hessianFreqs(jr, jphi, jz, tol=0.0001, nosym=True)[0]
    assert numpy.all(
        numpy.fabs((h - h.T) / h) < 0.03
    ), "actionAngleTorus Hessian is not symmetric"
    return None
//  [python]
def test_actionAngleTorus_hessian_freqs():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    freqO = aAT.Freqs(jr, jphi, jz)[:3]
    hessO = aAT.hessianFreqs(jr, jphi, jz)[1:4]
    assert n.all(
        n.fabs(n.array(freqO) - n.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods Freqs and hessianFreqs return different frequencies"
    return None
//  [python]
def test_actionAngleTorus_hessian_freqs():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    freqO = aAT.Freqs(jr, jphi, jz)[:3]
    hessO = aAT.hessianFreqs(jr, jphi, jz)[1:4]
    assert numpy.all(
        numpy.fabs(numpy.array(freqO) - numpy.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods Freqs and hessianFreqs return different frequencies"
    return None
//  [python]
def test_actionAngleTorus_jacobian_freqs():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    freqO = aAT.Freqs(jr, jphi, jz)[:3]
    hessO = aAT.xvJacobianFreqs(
        jr, jphi, jz, n.array([0.0]), n.array([1.0]), n.array([2.0])
    )[3:6]
    assert n.all(
        n.fabs(n.array(freqO) - n.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods Freqs and xvJacobianFreqs return different frequencies"
    return None
//  [python]
def test_actionAngleTorus_jacobian_freqs():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    freqO = aAT.Freqs(jr, jphi, jz)[:3]
    hessO = aAT.xvJacobianFreqs(
        jr, jphi, jz, numpy.array([0.0]), numpy.array([1.0]), numpy.array([2.0])
    )[3:6]
    assert numpy.all(
        numpy.fabs(numpy.array(freqO) - numpy.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods Freqs and xvJacobianFreqs return different frequencies"
    return None
//  [python]
def test_actionAngleTorus_hessian_linear():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    h = aAT.hessianFreqs(jr, jphi, jz, tol=0.0001, nosym=True)[0]
    dj = numpy.array([0.02, 0.005, -0.01])
    do_fromhessian = numpy.dot(h, dj)
    O = numpy.array(aAT.Freqs(jr, jphi, jz)[:3])
    do = numpy.array(aAT.Freqs(jr + dj[0], jphi + dj[1], jz + dj[2])[:3]) - O
    assert n.all(
        n.fabs((do_fromhessian - do) / O) < 0.001
    ), "actionAngleTorus Hessian does not return good approximation to dO/dJ"
    return None
//  [python]
def test_actionAngleTorus_hessian_linear():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    h = aAT.hessianFreqs(jr, jphi, jz, tol=0.0001, nosym=True)[0]
    dj = numpy.array([0.02, 0.005, -0.01])
    do_fromhessian = numpy.dot(h, dj)
    O = numpy.array(aAT.Freqs(jr, jphi, jz)[:3])
    do = numpy.array(aAT.Freqs(jr + dj[0], jphi + dj[1], jz + dj[2])[:3]) - O
    assert numpy.all(
        numpy.fabs((do_fromhessian - do) / O) < 0.001
    ), "actionAngleTorus Hessian does not return good approximation to dO/dJ"
    return None
//  [python]
def test_unalignedmath(self):
        mydtypes = [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.int64, np.float32, np.float64]
        for dt in mydtypes:
            for length in [1, 3, 10, 1000]:
                a = arange(length, dtype=dt) + 2
                # come in directly also
                self.assertTrue(
                    n.all(abs(a) == abs(a._np)),
                    msg=f"step 0 func was abs direct dtype:{a.dtype}  stride:{a.strides} {abs(a)} {abs(a._np)}",
                )
                self.assertTrue(
                    n.all(abs(a[1:]) == abs(a[1:]._np)),
                    msg=f"step 0 func was abs direct dtype:{a.dtype}  stride:{a.strides}",
                )
                funclist = [np.abs, np.floor, np.ceil, np.trunc, np.round, np.isnan, np.isfinite, np.negative]
                for func in funclist:
                    self.assertTrue(
                        n.all(func(a) == func(a._np)),
                        msg=f"step 1 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )
                    a = a[1:]
                    self.assertTrue(
                        n.all(func(a) == func(a._np)),
                        msg=f"step 2 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )
                    a = a[::2]
                    self.assertTrue(
                        n.all(func(a) == func(a._np)),
                        msg=f"step 3 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )
                    a = a[::-1]
                    self.assertTrue(
                        n.all(func(a) == func(a._np)),
                        msg=f"step 4 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )

        mydtypes = [np.float32, np.float64]
        for dt in mydtypes:
            a = arange(1000.0, dtype=dt) + 2
            funclist = [np.sqrt, isnotfinite, isnotnan]
            for func in funclist:
                self.assertTrue(
                    n.all(func(a) == func(a._np)), msg=f"step 1 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
                a = a[1:]
                self.assertTrue(
                    n.all(func(a) == func(a._np)), msg=f"step 2 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
                a = a[::2]
                self.assertTrue(
                    n.all(func(a) == func(a._np)), msg=f"step 3 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
                a = a[::-1]
                self.assertTrue(
                    n.all(func(a) == func(a._np)), msg=f"step 4 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
//  [python]
def test_unalignedmath(self):
        mydtypes = [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.int64, np.float32, np.float64]
        for dt in mydtypes:
            for length in [1, 3, 10, 1000]:
                a = arange(length, dtype=dt) + 2
                # come in directly also
                self.assertTrue(
                    np.all(abs(a) == abs(a._np)),
                    msg=f"step 0 func was abs direct dtype:{a.dtype}  stride:{a.strides} {abs(a)} {abs(a._np)}",
                )
                self.assertTrue(
                    np.all(abs(a[1:]) == abs(a[1:]._np)),
                    msg=f"step 0 func was abs direct dtype:{a.dtype}  stride:{a.strides}",
                )
                funclist = [np.abs, np.floor, np.ceil, np.trunc, np.round, np.isnan, np.isfinite, np.negative]
                for func in funclist:
                    self.assertTrue(
                        np.all(func(a) == func(a._np)),
                        msg=f"step 1 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )
                    a = a[1:]
                    self.assertTrue(
                        np.all(func(a) == func(a._np)),
                        msg=f"step 2 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )
                    a = a[::2]
                    self.assertTrue(
                        np.all(func(a) == func(a._np)),
                        msg=f"step 3 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )
                    a = a[::-1]
                    self.assertTrue(
                        np.all(func(a) == func(a._np)),
                        msg=f"step 4 func was {func} {length} dtype:{a.dtype}  stride:{a.strides}",
                    )

        mydtypes = [np.float32, np.float64]
        for dt in mydtypes:
            a = arange(1000.0, dtype=dt) + 2
            funclist = [np.sqrt, isnotfinite, isnotnan]
            for func in funclist:
                self.assertTrue(
                    np.all(func(a) == func(a._np)), msg=f"step 1 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
                a = a[1:]
                self.assertTrue(
                    np.all(func(a) == func(a._np)), msg=f"step 2 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
                a = a[::2]
                self.assertTrue(
                    np.all(func(a) == func(a._np)), msg=f"step 3 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
                a = a[::-1]
                self.assertTrue(
                    np.all(func(a) == func(a._np)), msg=f"step 4 func was {func} dtype:{a.dtype}  stride:{a.strides}"
                )
//  [python]
def test_actionAngleTorus_jacobian_hessian():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    freqO = aAT.hessianFreqs(jr, jphi, jz)[0]
    hessO = aAT.xvJacobianFreqs(
        jr, jphi, jz, n.array([0.0]), n.array([1.0]), n.array([2.0])
    )[2]
    assert n.all(
        n.fabs(n.array(freqO) - n.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods hessianFreqs and xvJacobianFreqs return different Hessians"
    return None
//  [python]
def test_actionAngleTorus_jacobian_hessian():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    freqO = aAT.hessianFreqs(jr, jphi, jz)[0]
    hessO = aAT.xvJacobianFreqs(
        jr, jphi, jz, numpy.array([0.0]), numpy.array([1.0]), numpy.array([2.0])
    )[2]
    assert numpy.all(
        numpy.fabs(numpy.array(freqO) - numpy.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods hessianFreqs and xvJacobianFreqs return different Hessians"
    return None
//  [python]
def test_as_boolean(self):
        a = Vector([1, 0]).as_boolean()
        assert a.is_boolean()
        assert all(a == [True, False])
//  [python]
def test_as_boolean(self):
        a = Vector([1, 0]).as_boolean()
        assert a.is_boolean()
        assert np.all(a == [True, False])
//  [python]
def test_actionAngleTorus_orbit():
    from galpy.actionAngle import actionAngleTorus
    from galpy.orbit import Orbit
    from galpy.potential import MWPotential2014
    import numpy as n

    # Set up instance
    aAT = actionAngleTorus(pot=MWPotential2014, tol=10.0**-5.0)
    jr, jphi, jz = 0.05, 1.1, 0.025
    # First calculate frequencies and the initial RvR
    RvRom = aAT.xvFreqs(
        jr, jphi, jz, n.array([0.0]), n.array([1.0]), n.array([2.0])
    )
    om = RvRom[1:]
    # Angles along an orbit
    ts = n.linspace(0.0, 100.0, 1001)
    angler = ts * om[0]
    anglephi = 1.0 + ts * om[1]
    anglez = 2.0 + ts * om[2]
    # Calculate the orbit using actionAngleTorus
    RvR = aAT(jr, jphi, jz, angler, anglephi, anglez).T
    # Calculate the orbit using orbit integration
    orb = Orbit(
        [
            RvRom[0][0, 0],
            RvRom[0][0, 1],
            RvRom[0][0, 2],
            RvRom[0][0, 3],
            RvRom[0][0, 4],
            RvRom[0][0, 5],
        ]
    )
    orb.integrate(ts, MWPotential2014)
    # Compare
    tol = -3.0
    assert n.all(
        n.fabs(orb.R(ts) - RvR[0]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in R"
    assert n.all(
        n.fabs(orb.vR(ts) - RvR[1]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in vR"
    assert n.all(
        n.fabs(orb.vT(ts) - RvR[2]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in vT"
    assert n.all(
        n.fabs(orb.z(ts) - RvR[3]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in z"
    assert n.all(
        n.fabs(orb.vz(ts) - RvR[4]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in vz"
    assert n.all(
        n.fabs((orb.phi(ts) - RvR[5] + n.pi) % (2.0 * n.pi) - n.pi)
        < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in phi"
    return None
//  [python]
def test_actionAngleTorus_orbit():
    from galpy.actionAngle import actionAngleTorus
    from galpy.orbit import Orbit
    from galpy.potential import MWPotential2014

    # Set up instance
    aAT = actionAngleTorus(pot=MWPotential2014, tol=10.0**-5.0)
    jr, jphi, jz = 0.05, 1.1, 0.025
    # First calculate frequencies and the initial RvR
    RvRom = aAT.xvFreqs(
        jr, jphi, jz, numpy.array([0.0]), numpy.array([1.0]), numpy.array([2.0])
    )
    om = RvRom[1:]
    # Angles along an orbit
    ts = numpy.linspace(0.0, 100.0, 1001)
    angler = ts * om[0]
    anglephi = 1.0 + ts * om[1]
    anglez = 2.0 + ts * om[2]
    # Calculate the orbit using actionAngleTorus
    RvR = aAT(jr, jphi, jz, angler, anglephi, anglez).T
    # Calculate the orbit using orbit integration
    orb = Orbit(
        [
            RvRom[0][0, 0],
            RvRom[0][0, 1],
            RvRom[0][0, 2],
            RvRom[0][0, 3],
            RvRom[0][0, 4],
            RvRom[0][0, 5],
        ]
    )
    orb.integrate(ts, MWPotential2014)
    # Compare
    tol = -3.0
    assert numpy.all(
        numpy.fabs(orb.R(ts) - RvR[0]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in R"
    assert numpy.all(
        numpy.fabs(orb.vR(ts) - RvR[1]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in vR"
    assert numpy.all(
        numpy.fabs(orb.vT(ts) - RvR[2]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in vT"
    assert numpy.all(
        numpy.fabs(orb.z(ts) - RvR[3]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in z"
    assert numpy.all(
        numpy.fabs(orb.vz(ts) - RvR[4]) < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in vz"
    assert numpy.all(
        numpy.fabs((orb.phi(ts) - RvR[5] + numpy.pi) % (2.0 * numpy.pi) - numpy.pi)
        < 10.0**tol
    ), "Integrated orbit does not agree with torus orbit in phi"
    return None
//  [python]
def test_actionAngleTorus_jacobian_xv():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    angler = numpy.array([0.0, 1.0])
    anglephi = numpy.array([1.0, 2.0])
    anglez = numpy.array([2.0, 3.0])
    freqO = aAT(jr, jphi, jz, angler, anglephi, anglez)
    hessO = aAT.xvJacobianFreqs(jr, jphi, jz, angler, anglephi, anglez)[0]
    assert n.all(
        n.fabs(n.array(freqO) - n.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods __call__ and xvJacobianFreqs return different xv"
    return None
//  [python]
def test_actionAngleTorus_jacobian_xv():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    angler = numpy.array([0.0, 1.0])
    anglephi = numpy.array([1.0, 2.0])
    anglez = numpy.array([2.0, 3.0])
    freqO = aAT(jr, jphi, jz, angler, anglephi, anglez)
    hessO = aAT.xvJacobianFreqs(jr, jphi, jz, angler, anglephi, anglez)[0]
    assert numpy.all(
        numpy.fabs(numpy.array(freqO) - numpy.array(hessO)) < 10.0**-8.0
    ), "actionAngleTorus methods __call__ and xvJacobianFreqs return different xv"
    return None
//  [python]
def test_as_bytes(self):
        a = Vector([0, 1]).as_bytes()
        assert a.is_bytes()
        assert n.all(a == [b"0", b"1"])
//  [python]
def test_as_bytes(self):
        a = Vector([0, 1]).as_bytes()
        assert a.is_bytes()
        assert np.all(a == [b"0", b"1"])
//  [python]
def test_actionAngleTorus_jacobian_linear():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014
    import numpy as n

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    angler = n.array([0.5])
    anglephi = n.array([1.0])
    anglez = n.array([2.0])
    jf = aAT.xvJacobianFreqs(jr, jphi, jz, angler, anglephi, anglez)
    xv = aAT(jr, jphi, jz, angler, anglephi, anglez)
    dja = 2.0 * n.array([0.001, 0.002, 0.003, -0.002, 0.004, 0.002])
    xv_direct = aAT(
        jr + dja[0],
        jphi + dja[1],
        jz + dja[2],
        angler + dja[3],
        anglephi + dja[4],
        anglez + dja[5],
    )
    xv_fromjac = xv + n.dot(jf[1], dja)
    assert n.all(
        n.fabs((xv_fromjac - xv_direct) / xv_direct) < 0.01
    ), "Jacobian returned by actionAngleTorus method xvJacobianFreqs does not appear to be correct"
    return None
//  [python]
def test_actionAngleTorus_jacobian_linear():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import MWPotential2014

    aAT = actionAngleTorus(pot=MWPotential2014)
    jr, jphi, jz = 0.075, 1.1, 0.05
    angler = numpy.array([0.5])
    anglephi = numpy.array([1.0])
    anglez = numpy.array([2.0])
    jf = aAT.xvJacobianFreqs(jr, jphi, jz, angler, anglephi, anglez)
    xv = aAT(jr, jphi, jz, angler, anglephi, anglez)
    dja = 2.0 * numpy.array([0.001, 0.002, 0.003, -0.002, 0.004, 0.002])
    xv_direct = aAT(
        jr + dja[0],
        jphi + dja[1],
        jz + dja[2],
        angler + dja[3],
        anglephi + dja[4],
        anglez + dja[5],
    )
    xv_fromjac = xv + numpy.dot(jf[1], dja)
    assert numpy.all(
        numpy.fabs((xv_fromjac - xv_direct) / xv_direct) < 0.01
    ), "Jacobian returned by actionAngleTorus method xvJacobianFreqs does not appear to be correct"
    return None
//  [python]
def test_as_date(self):
        a = Vector([DATETIME]).as_date()
        assert a.is_datetime()
        assert n.all(a == [np.datetime64(DATE, "D")])
//  [python]
def test_as_date(self):
        a = Vector([DATETIME]).as_date()
        assert a.is_datetime()
        assert np.all(a == [np.datetime64(DATE, "D")])
//  [python]
def test_as_bytes_string(self):
        a = Vector(["a", "ö"]).as_bytes()
        assert a.is_bytes()
        assert all(a == [b"a", b"\xc3\xb6"])
//  [python]
def test_as_bytes_string(self):
        a = Vector(["a", "ö"]).as_bytes()
        assert a.is_bytes()
        assert np.all(a == [b"a", b"\xc3\xb6"])
//  [python]
def test_as_datetime(self):
        a = Vector([DATETIME]).as_datetime()
        assert a.is_datetime()
        assert a == [np.datetime64(DATETIME, "us")]
//  [python]
def test_as_datetime(self):
        a = Vector([DATETIME]).as_datetime()
        assert a.is_datetime()
        assert np.all(a == [np.datetime64(DATETIME, "us")])
//  [python]
def test_as_datetime_precision(self):
        a = Vector([DATETIME]).as_datetime("s")
        assert a.is_datetime()
        assert all(a == [np.datetime64(DATETIME, "s")])
//  [python]
def test_as_datetime_precision(self):
        a = Vector([DATETIME]).as_datetime("s")
        assert a.is_datetime()
        assert np.all(a == [np.datetime64(DATETIME, "s")])
//  [python]
def test_actionAngleTorus_basic():
    from galpy.actionAngle import actionAngleTorus
    from galpy.potential import (
        FlattenedPowerPotential,
        MWPotential,
        PlummerPotential,
        rl,
        vcirc,
    )
    import numpy as n

    tol = -4.0
    jr = 10.0**-10.0
    jz = 10.0**-10.0
    aAT = actionAngleTorus(pot=MWPotential)
    # at R=1, Lz=1
    jphi = 1.0
    angler = n.linspace(0.0, 2.0 * n.pi, 101)
    anglephi = n.linspace(0.0, 2.0 * n.pi, 101) + 1.0
    anglez = n.linspace(0.0, 2.0 * n.pi, 101) + 2.0
    RvR = aAT(jr, jphi, jz, angler, anglephi, anglez).T
    assert n.all(
        n.fabs(RvR[0] - rl(MWPotential, jphi)) < 10.0**tol
    ), "circular orbit does not have constant radius for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[1]) < 10.0**tol
    ), "circular orbit does not have zero radial velocity for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[2] - vcirc(MWPotential, rl(MWPotential, jphi))) < 10.0**tol
    ), "circular orbit does not have constant vT=vc for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[3]) < 10.0**tol
    ), "circular orbit does not have zero vertical height for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[4]) < 10.0**tol
    ), "circular orbit does not have zero vertical velocity for actionAngleTorus"
    # at Lz=1.5, using Plummer
    tol = -3.25
    pp = PlummerPotential(normalize=1.0)
    aAT = actionAngleTorus(pot=pp)
    jphi = 1.5
    RvR = aAT(jr, jphi, jz, angler, anglephi, anglez).T
    assert n.all(
        n.fabs(RvR[0] - rl(pp, jphi)) < 10.0**tol
    ), "circular orbit does not have constant radius for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[1]) < 10.0**tol
    ), "circular orbit does not have zero radial velocity for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[2] - vcirc(pp, rl(pp, jphi))) < 10.0**tol
    ), "circular orbit does not have constant vT=vc for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[3]) < 10.0**tol
    ), "circular orbit does not have zero vertical height for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[4]) < 10.0**tol
    ), "circular orbit does not have zero vertical velocity for actionAngleTorus"
    # at Lz=0.5, using FlattenedPowerPotential
    tol = -4.0
    fp = FlattenedPowerPotential(normalize=1.0)
    aAT = actionAngleTorus(pot=fp)
    jphi = 0.5
    RvR = aAT(jr, jphi, jz, angler, anglephi, anglez).T
    assert n.all(
        n.fabs(RvR[0] - rl(fp, jphi)) < 10.0**tol
    ), "circular orbit does not have constant radius for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[1]) < 10.0**tol
    ), "circular orbit does not have zero radial velocity for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[2] - vcirc(fp, rl(fp, jphi))) < 10.0**tol
    ), "circular orbit does not have constant vT=vc for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[3]) < 10.0**tol
    ), "circular orbit does not have zero vertical height for actionAngleTorus"
    assert n.all(
        n.fabs(RvR[4]) < 10.0**tol
    ), "circular orbit does not have zero vertical velocity for actionAngleTorus"
    return None
//  [python]
def test_as_float(self):
        a = Vector([1, 2]).as_float()
        assert a.is_float()
        assert n.all(a == [1.0, 2.0])
//  [python]
def test_as_float(self):
        a = Vector([1, 2]).as_float()
        assert a.is_float()
        assert np.all(a == [1.0, 2.0])
//  [python]
def _generate_toy_data(trans_prob, n_traj=1000, n_frames=1000, seed=None, cluster=True):
    from htmd.metricdata import MetricData
    from pandas import DataFrame

    assert n.all((n.sum(trans_prob, axis=1)) - 1 < 1e-15)

    # Create real transition probability matrix
    n_states = trans_prob.shape[0]

    # Generate fake trajectories from it
    dat = []
    ref = []
    if seed is not None:
        np.random.seed(seed)

    for i in range(n_traj):  # ntraj
        trajref = np.zeros((n_frames, 2), dtype=np.int32)
        trajref[:, 0] = i
        trajref[:, 1] = np.arange(n_frames)
        trajdat = np.zeros((n_frames, n_states), dtype=np.int32)
        curr_state = np.random.randint(0, n_states)
        trajdat[0, curr_state] = 1
        for j in range(1, n_frames):  # nsteps
            curr_state = np.random.choice(n_states, p=trans_prob[curr_state])
            trajdat[j, curr_state] = 1
        dat.append(trajdat)
        ref.append(trajref)

    # Create fake test data
    data = MetricData(dat=dat, ref=ref)
    data._dataid = "fake"
    data.fstep = 1

    if cluster:
        for traj in data.trajectories:
            traj.cluster = np.where(traj.projection)[1].copy()
        data._clusterid = "fake"
        data.K = n_states
        data.N = np.bincount(np.concatenate(data.St))
        data.Centers = np.zeros((n_states, n_states), dtype=np.int32)

    types = ["coordinate"] * n_states
    indexes = np.arange(n_states)
    description = ["coordinate"] * n_states
    data.description = DataFrame(
        {"type": types, "atomIndexes": indexes, "description": description}
    )

    return data
//  [python]
def _generate_toy_data(trans_prob, n_traj=1000, n_frames=1000, seed=None, cluster=True):
    from htmd.metricdata import MetricData
    from pandas import DataFrame

    assert np.all((np.sum(trans_prob, axis=1)) - 1 < 1e-15)

    # Create real transition probability matrix
    n_states = trans_prob.shape[0]

    # Generate fake trajectories from it
    dat = []
    ref = []
    if seed is not None:
        np.random.seed(seed)

    for i in range(n_traj):  # ntraj
        trajref = np.zeros((n_frames, 2), dtype=np.int32)
        trajref[:, 0] = i
        trajref[:, 1] = np.arange(n_frames)
        trajdat = np.zeros((n_frames, n_states), dtype=np.int32)
        curr_state = np.random.randint(0, n_states)
        trajdat[0, curr_state] = 1
        for j in range(1, n_frames):  # nsteps
            curr_state = np.random.choice(n_states, p=trans_prob[curr_state])
            trajdat[j, curr_state] = 1
        dat.append(trajdat)
        ref.append(trajref)

    # Create fake test data
    data = MetricData(dat=dat, ref=ref)
    data._dataid = "fake"
    data.fstep = 1

    if cluster:
        for traj in data.trajectories:
            traj.cluster = np.where(traj.projection)[1].copy()
        data._clusterid = "fake"
        data.K = n_states
        data.N = np.bincount(np.concatenate(data.St))
        data.Centers = np.zeros((n_states, n_states), dtype=np.int32)

    types = ["coordinate"] * n_states
    indexes = np.arange(n_states)
    description = ["coordinate"] * n_states
    data.description = DataFrame(
        {"type": types, "atomIndexes": indexes, "description": description}
    )

    return data
//  [python]
def test_as_object(self):
        a = Vector([1, 2]).as_object()
        assert a.is_object()
        assert n.all(a == [1, 2])
//  [python]
def test_as_object(self):
        a = Vector([1, 2]).as_object()
        assert a.is_object()
        assert np.all(a == [1, 2])
//  [python]
def test_as_integer(self):
        a = Vector([1.1, 2.2]).as_integer()
        assert a.is_integer()
        assert n.all(a == [1, 2])
//  [python]
def test_as_integer(self):
        a = Vector([1.1, 2.2]).as_integer()
        assert a.is_integer()
        assert np.all(a == [1, 2])
//  [python]
def test_as_string(self):
        a = Vector([1, 2]).as_string()
        assert a.is_string()
        assert all(a == ["1", "2"])
//  [python]
def test_as_string(self):
        a = Vector([1, 2]).as_string()
        assert a.is_string()
        assert np.all(a == ["1", "2"])
//  [python]
def test_sample(self):
        a = Vector([1, 2, 3, 4, 5])
        assert all(np.isin(a.sample(3), a))
        assert a.sample(5).tolist() == [1, 2, 3, 4, 5]
//  [python]
def test_sample(self):
        a = Vector([1, 2, 3, 4, 5])
        assert np.all(np.isin(a.sample(3), a))
        assert a.sample(5).tolist() == [1, 2, 3, 4, 5]
//  [python]
def __eq__(self, other):
        """Return ``self == other``."""
        # Implemented separately for performance reasons
        if other is self:
            return True
        elif not isinstance(other, IntervalProd):
            return False

        return (n.all(self.min_pt == other.min_pt) and
                n.all(self.max_pt == other.max_pt))
//  [python]
def __eq__(self, other):
        """Return ``self == other``."""
        # Implemented separately for performance reasons
        if other is self:
            return True
        elif not isinstance(other, IntervalProd):
            return False

        return (np.all(self.min_pt == other.min_pt) and
                np.all(self.max_pt == other.max_pt))
//  [python]
def all(self, axis=None, **kwargs):
        return n.all(n.array(self), axis=axis, **kwargs)
//  [python]
def all(self, axis=None, **kwargs):
        return np.all(np.array(self), axis=axis, **kwargs)
//  [python]
def test_masked(image, measurements, module, objects, workspace):
    """Make sure we can process a completely masked image
    Regression test of IMG-971
    """
    image.pixel_data = numpy.zeros((10, 10, N_CHANNELS))

    image.mask = numpy.zeros((10, 10), bool)

    objects.segmented = numpy.ones((10, 10), int)

    module.nchannels.value = N_CHANNELS

    module.run(workspace)

    for meas_name in momc.ALL_MEASUREMENTS:
        for c in range(N_CHANNELS):
            feature_name = "%s_%s_%s_c%s" % (
                momc.INTENSITY,
                meas_name,
                "MyImage",
                c + 1,
            )

            data = measurements.get_current_measurement("MyObjects", feature_name)

            assert numpy.product(data.shape) == 1

            assert n.all(numpy.isnan(data) | (data == 0))

    assert_features_and_columns_match(measurements, module)
//  [python]
def test_masked(image, measurements, module, objects, workspace):
    """Make sure we can process a completely masked image
    Regression test of IMG-971
    """
    image.pixel_data = numpy.zeros((10, 10, N_CHANNELS))

    image.mask = numpy.zeros((10, 10), bool)

    objects.segmented = numpy.ones((10, 10), int)

    module.nchannels.value = N_CHANNELS

    module.run(workspace)

    for meas_name in momc.ALL_MEASUREMENTS:
        for c in range(N_CHANNELS):
            feature_name = "%s_%s_%s_c%s" % (
                momc.INTENSITY,
                meas_name,
                "MyImage",
                c + 1,
            )

            data = measurements.get_current_measurement("MyObjects", feature_name)

            assert numpy.product(data.shape) == 1

            assert numpy.all(numpy.isnan(data) | (data == 0))

    assert_features_and_columns_match(measurements, module)
//  [python]
def test_no_bounds(self):
        x0 = np.zeros(3)
        h = np.full(3, 1e-2)
        inf_lower = np.empty_like(x0)
        inf_upper = np.empty_like(x0)
        inf_lower.fill(-np.inf)
        inf_upper.fill(np.inf)

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 1, '1-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(n.all(one_sided))

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 2, '1-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(n.all(one_sided))

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 1, '2-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(n.all(~one_sided))

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 2, '2-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(n.all(~one_sided))
//  [python]
def test_no_bounds(self):
        x0 = np.zeros(3)
        h = np.full(3, 1e-2)
        inf_lower = np.empty_like(x0)
        inf_upper = np.empty_like(x0)
        inf_lower.fill(-np.inf)
        inf_upper.fill(np.inf)

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 1, '1-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(np.all(one_sided))

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 2, '1-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(np.all(one_sided))

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 1, '2-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(np.all(~one_sided))

        h_adjusted, one_sided = _adjust_scheme_to_bounds(
            x0, h, 2, '2-sided', inf_lower, inf_upper)
        assert_allclose(h_adjusted, h)
        assert_(np.all(~one_sided))
//  [python]
def project(self, M):
        """
        It enlarges a trigonometric polynomial by adding zeros to the Fourier
        coefficients with high frequencies.
        """
        if np.allclose(self.N, M):
            return self
        elif np.alltrue(np.greater(M, self.N)):
            val=np.zeros(np.hstack([self.d, M]), dtype=self.val.dtype)
            if self.Fourier is False:
                for m in np.arange(self.d):
                    val[m]=enlargeF(self.val[m], M)
            else:
                for m in np.arange(self.d):
                    val[m]=enlarge(self.val[m], M)
            return VecTri(name=self.name, val=val, Fourier=self.Fourier)
        elif np.alltrue(np.less(M, self.N)):
            val=np.zeros(np.hstack([self.d, M]), dtype=np.complex)
            if self.Fourier is False:
                Fval=DFT.fftnc(self.val, self.N)
            else:
                Fval=self.val
            for ii in range(self.d):
                val[ii]=decrease(Fval[ii], M)

            if self.Fourier is False:
                val=DFT.ifftnc(val, M).real
            return VecTri(name=self.name, val=val, Fourier=self.Fourier)
        else:
            raise NotImplementedError()
//  [python]
def project(self, M):
        """
        It enlarges a trigonometric polynomial by adding zeros to the Fourier
        coefficients with high frequencies.
        """
        if np.allclose(self.N, M):
            return self
        elif np.all(np.greater(M, self.N)):
            val=np.zeros(np.hstack([self.d, M]), dtype=self.val.dtype)
            if self.Fourier is False:
                for m in np.arange(self.d):
                    val[m]=enlargeF(self.val[m], M)
            else:
                for m in np.arange(self.d):
                    val[m]=enlarge(self.val[m], M)
            return VecTri(name=self.name, val=val, Fourier=self.Fourier)
        elif np.all(np.less(M, self.N)):
            val=np.zeros(np.hstack([self.d, M]), dtype=np.complex)
            if self.Fourier is False:
                Fval=DFT.fftnc(self.val, self.N)
            else:
                Fval=self.val
            for ii in range(self.d):
                val[ii]=decrease(Fval[ii], M)

            if self.Fourier is False:
                val=DFT.ifftnc(val, M).real
            return VecTri(name=self.name, val=val, Fourier=self.Fourier)
        else:
            raise NotImplementedError()
//  [python]
def prob_reaching_terminal_state(terminal_state,  A, root,  n_simulations, q,
                                  cumstateChangeHist, cumstateChangeHist_all, seed):
    # this function is defined outside the VIA class to enable smooth parallel processing in Windows

    n = A.shape[0]

    A /= np.max(A)
    for i, r in enumerate(A):
        if n.all(r == 0):
            A[i, i] = 1
    #ensure probabilities sum to 1 along the rows
    P = A / A.sum(axis=1).reshape((n, 1))

    n_steps, count_reach_terminal_state = 2*n, 0
    for _ in range(n_simulations):
        cur_state = root
        change_hist = np.zeros((n, n))
        change_hist[root, root] = 1

        x, terminal_state_found = 0, False

        while x < n_steps and not terminal_state_found:
            seed+=1
            np.random.seed(seed)
            next_state = np.random.choice(range(P.shape[0]), p=P[cur_state])
            if next_state == terminal_state:
                terminal_state_found = True

            change_hist[cur_state, next_state] += 1
            cur_state = next_state
            x += 1

        if terminal_state_found:
            cumstateChangeHist += np.any(change_hist > 0, axis=0)
            count_reach_terminal_state += 1
        cumstateChangeHist_all += np.any(change_hist > 0, axis=0)

    cumstateChangeHist_all[cumstateChangeHist_all == 0] = 1
    q.append([cumstateChangeHist, cumstateChangeHist_all])
//  [python]
def prob_reaching_terminal_state(terminal_state,  A, root,  n_simulations, q,
                                  cumstateChangeHist, cumstateChangeHist_all, seed):
    # this function is defined outside the VIA class to enable smooth parallel processing in Windows

    n = A.shape[0]

    A /= np.max(A)
    for i, r in enumerate(A):
        if np.all(r == 0):
            A[i, i] = 1
    #ensure probabilities sum to 1 along the rows
    P = A / A.sum(axis=1).reshape((n, 1))

    n_steps, count_reach_terminal_state = 2*n, 0
    for _ in range(n_simulations):
        cur_state = root
        change_hist = np.zeros((n, n))
        change_hist[root, root] = 1

        x, terminal_state_found = 0, False

        while x < n_steps and not terminal_state_found:
            seed+=1
            np.random.seed(seed)
            next_state = np.random.choice(range(P.shape[0]), p=P[cur_state])
            if next_state == terminal_state:
                terminal_state_found = True

            change_hist[cur_state, next_state] += 1
            cur_state = next_state
            x += 1

        if terminal_state_found:
            cumstateChangeHist += np.any(change_hist > 0, axis=0)
            count_reach_terminal_state += 1
        cumstateChangeHist_all += np.any(change_hist > 0, axis=0)

    cumstateChangeHist_all[cumstateChangeHist_all == 0] = 1
    q.append([cumstateChangeHist, cumstateChangeHist_all])
//  [python]
def plot(self, ind=0, N=None, filen=None, Y=None, ptype='surface'):
        dim=self.N.size
        if dim!=2:
            raise ValueError("The plotting is suited only for dim=2!")
        if Y is None:
            Y=np.ones(dim)
        if N is None:
            N=self.N

        from mpl_toolkits.mplot3d import axes3d
        import matplotlib.pyplot as plt
        from ffthompy.trigpol import Grid
        fig=plt.figure()
        coord=Grid.get_coordinates(N, Y)
        if np.all(np.greater(N, self.N)):
            Z=DFT.ifftnc(enlarge(DFT.fftnc(self.val[ind], self.N), N), N).real
        elif np.all(np.less(N, self.N)):
            Z=DFT.ifftnc(decrease(DFT.fftnc(self.val[ind], self.N), N), N).real
        elif np.allclose(N, self.N):
            Z=self.val[ind]

        if ptype in ['wireframe']:
            ax=fig.add_subplot(111, projection='3d')
            ax.plot_wireframe(coord[0], coord[1], Z)
        elif ptype in ['surface']:
            from matplotlib import cm
            ax=fig.gca(projection='3d')
            surf=ax.plot_surface(coord[0], coord[1], Z,
                                   rstride=1, cstride=1, cmap=cm.coolwarm,
                                   linewidth=0, antialiased=False)
            fig.colorbar(surf, shrink=0.5, aspect=5)

        if filen is None:
            plt.show()
        else:
            plt.savefig(filen)
//  [python]
def test_sortcols(self):
        a = np.array([[1, 1], [-2, 2], [-3, 3], [-4, 4], [5, 5]]).T
        s = oapackage.oahelper.sortcols(a)
        self.assertTrue(n.all(s == [3, 2, 1, 0, 4]))
//  [python]
def test_sortcols(self):
        a = np.array([[1, 1], [-2, 2], [-3, 3], [-4, 4], [5, 5]]).T
        s = oapackage.oahelper.sortcols(a)
        self.assertTrue(np.all(s == [3, 2, 1, 0, 4]))
//  [python]
def test_sortrows(self):
        a = np.array([[1, 1], [-2, 2], [-3, 3], [-4, 4], [5, 5]])
        s = oapackage.oahelper.sortrows(a)
        self.assertTrue(np.all(s == [3, 2, 1, 0, 4]))

        x = -np.array([[0, 0, 1], [0, 1, 0], [0, 1, 1]])
        idx = oapackage.oahelper.sortrows(x)
        assert(np.all(idx == np.array([2, 1, 0], dtype=np.int64)))

        x = np.array([])
        idx = oapackage.oahelper.sortrows(x)
        self.assertTrue(len(idx) == 0)
//  [python]
def _fit(self, X, handle_unknown="error"):
        X_list, n_samples, n_features = self._check_X(X)

        if self.categories != "auto":
            if len(self.categories) != n_features:
                raise ValueError("Shape mismatch: if categories is an array," " it has to be of shape (n_features,).")

        if self.max_levels is not None:
            if not isinstance(self.max_levels, Integral) or self.max_levels <= 0:
                raise ValueError("max_levels must be None or a strictly " "positive int, got {}.".format(self.max_levels))

        self.categories_ = []
        self.infrequent_indices_ = []

        for i in range(n_features):
            Xi = X_list[i]
            if self.categories == "auto":
                cats = _encode(Xi)
            else:
                cats = np.array(self.categories[i], dtype=Xi.dtype)
                if Xi.dtype != object:
                    if not n.all(np.sort(cats) == cats):
                        raise ValueError("Unsorted categories are not " "supported for numerical categories")
                if handle_unknown == "error":
                    diff = _encode_check_unknown(Xi, cats)
                    if diff:
                        msg = "Found unknown categories {0} in column {1}" " during fit".format(diff, i)
                        raise ValueError(msg)
            self.categories_.append(cats)

            if self.max_levels is not None:
                infrequent_indices = self._find_infrequent_category_indices(Xi)
            else:
                infrequent_indices = np.array([])
            self.infrequent_indices_.append(infrequent_indices)