text:
"""
This module defines the mpf, mpc classes, and standard functions for
operating with them.
"""
__docformat__ = 'plaintext'

import re

from settings import (MP_BASE, MP_ONE, mp, prec_rounding, extraprec, extradps,
    workprec, workdps, int_types, repr_dps, round_floor, round_ceiling, dps_to_prec)

from libmpf import (
    ComplexResult, to_pickable, from_pickable, normalize,
    from_int, from_float, from_str, to_int, to_float, to_str,
    from_rational, from_man_exp,
    fone, fzero, finf, fninf, fnan,
    mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,
    mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,
    mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,
    mpf_hash, mpf_rand,
    mpf_sum
)

from libmpc import (
    complex_to_str,
    mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,
    mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int
)

from libelefun import mpf_pow

from libmpi import (
    mpi_mid, mpi_delta, mpi_str,
    mpi_abs, mpi_pos, mpi_neg, mpi_add, mpi_sub,
    mpi_mul, mpi_div, mpi_pow_int, mpi_pow
)

class mpnumeric(object):
    """Base class for mpf and mpc. Calling mpnumeric(x) returns an mpf
    if x can be converted to an mpf (if it is a float, int, mpf, ...),
    and an mpc if x is complex."""
    __slots__ = []
    def __new__(cls, val):
        # TODO: should maybe normalize here
        if isinstance(val, cls): return val
        if isinstance(val, complex): return mpc(val)
        return mpf(val)

get_complex = re.compile(r'^\(?(?P<re>[\+\-]?\d*\.?\d*(e[\+\-]?\d+)?)??'
                         r'(?P<im>[\+\-]?\d*\.?\d*(e[\+\-]?\d+)?j)?\)?$')
# TODO: add tests

def mpmathify(x, strings=True):
    """
    Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``,
    ``mpc``, ``int``, ``float``, ``complex``, the conversion
    will be performed losslessly.

    If *x* is a string, the result will be rounded to the present
    working precision. Strings representing fractions or complex
    numbers are permitted.

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> mpmathify(3.5)
        mpf('3.5')
        >>> mpmathify('2.1')
        mpf('2.1000000000000001')
        >>> mpmathify('3/4')
        mpf('0.75')
        >>> mpmathify('2+3j')
        mpc(real='2.0', imag='3.0')

    """
    if isinstance(x, mpnumeric): return x
    if isinstance(x, int_types): return make_mpf(from_int(x))
    if isinstance(x, float): return make_mpf(from_float(x))
    if isinstance(x, complex): return mpc(x)
    if strings and isinstance(x, basestring):
        try:
            return make_mpf(from_str(x, *prec_rounding))
        except Exception, e:
            if '/' in x:
                fract = x.split('/')
                assert len(fract) == 2
                return mpmathify(fract[0]) / mpmathify(fract[1])
            if 'j' in x.lower():
                x = x.lower().replace(' ', '')
                match = get_complex.match(x)
                re = match.group('re')
                if not re:
                    re = 0
                im = match.group('im').rstrip('j')
                return mpc(mpmathify(re),
                           mpmathify(im))
            raise e
    if hasattr(x, '_mpf_'): return make_mpf(x._mpf_)
    if hasattr(x, '_mpc_'): return make_mpc(x._mpc_)
    if hasattr(x, '_mpmath_'):
        return mpmathify(x._mpmath_(*prec_rounding))
    raise TypeError("cannot create mpf from " + repr(x))

def try_convert_mpf_value(x, prec, rounding):
    if isinstance(x, float): return from_float(x)
    if hasattr(x, '_mpf_'): return x._mpf_
    if hasattr(x, '_mpmath_'):
        t = mpmathify(x._mpmath_(prec, rounding))
        if isinstance(t, mpf):
            return t._mpf_
    return NotImplemented

def mpf_convert_arg(x, prec, rounding):
    if isinstance(x, int_types): return from_int(x)
    if isinstance(x, float): return from_float(x)
    if isinstance(x, basestring): return from_str(x, prec, rounding)
    if isinstance(x, constant): return x.func(prec, rounding)
    if hasattr(x, '_mpf_'): return x._mpf_
    if hasattr(x, '_mpmath_'):
        t = mpmathify(x._mpmath_(prec, rounding))
        if isinstance(t, mpf):
            return t._mpf_
    raise TypeError("cannot create mpf from " + repr(x))

def mpf_convert_rhs(x):
    if isinstance(x, int_types): return from_int(x)
    if isinstance(x, float): return from_float(x)
    if isinstance(x, complex_types): return mpc(x)
    if hasattr(x, '_mpf_'): return x._mpf_
    if hasattr(x, '_mpmath_'):
        t = mpmathify(x._mpmath_(*prec_rounding))
        if isinstance(t, mpf):
            return t._mpf_
        return t
    return NotImplemented

def mpf_convert_lhs(x):
    x = mpf_convert_rhs(x)
    if type(x) is tuple:
        return make_mpf(x)
    return x

def mpc_convert_lhs(x):
    try:
        return mpmathify(x)
    except TypeError:
        return NotImplemented

new = object.__new__

class mpf(mpnumeric):
    """
    An mpf instance holds a real-valued floating-point number. mpf:s
    work analogously to Python floats, but support arbitrary-precision
    arithmetic.
    """
    __slots__ = ['_mpf_']

    def __new__(cls, val=fzero, **kwargs):
        """A new mpf can be created from a Python float, an int, a
        or a decimal string representing a number in floating-point
        format."""
        prec, rounding = prec_rounding
        if kwargs:
            prec = kwargs.get('prec', prec)
            if 'dps' in kwargs:
                prec = dps_to_prec(kwargs['dps'])
            rounding = kwargs.get('rounding', rounding)
        if type(val) is cls:
            sign, man, exp, bc = val._mpf_
            if (not man) and exp:
                return val
            return make_mpf(normalize(sign, man, exp, bc, prec, rounding))
        elif type(val) is tuple:
            if len(val) == 2:
                return make_mpf(from_man_exp(val[0], val[1], prec, rounding))
            if len(val) == 4:
                sign, man, exp, bc = val
                return make_mpf(normalize(sign, MP_BASE(man), exp, bc, prec, rounding))
            raise ValueError
        else:
            return make_mpf(mpf_pos(mpf_convert_arg(val, prec, rounding), prec, rounding))

    man_exp = property(lambda self: self._mpf_[1:3])
    man = property(lambda self: self._mpf_[1])
    exp = property(lambda self: self._mpf_[2])
    bc = property(lambda self: self._mpf_[3])

    real = property(lambda self: self)
    imag = property(lambda self: zero)

    conjugate = lambda self: self

    def __getstate__(self): return to_pickable(self._mpf_)
    def __setstate__(self, val): self._mpf_ = from_pickable(val)

    def __repr__(s): return "mpf('%s')" % to_str(s._mpf_, repr_dps(mp.prec))
    def __str__(s): return to_str(s._mpf_, mp.dps)
    def __hash__(s): return mpf_hash(s._mpf_)
    def __int__(s): return int(to_int(s._mpf_))
    def __long__(s): return long(to_int(s._mpf_))
    def __float__(s): return to_float(s._mpf_)
    def __complex__(s): return complex(float(s))
    def __nonzero__(s): return s._mpf_ != fzero
    def __abs__(s): return make_mpf(mpf_abs(s._mpf_, *prec_rounding))
    def __pos__(s): return make_mpf(mpf_pos(s._mpf_, *prec_rounding))
    def __neg__(s): return make_mpf(mpf_neg(s._mpf_, *prec_rounding))

    def _cmp(s, t, func):
        if hasattr(t, '_mpf_'):
            t = t._mpf_
        else:
            t = mpf_convert_rhs(t)
            if t is NotImplemented:
                return t
        return func(s._mpf_, t)

    def __cmp__(s, t): return s._cmp(t, mpf_cmp)
    def __lt__(s, t): return s._cmp(t, mpf_lt)
    def __gt__(s, t): return s._cmp(t, mpf_gt)
    def __le__(s, t): return s._cmp(t, mpf_le)
    def __ge__(s, t): return s._cmp(t, mpf_ge)

    def __ne__(s, t):
        v = s.__eq__(t)
        if v is NotImplemented:
            return v
        return not v

    def __rsub__(s, t):
        prec, rounding = prec_rounding
        if type(t) in int_types:
            return make_mpf(mpf_sub(from_int(t), s._mpf_, prec, rounding))
        t = mpf_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t - s

    def __rdiv__(s, t):
        prec, rounding = prec_rounding
        if isinstance(t, int_types):
            return make_mpf(mpf_rdiv_int(t, s._mpf_, prec, rounding))
        t = mpf_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t / s

    def __rpow__(s, t):
        t = mpf_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t ** s

    def __rmod__(s, t):
        t = mpf_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t % s

    def sqrt(s):
        from functions import sqrt
        return sqrt(s)

    def ae(s, t, rel_eps=None, abs_eps=None):
        return almosteq(s, t, rel_eps, abs_eps)

mpf_binary_op = """
def %NAME%(self, other):
    prec, rounding = prec_rounding
    sval = self._mpf_
    if hasattr(other, '_mpf_'):
    #try:
        tval = other._mpf_
        %WITH_MPF%
    #except AttributeError:
    #    pass
    ttype = type(other)
    if ttype in int_types:
        %WITH_INT%
    elif ttype is float:
        tval = from_float(other)
        %WITH_MPF%
    elif ttype is mpc:
        tval = other._mpc_
        %WITH_MPC%
    elif ttype is complex:
        tval = from_float(other.real), from_float(other.imag)
        %WITH_MPC%
    if isinstance(other, mpnumeric):
        return NotImplemented
    try:
        other = mpmathify(other, strings=False)
    except TypeError:
        return NotImplemented
    return self.%NAME%(other)
"""

return_mpf = "; obj = new(mpf); obj._mpf_ = val; return obj"
return_mpc = "; obj = new(mpc); obj._mpc_ = val; return obj"

mpf_pow_same = """
        try:
            val = mpf_pow(sval, tval, prec, rounding) %s
        except ComplexResult:
            if mp.trap_complex:
                raise
            val = mpc_pow((sval, fzero), (tval, fzero), prec, rounding) %s
""" % (return_mpf, return_mpc)

def binary_op(name, with_mpf='', with_int='', with_mpc=''):
    code = mpf_binary_op
    code = code.replace("%WITH_INT%", with_int)
    code = code.replace("%WITH_MPC%", with_mpc)
    code = code.replace("%WITH_MPF%", with_mpf)
    code = code.replace("%NAME%", name)
    np = {}
    exec code in globals(), np
    return np[name]

mpf.__eq__ = binary_op('__eq__',
    'return mpf_eq(sval, tval)',
    'return mpf_eq(sval, from_int(other))',
    'return (tval[1] == fzero) and mpf_eq(tval[0], sval)')

mpf.__add__ = binary_op('__add__',
    'val = mpf_add(sval, tval, prec, rounding)' + return_mpf,
    'val = mpf_add(sval, from_int(other), prec, rounding)' + return_mpf,
    'val = mpc_add_mpf(tval, sval, prec, rounding)' + return_mpc)

mpf.__sub__ = binary_op('__sub__',
    'val = mpf_sub(sval, tval, prec, rounding)' + return_mpf,
    'val = mpf_sub(sval, from_int(other), prec, rounding)' + return_mpf,
    'val = mpc_sub((sval, fzero), tval, prec, rounding)' + return_mpc)

mpf.__mul__ = binary_op('__mul__',
    'val = mpf_mul(sval, tval, prec, rounding)' + return_mpf,
    'val = mpf_mul_int(sval, other, prec, rounding)' + return_mpf,
    'val = mpc_mul_mpf(tval, sval, prec, rounding)' + return_mpc)

