Beispiel #1
0
def plot_raw():

    fld_prj = find_fld_prj(mech)
    d = "0.142"
    case = "U69_d" + d + "cm"
    fld_raw = os.path.join(fld_prj, "detailed", "raw", "[syngas] + [air]",
                           "DNS", "phi1.0_1.0atm_500.0K", case)
    path_npz = os.path.join(fld_raw, "raw.npz")
    raw = load_raw(path_npz)

    #plt.plot(raw["axis0"], raw["temperature"])
    plt.plot(raw["axis0"], raw["mole_fraction"][:, 0])
    plt.show()
Beispiel #2
0
def run_GPSA(parent, progress):
    if not run_graph(parent, progress, 'GPSA'):
        return False

    min_dT = parent.min_dT

    dir_public = parent.project['dir_public']
    soln = parent.soln['detailed']

    list_train = []
    train_name = parent.train_name
    for db_name in parent.project['database'].keys():
        if parent.project['database'][db_name]['train']:
            list_train.append(db_name)

    list_GPS = []
    for GPS_name in parent.project['GPS'].keys():
        if parent.project['GPS'][GPS_name]['checked']:
            list_GPS.append(GPS_name)

    if bool(list_GPS):

        # for different GPS settings ============================
        # add new GP

        print('run_GPSA: here0')
        for GPS_name in list_GPS:

            GPS = parent.project['GPS'][GPS_name]
            alpha_list = GPS['alpha']
            beta_list = GPS['beta']
            K_list = GPS['K']

            es_name = GPS['es']
            es = parent.project['es'][es_name]
            traced_list = []
            for e in es['element'].keys():
                if es['element'][e]['traced']:
                    traced_list.append(e)

            if GPS['iso_enable']:
                iso_name = GPS['iso']
                iso = parent.project['iso'][iso_name]
                gamma_list = GPS['gamma']
            else:
                iso_name = None
                iso = None
                gamma_list = [None]

            n_GP = 0
            for K in K_list:
                for beta in beta_list:
                    for alpha in alpha_list:
                        for gamma in gamma_list:

                            dir_sk = para2dir_GPS(dir_public, train_name, \
                                alpha=alpha, K=K, beta=beta, \
                                es_name=es_name, iso_name=iso_name, \
                                d=parent.n_digit, gamma=gamma)

                            dir_how = os.path.join(dir_sk, 'how')
                            print('[GPSA] checking dir_how: ' + str(dir_how))
                            if not os.path.exists(dir_how):
                                continue

                            for fo in os.listdir(dir_how):
                                dir_fo = os.path.join(dir_how, fo)
                                if ('+' not in fo) or (
                                        not os.path.isdir(dir_fo)):
                                    continue
                                for reactor in os.listdir(dir_fo):
                                    dir_reactor = os.path.join(dir_fo, reactor)
                                    if (not os.path.isdir(dir_reactor)):
                                        continue
                                    for fat in os.listdir(dir_reactor):
                                        dir_fat = os.path.join(
                                            dir_reactor, fat)
                                        if ('phi' not in fat) or (
                                                not os.path.isdir(dir_fat)):
                                            continue
                                        if reactor == 'DNS':
                                            dir_fat = dir_fat + '/' + os.listdir(
                                                dir_fat)[0]
                                        print('[GPSA] checking dir_fat: ' +
                                              str(dir_fat))
                                        for file in os.listdir(dir_fat):
                                            if 'graph' not in file: continue
                                            file_GP = os.path.join(
                                                dir_fat, file)
                                            traced = file.split(
                                                ',')[1].replace(
                                                    'graph',
                                                    '').strip().upper()
                                            GP_traced = 'GP_' + traced
                                            if GP_traced not in parent.project.keys(
                                            ):
                                                parent.project[
                                                    GP_traced] = dict()
                                            GPS_results = json.load(
                                                open(file_GP, 'r'))
                                            for GP_name in GPS_results[
                                                    'global_path'].keys():
                                                if GP_name not in parent.project[
                                                        GP_traced].keys():

                                                    GP_dict = dict()
                                                    GP_dict['alias'] = GP_name
                                                    GP_dict['name'] = GP_name
                                                    GP_dict[
                                                        'member'] = GPS_results[
                                                            'global_path'][
                                                                GP_name][
                                                                    'member']
                                                    GP_dict['traced'] = traced
                                                    parent.project[GP_traced][
                                                        GP_name] = GP_dict

                                                    print(
                                                        'added ' + traced +
                                                        '-traced global pathway: '
                                                        + str(GP_name))

    print('run_GPSA: here1')
    # find all GP ==============================
    GP_list = []

    filter_traced = str(parent.w.cb_GPSA_traced.currentText())
    print('filter_traced = ' + str(filter_traced))
    if filter_traced == 'no filter':
        ee = parent.soln['detailed'].element_names
    else:
        ee = [filter_traced]

    alias_only = (str(
        parent.w.cb_GPSA_alias.currentText()) == 'with alias only')

    source_str = str(parent.w.cb_GPSA_source.currentText())
    if source_str == 'no filter':
        sources = parent.soln['detailed'].species_names
    else:
        sources = [source_str]

    for traced in ee:
        traced = traced.upper()
        if 'GP_' + traced in parent.project.keys():
            for GP_name in parent.project['GP_' + traced].keys():
                GP_dir = parent.project['GP_' + traced][GP_name]
                if GP_dir['member'][0] not in sources:
                    continue
                if (not alias_only) or (alias_only and
                                        (GP_dir['alias'] != GP_name)):
                    GP_list.append((traced, GP_name))

    if not bool(GP_list):
        msg = 'GP_list is empty!\nTry to run GPS first or loose GPSA settings'
        QMessageBox.information(QWidget(), '', msg)
        return False

    print('len(GP_list) = ' + str(len(GP_list)))

    # for different training set ============================
    # to compute GPSA quantities

    dir_desk = parent.project['mech']['detailed']['desk']
    path_R_npz = os.path.join(dir_desk, 'mech', 'radical.npz')
    dnR = load_dR(path_R_npz, soln)
    soln = parent.soln['detailed']

    v = 0.0
    dv_db = 100.0 / len(list_train)
    for db_name in list_train:

        database = parent.project['database'][db_name]
        phi_list = database['phi']
        T0_list = database['T0']
        atm_list = database['atm']
        fuel_list = database['fuel']
        oxid_list = database['oxid']
        reactor = database['reactor']

        dv_raw = 1.0 * dv_db / (len(phi_list) * len(atm_list) * len(T0_list) *
                                len(fuel_list) * len(oxid_list))
        dv_GP = 1.0 * dv_raw / len(GP_list)

        for fuel_name in fuel_list:
            for oxid_name in oxid_list:
                for phi in phi_list:
                    for atm in atm_list:
                        for T0 in T0_list:

                            if progress.stop:
                                progress.close()
                                return False

                            fuel = parent.project['fuel'][fuel_name]
                            oxid = parent.project['oxid'][oxid_name]

                            fuel_comp = parent.project['fuel'][fuel_name][
                                'composition']

                            dir_de = os.path.join(dir_public, 'detailed')
                            dir_raw = cond2dir(dir_de, fuel_name, \
                             oxid_name, phi, atm, T0, \
                             reactor, parent.n_digit)
                            if 'DNS' in reactor:
                                dir_raw = os.path.join(dir_raw,
                                                       database['case'][0])
                                raw = load_raw(os.path.join(
                                    dir_raw, 'raw.npz'))
                                n_break = len(raw['axis0'])
                            else:
                                n_break = 0

                            dir_graph = os.path.join(dir_raw, 'graph')
                            no_graph = True
                            if os.path.exists(dir_graph):
                                for file in os.listdir(dir_graph):
                                    if file.endswith('.json'):
                                        no_graph = False
                                        break
                            if no_graph:
                                msg = 'no graph file found for: \n\n' + str(
                                    dir_raw.replace(dir_public,
                                                    '[working dir]'))
                                QMessageBox.information(QWidget(), '', msg)
                                return False

                            progress.set_info(str(dir_raw))

                            for traced, GP_name in GP_list:
                                msg = ' ' * 4 + 'computing GPSA for ' + str(
                                    GP_name)
                                print(msg)
                                progress.set_info(msg)
                                GP_dir = parent.project['GP_' +
                                                        traced][GP_name]
                                find_GPSA(dir_raw, GP_dir, soln, dnR,
                                          fuel_comp, n_break)

                                v += dv_GP
                                progress.set_value('GPSA', v)

    return True
