예제 #1
0
def go(species):
    method_dir = r'%s/method/Ding' % my_constants.basePath
    out_dir = r'%s/Ding' % my_constants.basePath
    my_util.mkdir_p(out_dir)

    # source_file = '%s/dataset/networks/%s' % (my_constants.basePath, my_constants.species_sbml[species])
    source_file = '%s/method/Ding/Y2H-union.txt'
    # S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(source_file, True, read_species_compart=True, remove_biomass=False, normalize_stoich=False)

    f = open('Ding.m', 'w')
    write_line(f, 'addpath %s/src' % method_dir)
    write_line(f, "model = readCbModel('%s')" % source_file)
    # write_line(f, "model.c(%d) = 1;" % (rxns.index(biomass[0]) + 1))
    # write_line(f, "changeCobraSolver('glpk');")
    write_line(f, '[modules] = main( model );')
    write_line(f, 'save Dingout.mat ')

    f.close()

    my_util.prepare_matlab_file_and_exec_and_wait_finish(
        'Ding', 'Dingout.mat', False)

    res_vars = my_util.try_load_matlab_result('Dingout.mat')
    raw_modules = res_vars[
        'modules']  # if matlab has failed, this will throw exception!
예제 #2
0
파일: muller2_new.py 프로젝트: emdadi/CAMND
def go(species):
    method_dir = r'%s/method/muller2_new' % my_constants.basePath
    out_dir = r'%s/%s/muller2_new' % (my_constants.resultPath, species)
    my_util.mkdir_p(out_dir)

    source_file = '%s/dataset/networks/%s' % (
        my_constants.basePath, my_constants.species_sbml[species])

    S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(
        source_file,
        True,
        read_species_compart=True,
        remove_biomass=False,
        normalize_stoich=False)

    f = open('muller2_new.m', 'w')
    write_line(f, 'addpath %s/code' % method_dir)
    write_line(f, "model = readCbModel('%s')" % source_file)
    write_line(f, "model.c(%d) = 1;" % (rxns.index(biomass[0]) + 1))
    write_line(f, "changeCobraSolver('glpk');")
    write_line(f, '[modules, var, flux] = computeModulesOpt( model );')
    write_line(f, 'save muller2_newout.mat modules var flux')

    f.close()

    my_util.prepare_matlab_file_and_exec_and_wait_finish(
        'muller2_new', 'muller2_newout.mat', False)

    res_vars = my_util.try_load_matlab_result('muller2_newout.mat')
    raw_modules = res_vars[
        'modules']  # if matlab has failed, this will throw exception!
    shutil.copy('muller2_newout.mat', out_dir)

    raw_modules = raw_modules.T.tolist(
    )  # eacho row will be a module where reactions are marked
    modules = []
    for raw_module in raw_modules:
        modules.append([])
        for rIdx, in_module in enumerate(raw_module):
            if in_module == 1:
                modules[-1].append(rxns[rIdx])

    out = open('%s/final_modules.txt' % out_dir, 'w')
    out.write(
        "#each row is a module of reactions. not all reactions are specified (nature of this method only select some reaction to be modules)\n"
    )
    for m in modules:
        out.write(' '.join(m))
        out.write('\n')
    out.close()
