Why do I get error with FunctionSpace on simple example?

When I run this simple example of constructing a function space

from dolfin import *
mesh = UnitSquareMesh(8, 8)
V = FunctionSpace(mesh, "Lagrange", 1)

I get the following error

  Calling FFC just-in-time (JIT) compiler, this may take some time.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/usr/lib/python3/dist-packages/sympy/core/compatibility.py in as_int(n, strict)
    418         if strict and not isinstance(n, SYMPY_INTS + (Integer,)):
--> 419             raise TypeError
    420         result = int(n)

TypeError: 

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-2-6e0119016ad8> in <module>
      3 # Create mesh and define function space
      4 mesh = UnitSquareMesh(8, 8)
----> 5 V = FunctionSpace(mesh, "Lagrange", 1)

/usr/lib/petsc/lib/python3/dist-packages/dolfin/function/functionspace.py in __init__(self, *args, **kwargs)
     31                 self._init_from_ufl(*args, **kwargs)
     32             else:
---> 33                 self._init_convenience(*args, **kwargs)
     34 
     35     def _init_from_ufl(self, mesh, element, constrained_domain=None):

/usr/lib/petsc/lib/python3/dist-packages/dolfin/function/functionspace.py in _init_convenience(self, mesh, family, degree, form_degree, constrained_domain, restriction)
     98                                     form_degree=form_degree)
     99 
--> 100         self._init_from_ufl(mesh, element, constrained_domain=constrained_domain)
    101 
    102     def dolfin_element(self):

/usr/lib/petsc/lib/python3/dist-packages/dolfin/function/functionspace.py in _init_from_ufl(self, mesh, element, constrained_domain)
     40 
     41         # Compile dofmap and element
---> 42         ufc_element, ufc_dofmap = ffc_jit(element, form_compiler_parameters=None,
     43                                           mpi_comm=mesh.mpi_comm())
     44         ufc_element = cpp.fem.make_ufc_finite_element(ufc_element)

/usr/lib/petsc/lib/python3/dist-packages/dolfin/jit/jit.py in mpi_jit(*args, **kwargs)
     48         # Just call JIT compiler when running in serial
     49         if MPI.size(mpi_comm) == 1:
---> 50             return local_jit(*args, **kwargs)
     51 
     52         # Default status (0 == ok, 1 == fail)

/usr/lib/petsc/lib/python3/dist-packages/dolfin/jit/jit.py in ffc_jit(ufl_form, form_compiler_parameters)
     98     p.update(dict(parameters["form_compiler"]))
     99     p.update(form_compiler_parameters or {})
--> 100     return ffc.jit(ufl_form, parameters=p)
    101 
    102 

/usr/lib/python3/dist-packages/ffc/jitcompiler.py in jit(ufl_object, parameters, indirect)
    215 
    216     # Inspect cache and generate+build if necessary
--> 217     module = jit_build(ufl_object, module_name, parameters)
    218 
    219     # Raise exception on failure to build or import module

/usr/lib/python3/dist-packages/ffc/jitcompiler.py in jit_build(ufl_object, module_name, parameters)
    128 
    129     # Carry out jit compilation, calling jit_generate only if needed
--> 130     module, signature = dijitso.jit(jitable=ufl_object,
    131                                     name=module_name,
    132                                     params=params,

/usr/lib/python3/dist-packages/dijitso/jit.py in jit(jitable, name, params, generate, send, receive, wait)
    163         elif generate:
    164             # 1) Generate source code
--> 165             header, source, dependencies = generate(jitable, name, signature, params["generator"])
    166             # Ensure we got unicode from generate
    167             header = as_unicode(header)

/usr/lib/python3/dist-packages/ffc/jitcompiler.py in jit_generate(ufl_object, module_name, signature, parameters)
     63         compile_object = compile_coordinate_mapping
     64 
---> 65     code_h, code_c, dependent_ufl_objects = compile_object(ufl_object,
     66             prefix=module_name, parameters=parameters, jit=True)
     67 

/usr/lib/python3/dist-packages/ffc/compiler.py in compile_element(elements, object_names, prefix, parameters, jit)
    147                     prefix="Element", parameters=None, jit=False):
    148     """This function generates UFC code for a given UFL element or list of UFL elements."""
