We shall employ the same reflectometry script as on the preceding page to explain some Python syntax used in BornAgain scripts.
For easy reference, here again the full script:
|
|
We shall now explain the code.
The shebang line
#!/usr/bin/env python3
selects python3 when an executable script is launched directly on Unix-like
operating systems;
see the chapter on how to run scripts
from the command line. It is ignored otherwise, as is all
text from the comment start character # to the end of the line.
The # /// script block declares dependencies for uv; see
Versioned Python scripts.
The text between triple quotes at the start of the script
"""
Text, text, text
"""
is the module’s docstring: a description available through Python’s help system.
import bornagain as ba gives the package the short name ba. The import
from bornagain import deg, angstrom, nm provides unit constants
used to express angles and lengths. ba.require_versions(...) checks installed
versions at runtime.
The function
def get_sample():
...
constructs and returns a sample model. For more reference, see the sample section.
The function
def get_simulation(sample):
...
constructs and returns a simulation model. For more information, see the simulation section, and specifically the reflectometry reference.
The clause
if __name__ == '__main__':
ensures that the following statements are only executed if the script is called directly, as a “main” program. This makes the script importable without immediately running the simulation.
The lines
sample = get_sample()
simulation = get_simulation(sample)
result = simulation.simulate()
construct a sample and instrument model and run a simulation.
The function simulate() returns a
Datafield instance.
The line
ba.plot_datafield(result)
plots the simulated reflectivity as function of the incident glancing angle,
using a BornAgain helper built on MatPlotLib. Like the simulation classes,
BornAgain’s data import, fitting, plotting, and sample-inspection helpers are
called directly through the ba package object.
ba.showSample3D(...) opens a 3D view of the sample. ba.plt.show() displays
the Matplotlib figures.