Beispiel #1
0
    def __init__(self):

        parser = argparse.ArgumentParser(description='analyze rate laws')
        parser = self.add_arguments(parser)
        args = parser.parse_args()

        # load all reactions
        self.all_reactions = load_reactions()

        # load dict of saved parameters and save parameter file name as param_id
        parameter_file = args.path
        with open(parameter_file, 'r') as fp:
            kinetic_parameters = json.load(fp)
        self.param_id = parameter_file.split(os.path.sep)[-1].split(".")[0]

        # make a dict of reactions that will be configured with the parameters
        make_reaction_ids = kinetic_parameters.keys()
        make_reactions = {
            reaction_id: specs
            for reaction_id, specs in self.all_reactions.items()
            if reaction_id in make_reaction_ids
        }

        # Make the kinetic model
        self.kinetic_rate_laws = rate_laws.KineticFluxModel(
            make_reactions, kinetic_parameters)

        # Get list of molecule_ids used by kinetic rate laws
        self.molecule_ids = self.kinetic_rate_laws.molecule_ids

        # make look up object and get saved concentrations from wcm (mmol/L)
        self.look_up = LookUp()
        self.concentrations = self.look_up.look_up('average', args.media,
                                                   self.molecule_ids)
        for mol_id, conc in self.concentrations.items():
            if conc is None:
                print(
                    '{} concentration is not available in look up table, setting to 1 mmol/L'
                    .format(mol_id))
                self.concentrations[mol_id] = 1.0

        if args.analyze:
            self.run_analysis()

        if args.template:
            reactions_list = args.template.split(',')
            self.template_from_reactions(reactions_list)

        if args.exchange_template:
            molecule_list = args.exchange_template.split(',')
            self.template_from_exchange(molecule_list)
Beispiel #2
0
    def __init__(self, initial_parameters=None):
        if initial_parameters is None:
            initial_parameters = {}

        self.media_id = 'minimal' # initial_parameters.get('media_id', 'minimal')
        self.lookup_type = 'average' # initial_parameters.get('lookup', 'average')
        self.nAvogadro = constants.N_A * 1/units.mol
        self.external_molecule_ids = external_molecule_ids

        # load all reactions and maps
        self.load_data()

        # external_molecule_ids declares which molecules' exchange will be applied
        self.transport_reaction_ids = get_reactions_from_exchange(self.all_transport_reactions, external_molecule_ids_p)
        all_molecule_ids = get_molecules_from_reactions(self.transport_reaction_ids, self.all_transport_reactions)
        self.internal_molecule_ids = [mol_id for mol_id in all_molecule_ids if mol_id not in external_molecule_ids_p]

        # make look up object
        self.look_up = LookUp()

        parameters = {}
        parameters.update(initial_parameters)
        super(TransportLookup, self).__init__(parameters)
