Python syntax used in BornAgain scripts

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:

Examples/specular/AlternatingLayers1.py

We shall now explain the code.

The shebang line

#!/usr/bin/env python3

makes the script executable under Unix-like operating systems, see the chapter on how to run scripts from the command line.

Lines between triple quotes

"""
Text, text, text
"""

are comments.

The function

def get_sample():
    ...

constructs and returns a sample model. For more information, see the sample section.

The function

def get_simulation(sample, scan_size=500):
    ...

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 precaution is required by the GUI, where scripts can be imported without being immediately executed.

The line

bp.parse_args(sim_n=500)

digests some command-line arguments that are mostly needed by the developers for automatized testing.

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 SimulationResult instance.

The line

bp.plot_simulation_result(/py/result)

plots the simulated reflectivity as function of the incident glancing angle, using MatPlotLib.