Beispiel #3
0
def run_GPS(parent, progress):
    if not run_graph(parent, progress, 'GPS'):
        return False

    min_dT = parent.min_dT

    dir_public = parent.project['dir_public']
    soln = parent.soln['detailed']

    list_train = []
    train_name = parent.train_name
    for db_name in parent.project['database'].keys():
        if parent.project['database'][db_name]['train']:
            list_train.append(db_name)

    list_GPS = []
    for GPS_name in parent.project['GPS'].keys():
        if parent.project['GPS'][GPS_name]['checked']:
            list_GPS.append(GPS_name)

    v = 0
    if bool(list_GPS) == False:
        return False
    dv_GPS = 100.0 / len(list_GPS)

    # for different GPS settings ============================

    for GPS_name in list_GPS:

        GPS = parent.project['GPS'][GPS_name]
        alpha_list = GPS['alpha']
        beta_list = GPS['beta']
        K_list = GPS['K']
        must_keep = GPS['must_keep']

        es_name = GPS['es']
        es = parent.project['es'][es_name]
        traced_list = []
        for e in es['element'].keys():
            if es['element'][e]['traced']:
                traced_list.append(e)

        if GPS['iso_enable']:
            iso_name = GPS['iso']
            iso = parent.project['iso'][iso_name]
            gamma_list = GPS['gamma']
        else:
            iso_name = None
            iso = None
            gamma_list = [None]

        dv_kab = 1.0 * dv_GPS / (len(K_list) * len(beta_list) *
                                 len(alpha_list) * len(gamma_list))

        for K in K_list:
            for beta in beta_list:
                for alpha in alpha_list:
                    for gamma in gamma_list:


                        dir_sk = para2dir_GPS(dir_public, train_name, \
                            alpha=alpha, K=K, beta=beta, \
                            es_name=es_name, iso_name=iso_name, \
                            d=parent.n_digit, gamma=gamma)

                        progress.set_info('\n' + '-' * 10 + dir_sk + ' ' +
                                          '-' * 10)

                        dir_mech_sk = os.path.join(dir_sk, 'mech')
                        path_cti_sk = os.path.join(dir_mech_sk, 'chem.cti')

                        if os.path.exists(path_cti_sk):
                            progress.set_info('<already exists, skipped> ' +
                                              path_cti_sk)
                            v += dv_kab
                            progress.set_value('GPS', v)
                            continue

                        dir_de = os.path.join(dir_public, 'detailed')
                        dir_mech_de = os.path.join(dir_de, 'mech')
                        path_cti_de = os.path.join(dir_mech_de, 'chem.cti')

                        species_kept = set(must_keep)

                        notes = ['! generated by global pathway selection, Gao et al,'+\
                         ' Combustion and flame, 167 (2016) 238-247']
                        notes.append('! alpha = ' + str(alpha) + ', K = ' + str(K) + \
                         ', beta = ' + str(beta))
                        notes.append('! training database: ' + train_name)

                        # for different training database ============================

                        dv_db = 1.0 * dv_kab / len(list_train)

                        for db_name in list_train:

                            database = parent.project['database'][db_name]
                            phi_list = database['phi']
                            T0_list = database['T0']
                            atm_list = database['atm']
                            fuel_list = database['fuel']
                            oxid_list = database['oxid']
                            reactor = database['reactor']

                            dv_raw = 1.0 * dv_db / (len(phi_list) * len(atm_list) * len(T0_list) *\
                             len(fuel_list) * len(oxid_list))

                            for fuel_name in fuel_list:
                                for oxid_name in oxid_list:
                                    for phi in phi_list:
                                        for atm in atm_list:
                                            for T0 in T0_list:

                                                if progress.stop:
                                                    progress.close()
                                                    return False

                                                fuel = parent.project['fuel'][
                                                    fuel_name]
                                                oxid = parent.project['oxid'][
                                                    oxid_name]
                                                species_kept |= set(
                                                    fuel['composition'].keys())
                                                species_kept |= set(
                                                    oxid['composition'].keys())

                                                e_available = set()
                                                for sp in fuel[
                                                        'composition'].keys():
                                                    e_available |= set(
                                                        soln.species(sp).
                                                        composition.keys())
                                                for sp in oxid[
                                                        'composition'].keys():
                                                    e_available |= set(
                                                        soln.species(sp).
                                                        composition.keys())



                                                dir_raw = cond2dir(dir_de, fuel_name, \
                                                 oxid_name, phi, atm, T0, \
                                                 reactor, parent.n_digit)
                                                if 'DNS' in reactor:
                                                    dir_raw = os.path.join(
                                                        dir_raw,
                                                        database['case'][0])

                                                progress.set_info('raw = '+\
                                                 dir_raw.replace(os.path.join(dir_de,'raw'),'').strip('/'))

                                                dir_graph = os.path.join(
                                                    dir_raw, 'graph')

                                                #raw_name = dir_raw.replace(\
                                                #	os.path.join(dir_de,'raw'),'').strip('/')

                                                raw_name = cond2dir('', fuel_name, \
                                                 oxid_name, phi, atm, T0, \
                                                 reactor, parent.n_digit)

                                                if 'DNS' in reactor:
                                                    raw_name += '/' + database[
                                                        'case'][0]

                                                dir_how = os.path.join(
                                                    dir_sk,
                                                    raw_name.replace(
                                                        'raw', 'how'))

                                                if not os.path.exists(dir_how):
                                                    os.makedirs(dir_how)

                                                raw = load_raw(
                                                    os.path.join(
                                                        dir_raw, 'raw.npz'))
                                                T = raw['temperature']
                                                axis0 = raw['axis0']

                                                # for different time instance ================

                                                flag = False
                                                # -----------------------------------------------
                                                # I only consider the points where T and T0 has
                                                # some difference, which means there're reactions
                                                # performing GPS on chemically frozen state, or
                                                # equilibirum state (for PSR), does not give too
                                                # much useful information
                                                #
                                                # once a point is sampled, flag = True
                                                # -----------------------------------------------

                                                dv_pnt = 1.0 * dv_raw / len(T)
                                                for i_pnt in range(len(T)):
                                                    """
													if 'active reactions' in raw.keys():
														if raw['active reactions'][i_pnt] == 0:
															print 'skipped pnt '+str(i_pnt)+' as no active reaction'
															continue
															"""

                                                    if flag == False:
                                                        if abs(T[i_pnt] -
                                                               T[0]) > min_dT:
                                                            flag = True

                                                    # for different source->target ==============

                                                    for e in traced_list:

                                                        if e not in e_available:
                                                            continue

                                                        sources = copy.copy(
                                                            es['element'][e]
                                                            ['source'])

                                                        if bool(sources
                                                                ) == False:
                                                            sources = [None]
                                                        if parent.alias_fuel in sources:
                                                            del sources[
                                                                sources.index(
                                                                    parent.
                                                                    alias_fuel
                                                                )]

                                                            for sp in fuel[
                                                                    'composition'].keys(
                                                                    ):
                                                                atoms = soln.species(
                                                                    sp
                                                                ).composition.keys(
                                                                )
                                                                #print 'atms of ' + sp + ' = ' +str(atoms)
                                                                if e in atoms:
                                                                    sources += [
                                                                        sp
                                                                    ]

                                                        targets = es[
                                                            'element'][e][
                                                                'target']
                                                        if bool(targets
                                                                ) == False:
                                                            targets = [None]

                                                        for target in targets:
                                                            for source in sources:
                                                                name_how = st2name(
                                                                    i_pnt, e,
                                                                    source,
                                                                    target)
                                                                if progress.verbose:
                                                                    progress.set_info(
                                                                        ' ' *
                                                                        5 +
                                                                        name_how
                                                                    )

                                                                path_gps = os.path.join(
                                                                    dir_how,
                                                                    name_how +
                                                                    '.json')
                                                                path_graph = os.path.join(
                                                                    dir_graph,
                                                                    e + '_' +
                                                                    str(i_pnt)
                                                                    + '.json')

                                                                if os.path.exists(
                                                                        path_graph
                                                                ):
                                                                    data = json.load(\
                                                                     open(path_graph, 'r'))
                                                                    flux_graph = json_graph.node_link_graph(
                                                                        data)

                                                                else:
                                                                    if progress.verbose:
                                                                        progress.set_info(
                                                                            ' '
                                                                            *
                                                                            10
                                                                            +
                                                                            'building graph...'
                                                                        )
                                                                    dir_graph = os.path.join(
                                                                        dir_raw,
                                                                        'graph'
                                                                    )
                                                                    if not os.path.exists(
                                                                            dir_graph
                                                                    ):
                                                                        os.makedirs(
                                                                            dir_graph
                                                                        )

                                                                    flux_graph = build_flux_graph(soln, raw, e, \
                                                                     path_save=path_graph, overwrite=False, \
                                                                     i0=i_pnt, i1=i_pnt, constV=False)

                                                                if flag == False:
                                                                    continue

                                                                GPS_notes = 'T = '+str(T[i_pnt])+', axis0 = '+str(axis0[i_pnt])+\
                                                                  ' ('+str(min(axis0))+' ~ '+str(max(axis0))+')'

                                                                GPS_results = GPS_algo(soln, flux_graph, source, target, \
                                                                 path_save=path_gps, K=K, alpha=alpha, beta=beta, \
                                                                 normal='max', iso=iso, overwrite=True, raw=dir_raw, \
                                                                 notes=GPS_notes, gamma=gamma)

                                                                new_kept = set(
                                                                    GPS_results[
                                                                        'species']
                                                                    .keys())
                                                                species_kept |= new_kept

                                                    v += dv_pnt
                                                    progress.set_value(
                                                        'GPS', v)

                        # generate chem.inp ***************
                        write_sk_inp(species_kept, dir_mech_de, dir_mech_sk,
                                     notes)
                        #"""

    progress.set_value('GPS', 100)
    return True