mpf.__div__ = binary_op('__div__',
    'val = mpf_div(sval, tval, prec, rounding)' + return_mpf,
    'val = mpf_div(sval, from_int(other), prec, rounding)' + return_mpf,
    'val = mpc_div((sval, fzero), tval, prec, rounding)' + return_mpc)

mpf.__mod__ = binary_op('__mod__',
    'val = mpf_mod(sval, tval, prec, rounding)' + return_mpf,
    'val = mpf_mod(sval, from_int(other), prec, rounding)' + return_mpf,
    'raise NotImplementedError("complex modulo")')

mpf.__pow__ = binary_op('__pow__',
    mpf_pow_same,
    'val = mpf_pow_int(sval, other, prec, rounding)' + return_mpf,
    'val = mpc_pow((sval, fzero), tval, prec, rounding)' + return_mpc)

mpf.__radd__ = mpf.__add__
mpf.__rmul__ = mpf.__mul__
mpf.__truediv__ = mpf.__div__
mpf.__rtruediv__ = mpf.__rdiv__

class mpc(mpnumeric):
    """
    An mpc represents a complex number using a pair of mpf:s (one
    for the real part and another for the imaginary part.) The mpc
    class behaves fairly similarly to Python's complex type.
    """

    __slots__ = ['_mpc_']

    def __new__(cls, real=0, imag=0):
        s = object.__new__(cls)
        if isinstance(real, complex_types):
            real, imag = real.real, real.imag
        elif hasattr(real, "_mpc_"):
            s._mpc_ = real._mpc_
            return s
        real = mpf(real)
        imag = mpf(imag)
        s._mpc_ = (real._mpf_, imag._mpf_)
        return s

    real = property(lambda self: make_mpf(self._mpc_[0]))
    imag = property(lambda self: make_mpf(self._mpc_[1]))

    def __getstate__(self):
        return to_pickable(self._mpc_[0]), to_pickable(self._mpc_[1])

    def __setstate__(self, val):
        self._mpc_ = from_pickable(val[0]), from_pickable(val[1])

    def __repr__(s):
        r = repr(s.real)[4:-1]
        i = repr(s.imag)[4:-1]
        return "mpc(real=%s, imag=%s)" % (r, i)

    def __str__(s):
        return "(%s)" % complex_to_str(s.real._mpf_, s.imag._mpf_, mp.dps)

    def __complex__(s): return complex(float(s.real), float(s.imag))
    def __pos__(s): return mpc(s.real, s.imag)
    def __abs__(s): return make_mpf(mpc_abs(s._mpc_, *prec_rounding))
    def __neg__(s): return mpc(-s.real, -s.imag)
    def __nonzero__(s): return bool(s.real) or bool(s.imag)
    def conjugate(s): return mpc(s.real, -s.imag)

    def __eq__(s, t):
        if not isinstance(t, mpc):
            if isinstance(t, str):
                return False
            t = mpc_convert_lhs(t)
            if t is NotImplemented:
                return t
        return s.real == t.real and s.imag == t.imag

    def __ne__(s, t):
        b = s.__eq__(t)
        if b is NotImplemented:
            return b
        return not b

    def _compare(*args):
        raise TypeError("no ordering relation is defined for complex numbers")

    __gt__ = _compare
    __le__ = _compare
    __gt__ = _compare
    __ge__ = _compare

    def __add__(s, t):
        prec, rounding = prec_rounding
        if not isinstance(t, mpc):
            t = mpc_convert_lhs(t)
            if t is NotImplemented:
                return t
            if isinstance(t, mpf):
                return make_mpc(mpc_add_mpf(s._mpc_, t._mpf_, prec, rounding))
        return make_mpc(mpc_add(s._mpc_, t._mpc_, prec, rounding))

    def __sub__(s, t):
        prec, rounding = prec_rounding
        if not isinstance(t, mpc):
            t = mpc_convert_lhs(t)
            if t is NotImplemented:
                return t
            if isinstance(t, mpf):
                return make_mpc(mpc_sub_mpf(s._mpc_, t._mpf_, prec, rounding))
        return make_mpc(mpc_sub(s._mpc_, t._mpc_, prec, rounding))

    def __mul__(s, t):
        prec, rounding = prec_rounding
        if not isinstance(t, mpc):
            if isinstance(t, int_types):
                return make_mpc(mpc_mul_int(s._mpc_, t, prec, rounding))
            t = mpc_convert_lhs(t)
            if t is NotImplemented:
                return t
            if isinstance(t, mpf):
                return make_mpc(mpc_mul_mpf(s._mpc_, t._mpf_, prec, rounding))
            t = mpc(t)
        return make_mpc(mpc_mul(s._mpc_, t._mpc_, prec, rounding))

    def __div__(s, t):
        prec, rounding = prec_rounding
        if not isinstance(t, mpc):
            t = mpc_convert_lhs(t)
            if t is NotImplemented:
                return t
            if isinstance(t, mpf):
                return make_mpc(mpc_div_mpf(s._mpc_, t._mpf_, prec, rounding))
        return make_mpc(mpc_div(s._mpc_, t._mpc_, prec, rounding))

    def __pow__(s, t):
        prec, rounding = prec_rounding
        if isinstance(t, int_types):
            return make_mpc(mpc_pow_int(s._mpc_, t, prec, rounding))
        t = mpc_convert_lhs(t)
        if t is NotImplemented:
            return t
        if isinstance(t, mpf):
            return make_mpc(mpc_pow_mpf(s._mpc_, t._mpf_, prec, rounding))
        return make_mpc(mpc_pow(s._mpc_, t._mpc_, prec, rounding))

    __radd__ = __add__

    def __rsub__(s, t):
        t = mpc_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t - s

    def __rmul__(s, t):
        prec, rounding = prec_rounding
        if isinstance(t, int_types):
            return make_mpc(mpc_mul_int(s._mpc_, t, prec, rounding))
        t = mpc_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t * s

    def __rdiv__(s, t):
        t = mpc_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t / s

    def __rpow__(s, t):
        t = mpc_convert_lhs(t)
        if t is NotImplemented:
            return t
        return t ** s

    __truediv__ = __div__
    __rtruediv__ = __rdiv__

    def ae(s, t, rel_eps=None, abs_eps=None):
        return almosteq(s, t, rel_eps, abs_eps)

complex_types = (complex, mpc)

class mpi(mpnumeric):
    """
    Interval arithmetic class. Precision is controlled by mp.prec.
    """

    def __new__(cls, a, b=None):
        if isinstance(a, mpi):
            return a
        if b is None:
            b = a
        a = mpf(a, rounding=round_floor)
        b = mpf(b, rounding=round_ceiling)
        if isnan(a) or isnan(b):
            a, b = -inf, inf
        assert a <= b, "endpoints must be properly ordered"
        return make_mpi((a._mpf_, b._mpf_))

    @property
    def a(self):
        return make_mpf(self._val[0])

    @property
    def b(self):
        return make_mpf(self._val[1])

    @property
    def mid(self):
        return make_mpf(mpi_mid(self._val, mp.prec))

    @property
    def delta(self):
        return make_mpf(mpi_delta(self._val, mp.prec))

    def _compare(*args):
        raise TypeError("no ordering relation is defined for intervals")

    __gt__ = _compare
    __le__ = _compare
    __gt__ = _compare
    __ge__ = _compare

    def __contains__(self, t):
        t = mpi(t)
        return (self.a <= t.a) and (t.b <= self.b)

    def __str__(self):
        return mpi_str(self._val, mp.prec)

    def __repr__(self):
        return "mpi(%r, %r)" % (self.a, self.b)

    def __eq__(self, other):
        if not isinstance(other, mpi):
            try:
                other = mpi(other)
            except:
                return NotImplemented
        return (self.a == other.a) and (self.b == other.b)

    def __ne__(self, other):
        return not (self == other)

    def __abs__(self):
        return make_mpi(mpi_abs(self._val, mp.prec))

    def __pos__(self):
        return make_mpi(mpi_pos(self._val, mp.prec))

    def __neg__(self):
        return make_mpi(mpi_neg(self._val, mp.prec))

    def __add__(self, other):
        if not isinstance(other, mpi):
            other = mpi(other)
        return make_mpi(mpi_add(self._val, other._val, mp.prec))

    def __sub__(self, other):
        if not isinstance(other, mpi):
            other = mpi(other)
        return make_mpi(mpi_sub(self._val, other._val, mp.prec))

    def __mul__(self, other):
        if not isinstance(other, mpi):
            other = mpi(other)
        return make_mpi(mpi_mul(self._val, other._val, mp.prec))

    def __div__(self, other):
        if not isinstance(other, mpi):
            other = mpi(other)
        return make_mpi(mpi_div(self._val, other._val, mp.prec))

    def __pow__(self, other):
        if isinstance(other, (int, long)):
            return make_mpi(mpi_pow_int(self._val, int(other), mp.prec))
        if not isinstance(other, mpi):
            other = mpi(other)
        return make_mpi(mpi_pow(self._val, other._val, mp.prec))

    def __rsub__(s, t):
        return mpi(t) - s

    def __rdiv__(s, t):
        return mpi(t) / s

    def __rpow__(s, t):
        return mpi(t) ** s

    __radd__ = __add__
    __rmul__ = __mul__
    __truediv__ = __div__
    __rtruediv__ = __rdiv__
    __floordiv__ = __div__
    __rfloordiv__ = __rdiv__

def make_mpi(val, cls=mpi):
    a = new(cls)
    a._val = val
    return a

def make_mpf(v, cls=mpf):
    a = new(cls)
    a._mpf_ = v
    return a

def make_mpc(v, cls=mpc):
    a = new(cls)
    a._mpc_ = v
    return a

one = make_mpf(fone)
zero = make_mpf(fzero)
inf = make_mpf(finf)
ninf = make_mpf(fninf)
nan = make_mpf(fnan)
j = mpc(0,1)

class constant(mpf):
    """Represents a mathematical constant with dynamic precision.
    When printed or used in an arithmetic operation, a constant
    is converted to a regular mpf at the working precision. A
    regular mpf can also be obtained using the operation +x."""

    def __new__(cls, func, name):
        a = object.__new__(cls)
        a.name = name
        a.func = func
        return a

    def __call__(self, prec=None, dps=None, rounding=None):
        if not prec: prec = prec_rounding[0]
        if not rounding: rounding = prec_rounding[1]
        if dps: prec = dps_to_prec(dps)
        return make_mpf(self.func(prec, rounding))

    @property
    def _mpf_(self):
        prec, rounding = prec_rounding
        return self.func(prec, rounding)

    def __repr__(self):
        return "<%s: %s~>" % (self.name, nstr(self))

eps = constant(lambda prec, rnd: (0, MP_ONE, 1-prec, 1),
    "epsilon of working precision")

def rand():
    """
    Returns an ``mpf`` with value chosen randomly from `[0, 1)`.
    The number of randomly generated bits in the mantissa is equal
    to the working precision.
    """
    return make_mpf(mpf_rand(mp.prec))

def isnan(x):
    """
    For an ``mpf`` *x*, determines whether *x* is not-a-number (nan)::

        >>> from sympy.mpmath import *
        >>> isnan(nan), isnan(3)
        (True, False)
    """
    if not isinstance(x, mpf):
        return False
    return x._mpf_ == fnan

def isinf(x):
    """
    For an ``mpf`` *x*, determines whether *x* is infinite::

        >>> from sympy.mpmath import *
        >>> isinf(inf), isinf(-inf), isinf(3)
        (True, True, False)
    """
    if not isinstance(x, mpf):
        return False
    return x._mpf_ in (finf, fninf)

def isint(x):
    """
    For an ``mpf`` *x*, or any type that can be converted
    to ``mpf``, determines whether *x* is exactly
    integer-valued::

        >>> from sympy.mpmath import *
        >>> isint(3), isint(mpf(3)), isint(3.2)
        (True, True, False)
    """
    if isinstance(x, int_types):
        return True
    try:
        x = mpmathify(x)
    except:
        return False
    if isinstance(x, mpf):
        if isnan(x) or isinf(x):
            return False
        return x == int(x)
    return False