예제 #3
0
def go(species):
    method_dir = r'%s/method/schuster' % my_constants.basePath
    out_dir = r'%s/%s/schuster' % (my_constants.resultPath, species)
    my_util.mkdir_p(out_dir)

    source_file = '%s/dataset/networks/%s' % (
        my_constants.basePath, my_constants.species_sbml[species])

    S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(
        source_file,
        True,
        read_species_compart=True,
        remove_biomass=True,
        normalize_stoich=True)

    external_strategy = eval(
        open('%s/external_strategy.txt' % method_dir, 'r').read())

    # both may either be with/without boundary reactions which is specified by the strategy
    # these will be used to create schuster.in file which is used by the method as the input network
    with_boundary_reacts = {}
    with_boundary_mets = list(mets)

    if external_strategy[
            species] == 'KEGG_PSEUDO_NETWORK':  # this implies networks are built from kegg by merging pathways
        subs_to_reacts = {}
        prods_to_reacts = {}
        for j, r in enumerate(rxns):
            subs = []
            prods = []
            for i in range(len(S)):
                if S[i][j] > 0:
                    prods.append([S[i][j],
                                  mets[i]])  # [stoichiometry, met_name]
                elif S[i][j] < 0:
                    subs.append([-S[i][j],
                                 mets[i]])  # [stoichiometry, met_name]
            with_boundary_reacts[r] = [subs, prods]

            has_subs, has_prods = False, False
            for i in range(len(S)):
                if S[i][j] > 0 or (S[i][j] < 0 and revs[j] != 0):
                    if mets[i] not in prods_to_reacts:
                        prods_to_reacts[mets[i]] = set()
                    prods_to_reacts[mets[i]].add(r)
                    has_prods = True
                if S[i][j] < 0 or (S[i][j] > 0 and revs[j] != 0):
                    if mets[i] not in subs_to_reacts:
                        subs_to_reacts[mets[i]] = set()
                    subs_to_reacts[mets[i]].add(r)
                    has_subs = True

            if not has_subs or not has_prods:
                raise Exception(
                    'reaction without substrate/products in KEGG pseudo networks! should never happen!'
                )

        # checks whether the reaction is internal in presence of reversiblity
        def is_internal(met):
            if met not in prods_to_reacts or met not in subs_to_reacts:
                return False
            if prods_to_reacts[met] == subs_to_reacts[met] and len(
                    prods_to_reacts[met]) == 1:
                the_react = list(prods_to_reacts[met])[0]
                the_react_subs = [
                    ss[1] for ss in with_boundary_reacts[the_react][0]
                ]
                the_react_prods = [
                    ss[1] for ss in with_boundary_reacts[the_react][1]
                ]
                if not (met in the_react_subs
                        and met in the_react_prods):  # not polymeric
                    return False
            return True

        internal_metabolites = [
            m for m in with_boundary_mets if is_internal(m)
        ]
        initial_external_metabolites = [
            m for m in with_boundary_mets if m not in internal_metabolites
        ]
    else:
        # may add to with_boundary_mets based on strategy.
        # may update with_boundary_reacts according to newly added with_boundary_mets
        for j, r in enumerate(rxns):
            subs = []
            prods = []
            for i in range(len(S)):
                if S[i][j] > 0:
                    prods.append([S[i][j],
                                  mets[i]])  # [stoichiometry, met_name]
                elif S[i][j] < 0:
                    subs.append([-S[i][j],
                                 mets[i]])  # [stoichiometry, met_name]

            # this strategy means reactions without product are boundary reactions
            # note that: reversibility could potentially be problematic BUT I HAVE CHECKED BIGG NETWORKS, THESE KIND OF REACTIONS ARE REAL OUTSIDE BOUNDARY
            if not subs:
                raise Exception(
                    'reaction without substrate! should never happen!')
            elif not prods:
                if external_strategy[species] == 'BOUNDARY':
                    if len(subs) != 1:
                        raise Exception(
                            'EXCHANGE reaction with more than one substrate metabolite! unacceptable.'
                        )
                    new_boundary_met = subs[0][1] + '_BND'
                    if new_boundary_met not in with_boundary_mets:
                        # print 'the only exceptions are once for h**o recon 1 and once for ecoli ijo 1366!'
                        with_boundary_mets.append(new_boundary_met)
                    prods = [[subs[0][0], new_boundary_met]]
                else:
                    print 'skipping reaction without product: EXCHANGE!'
                    continue

            with_boundary_reacts[r] = [subs, prods]

        if external_strategy[species] == 'BOUNDARY':
            initial_external_metabolites = [
                m for i, m in enumerate(with_boundary_mets)
                if with_boundary_mets[i].endswith('_BND')
            ]
            internal_metabolites = [
                m for m in with_boundary_mets
                if m not in initial_external_metabolites
            ]
        else:
            initial_external_metabolites = [
                m for i, m in enumerate(with_boundary_mets)
                if with_boundary_mets[i].endswith('_e')
            ]
            internal_metabolites = [
                m for m in with_boundary_mets
                if m not in initial_external_metabolites
            ]

    inf = open('schuster.in', 'w')
    write_line(inf, '-ENZREV')
    write_line(inf, ' '.join([r for i, r in enumerate(rxns) if revs[i] == 1]))
    write_line(inf, '')
    write_line(inf, '-ENZIRREV')
    write_line(inf, ' '.join([r for i, r in enumerate(rxns) if revs[i] != 1]))
    write_line(inf, '')
    write_line(inf, '-METINT')
    write_line(inf, ' '.join(internal_metabolites))
    write_line(inf, '')
    write_line(inf, '-METEXT')
    write_line(inf, ' '.join(initial_external_metabolites))
    write_line(inf, '')
    write_line(inf, '-CAT')
    for r_name, r in with_boundary_reacts.iteritems():
        react_str = '%s : %s = %s .' % (r_name, ' + '.join([
            '%d %s' % (p[0], p[1]) for p in r[0]
        ]), ' + '.join(['%d %s' % (p[0], p[1]) for p in r[1]]))
        write_line(inf, react_str)
    inf.close()

    # for each species, this may be defined or simply be '' which is ignored
    thresholds = eval(open('%s/thresholds.txt' % method_dir, 'r').read())

    for thr in thresholds[species]:
        run_for_all_template_files('subsystem%d.out', os.remove)
        run_for_all_template_files(out_dir + '/subsystem%d.out', os.remove)

        # subnet file_name
        if my_constants.win:
            res = os.system('%s/src/subnet.exe schuster.in %s' %
                            (method_dir, thr))
        else:
            res = os.system('subnet schuster.in %s' % thr)

        rmods = {}
        mmods = {}

        def read_module_and_move(resf_path, i):
            rmod, mmod = read_result_file(resf_path)
            rmods['%d' % i] = rmod
            mmods['%d' % i] = mmod

            int_out_dir_path = '%s/subsystem_%s_%d.out' % (out_dir, thr, i)
            shutil.copy(resf_path, int_out_dir_path)

        run_for_all_template_files('subsystem%d.out', read_module_and_move)

        outr = open('%s/react_modules_%s.txt' % (out_dir, thr), 'w')
        outrm = open('%s/metab_react_modules_%s.txt' % (out_dir, thr), 'w')
        outm = open('%s/metab_modules_%s.txt' % (out_dir, thr), 'w')
        for mname, rmod in rmods.iteritems():
            write_line(outr, ' '.join(rmod))
            write_line(outrm, ' '.join(mmods[mname]))
            if mmods[mname]:
                write_line(outm, ' '.join(mmods[mname]))
        outr.close()
        outrm.close()
        outm.close()

        shutil.copy(
            '%s/metab_modules_%s.txt' % (out_dir, thr),
            '%s/final_modules_%s.txt' %
            (out_dir,
             thr))  # TODO: which file r/m should be selected as final modules?