Beispiel #4
0
def run_graph(parent, progress, task):
    if task == 'GPS':
        obj = progress.w.label_GPS
    elif task == 'GPSA':
        obj = progress.w.label_GPSA

    obj.setText('building graph')

    dir_public = parent.project['dir_public']
    soln = parent.soln['detailed']

    list_train = []
    train_name = parent.train_name
    for db_name in parent.project['database'].keys():
        if parent.project['database'][db_name]['train']:
            list_train.append(db_name)

    traced_list = []
    for GPS_name in parent.project['GPS'].keys():
        if parent.project['GPS'][GPS_name]['checked']:
            GPS = parent.project['GPS'][GPS_name]
            es_name = GPS['es']
            es = parent.project['es'][es_name]
            for e in es['element'].keys():
                if es['element'][e]['traced']:
                    if e not in traced_list:
                        traced_list.append(e)

    if not bool(traced_list):
        msg = 'no traced element in selected GPS'
        QMessageBox.information(QWidget(), '', msg)
        return False

    v = 0.0
    dv_db = 100.0 / len(list_train)
    for db_name in list_train:

        database = parent.project['database'][db_name]
        phi_list = database['phi']
        T0_list = database['T0']
        atm_list = database['atm']
        fuel_list = database['fuel']
        oxid_list = database['oxid']
        reactor = database['reactor']

        dv_raw = dv_db / (len(phi_list) * len(atm_list) * len(T0_list) *\
         len(fuel_list) * len(oxid_list))

        for fuel_name in fuel_list:
            for oxid_name in oxid_list:
                for phi in phi_list:
                    for atm in atm_list:
                        for T0 in T0_list:

                            if progress.stop:
                                progress.close()
                                return False

                            dir_de = os.path.join(dir_public, 'detailed')
                            dir_raw = cond2dir(dir_de, fuel_name, \
                             oxid_name, phi, atm, T0, \
                             reactor, parent.n_digit)
                            if 'DNS' in reactor:
                                dir_raw = os.path.join(dir_raw,
                                                       database['case'][0])
                            raw = load_raw(os.path.join(dir_raw, 'raw.npz'))
                            dir_graph = os.path.join(dir_raw, 'graph')
                            if not os.path.exists(dir_graph):
                                os.makedirs(dir_graph)

                            n_pnt = len(raw['axis0'])
                            dv_pnt = 1.0 * dv_raw / n_pnt

                            print('dir_raw = ' + str(dir_raw))
                            print('n_point = ' + str(n_pnt))

                            for i_pnt in range(n_pnt):
                                """
								if 'active reactions' in raw.keys() and len(raw['active reactions'])>0:
									if raw['active reactions'][i_pnt] == 0:
										print 'skipped pnt '+str(i_pnt)+' as no active reaction'
										continue
										"""

                                for e in traced_list:
                                    path_graph = os.path.join(
                                        dir_graph,
                                        e + '_' + str(i_pnt) + '.json')
                                    if not os.path.exists(path_graph):
                                        info = 'building '+e+'-graph for pnt'+str(i_pnt)+' of '+\
                                         str(dir_raw.replace(dir_de,''))
                                        if i_pnt % 10 == 0:
                                            print(info)
                                        if n_pnt < 100:
                                            progress.set_info(info)
                                        flux_graph = build_flux_graph(soln, raw, e, \
                                         path_save=path_graph, overwrite=False, \
                                         i0=i_pnt, i1=i_pnt, constV=False)
                                    else:
                                        if i_pnt % 1e4 == 0 or i_pnt == n_pnt - 1:
                                            print('already exists ' +
                                                  str(path_graph))

                                v += dv_pnt
                                if n_pnt < 100:
                                    progress.set_value(task, v)

    obj.setText(task)
    progress.set_value(task, 0.0)
    return True