def absmin(x):
    """
    Returns ``abs(x).a`` for an interval, or ``abs(x)`` for anything else.
    """
    if isinstance(x, mpi):
        return abs(x).a
    return abs(x)

def absmax(x):
    """
    Returns ``abs(x).b`` for an interval, or ``abs(x)`` for anything else.
    """
    if isinstance(x, mpi):
        return abs(x).b
    return abs(x)

def AS_POINTS(x):
    if isinstance(x, mpi):
        return [x.a, x.b]
    return x

def fraction(p, q):
    """
    Given Python integers `(p, q)`, returns a lazy ``mpf`` representing
    the fraction `p/q`. The value is updated with the precision.

        >>> mp.dps = 15
        >>> a = fraction(1,100)
        >>> b = mpf(1)/100
        >>> print a; print b
        0.01
        0.01
        >>> mp.dps = 30
        >>> print a; print b      # a will be accurate
        0.01
        0.0100000000000000002081668171172
        >>> mp.dps = 15
    """
    return constant(lambda prec, rnd: from_rational(p, q, prec, rnd),
        '%s/%s' % (p, q))

from operator import gt, lt

def arange(*args):
    r"""
    This is a generalized version of Python's :func:`range` function
    that accepts fractional endpoints and step sizes and
    returns a list of ``mpf`` instances. Like :func:`range`,
    :func:`arange` can be called with 1, 2 or 3 arguments:

    ``arange(b)``
        `[0, 1, 2, \ldots, x]`
    ``arange(a, b)``
        `[a, a+1, a+2, \ldots, x]`
    ``arange(a, b, h)``
        `[a, a+h, a+h, \ldots, x]`

    where `b-1 \le x < b` (in the third case, `b-h \le x < b`).

    Like Python's :func:`range`, the endpoint is not included. To
    produce ranges where the endpoint is included, :func:`linspace`
    is more convenient.

    **Examples**

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> arange(4)
        [mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0')]
        >>> arange(1, 2, 0.25)
        [mpf('1.0'), mpf('1.25'), mpf('1.5'), mpf('1.75')]
        >>> arange(1, -1, -0.75)
        [mpf('1.0'), mpf('0.25'), mpf('-0.5')]

    """
    if not len(args) <= 3:
        raise TypeError('arange expected at most 3 arguments, got %i'
                        % len(args))
    if not len(args) >= 1:
        raise TypeError('arange expected at least 1 argument, got %i'
                        % len(args))
    # set default
    a = 0
    dt = 1
    # interpret arguments
    if len(args) == 1:
        b = args[0]
    elif len(args) >= 2:
        a = args[0]
        b = args[1]
    if len(args) == 3:
        dt = args[2]
    a, b, dt = mpf(a), mpf(b), mpf(dt)
    assert a + dt != a, 'dt is too small and would cause an infinite loop'
    # adapt code for sign of dt
    if a > b:
        if dt > 0:
            return []
        op = gt
    else:
        if dt < 0:
            return []
        op = lt
    # create list
    result = []
    i = 0
    t = a
    while 1:
        t = a + dt*i
        i += 1
        if op(t, b):
            result.append(t)
        else:
            break
    return result

def linspace(*args, **kwargs):
    """
    ``linspace(a, b, n)`` returns a list of `n` evenly spaced
    samples from `a` to `b`. The syntax ``linspace(mpi(a,b), n)``
    is also valid.

    This function is often more convenient than :func:`arange`
    for partitioning an interval into subintervals, since
    the endpoint is included::

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> linspace(1, 4, 4)
        [mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')]
        >>> linspace(mpi(1,4), 4)
        [mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')]

    You may also provide the keyword argument ``endpoint=False``::

        >>> linspace(1, 4, 4, endpoint=False)
        [mpf('1.0'), mpf('1.75'), mpf('2.5'), mpf('3.25')]

    """
    if len(args) == 3:
        a = mpf(args[0])
        b = mpf(args[1])
        n = int(args[2])
    elif len(args) == 2:
        assert isinstance(args[0], mpi)
        a = args[0].a
        b = args[0].b
        n = int(args[1])
    else:
        raise TypeError('linspace expected 2 or 3 arguments, got %i' \
                        % len(args))
    if n < 1:
        raise ValueError('n must be greater than 0')
    if not 'endpoint' in kwargs or kwargs['endpoint']:
        if n == 1:
            return [mpf(a)]
        step = (b - a) / mpf(n - 1)
        y = [i*step + a for i in xrange(n)]
        y[-1] = b
    else:
        step = (b - a) / mpf(n)
        y = [i*step + a for i in xrange(n)]
    return y

def almosteq(s, t, rel_eps=None, abs_eps=None):
    r"""
    Determine whether the difference between `s` and `t` is smaller
    than a given epsilon, either relatively or absolutely.

    Both a maximum relative difference and a maximum difference
    ('epsilons') may be specified. The absolute difference is
    defined as `|s-t|` and the relative difference is defined
    as `|s-t|/\max(|s|, |t|)`.

    If only one epsilon is given, both are set to the same value.
    If none is given, both epsilons are set to `2^{-p+m}` where
    `p` is the current working precision and `m` is a small
    integer. The default setting typically allows :func:`almosteq`
    to be used to check for mathematical equality
    in the presence of small rounding errors.

    **Examples**

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> almosteq(3.141592653589793, 3.141592653589790)
        True
        >>> almosteq(3.141592653589793, 3.141592653589700)
        False
        >>> almosteq(3.141592653589793, 3.141592653589700, 1e-10)
        True
        >>> almosteq(1e-20, 2e-20)
        True
        >>> almosteq(1e-20, 2e-20, rel_eps=0, abs_eps=0)
        False

    """
    t = mpmathify(t)
    if abs_eps is None and rel_eps is None:
        rel_eps = abs_eps = make_mpf((0, 1, -mp.prec+4, 1))
    if abs_eps is None:
        abs_eps = rel_eps
    elif rel_eps is None:
        rel_eps = abs_eps
    diff = abs(s-t)
    if diff <= abs_eps:
        return True
    abss = abs(s)
    abst = abs(t)
    if abss < abst:
        err = diff/abst
    else:
        err = diff/abss
    return err <= rel_eps

def nstr(x, n=6):
    """
    Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n*
    significant digits. The small default value for *n* is chosen to
    make this function useful for printing collections of numbers
    (lists, matrices, etc).

    If *x* is a list or tuple, :func:`nstr` is applied recursively
    to each element. For unrecognized classes, :func:`nstr`
    simply returns ``str(x)``.

    The companion function :func:`nprint` prints the result
    instead of returning it.

        >>> from sympy.mpmath import *
        >>> nstr([+pi, ldexp(1,-500)])
        '[3.14159, 3.05494e-151]'
        >>> nprint([+pi, ldexp(1,-500)])
        [3.14159, 3.05494e-151]
    """
    if isinstance(x, list):
        return "[%s]" % (", ".join(nstr(c, n) for c in x))
    if isinstance(x, tuple):
        return "(%s)" % (", ".join(nstr(c, n) for c in x))
    if isinstance(x, mpf):
        return to_str(x._mpf_, n)
    if isinstance(x, mpc):
        return "(" + complex_to_str(x._mpc_[0], x._mpc_[1], n)  + ")"
    if isinstance(x, basestring):
        return repr(x)
    from matrices import matrix
    if isinstance(x, matrix):
        return x.__nstr__(n)
    return str(x)

def nprint(x, n=6):
    """
    Equivalent to ``print nstr(x, n)``.
    """
    print nstr(x, n)

def chop(x, tol=None):
    """
    Chops off small real or imaginary parts, or converts
    numbers close to zero to exact zeros. The input can be a
    single number or an iterable::

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> chop(5+1e-10j, tol=1e-9)
        mpf('5.0')
        >>> nprint(chop([1.0, 1e-20, 3+1e-18j, -4, 2]))
        [1.0, 0.0, 3.0, -4.0, 2.0]

    The tolerance defaults to ``100*eps``.
    """
    if tol is None:
        tol = 100*eps
    try:
        x = mpmathify(x)
        absx = abs(x)
        if abs(x) < tol:
            return zero
        if isinstance(x, mpc):
            if abs(x.imag) < min(tol, absx*tol):
                return x.real
            if abs(x.real) < min(tol, absx*tol):
                return mpc(0, x.imag)
    except TypeError:
        if hasattr(x, "__iter__"):
            return [chop(a, tol) for a in x]
    return x

def monitor(f, input='print', output='print'):
    """
    Returns a wrapped copy of *f* that monitors evaluation by calling
    *input* with every input (*args*, *kwargs*) passed to *f* and
    *output* with every value returned from *f*. The default action
    (specify using the special string value ``'print'``) is to print
    inputs and outputs to stdout, along with the total evaluation
    count::

        >>> from sympy.mpmath import *
        >>> mp.dps = 5
        >>> diff(monitor(exp), 1)   # diff will eval f(x-h) and f(x+h)
        in  0 (mpf('0.99999999906867742538452148'),) {}
        out 0 mpf('2.7182818259274480055282064')
        in  1 (mpf('1.0000000009313225746154785'),) {}
        out 1 mpf('2.7182818309906424675501024')
        mpf('2.7182808')

    To disable either the input or the output handler, you may
    pass *None* as argument.

    Custom input and output handlers may be used e.g. to store
    results for later analysis::

        >>> mp.dps = 15
        >>> input = []
        >>> output = []
        >>> findroot(monitor(sin, input.append, output.append), 3.0)
        mpf('3.1415926535897932')
        >>> len(input)  # Count number of evaluations
        9
        >>> print input[3], output[3]
        ((mpf('3.1415076583334066'),), {}) 8.49952562843408e-5
        >>> print input[4], output[4]
        ((mpf('3.1415928201669122'),), {}) -1.66577118985331e-7

    """
    if not input:
        input = lambda v: None
    elif input == 'print':
        incount = [0]
        def input(value):
            args, kwargs = value
            print "in  %s %r %r" % (incount[0], args, kwargs)
            incount[0] += 1
    if not output:
        output = lambda v: None
    elif output == 'print':
        outcount = [0]
        def output(value):
            print "out %s %r" % (outcount[0], value)
            outcount[0] += 1
    def f_monitored(*args, **kwargs):
        input((args, kwargs))
        v = f(*args, **kwargs)
        output(v)
        return v
    return f_monitored

def fsum(terms):
    """
    Calculates a sum containing a finite number of terms (for infinite
    series, see :func:`nsum`). The terms will be converted to
    mpmath numbers. For len(terms) > 2, this function is generally
    faster and produces more accurate results than the builtin
    Python function :func:`sum`.

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> fsum([1, 2, 0.5, 7])
        mpf('10.5')
    """
    prec, rnd = prec_rounding
    real = []
    imag = []
    other = 0
    for term in terms:
        if hasattr(term, "_mpf_"):
            val = term._mpf_
        elif hasattr(term, "_mpc_"):
            val, im = term._mpc_
            imag.append(im)
        else:
            term = mpmathify(term)
            if hasattr(term, "_mpf_"):
                val = term._mpf_
            elif hasattr(term, "_mpc_"):
                val, im = term._mpc_
                imag.append(im)
            else:
                other += term
                continue
        real.append(val)
    s = mpf_sum(real, prec, rnd)
    if imag:
        s = make_mpc((s, mpf_sum(imag, prec, rnd)))
    else:
        s = make_mpf(s)
    if other is 0:
        return s
    else:
        return s + other