예제 #4
0
파일: sridharan.py 프로젝트: emdadi/CAMND
def go(species, only_cut_dendogram=False):
    need_biomass_removal = False and my_constants.species_artificial_biomass[
        species]

    method_dir = r'%s/method/sridharan' % my_constants.basePath
    out_dir = r'%s/%s/sridharan' % (my_constants.resultPath, species)
    my_util.mkdir_p(out_dir)

    source_file = '%s/dataset/networks/%s' % (
        my_constants.basePath, my_constants.species_sbml[species])

    S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(
        source_file,
        True,
        read_species_compart=True,
        remove_biomass=need_biomass_removal,
        normalize_stoich=False)

    if not only_cut_dendogram:
        f = open('sridharan.m', 'w')
        write_line(f, 'addpath %s/code' % method_dir)
        write_line(f, "model = readCbModel('%s')" % source_file)
        if need_biomass_removal:
            for l in my_util.get_remove_reaction_matlab_script(
                    'model', biomass):
                write_line(f, l)
        write_line(
            f, '[mods, mods_hier] = Shred_Network_plos2011(model, false);')
        write_line(f, 'save sridharan.mat mods mods_hier')

        f.close()

        my_util.prepare_matlab_file_and_exec_and_wait_finish(
            'sridharan', 'sridharan.mat', False)

        shutil.copy('sridharan.mat', out_dir)

    modules_hierarchy, mods_mets, mods_rxns, raw_tree_height = read_module_hierarchy(
        '%s/sridharan.mat' % out_dir, mets, rxns)

    # TODO: very bad job!!!!
    # NOTE: mets are removed because their modules share metabolites!!!
    dummy_tree, tree_height, dummy_thresholds = read_hierarchical_decomposition_sridharan(
        species, '%s/sridharan.mat' % out_dir, mets, rxns, is_mets=False)

    def dendogram_height(hierarchy_height):
        return tree_height - hierarchy_height + 1

    cut_heights = eval(open('%s/cut_heights.txt' % method_dir, 'r').read())
    for thrr in cut_heights[species]:

        # TODO: very bad job
        thr_height = thrr * tree_height

        all_modularized_observations = set()
        cut_mods = []
        # to cut, find all modules above below cut height whose super above cut height
        # also all other observations are added as remaining modules (observations are not in module_hierarchy as one-sized-module and so should be specially treated)
        for m_idx, m_sup_sub in enumerate(modules_hierarchy):
            module_height = m_sup_sub[2]
            super_module_height = modules_hierarchy[m_sup_sub[0]][
                2] if m_sup_sub[0] is not None else tree_height + 1
            if dendogram_height(
                    module_height) <= thr_height < dendogram_height(
                        super_module_height):
                cut_mods.append(mods_rxns[m_idx])
                all_modularized_observations.update(mods_rxns[m_idx])

        for r in rxns:
            if r not in all_modularized_observations:
                cut_mods.append([r])

        outr = open('%s/react_modules_%s.txt' % (out_dir, thrr), 'w')
        # outm = open('%s/metab_modules_%s.txt' % (out_dir, thrr), 'w')
        # for rmod, mmod in zip(cut_mods_rxns, cut_mods_mets):
        for rmod in cut_mods:
            write_line(outr, ' '.join(rmod))
            # write_line(outm, ' '.join(mmod))
        outr.close()
        # outm.close()

        shutil.copy(
            '%s/react_modules_%s.txt' % (out_dir, thrr),
            '%s/final_modules_%s.txt' % (out_dir, thrr)
        )  # TODO: which file r/m should be selected as final modules?
