Esempio n. 1
0
	def __init__(self, S, lb, ub, rx_names, met_names, objective_reaction=None, context=None):
		self.model = ConstraintBasedModel(S, list(zip(lb, ub)), reaction_names=rx_names, metabolite_names=met_names)
		if context != None:
			apply_context(self.model, context)
		self.tasks = {}
		self.task_fail_status = {}
		self.__add_reactions = []
		self.flux_constraints = {}

		if objective_reaction:
			self.model.set_objective({objective_reaction: 1}, False)
		else:
			self.model.set_objective({0:1}, False)
Esempio n. 2
0
    def __init__(self,
                 template_model,
                 subset_forced_reactions,
                 media,
                 iterative=True,
                 max_time=0,
                 max_threads=0,
                 big_m=False,
                 big_m_value=1000):
        '''
		:param template_model: dict - must contain {S, lb, ub} and possibly rx_names/met_names
		:param subset_forced_reactions: list - contains reaction indexes
		:param media: dict - must contain the following keys - consumed, non_consumed, produced
		values can be set as empty lists if not needed
		:param iterative: boolean flag - determines whether the k-shortest algorithm behaviour
		'''
        if isinstance(template_model, dict):
            S, lb, ub = [template_model[k] for k in ['S', 'lb', 'ub']]
            self.cb_model = ConstraintBasedModel(
                S=S, thermodynamic_constraints=list(zip(lb, ub)))
        elif isinstance(template_model, ConstraintBasedModel):
            self.cb_model = template_model

        self.subset_forced_reactions = subset_forced_reactions
        self.met_pr, self.met_co, self.met_nc = [
            media[k] for k in ['produced', 'consumed', 'non_consumed']
        ]
        self.__iterative = iterative
        self.__max_time = max_time
        self.__max_threads = max_threads
        self.__big_m = big_m
        self.__big_m_value = big_m_value
Esempio n. 3
0
	def __init__(self, S, lb, ub, properties):
		self.S = array(S)
		self.lb, self.ub = array(lb), array(ub)
		self.properties = properties

		rx_names, mt_names = ['V' + str(i) for i in range(S.shape[1])], ['M' + str(i) for i in range(S.shape[0])]
		cbmodel = ConstraintBasedModel(S, list(zip(lb, ub)), reaction_names=rx_names,
									   metabolite_names=mt_names, optimizer=True, solver=properties['solver'])
		self._m, self._n = self.S.shape
		self.corso_fba = CORSOModel(cbmodel, solver=properties['solver'])
Esempio n. 4
0
	def __init__(self, S, lb, ub, properties):
		self.S = np.array(S)
		self.lb, self.ub = np.array(lb), np.array(ub)
		self.properties = properties
		self.model = GIMMEModel
		self.sol = None
		metabolite_names = ['M'+str(i) for i in range(S.shape[0])]
		reaction_names = ['R'+str(i) for i in range(S.shape[1])]
		cbm = ConstraintBasedModel(S, list(zip(lb,ub)), reaction_names=reaction_names, metabolite_names=metabolite_names)
		self.gm = GIMMEModel(cbm, self.properties['solver'])
Esempio n. 5
0
	def to_cobamp_cbm(self, solver=None):
		and_char, or_char, gpr_gene_parse_function, ttg_ratio = self.__gpr_read_params
		ngprs = GPRContainer(
			gpr_list=self.get_model_gpr_strings(),
			and_char=and_char, or_char=or_char, apply_fx=gpr_gene_parse_function, ttg_ratio=ttg_ratio)

		return ConstraintBasedModel(
			S=self.get_stoichiometric_matrix(),
			thermodynamic_constraints=[tuple(float(k) for k in l) for l in self.get_model_bounds()],
			reaction_names=self.r_ids,
			metabolite_names=self.m_ids,
			optimizer= (solver == True) or (solver is not None and solver != False),
			solver=solver if solver not in (True, False) else None,
			gprs=ngprs
		)
