KAHIBARO
Discord Login Register

3.3. Loops

Table of Contents

`for`

In GATE simulations you often need to repeat similar operations, for example creating many detector crystals, adding several sources, or running over lists of files. A for loop lets you repeat a block of Python code for each element in a sequence such as a list, a range of numbers, or any iterable object.

The most common pattern is to loop over a range of integers using the built-in range function. range(n) produces numbers from 0 up to but not including n. You can also give a start, stop, and step.

Key rule:
range(stop) gives 0, 1, 2, ..., stop - 1.
range(start, stop, step) goes from start to stop - 1 in increments of step.

Here are the basic forms:

python
# Loop over 0, 1, 2, 3, 4
for i in range(5):
    print("i =", i)
# Loop over 2, 3, 4, 5, 6
for i in range(2, 7):
    print("i =", i)
# Loop over 0, 2, 4, 6, 8
for i in range(0, 10, 2):
    print("even i =", i)

You can also loop directly over the elements of a list or other collection. This is useful when you already have parameters prepared, for example a list of detector materials or a set of source energies.

python
materials = ["G4_WATER", "G4_AIR", "G4_BONE_COMPACT_ICRU"]
for m in materials:
    print("Using material:", m)

If you need both the index and the value, use enumerate. This is common when you want to number detectors or sources.

python
energies_keV = [140, 511, 662]
for idx, e in enumerate(energies_keV):
    print("Source", idx, "has energy", e, "keV")

In many GATE scripts you will combine for loops with function calls that create parts of the simulation, for example:

python
crystal_sizes = [2.0, 3.0, 4.0]  # in mm
for size in crystal_sizes:
    create_crystal(size)  # imagine this is a function you defined elsewhere

You can also nest loops, which is especially useful when building arrays or grids of repeated objects.

python
n_x = 4
n_y = 3
for ix in range(n_x):
    for iy in range(n_y):
        print("Detector at index (", ix, ",", iy, ")")

You can control a for loop using break and continue. break stops the whole loop early. continue skips to the next iteration.

python
for i in range(10):
    if i == 5:
        break  # stop completely when i reaches 5
    print(i)
for i in range(10):
    if i % 2 == 0:
        continue  # skip even numbers
    print("odd i:", i)

For GATE beginners the most important ideas are that for loops let you avoid repetitive code and that range counts up to, but not including, the stop value. This pattern will appear repeatedly when you define repeated geometry or sets of simulation parameters.

`while`

A while loop repeats a block of code as long as a condition is true. Instead of looping over a fixed list or range, you control the loop using a logical expression. This is useful when you do not know in advance how many iterations you need, for example when waiting for some condition to be satisfied.

The general form is:

python
while condition:
    # repeated code

On each iteration Python evaluates condition. If it is True, the body runs once. After the body finishes, Python checks the condition again. The loop stops when the condition becomes False.

Here is a simple example that counts up to 5:

python
i = 0
while i < 5:
    print("i =", i)
    i = i + 1  # update i, so the loop eventually stops

Important rule:
Always make sure something inside the while loop changes so that the condition can become False. If the condition never becomes False, you create an infinite loop that never ends.

You can use while when you need to repeat until some value crosses a limit, until an error measure is small enough, or while waiting for user input. In most GATE scripts, fixed iteration tasks such as creating detectors are better written with for. while is more appropriate for open-ended processes.

You can still use break and continue inside while loops.

python
i = 0
while True:
    if i == 3:
        i = i + 1
        continue  # skip printing 3
    if i == 6:
        break      # stop the loop completely
    print("i =", i)
    i = i + 1

In this example the loop condition is True, so it would never end without break. This pattern is powerful but must be used carefully to avoid loops that run forever.

In the context of GATE, you might occasionally use while in helper scripts that, for example, monitor a directory and process new output files as they appear. For defining the structure of a simulation, however, for loops are usually clearer and safer to use.

Views: 14

Comments

Please login to add a comment.

Don't have an account? Register now!