Как создать несколько файлов, используя вложенный цикл - PullRequest
0 голосов
/ 09 апреля 2020

Я надеюсь, что в это время все будут здоровы, здоровы и здоровы. В настоящее время я работаю над заданием python. Используя следующий код, мне нужно пройти через каждое значение беты, и для каждого значения беты мне нужно пройти через каждое значение снижения), чтобы выполнить следующие шаги.

Затем для каждой итерации reductiom_factor для каждого значения беты мне нужно сохранить данные в файл с заголовками в listofsolutions. Две вещи, которые я не знаю, как это сделать: это как экспортировать данные с файлом с именем в списке решений (для каждого значения бета и extension_factor) и как использовать np.savez для сохранения данные в файлы, которые я только что создал.

Это мой исправленный код

   b = [1/4, 0]
   beta = np.asarray(b)
   gamma = 0.5
   listofsolutions = ['Q2_AA_0.1','Q2_AA_0.9','Q2_AA_0.99', 'Q2_AA_1', 'Q2_AA_1.1', 'Q2_AA_2','Q2_CD_0.1','Q2_CD_0.9','Q2_CD_0.99', 'Q2_CD_1', 'Q2_CD_1.1', 'Q2_CD_2']
   consistent = True   # use a consistent mass matrix
   for bb in itertools.zip_longest(beta):
       c = np.sqrt(E / rho_tilde)  # wave speed
       T = 0.016   # total time
# compute the critical time-step
# note: uncondionally stable AA scheme will return 1.0
       delta_t_crit = fe.get_delta_t_crit(le = le, gamma = gamma, beta = bb, consistent = consistent, c = c)
# actual times-step used is a factor of the critical time-step
      reduction_factor = [0.1, 0.9, 0.99, 1, 1.1, 2]
      for rf in reduction_factor:
          delta_t = rf * delta_t_crit
    # selected output data is stored to a file with the name given below
    # use this to save the results from the different runs
    # change the name to match the data you want to store
        for i in b and r in reduction_factor: 
            outfile[i] = listofsolutions[i]
    n_t_steps = int(np.ceil(T / delta_t));    # number of time step
    # initialise the time domain, K and M
    t = np.linspace(0, T, n_t_steps)
    K = np.zeros((n_dof, n_dof))
    M = np.zeros((n_dof, n_dof))

    # assemble K and M
    for ee in range(n_el):
        dof_index = fe.get_dof_index(ee)
        M[np.ix_(dof_index, dof_index)] +=  fe.get_Me(le = le, Ae = Ae, rho_tilde_e = rho_tilde, consistent = consistent)

    # damping matrix
    C = np.zeros((n_dof, n_dof))

    # assemble the system matrix A
    A_matrix = M + (gamma * delta_t) * C + (beta * delta_t**2)*K 

    # define the free dofs
    free_dof = np.arange(1,n_dof)

    # initial conditions
    d = np.zeros((n_dof, 1))
    v = np.zeros((n_dof, 1))
    F = np.zeros((n_dof, 1))

    # compute the initial acceleration
    a = np.linalg.solve(M, F - C.dot(v) - K.dot(d))

    # store the history data 
    # rows -> each node 
    # columns -> each time step including initial at 0
    d_his = np.zeros((n_dof, n_t_steps))
    v_his = np.zeros((n_dof, n_t_steps))
    a_his = np.zeros((n_dof, n_t_steps))
    d_his[:,0] = d[:,0]
    v_his[:,0] = v[:,0]
    a_his[:,0] = a[:,0]

    # loop over the time domain and solve the problem at each step
    for n in range(1,n_t_steps):
        # data at beginning of the time-step n
        a_n = a
        v_n = v
        d_n = d

        # applied loading
        t_current = n * delta_t # current time
        if t_current<0.001:
            F[-1] = A_bar * Ae * np.sin(1000 * t_current * np.pi)
        else:
            F[-1]=0.

        # define predictors
        d_tilde = d_n + delta_t*v_n + ((delta_t**2)/2.) * (1 - 2*beta) * a_n
        v_tilde = v_n + (1 - gamma) * delta_t * a_n

        # assemble the right-hand side from the known data
        R = F - C.dot(v_tilde) - K.dot(d_tilde)

        # impose essential boundary condition and solve A a = RHS
        A_free = A_matrix[np.ix_(free_dof, free_dof)]
        R_free = R[np.ix_(free_dof)]

        # solve for the accelerations at the free nodes
        a_free = np.linalg.solve(A_free, R_free) 
        a = np.zeros((n_dof, 1))
        a[1:] = a_free

        # update displacement and vecloity predictors using the acceleration
        d = d_tilde + (beta * delta_t**2) * a
        v = v_tilde + (gamma * delta_t) * a

        # store solutions
        d_his[:,n] = d[:,0]
        v_his[:,n] = v[:,0]
        a_his[:,n] = a[:,0]

    # post-processing
    mid_node = int(np.ceil(n_dof / 2))  # mid node

    # compute the stress in each element
    # assuming constant E
    stress = (E / le) * np.diff(d_his, axis=0)

    # here we save the stress data for the middle element

    np.savez(outfile, t, stress[mid_node,:]

Я не уверен, как указать программе сохранять результат для каждого значения reduction_factor в гамме. Кроме того, для последней строки кода я не уверен, как сохранить каждую итерацию в списке созданных мной имен файлов.

Я пытался сделать это, используя выражение "

for i in b` and r in reduction_factor: 
                outfile[i] = listofsolutions[i]"` 

, но я не думаю, что это имеет смысл.

Я совершенно новичок ie в python поэтому я не знаком с тем, как сохранять файлы во вложенных циклах. Я прошу прощения, если какой-либо из моих вопросов является элементарным.

1 Ответ

0 голосов
/ 09 апреля 2020
    for i in b and r in reduction_factor: 
        outfile[i] = listofsolutions[i]

Это не правильно. Возможное решение:

for i in b: # variable 'i' will take every value of list b
    for r in reduction_factor:  # 'r' will iterate through reduction_factor 
        outfile[i] = listofsolutions[i]  # outfile must be declared until it 

Тем не менее, нет логики c. Таким образом, вы можете создать словарь. Если вы действительно хотите создать файл - читайте о «с открытым (имя файла,« w »):» конструкцией и вложенными циклами или пониманием списка.

...