Example #1
0
def get_error(solution_object, args):
    """Get error from comparison between ignition delay for detailed and
        skeletal models. Uses tau array from detailed simulations, and makes
        new array of ignition delays from the reduced mechanism.

    Parameters
    ----------
    solution_object : obj
        Cantera solution object
    args : obj
        Terminal arguments
    """
    args.initial_sim = False
    print 'triggered'
    if args.tau_array:
        detailed_tau_array = args.tau_array
        error_array = []
        for index, initial_condition in enumerate(args.initial_temperature_array):
            tau_detailed = detailed_tau_array[index]
            args.Temp = initial_condition
            try:
                solution_result = autoignition_loop_control(solution_object, args)
                tau_skeletal = solution_result.tau
                error_array.append(float((abs((tau_detailed-tau_skeletal)/tau_detailed))*100.0))
            except Exception:
                tau_skeletal = 0.0
                error_array.append(0.0)

        print np.max(error_array)
        print 'Error: %s%%' %"{0:.2f}"''.format(max(error_array))
    else:
        tau_detailed = args.tau
        solution_result = autoignition_loop_control(solution_object, args)
        tau_skeletal = solution_result.tau
        error = float((abs((tau_detailed-tau_skeletal)/tau_detailed))*100.0)
        print 'Error: %s%%' %"{0:.2f}"''.format(max(error))
Example #2
0
def readin(args='none', **argv):
    """Main function for pyMARS

    Parameters
    ----------
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    write_ai_times:
        write autoignition times for each inital condition
    run_drg:
        Run DRG model reduction
    run_drgep:
	Run drgep model.
    error:
	Maximum ammount of error allowed. 
    keepers: list of strings
	The string names of the species that should be kept in the model no matter what.
    targets: list of strings
	The string names of the species that should be used as target species.

    Returns
    -------
        Converted mechanism file
        Trimmed Solution Object
        Trimmed Mechanism file

    Examples
    --------
    readin(file='gri30.cti', plot='y', species='OH, H')
    """
    class args():

        #package from terminal use case
        if args is not 'none':
            plot = args.plot
            points = args.points
            writecsv = True
            writehdf5 = True
            data_file = args.file
            thermo_file = args.thermo
            transport_file = args.transport
            run_drg = args.run_drg
            conditions_file = args.conditions
            convert = args.convert
            error = args.error
            run_drgep = args.run_drgep
            write_ai_times = args.write_ai_times
            target = 0
            if args.species is None:
                keepers = []
            else:
                keepers = [str(item) for item in args.species.split(',')]
                #strip spaces
                for i, sp in enumerate(keepers):
                    keepers[i] = sp.strip()
            if args.target is None:
                target = []
            else:
                target = [str(item) for item in args.target.split(',')]
                #strip spaces
                for i, sp in enumerate(target):
                    target[i] = sp.strip()

    file_extension = os.path.splitext(args.data_file)[1]

    if file_extension == ".cti" or file_extension == ".xml":  #If the file is a Cantera file.
        print("\nThis is a Cantera xml or cti file\n")
        solution_object = ct.Solution(args.data_file)

        #runs simulation once with additional features on
        if args.plot is True or args.writecsv is True or args.points is True or args.writehdf5 is True or args.write_ai_times is True:
            if os.path.exists('mass_fractions.hdf5'):
                os.system('rm mass_fractions.hdf5')
            if args.write_ai_times is True:
                if os.path.exists('autoignition_times.txt'):
                    os.system('rm autoignition_times.txt')
            print 'running simulation\n'
            sim_result = autoignition_loop_control(solution_object, args, True)

        if args.run_drg is True:
            run_drg(args, solution_object)

        if args.convert is True:
            soln2ck.write(solution_object)

        if args.run_drgep is True:  #If the user wants to run drgep and specifies it as a command line argument.
            run_drgep(args, solution_object)

    elif file_extension == ".inp" or file_extension == ".dat" or file_extension == ".txt":
        print("\n\nThis is a Chemkin file")
        #convert file to cti
        converted_file_name = convert(args.data_file, args.thermo_file,
                                      args.transport_file)

    else:
        print("\n\nFile type not supported")
