Skip to content

Commit

Permalink
modernise demos and make them Py2/3 compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
scoder committed Jul 26, 2015
1 parent 9b925e0 commit 6dd6325
Show file tree
Hide file tree
Showing 15 changed files with 82 additions and 39 deletions.
7 changes: 5 additions & 2 deletions Demos/embed/assert_equal.py
@@ -1,12 +1,15 @@
from __future__ import absolute_import, print_function

import sys

f1 = open(sys.argv[1])
f2 = open(sys.argv[2])
try:
if f1.read() != f2.read():
print ("Files differ")
print("Files differ")
sys.exit(1)
else:
print ("Files identical")
print("Files identical")
finally:
f1.close()
f2.close()
7 changes: 4 additions & 3 deletions Demos/embed/embedded.pyx
@@ -1,7 +1,8 @@
# cython: language_level=3

print __name__
print(__name__)

if __name__ == "__main__":
print "Hi, I'm embedded."
print("Hi, I'm embedded.")
else:
print "I'm being imported."
print("I'm being imported.")
12 changes: 9 additions & 3 deletions Demos/freeze/combinatorics.pyx
@@ -1,14 +1,20 @@
# cython: language_level=3

import lcmath


def nCr(n, r):
"""Return the number of ways to choose r elements of a set of n."""
return lcmath.exp( lcmath.lfactorial(n) - lcmath.lfactorial(r)
- lcmath.lfactorial(n-r) )
return lcmath.exp(
lcmath.lfactorial(n) -
lcmath.lfactorial(r) -
lcmath.lfactorial(n-r)
)

if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
sys.stderr.write("USAGE: %s n r\nPrints n-choose-r.\n" % sys.argv[0])
sys.exit(2)
n, r = map(float, sys.argv[1:])
print nCr(n, r)
print(nCr(n, r))
7 changes: 6 additions & 1 deletion Demos/freeze/lcmath.pyx
@@ -1,15 +1,20 @@
# cython: language_level=3

cdef extern from "math.h":
double c_lgamma "lgamma" (double)
double c_exp "exp" (double)


def exp(n):
"""Return e**n."""
return c_exp(n)


def lfactorial(n):
"""Return an estimate of the log factorial of n."""
return c_lgamma(n+1)


def factorial(n):
"""Return an estimate of the factorial of n."""
return c_exp( c_lgamma(n+1) )
Expand All @@ -21,4 +26,4 @@ if __name__ == "__main__":
sys.stderr.write("USAGE: %s n\nPrints n!.\n" % sys.argv[0])
sys.exit(2)
n, = map(float, sys.argv[1:])
print factorial(n)
print(factorial(n))
3 changes: 3 additions & 0 deletions Demos/integrate1.pyx
@@ -1,6 +1,9 @@
# cython: language_level=3

def f(x):
return x**2-x


def integrate_f(a, b, N):
s = 0.0
dx = (b-a)/N
Expand Down
3 changes: 3 additions & 0 deletions Demos/integrate2.pyx
@@ -1,6 +1,9 @@
# cython: language_level=3

cdef double f(double x) except? -2:
return x**2-x


def integrate_f(double a, double b, int N):
cdef int i
s = 0.0
Expand Down
8 changes: 5 additions & 3 deletions Demos/integrate_timing.py
@@ -1,13 +1,15 @@
from __future__ import absolute_import, print_function

import timeit

import integrate0, integrate1, integrate2

number = 10
py_time = None
for m in ('integrate0', 'integrate1', 'integrate2'):
print m
print(m)
t = min(timeit.repeat("integrate_f(0.0, 10.0, 10000000)", "from %s import integrate_f" % m, number=number))
if py_time is None:
py_time = t
print " ", t / number, "s"
print " ", py_time / t
print(" ", t / number, "s")
print(" ", py_time / t)
4 changes: 3 additions & 1 deletion Demos/libraries/setup.py
@@ -1,3 +1,5 @@
from __future__ import absolute_import, print_function

import os
import sys

Expand All @@ -8,7 +10,7 @@

# For demo purposes, we build our own tiny library.
try:
print "building libmymath.a"
print("building libmymath.a")
assert os.system("gcc -shared -fPIC -c mymath.c -o mymath.o") == 0
assert os.system("ar rcs libmymath.a mymath.o") == 0
except:
Expand Down
6 changes: 3 additions & 3 deletions Demos/numpy_demo.pyx
@@ -1,7 +1,7 @@
cimport numpy
import numpy
cimport numpy as cnp

def sum_of_squares(numpy.ndarray[double, ndim=1] arr):

def sum_of_squares(cnp.ndarray[double, ndim=1] arr):
cdef long N = arr.shape[0]
cdef double ss = 0
for i in range(N):
Expand Down
16 changes: 10 additions & 6 deletions Demos/overflow_perf.pyx
@@ -1,6 +1,7 @@
# cython: language_level=3
# distutils: extra_compile_args = -O3

import cython
cimport cython

ctypedef fused INT:
int
Expand All @@ -15,6 +16,7 @@ ctypedef fused C_INT:
unsigned int
unsigned long long


