text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqrt(x, context=None): """ Return the square root of ``x``. Return -0 if x is -0, to be consistent with the IEEE 754 standard. Return NaN if x is negative. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sqrt, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rec_sqrt(x, context=None): """ Return the reciprocal square root of x. Return +Inf if x is ±0, +0 if x is +Inf, and NaN if x is negative. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rec_sqrt, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cbrt(x, context=None): """ Return the cube root of x. For x negative, return a negative number. The cube root of -0 is defined to be -0. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cbrt, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def root(x, k, context=None): """ Return the kth root of x. For k odd and x negative (including -Inf), return a negative number. For k even and x negative (including -Inf), return NaN. The kth root of -0 is defined to be -0, whatever the parity of k. This function is only implemented for nonnegative k. """
if k < 0: raise ValueError("root function not implemented for negative k") return _apply_function_in_current_context( BigFloat, mpfr.mpfr_root, (BigFloat._implicit_convert(x), k), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pow(x, y, context=None): """ Return ``x`` raised to the power ``y``. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the pow function. * pow(±0, y) returns plus or minus infinity for y a negative odd integer. * pow(±0, y) returns plus infinity for y negative and not an odd integer. * pow(±0, y) returns plus or minus zero for y a positive odd integer. * pow(±0, y) returns plus zero for y positive and not an odd integer. * pow(-1, ±Inf) returns 1. * pow(+1, y) returns 1 for any y, even a NaN. * pow(x, ±0) returns 1 for any x, even a NaN. * pow(x, y) returns NaN for finite negative x and finite non-integer y. * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero for abs(x) > 1. * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity for abs(x) > 1. * pow(-Inf, y) returns minus zero for y a negative odd integer. * pow(-Inf, y) returns plus zero for y negative and not an odd integer. * pow(-Inf, y) returns minus infinity for y a positive odd integer. * pow(-Inf, y) returns plus infinity for y positive and not an odd integer. * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y positive. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_pow, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def neg(x, context=None): """ Return -x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_neg, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmp(op1, op2): """ Perform a three-way comparison of op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. Both op1 and op2 are considered to their full own precision, which may differ. If one of the operands is NaN, raise ValueError. Note: This function may be useful to distinguish the three possible cases. If you need to distinguish two cases only, it is recommended to use the predicate functions like 'greaterequal'; they behave like the IEEE 754 comparisons, in particular when one or both arguments are NaN. """
op1 = BigFloat._implicit_convert(op1) op2 = BigFloat._implicit_convert(op2) if is_nan(op1) or is_nan(op2): raise ValueError("Cannot perform comparison with NaN.") return mpfr.mpfr_cmp(op1, op2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmpabs(op1, op2): """ Compare the absolute values of op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. Both op1 and op2 are considered to their full own precision, which may differ. If one of the operands is NaN, raise ValueError. Note: This function may be useful to distinguish the three possible cases. If you need to distinguish two cases only, it is recommended to use the predicate functions like 'greaterequal'; they behave like the IEEE 754 comparisons, in particular when one or both arguments are NaN. """
op1 = BigFloat._implicit_convert(op1) op2 = BigFloat._implicit_convert(op2) if is_nan(op1) or is_nan(op2): raise ValueError("Cannot perform comparison with NaN.") return mpfr.mpfr_cmpabs(op1, op2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sgn(x): """ Return the sign of x. Return a positive integer if x > 0, 0 if x == 0, and a negative integer if x < 0. Raise ValueError if x is a NaN. This function is equivalent to cmp(x, 0), but more efficient. """
x = BigFloat._implicit_convert(x) if is_nan(x): raise ValueError("Cannot take sign of a NaN.") return mpfr.mpfr_sgn(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def greater(x, y): """ Return True if x > y and False otherwise. This function returns False whenever x and/or y is a NaN. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_greater_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def greaterequal(x, y): """ Return True if x >= y and False otherwise. This function returns False whenever x and/or y is a NaN. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_greaterequal_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def less(x, y): """ Return True if x < y and False otherwise. This function returns False whenever x and/or y is a NaN. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_less_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lessequal(x, y): """ Return True if x <= y and False otherwise. This function returns False whenever x and/or y is a NaN. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_lessequal_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equal(x, y): """ Return True if x == y and False otherwise. This function returns False whenever x and/or y is a NaN. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_equal_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notequal(x, y): """ Return True if x != y and False otherwise. This function returns True whenever x and/or y is a NaN. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return not mpfr.mpfr_equal_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unordered(x, y): """ Return True if x or y is a NaN and False otherwise. """
x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_unordered_p(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(x, context=None): """ Return the natural logarithm of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log2(x, context=None): """ Return the base-two logarithm of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log2, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log10(x, context=None): """ Return the base-ten logarithm of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log10, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exp(x, context=None): """ Return the exponential of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exp2(x, context=None): """ Return two raised to the power x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp2, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exp10(x, context=None): """ Return ten raised to the power x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp10, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cos(x, context=None): """ Return the cosine of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cos, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sin(x, context=None): """ Return the sine of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sin, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tan(x, context=None): """ Return the tangent of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_tan, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sec(x, context=None): """ Return the secant of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sec, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csc(x, context=None): """ Return the cosecant of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csc, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cot(x, context=None): """ Return the cotangent of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cot, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acos(x, context=None): """ Return the inverse cosine of ``x``. The mathematically exact result lies in the range [0, π]. However, note that as a result of rounding to the current context, it's possible for the actual value returned to be fractionally larger than π:: 3.1416 True """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_acos, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asin(x, context=None): """ Return the inverse sine of ``x``. The mathematically exact result lies in the range [-π/2, π/2]. However, note that as a result of rounding to the current context, it's possible for the actual value to lie just outside this range. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_asin, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atan(x, context=None): """ Return the inverse tangent of ``x``. The mathematically exact result lies in the range [-π/2, π/2]. However, note that as a result of rounding to the current context, it's possible for the actual value to lie just outside this range. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_atan, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cosh(x, context=None): """ Return the hyperbolic cosine of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_cosh, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sinh(x, context=None): """ Return the hyperbolic sine of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sinh, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tanh(x, context=None): """ Return the hyperbolic tangent of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_tanh, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sech(x, context=None): """ Return the hyperbolic secant of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sech, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csch(x, context=None): """ Return the hyperbolic cosecant of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csch, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coth(x, context=None): """ Return the hyperbolic cotangent of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_coth, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acosh(x, context=None): """ Return the inverse hyperbolic cosine of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_acosh, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asinh(x, context=None): """ Return the inverse hyperbolic sine of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_asinh, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atanh(x, context=None): """ Return the inverse hyperbolic tangent of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_atanh, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log1p(x, context=None): """ Return the logarithm of one plus x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log1p, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expm1(x, context=None): """ Return one less than the exponential of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_expm1, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eint(x, context=None): """ Return the exponential integral of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_eint, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def li2(x, context=None): """ Return the real part of the dilogarithm of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_li2, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gamma(x, context=None): """ Return the value of the Gamma function of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_gamma, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lngamma(x, context=None): """ Return the value of the logarithm of the Gamma function of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_lngamma, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lgamma(x, context=None): """ Return the logarithm of the absolute value of the Gamma function at x. """
return _apply_function_in_current_context( BigFloat, lambda rop, op, rnd: mpfr.mpfr_lgamma(rop, op, rnd)[0], (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zeta(x, context=None): """ Return the value of the Riemann zeta function on x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_zeta, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erf(x, context=None): """ Return the value of the error function at x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_erf, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erfc(x, context=None): """ Return the value of the complementary error function at x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_erfc, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def j0(x, context=None): """ Return the value of the first kind Bessel function of order 0 at x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j0, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def j1(x, context=None): """ Return the value of the first kind Bessel function of order 1 at x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j1, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jn(n, x, context=None): """ Return the value of the first kind Bessel function of order ``n`` at ``x``. ``n`` should be a Python integer. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_jn, (n, BigFloat._implicit_convert(x)), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def y0(x, context=None): """ Return the value of the second kind Bessel function of order 0 at x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_y0, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def y1(x, context=None): """ Return the value of the second kind Bessel function of order 1 at x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_y1, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yn(n, x, context=None): """ Return the value of the second kind Bessel function of order ``n`` at ``x``. ``n`` should be a Python integer. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_yn, (n, BigFloat._implicit_convert(x)), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agm(x, y, context=None): """ Return the arithmetic geometric mean of x and y. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_agm, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hypot(x, y, context=None): """ Return the Euclidean norm of x and y, i.e., the square root of the sum of the squares of x and y. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_hypot, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ai(x, context=None): """ Return the Airy function of x. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_ai, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ceil(x, context=None): """ Return the next higher or equal integer to x. If the result is not exactly representable, it will be rounded according to the current context. Note that the rounding step means that it's possible for the result to be smaller than ``x``. For example:: False One way to be sure of getting a result that's greater than or equal to ``x`` is to use the ``RoundTowardPositive`` rounding mode:: True Similar comments apply to the :func:`floor`, :func:`round` and :func:`trunc` functions. .. note:: This function corresponds to the MPFR function ``mpfr_rint_ceil``, not to ``mpfr_ceil``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_ceil, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def floor(x, context=None): """ Return the next lower or equal integer to x. If the result is not exactly representable, it will be rounded according to the current context. Note that it's possible for the result to be larger than ``x``. See the documentation of the :func:`ceil` function for more information. .. note:: This function corresponds to the MPFR function ``mpfr_rint_floor``, not to ``mpfr_floor``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_floor, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trunc(x, context=None): """ Return the next integer towards zero. If the result is not exactly representable, it will be rounded according to the current context. .. note:: This function corresponds to the MPFR function ``mpfr_rint_trunc``, not to ``mpfr_trunc``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_rint_trunc, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frac(x, context=None): """ Return the fractional part of ``x``. The result has the same sign as ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_frac, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(x, y, context=None): """ Return the minimum of x and y. If x and y are both NaN, return NaN. If exactly one of x and y is NaN, return the non-NaN value. If x and y are zeros of different signs, return −0. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_min, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max(x, y, context=None): """ Return the maximum of x and y. If x and y are both NaN, return NaN. If exactly one of x and y is NaN, return the non-NaN value. If x and y are zeros of different signs, return +0. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_max, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copysign(x, y, context=None): """ Return a new BigFloat object with the magnitude of x but the sign of y. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_copysign, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exact(cls, value, precision=None): """Convert an integer, float or BigFloat with no loss of precision. Also convert a string with given precision. This constructor makes no use of the current context. """
# figure out precision to use if isinstance(value, six.string_types): if precision is None: raise TypeError("precision must be supplied when " "converting from a string") else: if precision is not None: raise TypeError("precision argument should not be " "specified except when converting " "from a string") if isinstance(value, float): precision = _builtin_max(DBL_PRECISION, PRECISION_MIN) elif isinstance(value, six.integer_types): precision = _builtin_max(_bit_length(value), PRECISION_MIN) elif isinstance(value, BigFloat): precision = value.precision else: raise TypeError("Can't convert argument %s of type %s " "to BigFloat" % (value, type(value))) # Use unlimited exponents, with given precision. with _saved_flags(): set_flagstate(set()) # clear all flags context = ( WideExponentContext + Context(precision=precision) + RoundTiesToEven ) with context: result = BigFloat(value) if test_flag(Overflow): raise ValueError("value too large to represent as a BigFloat") if test_flag(Underflow): raise ValueError("value too small to represent as a BigFloat") if test_flag(Inexact) and not isinstance(value, six.string_types): # since this is supposed to be an exact conversion, the # inexact flag should never be set except when converting # from a string. assert False, ("Inexact conversion in BigFloat.exact. " "This shouldn't ever happen. Please report.") return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _significand(self): """Return the significand of self, as a BigFloat. If self is a nonzero finite number, return a BigFloat m with the same precision as self, such that 0.5 <= m < 1. and self = +/-m * 2**e for some exponent e. If self is zero, infinity or nan, return a copy of self with the sign set to 0. """
m = self.copy() if self and is_finite(self): mpfr.mpfr_set_exp(m, 0) mpfr.mpfr_setsign(m, m, False, ROUND_TIES_TO_EVEN) return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exponent(self): """Return the exponent of self, as an integer. The exponent is defined as the unique integer k such that 2**(k-1) <= abs(self) < 2**k. If self is not finite and nonzero, return a string: one of '0', 'inf' or 'nan'. """
if self and is_finite(self): return mpfr.mpfr_get_exp(self) if not self: return '0' elif is_inf(self): return 'inf' elif is_nan(self): return 'nan' else: assert False, "shouldn't ever get here"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_neg(self): """ Return a copy of self with the opposite sign bit. Unlike -self, this does not make use of the context: the result has the same precision as the original. """
result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) new_sign = not self._sign() mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_abs(self): """ Return a copy of self with the sign bit unset. Unlike abs(self), this does not make use of the context: the result has the same precision as the original. """
result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) mpfr.mpfr_setsign(result, self, False, ROUND_TIES_TO_EVEN) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hex(self): """Return a hexadecimal representation of a BigFloat."""
sign = '-' if self._sign() else '' e = self._exponent() if isinstance(e, six.string_types): return sign + e m = self._significand() _, digits, _ = _mpfr_get_str2( 16, 0, m, ROUND_TIES_TO_EVEN, ) # only print the number of digits that are actually necessary n = 1 + (self.precision - 1) // 4 assert all(c == '0' for c in digits[n:]) result = '%s0x0.%sp%+d' % (sign, digits[:n], e) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_to_floating_precision(self, precision): """ Format a nonzero finite BigFloat instance to a given number of significant digits. Returns a triple (negative, digits, exp) where: - negative is a boolean, True for a negative number, else False - digits is a string giving the digits of the output - exp represents the exponent of the output, The normalization of the exponent is such that <digits>E<exp> represents the decimal approximation to self. Rounding is always round-to-nearest. """
if precision <= 0: raise ValueError("precision argument should be at least 1") sign, digits, exp = _mpfr_get_str2( 10, precision, self, ROUND_TIES_TO_EVEN, ) return sign, digits, exp - len(digits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_to_fixed_precision(self, precision): """ Format 'self' to a given number of digits after the decimal point. Returns a triple (negative, digits, exp) where: - negative is a boolean, True for a negative number, else False - digits is a string giving the digits of the output - exp represents the exponent of the output The normalization of the exponent is such that <digits>E<exp> represents the decimal approximation to self. """
# MPFR only provides functions to format to a given number of # significant digits. So we must: # # (1) Identify an e such that 10**(e-1) <= abs(x) < 10**e. # # (2) Determine the number of significant digits required, and format # to that number of significant digits. # # (3) Adjust output if necessary if it's been rounded up to 10**e. # Zeros if is_zero(self): return is_negative(self), '0', -precision # Specials if is_inf(self): return is_negative(self), 'inf', None if is_nan(self): return is_negative(self), 'nan', None # Figure out the exponent by making a call to get_str2. exp satisfies # 10**(exp-1) <= self < 10**exp _, _, exp = _mpfr_get_str2( 10, 2, self, ROUND_TOWARD_ZERO, ) sig_figs = exp + precision if sig_figs < 0: sign = self._sign() return sign, '0', -precision elif sig_figs == 0: # Ex: 0.1 <= x < 1.0, rounding x to nearest multiple of 1.0. # Or: 100.0 <= x < 1000.0, rounding x to nearest multiple of 1000.0 sign, digits, new_exp = _mpfr_get_str2( 10, 2, self, ROUND_TOWARD_NEGATIVE, ) if int(digits) == 50: # Halfway case sign, digits, new_exp = _mpfr_get_str2( 10, 2, self, ROUND_TOWARD_POSITIVE, ) digits = '1' if int(digits) > 50 or new_exp == exp + 1 else '0' return sign, digits, -precision negative, digits, new_exp = self._format_to_floating_precision( sig_figs ) # It's possible that the rounding up involved changes the exponent; # in that case we have to adjust the digits accordingly. The only # possibility should be that new_exp == exp + 1. if new_exp + len(digits) != exp: assert new_exp + len(digits) == exp + 1 digits += '0' return negative, digits, -precision
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _implicit_convert(cls, arg): """Implicit conversion used for binary operations, comparisons, functions, etc. Return value should be an instance of BigFloat."""
# ints, long and floats mix freely with BigFloats, and are # converted exactly. if isinstance(arg, six.integer_types) or isinstance(arg, float): return cls.exact(arg) elif isinstance(arg, BigFloat): return arg else: raise TypeError("Unable to convert argument %s of type %s " "to BigFloat" % (arg, type(arg)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_merkle_pairs(bin_hashes, hash_function=bin_double_sha256): """ Calculate the parents of a row of a merkle tree. Takes in a list of binary hashes, returns a binary hash. The returned parents list is such that parents[i] == hash(bin_hashes[2*i] + bin_hashes[2*i+1]). """
hashes = list(bin_hashes) # if there are an odd number of hashes, double up the last one if len(hashes) % 2 == 1: hashes.append(hashes[-1]) new_hashes = [] for i in range(0, len(hashes), 2): new_hashes.append(hash_function(hashes[i] + hashes[i+1])) return new_hashes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_merkle_path(merkle_root_hex, serialized_path, leaf_hash_hex, hash_function=bin_double_sha256): """ Verify a merkle path. The given path is the path from two leaf nodes to the root itself. merkle_root_hex is a little-endian, hex-encoded hash. serialized_path is the serialized merkle path path_hex is a list of little-endian, hex-encoded hashes. Return True if the path is consistent with the merkle root. Return False if not. """
merkle_root = hex_to_bin_reversed(merkle_root_hex) leaf_hash = hex_to_bin_reversed(leaf_hash_hex) path = MerkleTree.path_deserialize(serialized_path) path = [{'order': p['order'], 'hash': hex_to_bin_reversed(p['hash'])} for p in path] if len(path) == 0: raise ValueError("Empty path") cur_hash = leaf_hash for i in range(0, len(path)): if path[i]['order'] == 'l': # left sibling cur_hash = hash_function(path[i]['hash'] + cur_hash) elif path[i]['order'] == 'r': # right sibling cur_hash = hash_function(cur_hash + path[i]['hash']) elif path[i]['order'] == 'm': # merkle root assert len(path) == 1 return cur_hash == path[i]['hash'] return cur_hash == merkle_root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _coords2idx(self, coords): """ Converts from sky coordinates to pixel indices. Args: coords (:obj:`astropy.coordinates.SkyCoord`): Sky coordinates. Returns: Pixel indices of the coordinates, with the same shape as the input coordinates. Pixels which are outside the map are given an index equal to the number of pixels in the map. """
x = self._coords2vec(coords) idx = self._kd.query(x, p=self._metric_p, distance_upper_bound=self._max_pix_scale) return idx[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gal2idx(self, gal): """ Converts from Galactic coordinates to pixel indices. Args: gal (:obj:`astropy.coordinates.SkyCoord`): Galactic coordinates. Must store an array of coordinates (i.e., not be scalar). Returns: ``j, k, mask`` - Pixel indices of the coordinates, as well as a mask of in-bounds coordinates. Outputs have the same shape as the input coordinates. """
# Make sure that l is in domain [-180 deg, 180 deg) l = coordinates.Longitude(gal.l, wrap_angle=180.*units.deg) j = (self._inv_pix_scale * (l.deg - self._l_bounds[0])).astype('i4') k = (self._inv_pix_scale * (gal.b.deg - self._b_bounds[0])).astype('i4') idx = (j < 0) | (j >= self._shape[0]) | (k < 0) | (k >= self._shape[1]) if np.any(idx): j[idx] = -1 k[idx] = -1 return j, k, ~idx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_block_hash( self, block_hash ): """ Append up to 2000 block hashes for which to get headers. """
if len(self.block_hashes) > 2000: raise Exception("A getheaders request cannot have over 2000 block hashes") hash_num = int("0x" + block_hash, 16) bh = BlockHash() bh.block_hash = hash_num self.block_hashes.append( bh ) self.hash_stop = hash_num
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run( self ): """ Interact with the blockchain peer, until we get a socket error or we exit the loop explicitly. Return True on success Raise on error """
self.handshake() try: self.loop() except socket.error, se: if self.finished: return True else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_ping(self, message_header, message): """ This method will handle the Ping message and then will answer every Ping message with a Pong message using the nonce received. :param message_header: The header of the Ping message :param message: The Ping message """
log.debug("handle ping") pong = Pong() pong.nonce = message.nonce log.debug("send pong") self.send_message(pong)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(cls, path): """ Set up an SPV client. If the locally-stored headers do not exist, then create a stub headers file with the genesis block information. """
if not os.path.exists( path ): block_header_serializer = BlockHeaderSerializer() genesis_block_header = BlockHeader() if USE_MAINNET: # we know the mainnet block header # but we don't know the testnet/regtest block header genesis_block_header.version = 1 genesis_block_header.prev_block = 0 genesis_block_header.merkle_root = int(GENESIS_BLOCK_MERKLE_ROOT, 16 ) genesis_block_header.timestamp = 1231006505 genesis_block_header.bits = int( "1d00ffff", 16 ) genesis_block_header.nonce = 2083236893 genesis_block_header.txns_count = 0 with open(path, "wb") as f: bin_data = block_header_serializer.serialize( genesis_block_header ) f.write( bin_data )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def height(cls, path): """ Get the locally-stored block height """
if os.path.exists( path ): sb = os.stat( path ) h = (sb.st_size / BLOCK_HEADER_SIZE) - 1 return h else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_header(cls, headers_path, block_height, allow_none=False): """ Get a block header at a particular height from disk. Return the header if found Return None if not. """
if os.path.exists(headers_path): header_parser = BlockHeaderSerializer() sb = os.stat( headers_path ) if sb.st_size < BLOCK_HEADER_SIZE * block_height: # beyond EOF if allow_none: return None else: raise Exception('EOF on block headers') with open( headers_path, "rb" ) as f: f.seek( block_height * BLOCK_HEADER_SIZE, os.SEEK_SET ) hdr = SPVClient.read_header_at( f ) return hdr else: if allow_none: return None else: raise Exception('No such file or directory: {}'.format(headers_path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block_header_verify( cls, headers_path, block_id, block_hash, block_header ): """ Given the block's numeric ID, its hash, and the bitcoind-returned block_data, use the SPV header chain to verify the block's integrity. block_header must be a dict with the following structure: * version: protocol version (int) * prevhash: previous block hash (hex str) * merkleroot: block Merkle root (hex str) * timestamp: UNIX time stamp (int) * bits: difficulty bits (hex str) * nonce: PoW nonce (int) * hash: block hash (hex str) (i.e. the format that the reference bitcoind returns via JSON RPC) Return True on success Return False on error """
prev_header = cls.read_header( headers_path, block_id - 1 ) prev_hash = prev_header['hash'] return bits.block_header_verify( block_header, prev_hash, block_hash )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tx_hash( cls, tx ): """ Calculate the hash of a transction structure given by bitcoind """
tx_hex = bits.btc_bitcoind_tx_serialize( tx ) tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex') return tx_hash
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tx_verify( cls, verified_block_txids, tx ): """ Given the block's verified block txids, verify that a transaction is legit. @tx must be a dict with the following fields: * locktime: int * version: int * vin: list of dicts with: * vout: int, * hash: hex str * sequence: int (optional) * scriptSig: dict with: * hex: hex str * vout: list of dicts with: * value: float * scriptPubKey: dict with: * hex: hex str """
tx_hash = cls.tx_hash( tx ) return tx_hash in verified_block_txids
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_header_chain(cls, path, chain=None): """ Verify that a given chain of block headers has sufficient proof of work. """
if chain is None: chain = SPVClient.load_header_chain( path ) prev_header = chain[0] for i in xrange(1, len(chain)): header = chain[i] height = header.get('block_height') prev_hash = prev_header.get('hash') if prev_hash != header.get('prev_block_hash'): log.error("prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash'))) return False bits, target = SPVClient.get_target( path, height/BLOCK_DIFFICULTY_CHUNK_SIZE, chain) if bits != header.get('bits'): log.error("bits mismatch: %s vs %s" % (bits, header.get('bits'))) return False _hash = header.get('hash') if int('0x'+_hash, 16) > target: log.error("insufficient proof of work: %s vs target %s" % (int('0x'+_hash, 16), target)) return False prev_header = header return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_header_chain(cls, path, bitcoind_server, last_block_id ): """ Synchronize our local block headers up to the last block ID given. @last_block_id is *inclusive* @bitcoind_server is host:port or just host """
current_block_id = SPVClient.height( path ) if current_block_id is None: assert USE_TESTNET current_block_id = -1 assert (current_block_id >= 0 and USE_MAINNET) or USE_TESTNET if current_block_id < last_block_id: if USE_MAINNET: log.debug("Synchronize %s to %s" % (current_block_id, last_block_id)) else: log.debug("Synchronize testnet %s to %s" % (current_block_id + 1, last_block_id )) # need to sync if current_block_id >= 0: prev_block_header = SPVClient.read_header( path, current_block_id ) prev_block_hash = prev_block_header['hash'] else: # can only happen when in testnet prev_block_hash = GENESIS_BLOCK_HASH_TESTNET # connect sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # timeout (10 min) sock.settimeout(600) bitcoind_port = 8333 if ":" in bitcoind_server: p = bitcoind_server.split(":") bitcoind_server = p[0] bitcoind_port = int(p[1]) log.debug("connect to %s:%s" % (bitcoind_server, bitcoind_port)) sock.connect( (bitcoind_server, bitcoind_port) ) client = BlockHeaderClient( sock, path, prev_block_hash, last_block_id ) # get headers client.run() # verify headers if SPVClient.height(path) < last_block_id: raise Exception("Did not receive all headers up to %s (only got %s)" % (last_block_id, SPVClient.height(path))) # defensive: make sure it's *exactly* that many blocks rc = SPVClient.verify_header_chain( path ) if not rc: raise Exception("Failed to verify headers (stored in '%s')" % path) log.debug("synced headers from %s to %s in %s" % (current_block_id, last_block_id, path)) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def IEEEContext(bitwidth): """ Return IEEE 754-2008 context for a given bit width. The IEEE 754 standard specifies binary interchange formats with bitwidths 16, 32, 64, 128, and all multiples of 32 greater than 128. This function returns the context corresponding to the interchange format for the given bitwidth. See section 3.6 of IEEE 754-2008 or the bigfloat source for more details. """
try: precision = {16: 11, 32: 24, 64: 53, 128: 113}[bitwidth] except KeyError: if not (bitwidth >= 128 and bitwidth % 32 == 0): raise ValueError("nonstandard bitwidth: bitwidth should be " "16, 32, 64, 128, or k*32 for some k >= 4") # The formula for the precision involves rounding 4*log2(width) to the # nearest integer. We have: # # round(4*log2(width)) == round(log2(width**8)/2) # == floor((log2(width**8) + 1)/2) # == (width**8).bit_length() // 2 # # (Note that 8*log2(width) can never be an odd integer, so we # don't care which way half-way cases round in the 'round' # operation.) precision = bitwidth - _bit_length(bitwidth ** 8) // 2 + 13 emax = 1 << bitwidth - precision - 1 return Context( precision=precision, emin=4 - emax - precision, emax=emax, subnormalize=True, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view(molecule, viewer=settings['defaults']['viewer'], use_curr_dir=False): """View your molecule or list of molecules. .. note:: This function writes a temporary file and opens it with an external viewer. If you modify your molecule afterwards you have to recall view in order to see the changes. Args: molecule: Can be a cartesian, or a list of cartesians. viewer (str): The external viewer to use. The default is specified in settings.viewer use_curr_dir (bool): If True, the temporary file is written to the current diretory. Otherwise it gets written to the OS dependendent temporary directory. Returns: None: """
try: molecule.view(viewer=viewer, use_curr_dir=use_curr_dir) except AttributeError: if pd.api.types.is_list_like(molecule): cartesian_list = molecule else: raise ValueError('Argument is neither list nor Cartesian.') if use_curr_dir: TEMP_DIR = os.path.curdir else: TEMP_DIR = tempfile.gettempdir() def give_filename(i): filename = 'ChemCoord_list_' + str(i) + '.molden' return os.path.join(TEMP_DIR, filename) i = 1 while os.path.exists(give_filename(i)): i = i + 1 to_molden(cartesian_list, buf=give_filename(i)) def open_file(i): """Open file and close after being finished.""" try: subprocess.check_call([viewer, give_filename(i)]) except (subprocess.CalledProcessError, FileNotFoundError): raise finally: if use_curr_dir: pass else: os.remove(give_filename(i)) Thread(target=open_file, args=(i,)).start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_molden(cartesian_list, buf=None, sort_index=True, overwrite=True, float_format='{:.6f}'.format): """Write a list of Cartesians into a molden file. .. note:: Since it permamently writes a file, this function is strictly speaking **not sideeffect free**. The list to be written is of course not changed. Args: cartesian_list (list): buf (str): StringIO-like, optional buffer to write to sort_index (bool): If sort_index is true, the Cartesian is sorted by the index before writing. overwrite (bool): May overwrite existing files. float_format (one-parameter function): Formatter function to apply to column’s elements if they are floats. The result of this function must be a unicode string. Returns: formatted : string (or unicode, depending on data and options) """
if sort_index: cartesian_list = [molecule.sort_index() for molecule in cartesian_list] give_header = ("[MOLDEN FORMAT]\n" + "[N_GEO]\n" + str(len(cartesian_list)) + "\n" + '[GEOCONV]\n' + 'energy\n{energy}' + 'max-force\n{max_force}' + 'rms-force\n{rms_force}' + '[GEOMETRIES] (XYZ)\n').format values = len(cartesian_list) * '1\n' energy = [str(m.metadata.get('energy', 1)) for m in cartesian_list] energy = '\n'.join(energy) + '\n' header = give_header(energy=energy, max_force=values, rms_force=values) coordinates = [x.to_xyz(sort_index=sort_index, float_format=float_format) for x in cartesian_list] output = header + '\n'.join(coordinates) if buf is not None: if overwrite: with open(buf, mode='w') as f: f.write(output) else: with open(buf, mode='x') as f: f.write(output) else: return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_molden(inputfile, start_index=0, get_bonds=True): """Read a molden file. Args: inputfile (str): start_index (int): Returns: list: A list containing :class:`~chemcoord.Cartesian` is returned. """
from chemcoord.cartesian_coordinates.cartesian_class_main import Cartesian with open(inputfile, 'r') as f: found = False while not found: line = f.readline() if '[N_GEO]' in line: found = True number_of_molecules = int(f.readline().strip()) energies = [] found = False while not found: line = f.readline() if 'energy' in line: found = True for _ in range(number_of_molecules): energies.append(float(f.readline().strip())) found = False while not found: line = f.readline() if '[GEOMETRIES] (XYZ)' in line: found = True current_line = f.tell() number_of_atoms = int(f.readline().strip()) f.seek(current_line) cartesians = [] for energy in energies: cartesian = Cartesian.read_xyz( f, start_index=start_index, get_bonds=get_bonds, nrows=number_of_atoms, engine='python') cartesian.metadata['energy'] = energy cartesians.append(cartesian) return cartesians
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat(cartesians, ignore_index=False, keys=None): """Join list of cartesians into one molecule. Wrapper around the :func:`pandas.concat` function. Default values are the same as in the pandas function except for ``verify_integrity`` which is set to true in case of this library. Args: ignore_index (sequence, bool, int): If it is a boolean, it behaves like in the description of :meth:`pandas.DataFrame.append`. If it is a sequence, it becomes the new index. If it is an integer, ``range(ignore_index, ignore_index + len(new))`` becomes the new index. keys (sequence): If multiple levels passed, should contain tuples. Construct hierarchical index using the passed keys as the outermost level Returns: Cartesian: """
frames = [molecule._frame for molecule in cartesians] new = pd.concat(frames, ignore_index=ignore_index, keys=keys, verify_integrity=True) if type(ignore_index) is bool: new = pd.concat(frames, ignore_index=ignore_index, keys=keys, verify_integrity=True) else: new = pd.concat(frames, ignore_index=True, keys=keys, verify_integrity=True) if type(ignore_index) is int: new.index = range(ignore_index, ignore_index + len(new)) else: new.index = ignore_index return cartesians[0].__class__(new)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dot(A, B): """Matrix multiplication between A and B This function is equivalent to ``A @ B``, which is unfortunately not possible under python 2.x. Args: A (sequence): B (sequence): Returns: sequence: """
try: result = A.__matmul__(B) if result is NotImplemented: result = B.__rmatmul__(A) except AttributeError: result = B.__rmatmul__(A) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orthonormalize_righthanded(basis): """Orthonormalizes righthandedly a given 3D basis. This functions returns a right handed orthonormalize_righthandedd basis. Since only the first two vectors in the basis are used, it does not matter if you give two or three vectors. Right handed means, that: .. math:: \\vec{e_1} \\times \\vec{e_2} &= \\vec{e_3} \\\\ \\vec{e_2} \\times \\vec{e_3} &= \\vec{e_1} \\\\ \\vec{e_3} \\times \\vec{e_1} &= \\vec{e_2} \\\\ Args: basis (np.array): An array of shape = (3,2) or (3,3) Returns: new_basis (np.array): A right handed orthonormalized basis. """
v1, v2 = basis[:, 0], basis[:, 1] e1 = normalize(v1) e3 = normalize(np.cross(e1, v2)) e2 = normalize(np.cross(e3, e1)) return np.array([e1, e2, e3]).T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_kabsch_rotation(Q, P): """Calculate the optimal rotation from ``P`` unto ``Q``. Using the Kabsch algorithm the optimal rotation matrix for the rotation of ``other`` unto ``self`` is calculated. The algorithm is described very well in `wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm>`_. Args: other (Cartesian): Returns: :class:`~numpy.array`: Rotation matrix """
# Naming of variables follows the wikipedia article: # http://en.wikipedia.org/wiki/Kabsch_algorithm A = np.dot(np.transpose(P), Q) # One can't initialize an array over its transposed V, S, W = np.linalg.svd(A) # pylint:disable=unused-variable W = W.T d = np.linalg.det(np.dot(W, V.T)) return np.linalg.multi_dot((W, np.diag([1., 1., d]), V.T))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_grad_zmat_tensor(grad_C, construction_table, cart_dist): """Apply the gradient for transformation to Zmatrix space onto cart_dist. Args: grad_C (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array. The mathematical details of the index layout is explained in :meth:`~chemcoord.Cartesian.get_grad_zmat()`. construction_table (pandas.DataFrame): Explained in :meth:`~chemcoord.Cartesian.get_construction_table()`. cart_dist (:class:`~chemcoord.Cartesian`): Distortions in cartesian space. Returns: :class:`Zmat`: Distortions in Zmatrix space. """
if (construction_table.index != cart_dist.index).any(): message = "construction_table and cart_dist must use the same index" raise ValueError(message) X_dist = cart_dist.loc[:, ['x', 'y', 'z']].values.T C_dist = np.tensordot(grad_C, X_dist, axes=([3, 2], [0, 1])).T if C_dist.dtype == np.dtype('i8'): C_dist = C_dist.astype('f8') try: C_dist[:, [1, 2]] = np.rad2deg(C_dist[:, [1, 2]]) except AttributeError: C_dist[:, [1, 2]] = sympy.deg(C_dist[:, [1, 2]]) from chemcoord.internal_coordinates.zmat_class_main import Zmat cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral'] dtypes = ['O', 'i8', 'f8', 'i8', 'f8', 'i8', 'f8'] new = pd.DataFrame(data=np.zeros((len(construction_table), 7)), index=cart_dist.index, columns=cols, dtype='f8') new = new.astype(dict(zip(cols, dtypes))) new.loc[:, ['b', 'a', 'd']] = construction_table new.loc[:, 'atom'] = cart_dist.loc[:, 'atom'] new.loc[:, ['bond', 'angle', 'dihedral']] = C_dist return Zmat(new, _metadata={'last_valid_cartesian': cart_dist})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _remove_child_node(node, context, xast, if_empty=False): '''Remove a child node based on the specified xpath. :param node: lxml element relative to which the xpath will be interpreted :param context: any context required for the xpath (e.g., namespace definitions) :param xast: parsed xpath (xpath abstract syntax tree) from :mod:`eulxml.xpath` :param if_empty: optional boolean; only remove a node if it is empty (no attributes and no child nodes); defaults to False :returns: True if a node was deleted ''' xpath = serialize(xast) child = _find_xml_node(xpath, node, context) if child is not None: # if if_empty was specified and node has children or attributes # other than any predicates defined in the xpath, don't remove if if_empty is True and \ not _empty_except_predicates(xast, child, context): return False node.remove(child) return True