Example #3
0
def readin(args='none', **argv):
    """Main function for pyMARS

    Parameters
    ----------
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    run_drg:
        Run DRG model reduction

    Returns
    -------
        Converted mechanism file
        Trimmed Solution Object
        Trimmed Mechanism file

    Examples
    --------
    readin(file='gri30.cti', plot='y', species='OH, H')
    """
    class args():

        #package from terminal use case
        if args is not 'none':
            plot = args.plot
            points = args.points
            writecsv = args.writecsv
            writehdf5 = args.writehdf5
            data_file = args.file
            thermo_file = args.thermo
            transport_file = args.transport
            run_drg = args.run_drg
            threshold_values = args.thresholds
            conditions_file = args.conditions
            convert = args.convert
            if args.species is None:
                exclusion_list = []
            else:
                exclusion_list = [
                    str(item) for item in args.species.split(',')
                ]
                #strip spaces
                for i, sp in enumerate(exclusion_list):
                    exclusion_list[i] = sp.strip()

    file_extension = os.path.splitext(args.data_file)[1]

    if file_extension == ".cti" or file_extension == ".xml":
        print("\nThis is an Cantera xml or cti file\n")
        solution_object = ct.Solution(args.data_file)
        if args.plot is True or args.writecsv is True or args.points is True or args.writehdf5 is True:
            print 'running sim'
            sim_result = autoignition_loop_control(solution_object, args)
        if args.run_drg is True:
            new_solution_objects = drg_loop_control(solution_object, args)
            os.system('rm production_rates.hdf5')
            os.system('rm mass_fractions.hdf5')
            drg_trimmed_file = soln2cti.write(new_solution_objects[1])
            try:
                os.system('rm production_rates.hdf5')
            except Exception:
                pass
        if args.convert is True:
            soln2ck.write(solution_object)

    elif file_extension == ".inp" or file_extension == ".dat" or file_extension == ".txt":
        print("\n\nThis is a Chemkin file")
        #convert file to cti
        converted_file_name = convert(args.data_file, args.thermo_file,
                                      args.transport_file)

    else:
        print("\n\nFile type not supported")
Example #4
0
def drgep_loop_control(solution_object, args, stored_error, threshold, done,
                       max_dic):
    """ Controls the trimming and error calculation of a solution with the graph already created using the DRGEP method.   

        Parameters
        ----------
        solution_object : obj
            Cantera solution object
        args : obj
            function arguments object
	stored_error: float singleton
	    The error introduced by the last simulation (to be replaced with this simulation).
	done: singleton
	    a singleton boolean value that represnts wether or not more species can be excluded from the graph or not. 
	max_dic: dictionary  
	    a dictionary keyed by species name that represents the species importance to the model.  

        Returns
        -------
        new_solution_objects : obj
            Cantera solution object That has been reduced.  
        """

    target_species = args.target

    try:
        os.system('rm mass_fractions.hdf5')
    except Exception:
        pass

    #run detailed mechanism and retain initial conditions
    detailed_result = autoignition_loop_control(solution_object,
                                                args)  #Run simulation
    detailed_result.test.close()
    ignition_delay_detailed = np.array(detailed_result.tau_array)
    species_retained = []
    printout = ''
    print 'Threshold     Species in Mech      Error'

    try:
        os.system('rm mass_fractions.hdf5')
    except Exception:
        pass

    #run DRGEP and create new reduced solution
    drgep = trim_drgep(max_dic, solution_object, threshold, args.keepers,
                       done)  #Find out what to cut from the model
    exclusion_list = drgep
    new_solution_objects = trim(
        solution_object, exclusion_list,
        args.data_file)  #Cut the exclusion list from the model.
    species_retained.append(len(new_solution_objects[1].species()))

    #simulated reduced solution
    reduced_result = autoignition_loop_control(
        new_solution_objects[1], args)  #Run simulation on reduced model
    if (reduced_result == 0):
        stored_error[0] = 100
        error = 100
        printout += str(threshold) + '                 ' + str(
            len(new_solution_objects[1].species())) + '              ' + str(
                round(np.max(error), 2)) + '%' + '\n'
        print printout
        return new_solution_objects
    reduced_result.test.close()
    ignition_delay_reduced = np.array(reduced_result.tau_array)

    #Calculate and print error.
    error = (abs(ignition_delay_reduced - ignition_delay_detailed) /
             ignition_delay_detailed) * 100  #Calculate error
    printout += str(threshold) + '                 ' + str(
        len(new_solution_objects[1].species())) + '              ' + str(
            round(np.max(error), 2)) + '%' + '\n'
    print printout
    stored_error[0] = round(np.max(error), 2)

    #Return new model
    new_solution_objects = new_solution_objects[1]
    return new_solution_objects