Esempio n. 6
0
    def get_gpr_model(F):
        c, g = F.shape

        S = vstack([
            hstack(r) for r in
            [[eye(g), -F.T, zeros([g, c + 1])],
             [zeros([c, g]), eye(c), -eye(c),
              zeros([c, 1])], [zeros([1, c + g]),
                               ones([1, c]), -ones([1, 1])]]
        ])

        bounds = [[0, None] for _ in range(S.shape[1])]
        mn = ['MG' + str(i)
              for i in range(g)] + ['MC' + str(i) for i in range(c)] + ['GPR']
        rn = ['SG'+str(i) for i in range(g)] + ['SC'+str(i) for i in range(c)] + ['OC'+str(i) for i in range(c)] + \
          ['GPRs']
        return ConstraintBasedModel(S,
                                    bounds,
                                    reaction_names=rn,
                                    metabolite_names=mn)
Esempio n. 7
0
    def transform(self, args, properties):

        # args must be:
        # - a dict with 'S', 'lb', 'ub' keys
        # - a ConstraintBasedModel
        if isinstance(args, dict):
            assert len(set(args.keys()) & {'S', 'lb', 'ub'}) == len(set(args.keys())), 'args must contain at least S' + \
                                 ', lb, and ub key-value pairs'

            S, lb, ub = [args[k] for k in ['S', 'lb', 'ub']]
            return self.transform_array(S, lb, ub, properties)

        elif isinstance(args, ConstraintBasedModel):
            S = args.get_stoichiometric_matrix()
            lb, ub = args.get_bounds_as_list()
            new_properties = deepcopy(properties)

            for k in ['block', 'keep']:
                if new_properties[k] != None:
                    new_properties[k] = [
                        args.decode_index(r, 'reaction') for r in properties[k]
                    ]

            Sn, lbn, ubn, mapping, metabs = self.transform_array(
                S, lb, ub, new_properties)

            reaction_names_new = [
                new_properties['reaction_id_sep'].join(
                    [args.reaction_names[i] for i in mapping.from_new(i)])
                for i in range(len(lbn))
            ]
            modeln = ConstraintBasedModel(
                S=Sn,
                thermodynamic_constraints=[
                    list(k) for k in list(zip(lbn, ubn))
                ],
                reaction_names=reaction_names_new,
                metabolite_names=[args.metabolite_names[k] for k in metabs])

            return modeln, mapping, metabs
Esempio n. 8
0
    def setUp(self) -> None:
        rows, cols, data = zip(*((0, 0, 1), (0, 1, -1), (0, 2, -1), (1, 1, 1),
                                 (1, 3, -1), (2, 3, 1), (2, 5, -1), (3, 5, 1),
                                 (3, 7, -1), (4, 2, 1), (4, 4, -1), (5, 4, 1),
                                 (5, 6, -1), (3, 6, 1)))

        # G_test = array([
        # 	[1,0,0,0,0,0,0,0,0,0],
        # 	[0,1,0,1,0,1,0,1,0,0],
        # 	[0,0,1,0,0,0,0,0,0,0],
        # 	[0,0,1,0,0,0,0,0,0,0],
        # 	[0,0,0,1,0,0,0,0,0,0],
        # 	[0,0,1,0,0,0,1,0,1,0],
        # 	[0,1,0,1,1,1,0,1,0,0],
        # 	[0,0,0,1,1,0,0,0,0,0]
        # ])
        #
        # F_test = array([
        # 	[1,0,0,0,0,0,0],
        # 	[0,1,0,0,0,0,0],
        # 	[0,0,1,0,0,0,0],
        # 	[0,0,0,1,0,0,0],
        # 	[0,0,0,0,1,0,0],
        # 	[0,0,1,0,0,1,0],
        # 	[0,1,0,0,0,0,1],
        # 	[0,0,0,0,1,1,1]
        # ])
        #
        # G_test_irrev = G_test[:,[0,5,1,2,3,6,4,9,7,8]]

        S = array(csc_matrix((data, (rows, cols))).todense())
        lb = array([0] * S.shape[1]).astype(float)
        ub = array([1000] * S.shape[1]).astype(float)
        lb[[1, 5]] = -1000
        rx_names = ['r' + str(i + 1) for i in range(S.shape[1] - 1)] + ['rbio']
        met_names = ['m' + str(i + 1)
                     for i in range(S.shape[0] - 1)] + ['mbio']
        gprs = [
            'g1', 'g2', 'g2', 'g3 and g4', 'g2 and g5', 'g3 or g6',
            '(g2 and (g5 or g6)) or g7', ''
        ]
        # gprs_irrev = gprs + [g for i, g in enumerate(gprs) if i in [1, 5]]

        cbm = ConstraintBasedModel(S,
                                   list(zip(lb, ub)),
                                   reaction_names=rx_names,
                                   metabolite_names=met_names,
                                   gprs=gprs)
        irrev_cbm, mapping = cbm.make_irreversible()

        gmat_builder = GeneMatrixBuilder(irrev_cbm.gpr)
        G_new, _, irreducible_gene_map, F_deps, weights = gmat_builder.get_GF_matrices(
        )

        gmcs_enumerator = KShortestGeneticMCSEnumeratorWrapper(
            model=irrev_cbm,
            target_flux_space_dict={'rbio': (1, None)},
            target_yield_space_dict={},
            stop_criteria=len(irrev_cbm.reaction_names),
            algorithm_type='kse_populate',
            excluded_solutions=[],
            G=G_new,
            gene_map=irreducible_gene_map,
            F=F_deps,
            gene_weights=weights)

        self.gmcs_enumerator = gmcs_enumerator