--> 149     return compile_ufl_objects(elements, "element", object_names,
    150                                prefix, parameters, jit)
    151 

/usr/lib/python3/dist-packages/ffc/compiler.py in compile_ufl_objects(ufl_objects, kind, object_names, prefix, parameters, jit)
    188     # Stage 2: intermediate representation
    189     cpu_time = time()
--> 190     ir = compute_ir(analysis, prefix, parameters, jit)
    191     _print_timing(2, time() - cpu_time)
    192 

/usr/lib/python3/dist-packages/ffc/representation.py in compute_ir(analysis, prefix, parameters, jit)
    165     # Compute representation of elements
    166     info("Computing representation of %d elements" % len(elements))
--> 167     ir_elements = [_compute_element_ir(e, element_numbers, classnames, parameters, jit)
    168                    for e in elements]
    169 

/usr/lib/python3/dist-packages/ffc/representation.py in <listcomp>(.0)
    165     # Compute representation of elements
    166     info("Computing representation of %d elements" % len(elements))
--> 167     ir_elements = [_compute_element_ir(e, element_numbers, classnames, parameters, jit)
    168                    for e in elements]
    169 

/usr/lib/python3/dist-packages/ffc/representation.py in _compute_element_ir(ufl_element, element_numbers, classnames, parameters, jit)
    198 
    199     # Create FIAT element
--> 200     fiat_element = create_element(ufl_element)
    201     cell = ufl_element.cell()
    202     cellname = cell.cellname()

/usr/lib/python3/dist-packages/ffc/fiatinterface.py in create_element(ufl_element)
     98     # Create regular FIAT finite element
     99     if isinstance(ufl_element, ufl.FiniteElement):
--> 100         element = _create_fiat_element(ufl_element)
    101 
    102     # Create mixed element (implemented by FFC)

/usr/lib/python3/dist-packages/ffc/fiatinterface.py in _create_fiat_element(ufl_element)
    196                 element = ElementClass(fiat_cell)
    197             else:
--> 198                 element = ElementClass(fiat_cell, degree)
    199 
    200     # Consistency check between UFL and FIAT elements.

/usr/lib/python3/dist-packages/FIAT/lagrange.py in __init__(self, ref_el, degree)
     41 
     42     def __init__(self, ref_el, degree):
---> 43         poly_set = polynomial_set.ONPolynomialSet(ref_el, degree)
     44         dual = LagrangeDualSet(ref_el, degree)
     45         formdegree = 0  # 0-form

/usr/lib/python3/dist-packages/FIAT/polynomial_set.py in __init__(self, ref_el, degree, shape)
    166             vinv = numpy.linalg.inv(v)
    167 
--> 168             dv = expansion_set.tabulate_derivatives(degree, pts)
    169             dtildes = [[[a[1][i] for a in dvrow] for dvrow in dv]
    170                        for i in range(sd)]

/usr/lib/python3/dist-packages/FIAT/expansions.py in tabulate_derivatives(self, n, pts)
    275     def tabulate_derivatives(self, n, pts):
    276         order = 1
--> 277         data = _tabulate_dpts(self._tabulate, 2, n, order, numpy.array(pts))
    278         # Put data in the required data structure, i.e.,
    279         # k-tuples which contain the value, and the k-1 derivatives

/usr/lib/python3/dist-packages/FIAT/expansions.py in _tabulate_dpts(tabulator, D, n, order, pts)
     72 
     73     # Tabulate symbolically
---> 74     symbolic_tab = tabulator(n, X)
     75     # Make sure that the entries of symbolic_tab are lists so we can
     76     # append derivatives

/usr/lib/python3/dist-packages/FIAT/expansions.py in _tabulate(self, n, pts)
    243         y = ref_pts[1]
    244 
