示例#1
0
文件: iterate.py 项目: KevinKSY/TEA
    if times:
        ini = time.time()

    # Execute Lagrange minimization
    lagrange_data = lg.lagrange(it_num, datadir, doprint, lambdacorr_data)

    # Time / speed testing for lagrange.py
    if times:
        fin = time.time()
        elapsed = fin - ini
        print("lagrange" + str(it_num).rjust(4) + " :      " + str(elapsed))

    # Print for debugging purposes
    if doprint:
        printout(
            'Iteration %d Lagrange complete. Starting lambda correction...',
            it_num)

    # Take final x_i mole numbers from last Lagrange calculation
    lagrange_x = lagrange_data[4]

    # Check if x_i have negative mole numbers, and if yes perform lambda correction
    if where((lagrange_x < 0) == True)[0].size != 0:
        # Print for debugging purposes
        if doprint:
            printout('Correction required. Initializing...')

        # Time / speed testing for lambdacorr.py
        if times:
            ini = time.time()
示例#2
0
 def handle(self, *args, **options):
         printout()
示例#3
0
def iterator(head, destination, location_out):
    # Correct location_TEA name
    if location_out[-1] != '/':
        location_out += '/'

    # Time / speed testing
    if times:
        end = time.time()
        elapsed = end - start
        print("iterate.py imports: " + str(elapsed))

    # Read run-time arguments
    header = head              # Name of header file
    desc   = destination              # Directory name

    # Create and name outputs and results directories if they do not exist
    datadir   = location_out + desc + '/outputs/' + 'transient/'
    datadirr  = location_out + desc + '/results'                

    if not os.path.exists(datadir): os.makedirs(datadir)
    if not os.path.exists(datadirr): os.makedirs(datadirr)

    # Retrieve header info
    inhead    = form.readheader(header)
    pressure  = inhead[0]
    temp      = inhead[1]

    # Locate and read initial iteration output from balance.py
    infile    = datadir + '/lagrange-iteration-0-machine-read.txt'
    input     = form.readoutput(infile)

    # Retrieve and set initial values
    speclist  = input[2]
    x         = input[3]
    x_bar     = input[6]

    # Set up first iteration 
    it_num  = 1
    repeat  = True

    # Prepare data object for iterative process 
    #         (see description of the 'direct' object in lagrange.py)
    lambdacorr_data = [header, 0, speclist, x, x, 0, x_bar, x_bar, 0]

    # Time / speed testing
    if times:
        new = time.time()
        elapsed = new - end
        print("pre-loop setup:     " + str(elapsed))

    # ====================== PERFORM MAIN TEA LOOP ====================== #

    while repeat:
        # Output iteration number
        if ((not doprint) & (not times)):
            stdout.write(' ' + str(it_num) + '\r')
            stdout.flush()

        # Time / speed testing for lagrange.py
        if times:
            ini = time.time()
        
        # Execute Lagrange minimization
        lagrange_data = lg.lagrange(it_num, datadir, doprint, lambdacorr_data)
        
        # Time / speed testing for lagrange.py
        if times:
            fin = time.time()
            elapsed = fin - ini
            print("lagrange" + str(it_num).rjust(4) + " :      " + str(elapsed))    
          
        # Print for debugging purposes
        if doprint:
            printout('Iteration %d Lagrange complete. Starting lambda correction...', it_num)
        
        # Take final x_i mole numbers from last Lagrange calculation 
        lagrange_x = lagrange_data[4]
        
        # Check if x_i have negative mole numbers, and if yes perform lambda correction
        if where((lagrange_x < 0) == True)[0].size != 0:
            # Print for debugging purposes 
            if doprint:
                printout('Correction required. Initializing...')
                
            # Time / speed testing for lambdacorr.py
            if times:
                ini = time.time()
            
            # Execute lambda correction
            lambdacorr_data = lc.lambdacorr(it_num, datadir, doprint, \
                                                       lagrange_data)
            
            # Print for debugging purposes
            if times:
                fin = time.time()
                elapsed = fin - ini
                print("lambcorr" + str(it_num).rjust(4) + " :      " + \
                                                          str(elapsed))
            
            # Print for debugging purposes
            if doprint:
                printout('Iteration %d lambda correction complete. Checking precision...', it_num)

        # Lambda correction is not needed
        else:
            # Pass previous Lagrange results as inputs to next iteration
            lambdacorr_data = lagrange_data

            # Print for debugging purposes
            if doprint:
                printout('Iteration %d did not need lambda correction.', it_num)
        
        # Retrieve most recent iteration values
        input_new = lambdacorr_data

        # Take most recent x_i and x_bar values    
        x_new     = input_new[4]
        x_bar_new = input_new[7]
        
        # If max iteration not met, continue with next iteration cycle
        if it_num < maxiter: 
            # Add 1 to iteration number
            it_num += 1

            # Print for debugging purposes
            if doprint:
                printout('Max interation not met. Starting next iteration...\n')
        
        # ============== Stop the loop, max iteration reached ============== #

        # Stop if max iteration is reached 
        else:
            # Print to screen
            printout('Maximum iteration reached, ending minimization.\n')

            # Set repeat to False to stop the loop
            repeat = False

            # Calculate delta values
            delta = x_new - x

            # Calculate delta_bar values
            delta_bar = x_bar_new - x_bar
            
            # Name output files with corresponding iteration number name
            file_results       = datadirr + '/results-machine-read.txt'
            file_fancyResults  = datadirr + '/results-visual.txt'

            # Export all values into machine and human readable output files  
            form.output(datadirr, header, it_num, speclist, x, x_new, delta,    \
                        x_bar, x_bar_new, delta_bar, file_results, doprint)
            form.fancyout_results(datadirr, header, it_num, speclist, x, x_new, \
                                  delta, x_bar, x_bar_new, delta_bar, pressure, \
                                  temp, file_fancyResults, doprint)