def find_yy(soln, dir_raw, parent, fig_opt, sub_opt, tp):

    # tp is type
    """

	.8888b oo                dP                                
	88   "                   88                                
	88aaa  dP 88d888b. .d888b88              dP    dP dP    dP 
	88     88 88'  `88 88'  `88              88    88 88    88 
	88     88 88    88 88.  .88              88.  .88 88.  .88 
	dP     dP dP    dP `88888P8              `8888P88 `8888P88 
	                            oooooooooooo      .88      .88 
	                                          d8888P   d8888P  

	"""

    #dnR = load_dR(path_R_npz, soln)

    path_raw = os.path.join(dir_raw, 'raw.npz')
    raw = load_raw(path_raw)

    xtype = fig_opt['xtype']
    mf = raw['mole_fraction']
    mole = [float(v) for v in raw['mole']]
    xx = [float(v) for v in raw['axis0']]
    TT = [float(v) for v in raw['temperature']]

    # ==========================================
    if '_T' in tp:
        if xtype == 'Temperature (K)':
            yy = [xx]
        else:
            yy = [TT]

        ff = ['']

    elif '_Qdot' in tp:
        yy = [raw['heat_release_rate']]
        ff = ['']

    # ==========================================
    elif '_tau-ign' in tp:
        yy = [xx]
        ff = ['']

    # ==========================================
    elif '_psr-T' in tp:
        yy = [TT]
        ff = ['']

    # ==========================================
    elif '_sp' in tp:
        yy = []
        ff = []

        for i_sp in range(len(sub_opt['sp'])):
            sp = sub_opt['sp'][i_sp]
            yy.append([])
            ff.append(sp)

        for i_pnt in range(len(raw['axis0'])):
            soln = raw2soln(soln, raw, i_pnt)

            for i_sp in range(len(sub_opt['sp'])):
                sp = sub_opt['sp'][i_sp]
                if sp != 'radical':
                    sp_id_list = [soln.species_index(sp)]
                else:
                    sp_id_list = [
                        soln.species_index(R) for R in ['O', 'H', 'OH']
                    ]

                yi = 0
                for sp_id in sp_id_list:
                    if sub_opt['task'] == 'mole fraction':
                        yi += float(mf[i_pnt, sp_id])
                    else:
                        yi += soln.net_production_rates[sp_id]
                yy[i_sp].append(yi)

    # ==========================================
    elif '_GP' in tp:
        key = 'GP_' + sub_opt['traced']
        method = sub_opt['method']
        traced = sub_opt['traced']
        yy = []
        ff = []

        for i_GP in range(len(sub_opt[key])):
            GP_name = sub_opt[key][i_GP]
            GP_dir = parent.project[key][GP_name]
            GP_alias = GP_dir['alias']

            y = load_GPSA(dir_raw, GP_dir, method)
            if y is None:
                msg = 'could not find GPSA data for: \n'+GP_alias+' \nin:\n '+str(dir_raw)[-20:]+\
                 'try to run GPSA first'
                QMessageBox.information(QWidget(), '', msg)
                return False, False, False, False

            yy.append(y)
            ff.append(GP_alias)

    # ==========================================
    elif '_node' in tp:
        extra = {
            'n_edge': int(sub_opt['n_edge'][0]),
            'traced': sub_opt['traced'],
            'species': soln.species_names
        }
        yy, ff = find_node_edges(dir_raw, sub_opt['node'], extra)

    ff_sorted = sorted(ff)
    yy_sorted = []
    for f in ff_sorted:
        i_f = ff.index(f)
        yy_sorted.append(yy[i_f])

    # ff is the label
    return yy_sorted, xx, TT, ff_sorted
