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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python3
"""
Basic example of specular reflectometry simulation with BornAgain.
The sample consists of 20 alternating Ti and Ni layers.
"""

from bornagain import ba_plot as bp, std_samples, std_simulations


def get_sample():
    return std_samples.alternating_layers()


def get_simulation(sample):
    n = bp.simargs['n']
    return std_simulations.specular(sample, n)


if __name__ == '__main__':
    bp.parse_args(sim_n=500)
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    bp.plot_simulation_result(result)
Examples/specular/AlternatingLayers.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 block

def get_sample():
    from bornagain import std_samples
    return std_samples.alternating_layers()
defines the function get_sample that imports the BornAgain submodule std_samples, and returns the alternating layers sample model.

Similarly, the next block

def get_simulation(sample, scan_size=500):
    from bornagain import std_simulations
    return std_simulations.specular(sample, scan_size)
defines the function get_simulation that) imports the BornAgain submodule std_simulations, and returns a standard setup to simulate a specular reflectivity scan.

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.

In the main block, the statement

    ba_plot.run_and_plot(simulation)
runs the previously defined simulation, and calls MatPlotLib to display the results. The function run_and_plot is implemented in the module ba_plot.