예제 #5
0
def go(species, pseudo_species=None):
    method_dir = r'%s/method/verwoerd' % my_constants.basePath
    out_dir = r'%s/%s/verwoerd' % (my_constants.resultPath, species)
    my_util.mkdir_p(out_dir)

    source_file = '%s/dataset/networks/%s' % (
        my_constants.basePath, my_constants.species_sbml[species])

    S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(
        source_file,
        True,
        read_species_compart=True,
        remove_biomass=True,
        normalize_stoich=True)

    external_strategy = eval(
        open('%s/external_strategy.txt' % method_dir, 'r').read())

    # both may either be with/without boundary reactions which is specified by the strategy
    with_boundary_reacts = {}
    with_boundary_mets = list(mets)
    with_boundary_comparts = list(met_comparts)

    next_boundary_met_idx = len(mets)
    if external_strategy[
            species] == 'KEGG_PSEUDO_NETWORK':  # this implies networks are built from kegg by merging pathways
        subs_to_reacts = {}
        prods_to_reacts = {}
        for j, r in enumerate(rxns):
            subs = []
            prods = []
            for i in range(len(S)):
                if S[i][j] > 0:
                    prods.append([S[i][j], i])  # [stoichiometry, met_name]
                elif S[i][j] < 0:
                    subs.append([-S[i][j], i])  # [stoichiometry, met_name]
            with_boundary_reacts[r] = [subs, prods]

            has_subs, has_prods = False, False
            for i in range(len(S)):
                if S[i][j] > 0 or (S[i][j] < 0 and revs[j] != 0):
                    if mets[i] not in prods_to_reacts:
                        prods_to_reacts[mets[i]] = set()
                    prods_to_reacts[mets[i]].add(r)
                    has_prods = True
                if S[i][j] < 0 or (S[i][j] > 0 and revs[j] != 0):
                    if mets[i] not in subs_to_reacts:
                        subs_to_reacts[mets[i]] = set()
                    subs_to_reacts[mets[i]].add(r)
                    has_subs = True

            if not has_subs or not has_prods:
                raise Exception(
                    'reaction without substrate/products in KEGG pseudo networks! should never happen!'
                )

        # checks whether the reaction is internal in presence of reversiblity
        def is_internal(met):
            if met not in prods_to_reacts or met not in subs_to_reacts:
                return False
            if prods_to_reacts[met] == subs_to_reacts[met] and len(
                    prods_to_reacts[met]) == 1:
                the_react = list(prods_to_reacts[met])[0]
                the_react_subs = [
                    mets[ss[1]] for ss in with_boundary_reacts[the_react][0]
                ]
                the_react_prods = [
                    mets[ss[1]] for ss in with_boundary_reacts[the_react][1]
                ]
                if not (met in the_react_subs
                        and met in the_react_prods):  # not polymeric
                    return False
            return True

        initial_external_metabolites_idxs = [
            mets.index(m) for m in with_boundary_mets if not is_internal(m)
        ]
        # internal_metabolites = [m for m in with_boundary_mets if m in mets_used_as_subs and m in mets_used_as_prods]
    else:
        # may add to with_boundary_mets based on strategy.
        # may update with_boundary_reacts according to newly added with_boundary_mets
        for j, r in enumerate(rxns):
            subs = []
            prods = []
            for i in range(len(S)):
                if S[i][j] > 0:
                    prods.append([S[i][j], i])
                elif S[i][j] < 0:
                    subs.append([-S[i][j], i])

            if not subs:
                raise Exception(
                    'reaction without substrate! should never happen!')
            elif not prods:
                if external_strategy[species] == 'BOUNDARY':
                    if len(subs) != 1:
                        raise Exception(
                            'EXCHANGE reaction with more than one substrate metabolite! unacceptable.'
                        )
                    new_boundary_met = mets[subs[0][1]] + '_BND'
                    if new_boundary_met in with_boundary_mets:
                        # print 'should happen only once for h**o recon 1 and once for ecoli ijo 1366!'
                        prods = [[
                            subs[0][0],
                            with_boundary_mets.index(new_boundary_met)
                        ]]
                    else:
                        with_boundary_mets.append(new_boundary_met)
                        with_boundary_comparts.append('B')
                        prods = [[subs[0][0], next_boundary_met_idx]]
                        next_boundary_met_idx += 1
                else:
                    print 'skipping reaction without product: EXCHANGE!'
                    continue

            with_boundary_reacts[r] = [subs, prods]

        # with_boundary_S = [[] for i in range(len(with_boundary_mets))]
        # for ri, r in rxns:
        #     r_def = with_boundary_reacts[r]
        #     for e in r_def[0]:  # substrates
        #         if e[0] != 0:

        if external_strategy[species] == 'BOUNDARY':
            initial_external_metabolites_idxs = [
                i for i, m in enumerate(with_boundary_mets)
                if with_boundary_mets[i].endswith('_BND')
            ]
        else:
            initial_external_metabolites_idxs = [
                i for i, m in enumerate(with_boundary_mets)
                if with_boundary_mets[i].endswith('_e')
            ]
            # internal_metabolites = [m for m in with_boundary_mets if m not in initial_external_metabolites]

    if pseudo_species:
        my_util.mkdir_p(pseudo_species)
        inf = open('%s/verwoerd.tsv' % pseudo_species, 'w')
    else:
        inf = open('verwoerd_%s.tsv' % species, 'w')
    write_line(inf, '<Title>')
    write_line(inf, species.replace('/', ''))
    write_line(inf, '<Reactions>')
    write_line(inf, '\t'.join(rxns))
    write_line(inf, '<ReversibleReactions>')
    write_line(inf, '\t'.join([r for i, r in enumerate(rxns) if revs[i] == 1]))
    write_line(inf, '<InternalCompounds>')
    # write_line(inf, '\t'.join(['%s' % (with_boundary_mets[i]) for i in range(len(with_boundary_mets))]))
    write_line(
        inf, '\t'.join([
            '%s %s' % (with_boundary_mets[i], with_boundary_comparts[i])
            for i in range(len(with_boundary_mets))
        ]))
    write_line(inf, '<ExternalCompounds>')
    # write_line(inf, '\t'.join(['%s %s' % (with_boundary_mets[i], with_boundary_comparts[i]) for i in initial_external_metabolites_idxs]))
    write_line(inf, '<Stoichiometry>')
    write_line(inf, '%%MatrixMarket matrix coordinate real general')

    s_lines = []
    nnz_s = 0
    for ri, r in enumerate(rxns):
        if r not in with_boundary_reacts:  # exchange reactions
            continue

        rdef = with_boundary_reacts[r]
        for e in rdef[0]:
            s_lines.append('%d\t%d\t%s' % (e[1] + 1, ri + 1, -e[0]))
            nnz_s += 1
        for e in rdef[1]:
            s_lines.append('%d\t%d\t%s' % (e[1] + 1, ri + 1, e[0]))
            nnz_s += 1

    write_line(
        inf, '\t\t\t%d\t%d\t%d' %
        (len(with_boundary_mets), len(with_boundary_reacts), nnz_s))
    for sl in s_lines:
        write_line(inf, sl)

    inf.close()

    if pseudo_species:
        inf = open('%s/verwoerd-ext.txt' % pseudo_species, 'w')
    else:
        inf = open('verwoerd-ext_%s.txt' % species, 'w')
    for init_extern_idx in initial_external_metabolites_idxs:
        write_line(inf, with_boundary_mets[init_extern_idx])
    inf.close()