def fdot(A, B=None):
    r"""
    Computes the dot product of the iterables `A` and `B`,

    .. math ::

        \sum_{k=0} A_k B_k.

    Alternatively, :func:`fdot` accepts a single iterable of pairs.
    In other words, ``fdot(A,B)`` and ``fdot(zip(A,B))`` are equivalent.

    The elements are automatically converted to mpmath numbers.

    Examples::

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> A = [2, 1.5, 3]
        >>> B = [1, -1, 2]
        >>> fdot(A, B)
        mpf('6.5')
        >>> zip(A, B)
        [(2, 1), (1.5, -1), (3, 2)]
        >>> fdot(_)
        mpf('6.5')

    """
    if B:
        A = zip(A, B)
    prec, rnd = prec_rounding
    real = []
    imag = []
    other = 0
    hasattr_ = hasattr
    types = (mpf, mpc)
    for a, b in A:
        if type(a) not in types: a = mpmathify(a)
        if type(b) not in types: b = mpmathify(b)
        a_real = hasattr_(a, "_mpf_")
        b_real = hasattr_(b, "_mpf_")
        if a_real and b_real:
            real.append(mpf_mul(a._mpf_, b._mpf_))
            continue
        a_complex = hasattr_(a, "_mpc_")
        b_complex = hasattr_(b, "_mpc_")
        if a_real and b_complex:
            aval = a._mpf_
            bre, bim = b._mpc_
            real.append(mpf_mul(aval, bre))
            imag.append(mpf_mul(aval, bim))
        elif b_real and a_complex:
            are, aim = a._mpc_
            bval = b._mpf_
            real.append(mpf_mul(are, bval))
            imag.append(mpf_mul(aim, bval))
        elif a_complex and b_complex:
            re, im = mpc_mul(a._mpc_, b._mpc_, prec+20)
            real.append(re)
            imag.append(im)
        else:
            other += a*b
    s = mpf_sum(real, prec, rnd)
    if imag:
        s = make_mpc((s, mpf_sum(imag, prec, rnd)))
    else:
        s = make_mpf(s)
    if other is 0:
        return s
    else:
        return s + other

def fprod(factors):
    r"""
    Calculates a product containing a finite number of factors (for
    infinite products, see :func:`nprod`). The factors will be
    converted to mpmath numbers.

        >>> from sympy.mpmath import *
        >>> mp.dps = 15
        >>> fprod([1, 2, 0.5, 7])
        mpf('7.0')

    """
    orig = mp.prec
    try:
        v = mpf(1)
        for p in factors:
            v *= p
    finally:
        mp.prec = orig
    return +v

def timing(f, *args, **kwargs):
    """
    Returns time elapsed for evaluating ``f()``. Optionally arguments
    may be passed to time the execution of ``f(*args, **kwargs)``.

    If the first call is very quick, ``f`` is called
    repeatedly and the best time is returned.
    """
    once = kwargs.get('once')
    if 'once' in kwargs:
        del kwargs['once']
    if args or kwargs:
        if len(args) == 1 and not kwargs:
            arg = args[0]
            g = lambda: f(arg)
        else:
            g = lambda: f(*args, **kwargs)
    else:
        g = f
    from timeit import default_timer as clock
    t1=clock(); v=g(); t2=clock(); t=t2-t1
    if t > 0.05 or once:
        return t
    for i in range(3):
        t1=clock();
        # Evaluate multiple times because the timer function
        # has a significant overhead
        g();g();g();g();g();g();g();g();g();g()
        t2=clock()
        t=min(t,(t2-t1)/10)
    return t

if __name__ == '__main__':
    import doctest
    doctest.testmod()

max_stars_repo_name: gnulinooks/sympy

max_issues_repo_name: gnulinooks/sympy

max_forks_repo_name: gnulinooks/sympy

reason: from sympy


text:
from math import log
import numpy as np

def net_args(parser):
    parser.add_argument("--batch", default=16, type=int, help="batch size")
    parser.add_argument(
        "--n_channels", default=1, type=int, help="number of image channels"
    )
    parser.add_argument("--epochs", default=200000, type=int, help="maximum epochs")
    parser.add_argument(
        "--n_flow", default=32, type=int, help="number of flows in each block"
    )
    parser.add_argument("--n_block", default=4, type=int, help="number of blocks")
    parser.add_argument(
        "--no_lu",
        action="store_true",
        help="use plain convolution instead of LU decomposed version",
    )
    parser.add_argument(
        "--affine", action="store_true", help="use affine coupling instead of additive"
    )
    parser.add_argument(
        "--tr_dq",
        action="store_true",
        help="use de-quantization during training",
    )
    parser.add_argument(
        "--te_dq",
        action="store_true",
        help="use de-quantization during testing",
    )
    parser.add_argument(
        "--te_noise", action="store_true", help="use noise during testing"
    )
    parser.add_argument("--n_bits", default=5, type=int, help="number of bits")
    parser.add_argument("--lr", default=1e-4, type=float, help="learning rate")
    parser.add_argument("--img_size", default=64, type=int, help="image size")
    parser.add_argument(
        "--temp", default=0.7, type=float, help="temperature of sampling"
    )
    parser.add_argument("--n_sample", default=20, type=int, help="number of samples")
    parser.add_argument(
        "--dataset",
        default="mnist",
        type=str,
        choices=["mnist", "fashion_mnist", "point_2d", "celeba", "ffhq_5", "cifar_horses_40", "ffhq_50", "cifar_horses_20", "cifar_horses_80", "mnist_30", "mnist_gan_all", "mnist_pad", "cifar_horses_20_top", "cifar_horses_40_top", "cifar_horses_20_top_small_lr", "cifar_horses_40_top_small_lr", "arrows_big", "arrows_small", "cifar_20_picked_inds_2", "cifar_40_picked_inds_2", "cifar_20_picked_inds_3", "cifar_40_picked_inds_3"],
        help="name of the dataset",
    )
    parser.add_argument(
        "--device",
        default="cpu",
        type=str,
        choices=["cpu", "cuda:0", "cuda:1"],
        help="device used to run the neural network",
    )
    parser.add_argument(
        "--delta",
        default=0.01,
        type=float,
        help="standard deviation of the de-quantizing noise",
    )
    return parser

def calc_z_shapes(n_channel, input_size, n_flow, n_block):
    z_shapes = []

    for i in range(n_block - 1):
        input_size //= 2
        n_channel *= 2

        z_shapes.append((n_channel, input_size, input_size))

    input_size //= 2
    z_shapes.append((n_channel * 4, input_size, input_size))

    return z_shapes

def calc_loss(log_p, logdet, image_size, n_bins, n_dim):
    n_pixel = image_size * image_size * n_dim

    loss = -log(n_bins) * n_pixel
    loss = loss + logdet + log_p

    return (
        (-loss / (log(2) * n_pixel)).mean(),
        (log_p / (log(2) * n_pixel)).mean(),
        (logdet / (log(2) * n_pixel)).mean(),
    )

def string_args(args):
    return ";".join(
        [f"{k}#{v}" for k, v in args.__dict__.items() if "model_path" not in k]
    )

def expspace(start: float, end: float, n_steps: int):
    space = np.linspace(np.log(start), np.log(end), n_steps)
    space = np.exp(space)
    return space

def create_deltas_sequence(start: float, stop: float):
    deltas = [start] * 50
    steps = expspace(start, stop, 16)
    for s in steps[1:]:
        deltas += [s] * 10
    return deltas

ext: py

max_stars_repo_name: ptempczyk/glow-pytorch

max_issues_repo_name: ptempczyk/lidl

max_forks_repo_name: ptempczyk/lidl

reason: import numpy


text:
import pytest
import numpy as np
from mock import patch
import baseline
from baseline.train import (
    cyclic_lr,
    zaremba_decay,
    cosine_decay,
    exponential_decay,
    staircase_decay,
    piecewise_decay,
)

@pytest.fixture
def piecewise():
    min_ = np.random.randint(1, 5)
    max_ = np.random.randint(min_ + 2, min_ + 7)
    bounds = [min_, max_]
    vals = np.random.uniform(size=len(bounds) + 1)
    return bounds, vals

def test_zaremba_values():
    eta = np.random.rand()
    decay_rate = np.random.rand()
    bounds_count = np.random.randint(5, 10)
    bounds = list(range(bounds_count))
    gold_vals = [eta / (decay_rate ** i) for i in range(len(bounds) + 1)]
    with patch('baseline.train.piecewise_decay') as pw_mock:
        zd = zaremba_decay(eta, bounds, decay_rate)
        assert pw_mock.call_args[0][0] == bounds
        assert pw_mock.call_args[0][1] == gold_vals

def test_zaremba_call_to_piecewise():
    with patch('baseline.train.piecewise_decay') as pw_mock:
        zd = zaremba_decay(1.0, [1, 2, 3], 0.5)
        pw_mock.assert_called()

def test_zaremba_with_nones():
    eta = np.random.rand()
    zd = zaremba_decay(eta)
    for step in np.random.randint(0, 1000000, size=100):
        assert zd(step) == eta

def test_piecewise_start(piecewise):
    b, v = piecewise
    p = piecewise_decay(b, v)
    lr = p(0)
    assert lr == v[0]

def test_piecewise_mid(piecewise):
    b, v = piecewise
    p = piecewise_decay(b, v)
    step = np.random.randint(np.min(b) + 1, np.max(b))
    lr = p(step)
    assert lr == v[1]

def test_piecewise_lsat(piecewise):
    b, v = piecewise
    p = piecewise_decay(b, v)
    step = np.random.randint(np.max(b) + 3, np.max(b) + 100)
    lr = p(step)
    assert lr == v[-1]

def test_staircase_decay_flat():
    steps = np.random.randint(900, 1001)
    sd = staircase_decay(np.random.rand(), steps, np.random.rand())
    stair_one_one = sd(np.random.randint(steps - 100, steps))
    stair_one_two = sd(np.random.randint(steps - 100, steps))
    stair_two = sd(np.random.randint(steps + 1, steps + 10))
    assert stair_one_one == stair_one_two
    assert stair_one_two != stair_two

def test_staircase_value():
    sd = staircase_decay(1.0, 1000, 0.9)
    gold = 1.0
    test = sd(100)
    np.testing.assert_allclose(test, gold)
    gold = 0.9
    test = sd(1001)
    np.testing.assert_allclose(test, gold)

def test_exp_values():
    sd = exponential_decay(1.0, 1000, 0.9)
    gold = 0.9895192582062144
    test = sd(100)
    np.testing.assert_allclose(test, gold)
    gold = 0.8999051805311098
    test = sd(1001)
    np.testing.assert_allclose(test, gold)

def test_cyclic_lr():
    bounds = 1000
    min_eta = 1e-5
    max_eta = 1e-2
    clr = cyclic_lr(min_eta, max_eta, bounds)
    start = clr(0)
    up = clr(bounds / 2.)
    mid = clr(bounds)
    down = clr(bounds + (bounds / 2.))
    end = clr(2 * bounds)
    late = clr(3 * bounds)
    assert start == min_eta
    assert up > start
    assert up < mid
    assert mid == max_eta
    assert down < mid
    assert down > end
    assert end == min_eta
    assert late == max_eta

def test_cosine_lr():
    cd = cosine_decay(0.1, 1000)
    iters = [0, 100, 900, 1000, 1001]
    golds = [0.1, 0.09755283, 0.002447176, 0.0, 0.0]
    for i, gold in zip(iters, golds):
        np.testing.assert_allclose(cd(i), gold, rtol=1e-6)


text:
#from pymnet import *
from py3plex.visualization.multilayer import draw, draw_multiedges, draw_multilayer_default, models
from py3plex.visualization.colors import colors_default
from py3plex.core import multinet
import time
import matplotlib.pyplot as plt