Beispiel #6
0
def	find_GPSA(dir_raw, GP_dict, soln, dnR, fuel_comp, n_break=0):

	GP_name = GP_dict['name']
	traced = GP_dict['traced']
	dir_save = os.path.join(dir_raw,'GPSA',traced)
	if not os.path.exists(dir_save):
		os.makedirs(dir_save)
	path_save = os.path.join(dir_save, shorten_GP_name(GP_name)+'.json')

	# =====================================
	# if previously computed, return False

	GPSA_all = dict()
	if os.path.exists(path_save):
		GPSA_all = json.load(open(path_save,'r'))
		if GP_name in GPSA_all.keys():
			return False

	# =====================================
	# if not loaded, compute these results


	print 'computing GPSA for '+GP_name

	traced = GP_dict['traced']
	GP_member = GP_dict['member']
	dir_graph = os.path.join(dir_raw,'graph')	
	path_raw = os.path.join(dir_raw,'raw.npz')
	raw = load_raw(path_raw)
	rr_mat = raw['net_reaction_rate']

	GPSA = dict()
	GPSA['R_GP'] = []		# net radical production rate associated with a Global Pathway (GP)
	GPSA['Q_GP'] = []		# net heat release rate associated with a GP
	GPSA['D_GP'] = []		# dominancy of a GP

	GPSA['R_ij'] = dict()	# net radical production rate associated with a conversion step (from the i-th species to the j-th species)
	GPSA['Q_ij'] = dict()
	GPSA['a_iji'] = dict()
	#GPSA['perc_ij'] = dict()

	for i in range(len(GP_member)-1):
		edge = find_edge_name(GP_member, i)

		GPSA['R_ij'][edge] = dict()
		GPSA['R_ij'][edge]['member'] = []
		GPSA['R_ij'][edge]['net'] = []

		GPSA['Q_ij'][edge] = dict()
		GPSA['Q_ij'][edge]['member'] = []
		GPSA['Q_ij'][edge]['net'] = []

		GPSA['a_iji'][edge] = dict()
		GPSA['a_iji'][edge]['member'] = []
		GPSA['a_iji'][edge]['net'] = []

		#GPSA['perc_ij'][edge] = dict()
		#GPSA['perc_ij'][edge]['member'] = []
		#GPSA['perc_ij'][edge]['net'] = []

	source = GP_dict['member'][0]
	traced = GP_dict['traced']
	if source not in fuel_comp.keys():
		perc_from_source = 0.0
	else:
		total_atom = 0
		for k in fuel_comp.keys():
			sp = soln.species(k)
			atom = 0.0
			if traced in sp.composition.keys():
				atom += fuel_comp[k] * sp.composition[traced]
			if source == k:
				atom_source = atom
			total_atom += atom

		perc_from_source = 1.0 * atom_source / total_atom

		#print 'total '+traced+' atoms for '+str(fuel_comp)+' is '+str(total_atom)
		#print 'source '+str(source)+' has '+str(atom_source)+' atms'
		#print 'so perc_from_source = '+str(perc_from_source)

	#GPSA['perc_ij']['from_source'] = perc_from_source


	# for each point -----------

	i_pnt = 0
	while True:

			

		path_graph = os.path.join(dir_graph, traced+'_'+str(i_pnt) + '.json')
		if not os.path.exists(path_graph): 			
			if i_pnt>n_break:
				print 'break as cannot find: '+str(path_graph)
				break
			
			else:			
				# fill this with None ---------------
				if i_pnt%10 == 0:
					print '   fill None GPSA for '+str(path_graph)

				for i in range(len(GP_member)-1):
					s = GP_member[i]
					t = GP_member[i+1]
					edge = find_edge_name(GP_member, i)
					for k in ['member','net']:
						GPSA['R_ij'][edge][k].append(None)
						GPSA['Q_ij'][edge][k].append(None)
						GPSA['a_iji'][edge][k].append(None)
						#GPSA['perc_ij'][edge][k].append(None)

				GPSA['R_GP'].append(None)
				GPSA['D_GP'].append(None)

				i_pnt += 1
				continue

		soln = raw2soln(soln, raw, i_pnt)	
		if i_pnt%10 == 0:
			print '   finding GPSA for '+str(path_graph)

		# fill this with real value ---------------
		#norm_Rpro = 0.0
		#norm_Rcon = 0.0
		for id_rxn in range(soln.n_reactions):
			dR = dnR[id_rxn] * rr_mat[i_pnt, id_rxn]
			#norm_Rpro += max(0, dR)
			#norm_Rcon += max(0, -dR)


		flux_graph = json_graph.node_link_graph(json.load(open(path_graph, 'r')))
		out_deg = flux_graph.out_degree(weight='flux')
		norm_out_deg = sum([out_deg[m] for m in fuel_comp.keys() if m in out_deg.keys()])

		flux = []
		rxn_involved = []
		sum_OMEGA_R = 0
		sum_OMEGA_Q = 0
		perc_ij_list = []

		# for each edge (conversion step) -----------------


		for i in range(len(GP_member)-1):
			s = GP_member[i]
			t = GP_member[i+1]
			edge = find_edge_name(GP_member, i)
			GPSA['R_ij'][edge]['member'].append(dict())
			GPSA['Q_ij'][edge]['member'].append(dict())
			GPSA['a_iji'][edge]['member'].append(dict())
			#GPSA['perc_ij'][edge]['member'].append(dict())

			# ------------------------------

			try:
				st = flux_graph[s][t]
			except KeyError:
				st = None

			perc_ij = None
			if st is not None:
				flux.append(st['flux'])
				perc_ij = 1.0 * st['flux'] / out_deg[s]
				perc_ij_list.append(perc_ij)

				for id_rxn_s in st['member'].keys():
					id_rxn = int(id_rxn_s)
					rxn = soln.reaction_equation(id_rxn)
					rr = rr_mat[i_pnt, id_rxn]
					if rr < 0:
						sign_rxn = -id_rxn
					else:
						sign_rxn = id_rxn

					GPSA['a_iji'][edge]['member'][i_pnt][sign_rxn] = st['member'][id_rxn_s]
					#GPSA['perc_ij'][edge]['member'][i_pnt][sign_rxn] = 1.0 * st['member'][id_rxn_s]/out_deg[s]

					OMEGA_R = float(rr * dnR[id_rxn])
					GPSA['R_ij'][edge]['member'][i_pnt][sign_rxn] = OMEGA_R					

					OMEGA_Q = float(rr * soln.delta_enthalpy[id_rxn])
					GPSA['Q_ij'][edge]['member'][i_pnt][sign_rxn] = OMEGA_Q

					if id_rxn not in rxn_involved:
						sum_OMEGA_R += OMEGA_R
						sum_OMEGA_Q += OMEGA_Q
						rxn_involved.append(id_rxn)




			# ------------------------------

			try:
				ts = flux_graph[t][s]
			except KeyError:
				ts = None

			if ts is not None:
				for id_rxn_s in ts['member'].keys():
					id_rxn = int(id_rxn_s)
					rxn = soln.reaction_equation(id_rxn)
					rr = rr_mat[i_pnt, id_rxn]
					if rr < 0:
						sign_rxn = -id_rxn
					else:
						sign_rxn = id_rxn
					GPSA['a_iji'][edge]['member'][i_pnt][sign_rxn] = - ts['member'][id_rxn_s]

			# ------------------------------

			GPSA['R_ij'][edge]['net'].append(sum(GPSA['R_ij'][edge]['member'][i_pnt].values()))
			GPSA['Q_ij'][edge]['net'].append(sum(GPSA['Q_ij'][edge]['member'][i_pnt].values()))
			GPSA['a_iji'][edge]['net'].append(sum(GPSA['a_iji'][edge]['member'][i_pnt].values()))
			#GPSA['perc_ij'][edge]['net'].append(perc_ij)


		domi_perc = gmean(perc_ij_list)*perc_from_source
		if bool(flux):
			min_flux = min(flux)
			if norm_out_deg>0:
				domi_flux = 1.0 * min_flux/norm_out_deg
			else:
				domi_flux = float('nan')
		else:
			min_flux = 0.0
			domi_flux = 0.0

		R_GP = domi_perc * sum_OMEGA_R
		Q_GP = domi_perc * sum_OMEGA_Q
		GPSA['R_GP'].append(R_GP)
		GPSA['Q_GP'].append(Q_GP)
		GPSA['D_GP'].append(domi_perc)


		i_pnt += 1


	GPSA_all[GP_name] = GPSA
	json.dump(GPSA_all, open(path_save,'w'))
	return True
