text:
int_rules_6_7_9 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 6.7.9*Active*hyperbolic*functions =#
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x)) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => -((~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + 2 * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (~c + ~d * ~x)) / (~a + ~b * ℯ ^ (~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 + (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x)) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => -((~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + 2 * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (~c + ~d * ~x)) / (~a + ~b * ℯ ^ (~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x)) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => -((~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (~c + ~d * ~x)) / ((~a - Rt((~a) ^ 2 + (~b) ^ 2, 2)) + ~b * ℯ ^ (~c + ~d * ~x)), ~x) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (~c + ~d * ~x)) / (~a + Rt((~a) ^ 2 + (~b) ^ 2, 2) + ~b * ℯ ^ (~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~a) ^ 2 + (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x)) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => -((~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (~c + ~d * ~x)) / ((~a - Rt((~a) ^ 2 - (~b) ^ 2, 2)) + ~b * ℯ ^ (~c + ~d * ~x)), ~x) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (~c + ~d * ~x)) / (~a + Rt((~a) ^ 2 - (~b) ^ 2, 2) + ~b * ℯ ^ (~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NeQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 2), ~x) + (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 2) * sinh(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m], ~x) && (IGtQ(~n, 1) && EqQ((~a) ^ 2 + (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (-1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 2), ~x) + (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 2) * cosh(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m], ~x) && (IGtQ(~n, 1) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (-(~a) / (~b) ^ 2) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 2), ~x) + (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 2) * sinh(~c + ~d * ~x), ~x) + (((~a) ^ 2 + (~b) ^ 2) / (~b) ^ 2) * Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~n, 1) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && IGtQ(~m, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (-(~a) / (~b) ^ 2) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 2), ~x) + (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 2) * cosh(~c + ~d * ~x), ~x) + (((~a) ^ 2 - (~b) ^ 2) / (~b) ^ 2) * Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~n, 1) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IGtQ(~m, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * tanh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) * tanh(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) * tanh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * coth(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) * coth(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) * coth(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * coth(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * coth(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) * coth(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * tanh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * tanh(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) * tanh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sech(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~n + 2), ~x) + (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~n + 1) * tanh(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 + (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csch(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (-1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~n + 2), ~x) + (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~n + 1) * coth(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sech(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => ((~b) ^ 2 / ((~a) ^ 2 + (~b) ^ 2)) * Antiderivative(((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) + (1 / ((~a) ^ 2 + (~b) ^ 2)) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ ~n * (~a - ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (NeQ((~a) ^ 2 + (~b) ^ 2, 0) && IGtQ(~n, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csch(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => ((~b) ^ 2 / ((~a) ^ 2 - (~b) ^ 2)) * Antiderivative(((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) + (1 / ((~a) ^ 2 - (~b) ^ 2)) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ ~n * (~a - ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IGtQ(~n, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csch(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sech(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * (~F)(~c + ~d * ~x) ^ ~n) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && HyperbolicQ(~F)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * (~F)(~c + ~d * ~x) ^ ~n) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && HyperbolicQ(~F)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~(p') * sinh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ ~p * sinh(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ ~p * sinh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~(p') * cosh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ ~p * cosh(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ ~p * cosh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~(p') * tanh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~p - 1) * tanh(~c + ~d * ~x) ^ ~n, ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~p - 1) * tanh(~c + ~d * ~x) ^ ~n) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~(p') * coth(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~p - 1) * coth(~c + ~d * ~x) ^ ~n, ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~p - 1) * coth(~c + ~d * ~x) ^ ~n) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sech(~(c') + ~(d') * ~x) ^ ~(p') * tanh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~p + 1) * tanh(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~p + 1) * tanh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csch(~(c') + ~(d') * ~x) ^ ~(p') * coth(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~p + 1) * coth(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~p + 1) * coth(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~(p') * coth(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ ~p * coth(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ (~p + 1) * coth(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~(p') * tanh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ ~p * tanh(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ (~p + 1) * tanh(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csch(~(c') + ~(d') * ~x) ^ ~(p') * coth(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ ~p * coth(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ (~p - 1) * coth(~c + ~d * ~x) ^ ~n) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sech(~(c') + ~(d') * ~x) ^ ~(p') * tanh(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ ~p * tanh(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ (~p - 1) * tanh(~c + ~d * ~x) ^ ~n) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sech(~(c') + ~(d') * ~x) ^ ~(p') * csch(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ ~p * csch(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sech(~c + ~d * ~x) ^ ~p * csch(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csch(~(c') + ~(d') * ~x) ^ ~(p') * sech(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ ~p * sech(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * csch(~c + ~d * ~x) ^ ~p * sech(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n') * (~G)(~(c') + ~(d') * ~x) ^ ~(p')) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * (~F)(~c + ~d * ~x) ^ ~n * (~G)(~c + ~d * ~x) ^ ~p) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~p], ~x) && (HyperbolicQ(~F) && HyperbolicQ(~G))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n') * (~G)(~(c') + ~(d') * ~x) ^ ~(p')) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * (~F)(~c + ~d * ~x) ^ ~n * (~G)(~c + ~d * ~x) ^ ~p) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~p], ~x) && (HyperbolicQ(~F) && HyperbolicQ(~G))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sech(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n) / (~b + ~a * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (HyperbolicQ(~F) && IntegersQ(~m, ~n))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * csch(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n) / (~b + ~a * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (HyperbolicQ(~F) && IntegersQ(~m, ~n))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n') * (~G)(~(c') + ~(d') * ~x) ^ ~(p')) / (~a + ~(b') * sech(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * cosh(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n * (~G)(~c + ~d * ~x) ^ ~p) / (~b + ~a * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (HyperbolicQ(~F) && (HyperbolicQ(~G) && IntegersQ(~m, ~n, ~p)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n') * (~G)(~(c') + ~(d') * ~x) ^ ~(p')) / (~a + ~(b') * csch(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * sinh(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n * (~G)(~c + ~d * ~x) ^ ~p) / (~b + ~a * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (HyperbolicQ(~F) && (HyperbolicQ(~G) && IntegersQ(~m, ~n, ~p)))
    @apply_utils Antiderivative(sinh(~(a') + ~(b') * ~x) ^ ~(p') * sinh(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((-(ℯ ^ (-(~c) - ~d * ~x)) + ℯ ^ (~c + ~d * ~x)) ^ ~q, (-(ℯ ^ (-(~a) - ~b * ~x)) + ℯ ^ (~a + ~b * ~x)) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(cosh(~(a') + ~(b') * ~x) ^ ~(p') * cosh(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((ℯ ^ (-(~c) - ~d * ~x) + ℯ ^ (~c + ~d * ~x)) ^ ~q, (ℯ ^ (-(~a) - ~b * ~x) + ℯ ^ (~a + ~b * ~x)) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(sinh(~(a') + ~(b') * ~x) ^ ~(p') * cosh(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((ℯ ^ (-(~c) - ~d * ~x) + ℯ ^ (~c + ~d * ~x)) ^ ~q, (-(ℯ ^ (-(~a) - ~b * ~x)) + ℯ ^ (~a + ~b * ~x)) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(cosh(~(a') + ~(b') * ~x) ^ ~(p') * sinh(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((-(ℯ ^ (-(~c) - ~d * ~x)) + ℯ ^ (~c + ~d * ~x)) ^ ~q, (ℯ ^ (-(~a) - ~b * ~x) + ℯ ^ (~a + ~b * ~x)) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(sinh(~(a') + ~(b') * ~x) * tanh(~(c') + ~(d') * ~x), ~x) => Antiderivative((-(ℯ ^ -((~a + ~b * ~x))) / 2 + ℯ ^ (~a + ~b * ~x) / 2 + ℯ ^ -((~a + ~b * ~x)) / (1 + ℯ ^ (2 * (~c + ~d * ~x)))) - ℯ ^ (~a + ~b * ~x) / (1 + ℯ ^ (2 * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(cosh(~(a') + ~(b') * ~x) * coth(~(c') + ~(d') * ~x), ~x) => Antiderivative(((ℯ ^ -((~a + ~b * ~x)) / 2 + ℯ ^ (~a + ~b * ~x) / 2) - ℯ ^ -((~a + ~b * ~x)) / (1 - ℯ ^ (2 * (~c + ~d * ~x)))) - ℯ ^ (~a + ~b * ~x) / (1 - ℯ ^ (2 * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(sinh(~(a') + ~(b') * ~x) * coth(~(c') + ~(d') * ~x), ~x) => Antiderivative((-(ℯ ^ -((~a + ~b * ~x))) / 2 + ℯ ^ (~a + ~b * ~x) / 2 + ℯ ^ -((~a + ~b * ~x)) / (1 - ℯ ^ (2 * (~c + ~d * ~x)))) - ℯ ^ (~a + ~b * ~x) / (1 - ℯ ^ (2 * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(cosh(~(a') + ~(b') * ~x) * tanh(~(c') + ~(d') * ~x), ~x) => Antiderivative(((ℯ ^ -((~a + ~b * ~x)) / 2 + ℯ ^ (~a + ~b * ~x) / 2) - ℯ ^ -((~a + ~b * ~x)) / (1 + ℯ ^ (2 * (~c + ~d * ~x)))) - ℯ ^ (~a + ~b * ~x) / (1 + ℯ ^ (2 * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(sinh(~(a') / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(sinh(~a * ~x) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~c, ~d], ~x) && IGtQ(~n, 0)
    @apply_utils Antiderivative(cosh(~(a') / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(cosh(~a * ~x) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~c, ~d], ~x) && IGtQ(~n, 0)
    @apply_utils Antiderivative(sinh((~(e') * (~(a') + ~(b') * ~x)) / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(sinh((~b * ~e) / ~d - (~e * (~b * ~c - ~a * ~d) * ~x) / ~d) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~n, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(cosh((~(e') * (~(a') + ~(b') * ~x)) / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(cosh((~b * ~e) / ~d - (~e * (~b * ~c - ~a * ~d) * ~x) / ~d) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~n, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(sinh(~u) ^ ~(n'), ~x) => With([lst = QuotientOfLinearsParts(~u, ~x)], Antiderivative(sinh((lst(1) + lst(2) * ~x) / (lst(3) + lst(4) * ~x)) ^ ~n, ~x)) <-- IGtQ(~n, 0) && QuotientOfLinearsQ(~u, ~x)
    @apply_utils Antiderivative(cosh(~u) ^ ~(n'), ~x) => With([lst = QuotientOfLinearsParts(~u, ~x)], Antiderivative(cosh((lst(1) + lst(2) * ~x) / (lst(3) + lst(4) * ~x)) ^ ~n, ~x)) <-- IGtQ(~n, 0) && QuotientOfLinearsQ(~u, ~x)
    @apply_utils Antiderivative(~(u') * sinh(~v) ^ ~(p') * sinh(~w) ^ ~(q'), ~x) => Antiderivative(~u * sinh(~v) ^ (~p + ~q), ~x) <-- EqQ(~w, ~v)
    @apply_utils Antiderivative(~(u') * cosh(~v) ^ ~(p') * cosh(~w) ^ ~(q'), ~x) => Antiderivative(~u * cosh(~v) ^ (~p + ~q), ~x) <-- EqQ(~w, ~v)
    @apply_utils Antiderivative(sinh(~v) ^ ~(p') * sinh(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce(sinh(~v) ^ ~p * sinh(~w) ^ ~q, ~x), ~x) <-- IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x)))
    @apply_utils Antiderivative(cosh(~v) ^ ~(p') * cosh(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce(cosh(~v) ^ ~p * cosh(~w) ^ ~q, ~x), ~x) <-- IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x)))
    @apply_utils Antiderivative((~x) ^ ~(m') * sinh(~v) ^ ~(p') * sinh(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce((~x) ^ ~m, sinh(~v) ^ ~p * sinh(~w) ^ ~q, ~x), ~x) <-- IGtQ(~m, 0) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x))))
    @apply_utils Antiderivative((~x) ^ ~(m') * cosh(~v) ^ ~(p') * cosh(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce((~x) ^ ~m, cosh(~v) ^ ~p * cosh(~w) ^ ~q, ~x), ~x) <-- IGtQ(~m, 0) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x))))
    @apply_utils Antiderivative(~(u') * sinh(~v) ^ ~(p') * cosh(~w) ^ ~(p'), ~x) => (1 / 2 ^ ~p) * Antiderivative(~u * sinh(2 * ~v) ^ ~p, ~x) <-- EqQ(~w, ~v) && IntegerQ(~p)
    @apply_utils Antiderivative(sinh(~v) ^ ~(p') * cosh(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce(sinh(~v) ^ ~p * cosh(~w) ^ ~q, ~x), ~x) <-- IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x)))
    @apply_utils Antiderivative((~x) ^ ~(m') * sinh(~v) ^ ~(p') * cosh(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce((~x) ^ ~m, sinh(~v) ^ ~p * cosh(~w) ^ ~q, ~x), ~x) <-- IGtQ(~m, 0) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x))))
    @apply_utils Antiderivative(sinh(~v) * tanh(~w) ^ ~(n'), ~x) => Antiderivative(cosh(~v) * tanh(~w) ^ (~n - 1), ~x) - cosh(~v - ~w) * Antiderivative(sech(~w) * tanh(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(cosh(~v) * coth(~w) ^ ~(n'), ~x) => Antiderivative(sinh(~v) * coth(~w) ^ (~n - 1), ~x) + cosh(~v - ~w) * Antiderivative(csch(~w) * coth(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(sinh(~v) * coth(~w) ^ ~(n'), ~x) => Antiderivative(cosh(~v) * coth(~w) ^ (~n - 1), ~x) + sinh(~v - ~w) * Antiderivative(csch(~w) * coth(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(cosh(~v) * tanh(~w) ^ ~(n'), ~x) => Antiderivative(sinh(~v) * tanh(~w) ^ (~n - 1), ~x) - sinh(~v - ~w) * Antiderivative(sech(~w) * tanh(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(sinh(~v) * sech(~w) ^ ~(n'), ~x) => cosh(~v - ~w) * Antiderivative(tanh(~w) * sech(~w) ^ (~n - 1), ~x) + sinh(~v - ~w) * Antiderivative(sech(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(cosh(~v) * csch(~w) ^ ~(n'), ~x) => cosh(~v - ~w) * Antiderivative(coth(~w) * csch(~w) ^ (~n - 1), ~x) + sinh(~v - ~w) * Antiderivative(csch(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(sinh(~v) * csch(~w) ^ ~(n'), ~x) => sinh(~v - ~w) * Antiderivative(coth(~w) * csch(~w) ^ (~n - 1), ~x) + cosh(~v - ~w) * Antiderivative(csch(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative(cosh(~v) * sech(~w) ^ ~(n'), ~x) => sinh(~v - ~w) * Antiderivative(tanh(~w) * sech(~w) ^ (~n - 1), ~x) + cosh(~v - ~w) * Antiderivative(sech(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (NeQ(~w, ~v) && FreeQ(~v - ~w, ~x))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * (~a + ~(b') * sinh(~(c') + ~(d') * ~x) * cosh(~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => Antiderivative((~e + ~f * ~x) ^ ~m * (~a + (~b * sinh(2 * ~c + 2 * ~d * ~x)) / 2) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x)
    @apply_utils Antiderivative((~x) ^ ~(m') * (~a + ~(b') * sinh(~(c') + ~(d') * ~x) ^ 2) ^ ~n, ~x) => (1 / 2 ^ ~n) * Antiderivative((~x) ^ ~m * ((2 * ~a - ~b) + ~b * cosh(2 * ~c + 2 * ~d * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (NeQ(~a - ~b, 0) && (IGtQ(~m, 0) && (ILtQ(~n, 0) && (EqQ(~n, -1) || EqQ(~m, 1) && EqQ(~n, -2)))))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~a + ~(b') * cosh(~(c') + ~(d') * ~x) ^ 2) ^ ~n, ~x) => (1 / 2 ^ ~n) * Antiderivative((~x) ^ ~m * (2 * ~a + ~b + ~b * cosh(2 * ~c + 2 * ~d * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (NeQ(~a - ~b, 0) && (IGtQ(~m, 0) && (ILtQ(~n, 0) && (EqQ(~n, -1) || EqQ(~m, 1) && EqQ(~n, -2)))))
    @apply_utils Antiderivative((~(f') + ~(g') * ~x) ^ ~(m') / (~(a') + ~(b') * cosh(~(d') + ~(e') * ~x) ^ 2 + ~(c') * sinh(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (((2 * ~a + ~b) - ~c) + (~b + ~c) * cosh(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g], ~x) && (IGtQ(~m, 0) && (NeQ(~a + ~b, 0) && NeQ(~a + ~c, 0)))
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * sech(~(d') + ~(e') * ~x) ^ 2) / (~b + ~(c') * tanh(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / ((~b - ~c) + (~b + ~c) * cosh(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~g], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * sech(~(d') + ~(e') * ~x) ^ 2) / (~(b') + ~(a') * sech(~(d') + ~(e') * ~x) ^ 2 + ~(c') * tanh(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (((2 * ~a + ~b) - ~c) + (~b + ~c) * cosh(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g], ~x) && (IGtQ(~m, 0) && (NeQ(~a + ~b, 0) && NeQ(~a + ~c, 0)))
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * csch(~(d') + ~(e') * ~x) ^ 2) / (~c + ~(b') * coth(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / ((~b - ~c) + (~b + ~c) * cosh(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~g], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * csch(~(d') + ~(e') * ~x) ^ 2) / (~(c') + ~(b') * coth(~(d') + ~(e') * ~x) ^ 2 + ~(a') * csch(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (((2 * ~a + ~b) - ~c) + (~b + ~c) * cosh(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g], ~x) && (IGtQ(~m, 0) && (NeQ(~a + ~b, 0) && NeQ(~a + ~c, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) * (~A + ~(B') * sinh(~(c') + ~(d') * ~x))) / (~a + ~(b') * sinh(~(c') + ~(d') * ~x)) ^ 2, ~x) => (~B * (~e + ~f * ~x) * cosh(~c + ~d * ~x)) / (~a * ~d * (~a + ~b * sinh(~c + ~d * ~x))) - ((~B * ~f) / (~a * ~d)) * Antiderivative(cosh(~c + ~d * ~x) / (~a + ~b * sinh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B], ~x) && EqQ(~a * ~A + ~b * ~B, 0)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) * (~A + ~(B') * cosh(~(c') + ~(d') * ~x))) / (~a + ~(b') * cosh(~(c') + ~(d') * ~x)) ^ 2, ~x) => (~B * (~e + ~f * ~x) * sinh(~c + ~d * ~x)) / (~a * ~d * (~a + ~b * cosh(~c + ~d * ~x))) - ((~B * ~f) / (~a * ~d)) * Antiderivative(sinh(~c + ~d * ~x) / (~a + ~b * cosh(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B], ~x) && EqQ(~a * ~A - ~b * ~B, 0)
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * sinh(~(a') + ~(b') * (~c + ~(d') * ~x) ^ ~n) ^ ~(p'), ~x) => (1 / (~d) ^ (~m + 1)) * Subst(Antiderivative(((~d * ~e - ~c * ~f) + ~f * ~x) ^ ~m * sinh(~a + ~b * (~x) ^ ~n) ^ ~p, ~x), ~x, ~c + ~d * ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (IGtQ(~m, 0) && RationalQ(~p))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * cosh(~(a') + ~(b') * (~c + ~(d') * ~x) ^ ~n) ^ ~(p'), ~x) => (1 / (~d) ^ (~m + 1)) * Subst(Antiderivative(((~d * ~e - ~c * ~f) + ~f * ~x) ^ ~m * cosh(~a + ~b * (~x) ^ ~n) ^ ~p, ~x), ~x, ~c + ~d * ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (IGtQ(~m, 0) && RationalQ(~p))
    @apply_utils Antiderivative(sech(~v) ^ ~(m') * (~a + ~(b') * tanh(~v)) ^ ~(n'), ~x) => Antiderivative((~a * cosh(~v) + ~b * sinh(~v)) ^ ~n, ~x) <-- FreeQ([~a, ~b], ~x) && (IntegerQ((~m - 1) / 2) && EqQ(~m + ~n, 0))
    @apply_utils Antiderivative(csch(~v) ^ ~(m') * (~a + ~(b') * coth(~v)) ^ ~(n'), ~x) => Antiderivative((~b * cosh(~v) + ~a * sinh(~v)) ^ ~n, ~x) <-- FreeQ([~a, ~b], ~x) && (IntegerQ((~m - 1) / 2) && EqQ(~m + ~n, 0))
    @apply_utils Antiderivative(~(u') * sinh(~(a') + ~(b') * ~x) ^ ~(m') * sinh(~(c') + ~(d') * ~x) ^ ~(n'), ~x) => Antiderivative(ExpandTrigReduce(~u, sinh(~a + ~b * ~x) ^ ~m * sinh(~c + ~d * ~x) ^ ~n, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(~(u') * cosh(~(a') + ~(b') * ~x) ^ ~(m') * cosh(~(c') + ~(d') * ~x) ^ ~(n'), ~x) => Antiderivative(ExpandTrigReduce(~u, cosh(~a + ~b * ~x) ^ ~m * cosh(~c + ~d * ~x) ^ ~n, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(sech(~(a') + ~(b') * ~x) * sech(~c + ~(d') * ~x), ~x) => -(csch((~b * ~c - ~a * ~d) / ~d)) * Antiderivative(tanh(~a + ~b * ~x), ~x) + csch((~b * ~c - ~a * ~d) / ~b) * Antiderivative(tanh(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(csch(~(a') + ~(b') * ~x) * csch(~c + ~(d') * ~x), ~x) => csch((~b * ~c - ~a * ~d) / ~b) * Antiderivative(coth(~a + ~b * ~x), ~x) - csch((~b * ~c - ~a * ~d) / ~d) * Antiderivative(coth(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(tanh(~(a') + ~(b') * ~x) * tanh(~c + ~(d') * ~x), ~x) => (~b * ~x) / ~d - (~b / ~d) * cosh((~b * ~c - ~a * ~d) / ~d) * Antiderivative(sech(~a + ~b * ~x) * sech(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(coth(~(a') + ~(b') * ~x) * coth(~c + ~(d') * ~x), ~x) => (~b * ~x) / ~d + cosh((~b * ~c - ~a * ~d) / ~d) * Antiderivative(csch(~a + ~b * ~x) * csch(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(~(u') * (~(a') * cosh(~v) + ~(b') * sinh(~v)) ^ ~(n'), ~x) => Antiderivative(~u * (~a * ℯ ^ ((~a / ~b) * ~v)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~n], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(sinh(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (-1 / 2) * Antiderivative(ℯ ^ (-(~d) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) + (1 / 2) * Antiderivative(ℯ ^ (~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~n], ~x)
    @apply_utils Antiderivative(cosh(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (1 / 2) * Antiderivative(ℯ ^ (-(~d) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) + (1 / 2) * Antiderivative(ℯ ^ (~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~n], ~x)
    @apply_utils Antiderivative((~(e') * ~x) ^ ~(m') * sinh(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (-1 / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (-(~d) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) + (1 / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n], ~x)
    @apply_utils Antiderivative((~(e') * ~x) ^ ~(m') * cosh(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (1 / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (-(~d) * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) + (1 / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n], ~x)
end

max_stars_repo_path: src/rules/6 Hyperbolic functions/6.7 Miscellaneous/6.7.9 Active hyperbolic functions.jl


text:
defenceAreaTblfile=ENV["defenceAreaTblfile"]
specifiedParaofFiberLenFile= ENV["specifiedParaofFiberLenFile"]
machineInfoMainfile= ENV["machineInfoMainfile"]
tgrParafilename= ENV["tgrParafilename"]
machine友好名= ENV["machine友好名"]

####################################  below do not alter   ###########################################################
include("CSVParas/readCsvLib.jl")
include("CSVParas/mappingLib.jl")

CsvInfoObj = CsvInfos()
CsvInfoObj.防区表fieldname ="定位界标1,定位界标2,xxxx主机IP,通道号,定位界标1光程,定位界标2光程,子防区编号,防区起点GPS经度坐标,防区起点GPS纬度坐标,防区终点GPS经度坐标,防区终点GPS纬度坐标,左右岸,地名信息,界标之间围栏长度,管理处,分局"
CsvInfoObj.防区表signalStringName="定位界标1光程"
CsvInfoObj.防区表keyFieldNames ="定位界标1,定位界标1光程,定位界标2,定位界标2光程"
CsvInfoObj.防区表filename = defenceAreaTblfile

CsvInfoObj.老版参数表fieldname ="编号,使能,描述,通道,起始位置(米),结束位置(米),修改时间,立案票数,过零.静态票数,过零.动态票数,能量.静态票数,能量.动态票数,过零.静态阈值.数值,过零.动态时间常数(秒),过零.动态系数,过零.动态上限,过零.动态下限,能量.静态阈值,能量.动态时间常数(秒),能量.动态系数,能量.动态上限,能量.动态下限,空间.合并(米),空间.滤除(米),时间.合并(帧),时间.滤除(帧),振动范围上限(米),振动范围下限(米),持续时间上限(秒),持续时间下限(秒),时空积上限(米*秒),时空积下限(米*秒)"
CsvInfoObj.老版参数表signalStringName="起始位置(米)"
CsvInfoObj.老版参数表keyFieldNames ="编号,通道,起始位置(米),结束位置(米),过零.动态时间常数(秒),过零.动态系数,过零.动态上限,过零.动态下限,空间.合并(米),空间.滤除(米),时间.合并(帧),时间.滤除(帧),振动范围上限(米),振动范围下限(米),持续时间上限(秒),持续时间下限(秒)"
CsvInfoObj.老版参数表filename =specifiedParaofFiberLenFile

CsvInfoObj.主机信息表fieldname = "主机编号,友好名,主机位置,主机类型"
CsvInfoObj.主机信息表signalStringName = "主机类型"
CsvInfoObj.主机信息表keyFieldNames = "主机编号,友好名,主机位置,主机类型"
CsvInfoObj.主机信息表filename     = machineInfoMainfile

basicInit( CsvInfoObj)
convertPara2SignalCordinate(CsvInfoObj,machine友好名1=machine友好名)
# show(CsvInfoObj.csvInfoDefencePara )

tem1 = CsvInfoObj.csvInfoDefencePara.keyFieldNames
tem1= replace(tem1,"起始位置(米)"=>"标牌坐标1")
tem1= replace(tem1,"结束位置(米)"=>"标牌坐标2")

tem1= replace(tem1,"过零.动态时间常数(秒)"=>"动态阈值时长")

tem1= replace(tem1,"过零.动态系数"=>"动态阈值系数")
tem1= replace(tem1,"过零.动态下限"=>"动态阈值下限")
tem1= replace(tem1,"过零.动态上限"=>"动态阈值上限" )

tem1= replace(tem1,"空间.合并(米)"=>"事件合并距离"  )

tem1= replace(tem1,"空间.滤除(米)"=>"事件滤除距离")
tem1= replace(tem1,"时间.合并(帧)"=>"事件合并时长")
tem1= replace(tem1,"时间.滤除(帧)"=>"事件滤除时间")
tem1= replace(tem1,"振动范围上限(米)"=>"告警空间上限")
tem1= replace(tem1,"振动范围下限(米)"=>"告警空间下限")
tem1= replace(tem1,"持续时间上限(秒)"=>"告警续时上限")
tem1= replace(tem1,"持续时间下限(秒)"=>"告警续时下限")

CsvInfoObj.csvInfoDefencePara.keyFieldNames =tem1
tem2 =CsvInfoObj.csvInfoDefencePara.keyFieldNames
# for key1 in split(tem2 ,",")
#     println( key1)
# end
csvObject = CsvInfoObj.csvInfoDefencePara.Area2FiberLen
total = length(csvObject)
for  idx  = 1: total
    row = csvObject[idx]

    i=5 # 转换  过零.动态时间常数(秒) 单位为 帧（0.426秒)
    a = floor(Int, parse( Int , row[i] ) /0.426)
    row[i]  =string(a)

    i=6 # 转换 动态阈值的系数 单位为 0.01
    a = parse( Int , row[i] ) *100
    row[i]  =string(a)

    i=16 # # 转换  持续时间上/下限(秒) 单位为 帧（0.426秒)
    a = floor(Int, parse( Int , row[i] ) /0.426)
    row[i]  =string(a)
    i=15 # # 转换  持续时间上/下限(秒) 单位为 帧（0.426秒)
    a = floor(Int, parse( Int , row[i] ) /0.426)
    row[i]  =string(a)

    # i=6 # 转换动态阈值的系数单位为 0.01
    # a = parse( Int , row[i] ) *100
    # row[i]  =string(a)

    if row[1] =="1001" || row[1] =="2001"
        row[3]=row[4]="0+0"
        println(row[1],"-",row[3],"-",row[4])
    end
#         print("$fieldname:$(row[i]) ,$a\r\n")
end
write2CSV(CSVinfo1= CsvInfoObj.csvInfoDefencePara,filename=tgrParafilename )
println()
# convertPara_Fiberlength( CsvInfoObj,machine友好名1="高元001")
# show(CsvInfoObj.csvInfoDefencePara )

ext: jl

max_stars_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_issues_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_forks_repo_name: wangzhongtian/fiberAlarmAnalyseTool


text:
#****************************************************************************
#                     Molecular Dynamics Potentials (MDP)
#                            CESMIX-MIT Project
#
#  Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com)
#****************************************************************************

function readweight(app, config)

if app.weightmode == 0
    tmp = ones(1,2*config.nconfigs);
    tmp[1:config.nconfigs] .= app.we;
    tmp[(config.nconfigs+1):2*config.nconfigs] .= app.wf;
elseif app.weightmode == 1 # binary
    filename = app.weightfile;
    tmp = reinterpret(Float64,read(filename));
elseif app.weightmode == 2 # text
    filename = app.weightfile;
    tmp = Main.DelimitedFiles.readdlm(filename);
end

# determine weights
if (app.dftdata == 1)
    config.we = reshape(tmp[1:config.nconfigs],1,config.nconfigs);
    config.wf = reshape([],0,2);
elseif (app.dftdata == 2)
    config.we = reshape([],0,2);
    config.wf = reshape(tmp[1:config.nconfigs],1,config.nconfigs);
elseif (app.dftdata == 3)
    config.we = reshape(tmp[1:config.nconfigs],1,config.nconfigs);
    config.wf = reshape(tmp[(config.nconfigs+1):2*config.nconfigs],1,config.nconfigs);
end

return config

end

max_stars_repo_name: cesmix-mit/MDP

max_issues_repo_name: cesmix-mit/MDP

max_forks_repo_name: cesmix-mit/MDP


text:
function CommonModulusAttack(e₁, c₁, e₂, c₂, N)
    d, u, v = gcdx(e₁, e₂)
    println("gcd(e₁,e₂):$d")

    e₁ = e₁ ÷ d
    e₂ = e₂ ÷ d
    d₀ = d
    d, u, v = gcdx(e₁, e₂)
    println("u:$u v:$v")
    println("e₁:$e₁*$d e₂:$e₂*$d")

    u < 0 && (c₁ = invmod(c₁, N))
    v < 0 && (c₂ = invmod(c₂, N))

    c₁ᵘ = powermod(c₁, abs(u), N)
    c₂ᵛ = powermod(c₂, abs(v), N)
    m = mod(c₁ᵘ * c₂ᵛ, N)

    m = trunc(BigInt, m ^ (1 / d₀))
    println("dec : " * string(m))
    println("hex : " * string(m, base=16))

    try
        flag = join(map(x -> Char(x), hex2bytes(string(m, base=16))))
        println("FLAG: $flag")
    catch
        println("FLAG: (m is not ascii)")
    end
end

function main()
    setprecision(2000);
    print("e₁:")
    e₁ = parse(BigInt, readline())
    print("c₁:")
    c₁ = parse(BigInt, readline())
    print("e₂:")
    e₂ = parse(BigInt, readline())
    print("c₂:")
    c₂ = parse(BigInt, readline())
    print("N:")
    N = parse(BigInt, readline())
    CommonModulusAttack(e₁, c₁, e₂, c₂, N)
end

main()

max_stars_repo_name: HalsSC/CTF

max_issues_repo_name: HalsSC/CTF

max_forks_repo_name: HalsSC/CTF


text:
@mix @columns struct Kernel{NH}
    # Field          | Default              | Flat | Bounds | Description
    neighborhood::NH | DispersalKernel{3}() | true | _      | "Normalised proportions of dispersal to surrounding cells"
end

"""
    DispersalKernel{Radius}(formulation::F, kernel::K, cellsize::C, distancemethod::D)
    DispersalKernel{Radius}(; formulation=ExponentialKernel(1.0), cellsize=1.0, distancemethod=CentroidToCentroid())

arguments, but preferably use the keyword constructor to build the array from
a dispersal kernel function.
$(FIELDDOCTABLE)
"""
@columns struct DispersalKernel{R,F,K,C,D,B} <: AbstractRadialNeighborhood{R,B}
    # Field           | Default                | Flat  | Bounds      | Description
    formulation::F    | ExponentialKernel(1.0) | true  | _           | "Kernel formulation object"
    kernel::K         | nothing                | false | _           | "Kernel matrix"
    cellsize::C       | 1.0                    | false | (0.0, 10.0) | "Simulation cell size"
    distancemethod::D | CentroidToCentroid()   | false | _           | "Method for calculating distance between cells"
    buffer::B         | nothing                | false | _           | "Neighborhood buffer"
end
DispersalKernel{R}(formulation, kernel, cellsize, distancemethod, buffer) where R = begin
    # Convert kenel the type of the init array
    newkernel = scale(buildkernel(formulation, distancemethod, cellsize, R))
    newkernel = kernel isa Nothing ? newkernel : typeof(kernel)(newkernel)
    DispersalKernel{R,map(typeof, (formulation, newkernel, cellsize, distancemethod, buffer))...
                         }(formulation, newkernel, cellsize, distancemethod, buffer)
end
DispersalKernel{R}(; kwargs...) where R = begin
    args = FieldDefaults.insert_kwargs(kwargs, DispersalKernel)
    DispersalKernel{R}(args...)
end

ConstructionBase.constructorof(::Type{<:DispersalKernel{R}}) where R = DispersalKernel{R}

DynamicGrids.radius(hood::DispersalKernel{R}) where R = R

# The default method will rebuild the kernel every timestep, which can be costly.
DynamicGrids.spreadbuffers(rule::NeighborhoodRule, k::DispersalKernel{R,F,K,C,D,B},
                           buffers::Tuple, grid::AbstractArray) where {R,F,K,C,D,B} = begin
    kernels = map(buffers) do b
        DispersalKernel{R,F,K,C,D,typeof(b)}(
            formulation(k), kernel(k), cellsize(k), distancemethod(k), b
        )
    end
    buffers, map(k -> (@set rule.neighborhood = k), kernels)
end

kernel(hood::DispersalKernel) = hood.kernel
cellsize(hood::DispersalKernel) = hood.cellsize
distancemethod(hood::DispersalKernel) = hood.distancemethod
neighbors(hood::DispersalKernel) = buffer(hood)
formulation(hood::DispersalKernel) = hood.formulation

@inline disperse(hood::DispersalKernel) =
    @inbounds return buffer(hood) ⋅ kernel(hood)

buildkernel(formulation, distancemethod, cellsize, r) = begin
    # The radius doesn't include the center cell, so add it
    sze = 2r + 1
    kernel = zeros(typeof(cellsize), sze, sze)
    r1 = r + one(r)
    # Paper: l. 97
    for x = 0:r, y = 0:r
        # Calculate the distance effect from the center cell to this cell
        prob = dispersalprob(formulation, distancemethod, x, y, cellsize)
        # Update the kernel value based on the formulation and distance
        kernel[x + r1, y + r1] = prob
        kernel[x + r1, -y + r1] = prob
        kernel[-x + r1, y + r1] = prob
        kernel[-x + r1, -y + r1] = prob
    end
    kernel
end

scale(x) = x ./= sum(x)

# build_dispersal_kernel(formulation, distancemethod, cellsize, r) = begin
#     # The radius doesn't include the center cell, so add it
#     sze = 2r + 1
#     kernels = [zeros(Float64, sze, sze) for thread in 1:Threads.nthreads()]
#     r1 = r + one(r)

#     # Calculate one quadrant
#     Threads.@threads for x = 0:r
#         kernel = kernels[Threads.threadid()]
#         for y = 0:r
#             kernel[x + r1, y + r1] = dispersalprob(formulation, distancemethod, x, y, cellsize)
#         end
#     end
#     kernel = sum(kernels)
#     println()
#     println(length(kernels))
#     display(kernels)
#     println()
#     # Update the other 3 quadrants
#     for x = 0:r, y = 0:r
#         # Just sum the threads, most are zero
#         prob = kernel[x + r1, y + r1]
#         kernel[x + r1, -y + r1] = prob
#         kernel[-x + r1, y + r1] = prob
#         kernel[-x + r1, -y + r1] = prob
#     end
#     # Normalise
#     kernel ./= sum(kernel)
# end

"""
Abstract supertype for methods of calculating distances and dispersal probabilities
between cells in a grid.
"""
abstract type DistanceMethod end

subsampling(method::DistanceMethod) = method.subsampling

"""
    CentroidToCentroid()

Calculates probability of dispersal between source and destination cell centroids
This is the obvious, naive method, but it will not handle low grid resolution well.
"""
struct CentroidToCentroid <: DistanceMethod end

dispersalprob(f, ::CentroidToCentroid, x, y, cellsize) =
    sqrt(x^2 + y^2) * cellsize |> f

# """
#     CentroidToCentroid(subsampling)
#     CentroidToCentroid(; subsampling=10.0)
#
# Calculates probability of dispersal between source cell centroid and destination cell area.
#
# $(FIELDDOCTABLE)
# """
# @columns struct CentroidToArea <: DistanceMethod
    # Field        | Default | Flat | Bounds      | Description
    # subsampling::Int | 10.0    | true | (2.0, 40.0) | "Subsampling for brute-force integration"
# end

# dispersalprob(f, dm::CentroidToArea, x, y, cellsize) = error("not implemented yet")

"""
    AreaToCentroid(subsampling)
    AreaToCentroid(; subsampling=10.0)

Calculates probability of dispersal between source cell area and destination centroid.

$(FIELDDOCTABLE)
"""
@columns struct AreaToCentroid <: DistanceMethod
    # Field          | Default | Flat | Bounds      | Description
    subsampling::Int | 10.0    | true | (2.0, 40.0) | "Subsampling for brute-force integration"
end
AreaToCentroid(subsampling::AbstractFloat) = AreaToCentroid(round(Int, subsampling))

@inline dispersalprob(f, dm::AreaToCentroid, x, y, cellsize) = begin
    prob = zero(cellsize)
    centerfirst = 1 / subsampling(dm) / 2 - 0.5
    centerlast = centerfirst * -1
    range = LinRange(centerfirst, centerlast, subsampling(dm))
    for j in range, i in range
        prob += sqrt((x + i)^2 + (y + j)^2) * cellsize |> f
    end
    prob / subsampling(dm)^2
end

"""
    AreaToArea(subsampling)
    AreaToArea(; subsampling=10.0)

Calculates probability of dispersal between source and destination cell areas.

$(FIELDDOCTABLE)
"""
struct AreaToArea <: DistanceMethod
    subsampling::Int
end
AreaToArea(subsampling::AbstractFloat) = AreaToArea(round(Int, subsampling))

@inline dispersalprob(f, dm::AreaToArea, x, y, cellsize) = begin
    prob = zero(cellsize)
    # Get the center point of the first cell (for both dimensions)
    centerfirst = 1 / subsampling(dm) / 2 - 0.5
    centerlast = centerfirst * -1
    range = LinRange(centerfirst, centerlast, subsampling(dm))
    for i in range, j in range
        for a in range, b in range
            prob += sqrt((x + i + a)^2 + (y + j + b)^2) * cellsize |> f
        end
    end
    prob / subsampling(dm)^4
end

"""
Abstract supertype for functors for calculating the probability of
dispersal between two points.

Concrete implementations must define functor methods with the form:
```julia
(k::SomeKernel)(x) = ? # do something with `x` and `k`"
```
"""
abstract type KernelFormulation end

"""
    ExponentialKernel(λ)

Probability of dispersal with a negatitve exponential relationship to distance.

$(FIELDDOCTABLE)
"""
@columns struct ExponentialKernel{P} <: KernelFormulation
    # Field | Default | Flat | Bounds     | Description
    λ::P    | 1.0     | true | (0.0, 2.0) | "Parameter for adjusting spread of dispersal propability"
end
(f::ExponentialKernel)(distance) = exp(-distance / f.λ)

@columns struct ExponentialKernel2{P} <: KernelFormulation
    # Field | Default | Flat | Bounds     | Description
    λ::P    | 1.0     | true | (0.0, 2.0) | "Parameter for adjusting spread of dispersal propability"
end
(f::ExponentialKernel2)(distance) = 1/(2 * π * f.λ^2) * exp(-distance / f.λ)

"""
    GeometricKernel(p)

Probability of dispersal with a geometric relationship to distance.

$(FIELDDOCTABLE)
"""
@columns struct GeometricKernel{P} <: KernelFormulation
    # Field | Default | Flat | Bounds     | Description
    β::P    | 0.5     | true | (-100.0, 100.0) | "Parameter for adjusting spread of dispersal propability"
end
(f::GeometricKernel)(distance) = (f.β+1)*(f.β+2) / (2*π) * (1+distance)^f.β

"""
    GaussianKernel(m)

Probability of dispersal with a geometric relationship to distance.

$(FIELDDOCTABLE)
"""
@columns struct GaussianKernel{P} <: KernelFormulation
    # Field | Default | Flat | Bounds     | Description
    α::P    | 0.5     | true | (0.0, 100.0) | "Parameter for adjusting spread of dispersal propability"
end
(f::GaussianKernel)(distance) = 1 / (π*f.α^2) * exp(-(distance/f.α)^2)


text:
# Create an initial dataset

using NveData
using DataFrames
using Dates

stat_list = ["2.11","2.28","2.32","2.142","2.145","2.265","2.268","2.279", "2.291","2.323","2.439","2.463","2.479",
            "2.604","2.614","2.633","2.634","3.22","6.10","6.71","8.2","8.6","12.70","12.97","12.114","12.150","12.171",
            "12.178","12.192","12.193","12.209","12.215","12.286","12.290","15.15","15.21","15.49","15.53","15.53",
            "15.79","15.79","15.174","16.66","16.75","16.122","16.132","16.140","16.193","18.10","19.107","20.2",
            "21.47","22.4","22.16","22.16","22.22","24.8","24.9","25.24","25.32","26.20","26.26","26.26","26.29",
            "27.16","27.24","28.7","35.16","36.9","41.1","42.2","46.9","48.1","48.5","50.1","50.13","50.13","55.4",
            "55.5","62.5","62.10","62.10","62.18","72.5","73.27","75.23","76.5","76.5","77.3","78.8","79.3","82.4",
            "82.4","83.2","84.11","84.11","86.12","87.10","88.4","97.1","98.4","103.1","103.40","104.23","105.1",
            "107.3","109.9","109.29","109.42","112.8","121.20","122.9","122.11","122.17","123.31","124.2","127.11",
            "127.13","133.7","138.1","139.15","139.35","148.2","151.15","152.4","156.10","157.3","160.7","161.7",
            "163.5","165.6","168.2","173.8","174.3","174.11","177.4","191.2","196.35","200.4","203.2","206.3",
            "208.3","212.10","212.27","212.49","223.2","230.1","234.13","234.18","247.3","311.6","311.460","313.10"]

stat_list = unique(stat_list)

time_vec = floor(now()-Day(20), Day):Day(1):floor(now()-Day(10), Day)

save_folder = "/home/jmg/temp"

init_dataset(stat_list, time_vec, save_folder)

# Update an existing dataset

using NveData
using DataFrames

save_folder = "/home/jmg/temp/"

stat_list = readdir(save_folder)
stat_list = [replace(x, "_data" => "") for x in stat_list]
stat_list = [replace(x, "_" => ".") for x in stat_list]

update_dataset(stat_list, save_folder)

max_forks_repo_name: jmgnve/NveData


text:
module MimeWriter

using ..FileIO: File, @format_str

function save(file::File{format"PNG"}, data)
    if showable("image/png", data)
        open(file.filename, "w") do s
            show(IOContext(s, :full_fidelity=>true), "image/png", data)
        end
    else
        throw(ArgumentError("Argument does not support conversion to png."))
    end
end

function save(file::File{format"SVG"}, data)
    if showable("image/svg+xml", data)
        open(file.filename, "w") do s
            show(IOContext(s, :full_fidelity=>true), "image/svg+xml", data)
        end
    else
        throw(ArgumentError("Argument does not support conversion to svg."))
    end
end

function save(file::File{format"PDF"}, data)
    if showable("application/pdf", data)
        open(file.filename, "w") do s
            show(IOContext(s, :full_fidelity=>true), "application/pdf", data)
        end
    else
        throw(ArgumentError("Argument does not support conversion to pdf."))
    end
end

function save(file::File{format"EPS"}, data)
    if showable("application/eps", data)
        open(file.filename, "w") do s
            show(IOContext(s, :full_fidelity=>true), "application/eps", data)
        end
    else
        throw(ArgumentError("Argument does not support conversion to eps."))
    end
end

function save(file::File{format"HTML"}, data)
    if showable("application/vnd.julia.fileio.htmlfile", data)
        open(file.filename, "w") do s
            show(s, "application/vnd.julia.fileio.htmlfile", data)
        end
    elseif showable("text/html", data)
        open(file.filename, "w") do s
            show(s, "text/html", data)
        end
    else
        throw(ArgumentError("Argument does not support conversion to HTML."))
    end
end

end


text:
using OrdinaryDiffEq, Test
using DiffEqProblemLibrary.ODEProblemLibrary: importodeproblems; importodeproblems()
import DiffEqProblemLibrary.ODEProblemLibrary: prob_ode_linear,
       linear, f_2dlinear

# scalar, not in-place
prob = prob_ode_linear
sol = solve(prob, DP5(); save_idxs=1)
sol(0.5) # test interpolation

# vector, not in-place
prob2 = ODEProblem(linear, [0.5], (0., 1.), 1.01)
sol2 = solve(prob2, DP5(); save_idxs=1)
@test sol.t ≈ sol2.t && sol.u ≈ sol2.u
sol2(0.5)

sol2b = solve(prob2, DP5(); save_idxs=[1])
@test sol.t ≈ sol2b.t && sol.u ≈ [u[1] for u in sol2b.u]
sol2b(0.5)

# vector, in-place
prob3 = ODEProblem(f_2dlinear, [0.5], (0., 1.), 1.01)
sol3 = solve(prob3, DP5(); save_idxs=1)
@test sol.t ≈ sol3.t && sol.u ≈ sol3.u
sol3(0.5)

sol3b = solve(prob3, DP5(); save_idxs=[1])
@test sol.t ≈ sol3b.t && sol2b.u ≈ sol3b.u
sol3b(0.5)


text:
using DataFrames
using CSV
using SpatialEcology
using Test

@testset "Assemblage" begin
    amphdat = CSV.read(joinpath(dirname(pathof(SpatialEcology)), "..", "data", "amph_Europe.csv"))
    amph = Assemblage(amphdat[!,4:end], amphdat[!,1:3], sitecolumns = false)

    @test typeof(amph) == Assemblage{Bool,SpatialEcology.Locations{SpatialEcology.GridData}}

    # accesseors
    @test extrema(richness(amph)) == (1, 20)
    @test nsites(amph) == 1010
    @test noccupied(amph) == 1010
    @test nspecies(amph) == 73
    @test noccurring(amph) == 73
    @test occurring(amph, 718) == [15]
    @test occupancy(amph)[1] == 353

    # views
    va = view(amph, species = 1:10)

    #operations
    amp2 = aggregate(amph, 2)
    @test sum(richness(amp2)) == 2862
    @test nsites(amp2) == 285

    pointamph = Assemblage(amphdat[!,4:end], amphdat[!,1:3], sitecolumns = false, cdtype = SpatialEcology.pointdata)
    amp3 = aggregate(pointamph, 2)
    @test richness(amp3) == richness(amp2)
end


text: Dict{String, Any}("space" => Dict{String, Any}("value" => "1987-07-05T17:45:00Z", "type" => "datetime"), "lower" => Dict{String, Any}("value" => "1987-07-05T17:45:00Z", "type" => "datetime"))


text:
struct Operations end

Primitives() = Multi(Operations(), Basic())

exprtype(ir, x) = IRTools.exprtype(ir, x, typeof = Const)

xtypeof(x::XScalar) = Const(x)
xtypeof(x::Tuple) = ptuple(xtypeof.(x)...)
xtypeof(x::Array{<:XScalar}) = Mjolnir.Shape{typeof(x)}(size(x))
xtypeof(x::XArray{T,N}) where {T,N} = Mjolnir.Shape{Array{T,N}}(size(x))
xtypeof(x) = isbits(x) && nfields(x) == 0 ? Const(x) : Partial{typeof(x)}((; map(f -> f=>xtypeof(getfield(x, f)), fieldnames(typeof(x)))...))

layout(x::Type{<:XScalar}) = [x]
layout(::Const) = []
layout(x::XShape) = [x]
layout(x::Mjolnir.Shape) = [XShape(eltype(x), size(x))]
layout(x::Type{<:Array{<:XScalar}}) = [x]
layout(x::Partial) = vcat(map(i -> layout(x.value[i]), 1:fieldcount(widen(x)))...)
layout(x::Type) = vcat(map(f -> layout(fieldtype(x, f)), fieldnames(x))...)
layout(x::Mjolnir.Node) = layout(widen(x))

subtype(T::Partial, i) = T.value[i]
subtype(T::Type, i) = fieldtype(T, i)

function subrange(T, i)
  offset = sum(Int[length(layout(subtype(T, j))) for j = 1:i-1])
  len = length(layout(subtype(T, i)))
  return offset .+ (1:len)
end

struct Print
  data
end

@abstract Operations repr(x) = x
@abstract Operations println(xs...) = Partial{Print}(Any[Mjolnir.ptuple(xs...)])

@abstract Operations Base.vect(xs::Const...) = Const([x.value for x in xs])

@abstract Operations NNlib.DenseConvDims(xs::Const...; kw...) =
  Const(DenseConvDims(map(x -> x.value, xs)...; kw...))

@abstract Operations NNlib.PoolDims(xs::Const...; kw...) =
  Const(PoolDims(map(x -> x.value, xs)...; kw...))

@abstract Operations conv(x::Array, w::Array, dims::Const{<:DenseConvDims}) =
  Shape{widen(x)}((NNlib.output_size(dims.value)..., size(w)[end], size(x)[end]))

@abstract Operations ∇conv_data(dy::Array, w::Array, dims::Const{<:DenseConvDims}) =
  Shape{widen(dy)}((NNlib.input_size(dims.value)..., NNlib.channels_in(dims.value), size(dy)[end]))

@abstract Operations ∇conv_filter(dy::Array, w::Array, dims::Const{<:DenseConvDims}) =
  Shape{widen(dy)}((NNlib.kernel_size(dims.value)..., NNlib.channels_in(dims.value), NNlib.channels_out(dims.value)))

function transpose!(ir, v, sz = size(exprtype(ir, v)))
  insertafter!(ir, v, xcall(Reshape(length(sz):-1:1, reverse(sz)), v))
end

xpadding() = ()
xpadding(a, b, ps...) = ((a, b), xpadding(ps...)...)

function xlaop!(ir, v, ::AType{typeof(conv)}, X, W, ::AType{DenseConvDims{N,K,C_in,C_out,S,P,D,F}}) where {N,K,C_in,C_out,S,P,D,F}
  @assert length(size(X)) == 4 "Only 2D conv currently supported"
  _, x, w = ir[v].expr.args
  F || (w = insertafter!(ir, w, xcall(Rev([1, 2]), w)))
  ir[v] = xcall(Conv(S, xpadding(P...), [1, 1], [1, 1]), x, w)
end

function xlaop!(ir, v, ::AType{typeof(∇conv_data)}, Ȳ, W, ::AType{DenseConvDims{N,K,C_in,C_out,S,P,D,F}}) where {N,K,C_in,C_out,S,P,D,F}
  @assert length(size(Ȳ)) == 4 "Only 2D conv currently supported"
  _, dy, w = ir[v].expr.args
  F && (w = insertafter!(ir, w, xcall(Rev([1, 2]), w)))
  w = insertafter!(ir, w, xcall(Reshape([1, 2, 4, 3], getindex.((size(W),), [1, 2, 4, 3])), w))
  p = xpadding(P...)
  p = ntuple(i -> size(W)[i]-1 .- p[i], length(p))
  ir[v] = xcall(Conv(S, p, [1, 1], [1, 1]), dy, w)
end

function xlaop!(ir, v, ::AType{typeof(∇conv_filter)}, X, Ȳ, dims::Const{DenseConvDims{N,K,C_in,C_out,S,P,D,F}}) where {N,K,C_in,C_out,S,P,D,F}
  @assert length(size(X)) == 4 "Only 2D conv currently supported"
  _, x, dy = ir[v].expr.args
  W = exprtype(ir, v)
  x = insertafter!(ir, x, xcall(Reshape([1, 2, 4, 3], getindex.((size(X),), [1, 2, 4, 3])), x))
  dy = insertafter!(ir, dy, xcall(Reshape([1, 2, 4, 3], getindex.((size(Ȳ),), [1, 2, 4, 3])), dy))
  p = xpadding(P...)
  dw = insert!(ir, v, xcall(Conv(S, p, [1, 1], [1, 1]), x, dy))
  F || (dw = insertafter!(ir, dw, xcall(Rev([1, 2]), dw)))
  ir[v] = xcall(Reshape([1, 2, 4, 3], size(W)), dw)
end

@abstract Operations function maxpool(x::Array, dims::Const{<:PoolDims})
  Shape{widen(x)}((NNlib.output_size(dims.value)..., size(x)[end-1:end]...))
end

@abstract Operations function ∇maxpool(dy::Array, y::Array, x::Array, dims::Const{<:PoolDims})
  Shape{widen(x)}(size(x))
end

poolwindow(x, k) = ntuple(i -> i > length(k) ? 1 : k[i], length(x))

function xlaop!(ir, v, ::AType{typeof(maxpool)}, X, dims::Const{<:PoolDims})
  _, x = ir[v].expr.args
  reducer = insert!(ir, v, code_xla(max, eltype(X), eltype(X)))
  init = zero(eltype(X))
  ir[v] = xcall(ReduceWindow(poolwindow(size(X), NNlib.kernel_size(dims.value))), reducer, x, init)
end

function xlaop!(ir, v, ::AType{typeof(∇maxpool)}, Ȳ, Y, X, dims::Const{<:PoolDims})
  _, dy, y, x = ir[v].expr.args
  select = insert!(ir, v, code_xla(>, eltype(X), eltype(X)))
  scatter = insert!(ir, v, code_xla((x, y) -> y, eltype(X), eltype(X)))
  ir[v] = xcall(SelectAndScatter(poolwindow(size(X), NNlib.kernel_size(dims.value))), select, scatter, x, dy, zero(eltype(X)))
end

# Base's `<` does something complicated.
simplelt(a, b) = <(promote(a, b)...)

instead(::Operations, args, ::AType{typeof(<)}, a::AType{<:XScalar}, b::AType{<:XScalar}) =
  widen(a) == widen(b) ? nothing : ([simplelt, args[2], args[3]], (Const(simplelt), a, b))

instead(::Operations, args, ::AType{typeof(//)}, a::AType{<:XScalar}, b::AType{<:XScalar}) =
  [(/), args[2], args[3]], [Const(/), a, b]

@abstract Operations convert(::Type{T}, x::Const{<:XScalar}) where T<:XScalar =
  Const(convert(T, x.value))

@abstract Operations convert(::Type{T}, S::XScalar) where T<:XScalar =
  widen(S) <: T ? S : T

@abstract Operations (::Type{T})(S::XScalar) where T<:XScalar =
  abstract(Operations(), Const(convert), Const(T), S)

@abstract Operations fill(x::Const, sz::Const) = Const(fill(x.value, sz.value))
@abstract Operations ones(x::Const{<:Tuple{Vararg{Integer}}}) = Const(ones(x.value))

xlaop(args, ::AType{typeof(convert)}, ::AType{Type{T}}, _) where T<:XScalar =
  xcall(ConvertElementType(T), args[3])

xlaop(args, ::AType{Type{T}}, ::AType{<:XScalar}) where T<:XScalar =
  xcall(ConvertElementType(T), args[2])

for (op, xop) in [(+, :Add), (*, :Mul), (-, :Sub), (/, :Div), (^, :Pow), (>, :Gt),
                  (<, :Lt), (>=, :Ge), (<=, :Le), (max, :Max)]
  @eval @abstract Operations $op(a::Const{T}, b::Const{T}) where T<:XScalar =
    Const($op(a.value, b.value))
  @eval @abstract Operations $op(a::AType{T}, b::AType{T}) where T<:XScalar =
    Core.Compiler.return_type($op, Tuple{T,T})
  @eval xlaop(args, ::AType{typeof($op)}, a::AType{T}, b::AType{T}) where T<:XScalar =
          xcall($xop(), args[2:end]...)
end

@abstract Operations -(a::Const{T}) where T<:XScalar = Const(-a.value)
@abstract Operations -(a::AType{T}) where T<:XScalar = T
xlaop(args, ::AType{typeof(-)}, a::AType{T}) where T<:XScalar =
        xcall(Neg(), args[2:end]...)

for (op, xop) in [(exp, :Exp), (sin, :Sin), (cos, :Cos), (log, :Log)]
  @eval @abstract Operations $op(a::XFloat) = widen(a)
  @eval xlaop(args, ::AType{typeof($op)}, _) = xcall($xop(), args[2])
end

for (op, xop) in [(+, :Add), (-, :Sub)]
  @eval @abstract Operations $op(a::T, b::T) where T<:Array{<:XScalar} =
    Shape{Array{eltype(a),ndims(a)}}(size(a))
  @eval xlaop(args, ::AType{typeof($op)}, a::AType{T}, b::AType{T}) where T<:Array{<:XScalar} =
          xcall($xop(), args[2:end]...)
end

@abstract Operations reshape(A::Array{T}, i::NTuple{N,Int}) where {T<:XScalar,N} =
  Shape{Array{T,length(i.value)}}(i.value)

@abstract Operations function reshape(A::Array{T}, i::NTuple{N,Union{Int,Colon}}) where {T<:XScalar,N}
  dims = Base._reshape_uncolon(Fill(0, size(A)), i.value)
  Shape{Array{T,length(i.value)}}(dims)
end

xlaop(args, ::AType{typeof(reshape)}, x, sh::Const{NTuple{N,Int}}) where N =
  xcall(Reshape(1:ndims(x), sh.value), args[2])

xlaop(args, ::AType{typeof(reshape)}, x, sh::Const{<:Tuple{Vararg{Union{Int,Colon}}}}) =
  xcall(Reshape(1:ndims(x), Base._reshape_uncolon(Fill(0, size(x)), sh.value)), args[2])

@abstract Operations getindex(A::Vector{T}, i::Integer) where T<:XScalar = T

function xlaop!(ir, v, ::AType{typeof(getindex)}, A, i)
  args = ir[v].expr.args
  x = insert!(ir, v, xcall(DynamicSlice([1]), args[2], args[3:end]...))
  ir[v] = xcall(Reshape([1], []), x)
end

@abstract Operations function (a::Matrix{T} * b::Vector{T}) where T<:XScalar
  a isa Const && b isa Const && return Const(a.value * b.value)
  n, m = size(a)
  m == size(b)[1] || error("Dimension mismatch")
  Mjolnir.Shape{Vector{T}}((n,))
end

@abstract Operations function (a::Matrix{T} * b::Matrix{T}) where T<:XScalar
  a isa Const && b isa Const && return Const(a.value * b.value)
  n, m = size(a)
  m == size(b)[1] || error("Dimension mismatch")
  Mjolnir.Shape{Matrix{T}}((n,size(b)[2]))
end

@abstract Operations function (a::Vector{T} * b::Matrix{T}) where T<:XScalar
  a isa Const && b isa Const && return Const(a.value * b.value)
  n, = size(a)
  size(b)[1] == 1 || error("Dimension mismatch")
  Mjolnir.Shape{Vector{T}}((n,size(b)[2]))
end

function xlaop!(ir, v, ::AType{typeof(*)}, A::AType{<:Array{T}}, B::AType{<:Array{T}}) where T<:XScalar
  _, a, b = ir[v].expr.args
  A isa AType{<:Vector} && (a = insert!(ir, v, xcall(Reshape([1], [size(A)[1], 1]), a)))
  ir[v] = xcall(Dot(), a, b)
end

@abstract Operations adjoint(x::Shape{Vector{T}}) where T<:XScalar = Mjolnir.Shape{Matrix{T}}((1, size(x)[1]))
@abstract Operations adjoint(x::Shape{Matrix{T}}) where T<:XScalar = Mjolnir.Shape{Matrix{T}}(reverse(size(x)))
@abstract Operations adjoint(x::Const{<:Array{<:XScalar}}) = Const(collect(adjoint(x.value)))

xlaop(args, ::AType{typeof(adjoint)}, x::AType{<:Vector}) = xcall(Reshape([1], [1, size(x)[1]]), args[2])
xlaop(args, ::AType{typeof(adjoint)}, x::AType{<:Matrix}) = xcall(Reshape([2, 1], [reverse(size(x))...]), args[2])

xlaop(args, ::AType{typeof(repr)}, x) = args[2]

fieldnum(T, f) = findfirst(==(f), fieldnames(T))

function strip_self_arg!(ir)
  @assert exprtype(ir, arguments(ir)[1]) isa Const
  deletearg!(ir, 1)
  return ir
end

function tuplerange!(ir, v, xs, is)
  part(i) = length(layout(exprtype(ir, xs))) == 1 ? xs : insert!(ir, v, xcall(GetTupleElement(i-1), xs))
  ir[v] = length(is) == 1 ? part(is[]) : xcall(XTuple(), part.(is)...)
end

function tuplecat!(ir, v, xs)
  layouts = layout.(exprtype.((ir,), xs))
  if sum(length.(layouts)) == 1
    ir[v] = xs[findfirst(x -> !isempty(x), layouts)]
  else
    parts(i) = length(layouts[i]) == 1 ? [xs[i]] : [insert!(ir, v, xcall(GetTupleElement(j-1), xs[i])) for j = 1:length(layouts[i])]
    ir[v] = xcall(XTuple(), vcat([parts(i) for i = 1:length(xs)]...)...)
  end
end

function xlaop!(ir, v, ::AType{typeof(getindex)}, T::AType{<:Tuple}, i::Const{<:Integer})
  xs = ir[v].expr.args[2]
  is = subrange(T, i.value)
  tuplerange!(ir, v, xs, is)
end

function xlaop!(ir, v, ::AType{typeof(getfield)}, T::AType, i::Const{Symbol})
  xs = ir[v].expr.args[2]
  is = subrange(T, fieldnum(widen(T), i.value))
  tuplerange!(ir, v, xs, is)
end

function xlaop!(ir, v, ::AType{typeof(Mjolnir.__new__)}, ::AType{Type{T}}, xs...) where T
  args = ir[v].expr.args[3:end]
  tuplecat!(ir, v, args)
end

function xlaop!(ir, v, ::AType{typeof(Mjolnir.__splatnew__)}, ::AType{Type{T}}, xs) where T
  ir[v] = ir[v].expr.args[3]
end

function xlaop!(ir, v, ::AType{typeof(tuple)}, xs...)
  args = ir[v].expr.args[2:end]
  tuplecat!(ir, v, args)
end

function xlaop!(ir, v, ::AType{typeof(println)}, xs...)
  tuplecat!(ir, v, ir[v].expr.args[2:end])
end

function expand(ir, x, old, new)
  if x isa Variable
    x = insertafter!(ir, x, xcall(Reshape(1:length(old), ntuple(i -> i > length(old) ? 1 : old[i], length(new))), x))
    x = insertafter!(ir, x, xcall(BroadcastInDim(new, 1:length(new)), x))
  end
  return x
end

function xlaop!(ir, v, ::AType{typeof(broadcast)}, f, As...)
  args = ir[v].expr.args
  f = ir[args[2]].expr
  strip_self_arg!(f)
  xs = args[3:end]
  # TODO fold this into `expand`, do a generic type promotion
  for i = 1:length(xs)
    if As[i] isa Const{<:Number}
      xs[i] = fill(convert(eltype(As[1]), xs[i]), size(As[1]))
    end
  end
  new = Broadcast.broadcast_shape(size.(As)...)
  xs = expand.((ir,), xs, size.(As), (new,))
  ir[v] = Expr(:call, Map(), args[2], xs...)
end

function xlaop!(ir, v, ::AType{typeof(mapreduce)}, ::AType{typeof(identity)}, op, xs; dims = :)
  args = ir[v].expr.args
  args[1] isa KwFunc && (popfirst!(args); popfirst!(args))
  f = ir[args[3]].expr
  strip_self_arg!(f)
  if dims == (:)
    ir[v] = Expr(:call, Reduce(dims), args[3], args[4], zero(eltype(widen(xs))))
  else
    dims = filter(d -> d <= ndims(xs), collect(dims))
    out = insert!(ir, v, Expr(:call, Reduce(dims), args[3], args[4], zero(eltype(widen(xs)))))
    sz = size(ir[v].type)
    ir[v] = Expr(:call,
                 Reshape(1:length(size(xs))-length(dims),
                         ntuple(i -> i in dims ? 1 : size(xs)[i], length(sz))),
                 out)
  end
end

function xla_identity(T)
  ir = IR()
  return!(ir, argument!(ir, T))
  return ir
end

function xlaop!(ir, v, ::AType{typeof(ifelse)}, cond, T, F)
  _, cond, t, f = ir[v].expr.args
  tfunc = insert!(ir, v, xla_identity(T))
  ffunc = insert!(ir, v, xla_identity(F))
  ir[v] = xcall(Conditional(), cond, t, tfunc, f, ffunc)
end

xlaop!(ir, v, ::AType{<:KwFunc}, kw::Const, f, args...) =
  xlaop!(ir, v, f, args...; kw.value...)

function xlaop!(ir, v, args...; kw...)
  ir[v] = xlaop(ir[v].expr.args, args...; kw...)
end

function xlaops!(ir)
  for (v, st) in ir
    if st.expr isa Expr
      xlaop!(ir, v, exprtype.((ir,), st.expr.args)...)
    elseif st.expr isa IR
      ir[v] = xlaops!(st.expr)
    end
  end
  # TODO: more fine grained way of ensuring the right return value.
  t = push!(ir, xcall(XTuple(), returnvalue(blocks(ir)[end])))
  push!(ir, xcall(GetTupleElement(0), t))
  return ir
end

function flattenargs!(ir, T)
  arglayout = (layout(T)...,)
  args = copy(arguments(ir))
  deletearg!(ir, 1:length(args))
  components = [argument!(ir, arglayout[i]) for i = 1:length(arglayout)]
  env = Dict()
  for i = 1:length(args)
    cs = components[subrange(T,i)]
    env[args[i]] = length(cs) == 1 ? cs[1] : pushfirst!(ir, xcall(XTuple(), cs...))
  end
  prewalk!(x -> get(env, x, x), ir)
  for (v, st) in ir
    ir[v] = stmt(st, type = Any)
  end
  return ir
end

function convert_xla!(ir, T)
  xlaops!(ir)
  flattenargs!(ir, T)
  return ir
end


text:
using StochasticBlockModel
using Test

@testset "SBM struct" begin

    w = [1.0 0.3; 0.3 1.2]
    sbm = StochasticBlockModel.SBM(w, "poisson")
    @test sbm.w == w
    @test sbm.dist == "poisson"
    @test sbm.n_communities == 2

    @test_throws ArgumentError StochasticBlockModel.SBM([1.0 0; 0 1; 9 1], "poisson")
    @test_throws DomainError StochasticBlockModel.SBM([1.0 0; 0 -1], "bernoulli")
    @test_throws DomainError StochasticBlockModel.SBM([1.0 0; 0 1.2], "bernoulli")
    @test_throws ArgumentError StochasticBlockModel.SBM([1.0 0; 0.2 0.5], "bernoulli")
end

@testset "Generate graphs" begin

    expected_A =[0  1  2  1  0  0  0  0
                 1  0  1  1  0  0  0  0
                 2  1  0  1  0  0  0  0
                 1  1  1  2  0  0  0  0
                 0  0  0  0  2  0  2  3
                 0  0  0  0  0  0  0  1
                 0  0  0  0  2  0  0  1
                 0  0  0  0  3  1  1  0]
    dataset = StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [4; 4], seed=2)
    @test dataset.A == expected_A
    @test dataset.n_communities == 2

    expected_A = [0  1  2  0  0  0
                  1  0  1  0  0  0
                  2  1  0  0  0  0
                  0  0  0  2  2  2
                  0  0  0  2  2  0
                  0  0  0  2  0  0]
    dataset = StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [3; 3], seed=2)
    @test dataset.A == expected_A
    @test dataset.n_communities == 2

    expected_A = [0  1  1  1  0  0  0  0
                  1  0  1  1  0  0  0  0
                  1  1  0  1  0  0  0  0
                  1  1  1  0  0  0  0  0
                  0  0  0  0  0  1  1  1
                  0  0  0  0  1  0  1  1
                  0  0  0  0  1  1  0  1
                  0  0  0  0  1  1  1  0]
    dataset = StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [4; 4], distribution="bernoulli", seed=2)
    @test dataset.A == expected_A
    @test dataset.n_communities == 2

    # Test for invalid argument for "distribution"
    @test_throws ArgumentError StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [4; 4], distribution="a", seed=2)

    # Test for invalid argument for "n_per_community"
    @test_throws DomainError StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [4; -4], distribution="poisson", seed=2)
    @test_throws DomainError StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [0; 2], distribution="bernoulli", seed=2)
    @test_throws ArgumentError StochasticBlockModel.generate([1.0 0.0; 0.0 1.0], [1; 2; 4], distribution="bernoulli", seed=2)

    # Test for invalid argument for "probability_matrix"
    @test_throws DomainError StochasticBlockModel.generate([1.0 -0.2; 0.0 1.0], [4; 4], distribution="poisson", seed=2)
    @test_throws DomainError StochasticBlockModel.generate([-1.0 0.0; 0.0 1.0], [2; 2], distribution="bernoulli", seed=2)
end


text:
abstract type ExptData end

struct R2Data <: ExptData
    ZQ
    DQ
    QQ⁻
    QQ⁺
    B0
    R2Data(ZQ, DQ, QQ⁻, QQ⁺, B0=nothing) = new(ZQ, DQ, QQ⁻, QQ⁺, B0)
end

abstract type CPMGData <: ExptData end

struct CPMGData_MQ <: CPMGData
    νCPMG
    R2eff
    B0
    Trelax
end

struct CPMGData_SQ1H <: CPMGData
    νCPMG
    R2eff
    B0
    Trelax
end

struct modelpars_2state
    kex
    pB
end

max_stars_repo_name: chriswaudby/qq-hahnecho

max_issues_repo_name: chriswaudby/qq-hahnecho

max_forks_repo_name: chriswaudby/qq-hahnecho


text:
function parse_input(io::IO)
    monad = []
    while !eof(io)
        line = readline(io)
        isempty(line) && continue
        (opc, args...) = split(line, ' ')
        opc = getfield(@__MODULE__, Symbol(opc))
        tgt = Symbol(args[1])
        src = length(args) == 1 ? nothing : args[2][1] ∈ "xyzw" ?
            Symbol(args[2]) : parse(Int, args[2])
        push!(monad, (opc, tgt, src))
    end
    return monad
end

mutable struct ALU
    x
    y
    z
    w
    ALU(x = 0, y = 0, z = 0, w = 0) = new(x, y, z, w)
end

Base.getindex(alu::ALU, v::Integer) = v
Base.getindex(alu::ALU, r::Symbol) = getfield(alu, r)
Base.setindex!(alu::ALU, v, r::Symbol) = setfield!(alu, r, v)

inp(tgt::Symbol, ::Nothing, alu::ALU, in::Vector) = alu[tgt] = popfirst!(in)
add(tgt::Symbol, src, alu::ALU, _) = alu[tgt] = alu[tgt] + alu[src]
mul(tgt::Symbol, src, alu::ALU, _) = alu[tgt] = alu[tgt] * alu[src]
div(tgt::Symbol, src, alu::ALU, _) = alu[tgt] = alu[tgt] ÷ alu[src]
mod(tgt::Symbol, src, alu::ALU, _) = alu[tgt] = alu[tgt] % alu[src]
eql(tgt::Symbol, src, alu::ALU, _) = alu[tgt] = alu[tgt] == alu[src] ? 1 : 0

function run(code::AbstractVector, input::Int, alu::ALU = ALU())::Int
    input = parse.(Int, split(string(input), ""))
    for (opc, tgt, src) in code
        if opc == inp && isempty(input)
            @warn "terminate early"
            return alu
        end
        opc(tgt, src, alu, input)
    end
    isempty(input) || @warn "unparsed input $(join(input))"
    return alu.z
end

monad = open(parse_input, "day24.in", "r")

# for calculations, see day24-decoded.txt

@assert run(monad, 93997999296912) == 0 # Q1, largest model number
@assert run(monad, 81111379141811) == 0 # Q2, smallest model number

max_stars_repo_name: dhanak/competitive-coding

max_issues_repo_name: dhanak/competitive-coding

max_forks_repo_name: dhanak/competitive-coding


text:
module RipQP

using LinearAlgebra, Quadmath, SparseArrays, Statistics

using LDLFactorizations, QuadraticModels, SolverCore

export ripqp

include("types_definition.jl")
include("iterations/iterations.jl")
include("refinement.jl")
include("data_initialization.jl")
include("starting_points.jl")
include("scaling.jl")
include("multi_precision.jl")

"""
    stats = ripqp(QM :: QuadraticModel; iconf :: InputConfig{Int} = InputConfig(),
                  itol :: InputTol{Tu, Int} = InputTol(),
                  display :: Bool = true) where {Tu<:Real}

Minimize a convex quadratic problem. Algorithm stops when the criteria in pdd, rb, and rc are valid.
Returns a [GenericExecutionStats](https://juliasmoothoptimizers.github.io/SolverCore.jl/dev/api/#SolverCore.GenericExecutionStats)
containing information about the solved problem.

- `QM :: QuadraticModel`: problem to solve
- `iconf :: InputConfig{Int}`: input RipQP configuration. See `InputConfig{I}`.
- `itol :: InputTol{T, Int}` input Tolerances for the stopping criteria. See `InputTol{T, I}`.
- `display::Bool`: activate/deactivate iteration data display
"""
function ripqp(QM :: QuadraticModel; iconf :: InputConfig{Int} = InputConfig(), itol :: InputTol{Tu, Int} = InputTol(),
               display :: Bool = true) where {Tu<:Real}

    start_time = time()
    elapsed_time = 0.0
    sc = StopCrit(false, false, false, false, itol.max_iter, itol.max_time, start_time, 0.)

    nvar_init = QM.meta.nvar
    SlackModel!(QM) # add slack variables to the problem if QM.meta.lcon != QM.meta.ucon

    fd_T0, id, T = get_QM_data(QM)
    T0 = T # T0 is the data type, in mode :multi T will gradually increase to T0
    ϵ = Tolerances(T(itol.ϵ_pdd), T(itol.ϵ_rb), T(itol.ϵ_rc), one(T), one(T), T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol)

    if iconf.scaling
        fd_T0, d1, d2, d3 = scaling_Ruiz!(fd_T0, id, T(1.0e-3))
    end

    # initialization
    if iconf.mode == :multi
        T = Float32
        ϵ32 = Tolerances(T(itol.ϵ_pdd32), T(itol.ϵ_rb32), T(itol.ϵ_rc32), one(T), one(T), T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol)
        fd32 = convert_FloatData(T, fd_T0)
        itd, ϵ32, dda, pad, pt, res, sc, cnts = init_params(fd32, id, ϵ32, sc, iconf, T0)
        set_tol_residuals!(ϵ, T0(res.rbNorm), T0(res.rcNorm))
        if T0 == Float128
            T = Float64
            fd64 = convert_FloatData(T, fd_T0)
            ϵ64 = Tolerances(T(itol.ϵ_pdd64), T(itol.ϵ_rb64), T(itol.ϵ_rc64), one(T), one(T), T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol)
            set_tol_residuals!(ϵ64, T(res.rbNorm), T(res.rcNorm))
            T = Float32
        end
    elseif iconf.mode == :mono
        itd, ϵ, dda, pad, pt, res, sc, cnts = init_params(fd_T0, id, ϵ, sc, iconf, T0)
    end

    Δt = time() - start_time
    sc.tired = Δt > itol.max_time

    cnts = Counters(zero(Int), zero(Int), 0, 0, iconf.kc==-1 ? nb_corrector_steps(pad.K.colptr, id.ncon, id.nvar, T) : iconf.kc,
                    iconf.max_ref, zero(Int))

    # display
    if display == true
        @info log_header([:k, :pri_obj, :pdd, :rbNorm, :rcNorm, :n_Δx, :α_pri, :α_du, :μ],
        [Int, T, T, T, T, T, T, T, T, T, T, T],
        hdr_override=Dict(:k => "iter", :pri_obj => "obj", :pdd => "rgap",
        :rbNorm => "‖rb‖", :rcNorm => "‖rc‖",
        :n_Δx => "‖Δx‖"))
        @info log_row(Any[cnts.k, itd.pri_obj, itd.pdd, res.rbNorm, res.rcNorm, res.n_Δx, zero(T), zero(T), itd.μ])
    end

    if iconf.mode == :multi
        # iter in Float32 then convert data to Float64
        pt, itd, res, dda, pad = iter_and_update_T!(pt, itd, fd32, id, res, sc, dda, pad, ϵ32, ϵ, cnts,
                                                    itol.max_iter32, Float64, display)

        if T0 == Float128
            # iters in Float64 then convert data to Float128
            pt, itd, res, dda, pad = iter_and_update_T!(pt, itd, fd64, id, res, sc, dda, pad, ϵ64, ϵ, cnts,
                                                        itol.max_iter64, Float128, display)
        end
        sc.max_iter = itol.max_iter
    end

    ## iter T0
    # refinement
    if iconf.refinement == :zoom || iconf.refinement == :ref
        ϵz = Tolerances(T(1), T(itol.ϵ_rbz), T(itol.ϵ_rbz), T(ϵ.tol_rb * T(itol.ϵ_rbz / itol.ϵ_rb)), one(T),
                        T(itol.ϵ_μ), T(itol.ϵ_Δx), iconf.normalize_rtol)
        iter!(pt, itd, fd_T0, id, res, sc, dda, pad, ϵz, cnts, T0, display)
        sc.optimal = false

        fd_ref, pt_ref = fd_refinement(fd_T0, id, res, itd.Δxy, pt, itd, ϵ, dda, pad, cnts, T0, iconf.refinement)
        iter!(pt_ref, itd, fd_ref, id, res, sc, dda, pad, ϵ, cnts, T0, display)
        update_pt_ref!(fd_ref.Δref, pt, pt_ref, res, id, fd_T0, itd)

    elseif iconf.refinement == :multizoom || iconf.refinement == :multiref
        fd_ref, pt_ref = fd_refinement(fd_T0, id, res, itd.Δxy, pt, itd, ϵ, dda, pad, cnts, T0, iconf.refinement, centering = true)
        iter!(pt_ref, itd, fd_ref, id, res, sc, dda, pad, ϵ, cnts, T0, display)
        update_pt_ref!(fd_ref.Δref, pt, pt_ref, res, id, fd_T0, itd)

    else
        # iters T0, no refinement
        iter!(pt, itd, fd_T0, id, res, sc, dda, pad, ϵ, cnts, T0, display)
    end

    # output status
    if cnts.k>= itol.max_iter
        status = :max_iter
    elseif sc.tired
        status = :max_time
    elseif sc.optimal
        status = :acceptable
    else
        status = :unknown
    end

    if iconf.scaling
        pt, pri_obj, res = post_scale(d1, d2, d3, pt, res, fd_T0, id, itd.Qx, itd.ATy,
                                      itd.Ax, itd.cTx, itd.pri_obj, itd.dual_obj, itd.xTQx_2)
    end

    elapsed_time = time() - sc.start_time

    stats = GenericExecutionStats(status, QM, solution = pt.x[1:nvar_init],
                                  objective = itd.pri_obj,
                                  dual_feas = res.rcNorm,
                                  primal_feas = res.rbNorm,
                                  multipliers = pt.y,
                                  multipliers_L = pt.s_l,
                                  multipliers_U = pt.s_u,
                                  iter = cnts.km,
                                  elapsed_time = elapsed_time,
                                  solver_specific = Dict(:absolute_iter_cnt=>cnts.k))
    return stats
end

end


text:
# algorithm 4 in section 5.4 of https://www.annualreviews.org/doi/10.1146/annurev-conmatphys-031016-025507

struct bimps
    A::TensorMap{ComplexSpace, 2, 1}
    B::TensorMap{ComplexSpace, 2, 1}
end

function bimps(f, chi::Integer, d::Integer)
    A = TensorMap(f, ComplexF64, ℂ^chi*ℂ^d, ℂ^chi)
    B = TensorMap(f, ComplexF64, ℂ^chi*ℂ^d, ℂ^chi)
    return bimps(A, B)
end

function A_canonical(T::TensorMap{ComplexSpace, 2, 2}, psi::bimps, tol::Float64=1e-15)

    # convert A to right canonical form
    Y, AR = right_canonical_QR(psi.A, tol)
    Yinv = inv(Y')'
    @tensor BR[-1, -2; -3] := psi.B[1, -2, 2] * Yinv'[-1, 1] * Y'[2, -3]

    # construct the linear operator for the maping of B
    function lop(v::TensorMap{ComplexSpace, 2, 1})
        @tensor Tv[-1, -2; -3] := v[1, 3, 4] * AR'[4, -3, 5] * AR[-1, 2, 1] * T[-2, 5, 2, 3]
        return Tv
    end

    # solve BR from the fixed point equation
    λ, BR = eigsolve(lop, BR, 1)
    BR = BR[1]
    λ = λ[1]
    return λ, bimps(AR, BR)
end

function B_canonical(T::TensorMap{ComplexSpace, 2, 2}, psi::bimps, tol::Float64=1e-15)

    # convert B to left canonical form
    X, BL = left_canonical_QR(psi.B, tol)
    Xinv = inv(X)
    @tensor AL[-1, -2; -3] := X[-1, 1] * psi.A[1, -2, 2] * Xinv[2, -3]

    # construct the linear operator for the maping of A
    function lop(v::TensorMap{ComplexSpace, 2, 1})
        @tensor Tv[-1, -2; -3] := v[4, 2, 1] * BL[1, 3, -3] * T[5, -2, 2, 3] * BL'[-1, 4, 5]
        return Tv
    end

    # solve AR from the fixed point equation
    λ, AL = eigsolve(lop, AL, 1)
    AL = AL[1]
    λ = λ[1]
    return λ, bimps(AL, BL)
end


text:
#cd("$(homedir())/Documents/GitHub")

# Push Documents/GitHub on the search path
push!(LOAD_PATH, "$(homedir())/Documents/GitHub")

using NEPA
using Base.Test

# Test DEAData.jl
X = [1 2 3;4 5 6; 7 8 9]
Y = [2;5;8]
Data = DEAData(X,Y,X,Y)

@test getnrdmu(Data) == 3
@test getiodim(Data) == (3,1)
@test getindexes(Data) == [1,2,3]
@test size(Data) == (3,)

for i in eachindex(Data)
  Xk,Yk,gxk,gyk = Data[i]
  @test (Xk,Yk,gxk,gyk) == (X[i,:],Y[i,:],X[i,:],Y[i,:])
  @test Xk == gxk
  @test Yk == gyk
end

ind = [1,3]
@test Data[ind] == (X[ind,:],Y[ind,:],X[ind,:],Y[ind,:])
@test Data[1:end] == (X[1:end,:],Y[1:end,:],X[1:end,:],Y[1:end,:])

Data = DEAData(X,Y,X,Y,indexes = ind)
@test Data[1:end] == (X[ind,:],Y[ind,:],X[ind,:],Y[ind,:])

# Test AbstractDEA
@test eltype(AbstractDEA{Convex,VRS}) == (Convex,VRS)
@test eltype(AbstractDEA{FreeDisposal,VRS}) != (Convex,VRS)
@test eltype(AbstractDEA{FreeDisposal,CRS}) == (FreeDisposal,CRS)
@test eltype(AbstractDEA{FreeDisposal,VRS}) != (FreeDisposal,CRS)

#Test SBM model using Tone(2001) example
X = [4.0 3.0; 6.0 3.0; 8.0 1.0; 8.0 1.0; 2.0 4.0]
Y = [2.0 3.0; 2.0 3.0; 6.0 2.0; 6.0 1.0; 1.0 4.0]

D = SBM{CRS}(X,Y)
@test D[[1,2,5]] == (X[[1,2,5],:],Y[[1,2,5],:])
@test_throws BoundsError D[[3,6]]
sbmres = D()
@test geteff(sbmres) ≈ [0.798 0.568 1.0 0.667 1.0]' atol=1e-3
D = DEA_CRS(X,Y,true)
deares = D()
@test geteff(deares) ≈ [0.9 0.833 1.0 1.0 1.0]' atol=1e-3

#Base.show(deares[1])
#Base.show(sbmres)
#Base.show(deares)

Dout = DEA_CRS(X,Y,false)
@test geteff(Dout()) ≈ 1./geteff(deares) atol=1e-3

H = Hyperbolic{FreeDisposal,CRS}(X,Y)
F = FDH_CRS(X,Y,false)
@test geteff(H()) ≈ 1./geteff(F()) atol=1e-3

#Test DDF model using Cherchye et al. (2001) numerical example
X = [3.0;6.0;4.0;6.0;5.0;8.0;12.0;14.0;18.0]
Y = [4.0;5.0;6.0;7.0;8.0;9.0;11.0;13.0;14.0]

DDFMcFadden = DDF{FreeDisposal,VRS}(X,Y,-X,Y)
@test geteff(DDFMcFadden(X[2,:],Y[2,:],-X[2,:],Y[2,:])) ≈ 1.6 atol=1e-3
@test find(getpeers(DDFMcFadden(X[2,:],Y[2,:],-X[2,:],Y[2,:])) .> 0.0) == [8] # peer H

Ysens = zeros(9)
Ysens[9,:] = 1.0
DDFMcFadden = DDF{FreeDisposal,VRS}(X,Y+Ysens,-X,Y+Ysens)
@test geteff(DDFMcFadden(X[2,:],Y[2,:],-X[2,:],Y[2,:])) ≈ 2.0 atol=1e-3
@test find(getpeers(DDFMcFadden(X[2,:],Y[2,:],-X[2,:],Y[2,:])) .> 0.0) == [9] # peer I

#FIXME For some reason incorrect results: it should be 9.5 but we find 1.8...
Xsens = zeros(9)
Xsens[9,:] = 1.2
DDFMcFadden = DDF{FreeDisposal,VRS}(X-Xsens,Y,-X+Xsens,Y)
#@test geteff(DDFMcFadden(X[2,:],Y[2,:],-X[2,:],Y[2,:])) ≈ 9.5 atol=1e-3
@test find(getpeers(DDFMcFadden(X[2,:],Y[2,:],-X[2,:],Y[2,:])) .> 0.0) == [9] # peer I

Graph = Hyperbolic{FreeDisposal,VRS}(X,Y)
println(geteff(Graph()))

max_stars_repo_name: kepiej/NEPA


text:
module LatPhysPlottingMakie

using Reexport
using LatPhysBase, LatPhysReciprocal, LatPhysBandstructures

using LinearAlgebra, Printf
using Statistics: mean
using GeometryBasics
using Makie, MakieCore
@reexport using Colors

import MakieCore: convert_arguments, PointBased, Plot, default_theme,
    plot!, automatic, Attributes

include("colorcodes.jl")
include("Makie_helpers.jl")
export setup_axis!

include("MakieExtensions.jl")
include("combined_plots.jl")
export BandstructureGUI

end # module


text:
using Test
include(normpath(joinpath(dirname(@__FILE__),"..","src","ClustForOpt_priv_development.jl")))

@testset "z_normalize" begin
  #srand(1991)
  data = rand(24,365)
  # hourly
  dn,mn,sdv = z_normalize(data;scope="hourly")
  @test sum(mn - mean(data,dims=2)) <= 1e-8
  @test sum(sdv - std(data,dims=2)) <= 1e-8

  data_out = undo_z_normalize(dn,mn,sdv)
  @test sum(data_out - data) <=1e-8

  # full
  dn,mn,sdv = z_normalize(data;scope="full")
  @test sum(mn .- mean(data)) <= 1e-8
  @test sum(sdv .- std(data)) <= 1e-8

  data_out = undo_z_normalize(dn,mn,sdv)
  @test sum(data_out - data) <=1e-8

  # sequence
  data = ones(5,4)
  m_t=zeros(4)
  sdv_t=zeros(4)
  d1 = [1,2,3,4,5]
  m_t[1] = mean(d1)
  sdv_t[1]= std(d1)
  d2 = [3,3,3,3,3]
  m_t[2] = mean(d2)
  sdv_t[2] = std(d2)
  d3 = [-1,-2,1,2,0]
  m_t[3] = mean(d3)
  sdv_t[3] = std(d3)
  d4 = [0,1,5,3,4]
  m_t[4] = mean(d4)
  sdv_t[4] = std(d4)
  data[:,1]=d1
  data[:,2]=d2
  data[:,3]=d3
  data[:,4]=d4
  dn,mn,sdv = z_normalize(data;scope="sequence")
  println(mn)
  println(sdv)
  println(dn)
  @test sum(m_t -mn) <= 1e-8
  @test sum(sdv_t - sdv) <= 1e-8
  @test sum(isnan.(dn)) == 0 # tests edge case standard deviation 0

  data_out = undo_z_normalize(ones(5,2),mn,sdv;idx=[1,2,2,1])
  @test size(data_out,2) ==2
  @test sum(data_out[:,1] - ( ones(5)*1*(sdv_t[1]+sdv_t[4])/2 .+ (m_t[1]+m_t[4])/2) ) <=1e-8
  @test sum(data_out[:,2] - ( ones(5)*1*(sdv_t[2]+sdv_t[3])/2 .+ (m_t[2]+m_t[3])/2) ) <=1e-8

  # edge case 1: data with zero standard deviation
  data = zeros(24,365)
  # full
  dn,mn,sdv = z_normalize(data;scope="full")
  @test sum(mn .- mean(data)) <= 1e-8
  @test sum(sdv .- std(data)) <= 1e-8
  data_out = undo_z_normalize(dn,mn,sdv)
  @test sum(data_out - data) <=1e-8

  # hour
  dn,mn,sdv = z_normalize(data;scope="hourly")
  @test sum(mn - mean(data,dims=2)) <= 1e-8
  @test sum(sdv - std(data,dims=2)) <= 1e-8

  data_out = undo_z_normalize(dn,mn,sdv)
  @test sum(data_out - data) <=1e-8

  # sequence
  #already covered by case above d2

  # edge case 2: data with zero standard deviation, but nonzero values
  data = ones(24,365)
  # full
  dn,mn,sdv = z_normalize(data;scope="full")
  @test sum(mn .- mean(data)) <= 1e-8
  @test sum(sdv .- std(data)) <= 1e-8
  data_out = undo_z_normalize(dn,mn,sdv)
  @test sum(data_out - data) <=1e-8

  # hour
  dn,mn,sdv = z_normalize(data;scope="hourly")
  @test sum(mn - mean(data,dims=2)) <= 1e-8
  @test sum(sdv - std(data,dims=2)) <= 1e-8

  data_out = undo_z_normalize(dn,mn,sdv)
  @test sum(data_out - data) <=1e-8

  # sequence
  #already covered by case above d2

end


text:
module TriMatrices

using LinearAlgebra
using DocStringExtensions

export TriUpper, TriLower, TriSymmetric, TriMatrix

include("layout.jl")

include("Indexing/Indexing.jl")
using .Indexing

include("trimatrix.jl")
include("linearalgebra.jl")
include("Testing.jl")

end # module


text:
function assert_pd(d, α)
    @assert α == 0 && all(x -> x > 0, d) "The input matrix is not positive definite."
end

function update_L!(L, d)
    @inbounds for j in 1:size(L, 2)
        _d = sqrt(d[j])
        L[j,j] = _d
        for i in Base.Iterators.drop(nzrange(L, j), 1)
            L.nzval[i] *= _d
        end
    end
    return L
end

mutable struct CholeskyPreconditioner{T, S <: AbstractSparseMatrix{T}} <: AbstractPreconditioner
    L::LowerTriangular{T, S}
    memory::Int
end
function EmptyCholeskyPreconditioner(A, memory=1)
    T = eltype(A)
    _A = A isa Symmetric || A isa Hermitian ? A.data : A
    return CholeskyPreconditioner(LowerTriangular(sparse(one(T)*I, size(_A)...)), memory)
end

function CholeskyPreconditioner(A, memory=2)
    _A = get_data(A)
    L, d, α = lldl(_A, memory=memory)
    assert_pd(d, α)
    update_L!(L, d)
    return CholeskyPreconditioner(LowerTriangular(L), memory)
end

function UpdatePreconditioner!(C::CholeskyPreconditioner, A, memory=C.memory)
    _A = get_data(A)
    L, d, α = lldl(_A, memory=memory)
    assert_pd(d, α)
    update_L!(L, d)
    C.L = LowerTriangular(L)
    return C
end

@inline function ldiv!(C::CholeskyPreconditioner{T}, y::AbstractVector{T}) where {T}
    ldiv!(C.L, y)
    return ldiv!(C.L', y)
end
@inline function ldiv!(y::AbstractVector{T}, C::CholeskyPreconditioner{T}, b::AbstractVector{T}) where {T}
    y .= b
    return ldiv!(C, y)
end
@inline function (\)(C::CholeskyPreconditioner{T, <:AbstractSparseMatrix{T}}, b::AbstractVector{T}) where {T}
    y = copy(b)
    return ldiv!(C, y)
end