def py3plex_visualization(network):

    start = time.time()
    multilayer_network = multinet.multi_layer_network(
        verbose=False).load_network(network,
                                    directed=False,
                                    input_type="multiedge_tuple_list")
    network_labels, graphs, multilinks = multilayer_network.get_layers(
    )  # get layers for visualization

    draw_multilayer_default(graphs,
                            display=False,
                            background_shape="circle",
                            labels=network_labels,
                            layout_algorithm="force",
                            verbose=False)

    enum = 1
    color_mappings = {idx: col for idx, col in enumerate(colors_default)}
    for edge_type, edges in multilinks.items():
        draw_multiedges(graphs,
                        edges,
                        alphachannel=0.2,
                        linepoints="-.",
                        linecolor="black",
                        curve_height=5,
                        linmod="upper",
                        linewidth=0.4)
        enum += 1

    end = time.time()
    plt.show()
    plt.clf()
    return (end - start)

def pymnet_visualization(network):
    start = time.time()
    draw(network)
    plt.show()
    end = time.time()
    plt.clf()
    return (end - start)

if __name__ == "__main__":

    import numpy as np
    import itertools
    import pandas as pd

    number_of_nodes = np.arange(5, 200, 15).tolist()
    number_of_edges = reversed([x + 1 for x in list(range(8))])
    probabilities = np.arange(0.05, 0.5, 0.02).tolist()

    merged = [number_of_nodes, number_of_edges, probabilities]
    combinations = list(itertools.product(*merged))

    datapoints = []

    for combination in combinations:
        N, L, p = combination
        print("Evaluating {} {} {} setting.".format(N, L, p))
        net = models.er_multilayer(N, L, p)
        try:
            t_pp = py3plex_visualization(net.edges)
            t_pmn = 0
#            t_pmn = pymnet_visualization(net)

        except Exception as err:
            print(err)

        datapoint = {"N": N, "E": L, "p": p, "Py3plex": t_pp, "Pymnet": t_pmn}
        datapoints.append(datapoint)

    result_frame = pd.DataFrame(datapoints)
    result_frame.to_csv("example_benchmark2.csv")

max_stars_repo_name: SkBlaz/supertest

max_issues_repo_name: SkBlaz/supertest


text:
from itertools import izip
import json
from datetime import datetime

from scipy.weave.ext_tools import indent

def no_of_fields_score(json_line):
    count = 0
    score = 0.0
    for key in json_line:
        count += 1
    if count<20:
        score = count/20.0
    if count >= 20:
        score =1
    return score

def get_metadata_score(json_line):
    metadata_score = 0
    if 'description' in json_line:
        metadata_score += 0.5
    if 'title' in json_line:
        metadata_score+=0.25
    if 'version' in json_line:
        metadata_score+=0.25
    if 'license' in json_line:
        metadata_score+=1
    #calculates scores based on the keys in the json file
    countscore = no_of_fields_score(json_line)
    metadata_score += countscore
    #adds DOI score
    metadata_score+=1
    #for long term management constant score 1
    metadata_score+=1
    #normalizing the score
    metadata_score = '%.3f'%(metadata_score/6)
    print "metadata score is ", metadata_score
    print(json.dumps(json_line, indent=4))
    return metadata_score

def main():
    start_time = datetime.now()
    merged_file_path = 'E:/Sem2/CSCI599/Assignment2/Part8/merged_features.json'

    merged_features_file_with_score = open('merged_features_with_score.json', 'w+')
    i = 0
    with open(merged_file_path) as merged_data:
        for line in merged_data:
            json_line = json.loads(line.strip())
            i += 1
            json_line['metadata_score'] = get_metadata_score(json_line)
            print ('Parsed ' + str(i) + ' files')
            json.dump(json_line, merged_features_file_with_score)
            merged_features_file_with_score.write('\n')

    end_time = datetime.now()
    print(end_time - start_time)
    print('Merged ' + str(i) + ' files')

if __name__ == '__main__':
    main()

reason: from scipy


text:
# -*- coding: utf-8 -*-

