1.1. Python scientific computing ecosystem

Authors: Fernando Perez, Emmanuelle Gouillart, Gaël Varoquaux, Valentin Haenel

1.1.1. Why Python?

1.1.1.1. The scientist’s needs

  • Get data (simulation, experiment control),

  • Manipulate and process data,

  • Visualize results, quickly to understand, but also with high quality figures, for reports or publications.

1.1.1.2. Python’s strengths

  • Batteries included Rich collection of already existing bricks of classic numerical methods, plotting or data processing tools. We don’t want to re-program the plotting of a curve, a Fourier transform or a fitting algorithm. Don’t reinvent the wheel!

  • Easy to learn Most scientists are not paid as programmers, neither have they been trained so. They need to be able to draw a curve, smooth a signal, do a Fourier transform in a few minutes.

  • Easy communication To keep code alive within a lab or a company it should be as readable as a book by collaborators, students, or maybe customers. Python syntax is simple, avoiding strange symbols or lengthy routine specifications that would divert the reader from mathematical or scientific understanding of the code.

  • Efficient code Python numerical modules are computationally efficient. But needless to say that a very fast code becomes useless if too much time is spent writing it. Python aims for quick development times and quick execution times.

  • Universal Python is a language used for many different problems. Learning Python avoids learning a new software for each new problem.

1.1.1.3. How does Python compare to other solutions?

Compiled languages: C, C++, Fortran…

Pros:
  • Very fast. For heavy computations, it’s difficult to outperform these languages.

Cons:
  • Painful usage: no interactivity during development, mandatory compilation steps, verbose syntax, manual memory management. These are difficult languages for non programmers.

Matlab scripting language

Pros:
  • Very rich collection of libraries with numerous algorithms, for many different domains. Fast execution because these libraries are often written in a compiled language.

  • Pleasant development environment: comprehensive and help, integrated editor, etc.

  • Commercial support is available.

Cons:
  • Base language is quite poor and can become restrictive for advanced users.

  • Not free and not everything is open sourced.

Julia

Pros:
  • Fast code, yet interactive and simple.

  • Easily connects to Python or C.

Cons:
  • Ecosystem limited to numerical computing.

  • Still young.

Other scripting languages: Scilab, Octave, R, IDL, etc.

Pros:
  • Open-source, free, or at least cheaper than Matlab.

  • Some features can be very advanced (statistics in R, etc.)

Cons:
  • Fewer available algorithms than in Matlab, and the language is not more advanced.

  • Some software are dedicated to one domain. Ex: Gnuplot to draw curves. These programs are very powerful, but they are restricted to a single type of usage, such as plotting.

Python

Pros:
  • Very rich scientific computing libraries

  • Well thought out language, allowing to write very readable and well structured code: we “code what we think”.

  • Many libraries beyond scientific computing (web server, serial port access, etc.)

  • Free and open-source software, widely spread, with a vibrant community.

  • A variety of powerful environments to work in, such as IPython, Spyder, Jupyter notebooks, Pycharm, Visual Studio Code

Cons:
  • Not all the algorithms that can be found in more specialized software or toolboxes.

1.1.2. The scientific Python ecosystem

Unlike Matlab, or R, Python does not come with a pre-bundled set of modules for scientific computing. Below are the basic building blocks that can be combined to obtain a scientific computing environment:


Python, a generic and modern computing language

  • The language: flow control, data types (string, int), data collections (lists, dictionaries), etc.

  • Modules of the standard library: string processing, file management, simple network protocols.

  • A large number of specialized modules or applications written in Python: web framework, etc. … and scientific computing.

  • Development tools (automatic testing, documentation generation)

Core numeric libraries

Advanced interactive environments:

Domain-specific packages,

and many more packages not documented in the Scientific Python Lectures.

1.1.3. Before starting: Installing a working environment

Python comes in many flavors, and there are many ways to install it. However, we recommend to install a scientific-computing distribution, that comes readily with optimized versions of scientific modules.

Under Linux

If you have a recent distribution, most of the tools are probably packaged, and it is recommended to use your package manager.

Other systems

There are several fully-featured scientific Python distributions:

1.1.4. The workflow: interactive environments and text editors