Beispiel #3
0
class RateLawUtilities(object):
    def __init__(self):

        parser = argparse.ArgumentParser(description='analyze rate laws')
        parser = self.add_arguments(parser)
        args = parser.parse_args()

        # load all reactions
        self.all_reactions = load_reactions()

        # load dict of saved parameters and save parameter file name as param_id
        parameter_file = args.path
        with open(parameter_file, 'r') as fp:
            kinetic_parameters = json.load(fp)
        self.param_id = parameter_file.split(os.path.sep)[-1].split(".")[0]

        # make a dict of reactions that will be configured with the parameters
        make_reaction_ids = kinetic_parameters.keys()
        make_reactions = {
            reaction_id: specs
            for reaction_id, specs in self.all_reactions.items()
            if reaction_id in make_reaction_ids
        }

        # Make the kinetic model
        self.kinetic_rate_laws = rate_laws.KineticFluxModel(
            make_reactions, kinetic_parameters)

        # Get list of molecule_ids used by kinetic rate laws
        self.molecule_ids = self.kinetic_rate_laws.molecule_ids

        # make look up object and get saved concentrations from wcm (mmol/L)
        self.look_up = LookUp()
        self.concentrations = self.look_up.look_up('average', args.media,
                                                   self.molecule_ids)
        for mol_id, conc in self.concentrations.items():
            if conc is None:
                print(
                    '{} concentration is not available in look up table, setting to 1 mmol/L'
                    .format(mol_id))
                self.concentrations[mol_id] = 1.0

        if args.analyze:
            self.run_analysis()

        if args.template:
            reactions_list = args.template.split(',')
            self.template_from_reactions(reactions_list)

        if args.exchange_template:
            molecule_list = args.exchange_template.split(',')
            self.template_from_exchange(molecule_list)

    def add_arguments(self, parser):

        parser.add_argument(
            '-a',
            '--analyze',
            action='store_true',
            default=False,
            help='run analysis on parameter files specified by path')

        parser.add_argument(
            '-t',
            '--template',
            type=str,
            default='',
            help=
            'A list of reactions for making an empty parameter template, formatted as "reaction_id_1, reaction_id_2"'
        )

        parser.add_argument(
            '-ex',
            '--exchange_template',
            type=str,
            default='',
            help=
            'A list of exchange molecules for making an empty parameter template, formatted as "molecule_id_1, molecule_id_2"'
        )

        parser.add_argument('-m',
                            '--media',
                            type=str,
                            default='minimal',
                            help='The environment media')

        parser.add_argument(
            '--path',
            type=str,
            default=os.path.join(KINETIC_PARAMETERS_PATH,
                                 'example_parameters.json'),
            help=
            'the path to the parameter file to be analyzed. parameters available in {}'
            .format(KINETIC_PARAMETERS_PATH))

        return parser

    def run_analysis(self):

        # run analyses and save output
        analyze_rate_laws(self.kinetic_rate_laws, self.concentrations,
                          self.param_id)

    def template_from_exchange(self, exchange_molecules):
        '''
        saves a rate law parameter template for the list of exchange molecules

        '''

        # get a list of all reactions with exchange_molecules
        reactions_list = get_reactions_from_exchange(self.all_reactions,
                                                     exchange_molecules)

        self.template_from_reactions(reactions_list)

    def template_from_reactions(self, reactions_list):
        '''
        saves a rate law parameter template for the list of reactions

        '''
        # make a dict of the given reactions using specs from all_reactions
        reactions = {
            reaction_id: self.all_reactions[reaction_id]
            for reaction_id in reactions_list
        }

        # make a parameter template
        parameter_template = self.get_parameter_template(reactions)

        time_stamp = filepath.timestamp()
        output_name = 'parameter_template_' + time_stamp + '.json'
        output_file = os.path.join(OUTPUT_DIR, output_name)
        with open(output_file, 'w') as fp:
            json.dump(parameter_template, fp, sort_keys=True, indent=2)

        print('rate law parameter template saved')

    def get_parameter_template(self, reactions):
        '''
        Given a list of reactions, return a template for required parameters

        Args:
            reactions (dict): a reaction network, with
             {reaction_id: {'catalyzed by': (list), 'is reversible': (bool), 'stoichiometry': (dict)}}

        Returns:
            parameter_template (dict): a template for all parameters required by this rate_law_configuration,
                filled with values of 0.0.

        '''

        rate_law_configuration = rate_laws.make_configuration(reactions)

        parameter_template = {}
        for enzyme_id, configuration in rate_law_configuration.items():
            reaction_cofactors = configuration['reaction_cofactors']
            partition = configuration['partition']

            for reaction_id, cofactors in reaction_cofactors.items():

                # check if reaction is already in the template
                if reaction_id not in parameter_template:
                    parameter_template[reaction_id] = {}

                parameter_template[reaction_id][enzyme_id] = {}
                parameter_template[reaction_id][enzyme_id]['kcat_f'] = None

                reversible = reactions[reaction_id]['is reversible']
                if reversible:
                    parameter_template[reaction_id][enzyme_id]['kcat_r'] = None

                all_bound_molecules = [
                    mol_id for set in partition for mol_id in set
                ]

                for molecule_id in all_bound_molecules:
                    parameter_template[reaction_id][enzyme_id][
                        molecule_id] = None

        return parameter_template