"""Common visuals."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import gzip
import os.path as op

import numpy as np
from six import string_types
from vispy.gloo import Texture2D

from .base import BaseVisual
from .transform import Range, NDC
from .utils import (_tesselate_histogram,
                    _get_texture,
                    _get_array,
                    _get_data_bounds,
                    _get_pos,
                    _get_index,
                    )
from phy.utils import Bunch

#------------------------------------------------------------------------------
# Utils
#------------------------------------------------------------------------------

DEFAULT_COLOR = (0.03, 0.57, 0.98, .75)

#------------------------------------------------------------------------------
# Scatter visuals
#------------------------------------------------------------------------------

class ScatterVisual(BaseVisual):
    _default_marker_size = 10.
    _default_marker = 'disc'
    _default_color = DEFAULT_COLOR
    _supported_markers = (
        'arrow',
        'asterisk',
        'chevron',
        'clover',
        'club',
        'cross',
        'diamond',
        'disc',
        'ellipse',
        'hbar',
        'heart',
        'infinity',
        'pin',
        'ring',
        'spade',
        'square',
        'tag',
        'triangle',
        'vbar',
    )

    def __init__(self, marker=None):
        super(ScatterVisual, self).__init__()

        # Set the marker type.
        self.marker = marker or self._default_marker
        assert self.marker in self._supported_markers

        self.set_shader('scatter')
        self.fragment_shader = self.fragment_shader.replace('%MARKER',
                                                            self.marker)
        self.set_primitive_type('points')
        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def vertex_count(x=None, y=None, pos=None, **kwargs):
        return y.size if y is not None else len(pos)

    @staticmethod
    def validate(x=None,
                 y=None,
                 pos=None,
                 color=None,
                 size=None,
                 depth=None,
                 data_bounds=None,
                 ):
        if pos is None:
            x, y = _get_pos(x, y)
            pos = np.c_[x, y]
        pos = np.asarray(pos)
        assert pos.ndim == 2
        assert pos.shape[1] == 2
        n = pos.shape[0]

        # Validate the data.
        color = _get_array(color, (n, 4),
                           ScatterVisual._default_color,
                           dtype=np.float32)
        size = _get_array(size, (n, 1), ScatterVisual._default_marker_size)
        depth = _get_array(depth, (n, 1), 0)
        if data_bounds is not None:
            data_bounds = _get_data_bounds(data_bounds, pos)
            assert data_bounds.shape[0] == n

        return Bunch(pos=pos, color=color, size=size,
                     depth=depth, data_bounds=data_bounds)

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        if data.data_bounds is not None:
            self.data_range.from_bounds = data.data_bounds
            pos_tr = self.transforms.apply(data.pos)
        else:
            pos_tr = data.pos
        pos_tr = np.c_[pos_tr, data.depth]
        self.program['a_position'] = pos_tr.astype(np.float32)
        self.program['a_size'] = data.size.astype(np.float32)
        self.program['a_color'] = data.color.astype(np.float32)

class UniformScatterVisual(BaseVisual):
    _default_marker_size = 10.
    _default_marker = 'disc'
    _default_color = DEFAULT_COLOR
    _supported_markers = (
        'arrow',
        'asterisk',
        'chevron',
        'clover',
        'club',
        'cross',
        'diamond',
        'disc',
        'ellipse',
        'hbar',
        'heart',
        'infinity',
        'pin',
        'ring',
        'spade',
        'square',
        'tag',
        'triangle',
        'vbar',
    )

    def __init__(self, marker=None, color=None, size=None):
        super(UniformScatterVisual, self).__init__()

        # Set the marker type.
        self.marker = marker or self._default_marker
        assert self.marker in self._supported_markers

        self.set_shader('uni_scatter')
        self.fragment_shader = self.fragment_shader.replace('%MARKER',
                                                            self.marker)

        self.color = color or self._default_color
        self.marker_size = size or self._default_marker_size

        self.set_primitive_type('points')
        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def vertex_count(x=None, y=None, pos=None, **kwargs):
        return y.size if y is not None else len(pos)

    @staticmethod
    def validate(x=None,
                 y=None,
                 pos=None,
                 masks=None,
                 data_bounds=None,
                 ):
        if pos is None:
            x, y = _get_pos(x, y)
            pos = np.c_[x, y]
        pos = np.asarray(pos)
        assert pos.ndim == 2
        assert pos.shape[1] == 2
        n = pos.shape[0]

        masks = _get_array(masks, (n, 1), 1., np.float32)
        assert masks.shape == (n, 1)

        # Validate the data.
        if data_bounds is not None:
            data_bounds = _get_data_bounds(data_bounds, pos)
            assert data_bounds.shape[0] == n

        return Bunch(pos=pos,
                     masks=masks,
                     data_bounds=data_bounds,
                     )

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        if data.data_bounds is not None:
            self.data_range.from_bounds = data.data_bounds
            pos_tr = self.transforms.apply(data.pos)
        else:
            pos_tr = data.pos

        masks = data.masks

        self.program['a_position'] = pos_tr.astype(np.float32)
        self.program['a_mask'] = masks.astype(np.float32)

        self.program['u_size'] = self.marker_size
        self.program['u_color'] = self.color
        self.program['u_mask_max'] = _max(masks)

#------------------------------------------------------------------------------
# Plot visuals
#------------------------------------------------------------------------------

def _as_list(arr):
    if isinstance(arr, np.ndarray):
        if arr.ndim == 1:
            return [arr]
        elif arr.ndim == 2:
            return list(arr)
    assert isinstance(arr, list)
    return arr

def _min(arr):
    return arr.min() if len(arr) else 0

def _max(arr):
    return arr.max() if len(arr) else 1

class PlotVisual(BaseVisual):
    _default_color = DEFAULT_COLOR
    allow_list = ('x', 'y')

    def __init__(self):
        super(PlotVisual, self).__init__()

        self.set_shader('plot')
        self.set_primitive_type('line_strip')

        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def validate(x=None,
                 y=None,
                 color=None,
                 depth=None,
                 data_bounds=None,
                 ):

        assert y is not None
        y = _as_list(y)

        if x is None:
            x = [np.linspace(-1., 1., len(_)) for _ in y]
        x = _as_list(x)

        # Remove empty elements.
        assert len(x) == len(y)

        assert [len(_) for _ in x] == [len(_) for _ in y]

        n_signals = len(x)

        if isinstance(data_bounds, string_types) and data_bounds == 'auto':
            xmin = [_min(_) for _ in x]
            ymin = [_min(_) for _ in y]
            xmax = [_max(_) for _ in x]
            ymax = [_max(_) for _ in y]
            data_bounds = np.c_[xmin, ymin, xmax, ymax]

        color = _get_array(color, (n_signals, 4),
                           PlotVisual._default_color,
                           dtype=np.float32,
                           )
        assert color.shape == (n_signals, 4)

        depth = _get_array(depth, (n_signals, 1), 0)
        assert depth.shape == (n_signals, 1)

        if data_bounds is not None:
            data_bounds = _get_data_bounds(data_bounds, length=n_signals)
            data_bounds = data_bounds.astype(np.float64)
            assert data_bounds.shape == (n_signals, 4)

        return Bunch(x=x, y=y,
                     color=color, depth=depth,
                     data_bounds=data_bounds)

    @staticmethod
    def vertex_count(y=None, **kwargs):
        """Take the output of validate() as input."""
        return y.size if isinstance(y, np.ndarray) else sum(len(_) for _ in y)

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)

        assert isinstance(data.y, list)
        n_signals = len(data.y)
        n_samples = [len(_) for _ in data.y]
        n = sum(n_samples)
        x = np.concatenate(data.x) if len(data.x) else np.array([])
        y = np.concatenate(data.y) if len(data.y) else np.array([])

        # Generate the position array.
        pos = np.empty((n, 2), dtype=np.float64)
        pos[:, 0] = x.ravel()
        pos[:, 1] = y.ravel()
        assert pos.shape == (n, 2)

        # Generate the color attribute.
        color = data.color
        assert color.shape == (n_signals, 4)
        color = np.repeat(color, n_samples, axis=0)
        assert color.shape == (n, 4)

        # Generate signal index.
        signal_index = np.repeat(np.arange(n_signals), n_samples)
        signal_index = _get_array(signal_index, (n, 1))
        assert signal_index.shape == (n, 1)

        # Transform the positions.
        if data.data_bounds is not None:
            data_bounds = np.repeat(data.data_bounds, n_samples, axis=0)
            self.data_range.from_bounds = data_bounds
            pos = self.transforms.apply(pos)

        # Position and depth.
        depth = np.repeat(data.depth, n_samples, axis=0)
        self.program['a_position'] = np.c_[pos, depth].astype(np.float32)
        self.program['a_color'] = color.astype(np.float32)
        self.program['a_signal_index'] = signal_index.astype(np.float32)

class UniformPlotVisual(BaseVisual):
    _default_color = DEFAULT_COLOR
    allow_list = ('x', 'y')

    def __init__(self, color=None, depth=None):
        super(UniformPlotVisual, self).__init__()

        self.set_shader('uni_plot')
        self.set_primitive_type('line_strip')
        self.color = color or self._default_color

        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def validate(x=None,
                 y=None,
                 masks=None,
                 data_bounds=None,
                 ):

        assert y is not None
        y = _as_list(y)

        if x is None:
            x = [np.linspace(-1., 1., len(_)) for _ in y]
        x = _as_list(x)

        # Remove empty elements.
        assert len(x) == len(y)

        assert [len(_) for _ in x] == [len(_) for _ in y]

        n_signals = len(x)

        masks = _get_array(masks, (n_signals, 1), 1., np.float32)
        assert masks.shape == (n_signals, 1)

        if isinstance(data_bounds, string_types) and data_bounds == 'auto':
            xmin = [_min(_) for _ in x]
            ymin = [_min(_) for _ in y]
            xmax = [_max(_) for _ in x]
            ymax = [_max(_) for _ in y]
            data_bounds = np.c_[xmin, ymin, xmax, ymax]

        if data_bounds is not None:
            data_bounds = _get_data_bounds(data_bounds, length=n_signals)
            data_bounds = data_bounds.astype(np.float64)
            assert data_bounds.shape == (n_signals, 4)

        return Bunch(x=x, y=y, masks=masks,
                     data_bounds=data_bounds,
                     )

    @staticmethod
    def vertex_count(y=None, **kwargs):
        """Take the output of validate() as input."""
        return y.size if isinstance(y, np.ndarray) else sum(len(_) for _ in y)

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)

        assert isinstance(data.y, list)
        n_signals = len(data.y)
        n_samples = [len(_) for _ in data.y]
        n = sum(n_samples)
        x = np.concatenate(data.x) if len(data.x) else np.array([])
        y = np.concatenate(data.y) if len(data.y) else np.array([])

        # Generate the position array.
        pos = np.empty((n, 2), dtype=np.float64)
        pos[:, 0] = x.ravel()
        pos[:, 1] = y.ravel()
        assert pos.shape == (n, 2)

        # Generate signal index.
        signal_index = np.repeat(np.arange(n_signals), n_samples)
        signal_index = _get_array(signal_index, (n, 1))
        assert signal_index.shape == (n, 1)

        # Masks.
        masks = np.repeat(data.masks, n_samples, axis=0)

        # Transform the positions.
        if data.data_bounds is not None:
            data_bounds = np.repeat(data.data_bounds, n_samples, axis=0)
            self.data_range.from_bounds = data_bounds
            pos = self.transforms.apply(pos)

        assert pos.shape == (n, 2)
        assert signal_index.shape == (n, 1)
        assert masks.shape == (n, 1)

        # Position and depth.
        self.program['a_position'] = pos.astype(np.float32)
        self.program['a_signal_index'] = signal_index.astype(np.float32)
        self.program['a_mask'] = masks.astype(np.float32)

        self.program['u_color'] = self.color
        self.program['u_mask_max'] = _max(masks)

#------------------------------------------------------------------------------
# Other visuals
#------------------------------------------------------------------------------

class HistogramVisual(BaseVisual):
    _default_color = DEFAULT_COLOR

    def __init__(self):
        super(HistogramVisual, self).__init__()

        self.set_shader('histogram')
        self.set_primitive_type('triangles')

        self.data_range = Range([0, 0, 1, 1])
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def validate(hist=None,
                 color=None,
                 ylim=None):
        assert hist is not None
        hist = np.asarray(hist, np.float64)
        if hist.ndim == 1:
            hist = hist[None, :]
        assert hist.ndim == 2
        n_hists, n_bins = hist.shape

        # Validate the data.
        color = _get_array(color, (n_hists, 4),
                           HistogramVisual._default_color,
                           dtype=np.float32,
                           )

        # Validate ylim.
        if ylim is None:
            ylim = hist.max() if hist.size > 0 else 1.
        ylim = np.atleast_1d(ylim)
        if len(ylim) == 1:
            ylim = np.tile(ylim, n_hists)
        if ylim.ndim == 1:
            ylim = ylim[:, np.newaxis]
        assert ylim.shape == (n_hists, 1)

        return Bunch(hist=hist,
                     ylim=ylim,
                     color=color,
                     )

    @staticmethod
    def vertex_count(hist, **kwargs):
        hist = np.atleast_2d(hist)
        n_hists, n_bins = hist.shape
        return 6 * n_hists * n_bins

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        hist = data.hist

        n_hists, n_bins = hist.shape
        n = self.vertex_count(hist)

        # NOTE: this must be set *before* `apply_cpu_transforms` such
        # that the histogram is correctly normalized.
        data_bounds = np.c_[np.zeros((n_hists, 2)),
                            n_bins * np.ones((n_hists, 1)),
                            data.ylim]
        data_bounds = np.repeat(data_bounds, 6 * n_bins, axis=0)
        self.data_range.from_bounds = data_bounds

        # Set the transformed position.
        pos = np.vstack(_tesselate_histogram(row) for row in hist)
        pos_tr = self.transforms.apply(pos)
        assert pos_tr.shape == (n, 2)
        self.program['a_position'] = pos_tr.astype(np.float32)

        # Generate the hist index.
        hist_index = _get_index(n_hists, n_bins * 6, n)
        self.program['a_hist_index'] = hist_index.astype(np.float32)

        # Hist colors.
        tex = _get_texture(data.color, self._default_color, n_hists, [0, 1])
        self.program['u_color'] = tex.astype(np.float32)
        self.program['n_hists'] = n_hists

class TextVisual(BaseVisual):
    """Display strings at multiple locations.

    Currently, the color, font family, and font size is not customizable.

    """
    _default_color = (1., 1., 1., 1.)

    def __init__(self, color=None):
        super(TextVisual, self).__init__()
        self.set_shader('text')
        self.set_primitive_type('triangles')
        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

        # Load the font.
        curdir = op.realpath(op.dirname(__file__))
        font_name = 'SourceCodePro-Regular'
        font_size = 32
        # The font texture is gzipped.
        fn = '%s-%d.npy.gz' % (font_name, font_size)
        with gzip.open(op.join(curdir, 'static', fn), 'rb') as f:
            self._tex = np.load(f)
        with open(op.join(curdir, 'static', 'chars.txt'), 'r') as f:
            self._chars = f.read()
        self.color = color if color is not None else self._default_color
        assert len(self.color) == 4

    def _get_glyph_indices(self, s):
        return [self._chars.index(char) for char in s]

    @staticmethod
    def validate(pos=None, text=None, anchor=None,
                 data_bounds=None,
                 ):

        if text is None:
            text = []
        if isinstance(text, string_types):
            text = [text]
        if pos is None:
            pos = np.zeros((len(text), 2))

        assert pos is not None
        pos = np.atleast_2d(pos)
        assert pos.ndim == 2
        assert pos.shape[1] == 2
        n_text = pos.shape[0]
        assert len(text) == n_text

        anchor = anchor if anchor is not None else (0., 0.)
        anchor = np.atleast_2d(anchor)
        if anchor.shape[0] == 1:
            anchor = np.repeat(anchor, n_text, axis=0)
        assert anchor.ndim == 2
        assert anchor.shape == (n_text, 2)

        if data_bounds is not None:
            data_bounds = _get_data_bounds(data_bounds, pos)
            assert data_bounds.shape[0] == n_text
            data_bounds = data_bounds.astype(np.float64)
            assert data_bounds.shape == (n_text, 4)

        return Bunch(pos=pos, text=text, anchor=anchor,
                     data_bounds=data_bounds)

    @staticmethod
    def vertex_count(pos=None, **kwargs):
        """Take the output of validate() as input."""
        # Total number of glyphs * 6 (6 vertices per glyph).
        return sum(map(len, kwargs['text'])) * 6

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        pos = data.pos.astype(np.float64)
        assert pos.ndim == 2
        assert pos.shape[1] == 2
        assert pos.dtype == np.float64

        # Concatenate all strings.
        text = data.text
        lengths = list(map(len, text))
        text = ''.join(text)
        a_char_index = self._get_glyph_indices(text)
        n_glyphs = len(a_char_index)

        tex = self._tex
        glyph_height = tex.shape[0] // 6
        glyph_width = tex.shape[1] // 16
        glyph_size = (glyph_width, glyph_height)

        # Position of all glyphs.
        a_position = np.repeat(pos, lengths, axis=0)
        if not len(lengths):
            a_glyph_index = np.zeros((0,))
        else:
            a_glyph_index = np.concatenate([np.arange(n) for n in lengths])
        a_quad_index = np.arange(6)

        a_anchor = data.anchor

        a_position = np.repeat(a_position, 6, axis=0)
        a_glyph_index = np.repeat(a_glyph_index, 6)
        a_quad_index = np.tile(a_quad_index, n_glyphs)
        a_char_index = np.repeat(a_char_index, 6)

        a_anchor = np.repeat(a_anchor, lengths, axis=0)
        a_anchor = np.repeat(a_anchor, 6, axis=0)

        a_lengths = np.repeat(lengths, lengths)
        a_lengths = np.repeat(a_lengths, 6)

        n_vertices = n_glyphs * 6

        # Transform the positions.
        if data.data_bounds is not None:
            data_bounds = data.data_bounds
            data_bounds = np.repeat(data_bounds, lengths, axis=0)
            data_bounds = np.repeat(data_bounds, 6, axis=0)
            assert data_bounds.shape == (n_vertices, 4)
            self.data_range.from_bounds = data_bounds
            pos_tr = self.transforms.apply(a_position)
            assert pos_tr.shape == (n_vertices, 2)
        else:
            pos_tr = a_position

        assert pos_tr.shape == (n_vertices, 2)
        assert a_glyph_index.shape == (n_vertices,)
        assert a_quad_index.shape == (n_vertices,)
        assert a_char_index.shape == (n_vertices,)
        assert a_anchor.shape == (n_vertices, 2)
        assert a_lengths.shape == (n_vertices,)

        self.program['a_position'] = pos_tr.astype(np.float32)
        self.program['a_glyph_index'] = a_glyph_index.astype(np.float32)
        self.program['a_quad_index'] = a_quad_index.astype(np.float32)
        self.program['a_char_index'] = a_char_index.astype(np.float32)
        self.program['a_anchor'] = a_anchor.astype(np.float32)
        self.program['a_lengths'] = a_lengths.astype(np.float32)

        self.program['u_glyph_size'] = glyph_size
        # TODO: color

        self.program['u_tex'] = Texture2D(tex[::-1, :])

class LineVisual(BaseVisual):
    """Lines."""
    _default_color = (.3, .3, .3, 1.)

    def __init__(self, color=None):
        super(LineVisual, self).__init__()
        self.set_shader('line')
        self.set_primitive_type('lines')
        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def validate(pos=None, color=None,
                 data_bounds=None,
                 ):
        assert pos is not None
        pos = np.atleast_2d(pos)
        assert pos.ndim == 2
        n_lines = pos.shape[0]
        assert pos.shape[1] == 4

        # Color.
        color = _get_array(color, (n_lines, 4), LineVisual._default_color)

        # By default, we assume that the coordinates are in NDC.
        if data_bounds is None:
            data_bounds = NDC
        data_bounds = _get_data_bounds(data_bounds, length=n_lines)
        data_bounds = data_bounds.astype(np.float64)
        assert data_bounds.shape == (n_lines, 4)

        return Bunch(pos=pos, color=color, data_bounds=data_bounds)

    @staticmethod
    def vertex_count(pos=None, **kwargs):
        """Take the output of validate() as input."""
        return pos.shape[0] * 2

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        pos = data.pos
        assert pos.ndim == 2
        assert pos.shape[1] == 4
        assert pos.dtype == np.float64
        n_lines = pos.shape[0]
        n_vertices = 2 * n_lines
        pos = pos.reshape((-1, 2))

        # Transform the positions.
        data_bounds = np.repeat(data.data_bounds, 2, axis=0)
        self.data_range.from_bounds = data_bounds
        pos_tr = self.transforms.apply(pos)

        # Position.
        assert pos_tr.shape == (n_vertices, 2)
        self.program['a_position'] = pos_tr.astype(np.float32)

        # Color.
        color = np.repeat(data.color, 2, axis=0)
        self.program['a_color'] = color.astype(np.float32)

class PolygonVisual(BaseVisual):
    """Polygon."""
    _default_color = (.5, .5, .5, 1.)

    def __init__(self):
        super(PolygonVisual, self).__init__()
        self.set_shader('polygon')
        self.set_primitive_type('line_loop')
        self.data_range = Range(NDC)
        self.transforms.add_on_cpu(self.data_range)

    @staticmethod
    def validate(pos=None,
                 data_bounds=None,
                 ):
        assert pos is not None
        pos = np.atleast_2d(pos)
        assert pos.ndim == 2
        assert pos.shape[1] == 2

        # By default, we assume that the coordinates are in NDC.
        if data_bounds is None:
            data_bounds = NDC
        data_bounds = _get_data_bounds(data_bounds)
        data_bounds = data_bounds.astype(np.float64)
        assert data_bounds.shape == (1, 4)

        return Bunch(pos=pos, data_bounds=data_bounds)

    @staticmethod
    def vertex_count(pos=None, **kwargs):
        """Take the output of validate() as input."""
        return pos.shape[0]

    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        pos = data.pos
        assert pos.ndim == 2
        assert pos.shape[1] == 2
        assert pos.dtype == np.float64
        n_vertices = pos.shape[0]

        # Transform the positions.
        self.data_range.from_bounds = data.data_bounds
        pos_tr = self.transforms.apply(pos)

        # Position.
        assert pos_tr.shape == (n_vertices, 2)
        self.program['a_position'] = pos_tr.astype(np.float32)

        self.program['u_color'] = self._default_color

max_stars_repo_name: m-beau/phy

max_issues_repo_name: m-beau/phy

max_forks_repo_name: m-beau/phy


text:
#!/usr/bin/env python

"""
@package mi.dataset.parser.test.test_adcp_jln
@fid marine-integrations/mi/dataset/parser/test/test_adcps_jln.py
@author Jeff Roy
@brief Test code for a Adcps_jln data parser
Parts of this test code were taken from test_adcpa.py
Due to the nature of the records in PD0 files, (large binary records with hundreds of parameters)
this code verifies select items in the parsed data particle
"""

from nose.plugins.attrib import attr
import yaml
import numpy
import os

from mi.core.log import get_logger; log = get_logger()
from mi.idk.config import Config
from mi.dataset.test.test_parser import ParserUnitTestCase
from mi.dataset.dataset_driver import DataSetDriverConfigKeys
from mi.dataset.parser.adcp_pd0 import AdcpPd0Parser, StateKey

RESOURCE_PATH = os.path.join(Config().base_dir(), 'mi', 'dataset',
                             'driver', 'adcps_jln', 'stc', 'resource')

@attr('UNIT', group='mi')
class AdcpsJlnParserUnitTestCase(ParserUnitTestCase):
    """
    Adcp_jln Parser unit test suite
    """
    def state_callback(self, state, fid_ingested):
        """ Call back method to watch what comes in via the position callback """
        self.state_callback_value = state
        self.fid_ingested_value = fid_ingested

    def pub_callback(self, pub):
        """ Call back method to watch what comes in via the publish callback """
        self.publish_callback_value = pub

    def exception_callback(self, exception):
        """ Call back method to match what comes in via the exception callback """
        self.exception_callback_value = exception

    def setUp(self):
        ParserUnitTestCase.setUp(self)
        self.config = {DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.adcps_jln',
                       DataSetDriverConfigKeys.PARTICLE_CLASS: 'AdcpsJlnParticle'}
        # Define test data particles and their associated timestamps which will be
        # compared with returned results

        self.start_state = {StateKey.POSITION: 0}

        self.fid_ingested_value = None
        self.state_callback_value = None
        self.publish_callback_value = None

        #test01 data was all manually verified against the IDD
        #and double checked with PD0decoder_v2 MATLAB tool
        self.test01 = {}
        self.test01['internal_timestamp'] = 3581719370.030000
        self.test01['ensemble_start_time'] = 3581719370.0299997329711914
        self.test01['echo_intensity_beam1'] = [89, 51, 44, 43, 43, 43, 43, 44, 43, 44, 43, 43, 44, 44, 44,
                                               43, 43, 44, 43, 44, 44, 43, 43, 44, 44, 44, 44, 44, 44, 44,
                                               43, 43, 43, 43, 43, 43, 43, 44, 44, 43, 44, 44, 43, 43, 44,
                                               43, 43, 44, 44, 43, 43, 44, 43, 43, 44]
        self.test01['correlation_magnitude_beam1'] = [68, 70, 18, 19, 17, 17, 20, 19, 17, 15, 17, 20, 16,
                                                      17, 16, 17, 17, 18, 18, 17, 17, 19, 18, 17, 17, 19,
                                                      19, 17, 16, 16, 18, 19, 19, 17, 19, 19, 19, 18, 20,
                                                      17, 19, 19, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.test01['percent_good_3beam'] = [53, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.test01['water_velocity_east'] = [383, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                              -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                              -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                              -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                              -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                              -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                              -32768, -32768, -32768, -32768, -32768, -32768, -32768]
        self.test01['water_velocity_north'] = [314, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                               -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                               -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                               -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                               -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                               -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                               -32768, -32768, -32768, -32768, -32768, -32768, -32768]
        self.test01['water_velocity_up'] = [459, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                            -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                            -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                            -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                            -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                            -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                            -32768]
        self.test01['error_velocity'] = [80, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                         -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                         -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                         -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                         -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                         -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768,
                                         -32768]
        #test02 data was extracted using the PD0decoder_v2 MATLAB tool
        #ensemble 1 of file ADCP_CCE1T_20.000
        self.test02 = {}
        self.test02['ensemble_number'] = 1
        self.test02['real_time_clock'] = [12, 9, 21, 0, 0, 0, 0]
        self.test02['heading'] = 21348
        self.test02['pitch'] = 4216
        self.test02['roll'] = 3980

        #test03 data was extracted using the PD0decoder_v2 MATLAB tool
        #ensemble 20 of file ADCP_CCE1T_20.000
        self.test03 = {}
        self.test03['ensemble_number'] = 20
        self.test03['real_time_clock'] = [12, 9, 21, 19, 0, 0, 0]
        self.test03['heading'] = 538
        self.test03['pitch'] = 147
        self.test03['roll'] = 221

        #test04 data was extracted using the PD0decoder_v2 MATLAB tool
        #ensemble 5 of file ADCP_CCE1T_20.000
        self.test04 = {}
        self.test04['ensemble_number'] = 6
        self.test04['real_time_clock'] = [12, 9, 21, 5, 0, 0, 0]
        self.test04['heading'] = 20127
        self.test04['pitch'] = 4218
        self.test04['roll'] = 3773

        #test05 data was extracted using the PD0decoder_v2 MATLAB tool
        #ensemble 2 of file ADCP_CCE1T_20.000
        self.test05 = {}
        self.test05['ensemble_number'] = 2
        self.test05['real_time_clock'] = [12, 9, 21, 1, 0, 0, 0]
        self.test05['heading'] = 28638
        self.test05['pitch'] = 4192
        self.test05['roll'] = 4004

    def particle_to_yml(self, particles, filename, mode='w'):
        """
        This is added as a testing helper, not actually as part of the parser tests. Since the same particles
        will be used for the driver test it is helpful to write them to .yml in the same form they need in the
        results.yml fids here.
        """
        # open write append, if you want to start from scratch manually delete this fid
        fid = open(os.path.join(RESOURCE_PATH, filename), mode)

        fid.write('header:\n')
        fid.write("    particle_object: 'MULTIPLE'\n")
        fid.write("    particle_type: 'MULTIPLE'\n")
        fid.write('data:\n')

        for i in range(0, len(particles)):
            particle_dict = particles[i].generate_dict()

            fid.write('  - _index: %d\n' % (i+1))

            fid.write('    particle_object: %s\n' % particles[i].__class__.__name__)
            fid.write('    particle_type: %s\n' % particle_dict.get('stream_name'))
            fid.write('    internal_timestamp: %f\n' % particle_dict.get('internal_timestamp'))

            for val in particle_dict.get('values'):
                if isinstance(val.get('value'), float):
                    fid.write('    %s: %16.16f\n' % (val.get('value_id'), val.get('value')))
                else:
                    fid.write('    %s: %s\n' % (val.get('value_id'), val.get('value')))
        fid.close()

    def get_dict_from_yml(self, filename):
        """
        This utility routine loads the contents of a yml file
        into a dictionary
        """

        fid = open(os.path.join(RESOURCE_PATH, filename), 'r')
        result = yaml.load(fid)
        fid.close()

        return result

    def create_yml(self):
        """
        This utility creates a yml file
        """

        #ADCP_data_20130702.PD0 has one record in it
        fid = open(os.path.join(RESOURCE_PATH, 'ADCP_CCE1T_21_40.000'), 'rb')

        self.stream_handle = fid
        self.parser = AdcpPd0Parser(self.config, self.start_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(20)

        self.particle_to_yml(particles, 'ADCP_CCE1T_21_40.yml')
        fid.close()

    def trim_file(self):
        """
        This utility routine can be used to trim large PD0 files down
        to a more manageable size.  It uses the sieve in the parser to
        create a copy of the file with a specified number of records
        """

        #define these values as needed

        input_file = 'ADCP_CCE1T.000'
        output_file = 'ADCP_CCE1T_21_40.000'
        num_rec = 20
        first_rec = 21
        log.info("opening file")
        infid = open(os.path.join(RESOURCE_PATH, input_file), 'rb')
        in_buffer = infid.read()
        log.info("file read")
        stream_handle = infid
        #parser needs a stream handle even though it won't use it
        parser = AdcpPd0Parser(self.config, self.start_state, stream_handle,
                               self.state_callback, self.pub_callback, self.exception_callback)
        log.info("parser created, calling sieve")
        indices = parser.sieve_function(in_buffer)
        #get the start and ends of all the records
        log.info("sieve returned %d indeces", len(indices))
        if len(indices) < first_rec + num_rec:
            log.info('trim_file: not enough records in file no output created')
            return

        first_byte = indices[first_rec-1][0]
        last_byte = indices[first_rec-1 + num_rec-1][1]
        log.info('first byte is %d last_byte is %d', first_byte, last_byte)

        outfid = open(os.path.join(RESOURCE_PATH, output_file), 'wb')
        outfid.write(in_buffer[first_byte:last_byte])
        outfid.close()
        infid.close()

    def assert_result(self, test, particle):
        """
        Suite of tests to run against each returned particle and expected
        results of the same.  The test parameter should be a dictionary
        that contains the keys to be tested in the particle
        the 'internal_timestamp' and 'position' keys are
        treated differently than others but can be verified if supplied
        """

        particle_dict = particle.generate_dict()

        #for efficiency turn the particle values list of dictionaries into a dictionary
        particle_values = {}
        for param in particle_dict.get('values'):
            particle_values[param['value_id']] = param['value']

        # compare each key in the test to the data in the particle
        for key in test:
            test_data = test[key]

            #get the correct data to compare to the test
            if key == 'internal_timestamp':
                particle_data = particle.get_value('internal_timestamp')
                #the timestamp is in the header part of the particle
            elif key == 'position':
                particle_data = self.state_callback_value['position']
                #position corresponds to the position in the file
            else:
                particle_data = particle_values.get(key)
                #others are all part of the parsed values part of the particle

            if particle_data is None:
                #generally OK to ignore index keys in the test data, verify others

                log.warning("\nWarning: assert_result ignoring test key %s, does not exist in particle", key)
            else:
                if isinstance(test_data, float):
                    # slightly different test for these values as they are floats.
                    compare = numpy.abs(test_data - particle_data) <= 1e-5
                    self.assertTrue(compare)
                else:
                    # otherwise they are all ints and should be exactly equal
                    self.assertEqual(test_data, particle_data)

    def test_simple(self):
        """
        Read test data and pull out data particles one at a time.
        Assert that the results are those we expected.
        The contents of ADCP_data_20130702.000 are the expected results
        from the IDD.  These results for the that record were manually verified
        and are the entire parsed particle is represented in ADCP_data_20130702.yml
        """

        #ADCP_data_20130702.PD0 has one record in it
        fid = open(os.path.join(RESOURCE_PATH, 'ADCP_data_20130702.000'), 'rb')

        self.stream_handle = fid
        self.parser = AdcpPd0Parser(self.config, self.start_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(1)

        #this simple test shows the 2 ways to verify results
        self.assert_result(self.test01, particles[0])

        test_data = self.get_dict_from_yml('ADCP_data_20130702.yml')
        self.assert_result(test_data['data'][0], particles[0])

        #close the file
        fid.close()

    def test_get_many(self):
        """
        Read test data and pull out multiple data particles at one time.
        Assert that the results are those we expected.
        """

        #ADCP_CCE1T_20.000 has 20 records in it
        fid = open(os.path.join(RESOURCE_PATH, 'ADCP_CCE1T_20.000'), 'rb')

        self.stream_handle = fid
        self.parser = AdcpPd0Parser(self.config, self.start_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(20)
        log.info('got back %d records', len(particles))

        self.assert_result(self.test02, particles[0])
        self.assert_result(self.test03, particles[19])

        fid.close()

    def test_mid_state_start(self):
        """
        Test starting the parser in a state in the middle of processing
        """
        #ADCP_CCE1T_20.000 has 20 records in it
        fid = open(os.path.join(RESOURCE_PATH, 'ADCP_CCE1T_20.000'), 'rb')

        self.stream_handle = fid

        new_state = {StateKey.POSITION: 6000}
        #ensembles in this file are 1254 bytes long
        #the first record found should be number 6 at byte 6270

        self.parser = AdcpPd0Parser(self.config, new_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(5)

        self.assert_result(self.test04, particles[0])

        fid.close()

    def test_set_state(self):
        """
        Test changing to a new state after initializing the parser and
        reading data, as if new data has been found and the state has
        changed
        """
        #ADCP_CCE1T_20.000 has 20 records in it
        fid = open(os.path.join(RESOURCE_PATH, 'ADCP_CCE1T_20.000'), 'rb')

        self.stream_handle = fid

        new_state = {StateKey.POSITION: 100}
        #ensembles in this file are 1254 bytes long
        #the first record found should be number 2 at byte 1254

        self.parser = AdcpPd0Parser(self.config, new_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(1)
        #just get 1 record
        self.assert_result(self.test05, particles[0])

        new_state = {StateKey.POSITION: 6000}
        #ensembles in this file are 1254 bytes long
        #the first record found should be number 6 at byte 6270

        self.parser = AdcpPd0Parser(self.config, new_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(1)
        #just get 1 record
        self.assert_result(self.test04, particles[0])

        fid.close()

    def test_bad_data(self):
        """
        Ensure that bad data is skipped when it exists.
        """
        #ADCP_data_Corrupted.PD0 has one bad record followed by one good in it
        fid = open(os.path.join(RESOURCE_PATH, 'ADCP_data_Corrupted.000'), 'rb')

        self.stream_handle = fid
        self.parser = AdcpPd0Parser(self.config, self.start_state, self.stream_handle,
                                    self.state_callback, self.pub_callback, self.exception_callback)

        particles = self.parser.get_records(1)
        self.assert_result(self.test01, particles[0])

        fid.close()


text:
#! /usr/bin/python3

import sys
import os
sys.path.append('../')
import numpy as np
import matplotlib.pyplot as plt
import imageio
import matplotlib.cm as cm
import time

from netCDF4 import MFDataset
import mesonh_probe as cdf

"""
test file for periodiccontainer and netcdfinterface types
    - arguments : mesonh (netcdf) files to open