예제 #6
0
def go(species, pseudo_species=None):
    method_dir = r'%s/method/verwoerd' % my_constants.basePath
    out_dir = r'%s/%s/verwoerd' % (my_constants.resultPath, species)
    my_util.mkdir_p(out_dir)

    source_file = '%s/dataset/networks/%s' % (
        my_constants.basePath, my_constants.species_sbml[species])

    S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(
        source_file,
        True,
        read_species_compart=True,
        remove_biomass=True,
        normalize_stoich=True)

    # for each species, this may be defined or simply be '' which is ignored
    thresholds = eval(open('%s/thresholds.txt' % method_dir, 'r').read())

    for thr in thresholds[species]:
        if pseudo_species:
            manual_results_dir = '%s/Subnetworks_%s' % (pseudo_species, thr)
        else:
            manual_results_dir = '%s_%s' % (species, thr)

        rmods = {}
        mmods = {}

        def read_module_and_move(resf_path, i):
            rmod, mmod = read_result_file(resf_path)
            rmods['%d' % i] = rmod
            mmods['%d' % i] = mmod

            int_out_dir_path = '%s/subsystem_%s_%d.out' % (out_dir, thr, i)
            shutil.copy(resf_path, int_out_dir_path)

        if pseudo_species:
            run_for_all_template_files(
                manual_results_dir + '/' + species.replace('/', '') +
                '_Block_%d.tsv', read_module_and_move)
        else:
            run_for_all_template_files(
                manual_results_dir + '/' + species + '_Block_%d.tsv',
                read_module_and_move)

        outr = open('%s/react_modules_%s.txt' % (out_dir, thr), 'w')
        outrm = open('%s/metab_react_modules_%s.txt' % (out_dir, thr), 'w')
        outm = open('%s/metab_modules_%s.txt' % (out_dir, thr), 'w')
        for mname, rmod in rmods.iteritems():
            write_line(outr, ' '.join(rmod))
            write_line(outrm, ' '.join(mmods[mname]))
            if mmods[mname]:
                write_line(outm, ' '.join(mmods[mname]))
        outr.close()
        outrm.close()
        outm.close()

        shutil.copy(
            '%s/metab_modules_%s.txt' % (out_dir, thr),
            '%s/final_modules_%s.txt' %
            (out_dir,
             thr))  # TODO: which file r/m should be selected as final modules?