--> 245         f1 = (1.0 + 2 * x + y) / 2.0
    246         f2 = (1.0 - y) / 2.0
    247         f3 = f2**2

/usr/lib/python3/dist-packages/sympy/core/decorators.py in __sympifyit_wrapper(a, b)
     89                 if not hasattr(b, '_op_priority'):
     90                     b = sympify(b, strict=True)
---> 91                 return func(a, b)
     92             except SympifyError:
     93                 return retval

/usr/lib/python3/dist-packages/sympy/core/decorators.py in binary_op_wrapper(self, other)
    127                     if f is not None:
    128                         return f(self)
--> 129             return func(self, other)
    130         return binary_op_wrapper
    131     return priority_decorator

/usr/lib/python3/dist-packages/sympy/core/expr.py in __rmul__(self, other)
    199     @call_highest_priority('__mul__')
    200     def __rmul__(self, other):
--> 201         return Mul(other, self)
    202 
    203     @_sympifyit('other', NotImplemented)

/usr/lib/python3/dist-packages/sympy/core/cache.py in wrapper(*args, **kwargs)
     92             def wrapper(*args, **kwargs):
     93                 try:
---> 94                     retval = cfunc(*args, **kwargs)
     95                 except TypeError:
     96                     retval = func(*args, **kwargs)

/usr/lib/python3/dist-packages/sympy/core/operations.py in __new__(cls, *args, **options)
     45             return args[0]
     46 
---> 47         c_part, nc_part, order_symbols = cls.flatten(args)
     48         is_commutative = not nc_part
     49         obj = cls._from_args(c_part + nc_part, is_commutative)

/usr/lib/python3/dist-packages/sympy/core/mul.py in flatten(cls, seq)
    205                     elif global_distribute[0] and b.is_commutative:
    206                         r, b = b.as_coeff_Add()
--> 207                         bargs = [_keep_coeff(a, bi) for bi in Add.make_args(b)]
    208                         _addsort(bargs)
    209                         ar = a*r

/usr/lib/python3/dist-packages/sympy/core/mul.py in <listcomp>(.0)
    205                     elif global_distribute[0] and b.is_commutative:
    206                         r, b = b.as_coeff_Add()
--> 207                         bargs = [_keep_coeff(a, bi) for bi in Add.make_args(b)]
    208                         _addsort(bargs)
    209                         ar = a*r

/usr/lib/python3/dist-packages/sympy/core/mul.py in _keep_coeff(coeff, factors, clear, sign)
   1895         if margs[0].is_Number:
   1896             margs[0] *= coeff
-> 1897             if margs[0] == 1:
   1898                 margs.pop(0)
   1899         else:

/usr/lib/python3/dist-packages/sympy/core/numbers.py in __eq__(self, other)
   1404             return self._mpf_ == other._mpf_
   1405         if other.is_Rational:
-> 1406             return other.__eq__(self)
   1407         if other.is_Number:
   1408             # numbers should compare at the same precision;

/usr/lib/python3/dist-packages/sympy/core/numbers.py in __eq__(self, other)
   2246         elif isinstance(other, Integer):
   2247             return (self.p == other.p)
-> 2248         return Rational.__eq__(self, other)
   2249 
   2250     def __ne__(self, other):

/usr/lib/python3/dist-packages/sympy/core/numbers.py in __eq__(self, other)
   1904                 # does m*2**t == self.p
   1905                 return self.p and not self.p % m and \