"""

mesonhfiles = sys.argv[slice(1,len(sys.argv))]
atm = MFDataset(mesonhfiles)
print("MesoNH loaded !")

# probe = cdf.MesoNHProbe(atm, ['RCT'])
# probe = cdf.MesoNHProbe(atm, ['WT'])
probe = cdf.MesoNHProbe(atm, ['RCT','WT'])
# probe = cdf.MesoNHProbe(atm, ['RCT','UT','VT','WT'])
# probe = cdf.MesoNHProbe(atm, ['UT','VT'])

# probe._MesoNHProbe__targetCacheSpan = cdf.Fancy()[30, -0.3:0.3, -0.6:0.6, -0.6:0.6]
probe._MesoNHProbe__targetCacheSpan = cdf.Fancy()[10, -0.2:0.1, -0.2:0.2, -0.2:0.2]
probe._MesoNHProbe__updateThreshold = 0.0
# probe._MesoNHProbe__updateThreshold = 0.1

position = cdf.Fancy()[probe.t0 + 2000, 2.0, 0.0, 0.0]
# v = 0.025
v = 0.020
dt = 1.0
# dt = 0.1

probe.update_cache(position, blocking=True)

for i in range(1000):
    print("Read ", i, " : ", position, ", ", probe[position])
    # tmp = probe[position]
    position = (position[0] + dt,
                position[1],
                position[2],
                position[3] + v*dt,)
    time.sleep(dt)
    # time.sleep(2*dt)
    # time.sleep(0.5*dt)
    # time.sleep(1.0)


text:
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 12:10:29 2020

@author: Nick

# ***********************************************************************
# read the 6-n params file. Format: atnum, rep, rmin,emin
# here is an example file for MM3 params
# 0 0.205 1.53 0.026
# 1 12.0 1.62 0.02
# 6 12.0 2.04 0.027
# 8 12.0 1.82 0.059
# 11 12.0 2.70 0.057
#
# references: MM3 params: Allinger et al. Theochem, Vol312, 69 (1994)
# and
# Halgren, JACS, 114, 7827 (1992) https://doi.org/10.1021/ja00046a032
#
# ***********************************************************************

temperature corrected radii was set by using -s flag in Sigma.

"""
from PySigmaFunctions import atomNumbers
import csv
import math
from scipy.optimize import minimize_scalar
from potential import P16_6_4, P12_6_4, P8_6_4
from scipy import interpolate