Interactive work to test and understand algorithms: In this section, we describe a workflow combining interactive work and consolidation.

Python is a general-purpose language. As such, there is not one blessed environment to work in, and not only one way of using it. Although this makes it harder for beginners to find their way, it makes it possible for Python to be used for programs, in web servers, or embedded devices.

1.1.4.1. Interactive work

We recommend an interactive work with the IPython console, or its offspring, the Jupyter notebook. They are handy to explore and understand algorithms.

Start ipython:

In [1]: print('Hello world')
Hello world

Getting help by using the ? operator after an object:

In [2]: print?
Signature: print(*args, sep=' ', end='\n', file=None, flush=False)
Docstring:
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Type: builtin_function_or_method

See also

1.1.4.2. Elaboration of the work in an editor

As you move forward, it will be important to not only work interactively, but also to create and reuse Python files. For this, a powerful code editor will get you far. Here are several good easy-to-use editors:

  • Spyder: integrates an IPython console, a debugger, a profiler…

  • PyCharm: integrates an IPython console, notebooks, a debugger… (freely available, but commercial)

  • Visual Studio Code: integrates a Python console, notebooks, a debugger, …

Some of these are shipped by the various scientific Python distributions, and you can find them in the menus.

As an exercise, create a file my_file.py in a code editor, and add the following lines:

s = 'Hello world'
print(s)

Now, you can run it in IPython console or a notebook and explore the resulting variables:

In [3]: %run my_file.py
Hello world
In [4]: s
Out[4]: 'Hello world'
In [5]: %whos
Variable Type Data/Info
----------------------------
s str Hello world

1.1.4.3. IPython and Jupyter Tips and Tricks

The user manuals contain a wealth of information. Here we give a quick introduction to four useful features: history, tab completion, magic functions, and aliases.


Command history Like a UNIX shell, the IPython console supports command history. Type up and down to navigate previously typed commands:

In [6]: x = 10
In [7]: <UP>
In [8]: x = 10

Tab completion Tab completion, is a convenient way to explore the structure of any object you’re dealing with. Simply type object_name.<TAB> to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.*

In [9]: x = 10
In [10]: x.<TAB>
as_integer_ratio() conjugate() imag to_bytes()
bit_count() denominator numerator
bit_length() from_bytes() real

Magic functions The console and the notebooks support so-called magic functions by prefixing a command with the % character. For example, the run and whos functions from the previous section are magic functions. Note that, the setting automagic, which is enabled by default, allows you to omit the preceding % sign. Thus, you can just type the magic function and it will work.

Other useful magic functions are:

  • %cd to change the current directory.

    In [11]: cd /tmp
    
    /tmp
  • %cpaste allows you to paste code, especially code from websites which has been prefixed with the standard Python prompt (e.g. >>>) or with an ipython prompt, (e.g. in [3]):

    In [12]: %cpaste
    
  • %timeit allows you to time the execution of short snippets using the timeit module from the standard library:

    In [12]: %timeit x = 10
    
    10.1 ns +- 0.759 ns per loop (mean +- std. dev. of 7 runs, 100,000,000 loops each)
  • %debug allows you to enter post-mortem debugging. That is to say, if the code you try to execute, raises an exception, using %debug will enter the debugger at the point where the exception was thrown.

    In [13]: x === 10
    
    Cell In[13], line 1
    x === 10
    ^
    SyntaxError: invalid syntax
    In [14]: %debug
    > /home/jarrod/.venv/lectures/lib64/python3.11/site-packages/IPython/core/compilerop.py(86)ast_parse()
    84 Arguments are exactly the same as ast.parse (in the standard library),
    85 and are passed to the built-in compile function."""
    ---> 86 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
    87
    88 def reset_compiler_flags(self):
    ipdb> locals()
    {'self': <IPython.core.compilerop.CachingCompiler object at 0x7f30d02efc10>, 'source': 'x === 10\n', 'filename': '<ipython-input-1-8e8bc565444b>', 'symbol': 'exec'}
    ipdb>

Aliases Furthermore IPython ships with various aliases which emulate common UNIX command line tools such as ls to list files, cp to copy files and rm to remove files (a full list of aliases is shown when typing alias).