def find_GP_order(dir_raw, traced, parent, sample, method='D_GP'):

    path_raw = os.path.join(dir_raw, 'raw.npz')
    raw = load_raw(path_raw)

    if sample['by'] != 'max':
        i_plot = find_i_plot(sample['at'], raw, sample_by=sample['by'])

    GP_traced = parent.project['GP_' + traced]
    list_GP_name = []
    list_GP_source = []
    list_GP_target = []
    list_GP_cc = []
    list_GP_nan = []

    any_available = False
    for GP_name in GP_traced.keys():
        GP_dir = GP_traced[GP_name]
        GP_alias = GP_dir['alias']
        member = GP_dir['member']
        cc = load_GPSA(dir_raw, GP_dir, method)
        if cc is None:
            c = 0
            list_GP_nan.append(True)
        else:
            any_available = True
            if sample['by'] == 'max':
                c = max(cc)
            else:
                c = cc[i_plot]
            list_GP_nan.append(False)

        list_GP_name.append(GP_name)
        list_GP_source.append(member[0])
        list_GP_target.append(member[-1])

        list_GP_cc.append(c)

    try:
        # sort by source first, then target, then cc
        ind = np.lexsort((list_GP_cc, list_GP_target, list_GP_source))
    except ValueError:
        print(list_GP_cc)
        print(list_GP_target)
        print(list_GP_source)
        import sys
        sys.exit()
    #print 'lexsort OK'

    if not any_available:
        msg = 'no '+traced+'-GPSA data is available for\n\n'+str(dir_raw)+\
         '\n\ntry different dataset or run GPSA first'
        QMessageBox.information(QWidget(), '', msg)

    list_GP_name_sorted = [list_GP_name[i] for i in ind]
    list_GP_nan_sorted = [list_GP_nan[i] for i in ind]

    if bool(dir_raw):
        if max(list_GP_cc) > 0:
            norm = max(list_GP_cc)
        else:
            norm = 1.0
        list_GP_cc_norm_sorted = [list_GP_cc[i] / norm for i in ind]
    else:
        list_GP_cc_norm_sorted = list_GP_cc

    return list_GP_name_sorted, list_GP_cc_norm_sorted, list_GP_nan_sorted