#def adj_r(natoms,maxatoms,atomr,buffr,atnum, degK,sixnfile,rep,emin,rmin,cfour,rnew,enew,gam)
def adj_r(geometry, temp):

    #reads through the LJ parameters file and sets up
    #a list with the parameters for each molecule in the
    #geometry.
    sixnfile=[]
    rep=[]
    rmin=[]
    emin=[]
    with open('adj.pot') as csvfile:
        LJParameters = csv.reader(csvfile, delimiter=" ")
        for row in LJParameters:
            sixnfile.append(row)
    numberedGeometry = atomNumbers(geometry)

    #sets the LJ parameters for the geometry.
    for atomrow in numberedGeometry:
        for row in sixnfile:
            if str(atomrow[0]) == str(row[0]):
                #row[1] is rep, row[2] is rmin, row[3] is emin
                rep.append(float(row[1]))
                rmin.append(float(row[2]))
                emin.append(float(row[3]))
                continue

    #sets the LJ parameters for the buffer gas.
    #called as atom 0 in the LJ input parameters.
    #declared the variables as 0 just to initialize them.
    rminbuf=0
    polbuf=0
    eminbuf=0
    for row in sixnfile:
        if str(row[0]) == str(0):
            polbuf=float(row[1])
            rminbuf=float(row[2])
            eminbuf=float(row[3])

#iterate over the geometry and correct each minimum radius by finding the radius that gives the minimum
#energy of the energy well calculated from the Lennard Jones parameters defining the n-6-4 potential.

    cfour=[]
    rnew=[]
    enew=[]
    gam=[]
    atomr=[]

    for i in range(0,len(rmin)):
        radd=rminbuf
        rmin[i]=2.0*rmin[i]
        radd=2.0*rminbuf

# Combination rules from the halgren paper "HHG" for radii and (14) for emin
        reg0=(rmin[i]**3 + radd**3)/(rmin[i]**2 + radd**2)
        rmin[i]=reg0
        emin[i]=(4.0*eminbuf*emin[i])/(math.sqrt(eminbuf)+math.sqrt(emin[i]))**2

# Units: kcal/mol for potential, Angstroms for radii
#     calculate constant C4 of r^-4 term
        cfour.append(0.5*polbuf*(3.3205E2/(len(rmin)**2)))

#     find new position of potential minimum [dV(n_6_4)/dr = 0]
#     it should reasonably be between 1 and 10 angstrom or something is wrong.
#     pass the equation coefficients to the function using current iterations rep, emin, rmin, and cfour values
#     so the bounded Brent optimization function can accept the function.
        minimum = minimize_scalar(vnsixfour,args=(rep[i], emin[i], rmin[i], cfour[i]),bracket=(1,10), options={'xtol':3E-8}, method='golden')
        rnew.append(minimum.x)

#     get new well depth
        enew.append(-1*vnsixfour(rnew[i],rep[i],emin[i],rmin[i],cfour[i]))
        tstar=temp/(enew[i]*5.032E2)
#     calculate gamma
        xnumratr = 4 * cfour[i] * (6-rep[i])
        dnomnatr = 3 * rep[i] * enew[i] * rnew[i]**4 + cfour[i] * (rep[i]-12)
        gam.append(1 + xnumratr/dnomnatr)

#     calculate omegastar
        qN = QRED(tstar,gam[i],rep[i])

#     calculate the new radius
        atomr.append(rnew[i]*math.sqrt(qN))

#        print('old:', numberedGeometry[i],rmin[i],emin[i])
#        print('new:', numberedGeometry[i],rnew[i],enew[i],gam[i])
#D       write(*,*) 'omega', qN,atomr(i),tstar
    newgeometry=[]
    for row, radius in zip(geometry, atomr):
        newgeometry.append([row[0], row[1], row[2], row[3], row[4], radius])
    return newgeometry

# The n -6 -4 potential
def vnsixfour(x,rep,emin,rmin,cfour):
    gam=1.0
    pre=rep*emin/(rep*(3.0+gam)-(12.0*(1+gam)))
    vrep=pre*12.0/rep *(1+gam)*(rmin/x)**12
    vsix=-pre*4.0*gam*(rmin/x)**6
    vfour=-cfour/x**4
    vnsixfour=vrep+vsix+vfour
    return vnsixfour.real

def QRED(t,g,r):
    Q3 = P16_6_4(t,g)
    Q2 = P12_6_4(t,g)
    Q1 = P8_6_4(t,g)
    Q = [round(Q1,5), round(Q2,5), round(Q3, 5)]
    X = [8., 12., 16.]
    QN = interpolate.pchip_interpolate(X, Q, r)
    return QN

max_stars_repo_name: nperaino/HRMSScripts

max_issues_repo_name: nperaino/HRMSScripts

max_forks_repo_name: nperaino/HRMSScripts