I am trying to learn Cython at the moment and have followed a tutorial here.
I have it working within Ubuntu (on vmware) but right now I am trying to get it working on windows (using VSCode). I took all the files that I had created in Ubuntu and put them on my machine.
When I try to run my python file testing.py I receive this error:
Exception has occurred: ModuleNotFoundError
No module named 'example_cy'
here is the code for the testing.py
import timeit
cy = timeit.timeit('example_cy.test(5000)', setup = 'import example_cy', number = 1000)
py = timeit.timeit('example_py.test(5000)', setup = 'import example_py', number = 1000)
print(cy, py)
print('Cython is {}x faster'.format(py/cy))
This is the example_cy.pyx file
cpdef int test(int x):
cdef int y = 0
cdef int i
for i in range(x):
y += i
return y
The example_py.py file
def test(x):
y = 0
for i in range(x):
y += i
return y
and the setup.py code
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('example_cy.pyx'))
Related
I'm making a calculator app. I am using Java and Jython. I wanted to use the SymPy module but after calling the code below I get an error that there is no such module. Any advice?
try (PythonInterpreter interpreter = new PythonInterpreter()) {
interpreter.exec("""
from sympy import cos, sin, pi
def f(x):
\treturn\040""" + wartoscCalki.getText() +
"""
\ndef simpson(a, b, n):
\tx1=0.0
\tx2=0.0
\tx0=f(a)+f(b)
\th=(b-a)/n
\twynik=0.0
\tfor i in range(1,n):
\t\tx=(a+(i*h))
\t\tif i%2==0:
\t\t\tx2+=f(x)
\t\telse:
\t\t\tx1+=f(x)
\twynik=h*(x0+2*x2+4*x1)/3
\treturn wynik
c=float(simpson(""" + granicaDolna.getText() + """
,""" + granicaGorna.getText() + """
,""" + liczbaPodprzedzialow.getText() + """
))"""
);
}
Caused by: Traceback (most recent call last):
File "", line 2, in module
ImportError: No module named sympy
sympy is not a jython module. What you need is this:
from Java.lang import Math
Once imported, you can use Math.sin(), Math.cos(), and Math.PI to perform the above listed calculations.
A complete list of Java.lang.Math methods can be found here:
Oracle Documentation
I know this might seem like a duplicated question, but I really could not find what I'm doing wrong... I wrote a .pyx file in order to compile it into a .pyd with cython. Long story short, it compiles my file just fine and creates a .pyd file. However, when I try to import that .pyd file I get an error saying No module named: "name_of_module". Note that this is my first time trying cython...
I am using venv with python3.9 on windows 10. I have cython installed along with minGW. To compile it into the .pyd file, I imply type in the command prompt in the same directory as the .pyx file:
python setup.py build_ext --inplace
Here is my setup.py file to cythonize my .pyx file:
from setuptools import setup, Extension
from Cython.Build import cythonize
extensions = [Extension('negamax_cy', ['negamax_cy.pyx'])]
setup(ext_modules=cythonize(extensions, language_level=3))
This is my .pyx file:
from connect4.constants import COLS, ROWS
from .position import Position
cdef int COLUMN_ORDER[7]
cdef int x
for x in range(COLS):
COLUMN_ORDER.append(COLS // 2 + (1 - 2 * (x % 2)) * (1 + x) // 2)
cpdef int negamax(pos, int depth, int alpha, int beta):
if pos.can_win(): # Check if current player can win this move
return 1000 - pos.moves*2
cdef long next_move = pos.possible_non_loosing_moves()
if next_move == 0: # Check for moves which are not losing moves
return -1000 + pos.moves # If we have 2 or more forcing moves we lose
if depth == 0: # Check if we have reached max depth
return 0
if pos.moves == ROWS * COLS: # Check for a draw game
return 0
cdef int col = 0
for col in COLUMN_ORDER[col]:
if next_move & Position.column_mask(col):
pos_cp = Position(position=pos)
pos_cp.play_col(col)
score = -negamax(pos_cp, depth - 1, -beta, -alpha)
if score >= beta:
return score
alpha = max(alpha, score)
return alpha
My project structure is as follow (I am trying to do a connect4 game with an A.I. in pygame):
connect4
/venv
/ai
__init__.py
setup.py
file_where_pyd_is_imported.py
negamax_cy.pyx
negamax_cy.pyd
negamax_cy.c
/connect4
__init__.py
other_files.py
__init__.py
main.py
Note that main.py imports file_where_pyd_is_imported.py
When I import I simply type:
import negamax_cy
this is the error I get:
Traceback (most recent call last):
File "D:\Users\dalla\Documents\Coding Projects\python\games\connect4\main.py", line 5, in <module>
from ai.negamax import mp_best_move, best_move, print_avg
File "D:\Users\dalla\Documents\Coding Projects\python\games\connect4\ai\negamax.py", line 7, in <module>
import negamax_cy
ModuleNotFoundError: No module named 'negamax_cy'
As I said I don't know what is wrong. Maybe it has to do with my project structure or something, or my setup.py file, but I am unsure... If anyone has an idea let me know.
Well turns out I'm really stupid and in python3 I have to upload like this:
from . import negamax_cy
Sorry for wasting anyone's time...
I have a function defined in a different file nhpp_next_arrival.py, which contains a function. The important thing to notice is that I am using numpy package.
def nhpp_next_arrival(t,Lambda, h_lam):
# current starting time t
# rate handle h_lam
# Lambda a majorizing function/constant
U = np.random.uniform()
V = np.random.uniform()
t = t - np.log(U)/Lambda
while V > h_lam(t)/Lambda:
t = t - np.log(U)/Lambda
U = np.random.uniform()
V = np.random.uniform()
return t
I imported this function in a different file as the following
import numpy as np
from nhpp import *
#Call nhpp_next_arrival
t_arrival = nhpp_next_arrival(t=t, Lambda=max_arrival, h_lam=h_arr_total)
Then I got the following error message.
U = np.random.uniform() NameError: name 'np' is not defined
Thank you!
You might be confused with a C #include (or something similar).
Your code is using numpy.random at nhpp_next_arrival.py, so you should have at its top
import numpy as np
Even though you imported it before the import to this file, when the interpreter sees
from nhpp import *
it doesn't import the packages into the namespace of that module.
Hi I have two python files: project.py and test.py.
I am trying to import variable from test.py to project.py.
Following is the code:
test.py
newton = 0
def apple(n):
global newton
n = newton
time.sleep(15)
n = n + 1
return
and in project.py
from test import *
class search(object):
def __init__(self):
self.servo = test.apple(n)
def run(self):
while (self.servo < 1):
print "hELLO"
When I run project.py I get NameError: Global name 'test' is not defined in project.py self.servo = test.apple(n)
Can anyone point out what is wrong in my code?
What are you expecting test to be?
from test import *
This will load everything found in test, which in this case is test.py. So that will load the following into the global namespace:
newton (with a value of 0)
apple (a function)
It does not load any symbol named test, so when you call test.apple in your __init__ method, you get a NameError.
If you want to import test.py as test, you instead need to just import the module itself, not import things from the module:
import test
I have this testing script, called test_boxplot.py:
__author__ = 'olga'
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import numpy as np
import prettyplotlib as ppl
import os
#image_comparison(baseline_images=['boxplot'], extensions=['png'])
def test_boxplot():
# Set the random seed for consistency
np.random.seed(10)
data = np.random.randn(8, 4)
labels = ['A', 'B', 'C', 'D']
fig, ax = plt.subplots()
ppl.boxplot(ax, data, xticklabels=labels)
# fig.savefig('%s/baseline_images/test_boxplot/boxplot.png' %
# os.path.dirname(__file__))
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'])
and if I run it directly, the tests all pass:
$ python test_boxplot.py
/Users/olga/workspace-git/matplotlib/lib/matplotlib/testing/decorators.py:288: UserWarning: test module run as script. guessing baseline image locations
warnings.warn('test module run as script. guessing baseline image locations')
.
----------------------------------------------------------------------
Ran 1 test in 0.224s
OK
but if I run it with nosetests it fails with this weird IndexError that centers around matplotlib's #image_comparison decorator's code:
$ nosetests test_boxplot.py
E
======================================================================
ERROR: Failure: IndexError (pop from empty list)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/loader.py", line 286, in generate
for test in g():
File "/Users/olga/workspace-git/matplotlib/lib/matplotlib/testing/decorators.py", line 145, in test
baseline_dir, result_dir = _image_directories(self._func)
File "/Users/olga/workspace-git/matplotlib/lib/matplotlib/testing/decorators.py", line 296, in _image_directories
assert mods.pop(0) == 'tests'
IndexError: pop from empty list
----------------------------------------------------------------------
Ran 1 test in 0.092s
FAILED (errors=1)
Any ideas what may be going on?
I think the problem is that the decorator expects to be used in a subdirectory names "tests" of the main project dir (usually project/tests or more correctly: the module of the test must start with something.tests.). This is the code in _image_directories():
mods = module_name.split('.')
mods.pop(0) # <- will be the name of the package being tested (in
# most cases "matplotlib")
assert mods.pop(0) == 'tests'
subdir = os.path.join(*mods)
_image_directories() has some special code in case of func.__module__ == '__main__' so you don't see the error in the first case.