Skip to content

Basic optimization¤

Example script: examples/run_basic_optimalization.py | Code documentation

Description¤

Basic optimization tool designed to optimize a set of parameters in a linear mater: one parameter is optimized at a time and the optimal value is used for the following optimization scans.

The scan optimizes one parameter at and then uses this optimized value for the following scans.

Only one ASTRA simulation is run at a time.

Tip

To run a simple scan of one parameter in a given range, see parallel scan instead.

Example script¤

examples/run_basic_scan.py
"""Basic optimisation script. 

The script will scan each defined parameter separately and choose the best parameter based on the defined optimization parameters. 
The best value for given parameter is set before proceding to the following scan.
"""

import sys
sys.path.append("..")

from optimalization import basic_optimalization

# no changes above
#####################################################################################################
# change the values of the parameters

# directory where the scan should be performed, must be full path
working_dir = r"full path to the working directory"
# number of parallel processes to be run
n_parallel = 3

#####################################################################################################
# no changes here

def main():
    # define the optimizer
    optimizer = basic_optimalization.BaseOptimalization(working_dir=working_dir, n_parallel=n_parallel)

    #####################################################################################################
    # make changes here to match what you want to scan

    # define the optimization parameters, the numerical value represents the relative importance (higher number -> more important)
    optimizer.add_optimalization_parameter("x_emit", 1000)
    optimizer.add_optimalization_parameter("energy_spread", 1)

    # definition of the simulation parameters, that should be optimised to yield the best optimization parameters
    # optimizer.add_scanning_parameter(parameter, start, end, step)
    optimizer.add_scanning_parameter("MaxB(1)", 0.24, 0.27, step=0.005)
    optimizer.add_scanning_parameter("Phi(2)", -40, 40, step=5)
    optimizer.add_scanning_parameter("Phi(3)", -40, 40, step=5)
    optimizer.add_scanning_parameter("Phi(4)", -40, 40, step=5)
    optimizer.add_scanning_parameter("Lx", 1.5, 3, step=0.1)
    optimizer.add_scanning_parameter("Q_total", 1, 7, step=2, only_scan=True)

    #####################################################################################################
    # no changes bellow

    optimizer.optimize()

if __name__ == "__main__":
    main()

For the script to work, the working_dir (working directory) specified when constructing the optimizer must be prepared as described here. The script itself is explained in detail later on this page.

With Python environment well set-up, the script can be simply run as

python run_basic_optimalization.py

Setup¤

Working directory setup¤

The working directory must contain a folder called BASE/, which serves as the base folder for running the scans. It must contain the files listed in the table bellow. It is recommended not to have any other files and folders in the working directory, except for pure text (.txt) files containing comments. This is to not mess up with the files created by the simulation.

Example directory setup
working_directory/ # (1)
    BASE/ # (2)
        ...
    ... # (3)
  1. Working directory that is used in the initialization process.
  2. BASE directory containing the initial setting files as well as the ASTRA executables. For the content of this directory, see the table bellow.
  3. It is recommended not to include other files in the working_directory in order not to mess with the output files. It should be safe though to include .txt files with additional information (scan settings etc.).
File Comment
Astra.exe Astra executable file.
generator.exe Astra initial particle distribution generator.
.dat files Files defining the structures used in the simulations.
Generator file File obtaining the initial distribution definition, which will be generated by the generator.exe. By default, the python code will assume this file is named generator.in, but this can be changed in the object setup.
Simulation definition file File obtaining the setup definition. By default, the python code will assume this file is named photo_track.in, but this can be changed in the object setup.

Run script setup¤

Important

Please note that the run script does not have to be in the working directory. It is recommended to keep the script and working directory separated and have the run script in a subdirectory of the main code directory (for example create a scripts/ directory inside the main code directory) to avoid problems when importing the code. The working directory will be passed as an argument, as explained later in this section.

The optimalization/basic_optimalization.py must be imported from the optimalization subpackage of the main package:

from optimalization import basic_optimalization

In case this fails, the main package must be specifically added to the python path so python actually recognizes that. This can be achieved by the sys library and the full import is therefore:

import sys
sys.path.append("..") #(1)

from optimalization import basic_optimalization
  1. Use .. when the script is located in a subdirectory of the main code folder (recommended), otherwise use the full path to the main code directory.

Optimization object setup¤

The optimization code is written as object-oriented. Therefore, after importing the corresponding source file, the optimization object has to be created.

from optimalization import basic_optimalization

def main():
    # define the optimizer and the working directory
    optimizer = basic_optimalization.BaseOptimalization(working_dir="<workingDirectory>") #(1)
    ...

if __name__ == "__main__":
    main()
  1. Full path to the working directory. See the full list of possible parameters here.

The full list of parameters to be set when initializing the object is listed here. The most important one is the working_dir parameter, which defines where the optimization should take place.

Scan setup¤

After the optimization object is created, the scan settings must be defined using the methods of the created optimization object:

Tip

See the implementation in the provided example.

  1. Define what is the optimization target

    First, define the optimization target using the BaseOptimization.add_optimalization_parameter method. These represent a bunch parameter, that needs to be minimized. Any of the parameters listed included in the pandas.DataFrame returned by this method can be used.

    Depending on the sign of the weight optional parameter, the parameter will be minimized (weight is positive, default) or maximized (weight is negative).

    Multiple optimization targets can be set. As the optimal setup, the simulation that minimizes the following sum will be selected

    \[ \sum_\text{optimization targets} (\text{weight}) \cdot (\text{optimization target nominal value}). \]
  2. Define optimization variables

    Secondly, the optimization variables need to be defined using the BaseOptimization.add_scanning_parameter method, defining the scanning range.

    All parameters present in the .in files (generator and the tracking file) can be used.

Output¤

Scan of each parameter is performed in a separate directory inside the main working directory with the name SCAN_<scanning parameter name>. By default, basic analysis is performed for each of these scans and its output are located in the SCAN_<scanning parameter name>/plots folder.

If the do_final_run optional argument is True (by default), the final run with the optimized is parameters will be performed. It can be found in the Final/ subfolder of the main working directory. Run analysis is automatically performed to extract the key information from the analysis and its outputs are saved within the Final/ folder.


Last update: October 29, 2023
Created: September 14, 2023