Esempio n. 9
0
class Tasks(object):
	def __init__(self, S, lb, ub, rx_names, met_names, objective_reaction=None, context=None):
		self.model = ConstraintBasedModel(S, list(zip(lb, ub)), reaction_names=rx_names, metabolite_names=met_names)
		if context != None:
			apply_context(self.model, context)
		self.tasks = {}
		self.task_fail_status = {}
		self.__add_reactions = []
		self.flux_constraints = {}

		if objective_reaction:
			self.model.set_objective({objective_reaction: 1}, False)
		else:
			self.model.set_objective({0:1}, False)

	def populate_model(self, task):
		rd, ifd, ofd, flc = task.get_task_components()
		sfail = task.should_fail

		## TODO: excepções para qd um metabolito não existir
		task_equations = {}
		for r_id, tup in rd.items():
			r_mets, bounds = tup
			r_name = '_'.join([task.task_name, r_id])
			self.model.add_reaction(arg=r_mets, bounds=bounds, name=r_name)
			task_equations[r_name] = bounds
			self.__add_reactions.append(r_name)

		task_sinks = {}
		for coef, sinkdict in zip([-1, 1], [ofd, ifd]):
			for m_id, bounds in sinkdict.items():
				r_name = '_'.join([task.task_name, m_id, 'sink'])
				self.model.add_reaction(arg={m_id:coef}, bounds=bounds, name=r_name)
				self.__add_reactions.append(r_name)
				task_sinks[r_name] = bounds
		self.tasks[task.task_name] = (task_equations, task_sinks)
		self.task_fail_status[task.task_name] = sfail
		self.flux_constraints[task.task_name] = flc

	def __run_single_task(self, task):
		return evaluate_task(model=self.model,
							 task_items=self.tasks[task],
							 sfail=self.task_fail_status[task],
							 flux_constraints=self.flux_constraints[task],
							 task_reactions=self.__add_reactions)

	def __task_initializer(self, task):
		if task.task_name not in self.tasks.keys():
			self.populate_model(task)

	def evaluate(self, task_arg):
		if isinstance(task_arg, (list, tuple, set)):
			for task in task_arg:
				if isinstance(task, Task):
					self.__task_initializer(task)
				else:
					raise TypeError('Invalid type object found within the task_arg iterable. Expected Task, found'+str(type(task)))
			if len(task_arg) <= MP_THREADS:
				return {task.task_name:self.__run_single_task(task.task_name) for task in task_arg}
			else:
				return task_pool(self.model, self.tasks, self.task_fail_status, self.flux_constraints, self.__add_reactions)

		elif isinstance(task_arg, Task):
			self.__task_initializer(task_arg)
			return self.__run_single_task(task_arg.task_name)
		else:
			raise TypeError('task_arg expected to be of type Task. Found '+str(type(task_arg))+' instead')