Example #5
0
def readin(args='none', **argv):
    """Main function for pyMARS

    Parameters
    ----------
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    run_drg:
        Run DRG model reduction

    Returns
    -------
        Converted mechanism file
        Trimmed Solution Object
        Trimmed Mechanism file

    Examples
    --------
    readin(file='gri30.cti', plot='y', species='OH, H')
    """

    class args():

        #package from terminal use case
        if args is not 'none':
            plot = args.plot
            points = args.points
            writecsv = args.writecsv
            writehdf5 = args.writehdf5
            data_file= args.file
            thermo_file = args.thermo
            transport_file = args.transport
            run_drg = args.run_drg
            threshold_values = args.thresholds
            conditions_file = args.conditions
            convert = args.convert
            if args.species is None:
                exclusion_list = []
            else:
                exclusion_list = [str(item) for item in args.species.split(',')]
                #strip spaces
                for i, sp in enumerate(exclusion_list):
                    exclusion_list[i]=sp.strip()

    file_extension= os.path.splitext(args.data_file)[1]

    if file_extension == ".cti" or file_extension == ".xml":
        print("\nThis is an Cantera xml or cti file\n")
        solution_object = ct.Solution(args.data_file)
        if args.plot is True or args.writecsv is True or args.points is True or args.writehdf5 is True:
            print 'running sim'
            sim_result = autoignition_loop_control(solution_object, args)
        if args.run_drg is True:
            new_solution_objects = drg_loop_control(solution_object, args)
            os.system('rm production_rates.hdf5')
            os.system('rm mass_fractions.hdf5')
            drg_trimmed_file = soln2cti.write(new_solution_objects[1])
            try:
                os.system('rm production_rates.hdf5')
            except Exception:
                pass
        if args.convert is True:
            soln2ck.write(solution_object)


    elif file_extension == ".inp" or file_extension == ".dat" or file_extension == ".txt":
        print("\n\nThis is a Chemkin file")
        #convert file to cti
        converted_file_name = convert(args.data_file, args.thermo_file, args.transport_file)

    else:
        print("\n\nFile type not supported")
Example #6
0
def run_drgep(args, solution_object):
    """
    Function to run the drgep method for model reduction

    Parameters
    ----------
    solution_object: ct._Solutuion object
	An object that represents the solution to be trimmed. 
    args: args object
	An object that contains the following:
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    run_drg:
        Run DRG model reduction
    run_drgep:
	Run drgep model.
    error:
	Maximum ammount of error allowed. 
    keepers: list of strings
	The string names of the species that should be kept in the model no matter what.
    targets: list of strings
	The string names of the species that should be used as target species.

	"""

    #Set up variables
    if len(args.target
           ) == 0:  #If the target species are not specified, puke and die.
        print "Please specify a target species."
        exit()
    done = [
    ]  #Singleton to hold wether or not any more species can be cut from the simulation.
    done.append(False)
    threshold = .1  #Starting threshold value
    threshold_i = .1
    error = [
        10.0
    ]  #Singleton to hold the error value of the previously ran simulation.

    try:
        os.system('rm mass_fractions.hdf5')
    except Exception:
        pass

#Find overall interaction coefficients.
    detailed_result = autoignition_loop_control(
        solution_object, args
    )  #The simulation needs to be ran to make the mass_fractions file which has the info to calucalte edge weights I think?
    detailed_result.test.close()
    ignition_delay_detailed = np.array(detailed_result.tau_array)
    rate_edge_data = get_rates(
        'mass_fractions.hdf5',
        solution_object)  #Get edge weight calculation data.
    max_dic = make_dic_drgep(
        solution_object, rate_edge_data,
        args.target)  #Make a dictionary of overall interaction coefficients.

    print "Testing for starting threshold value"
    drgep_loop_control(
        solution_object, args, error, threshold, done,
        max_dic)  #Trim the solution at that threshold and find the error.
    while error[
            0] != 0:  #While the error for trimming with that threshold value is greater than allowed.
        threshold = threshold / 10  #Reduce the starting threshold value and try again.
        threshold_i = threshold_i / 10
        drgep_loop_control(solution_object, args, error, threshold, done,
                           max_dic)

    print("Starting with a threshold value of " + str(threshold))
    sol_new = solution_object
    past = 0  #An integer representing the error introduced in the past simulation.
    done[0] = False

    while not done[0] and error[
            0] < args.error:  #Run the simulation until nothing else can be cut.
        sol_new = drgep_loop_control(
            solution_object, args, error, threshold, done,
            max_dic)  #Trim at this threshold value and calculate error.
        if args.error > error[
                0]:  #If a new max species cut without exceeding what is allowed is reached, save that threshold.
            max_t = threshold