Beispiel #4
0
class TransportLookup(Process):
    def __init__(self, initial_parameters=None):
        if initial_parameters is None:
            initial_parameters = {}

        self.media_id = 'minimal' # initial_parameters.get('media_id', 'minimal')
        self.lookup_type = 'average' # initial_parameters.get('lookup', 'average')
        self.nAvogadro = constants.N_A * 1/units.mol
        self.external_molecule_ids = external_molecule_ids

        # load all reactions and maps
        self.load_data()

        # external_molecule_ids declares which molecules' exchange will be applied
        self.transport_reaction_ids = get_reactions_from_exchange(self.all_transport_reactions, external_molecule_ids_p)
        all_molecule_ids = get_molecules_from_reactions(self.transport_reaction_ids, self.all_transport_reactions)
        self.internal_molecule_ids = [mol_id for mol_id in all_molecule_ids if mol_id not in external_molecule_ids_p]

        # make look up object
        self.look_up = LookUp()

        parameters = {}
        parameters.update(initial_parameters)
        super(TransportLookup, self).__init__(parameters)

    def ports_schema(self):
        media_id = 'minimal_plus_amino_acids'
        make_media = Media()
        media = make_media.get_saved_media(media_id)
        schema = {
            'global': {
                'volume': {
                    '_default': 1}},
            'external': {
                state_id: {
                    '_default': value,
                    '_emit': True}
                for state_id, value in media.items()},
            'internal': {
                state_id: {
                    '_default': 0.0}
                for state_id in self.internal_molecule_ids},
            'exchange': {
                state_id: {
                    '_default': 0.0,
                    '_emit': True}
                for state_id in self.external_molecule_ids},
        }

        return schema


    def next_update(self, timestep, states):
        external = states['external'] # TODO -- use external state? if concentrations near 0, cut off flux?

        volume = states['global']['volume'] * units.fL
        mmol_to_counts = self.nAvogadro.to('1/mmol') * volume.to('L')

        # get transport fluxes
        transport_fluxes = self.look_up.look_up(
            self.lookup_type,
            self.media_id,
            self.transport_reaction_ids)

        # time step dependence
        # TODO (Eran) -- load units in look_up
        transport_fluxes = {key: value * (FLUX_UNITS) * timestep * TIME_UNITS
                                 for key, value in transport_fluxes.items()}

        # convert to counts
        delta_counts = self.flux_to_counts(transport_fluxes, mmol_to_counts)

        # Get the deltas for environmental molecules
        environment_deltas = {}
        for molecule_id in delta_counts.keys():
            if molecule_id in self.molecule_to_external_map:
                external_molecule_id = self.molecule_to_external_map[molecule_id]
                environment_deltas[external_molecule_id] = delta_counts[molecule_id]

        return {'exchange': environment_deltas}

    # TODO (Eran) -- make this a util
    def flux_to_counts(self, fluxes, conversion):

        rxn_counts = {reaction_id: int(conversion * flux) for reaction_id, flux in fluxes.items()}
        delta_counts = {}
        for reaction_id, rxn_count in rxn_counts.items():
            stoichiometry = self.all_transport_reactions[reaction_id]['stoichiometry']
            substrate_counts = {substrate_id: coeff * rxn_count for substrate_id, coeff in stoichiometry.items()}
            # add to delta_counts
            for substrate, delta in substrate_counts.items():
                if substrate in delta_counts:
                    delta_counts[substrate] += delta
                else:
                    delta_counts[substrate] = delta

        return delta_counts

    def load_data(self):
        '''
        - Loads all reactions, including locations for enzymes.
        - Separates out the transport reactions as an class dictionary
        - Makes mappings from molecule ids with location tags to external molecules without location tags

        '''

        # use rate_law_utilities to get all_reactions
        all_reactions = load_reactions()

        # make dict of reactions in TRANSPORT_IDS_FILE
        self.all_transport_reactions = {}
        rows = load_tsv(TRANSPORT_IDS_FILE)
        for row in rows:
            reaction_id = row['reaction id']
            stoichiometry = all_reactions[reaction_id]['stoichiometry']
            reversible = all_reactions[reaction_id]['is reversible']
            transporters_loc = all_reactions[reaction_id]['catalyzed by']

            self.all_transport_reactions[reaction_id] = {
                'stoichiometry': stoichiometry,
                'is reversible': reversible,
                'catalyzed by': transporters_loc}

        # Make map of external molecule_ids with a location tag (as used in reaction stoichiometry) to molecule_ids in the environment
        self.molecule_to_external_map = {}
        self.external_to_molecule_map = {}
        rows = load_tsv(EXTERNAL_MOLECULES_FILE)
        for row in rows:
            molecule_id = row['molecule id']
            location = row['exchange molecule location']
            self.molecule_to_external_map[molecule_id + location] = molecule_id
            self.external_to_molecule_map[molecule_id] = molecule_id + location