예제 #7
0
def compute_couplings(S, mets, rxns, revs, REACT_MAX_LEN, METAB_MAX_LEN):
    global couplings_cache

    for cc in couplings_cache:
        if S == cc[0] and mets == cc[1] and rxns == cc[2] and revs == cc[
                3] and REACT_MAX_LEN == cc[4] and METAB_MAX_LEN == cc[5]:
            return cc[6], cc[7]
    couplings_cache.append([S, mets, rxns, revs, REACT_MAX_LEN, METAB_MAX_LEN])

    f = open('cohesion_coupling.m', 'w')

    s_str = 'thenet.stoichiometricMatrix = zeros(%d,%d);' % (len(mets),
                                                             len(rxns))
    write_line(f, s_str)

    for i in xrange(len(S)):
        s_str = 'thenet.stoichiometricMatrix(%d,:) = %s;' % (i + 1, str(S[i]))
        write_line(f, s_str)

    rev_str = 'thenet.reversibilityVector = [' + mat_rows(revs) + '];'
    write_line(f, rev_str)

    react_str = 'thenet.Reactions = [' + mat_rows(rxns, REACT_MAX_LEN) + '];'
    write_line(f, react_str)

    met_str = 'thenet.Metabolites = [' + mat_rows(mets, METAB_MAX_LEN) + '];'
    write_line(f, met_str)

    # mod_path = r'addpath %s/evaluation/fcf/ffca'
    # func = 'FFCA'
    mod_path = r'addpath %s/evaluation/fcf/f2c2'
    func = 'F2C2'
    fcf_tool_path = mod_path % my_constants.basePath
    write_line(f, fcf_tool_path)

    compute_str = "[cpls, blk] = %s('clp', thenet);" % func
    write_line(f, compute_str)

    save_str = 'save cohesion_coupling.mat cpls blk'
    write_line(f, save_str)

    f.close()

    my_util.prepare_matlab_file_and_exec_and_wait_finish(
        'cohesion_coupling', 'cohesion_coupling.mat', False)

    res_vars = my_util.try_load_matlab_result('cohesion_coupling.mat')
    # if matlab has failed, this will throw exception!
    couplings = res_vars['cpls'].tolist()
    blocks = [b[0] for b in res_vars['blk'].tolist()]

    couplings_cache[-1].append(couplings)
    couplings_cache[-1].append(blocks)
    return couplings, blocks
