Datasets:
mteb
/

Modalities:
Text
Formats:
parquet
ArXiv:
Libraries:
Datasets
Dask
License:
Dataset Viewer
Auto-converted to Parquet
title
stringclasses
1 value
text
stringlengths
46
1.11M
id
stringlengths
27
30
sympy/utilities/lambdify.py/_EvaluatorPrinter/_preprocess class _EvaluatorPrinter: def _preprocess(self, args, expr): """Preprocess args, expr to replace arguments that do not map to valid Python identifiers. Returns string form of args, and updated expr. """ from sympy import Dummy, Symbol, Function, flatten from sympy.matrices import DeferredVector dummify = self._dummify # Args of type Dummy can cause name collisions with args # of type Symbol. Force dummify of everything in this # situation. if not dummify: dummify = any(isinstance(arg, Dummy) for arg in flatten(args)) argstrs = [] for arg in args: if iterable(arg): nested_argstrs, expr = self._preprocess(arg, expr) argstrs.append(nested_argstrs) elif isinstance(arg, DeferredVector): argstrs.append(str(arg)) elif isinstance(arg, Symbol): argrep = self._argrepr(arg) if dummify or not self._is_safe_ident(argrep): dummy = Dummy() argstrs.append(self._argrepr(dummy)) expr = self._subexpr(expr, {arg: dummy}) else: argstrs.append(argrep) elif isinstance(arg, Function): dummy = Dummy() argstrs.append(self._argrepr(dummy)) expr = self._subexpr(expr, {arg: dummy}) else: argstrs.append(str(arg)) return argstrs, expr
apositive_train_query0_00000
examples/all.py/__import__ def __import__(name, globals=None, locals=None, fromlist=None): """An alternative to the import function so that we can import modules defined as strings. This code was taken from: http://docs.python.org/lib/examples-imp.html """ # Fast path: see if the module has already been imported. try: return sys.modules[name] except KeyError: pass # If any of the following calls raises an exception, # there's a problem we can't handle -- let the caller handle it. module_name = name.split('.')[-1] module_path = os.path.join(EXAMPLE_DIR, *name.split('.')[:-1]) fp, pathname, description = imp.find_module(module_name, [module_path]) try: return imp.load_module(module_name, fp, pathname, description) finally: # Since we may exit via an exception, close fp explicitly. if fp: fp.close()
negative_train_query0_00000
examples/all.py/load_example_module def load_example_module(example): """Loads modules based upon the given package name""" mod = __import__(example) return mod
negative_train_query0_00001
examples/all.py/run_examples def run_examples(windowed=False, quiet=False, summary=True): """Run all examples in the list of modules. Returns a boolean value indicating whether all the examples were successful. """ successes = [] failures = [] examples = TERMINAL_EXAMPLES if windowed: examples += WINDOWED_EXAMPLES if quiet: from sympy.utilities.runtests import PyTestReporter reporter = PyTestReporter() reporter.write("Testing Examples\n") reporter.write("-" * reporter.terminal_width) else: reporter = None for example in examples: if run_example(example, reporter=reporter): successes.append(example) else: failures.append(example) if summary: show_summary(successes, failures, reporter=reporter) return len(failures) == 0
negative_train_query0_00002
examples/all.py/run_example def run_example(example, reporter=None): """Run a specific example. Returns a boolean value indicating whether the example was successful. """ if reporter: reporter.write(example) else: print("=" * 79) print("Running: ", example) try: mod = load_example_module(example) if reporter: suppress_output(mod.main) reporter.write("[PASS]", "Green", align="right") else: mod.main() return True except KeyboardInterrupt as e: raise e except: if reporter: reporter.write("[FAIL]", "Red", align="right") traceback.print_exc() return False
negative_train_query0_00003
examples/all.py/suppress_output def suppress_output(fn): """Suppresses the output of fn on sys.stdout.""" save_stdout = sys.stdout try: sys.stdout = DummyFile() fn() finally: sys.stdout = save_stdout
negative_train_query0_00004
examples/all.py/show_summary def show_summary(successes, failures, reporter=None): """Shows a summary detailing which examples were successful and which failed.""" if reporter: reporter.write("-" * reporter.terminal_width) if failures: reporter.write("FAILED:\n", "Red") for example in failures: reporter.write(" %s\n" % example) else: reporter.write("ALL EXAMPLES PASSED\n", "Green") else: if successes: print("SUCCESSFUL: ", file=sys.stderr) for example in successes: print(" -", example, file=sys.stderr) else: print("NO SUCCESSFUL EXAMPLES", file=sys.stderr) if failures: print("FAILED: ", file=sys.stderr) for example in failures: print(" -", example, file=sys.stderr) else: print("NO FAILED EXAMPLES", file=sys.stderr)
negative_train_query0_00005
examples/all.py/main def main(*args, **kws): """Main script runner""" parser = optparse.OptionParser() parser.add_option('-w', '--windowed', action="store_true", dest="windowed", help="also run examples requiring windowed environment") parser.add_option('-q', '--quiet', action="store_true", dest="quiet", help="runs examples in 'quiet mode' suppressing example output and \ showing simple status messages.") parser.add_option('--no-summary', action="store_true", dest="no_summary", help="hides the summary at the end of testing the examples") (options, _) = parser.parse_args() return 0 if run_examples(windowed=options.windowed, quiet=options.quiet, summary=not options.no_summary) else 1
negative_train_query0_00006
examples/all.py/DummyFile/write class DummyFile: def write(self, x): pass
negative_train_query0_00007
examples/intermediate/vandermonde.py/symbol_gen def symbol_gen(sym_str): """Symbol generator Generates sym_str_n where n is the number of times the generator has been called. """ n = 0 while True: yield Symbol("%s_%d" % (sym_str, n)) n += 1
negative_train_query0_00008
examples/intermediate/vandermonde.py/comb_w_rep def comb_w_rep(n, k): """Combinations with repetition Returns the list of k combinations with repetition from n objects. """ if k == 0: return [[]] combs = [[i] for i in range(n)] for i in range(k - 1): curr = [] for p in combs: for m in range(p[-1], n): curr.append(p + [m]) combs = curr return combs
negative_train_query0_00009
examples/intermediate/vandermonde.py/vandermonde def vandermonde(order, dim=1, syms='a b c d'): """Computes a Vandermonde matrix of given order and dimension. Define syms to give beginning strings for temporary variables. Returns the Matrix, the temporary variables, and the terms for the polynomials. """ syms = syms.split() n = len(syms) if n < dim: new_syms = [] for i in range(dim - n): j, rem = divmod(i, n) new_syms.append(syms[rem] + str(j)) syms.extend(new_syms) terms = [] for i in range(order + 1): terms.extend(comb_w_rep(dim, i)) rank = len(terms) V = zeros(rank) generators = [symbol_gen(syms[i]) for i in range(dim)] all_syms = [] for i in range(rank): row_syms = [next(g) for g in generators] all_syms.append(row_syms) for j, term in enumerate(terms): v_entry = 1 for k in term: v_entry *= row_syms[k] V[i*rank + j] = v_entry return V, all_syms, terms
negative_train_query0_00010
examples/intermediate/vandermonde.py/gen_poly def gen_poly(points, order, syms): """Generates a polynomial using a Vandermonde system""" num_pts = len(points) if num_pts == 0: raise ValueError("Must provide points") dim = len(points[0]) - 1 if dim > len(syms): raise ValueError("Must provide at least %d symbols for the polynomial" % dim) V, tmp_syms, terms = vandermonde(order, dim) if num_pts < V.shape[0]: raise ValueError( "Must provide %d points for order %d, dimension " "%d polynomial, given %d points" % (V.shape[0], order, dim, num_pts)) elif num_pts > V.shape[0]: print("gen_poly given %d points but only requires %d, "\ "continuing using the first %d points" % \ (num_pts, V.shape[0], V.shape[0])) num_pts = V.shape[0] subs_dict = {} for j in range(dim): for i in range(num_pts): subs_dict[tmp_syms[i][j]] = points[i][j] V_pts = V.subs(subs_dict) V_inv = V_pts.inv() coeffs = V_inv.multiply(Matrix([points[i][-1] for i in range(num_pts)])) f = 0 for j, term in enumerate(terms): t = 1 for k in term: t *= syms[k] f += coeffs[j]*t return f
negative_train_query0_00011
examples/intermediate/vandermonde.py/main def main(): order = 2 V, tmp_syms, _ = vandermonde(order) print("Vandermonde matrix of order 2 in 1 dimension") pprint(V) print('-'*79) print("Computing the determinant and comparing to \sum_{0<i<j<=3}(a_j - a_i)") det_sum = 1 for j in range(order + 1): for i in range(j): det_sum *= (tmp_syms[j][0] - tmp_syms[i][0]) print(""" det(V) = %(det)s \sum = %(sum)s = %(sum_expand)s """ % {"det": V.det(), "sum": det_sum, "sum_expand": det_sum.expand(), }) print('-'*79) print("Polynomial fitting with a Vandermonde Matrix:") x, y, z = symbols('x,y,z') points = [(0, 3), (1, 2), (2, 3)] print(""" Quadratic function, represented by 3 points: points = %(pts)s f = %(f)s """ % {"pts": points, "f": gen_poly(points, 2, [x]), }) points = [(0, 1, 1), (1, 0, 0), (1, 1, 0), (Rational(1, 2), 0, 0), (0, Rational(1, 2), 0), (Rational(1, 2), Rational(1, 2), 0)] print(""" 2D Quadratic function, represented by 6 points: points = %(pts)s f = %(f)s """ % {"pts": points, "f": gen_poly(points, 2, [x, y]), }) points = [(0, 1, 1, 1), (1, 1, 0, 0), (1, 0, 1, 0), (1, 1, 1, 1)] print(""" 3D linear function, represented by 4 points: points = %(pts)s f = %(f)s """ % {"pts": points, "f": gen_poly(points, 1, [x, y, z]), })
negative_train_query0_00012
examples/intermediate/infinite_1d_box.py/X_n def X_n(n, a, x): """ Returns the wavefunction X_{n} for an infinite 1D box ``n`` the "principal" quantum number. Corresponds to the number of nodes in the wavefunction. n >= 0 ``a`` width of the well. a > 0 ``x`` x coordinate. """ n, a, x = map(S, [n, a, x]) C = sqrt(2 / a) return C * sin(pi * n * x / a)
negative_train_query0_00013
examples/intermediate/infinite_1d_box.py/E_n def E_n(n, a, mass): """ Returns the Energy psi_{n} for a 1d potential hole with infinity borders ``n`` the "principal" quantum number. Corresponds to the number of nodes in the wavefunction. n >= 0 ``a`` width of the well. a > 0 ``mass`` mass. """ return ((n * pi / a)**2) / mass
negative_train_query0_00014
examples/intermediate/infinite_1d_box.py/energy_corrections def energy_corrections(perturbation, n, a=10, mass=0.5): """ Calculating first two order corrections due to perturbation theory and returns tuple where zero element is unperturbated energy, and two second is corrections ``n`` the "nodal" quantum number. Corresponds to the number of nodes in the wavefunction. n >= 0 ``a`` width of the well. a > 0 ``mass`` mass. """ x, _a = var("x _a") Vnm = lambda n, m, a: Integral(X_n(n, a, x) * X_n(m, a, x) * perturbation.subs({_a: a}), (x, 0, a)).n() # As we know from theory for V0*r/a we will just V(n, n-1) and V(n, n+1) # wouldn't equals zero return (E_n(n, a, mass).evalf(), Vnm(n, n, a).evalf(), (Vnm(n, n - 1, a)**2/(E_n(n, a, mass) - E_n(n - 1, a, mass)) + Vnm(n, n + 1, a)**2/(E_n(n, a, mass) - E_n(n + 1, a, mass))).evalf())
negative_train_query0_00015
examples/intermediate/infinite_1d_box.py/main def main(): print() print("Applying perturbation theory to calculate the ground state energy") print("of the infinite 1D box of width ``a`` with a perturbation") print("which is linear in ``x``, up to second order in perturbation.") print() x, _a = var("x _a") perturbation = .1 * x / _a E1 = energy_corrections(perturbation, 1) print("Energy for first term (n=1):") print("E_1^{(0)} = ", E1[0]) print("E_1^{(1)} = ", E1[1]) print("E_1^{(2)} = ", E1[2]) print() E2 = energy_corrections(perturbation, 2) print("Energy for second term (n=2):") print("E_2^{(0)} = ", E2[0]) print("E_2^{(1)} = ", E2[1]) print("E_2^{(2)} = ", E2[2]) print() E3 = energy_corrections(perturbation, 3) print("Energy for third term (n=3):") print("E_3^{(0)} = ", E3[0]) print("E_3^{(1)} = ", E3[1]) print("E_3^{(2)} = ", E3[2]) print()
negative_train_query0_00016
examples/intermediate/trees.py/T def T(x): return x + x**2 + 2*x**3 + 4*x**4 + 9*x**5 + 20*x**6 + 48 * x**7 + \ 115*x**8 + 286*x**9 + 719*x**10
negative_train_query0_00017
examples/intermediate/trees.py/A def A(x): return 1 + T(x) - T(x)**2/2 + T(x**2)/2
negative_train_query0_00018
examples/intermediate/trees.py/main def main(): x = Symbol("x") s = Poly(A(x), x) num = list(reversed(s.coeffs()))[:11] print(s.as_expr()) print(num)
negative_train_query0_00019
examples/intermediate/differential_equations.py/main def main(): x = Symbol("x") f = Function("f") eq = Eq(f(x).diff(x), f(x)) print("Solution for ", eq, " : ", dsolve(eq, f(x))) eq = Eq(f(x).diff(x, 2), -f(x)) print("Solution for ", eq, " : ", dsolve(eq, f(x))) eq = Eq(x**2*f(x).diff(x), -3*x*f(x) + sin(x)/x) print("Solution for ", eq, " : ", dsolve(eq, f(x)))
negative_train_query0_00020
examples/intermediate/print_gtk.py/main def main(): x = Symbol('x') example_limit = Limit(sin(x)/x, x, 0) print_gtk(example_limit) example_integral = Integral(x, (x, 0, 1)) print_gtk(example_integral)
negative_train_query0_00021
examples/intermediate/coupled_cluster.py/get_CC_operators def get_CC_operators(): """ Returns a tuple (T1,T2) of unique operators. """ i = symbols('i', below_fermi=True, cls=Dummy) a = symbols('a', above_fermi=True, cls=Dummy) t_ai = AntiSymmetricTensor('t', (a,), (i,)) ai = NO(Fd(a)*F(i)) i, j = symbols('i,j', below_fermi=True, cls=Dummy) a, b = symbols('a,b', above_fermi=True, cls=Dummy) t_abij = AntiSymmetricTensor('t', (a, b), (i, j)) abji = NO(Fd(a)*Fd(b)*F(j)*F(i)) T1 = t_ai*ai T2 = Rational(1, 4)*t_abij*abji return (T1, T2)
negative_train_query0_00022
examples/intermediate/coupled_cluster.py/main def main(): print() print("Calculates the Coupled-Cluster energy- and amplitude equations") print("See 'An Introduction to Coupled Cluster Theory' by") print("T. Daniel Crawford and Henry F. Schaefer III") print("Reference to a Lecture Series: http://vergil.chemistry.gatech.edu/notes/sahan-cc-2010.pdf") print() # setup hamiltonian p, q, r, s = symbols('p,q,r,s', cls=Dummy) f = AntiSymmetricTensor('f', (p,), (q,)) pr = NO((Fd(p)*F(q))) v = AntiSymmetricTensor('v', (p, q), (r, s)) pqsr = NO(Fd(p)*Fd(q)*F(s)*F(r)) H = f*pr + Rational(1, 4)*v*pqsr print("Using the hamiltonian:", latex(H)) print("Calculating 4 nested commutators") C = Commutator T1, T2 = get_CC_operators() T = T1 + T2 print("commutator 1...") comm1 = wicks(C(H, T)) comm1 = evaluate_deltas(comm1) comm1 = substitute_dummies(comm1) T1, T2 = get_CC_operators() T = T1 + T2 print("commutator 2...") comm2 = wicks(C(comm1, T)) comm2 = evaluate_deltas(comm2) comm2 = substitute_dummies(comm2) T1, T2 = get_CC_operators() T = T1 + T2 print("commutator 3...") comm3 = wicks(C(comm2, T)) comm3 = evaluate_deltas(comm3) comm3 = substitute_dummies(comm3) T1, T2 = get_CC_operators() T = T1 + T2 print("commutator 4...") comm4 = wicks(C(comm3, T)) comm4 = evaluate_deltas(comm4) comm4 = substitute_dummies(comm4) print("construct Hausdorff expansion...") eq = H + comm1 + comm2/2 + comm3/6 + comm4/24 eq = eq.expand() eq = evaluate_deltas(eq) eq = substitute_dummies(eq, new_indices=True, pretty_indices=pretty_dummies_dict) print("*********************") print() print("extracting CC equations from full Hbar") i, j, k, l = symbols('i,j,k,l', below_fermi=True) a, b, c, d = symbols('a,b,c,d', above_fermi=True) print() print("CC Energy:") print(latex(wicks(eq, simplify_dummies=True, keep_only_fully_contracted=True))) print() print("CC T1:") eqT1 = wicks(NO(Fd(i)*F(a))*eq, simplify_kronecker_deltas=True, keep_only_fully_contracted=True) eqT1 = substitute_dummies(eqT1) print(latex(eqT1)) print() print("CC T2:") eqT2 = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*eq, simplify_dummies=True, keep_only_fully_contracted=True, simplify_kronecker_deltas=True) P = PermutationOperator eqT2 = simplify_index_permutations(eqT2, [P(a, b), P(i, j)]) print(latex(eqT2))
negative_train_query0_00023
examples/intermediate/partial_differential_eqs.py/main def main(): r, phi, theta = symbols("r,phi,theta") Xi = Function('Xi') R, Phi, Theta, u = map(Function, ['R', 'Phi', 'Theta', 'u']) C1, C2 = symbols('C1,C2') pprint("Separation of variables in Laplace equation in spherical coordinates") pprint("Laplace equation in spherical coordinates:") eq = Eq(D(Xi(r, phi, theta), r, 2) + 2/r * D(Xi(r, phi, theta), r) + 1/(r**2 * sin(phi)**2) * D(Xi(r, phi, theta), theta, 2) + cos(phi)/(r**2 * sin(phi)) * D(Xi(r, phi, theta), phi) + 1/r**2 * D(Xi(r, phi, theta), phi, 2)) pprint(eq) pprint("We can either separate this equation in regards with variable r:") res_r = pde_separate(eq, Xi(r, phi, theta), [R(r), u(phi, theta)]) pprint(res_r) pprint("Or separate it in regards of theta:") res_theta = pde_separate(eq, Xi(r, phi, theta), [Theta(theta), u(r, phi)]) pprint(res_theta) res_phi = pde_separate(eq, Xi(r, phi, theta), [Phi(phi), u(r, theta)]) pprint("But we cannot separate it in regards of variable phi: ") pprint("Result: %s" % res_phi) pprint("\n\nSo let's make theta dependent part equal with -C1:") eq_theta = Eq(res_theta[0], -C1) pprint(eq_theta) pprint("\nThis also means that second part is also equal to -C1:") eq_left = Eq(res_theta[1], -C1) pprint(eq_left) pprint("\nLets try to separate phi again :)") res_theta = pde_separate(eq_left, u(r, phi), [Phi(phi), R(r)]) pprint("\nThis time it is successful:") pprint(res_theta) pprint("\n\nSo our final equations with separated variables are:") pprint(eq_theta) pprint(Eq(res_theta[0], C2)) pprint(Eq(res_theta[1], C2))
negative_train_query0_00024
examples/intermediate/sample.py/sample2d def sample2d(f, x_args): """ Samples a 2d function f over specified intervals and returns two arrays (X, Y) suitable for plotting with matlab (matplotlib) syntax. See examples\mplot2d.py. f is a function of one variable, such as x**2. x_args is an interval given in the form (var, min, max, n) """ try: f = sympify(f) except SympifyError: raise ValueError("f could not be interpretted as a SymPy function") try: x, x_min, x_max, x_n = x_args except AttributeError: raise ValueError("x_args must be a tuple of the form (var, min, max, n)") x_l = float(x_max - x_min) x_d = x_l/float(x_n) X = np.arange(float(x_min), float(x_max) + x_d, x_d) Y = np.empty(len(X)) for i in range(len(X)): try: Y[i] = float(f.subs(x, X[i])) except TypeError: Y[i] = None return X, Y
negative_train_query0_00025
examples/intermediate/sample.py/sample3d def sample3d(f, x_args, y_args): """ Samples a 3d function f over specified intervals and returns three 2d arrays (X, Y, Z) suitable for plotting with matlab (matplotlib) syntax. See examples\mplot3d.py. f is a function of two variables, such as x**2 + y**2. x_args and y_args are intervals given in the form (var, min, max, n) """ x, x_min, x_max, x_n = None, None, None, None y, y_min, y_max, y_n = None, None, None, None try: f = sympify(f) except SympifyError: raise ValueError("f could not be interpreted as a SymPy function") try: x, x_min, x_max, x_n = x_args y, y_min, y_max, y_n = y_args except AttributeError: raise ValueError("x_args and y_args must be tuples of the form (var, min, max, intervals)") x_l = float(x_max - x_min) x_d = x_l/float(x_n) x_a = np.arange(float(x_min), float(x_max) + x_d, x_d) y_l = float(y_max - y_min) y_d = y_l/float(y_n) y_a = np.arange(float(y_min), float(y_max) + y_d, y_d) def meshgrid(x, y): """ Taken from matplotlib.mlab.meshgrid. """ x = np.array(x) y = np.array(y) numRows, numCols = len(y), len(x) x.shape = 1, numCols X = np.repeat(x, numRows, 0) y.shape = numRows, 1 Y = np.repeat(y, numCols, 1) return X, Y X, Y = np.meshgrid(x_a, y_a) Z = np.ndarray((len(X), len(X[0]))) for j in range(len(X)): for k in range(len(X[0])): try: Z[j][k] = float(f.subs(x, X[j][k]).subs(y, Y[j][k])) except (TypeError, NotImplementedError): Z[j][k] = 0 return X, Y, Z
negative_train_query0_00026
examples/intermediate/sample.py/sample def sample(f, *var_args): """ Samples a 2d or 3d function over specified intervals and returns a dataset suitable for plotting with matlab (matplotlib) syntax. Wrapper for sample2d and sample3d. f is a function of one or two variables, such as x**2. var_args are intervals for each variable given in the form (var, min, max, n) """ if len(var_args) == 1: return sample2d(f, var_args[0]) elif len(var_args) == 2: return sample3d(f, var_args[0], var_args[1]) else: raise ValueError("Only 2d and 3d sampling are supported at this time.")
negative_train_query0_00027
examples/intermediate/sample.py/meshgrid def meshgrid(x, y): """ Taken from matplotlib.mlab.meshgrid. """ x = np.array(x) y = np.array(y) numRows, numCols = len(y), len(x) x.shape = 1, numCols X = np.repeat(x, numRows, 0) y.shape = numRows, 1 Y = np.repeat(y, numCols, 1) return X, Y
negative_train_query0_00028
examples/intermediate/mplot3d.py/mplot3d def mplot3d(f, var1, var2, show=True): """ Plot a 3d function using matplotlib/Tk. """ import warnings warnings.filterwarnings("ignore", "Could not match \S") p = import_module('pylab') # Try newer version first p3 = import_module('mpl_toolkits.mplot3d', __import__kwargs={'fromlist': ['something']}) or import_module('matplotlib.axes3d') if not p or not p3: sys.exit("Matplotlib is required to use mplot3d.") x, y, z = sample(f, var1, var2) fig = p.figure() ax = p3.Axes3D(fig) # ax.plot_surface(x, y, z, rstride=2, cstride=2) ax.plot_wireframe(x, y, z) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if show: p.show()
negative_train_query0_00029
examples/intermediate/mplot3d.py/main def main(): x = Symbol('x') y = Symbol('y') mplot3d(x**2 - y**2, (x, -10.0, 10.0, 20), (y, -10.0, 10.0, 20))
negative_train_query0_00030
examples/intermediate/mplot2d.py/mplot2d def mplot2d(f, var, show=True): """ Plot a 2d function using matplotlib/Tk. """ import warnings warnings.filterwarnings("ignore", "Could not match \S") p = import_module('pylab') if not p: sys.exit("Matplotlib is required to use mplot2d.") if not is_sequence(f): f = [f, ] for f_i in f: x, y = sample(f_i, var) p.plot(x, y) p.draw() if show: p.show()
negative_train_query0_00031
examples/intermediate/mplot2d.py/main def main(): x = Symbol('x') # mplot2d(log(x), (x, 0, 2, 100)) # mplot2d([sin(x), -sin(x)], (x, float(-2*pi), float(2*pi), 50)) mplot2d([sqrt(x), -sqrt(x), sqrt(-x), -sqrt(-x)], (x, -40.0, 40.0, 80))
negative_train_query0_00032
examples/beginner/limits_examples.py/sqrt3 def sqrt3(x): return x**Rational(1, 3)
negative_train_query0_00033
examples/beginner/limits_examples.py/show def show(computed, correct): print("computed:", computed, "correct:", correct)
negative_train_query0_00034
examples/beginner/limits_examples.py/main def main(): x = Symbol("x") show( limit(sqrt(x**2 - 5*x + 6) - x, x, oo), -Rational(5)/2 ) show( limit(x*(sqrt(x**2 + 1) - x), x, oo), Rational(1)/2 ) show( limit(x - sqrt(x**3 - 1), x, oo), Rational(0) ) show( limit(log(1 + exp(x))/x, x, -oo), Rational(0) ) show( limit(log(1 + exp(x))/x, x, oo), Rational(1) ) show( limit(sin(3*x)/x, x, 0), Rational(3) ) show( limit(sin(5*x)/sin(2*x), x, 0), Rational(5)/2 ) show( limit(((x - 1)/(x + 1))**x, x, oo), exp(-2))
negative_train_query0_00035
examples/beginner/series.py/main def main(): x = Symbol('x') e = 1/cos(x) print('') print("Series for sec(x):") print('') pprint(e.series(x, 0, 10)) print("\n") e = 1/sin(x) print("Series for csc(x):") print('') pprint(e.series(x, 0, 4)) print('')
negative_train_query0_00036
examples/beginner/precision.py/main def main(): x = Pow(2, 50, evaluate=False) y = Pow(10, -50, evaluate=False) # A large, unevaluated expression m = Mul(x, y, evaluate=False) # Evaluating the expression e = S(2)**50/S(10)**50 print("%s == %s" % (m, e))
negative_train_query0_00037
examples/beginner/plotting_nice_plot.py/main def main(): fun1 = cos(x)*sin(y) fun2 = sin(x)*sin(y) fun3 = cos(y) + log(tan(y/2)) + 0.2*x PygletPlot(fun1, fun2, fun3, [x, -0.00, 12.4, 40], [y, 0.1, 2, 40])
negative_train_query0_00038
examples/beginner/print_pretty.py/main def main(): x = Symbol("x") y = Symbol("y") pprint( x**x ) print('\n') # separate with two blank likes pprint(x**2 + y + x) print('\n') pprint(sin(x)**x) print('\n') pprint( sin(x)**cos(x) ) print('\n') pprint( sin(x)/(cos(x)**2 * x**x + (2*y)) ) print('\n') pprint( sin(x**2 + exp(x)) ) print('\n') pprint( sqrt(exp(x)) ) print('\n') pprint( sqrt(sqrt(exp(x))) ) print('\n') pprint( (1/cos(x)).series(x, 0, 10) ) print('\n')
negative_train_query0_00039
examples/beginner/expansion.py/main def main(): a = Symbol('a') b = Symbol('b') e = (a + b)**5 print("\nExpression:") pprint(e) print('\nExpansion of the above expression:') pprint(e.expand()) print()
negative_train_query0_00040
examples/beginner/differentiation.py/main def main(): a = Symbol('a') b = Symbol('b') e = (a + 2*b)**5 print("\nExpression : ") print() pprint(e) print("\n\nDifferentiating w.r.t. a:") print() pprint(e.diff(a)) print("\n\nDifferentiating w.r.t. b:") print() pprint(e.diff(b)) print("\n\nSecond derivative of the above result w.r.t. a:") print() pprint(e.diff(b).diff(a, 2)) print("\n\nExpanding the above result:") print() pprint(e.expand().diff(b).diff(a, 2)) print()
negative_train_query0_00041
examples/beginner/functions.py/main def main(): a = Symbol('a') b = Symbol('b') e = log((a + b)**5) print() pprint(e) print('\n') e = exp(e) pprint(e) print('\n') e = log(exp((a + b)**5)) pprint(e) print
negative_train_query0_00042
examples/beginner/substitution.py/main def main(): x = sympy.Symbol('x') y = sympy.Symbol('y') e = 1/sympy.cos(x) print() pprint(e) print('\n') pprint(e.subs(sympy.cos(x), y)) print('\n') pprint(e.subs(sympy.cos(x), y).subs(y, x**2)) e = 1/sympy.log(x) e = e.subs(x, sympy.Float("2.71828")) print('\n') pprint(e) print('\n') pprint(e.evalf()) print() a = sympy.Symbol('a') b = sympy.Symbol('b') e = a*2 + a**b/a print('\n') pprint(e) a = 2 print('\n') pprint(e.subs(a,8)) print()
negative_train_query0_00043
examples/beginner/basic.py/main def main(): a = Symbol('a') b = Symbol('b') c = Symbol('c') e = ( a*b*b + 2*b*a*b )**c print('') pprint(e) print('')
negative_train_query0_00044
examples/advanced/grover_example.py/demo_vgate_app def demo_vgate_app(v): for i in range(2**v.nqubits): print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits)) pprint(qapply(v*IntQubit(i, v.nqubits))) qapply(v*IntQubit(i, v.nqubits))
negative_train_query0_00045
examples/advanced/grover_example.py/black_box def black_box(qubits): return True if qubits == IntQubit(1, qubits.nqubits) else False
negative_train_query0_00046
examples/advanced/grover_example.py/main def main(): print() print('Demonstration of Grover\'s Algorithm') print('The OracleGate or V Gate carries the unknown function f(x)') print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)') print('> and 0 (False in our case) otherwise') print() nqubits = 2 print('nqubits = ', nqubits) v = OracleGate(nqubits, black_box) print('Oracle or v = OracleGate(%r, black_box)' % nqubits) print() psi = superposition_basis(nqubits) print('psi:') pprint(psi) demo_vgate_app(v) print('qapply(v*psi)') pprint(qapply(v*psi)) print() w = WGate(nqubits) print('WGate or w = WGate(%r)' % nqubits) print('On a 2 Qubit system like psi, 1 iteration is enough to yield |1>') print('qapply(w*v*psi)') pprint(qapply(w*v*psi)) print() nqubits = 3 print('On a 3 Qubit system, it requires 2 iterations to achieve') print('|1> with high enough probability') psi = superposition_basis(nqubits) print('psi:') pprint(psi) v = OracleGate(nqubits, black_box) print('Oracle or v = OracleGate(%r, black_box)' % nqubits) print() print('iter1 = grover.grover_iteration(psi, v)') iter1 = qapply(grover_iteration(psi, v)) pprint(iter1) print() print('iter2 = grover.grover_iteration(iter1, v)') iter2 = qapply(grover_iteration(iter1, v)) pprint(iter2) print()
negative_train_query0_00047
examples/advanced/autowrap_integrators.py/main def main(): print(__doc__) # arrays are represented with IndexedBase, indices with Idx m = Symbol('m', integer=True) i = Idx('i', m) A = IndexedBase('A') B = IndexedBase('B') x = Symbol('x') print("Compiling ufuncs for radial harmonic oscillator solutions") # setup a basis of ho-solutions (for l=0) basis_ho = {} for n in range(basis_dimension): # Setup the radial ho solution for this n expr = R_nl(n, orbital_momentum_l, omega2, x) # Reduce the number of operations in the expression by eval to float expr = expr.evalf(15) print("The h.o. wave function with l = %i and n = %i is" % ( orbital_momentum_l, n)) pprint(expr) # implement, compile and wrap it as a ufunc basis_ho[n] = ufuncify(x, expr) # now let's see if we can express a hydrogen radial wave in terms of # the ho basis. Here's the solution we will approximate: H_ufunc = ufuncify(x, hydro_nl(hydrogen_n, orbital_momentum_l, 1, x)) # The transformation to a different basis can be written like this, # # psi(r) = sum_i c(i) phi_i(r) # # where psi(r) is the hydrogen solution, phi_i(r) are the H.O. solutions # and c(i) are scalar coefficients. # # So in order to express a hydrogen solution in terms of the H.O. basis, we # need to determine the coefficients c(i). In position space, it means # that we need to evaluate an integral: # # psi(r) = sum_i Integral(R**2*conj(phi(R))*psi(R), (R, 0, oo)) phi_i(r) # # To calculate the integral with autowrap, we notice that it contains an # element-wise sum over all vectors. Using the Indexed class, it is # possible to generate autowrapped functions that perform summations in # the low-level code. (In fact, summations are very easy to create, and as # we will see it is often necessary to take extra steps in order to avoid # them.) # we need one integration ufunc for each wave function in the h.o. basis binary_integrator = {} for n in range(basis_dimension): # # setup basis wave functions # # To get inline expressions in the low level code, we attach the # wave function expressions to a regular SymPy function using the # implemented_function utility. This is an extra step needed to avoid # erroneous summations in the wave function expressions. # # Such function objects carry around the expression they represent, # but the expression is not exposed unless explicit measures are taken. # The benefit is that the routines that searches for repeated indices # in order to make contractions will not search through the wave # function expression. psi_ho = implemented_function('psi_ho', Lambda(x, R_nl(n, orbital_momentum_l, omega2, x))) # We represent the hydrogen function by an array which will be an input # argument to the binary routine. This will let the integrators find # h.o. basis coefficients for any wave function we throw at them. psi = IndexedBase('psi') # # setup expression for the integration # step = Symbol('step') # use symbolic stepsize for flexibility # let i represent an index of the grid array, and let A represent the # grid array. Then we can approximate the integral by a sum over the # following expression (simplified rectangular rule, ignoring end point # corrections): expr = A[i]**2*psi_ho(A[i])*psi[i]*step if n == 0: print("Setting up binary integrators for the integral:") pprint(Integral(x**2*psi_ho(x)*Function('psi')(x), (x, 0, oo))) # Autowrap it. For functions that take more than one argument, it is # a good idea to use the 'args' keyword so that you know the signature # of the wrapped function. (The dimension m will be an optional # argument, but it must be present in the args list.) binary_integrator[n] = autowrap(expr, args=[A.label, psi.label, step, m]) # Lets see how it converges with the grid dimension print("Checking convergence of integrator for n = %i" % n) for g in range(3, 8): grid, step = np.linspace(0, rmax, 2**g, retstep=True) print("grid dimension %5i, integral = %e" % (2**g, binary_integrator[n](grid, H_ufunc(grid), step))) print("A binary integrator has been set up for each basis state") print("We will now use them to reconstruct a hydrogen solution.") # Note: We didn't need to specify grid or use gridsize before now grid, stepsize = np.linspace(0, rmax, gridsize, retstep=True) print("Calculating coefficients with gridsize = %i and stepsize %f" % ( len(grid), stepsize)) coeffs = {} for n in range(basis_dimension): coeffs[n] = binary_integrator[n](grid, H_ufunc(grid), stepsize) print("c(%i) = %e" % (n, coeffs[n])) print("Constructing the approximate hydrogen wave") hydro_approx = 0 all_steps = {} for n in range(basis_dimension): hydro_approx += basis_ho[n](grid)*coeffs[n] all_steps[n] = hydro_approx.copy() if pylab: line = pylab.plot(grid, all_steps[n], ':', label='max n = %i' % n) # check error numerically diff = np.max(np.abs(hydro_approx - H_ufunc(grid))) print("Error estimate: the element with largest deviation misses by %f" % diff) if diff > 0.01: print("This is much, try to increase the basis size or adjust omega") else: print("Ah, that's a pretty good approximation!") # Check visually if pylab: print("Here's a plot showing the contribution for each n") line[0].set_linestyle('-') pylab.plot(grid, H_ufunc(grid), 'r-', label='exact') pylab.legend() pylab.show() print("""Note: These binary integrators were specialized to find coefficients for a harmonic oscillator basis, but they can process any wave function as long as it is available as a vector and defined on a grid with equidistant points. That is, on any grid you get from numpy.linspace. To make the integrators even more flexible, you can setup the harmonic oscillator solutions with symbolic parameters omega and l. Then the autowrapped binary routine will take these scalar variables as arguments, so that the integrators can find coefficients for *any* isotropic harmonic oscillator basis. """)
negative_train_query0_00048
examples/advanced/fem.py/bernstein_space def bernstein_space(order, nsd): if nsd > 3: raise RuntimeError("Bernstein only implemented in 1D, 2D, and 3D") sum = 0 basis = [] coeff = [] if nsd == 1: b1, b2 = x, 1 - x for o1 in range(0, order + 1): for o2 in range(0, order + 1): if o1 + o2 == order: aij = Symbol("a_%d_%d" % (o1, o2)) sum += aij*binomial(order, o1)*pow(b1, o1)*pow(b2, o2) basis.append(binomial(order, o1)*pow(b1, o1)*pow(b2, o2)) coeff.append(aij) if nsd == 2: b1, b2, b3 = x, y, 1 - x - y for o1 in range(0, order + 1): for o2 in range(0, order + 1): for o3 in range(0, order + 1): if o1 + o2 + o3 == order: aij = Symbol("a_%d_%d_%d" % (o1, o2, o3)) fac = factorial(order) / (factorial(o1)*factorial(o2)*factorial(o3)) sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3) basis.append(fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)) coeff.append(aij) if nsd == 3: b1, b2, b3, b4 = x, y, z, 1 - x - y - z for o1 in range(0, order + 1): for o2 in range(0, order + 1): for o3 in range(0, order + 1): for o4 in range(0, order + 1): if o1 + o2 + o3 + o4 == order: aij = Symbol("a_%d_%d_%d_%d" % (o1, o2, o3, o4)) fac = factorial(order)/(factorial(o1)*factorial(o2)*factorial(o3)*factorial(o4)) sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)*pow(b4, o4) basis.append(fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)*pow(b4, o4)) coeff.append(aij) return sum, coeff, basis
negative_train_query0_00049
examples/advanced/fem.py/create_point_set def create_point_set(order, nsd): h = Rational(1, order) set = [] if nsd == 1: for i in range(0, order + 1): x = i*h if x <= 1: set.append((x, y)) if nsd == 2: for i in range(0, order + 1): x = i*h for j in range(0, order + 1): y = j*h if x + y <= 1: set.append((x, y)) if nsd == 3: for i in range(0, order + 1): x = i*h for j in range(0, order + 1): y = j*h for k in range(0, order + 1): z = j*h if x + y + z <= 1: set.append((x, y, z)) return set
negative_train_query0_00050
examples/advanced/fem.py/create_matrix def create_matrix(equations, coeffs): A = zeros(len(equations)) i = 0 j = 0 for j in range(0, len(coeffs)): c = coeffs[j] for i in range(0, len(equations)): e = equations[i] d, _ = reduced(e, [c]) A[i, j] = d[0] return A
negative_train_query0_00051
examples/advanced/fem.py/main def main(): t = ReferenceSimplex(2) fe = Lagrange(2, 2) u = 0 # compute u = sum_i u_i N_i us = [] for i in range(0, fe.nbf()): ui = Symbol("u_%d" % i) us.append(ui) u += ui*fe.N[i] J = zeros(fe.nbf()) for i in range(0, fe.nbf()): Fi = u*fe.N[i] print(Fi) for j in range(0, fe.nbf()): uj = us[j] integrands = diff(Fi, uj) print(integrands) J[j, i] = t.integrate(integrands) pprint(J)
negative_train_query0_00052
examples/advanced/fem.py/ReferenceSimplex/__init__ class ReferenceSimplex: def __init__(self, nsd): self.nsd = nsd if nsd <= 3: coords = symbols('x,y,z')[:nsd] else: coords = [Symbol("x_%d" % d) for d in range(nsd)] self.coords = coords
negative_train_query0_00053
examples/advanced/fem.py/ReferenceSimplex/integrate class ReferenceSimplex: def integrate(self, f): coords = self.coords nsd = self.nsd limit = 1 for p in coords: limit -= p intf = f for d in range(0, nsd): p = coords[d] limit += p intf = integrate(intf, (p, 0, limit)) return intf
negative_train_query0_00054
examples/advanced/fem.py/Lagrange/__init__ class Lagrange: def __init__(self, nsd, order): self.nsd = nsd self.order = order self.compute_basis()
negative_train_query0_00055
examples/advanced/fem.py/Lagrange/nbf class Lagrange: def nbf(self): return len(self.N)
negative_train_query0_00056
examples/advanced/fem.py/Lagrange/compute_basis class Lagrange: def compute_basis(self): order = self.order nsd = self.nsd N = [] pol, coeffs, basis = bernstein_space(order, nsd) points = create_point_set(order, nsd) equations = [] for p in points: ex = pol.subs(x, p[0]) if nsd > 1: ex = ex.subs(y, p[1]) if nsd > 2: ex = ex.subs(z, p[2]) equations.append(ex) A = create_matrix(equations, coeffs) Ainv = A.inv() b = eye(len(equations)) xx = Ainv*b for i in range(0, len(equations)): Ni = pol for j in range(0, len(coeffs)): Ni = Ni.subs(coeffs[j], xx[j, i]) N.append(Ni) self.N = N
negative_train_query0_00057
examples/advanced/autowrap_ufuncify.py/main def main(): print(__doc__) x = symbols('x') # a numpy array we can apply the ufuncs to grid = np.linspace(-1, 1, 1000) # set mpmath precision to 20 significant numbers for verification mpmath.mp.dps = 20 print("Compiling legendre ufuncs and checking results:") # Let's also plot the ufunc's we generate for n in range(6): # Setup the SymPy expression to ufuncify expr = legendre(n, x) print("The polynomial of degree %i is" % n) pprint(expr) # This is where the magic happens: binary_poly = ufuncify(x, expr) # It's now ready for use with numpy arrays polyvector = binary_poly(grid) # let's check the values against mpmath's legendre function maxdiff = 0 for j in range(len(grid)): precise_val = mpmath.legendre(n, grid[j]) diff = abs(polyvector[j] - precise_val) if diff > maxdiff: maxdiff = diff print("The largest error in applied ufunc was %e" % maxdiff) assert maxdiff < 1e-14 # We can also attach the autowrapped legendre polynomial to a sympy # function and plot values as they are calculated by the binary function plot1 = plt.pyplot.plot(grid, polyvector, hold=True) print("Here's a plot with values calculated by the wrapped binary functions") plt.pyplot.show()
negative_train_query0_00058
examples/advanced/dense_coding_example.py/main def main(): psi = superposition_basis(2) psi # Dense coding demo: # Assume Alice has the left QBit in psi print("An even superposition of 2 qubits. Assume Alice has the left QBit.") pprint(psi) # The corresponding gates applied to Alice's QBit are: # Identity Gate (1), Not Gate (X), Z Gate (Z), Z Gate and Not Gate (ZX) # Then there's the controlled not gate (with Alice's as control):CNOT(1, 0) # And the Hadamard gate applied to Alice's Qbit: H(1) # To Send Bob the message |0>|0> print("To Send Bob the message |00>.") circuit = H(1)*CNOT(1, 0) result = qapply(circuit*psi) result pprint(result) # To send Bob the message |0>|1> print("To Send Bob the message |01>.") circuit = H(1)*CNOT(1, 0)*X(1) result = qapply(circuit*psi) result pprint(result) # To send Bob the message |1>|0> print("To Send Bob the message |10>.") circuit = H(1)*CNOT(1, 0)*Z(1) result = qapply(circuit*psi) result pprint(result) # To send Bob the message |1>|1> print("To Send Bob the message |11>.") circuit = H(1)*CNOT(1, 0)*Z(1)*X(1) result = qapply(circuit*psi) result pprint(result)
negative_train_query0_00059
examples/advanced/qft.py/u def u(p, r): """ p = (p1, p2, p3); r = 0,1 """ if r not in [1, 2]: raise ValueError("Value of r should lie between 1 and 2") p1, p2, p3 = p if r == 1: ksi = Matrix([[1], [0]]) else: ksi = Matrix([[0], [1]]) a = (sigma1*p1 + sigma2*p2 + sigma3*p3) / (E + m)*ksi if a == 0: a = zeros(2, 1) return sqrt(E + m) *\ Matrix([[ksi[0, 0]], [ksi[1, 0]], [a[0, 0]], [a[1, 0]]])
negative_train_query0_00060
examples/advanced/qft.py/v def v(p, r): """ p = (p1, p2, p3); r = 0,1 """ if r not in [1, 2]: raise ValueError("Value of r should lie between 1 and 2") p1, p2, p3 = p if r == 1: ksi = Matrix([[1], [0]]) else: ksi = -Matrix([[0], [1]]) a = (sigma1*p1 + sigma2*p2 + sigma3*p3) / (E + m)*ksi if a == 0: a = zeros(2, 1) return sqrt(E + m) *\ Matrix([[a[0, 0]], [a[1, 0]], [ksi[0, 0]], [ksi[1, 0]]])
negative_train_query0_00061
examples/advanced/qft.py/pslash def pslash(p): p1, p2, p3 = p p0 = sqrt(m**2 + p1**2 + p2**2 + p3**2) return gamma0*p0 - gamma1*p1 - gamma2*p2 - gamma3*p3
negative_train_query0_00062
examples/advanced/qft.py/Tr def Tr(M): return M.trace()
negative_train_query0_00063
examples/advanced/qft.py/xprint def xprint(lhs, rhs): pprint(Eq(sympify(lhs), rhs))
negative_train_query0_00064
examples/advanced/qft.py/main def main(): a = Symbol("a", real=True) b = Symbol("b", real=True) c = Symbol("c", real=True) p = (a, b, c) assert u(p, 1).D*u(p, 2) == Matrix(1, 1, [0]) assert u(p, 2).D*u(p, 1) == Matrix(1, 1, [0]) p1, p2, p3 = [Symbol(x, real=True) for x in ["p1", "p2", "p3"]] pp1, pp2, pp3 = [Symbol(x, real=True) for x in ["pp1", "pp2", "pp3"]] k1, k2, k3 = [Symbol(x, real=True) for x in ["k1", "k2", "k3"]] kp1, kp2, kp3 = [Symbol(x, real=True) for x in ["kp1", "kp2", "kp3"]] p = (p1, p2, p3) pp = (pp1, pp2, pp3) k = (k1, k2, k3) kp = (kp1, kp2, kp3) mu = Symbol("mu") e = (pslash(p) + m*ones(4))*(pslash(k) - m*ones(4)) f = pslash(p) + m*ones(4) g = pslash(p) - m*ones(4) xprint('Tr(f*g)', Tr(f*g)) M0 = [(v(pp, 1).D*mgamma(mu)*u(p, 1))*(u(k, 1).D*mgamma(mu, True) * v(kp, 1)) for mu in range(4)] M = M0[0] + M0[1] + M0[2] + M0[3] M = M[0] if not isinstance(M, Basic): raise TypeError("Invalid type of variable") d = Symbol("d", real=True) # d=E+m xprint('M', M) print("-"*40) M = ((M.subs(E, d - m)).expand()*d**2).expand() xprint('M2', 1 / (E + m)**2*M) print("-"*40) x, y = M.as_real_imag() xprint('Re(M)', x) xprint('Im(M)', y) e = x**2 + y**2 xprint('abs(M)**2', e) print("-"*40) xprint('Expand(abs(M)**2)', e.expand())
negative_train_query0_00065
examples/advanced/pidigits.py/display_fraction def display_fraction(digits, skip=0, colwidth=10, columns=5): """Pretty printer for first n digits of a fraction""" perline = colwidth * columns printed = 0 for linecount in range((len(digits) - skip) // (colwidth * columns)): line = digits[skip + linecount*perline:skip + (linecount + 1)*perline] for i in range(columns): print(line[i*colwidth: (i + 1)*colwidth],) print(":", (linecount + 1)*perline) if (linecount + 1) % 10 == 0: print printed += colwidth*columns rem = (len(digits) - skip) % (colwidth * columns) if rem: buf = digits[-rem:] s = "" for i in range(columns): s += buf[:colwidth].ljust(colwidth + 1, " ") buf = buf[colwidth:] print(s + ":", printed + colwidth*columns)
negative_train_query0_00066
examples/advanced/pidigits.py/calculateit def calculateit(func, base, n, tofile): """Writes first n base-digits of a mpmath function to file""" prec = 100 intpart = libmp.numeral(3, base) if intpart == 0: skip = 0 else: skip = len(intpart) print("Step 1 of 2: calculating binary value...") prec = int(n*math.log(base, 2)) + 10 t = clock() a = func(prec) step1_time = clock() - t print("Step 2 of 2: converting to specified base...") t = clock() d = libmp.bin_to_radix(a.man, -a.exp, base, n) d = libmp.numeral(d, base, n) step2_time = clock() - t print("\nWriting output...\n") if tofile: out_ = sys.stdout sys.stdout = tofile print("%i base-%i digits of pi:\n" % (n, base)) print(intpart, ".\n") display_fraction(d, skip, colwidth=10, columns=5) if tofile: sys.stdout = out_ print("\nFinished in %f seconds (%f calc, %f convert)" % \ ((step1_time + step2_time), step1_time, step2_time))
negative_train_query0_00067
examples/advanced/pidigits.py/interactive def interactive(): """Simple function to interact with user""" print("Compute digits of pi with SymPy\n") base = input("Which base? (2-36, 10 for decimal) \n> ") digits = input("How many digits? (enter a big number, say, 10000)\n> ") tofile = raw_input("Output to file? (enter a filename, or just press enter\nto print directly to the screen) \n> ") if tofile: tofile = open(tofile, "w") calculateit(pi, base, digits, tofile)
negative_train_query0_00068
examples/advanced/pidigits.py/main def main(): """A non-interactive runner""" base = 16 digits = 500 tofile = None calculateit(pi, base, digits, tofile)
negative_train_query0_00069
examples/advanced/pyglet_plotting.py/main def main(): x, y, z = symbols('x,y,z') # toggle axes visibility with F5, colors with F6 axes_options = 'visible=false; colored=true; label_ticks=true; label_axes=true; overlay=true; stride=0.5' # axes_options = 'colored=false; overlay=false; stride=(1.0, 0.5, 0.5)' p = PygletPlot( width=600, height=500, ortho=False, invert_mouse_zoom=False, axes=axes_options, antialiasing=True) examples = [] def example_wrapper(f): examples.append(f) return f @example_wrapper def mirrored_saddles(): p[5] = x**2 - y**2, [20], [20] p[6] = y**2 - x**2, [20], [20] @example_wrapper def mirrored_saddles_saveimage(): p[5] = x**2 - y**2, [20], [20] p[6] = y**2 - x**2, [20], [20] p.wait_for_calculations() # although the calculation is complete, # we still need to wait for it to be # rendered, so we'll sleep to be sure. sleep(1) p.saveimage("plot_example.png") @example_wrapper def mirrored_ellipsoids(): p[2] = x**2 + y**2, [40], [40], 'color=zfade' p[3] = -x**2 - y**2, [40], [40], 'color=zfade' @example_wrapper def saddle_colored_by_derivative(): f = x**2 - y**2 p[1] = f, 'style=solid' p[1].color = abs(f.diff(x)), abs(f.diff(x) + f.diff(y)), abs(f.diff(y)) @example_wrapper def ding_dong_surface(): f = sqrt(1.0 - y)*y p[1] = f, [x, 0, 2*pi, 40], [y, - 1, 4, 100], 'mode=cylindrical; style=solid; color=zfade4' @example_wrapper def polar_circle(): p[7] = 1, 'mode=polar' @example_wrapper def polar_flower(): p[8] = 1.5*sin(4*x), [160], 'mode=polar' p[8].color = z, x, y, (0.5, 0.5, 0.5), ( 0.8, 0.8, 0.8), (x, y, None, z) # z is used for t @example_wrapper def simple_cylinder(): p[9] = 1, 'mode=cylindrical' @example_wrapper def cylindrical_hyperbola(): # (note that polar is an alias for cylindrical) p[10] = 1/y, 'mode=polar', [x], [y, -2, 2, 20] @example_wrapper def extruded_hyperbolas(): p[11] = 1/x, [x, -10, 10, 100], [1], 'style=solid' p[12] = -1/x, [x, -10, 10, 100], [1], 'style=solid' @example_wrapper def torus(): a, b = 1, 0.5 # radius, thickness p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x)) *\ sin(y), b*sin(x), [x, 0, pi*2, 40], [y, 0, pi*2, 40] @example_wrapper def warped_torus(): a, b = 2, 1 # radius, thickness p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x))*sin(y), b *\ sin(x) + 0.5*sin(4*y), [x, 0, pi*2, 40], [y, 0, pi*2, 40] @example_wrapper def parametric_spiral(): p[14] = cos(y), sin(y), y / 10.0, [y, -4*pi, 4*pi, 100] p[14].color = x, (0.1, 0.9), y, (0.1, 0.9), z, (0.1, 0.9) @example_wrapper def multistep_gradient(): p[1] = 1, 'mode=spherical', 'style=both' # p[1] = exp(-x**2-y**2+(x*y)/4), [-1.7,1.7,100], [-1.7,1.7,100], 'style=solid' # p[1] = 5*x*y*exp(-x**2-y**2), [-2,2,100], [-2,2,100] gradient = [0.0, (0.3, 0.3, 1.0), 0.30, (0.3, 1.0, 0.3), 0.55, (0.95, 1.0, 0.2), 0.65, (1.0, 0.95, 0.2), 0.85, (1.0, 0.7, 0.2), 1.0, (1.0, 0.3, 0.2)] p[1].color = z, [None, None, z], gradient # p[1].color = 'zfade' # p[1].color = 'zfade3' @example_wrapper def lambda_vs_sympy_evaluation(): start = clock() p[4] = x**2 + y**2, [100], [100], 'style=solid' p.wait_for_calculations() print("lambda-based calculation took %s seconds." % (clock() - start)) start = clock() p[4] = x**2 + y**2, [100], [100], 'style=solid; use_sympy_eval' p.wait_for_calculations() print( "sympy substitution-based calculation took %s seconds." % (clock() - start)) @example_wrapper def gradient_vectors(): def gradient_vectors_inner(f, i): from sympy import lambdify from sympy.plotting.plot_interval import PlotInterval from pyglet.gl import glBegin, glColor3f from pyglet.gl import glVertex3f, glEnd, GL_LINES def draw_gradient_vectors(f, iu, iv): """ Create a function which draws vectors representing the gradient of f. """ dx, dy, dz = f.diff(x), f.diff(y), 0 FF = lambdify([x, y], [x, y, f]) FG = lambdify([x, y], [dx, dy, dz]) iu.v_steps /= 5 iv.v_steps /= 5 Gvl = list(list([FF(u, v), FG(u, v)] for v in iv.frange()) for u in iu.frange()) def draw_arrow(p1, p2): """ Draw a single vector. """ glColor3f(0.4, 0.4, 0.9) glVertex3f(*p1) glColor3f(0.9, 0.4, 0.4) glVertex3f(*p2) def draw(): """ Iterate through the calculated vectors and draw them. """ glBegin(GL_LINES) for u in Gvl: for v in u: point = [[v[0][0], v[0][1], v[0][2]], [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]]] draw_arrow(point[0], point[1]) glEnd() return draw p[i] = f, [-0.5, 0.5, 25], [-0.5, 0.5, 25], 'style=solid' iu = PlotInterval(p[i].intervals[0]) iv = PlotInterval(p[i].intervals[1]) p[i].postdraw.append(draw_gradient_vectors(f, iu, iv)) gradient_vectors_inner(x**2 + y**2, 1) gradient_vectors_inner(-x**2 - y**2, 2) def help_str(): s = ("\nPlot p has been created. Useful commands: \n" " help(p), p[1] = x**2, print p, p.clear() \n\n" "Available examples (see source in plotting.py):\n\n") for i in range(len(examples)): s += "(%i) %s\n" % (i, examples[i].__name__) s += "\n" s += "e.g. >>> example(2)\n" s += " >>> ding_dong_surface()\n" return s def example(i): if callable(i): p.clear() i() elif i >= 0 and i < len(examples): p.clear() examples[i]() else: print("Not a valid example.\n") print(p) example(0) # 0 - 15 are defined above print(help_str())
negative_train_query0_00070
examples/advanced/pyglet_plotting.py/example_wrapper def example_wrapper(f): examples.append(f) return f
negative_train_query0_00071
examples/advanced/pyglet_plotting.py/mirrored_saddles def mirrored_saddles(): p[5] = x**2 - y**2, [20], [20] p[6] = y**2 - x**2, [20], [20]
negative_train_query0_00072
examples/advanced/pyglet_plotting.py/mirrored_saddles_saveimage def mirrored_saddles_saveimage(): p[5] = x**2 - y**2, [20], [20] p[6] = y**2 - x**2, [20], [20] p.wait_for_calculations() # although the calculation is complete, # we still need to wait for it to be # rendered, so we'll sleep to be sure. sleep(1) p.saveimage("plot_example.png")
negative_train_query0_00073
examples/advanced/pyglet_plotting.py/mirrored_ellipsoids def mirrored_ellipsoids(): p[2] = x**2 + y**2, [40], [40], 'color=zfade' p[3] = -x**2 - y**2, [40], [40], 'color=zfade'
negative_train_query0_00074
examples/advanced/pyglet_plotting.py/saddle_colored_by_derivative def saddle_colored_by_derivative(): f = x**2 - y**2 p[1] = f, 'style=solid' p[1].color = abs(f.diff(x)), abs(f.diff(x) + f.diff(y)), abs(f.diff(y))
negative_train_query0_00075
examples/advanced/pyglet_plotting.py/ding_dong_surface def ding_dong_surface(): f = sqrt(1.0 - y)*y p[1] = f, [x, 0, 2*pi, 40], [y, - 1, 4, 100], 'mode=cylindrical; style=solid; color=zfade4'
negative_train_query0_00076
examples/advanced/pyglet_plotting.py/polar_circle def polar_circle(): p[7] = 1, 'mode=polar'
negative_train_query0_00077
examples/advanced/pyglet_plotting.py/polar_flower def polar_flower(): p[8] = 1.5*sin(4*x), [160], 'mode=polar' p[8].color = z, x, y, (0.5, 0.5, 0.5), ( 0.8, 0.8, 0.8), (x, y, None, z) # z is used for t
negative_train_query0_00078
examples/advanced/pyglet_plotting.py/simple_cylinder def simple_cylinder(): p[9] = 1, 'mode=cylindrical'
negative_train_query0_00079
examples/advanced/pyglet_plotting.py/cylindrical_hyperbola def cylindrical_hyperbola(): # (note that polar is an alias for cylindrical) p[10] = 1/y, 'mode=polar', [x], [y, -2, 2, 20]
negative_train_query0_00080
examples/advanced/pyglet_plotting.py/extruded_hyperbolas def extruded_hyperbolas(): p[11] = 1/x, [x, -10, 10, 100], [1], 'style=solid' p[12] = -1/x, [x, -10, 10, 100], [1], 'style=solid'
negative_train_query0_00081
examples/advanced/pyglet_plotting.py/torus def torus(): a, b = 1, 0.5 # radius, thickness p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x)) *\ sin(y), b*sin(x), [x, 0, pi*2, 40], [y, 0, pi*2, 40]
negative_train_query0_00082
examples/advanced/pyglet_plotting.py/warped_torus def warped_torus(): a, b = 2, 1 # radius, thickness p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x))*sin(y), b *\ sin(x) + 0.5*sin(4*y), [x, 0, pi*2, 40], [y, 0, pi*2, 40]
negative_train_query0_00083
examples/advanced/pyglet_plotting.py/parametric_spiral def parametric_spiral(): p[14] = cos(y), sin(y), y / 10.0, [y, -4*pi, 4*pi, 100] p[14].color = x, (0.1, 0.9), y, (0.1, 0.9), z, (0.1, 0.9)
negative_train_query0_00084
examples/advanced/pyglet_plotting.py/multistep_gradient def multistep_gradient(): p[1] = 1, 'mode=spherical', 'style=both' # p[1] = exp(-x**2-y**2+(x*y)/4), [-1.7,1.7,100], [-1.7,1.7,100], 'style=solid' # p[1] = 5*x*y*exp(-x**2-y**2), [-2,2,100], [-2,2,100] gradient = [0.0, (0.3, 0.3, 1.0), 0.30, (0.3, 1.0, 0.3), 0.55, (0.95, 1.0, 0.2), 0.65, (1.0, 0.95, 0.2), 0.85, (1.0, 0.7, 0.2), 1.0, (1.0, 0.3, 0.2)] p[1].color = z, [None, None, z], gradient
negative_train_query0_00085
examples/advanced/pyglet_plotting.py/lambda_vs_sympy_evaluation def lambda_vs_sympy_evaluation(): start = clock() p[4] = x**2 + y**2, [100], [100], 'style=solid' p.wait_for_calculations() print("lambda-based calculation took %s seconds." % (clock() - start)) start = clock() p[4] = x**2 + y**2, [100], [100], 'style=solid; use_sympy_eval' p.wait_for_calculations() print( "sympy substitution-based calculation took %s seconds." % (clock() - start))
negative_train_query0_00086
examples/advanced/pyglet_plotting.py/gradient_vectors def gradient_vectors(): def gradient_vectors_inner(f, i): from sympy import lambdify from sympy.plotting.plot_interval import PlotInterval from pyglet.gl import glBegin, glColor3f from pyglet.gl import glVertex3f, glEnd, GL_LINES def draw_gradient_vectors(f, iu, iv): """ Create a function which draws vectors representing the gradient of f. """ dx, dy, dz = f.diff(x), f.diff(y), 0 FF = lambdify([x, y], [x, y, f]) FG = lambdify([x, y], [dx, dy, dz]) iu.v_steps /= 5 iv.v_steps /= 5 Gvl = list(list([FF(u, v), FG(u, v)] for v in iv.frange()) for u in iu.frange()) def draw_arrow(p1, p2): """ Draw a single vector. """ glColor3f(0.4, 0.4, 0.9) glVertex3f(*p1) glColor3f(0.9, 0.4, 0.4) glVertex3f(*p2) def draw(): """ Iterate through the calculated vectors and draw them. """ glBegin(GL_LINES) for u in Gvl: for v in u: point = [[v[0][0], v[0][1], v[0][2]], [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]]] draw_arrow(point[0], point[1]) glEnd() return draw p[i] = f, [-0.5, 0.5, 25], [-0.5, 0.5, 25], 'style=solid' iu = PlotInterval(p[i].intervals[0]) iv = PlotInterval(p[i].intervals[1]) p[i].postdraw.append(draw_gradient_vectors(f, iu, iv)) gradient_vectors_inner(x**2 + y**2, 1) gradient_vectors_inner(-x**2 - y**2, 2)
negative_train_query0_00087
examples/advanced/pyglet_plotting.py/help_str def help_str(): s = ("\nPlot p has been created. Useful commands: \n" " help(p), p[1] = x**2, print p, p.clear() \n\n" "Available examples (see source in plotting.py):\n\n") for i in range(len(examples)): s += "(%i) %s\n" % (i, examples[i].__name__) s += "\n" s += "e.g. >>> example(2)\n" s += " >>> ding_dong_surface()\n" return s
negative_train_query0_00088
examples/advanced/pyglet_plotting.py/example def example(i): if callable(i): p.clear() i() elif i >= 0 and i < len(examples): p.clear() examples[i]() else: print("Not a valid example.\n") print(p)
negative_train_query0_00089
examples/advanced/pyglet_plotting.py/gradient_vectors_inner def gradient_vectors_inner(f, i): from sympy import lambdify from sympy.plotting.plot_interval import PlotInterval from pyglet.gl import glBegin, glColor3f from pyglet.gl import glVertex3f, glEnd, GL_LINES def draw_gradient_vectors(f, iu, iv): """ Create a function which draws vectors representing the gradient of f. """ dx, dy, dz = f.diff(x), f.diff(y), 0 FF = lambdify([x, y], [x, y, f]) FG = lambdify([x, y], [dx, dy, dz]) iu.v_steps /= 5 iv.v_steps /= 5 Gvl = list(list([FF(u, v), FG(u, v)] for v in iv.frange()) for u in iu.frange()) def draw_arrow(p1, p2): """ Draw a single vector. """ glColor3f(0.4, 0.4, 0.9) glVertex3f(*p1) glColor3f(0.9, 0.4, 0.4) glVertex3f(*p2) def draw(): """ Iterate through the calculated vectors and draw them. """ glBegin(GL_LINES) for u in Gvl: for v in u: point = [[v[0][0], v[0][1], v[0][2]], [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]]] draw_arrow(point[0], point[1]) glEnd() return draw p[i] = f, [-0.5, 0.5, 25], [-0.5, 0.5, 25], 'style=solid' iu = PlotInterval(p[i].intervals[0]) iv = PlotInterval(p[i].intervals[1]) p[i].postdraw.append(draw_gradient_vectors(f, iu, iv))
negative_train_query0_00090
examples/advanced/pyglet_plotting.py/draw_gradient_vectors def draw_gradient_vectors(f, iu, iv): """ Create a function which draws vectors representing the gradient of f. """ dx, dy, dz = f.diff(x), f.diff(y), 0 FF = lambdify([x, y], [x, y, f]) FG = lambdify([x, y], [dx, dy, dz]) iu.v_steps /= 5 iv.v_steps /= 5 Gvl = list(list([FF(u, v), FG(u, v)] for v in iv.frange()) for u in iu.frange()) def draw_arrow(p1, p2): """ Draw a single vector. """ glColor3f(0.4, 0.4, 0.9) glVertex3f(*p1) glColor3f(0.9, 0.4, 0.4) glVertex3f(*p2) def draw(): """ Iterate through the calculated vectors and draw them. """ glBegin(GL_LINES) for u in Gvl: for v in u: point = [[v[0][0], v[0][1], v[0][2]], [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]]] draw_arrow(point[0], point[1]) glEnd() return draw
negative_train_query0_00091
examples/advanced/pyglet_plotting.py/draw_arrow def draw_arrow(p1, p2): """ Draw a single vector. """ glColor3f(0.4, 0.4, 0.9) glVertex3f(*p1) glColor3f(0.9, 0.4, 0.4) glVertex3f(*p2)
negative_train_query0_00092
examples/advanced/pyglet_plotting.py/draw def draw(): """ Iterate through the calculated vectors and draw them. """ glBegin(GL_LINES) for u in Gvl: for v in u: point = [[v[0][0], v[0][1], v[0][2]], [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]]] draw_arrow(point[0], point[1]) glEnd()
negative_train_query0_00093
examples/advanced/relativity.py/grad def grad(f, X): a = [] for x in X: a.append(f.diff(x)) return a
negative_train_query0_00094
examples/advanced/relativity.py/d def d(m, x): return grad(m[0, 0], x)
negative_train_query0_00095
examples/advanced/relativity.py/curvature def curvature(Rmn): return Rmn.ud(0, 0) + Rmn.ud(1, 1) + Rmn.ud(2, 2) + Rmn.ud(3, 3)
negative_train_query0_00096
examples/advanced/relativity.py/pprint_Gamma_udd def pprint_Gamma_udd(i, k, l): pprint(Eq(Symbol('Gamma^%i_%i%i' % (i, k, l)), Gamma.udd(i, k, l)))
negative_train_query0_00097
examples/advanced/relativity.py/pprint_Rmn_dd def pprint_Rmn_dd(i, j): pprint(Eq(Symbol('R_%i%i' % (i, j)), Rmn.dd(i, j)))
negative_train_query0_00098
End of preview. Expand in Data Studio