@cython.overflowcheck(False)
def fib(INT n):
"""
Expand Down Expand Up @@ -54,12 +56,13 @@ def collatz(INT n):
cdef INT k = 0
while n != 1:
if n % 2 == 0:
n /= 2
n //= 2
else:
n = 3*n + 1
k += 1
return int(k)


@cython.overflowcheck(True)
@cython.overflowcheck.fold(False)
def collatz_overflow(INT n):
Expand All @@ -74,12 +77,13 @@ def collatz_overflow(INT n):
cdef INT k = 0
while n != 1:
if n % 2 == 0:
n /= 2
n //= 2
else:
n = 3*n + 1
k += 1
return int(k)


@cython.overflowcheck(True)
@cython.overflowcheck.fold(True)
def collatz_overflow_fold(INT n):
Expand All @@ -94,14 +98,13 @@ def collatz_overflow_fold(INT n):
cdef INT k = 0
while n != 1:
if n % 2 == 0:
n /= 2
n //= 2
else:
n = 3*n + 1
k += 1
return int(k)



@cython.overflowcheck(False)
def factorial(INT n):
"""
Expand Down Expand Up @@ -129,7 +132,6 @@ def factorial_overflow(INT n):
return int(res)



@cython.overflowcheck(False)
def most_orthogonal(C_INT[:,::1] vectors):
cdef C_INT n = vectors.shape[0]
Expand All @@ -148,6 +150,7 @@ def most_orthogonal(C_INT[:,::1] vectors):
min_pair = i, j
return vectors[i], vectors[j]


@cython.overflowcheck(True)
@cython.overflowcheck.fold(False)
def most_orthogonal_overflow(C_INT[:,::1] vectors):
Expand All @@ -167,6 +170,7 @@ def most_orthogonal_overflow(C_INT[:,::1] vectors):
min_pair = i, j
return vectors[i], vectors[j]


@cython.overflowcheck(True)
@cython.overflowcheck.fold(True)
def most_orthogonal_overflow_fold(C_INT[:,::1] vectors):
Expand Down
18 changes: 11 additions & 7 deletions Demos/overflow_perf_run.py
@@ -1,3 +1,5 @@
from __future__ import absolute_import, print_function

from overflow_perf import *

import sys
Expand All @@ -11,7 +13,7 @@
def run_tests(N):
global f
for func in most_orthogonal, fib, collatz, factorial:
print func.__name__
print(func.__name__)
for type in ['int', 'unsigned int', 'long long', 'unsigned long long', 'object']:
if func == most_orthogonal:
if type == 'object' or np == None:
Expand All @@ -23,15 +25,16 @@ def run_tests(N):
else:
arg = N
try:
print "%s[%s](%s)" % (func.__name__, type, N)
print("%s[%s](%s)" % (func.__name__, type, N))
with_overflow = my_timeit(globals()[func.__name__ + "_overflow"][type], arg)
no_overflow = my_timeit(func[type], arg)
print "\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow)
print("\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow))
if func.__name__ + "_overflow_fold" in globals():
with_overflow = my_timeit(globals()[func.__name__ + "_overflow_fold"][type], arg)
print "\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow), "(folded)"
print("\t%0.04e\t%0.04e\t%0.04f (folded)" % (
no_overflow, with_overflow, with_overflow / no_overflow))
except OverflowError:
print " ", "Overflow"
print(" ", "Overflow")

def my_timeit(func, N):
global f, arg
Expand All @@ -44,10 +47,11 @@ def my_timeit(func, N):
break
return res / times


params = sys.argv[1:]
if not params:
params = [129, 9, 97]
for arg in params:
print
print "N", arg
print()
print("N", arg)
run_tests(int(arg))
12 changes: 7 additions & 5 deletions Demos/primes.pyx
@@ -1,4 +1,6 @@
print "starting"
# cython: language_level=3

print("starting")

def primes(int kmax):
# cdef int n, k, i
Expand All @@ -10,11 +12,11 @@ def primes(int kmax):
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
while i < k and n % p[i] != 0:
i += 1
if i == k:
p[k] = n
k = k + 1
k += 1
result.append(n)
n = n + 1
n += 1
return result
6 changes: 5 additions & 1 deletion Demos/run_primes.py
@@ -1,7 +1,11 @@
from __future__ import absolute_import, print_function

import sys
from primes import primes

if len(sys.argv) >= 2:
n = int(sys.argv[1])
else:
n = 1000
print primes(n)

print(primes(n))
6 changes: 4 additions & 2 deletions Demos/run_spam.py
@@ -1,8 +1,10 @@
from __future__ import absolute_import, print_function

from spam import Spam

s = Spam()
print "Created:", s
print("Created:", s)
s.set_amount(42)
print "Amount =", s.get_amount()
print("Amount =", s.get_amount())
s.describe()
s = None
6 changes: 4 additions & 2 deletions Demos/spam.pyx
@@ -1,3 +1,5 @@
# cython: language_level=3

#
# Example of an extension type.
#
Expand All @@ -9,7 +11,7 @@ cdef class Spam:
self.amount = 0

def __dealloc__(self):
print self.amount, "tons of spam is history."
print(self.amount, "tons of spam is history.")

def get_amount(self):
return self.amount
Expand All @@ -18,4 +20,4 @@ cdef class Spam:
self.amount = new_amount

def describe(self):
print self.amount, "tons of spam!"
print(self.amount, "tons of spam!")

0 comments on commit 6dd6325

Please sign in to comment.