-> 1906                     integer_log(self.p//m, 2) == (t, True)
   1907             # does non-integer s*m/2**-t = p/q?
   1908             if self.is_Integer:

/usr/lib/python3/dist-packages/sympy/core/power.py in integer_log(y, x)
    145     if x in (-2, 2):
    146         x = int(x)
--> 147         y = as_int(y)
    148         e = y.bit_length() - 1
    149         return e, x**e == y

/usr/lib/python3/dist-packages/sympy/core/compatibility.py in as_int(n, strict)
    423         return result
    424     except TypeError:
--> 425         raise ValueError('%s is not an integer' % (n,))
    426 
    427 

ValueError: 1 is not an integer

I am using Ubuntu with Python 3.8.5. I installed FEniCS as instructed on the FEniCS website:

sudo apt-get install software-properties-common

sudo add-apt-repository ppa:fenics-packages/fenics

sudo apt-get update

sudo apt-get install --no-install-recommends fenics

I cannot reproduce with the following (using docker based on ubuntu 20.04):

docker run -ti --rm -v $PWD:/home/shared -w /home/shared ubuntu:20.04
apt-get update
apt-get install sudo 
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:fenics-packages/fenics
sudo apt-get update
sudo apt-get install --no-install-recommends fenics

Starting the docker container, running the commands above, I’m able to run your script without errors.
I guess it is the version on sympy on your system that is old (ref: Strange behavior of: as_int TypeError · Issue #20615 · sympy/sympy · GitHub). Could you check your sympy version?
Running:

python3 -c "import sympy ; print(sympy.__version__)"

yields

1.5.1

for me

Thanks for your reply. I also get 1.5.1

Are you using ubuntu 20.04?

Yes, it says Ubuntu 20.04.1 LTS

Thats really strange then. Could you Give me the result of pip3 list?

   Package                Version             
---------------------- --------------------
alabaster              0.7.8               
appdirs                1.4.3               
apptools               4.5.0               
apturl                 0.5.2               
asn1crypto             0.24.0              
astroid                2.3.3               
atomicwrites           1.1.5               
attrs                  19.3.0              
autobahn               17.10.1             
autokey                0.95.10             
Automat                0.8.0               
Babel                  2.6.0               
backcall               0.1.0               
basemap                1.2.1               
bcrypt                 3.1.7               
bleach                 3.1.1               
blinker                1.4                 
breezy                 3.0.2               
brial                  1.0.2               
Brlapi                 0.7.0               
cbor                   1.0.0               
ccsm                   0.9.14.1            
certifi                2019.11.28          
chardet                3.0.4               
chrome-gnome-shell     0.0.0               
Click                  7.0                 
cloudpickle            1.3.0               
colorama               0.4.3               
command-not-found      0.3                 
compizconfig-python    0.9.14.1            
configobj              5.0.6               
constantly             15.1.0              
cryptography           2.8                 
cssutils               1.0.2               
cupshelpers            1.0                 
cvxopt                 1.2.3               
cycler                 0.10.0              
cypari2                2.1.1               
Cython                 0.29.14             
dbus-python            1.2.16              
decorator              4.4.2               
defer                  1.0.6               
defusedxml             0.6.0               
Deprecated             1.2.7               
devscripts             2.20.2ubuntu2       
distlib                0.3.0               
distro                 1.4.0               
distro-info            0.23ubuntu1         
docutils               0.16                
dot2tex                2.11.3              
dulwich                0.19.15             
duplicity              0.8.12.0            
entrypoints            0.3                 
envisage               4.9.0               
et-xmlfile             1.0.1               
fasteners              0.14.1              
fastimport             0.9.8               
feedparser             5.2.1               
fenics-dijitso         2019.2.0.dev0       
fenics-dolfin          2019.2.0.dev0       
fenics-ffc             2019.2.0.dev0       
fenics-fiat            2019.2.0.dev0       
fenics-ufl             2019.2.0.dev0       
filelock               3.0.12              
flake8                 3.7.9               
fpylll                 0.5.1.dev0          
future                 0.18.2              
gajim                  1.1.3               
GDAL                   3.0.4               
geographiclib          1.50                
geopy                  1.20.0              
gmpy2                  2.1.0b3             
gpg                    1.13.1-unknown      
h5py                   2.10.0              
html5lib               1.0.1               
httplib2               0.14.0              
hyperlink              19.0.0              
idna                   2.8                 
imagesize              1.2.0               
importlib-metadata     1.5.0               
incremental            16.10.1             
iotop                  0.6                 
ipykernel              5.2.0               
ipython                7.13.0              
ipython-genutils       0.2.0               
isodate                0.6.0               
isort                  4.3.4               
itsdangerous           1.1.0               
jdcal                  1.0                 
jedi                   0.15.2              
Jinja2                 2.10.1              
joblib                 0.14.0              
jsonschema             3.2.0               
jupyter-client         6.1.2               
jupyter-core           4.6.3               
keyring                18.0.1              
keyrings.alt           3.4.0               
kiwisolver             1.0.1               
language-selector      0.1                 
launchpadlib           1.10.13             
lazr.restfulclient     0.14.2              
lazr.uri               1.0.3               
lazy-object-proxy      1.4.3               
libvirt-python         6.1.0               
lockfile               0.12.2              
logilab-common         1.4.3               
louis                  3.12.0              
lxml                   4.5.0               
lz4                    3.0.2+dfsg          
macaroonbakery         1.3.1               
Mako                   1.1.0               
MarkupSafe             1.1.0               
matplotlib             3.1.2               
mayavi                 4.7.1               
mccabe                 0.6.1               
meld                   3.20.2              
meshio                 4.0.4               
mistune                0.8.4               
mock                   3.0.5               
monotonic              1.5                 
more-itertools         4.2.0               
mpi4py                 3.0.3               
mpmath                 1.1.0               
mshr                   2019.2.0.dev0       
musicbrainzngs         0.7.1               
mutagen                1.44.0              
nbconvert              5.6.1               
nbformat               5.0.4               
nbxmpp                 0.6.10              
netifaces              0.10.4              
networkx               2.4                 
nose                   1.3.7               
notebook               6.0.3               
numexpr                2.7.1               
numpy                  1.17.4              
numpydoc               0.7.0               
oauth                  1.0.1               
oauthlib               3.1.0               
olefile                0.46                
openpyxl               3.0.3               
openshot-qt            2.4.3               
OWSLib                 0.19.1              
packaging              20.3                
pandas                 0.25.3              
pandocfilters          1.4.2               
paramiko               2.6.0               
parso                  0.5.2               
path.py                12.0.1              
pbr                    5.4.5               
pdfarranger            1.4.2               
petsc4py               3.12.0              
petsc4py-real          3.12.0              
pexpect                4.6.0               
pickleshare            0.7.5               
pikepdf                1.10.3+dfsg         
Pillow                 7.0.0               
pip                    20.0.2              
Pivy                   0.6.5               
pkgconfig              1.5.1               
plotly                 4.4.1               
pluggy                 0.13.0              
ply                    3.11                
pplpy                  0.8.4               
precis-i18n            1.0.0               
prometheus-client      0.7.1               
prompt-toolkit         2.0.10              
protobuf               3.6.1               
psutil                 5.5.1               
psycopg2               2.8.4               
PuLP                   1.6.0               
py                     1.8.1               
py-ubjson              0.14.0              
pyasn1                 0.4.2               
pyasn1-modules         0.2.1               
pybind11               2.4.3               
pycairo                1.16.2              
pycodestyle            2.5.0               
pycrypto               2.6.1               
pycups                 1.9.73              
pyface                 6.1.2               
pyflakes               2.1.1               
PyGithub               1.43.7              
Pygments               2.3.1               
PyGObject              3.36.0              
PyHamcrest             1.9.0               
pyinotify              0.9.6               
PyJWT                  1.7.1               
pylibacl               0.5.4               
pylint                 2.4.4               
pymacaroons            0.13.0              
PyNaCl                 1.3.0               
pyOpenSSL              19.0.0              
pyparsing              2.4.6               
PyPDF2                 1.26.0              
pypng                  0.0.20              
pyproj                 2.5.0               
PyQRCode               1.2.1               
PyQt5                  5.14.1              
pyRFC3339              1.1                 
pyrsistent             0.15.5              
pyshp                  2.1.0               
PyStemmer              1.3.0               
pysvn                  1.9.9               
pytest                 4.6.9               
python-apt             2.0.0+ubuntu0.20.4.3
python-dateutil        2.7.3               
python-debian          0.1.36ubuntu1       
python-gitlab          2.0.1               
python-libdiscid       1.0                 
python-pam             1.8.4               
python-snappy          0.5.3               
python-xapp            1.8.1               
python-xlib            0.23                
python3-openid         3.1.0               
PyTrie                 0.2                 
pytz                   2019.3              
pyxattr                0.6.1               
pyxdg                  0.26                
PyYAML                 5.3.1               
pyzmq                  18.1.1              
qrcode                 6.1                 
QtAwesome              0.4.4               
qtconsole              4.6.0               
QtPy                   1.9.0               
quodlibet              4.2.1               
rdflib                 4.2.2               
rdiff-backup           2.0.0               
reportlab              3.5.34              
requests               2.22.0              
requests-unixsocket    0.2.0               
retrying               1.3.3               
roman                  2.0.0               
rope                   0.10.5              
rpy2                   3.3.5               
rubber                 1.5.1               
sage                   9.0                 
sagenb-export          3.2                 
scikit-learn           0.22.2.post1        
scipy                  1.3.3               
seaborn                0.10.0              
SecretStorage          2.3.1               
Send2Trash             1.5.0               
service-identity       18.1.0              
setproctitle           1.1.10              
setuptools             45.2.0              
setuptools-scm         3.4.3               
simplegeneric          0.8.1               
simplejson             3.16.0              
sip                    4.19.21             
six                    1.14.0              
slepc4py               3.12.0              
slepc4py-real          3.12.0              
snowballstemmer        2.0.0               
Sphinx                 1.8.5               
spyder                 3.3.6               
spyder-kernels         0.5.2               
ssh-import-id          5.10                
sympy                  1.5.1               
system-service         0.3                 
systemd-python         234                 
tables                 3.6.1               
terminado              0.8.2               
testpath               0.4.4               
tinycss                0.4                 
toml                   0.10.0              
tornado                5.1.1               
traitlets              4.3.3               
traits                 5.2.0               
traitsui               6.1.3               
Twisted                18.9.0              
txaio                  2.10.0              
tzlocal                2.1b1               
u-msgpack-python       2.1                 
ubuntu-advantage-tools 20.3                
ubuntu-drivers-common  0.0.0               
ufw                    0.36                
unattended-upgrades    0.1                 
unity-tweak-tool       0.0.7               
urllib3                1.25.8              
usb-creator            0.3.7               
vcversioner            2.16.0.0            
virtualenv             20.0.17             
wadllib                1.3.3               
wcwidth                0.1.8               
webencodings           0.5.1               
Werkzeug               0.16.1              
wheel                  0.34.2              
wrapt                  1.11.2              
wsaccel                0.6.2               
xkit                   0.0.0               
xlrd                   1.1.0               
xlwt                   1.3.0               
zipp                   1.0.0               
zope.interface         4.7.1

I also have Firedrake installed although that’s in a venv. Could that be causing problems?

Quite hard to tell. As I couldn’t reproduce the error with docker in the post above, it indicatest that something is clashing with dolfin. Have you ever tried using docker (as I showed above, the code works fine there, and there exists prebuilt images, such as: quay.io/fenicsproject/dev:latest that is ready to work without any installation

I haven’t used Docker. I’ll try that, thanks.

From the looks of it, I’d suspect a package clash indeed: Have you noticed the different paths in the backtrace?

Does this still happen if you do not import dolfin globally? I.e.

import dolfin as do
mesh = do.UnitSquareMesh(8, 8)
V = do.FunctionSpace(mesh, "Lagrange", 1)

Thanks for your reply. Yes I still get the error when I import dolfin in that way (not globally). Do you know how I can resolve a package clash?

Hard to judge remotely. I’d say try the Docker image.

Hello, I have the same problem. Did you have any luck using docker?

I actually didn’t try it yet sorry. I’m using Firedrake instead for now as my colleague is familiar with it so can help me.

1 Like

I was told to try updating sympy:
python3 -m pip install sympy==1.6

and it’s fixed the issue.

1 Like

This worked for me too! Thanks so much!

This worked for me also. Thanks.