SWEbenchLiteRR

An MTEB dataset
Massive Text Embedding Benchmark

Software Issue Localization.

Task category t2t
Domains Programming, Written
Reference https://www.swebench.com/

Source datasets:

How to evaluate on this task

You can evaluate an embedding model on this dataset using the following code:

import mteb

task = mteb.get_task("SWEbenchLiteRR")
evaluator = mteb.MTEB([task])

model = mteb.get_model(YOUR_MODEL)
evaluator.run(model)

To learn more about how to run models on mteb task check out the GitHub repository.

Citation

If you use this dataset, please cite the dataset as well as mteb, as this dataset likely includes additional processing as a part of the MMTEB Contribution.


@misc{jimenez2024swebenchlanguagemodelsresolve,
  archiveprefix = {arXiv},
  author = {Carlos E. Jimenez and John Yang and Alexander Wettig and Shunyu Yao and Kexin Pei and Ofir Press and Karthik Narasimhan},
  eprint = {2310.06770},
  primaryclass = {cs.CL},
  title = {SWE-bench: Can Language Models Resolve Real-World GitHub Issues?},
  url = {https://arxiv.org/abs/2310.06770},
  year = {2024},
}


@article{enevoldsen2025mmtebmassivemultilingualtext,
  title={MMTEB: Massive Multilingual Text Embedding Benchmark},
  author={Kenneth Enevoldsen and Isaac Chung and Imene Kerboua and Márton Kardos and Ashwin Mathur and David Stap and Jay Gala and Wissam Siblini and Dominik Krzemiński and Genta Indra Winata and Saba Sturua and Saiteja Utpala and Mathieu Ciancone and Marion Schaeffer and Gabriel Sequeira and Diganta Misra and Shreeya Dhakal and Jonathan Rystrøm and Roman Solomatin and Ömer Çağatan and Akash Kundu and Martin Bernstorff and Shitao Xiao and Akshita Sukhlecha and Bhavish Pahwa and Rafał Poświata and Kranthi Kiran GV and Shawon Ashraf and Daniel Auras and Björn Plüster and Jan Philipp Harries and Loïc Magne and Isabelle Mohr and Mariya Hendriksen and Dawei Zhu and Hippolyte Gisserot-Boukhlef and Tom Aarsen and Jan Kostkan and Konrad Wojtasik and Taemin Lee and Marek Šuppa and Crystina Zhang and Roberta Rocca and Mohammed Hamdy and Andrianos Michail and John Yang and Manuel Faysse and Aleksei Vatolin and Nandan Thakur and Manan Dey and Dipam Vasani and Pranjal Chitale and Simone Tedeschi and Nguyen Tai and Artem Snegirev and Michael Günther and Mengzhou Xia and Weijia Shi and Xing Han Lù and Jordan Clive and Gayatri Krishnakumar and Anna Maksimova and Silvan Wehrli and Maria Tikhonova and Henil Panchal and Aleksandr Abramov and Malte Ostendorff and Zheng Liu and Simon Clematide and Lester James Miranda and Alena Fenogenova and Guangyu Song and Ruqiya Bin Safi and Wen-Ding Li and Alessia Borghini and Federico Cassano and Hongjin Su and Jimmy Lin and Howard Yen and Lasse Hansen and Sara Hooker and Chenghao Xiao and Vaibhav Adlakha and Orion Weller and Siva Reddy and Niklas Muennighoff},
  publisher = {arXiv},
  journal={arXiv preprint arXiv:2502.13595},
  year={2025},
  url={https://arxiv.org/abs/2502.13595},
  doi = {10.48550/arXiv.2502.13595},
}

@article{muennighoff2022mteb,
  author = {Muennighoff, Niklas and Tazi, Nouamane and Magne, Loïc and Reimers, Nils},
  title = {MTEB: Massive Text Embedding Benchmark},
  publisher = {arXiv},
  journal={arXiv preprint arXiv:2210.07316},
  year = {2022}
  url = {https://arxiv.org/abs/2210.07316},
  doi = {10.48550/ARXIV.2210.07316},
}

Dataset Statistics

Dataset Statistics

The following code contains the descriptive statistics from the task. These can also be obtained using:

import mteb

task = mteb.get_task("SWEbenchLiteRR")

desc_stats = task.metadata.descriptive_stats
{}

This dataset card was automatically generated using MTEB

Downloads last month
18