#if (past == error[0]): #If error wasn't increased, increase the threshold at a higher rate.
    #	threshold = threshold + (threshold_i * 4)
        past = error[0]
        #if (threshold >= .01):
        #        threshold_i = .01
        threshold = threshold + threshold_i

    print "\nGreatest result: "
    sol_new = drgep_loop_control(solution_object, args, error, max_t, done,
                                 max_dic)
    if os.path.exsists("production_rates.hdf5"):
        os.system('rm production_rates.hdf5')
    if os.path.exsists('mass_fractions.hdf5'):
        os.system('rm mass_fractions.hdf5')
    drgep_trimmed_file = soln2cti.write(
        sol_new
    )  #Write the solution object with the greatest error that isn't over the allowed ammount.

    try:
        os.system('rm production_rates.hdf5')
    except Exception:
        pass
Example #7
0
def drg_loop_control(solution_object, args):
    """ Controls repeated use of drg Function

        Parameters
        ----------
        solution_object : obj
            Cantera solution object
        args : obj
            function arguments object

        Returns
        -------
        new_solution_objects : obj
            Cantera solution object with skeletal mechanism
        """
    #get user input
    target_species = raw_input('\nEnter target starting species: ').split(',')

    #run detailed mechanism and retain initial conditions
    args.multiple_conditions = True
    detailed_result = autoignition_loop_control(solution_object, args)
    detailed_result.test.close()
    ignition_delay_detailed = np.array(detailed_result.tau_array)
    #--------------------------
    #get-rate data called here
    #--------------------------
    rate_edge_data = get_rates('mass_fractions.hdf5', solution_object)
    if args.threshold_values is None:
        try:
            threshold = float(raw_input('Enter threshold value: '))
        except ValueError:
            print 'try again'
            threshold = float(raw_input('Enter threshold value: '))

        #run DRG and create new reduced solution
        drg = make_graph(solution_object, 'production_rates.hdf5', threshold)
        exclusion_list = graph_search(solution_object, drg, target_species)
        new_solution_objects = trim(solution_object, exclusion_list, args.data_file)

        #simulate reduced solution
        reduced_result = autoignition_loop_control(new_solution_objects[1], args)
        reduced_result.test.close()
        ignition_delay_reduced = np.array(reduced_result.tau_array)
        error = (abs(ignition_delay_reduced-ignition_delay_detailed)/ignition_delay_detailed)*100
        print 'Error index: %s' %error
        #get_error()
        n_species_retained = len(new_solution_objects[1].species())
        print 'Number of species in reduced model: %s' %n_species_retained
        try:
            os.system('rm mass_fractions.hdf5')
        except Exception:
            pass
    else:
        threshold_values = genfromtxt(args.threshold_values, delimiter=',')
        species_retained = []
        printout = ''
        print 'Threshold     Species in Mech      Error'
        print 'flag'
        try:
            os.system('rm mass_fractions.hdf5')
        except Exception:
            pass

        if threshold_values.size > 1:
            for threshold in threshold_values:
                #run DRG and create new reduced solution
                drg = make_graph(solution_object, threshold, rate_edge_data, target_species)
                #exclusion_list = graph_search(solution_object, drg, target_species)
                exclusion_list = drg
                new_solution_objects = trim(solution_object, exclusion_list, args.data_file)
                species_retained.append(len(new_solution_objects[1].species()))
                try:
                    os.system('rm mass_fractions.hdf5')
                except Exception:
                    pass
                #simulated reduced solution
                reduced_result = autoignition_loop_control(new_solution_objects[1], args)
                reduced_result.test.close()
                ignition_delay_reduced = np.array(reduced_result.tau_array)
                error = (abs(ignition_delay_reduced-ignition_delay_detailed)/ignition_delay_detailed)*100
                printout += str(threshold) + '                 ' + str(len(new_solution_objects[1].species())) + '              '+  str(round(np.max(error), 2))+'%' + '\n'
                print printout

        else:

            #run DRG and create new reduced solution
            drg = make_graph(solution_object, threshold_values, rate_edge_data, target_species)
            #exclusion_list = graph_search(solution_object, drg, target_species)
            exclusion_list = drg
            new_solution_objects = trim(solution_object, exclusion_list, args.data_file)
            species_retained.append(len(new_solution_objects[1].species()))

            #simulated reduced solution
            reduced_result = autoignition_loop_control(new_solution_objects[1], args)
            reduced_result.test.close()
            ignition_delay_reduced = np.array(reduced_result.tau_array)
            error = (abs(ignition_delay_reduced-ignition_delay_detailed)/ignition_delay_detailed)*100
            printout += str(threshold_values) + '                 ' + str(len(new_solution_objects[1].species())) + '              '+  str(round(np.max(error), 2)) +'%' + '\n'
            print printout
        # print 'Detailed soln ign delay:'
        # print ignition_delay_detailed
        # print 'Reduced soln ign delay:'
        # print ignition_delay_reduced
    return new_solution_objects