#While Loop inside of a for loop for Python.

61 messages · Page 1 of 1 (latest)

cursive wrenBOT
#

@polar root

burtonrider Successfully Uploaded Some Code

I have a for loop with 6 if statements that will be triggered based on random number generation. If 5 of the 6 are triggered I want to run the next for loop. Otherwise I want it to keep looping without indexing up the j.

Uploaded these files to a Gist
polar root
#

@potent charm

#

It starts at line 60

potent charm
#

Thanks, taking a look now

polar root
#

I appreciate it.

potent charm
#

just to check, is there an error you're getting or would you like help implementing the loop as you described it above

polar root
#

I'm just trying to get it to work as I need it. It's kinda complicated.

#

basically if the scatter loop is triggered I want it to run again until it's not, but I want my j to not index up for a scatter

potent charm
#

ah ok

#

in that case it might be better to use a while loop instead of a for loop

#

and then you can control the j variable directly

polar root
#

if it scatters I need it to change direction based on np.random.choice and then chang position based on the distance_to_collision equation.

#

That's what chatgpt tried to do. I use chatgpt when I'm stumped, but they kept doing the full loop but it also indexed up everytime.

potent charm
#

ok one sec, I'll show what I mean with code

polar root
#

That would be awesome.

#

If you could show me some kind of simplified example that would be great too. I don't know which is easier for you to do. Modify my code or write a few lines of how you would do it.

potent charm
#
    # Loop through particles
    j = 0

    while j < n_particles:
        inc_j = True

        # Move particles based on direction
        distance_to_collision = -np.log(np.random.rand()) / Sigma_t
        position[j] += direction[j]*distance_to_collision

        rand_num = np.random.uniform(low=0, high=1)

        # Scatter
        if rand_num < Sigma_s / Sigma_t:
            inc_j = False
            scatter_dir = np.random.choice([-1, 1])
            direction[j] = scatter_dir
            print(j)
            print('we scatter')

            for index in range(I_bins):
                if x_index[index] < position[j] < x_index[index + 1]:
                    scatter_count[index, i] += 1


        # Kill particles that pass the boundaries
        if position[j] < x_min or position[j] > x_max:
            n_particles -= 1
            #distance_to_collision = x_max-np.abs(x_place)
            position = np.delete(position, j)
            direction = np.delete(direction, j)
            cont = False
#            keff_track += distance_to_collision * nu * Sigma_f


        # Capture
        elif Sigma_s/Sigma_t <= rand_num < (Sigma_s + Sigma_c)/Sigma_t:
            n_particles -= 1
            position = np.delete(position, j)
            direction = np.delete(direction, j)

            for index in range(I_bins):
                if x_index[index] < position[j] < x_index[index + 1]:
                    capture_count[index] += 1
            cont = False

#
        # Fission
        else:
            n_particles -= 1
            position = np.delete(position, j)
            direction = np.delete(direction, j)
            rand_num = np.random.uniform()
            num_fission += 1

            if rand_num < Sigma_f1/Sigma_f:
                neutron_count_per_batch += 1
                num_fission += 1
                n_particles += 1
                position = np.concatenate([
                    position, np.random.uniform(low=x_min, high=x_max, size=1)])

                direction = np.concatenate([
                    direction, np.random.choice([-1, 1], size=1)])

                for index in range(I_bins):
                    if x_index[index] < position[j] < x_index[index + 1]:
                        fission_count[1, index] += 1

            elif Sigma_f1/Sigma_f <= rand_num < (Sigma_f1+Sigma_f2)/Sigma_f:
                neutron_count_per_batch += 2
                num_fission += 1
                n_particles += 2
                position = np.concatenate([
                    position, np.random.uniform(low=x_min, high=x_max, size=2)])

                direction = np.concatenate([
                    direction, np.random.choice([-1, 1], size=2)])

                for index in range(I_bins):
                    if x_index[index] < position[j] < x_index[index + 1]:
                        fission_count[2, index] += 1

            else:
                neutron_count_per_batch += 3
                num_fission += 1
                n_particles += 3
                position = np.concatenate([
                    position, np.random.uniform(low=x_min, high=x_max, size=3)])

                direction = np.concatenate([
                    direction, np.random.choice([-1, 1], size=3)])

                for index in range(I_bins):
                    if x_index[index] < position[j] < x_index[index + 1]:
                        fission_count[3, index] += 1

            if inc_j:
                j += 1
#

Something like this is basically a for loop, but you increment j manually (see the final line), in this specific case it's slightly awkward just due to the order of the if-statements so what I've done is just made a variable (inc_j) that says if we want to increment j this loop or not. When I run this I still get the same error! so there might be an issue elsewhere

#

and this would just replace your code from line 59 to 154 inclusive

#

the only things I added were the j = 0, while j < n_particles, inc_j = True, and inv_j = False, and the final if statement to actually increment j

polar root
#

So I didn't realize that you had already answered Specter, because I was posting this. Sorry about that.

potent charm
#

haha nws

polar root
#

I think there is an issue elsewhere. I'm good at diagnosing those. It's just that I'm not good with the loops yet.

potent charm
#

can I ask how familar you are with defining your own functions? just because it might make this code a lot simpler and easier to debug

polar root
#

I can do it, but I have 10.5 hours to get 30 hw points so I don't have to take another class before I graduate, I feel like the code is close enough.

#

It's not working sitll, but I think it's closer. I will play with it some more

#

those are the j values along with my flag for scattering. I moved the print j back outside the if because that's not where it was supposed to be. It's 0 even if it doesn't scatter

potent charm
#

you only have one print(j) per loop?

polar root
#

It was supposed to go here

#

If it doesn't scatter it should index up

#

there should be a "we scatter" between all of the 0's

#

I added flags for the other events, so it's more clear what's happening

potent charm
#

just to check, is it intended that multiple events can occur in the same iteration?

#

ah I didn't indent the final if statement correctly

polar root
#

No, but I think I figured it out

potent charm
#

if you take one tab out of the if inc_j: and the line does that behave as expected>

polar root
#

Dude that's it.

#

Crap I need one last thing. I need it to also skip for #Kill particles that pass the boundaries.

#

Is there a break or something that I can use

potent charm
#

that will be exactly the same, just put a inc_j = False in that if statement

#

so that it looks like the scatter if statement

#

wait do you want to skip the rest of that iteration too?

polar root
#

So I had something wrong. after moving a particle. The first thing it should do is see if it has escaped the boundary

#

Yeah pretty much

#

so move particle, check to see if in bounds, if in bounds, either scatter,capture, or fission. if scattered, move and try again

potent charm
#

you can use continue to skip the rest of the current iteration, before you use conitnue though you should change j as needed, so maybe

j += 1
continue
``` or leave j as is depending on what you need I'm not sure of the exact context
polar root
#

Holy crap.

#

How are you this good??

#

You just saved me $3300

potent charm
#

haha

#

is it working as you need it to?

polar root
#

I'm not even joking.

#

Yeah

#

I tried for 2 hours on just getting hat

potent charm
#

I'm glad I could help lol

polar root
#

I had a hardship last fall and my professor let me do a deferred grade for this. I've been making up homeworks. It's my last class and I need a B average to graduate, which means I need a B in this class. I'm 3 points away at 77 which is 30 hw points.

#

I was really stuck on this

potent charm
#

great job getting through the work you needed in time!