February 1, 2023

Python interface to SwissQuantumPi Quantum Simulator

As you know, the core of the SwissQuantumPi simulator has been written in R language. R provides a lot of advantages in terms of performance, code quality and available scientific libraries. But it can be hard and dry for the regular programmer and most of quantum geeks are rather Python addicts. Moreover there are a lot of quantum Python libraries and code samples available.

So let’s try to provide a Python interface to our quantum simulator.

By chance, there is a very nice Python interface to the R language: Project rpy2 by Laurent Gautier. The project is mature, stable, documented, and widely used.

rpy2 is running an embedded R, providing access to it from Python using R’s own C-API through either:

  • a high-level interface making R functions an objects just like Python functions and providing a seamless conversion to numpy and pandas data structures
  • a low-level interface closer to the C-API

It is also providing features for when working with jupyter notebooks or ipython.

Installing should be as easy as:

sudo apt-get install libffi-dev
pip install rpy2

rpy2 provides the py.test and pytest scripts for testing the installation. But these scripts are installed in '/home/pi/.local/bin' which is not on PATH. Consider adding this directory to PATH, by modifying environment variables in /etc/environment.

Then test your rpy2 installation by typing:

pytest --pyargs 'rpy2.tests'

You should get no error message. Eventually, type also:

python -m rpy2.situation

This utility module is included to report what rpy2’s environment. You should get something like that:

rpy2 version:
Python version:
3.7.3 (default, Dec 20 2019, 18:57:59)
[GCC 8.3.0]
Looking for R's HOME:
    Environment variable R_HOME: None
    Calling `R RHOME`: /usr/lib/R
    Environment variable R_LIBS_USER: None
R's additions to LD_LIBRARY_PATH:
R version:
    In the PATH: R version 3.5.2 (2018-12-20) -- "Eggshell Igloo"
    Loading R library from rpy2: OK
Additional directories to load R packages from:
C extension compilation:
  ['R', 'pcre', 'lzma', 'bz2', 'z', 'rt', 'dl', 'm', 'icuuc', 'icui18n']
  ['-Wl,--export-dynamic', '-fopenmp', '-Wl,-z,relro']

rpy2 is running an embedded R. The object rpy2.robjects.r can be used as rudimentary communication channel between Python and R.

If you want to use the constant pi in R, you have to type:

> pi
[1] 3.141593

Within Python, using rpy2, you have to type:

import rpy2.robjects as robjects