Installing FEniCS on Google Colab

FEniCS is an open-source computing platform for solving partial differential equations. The syntax of FEniCS for implementing mathematical models and power of Python makes it a great choice for fast and robust numerical modeling and it also has a pretty active community. While installing FEniCS on Linux is pretty straightforward, that is not the case in Windows, especially if you want to use it inside a container. Google Colab gives a space to run Python Notebook and I found it to be the fastest option to run a simple FEniCS code for debugging or testing. It might not be ideal for running a real numerical simulation, though.

To run FEniCS inside a Colab Notebook, you need to sign into your Google account and open Google Colab. There is a great introduction into Colab available for you, which goes over different possibilities, mainly related to Data Science and Machine Learning. To use FEniCS, you need to open a new Notebook and run the following piece of code at the beginning of the Notebook:

try:
    from fenics import *; from mshr import *
except ImportError as e:
    !apt-get install software-properties-common
    !add-apt-repository ppa:fenics-packages/fenics
    !apt-get update
    !apt-get install --no-install-recommends fenics
    from fenics import *; from mshr import *

You can also use in-house Python modules in your Notebooks. To do that, you need to upload them on Google Drive and mount the folder in your Google Colab session. You can do that with the following piece of code:

import sys
from google.colab import drive
drive.mount('/content/gdrive/')
sys.path.append('/content/gdrive/inhouseModules')

Notebooks are great when you want to keep your report, codes, and results all in the same file. To see FEniCS plots in Colab, you can use the following line:

import matplotlib.pyplot as plt
%matplotlib inline

Then, you can use plt.figure() to create a new figure instance and plt.show() to print the figure in the Notebook.

Sometimes you have numerous results files and you want to download them on your system. To make the file transfer easier, you can turn them into a single zip file:

!zip -r results.zip results/

If you have made some videos using FEniCS results and are looking for embedding them into the colab notebook, you can use the following piece of code. I tried it with ogv extension.

from IPython.core.display import display, HTML
from IPython.core.display import HTML
display(HTML('<video width="420" height="300" controls><source src="\filename.ogv" \
             type="video/ogg">Video tag</video>'))