示例#4
0
文件: iterate.py 项目: KevinKSY/TEA
 # Time / speed testing for lagrange.py
 if times:
     ini = time.time()
 
 # Execute Lagrange minimization
 lagrange_data = lg.lagrange(it_num, datadir, doprint, lambdacorr_data)
 
 # Time / speed testing for lagrange.py
 if times:
     fin = time.time()
     elapsed = fin - ini
     print("lagrange" + str(it_num).rjust(4) + " :      " + str(elapsed))    
   
 # Print for debugging purposes
 if doprint:
     printout('Iteration %d Lagrange complete. Starting lambda correction...', it_num)
 
 # Take final x_i mole numbers from last Lagrange calculation 
 lagrange_x = lagrange_data[4]
 
 # Check if x_i have negative mole numbers, and if yes perform lambda correction
 if where((lagrange_x < 0) == True)[0].size != 0:
     # Print for debugging purposes 
     if doprint:
         printout('Correction required. Initializing...')
         
     # Time / speed testing for lambdacorr.py
     if times:
         ini = time.time()
     
     # Execute lambda correction
示例#5
0
文件: iterate.py 项目: pcubillos/TEA
def iterate(pressure,
            a,
            b,
            g_RT,
            maxiter,
            verb,
            times,
            guess,
            xtol=1e-8,
            save_info=None):
    """
    Run iterative Lagrangian minimization and lambda correction.

    Parameters
    ----------
    pressure: Float
          Atmospheric pressure (bar).
    a: 2D float ndarray
          Species stoichiometric coefficients.
    b: 1D float ndarray
          Elemental mixing fractions.
    g_RT: 1D float ndarray
          Species chemical potentials.
    maxiter: Integer
          Maximum number of iterations.
    verb: Integer
          Verbosity level (0=mute, 1=quiet, 2=verbose).
    times: Bool
          If True, track excecution times.
    guess: 1D list
          A two-element list with input guess values for x and x_bar.
    xtol: Float
          Error between iterations that is acceptable for convergence.
          The routine has converged when the sum of the relative improvement
          per species becomes less than xtol, i.e.:
         sum(abs((y-x)/y)) / len(x) <= xtol.
    save_info: List of stuff
          If not None, save info to files.  The list contains:
           [location_out, desc, speclist, temp]

    Returns
    -------
    y: float array
          Input guess of molecular species.
    x: float array
          Final mole numbers of molecular species.
    delta: float array
          Array containing change in initial and final mole numbers of
          molecular species for current iteration.
    y_bar: float
          Array containing total sum of initial guesses of all molecular
          species for current iteration.
    x_bar: float
          Total sum of the final mole numbers of all molecular species.
    delta_bar: float
          Change in total of initial and final mole numbers of molecular
          species.
    """

    # Retrieve header info
    i, j = np.shape(a)

    # Retrieve and set initial values
    x, x_bar = guess

    # Prepare data object for iterative process
    #         (see description of the 'input' object in lagrange.py)
    lc_data = x, x, 0, x_bar, x_bar, 0
    info = pressure, i, j, a, b, g_RT

    # ====================== PERFORM MAIN TEA LOOP ====================== #
    it_num = 1
    while it_num <= maxiter:
        # Output iteration number
        if verb >= 1 and (it_num % 10) == 0:
            stdout.write(' {:d}\r'.format(it_num))
            stdout.flush()

        # Time / speed testing for lagrange.py
        if times:
            ini = time.time()

        # Execute Lagrange minimization:
        lc_data = lg.lagrange(it_num, verb, lc_data, info, save_info)

        # Time / speed testing for lagrange.py
        if times:
            fin = time.time()
            elapsed = fin - ini
            print("lagrange {:>4d}:  {:f} s.".format(it_num, elapsed))

        # Print for debugging purposes
        if verb > 1:
            printout("Iteration {:d} Lagrange complete.  Starting lambda "
                     "correction...".format(it_num))

        # Check if x_i have negative mole numbers, if so, do lambda correction
        if np.any(lc_data[1] < 0):
            # Print for debugging purposes
            if verb > 1:
                printout('Correction required. Initializing...')

            # Time / speed testing for lambdacorr.py
            if times:
                ini = time.time()

            # Execute lambda correction
            lc_data = lc.lambdacorr(it_num, verb, lc_data, info, save_info)

            # Print for debugging purposes
            if times:
                fin = time.time()
                elapsed = fin - ini
                print("lambcorr {:>4d}:  {:f} s.".format(it_num, elapsed))

            # Print for debugging purposes
            if verb > 1:
                printout("Iteration {:d} lambda correction complete.  "
                         "Checking precision...".format(it_num))

        # Lambda correction is not needed
        else:
            # Print for debugging purposes
            if verb > 1:
                printout(
                    'Iteration {:d} did not need lambda correction.'.format(
                        it_num))

        # Check the tolerance
        xdiff = (lc_data[1] / lc_data[4]) / (lc_data[0] / lc_data[3]) - 1
        if np.sum(np.abs(xdiff)) / len(xdiff) <= xtol:
            if verb >= 1:
                stdout.write(' {:d}\r'.format(it_num))
                printout(
                    "The solution has converged to the given tolerance error.\n"
                )
            break

        it_num += 1
        # If max iteration not met, continue with next iteration cycle
        if verb > 1:
            printout('Max interation not met. Starting next iteration...\n')

    # ============== Stop the loop, max iteration reached ============== #

    # Stop if max iteration is reached
    if verb >= 1 and it_num == maxiter + 1:
        printout('Maximum iteration reached, ending minimization.\n')

    # Retrieve most recent iteration values
    input_new = lc_data

    # Take most recent x_i and x_bar values
    x_new = input_new[1]
    x_bar_new = input_new[4]

    # Calculate delta values
    delta = x_new - x

    # Calculate delta_bar values
    delta_bar = x_bar_new - x_bar

    if save_info is not None:
        location_out, desc, speclist, temp = save_info
        hfolder = location_out + desc + "/headers/"
        headerfile = "{:s}/header_{:s}_{:.0f}K_{:.2e}bar.txt".format(
            hfolder, desc, temp, pressure)

        # Create and name outputs and results directories if they do not exist
        datadirr = '{:s}{:s}/results/results_{:.0f}K_{:.2e}bar'.format(
            location_out, desc, temp, pressure)
        if not os.path.exists(datadirr):
            os.makedirs(datadirr)

        # Export all values into machine and human readable output files
        file = "{:s}/results-machine-read.txt".format(datadirr)
        form.output(headerfile, it_num, speclist, x, x_new, delta, x_bar,
                    x_bar_new, delta_bar, file, verb)
        file = "{:s}/results-visual.txt".format(datadirr)
        form.fancyout_results(headerfile, it_num, speclist, x, x_new, delta,
                              x_bar, x_bar_new, delta_bar, pressure, temp,
                              file, verb)

    return input_new