예제 #8
0
def compute_and_print_size_distribution(inf, is_mmod, species, method):
    out_dir = '%s/sizes' % my_constants.evalResultPath
    my_util.mkdir_p(out_dir)

    if is_mmod:
        mods = eval_util.read_mmods(inf)
    else:
        mods = eval_util.read_rmods(inf)

    sizes = []
    for mod_name, mod_metabs in mods.iteritems():
        sizes.append(len(mod_metabs))

    result_file = '%s/%s_%s.png' % (out_dir, species, method)
    alt_result_file = '%s/sc_%s_%s.png' % (out_dir, species, method)

    f = open('size_distrib.r', 'w')
    write_line(f, 'png("%s")' % result_file)
    write_line(
        f, "hist(c(%s), main='%d modules (%s)', xlab='', ylab='')" %
        (','.join([str(s) for s in sizes]), len(mods), species + ' ' + method))
    write_line(f, 'dev.off()')
    write_line(f, 'png("%s")' % alt_result_file)
    write_line(
        f,
        "stripchart(c(%s), main='%d modules (%s)', method='stack', offset=0.5, pch=1)"
        % (','.join([str(s)
                     for s in sizes]), len(mods), species + ' ' + method))
    write_line(f, 'dev.off()')
    f.close()

    res = os.system('%s size_distrib.r' % my_constants.rScriptPath)

    while not os.path.isfile(result_file):
        time.sleep(5)

    return '=HYPERLINK("%s")' % result_file