Infer compartment entries for model based on reaction compounds.
427406
def infer_compartment_entries(model):
    """"""
    compartment_ids = set()
    for reaction in model.reactions:
        equation = reaction.equation
        if equation is None:
            continue

        for compound, _ in equation.compounds:
            compartment = compound.compartment
            if compartment is None:
                compartment = model.default_compartment

            if compartment is not None:
                compartment_ids.add(compartment)

    for compartment in compartment_ids:
        if compartment in model.compartments:
            continue

        entry = DictCompartmentEntry(dict(id=compartment))
        model.compartments.add_entry(entry)
722697
def run(self):
        """"""

        # Load compound information
        def compound_name(id):
            if id not in self._model.compounds:
                return id
            return self._model.compounds[id].properties.get('name', id)

        # Create a set of excluded reactions
        exclude = set(self._args.exclude)
        count = 0
        unbalanced = 0
        unchecked = 0
        for reaction, charge in charge_balance(self._model):
            count += 1

            if reaction.id in exclude or reaction.equation is None:
                continue

            if math.isnan(charge):
                logger.debug('Not checking reaction {};'
                             ' missing charge'.format(reaction.id))
                unchecked += 1
            elif abs(charge) > self._args.epsilon:
                unbalanced += 1
                rxt = reaction.equation.translated_compounds(compound_name)
                print('{}\t{}\t{}'.format(reaction.id, charge, rxt))

        logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count))
        logger.info('Unchecked reactions due to missing charge: {}/{}'.format(
            unchecked, count))
        logger.info('Reactions excluded from check: {}/{}'.format(
            len(exclude), count))
328473
def convert_reaction_entry(self, reaction):
        """"""
        d = OrderedDict()
        d['id'] = reaction.id

        def is_equation_valid(equation):
            # If the equation is a Reaction object, it must have non-zero
            # number of compounds.
            return (equation is not None and (
                    not isinstance(equation, Reaction) or
                    len(equation.compounds) > 0))

        order = {
            key: i for i, key in enumerate(
                ['name', 'genes', 'equation', 'subsystem', 'ec'])}
        prop_keys = (set(reaction.properties) -
                     {'lower_flux', 'upper_flux', 'reversible'})
        for prop in sorted(prop_keys, key=lambda x: (order.get(x, 1000), x)):
            if reaction.properties[prop] is None:
                continue
            d[prop] = reaction.properties[prop]
            if prop == 'equation' and not is_equation_valid(d[prop]):
                del d[prop]

        return d
549878
def parse_reaction(reaction_def, default_compartment, context=None):
    

    reaction_id = reaction_def.get('id')
    _check_id(reaction_id, 'Reaction')

    reaction_props = dict(reaction_def)

    # Parse reaction equation
    if 'equation' in reaction_def:
        reaction_props['equation'] = parse_reaction_equation(
            reaction_def['equation'], default_compartment)

    mark = FileMark(context, None, None)
    return ReactionEntry(reaction_props, mark)
19177
def write_yaml_model(model, dest='.', convert_exchange=True,
                     split_subsystem=True):
    
    yaml.SafeDumper.add_representer(OrderedDict, _dict_representer)
    yaml.SafeDumper.add_representer(set, _set_representer)
    yaml.SafeDumper.add_representer(frozenset, _set_representer)
    yaml.SafeDumper.add_representer(
        boolean.Expression, _boolean_expression_representer)
    yaml.SafeDumper.add_representer(Decimal, _decimal_representer)

    yaml.SafeDumper.ignore_aliases = lambda *args: True

    yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
                         _dict_constructor)

    yaml_args = {'default_flow_style': False,
                 'encoding': 'utf-8',
                 'allow_unicode': True,
                 'width': 79}

    # The ModelWriter from PSAMM is not yet able to write the full model but
    # only reactions and compounds.
    writer = ModelWriter()

    with open(os.path.join(dest, 'compounds.yaml'), 'w+') as f:
        writer.write_compounds(f, sorted(model.compounds, key=lambda c: c.id))

    if model.default_flux_limit is None:
        model.default_flux_limit = detect_best_flux_limit(model)

    if model.extracellular_compartment is None:
        model.extracellular_compartment = (
            sbml.detect_extracellular_compartment(model))

    if model.default_compartment is None:
        model.default_compartment = get_default_compartment(model)

    if model.default_flux_limit is not None:
        logger.info('Using default flux limit of {}'.format(
            model.default_flux_limit))

    if convert_exchange:
        logger.info('Converting exchange reactions to exchange file')
        sbml.convert_exchange_to_compounds(model)

    if len(model.compartments) == 0:
        infer_compartment_entries(model)
        logger.info('Inferred {} compartments: {}'.format(
            len(model.compartments),
            ', '.join(c.id for c in model.compartments)))

    if len(model.compartments) != 0 and len(model.compartment_boundaries) == 0:
        infer_compartment_adjacency(model)

    reaction_files = reactions_to_files(model, dest, writer, split_subsystem)

    if len(model.exchange) > 0:
        with open(os.path.join(dest, 'exchange.yaml'), 'w+') as f:
            yaml.safe_dump(model_exchange(model), f, **yaml_args)

    reaction_limits = list(model_reaction_limits(model))
    if len(reaction_limits) > 0:
        with open(os.path.join(dest, 'limits.yaml'), 'w+') as f:
            yaml.safe_dump(reaction_limits, f, **yaml_args)

    model_d = OrderedDict()
    if model.name is not None:
        model_d['name'] = model.name

    if model.biomass_reaction is not None:
        model_d['biomass'] = model.biomass_reaction
    if model.default_flux_limit is not None:
        model_d['default_flux_limit'] = model.default_flux_limit
    if model.extracellular_compartment != 'e':
        model_d['extracellular'] = model.extracellular_compartment
    if model.default_compartment != 'c':
        model_d['default_compartment'] = model.default_compartment

    if len(model.compartments) > 0:
        adjacency = {}
        for c1, c2 in model.compartment_boundaries:
            adjacency.setdefault(c1, set()).add(c2)
            adjacency.setdefault(c2, set()).add(c1)

        compartment_list = []
        for compartment in sorted(model.compartments, key=lambda c: c.id):
            adjacent = adjacency.get(compartment.id)
            if adjacent is not None and len(adjacent) == 1:
                adjacent = next(iter(adjacent))
            compartment_list.append(writer.convert_compartment_entry(
                compartment, adjacent))

        model_d['compartments'] = compartment_list

    model_d['compounds'] = [{'include': 'compounds.yaml'}]
    model_d['reactions'] = []
    for reaction_file in reaction_files:
        model_d['reactions'].append({'include': reaction_file})

    if len(model.exchange) > 0:
        model_d['exchange'] = [{'include': 'exchange.yaml'}]

    if len(reaction_limits) > 0:
        model_d['limits'] = [{'include': 'limits.yaml'}]

    with open(os.path.join(dest, 'model.yaml'), 'w+') as f:
        yaml.safe_dump(model_d, f, **yaml_args)
773567
def create_model(self):
        
        properties = {
            'name': self.name,
            'default_flux_limit': 1000
        }

        # Load objective as biomass reaction
        objective = self.get_active_objective()
        if objective is not None:
            reactions = dict(objective.reactions)
            if len(reactions) == 1:
                reaction, value = next(iteritems(reactions))
                if ((value < 0 and objective.type == 'minimize') or
                        (value > 0 and objective.type == 'maximize')):
                    properties['biomass'] = reaction

        model = NativeModel(properties)

        # Load compartments into model
        for compartment in self.compartments:
            model.compartments.add_entry(compartment)

        # Load compounds into model
        for compound in self.species:
            model.compounds.add_entry(compound)

        # Load reactions into model
        for reaction in self.reactions:
            model.reactions.add_entry(reaction)

        # Create model reaction set
        for reaction in model.reactions:
            model.model[reaction.id] = None

        # Convert reaction limits properties to proper limits
        for reaction in model.reactions:
            props = reaction.properties
            if 'lower_flux' in props or 'upper_flux' in props:
                lower = props.get('lower_flux')
                upper = props.get('upper_flux')
                model.limits[reaction.id] = reaction.id, lower, upper

        # Load model limits from FBC V1 bounds if present, i.e. if FBC V1 is
        # used instead of V2.
        limits_lower = {}
        limits_upper = {}
        for bounds in self.flux_bounds:
            reaction = bounds.reaction
            if reaction in model.limits:
                continue

            if bounds.operation == SBMLFluxBoundEntry.LESS_EQUAL:
                if reaction not in limits_upper:
                    limits_upper[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))
            elif bounds.operation == SBMLFluxBoundEntry.GREATER_EQUAL:
                if reaction not in limits_lower:
                    limits_lower[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))
            elif bounds.operation == SBMLFluxBoundEntry.EQUAL:
                if (reaction not in limits_lower and
                        reaction not in limits_upper):
                    limits_lower[reaction] = bounds.value
                    limits_upper[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))

        for reaction in model.reactions:
            if reaction.id in limits_lower or reaction.id in limits_upper:
                lower = limits_lower.get(reaction.id, None)
                upper = limits_upper.get(reaction.id, None)
                model.limits[reaction.id] = reaction.id, lower, upper

        return model
148047
def run(self):
        """"""

        # Load compound information
        def compound_name(id):
            if id not in self._model.compounds:
                return id
            return self._model.compounds[id].properties.get('name', id)

        epsilon = self._args.epsilon

        if self._args.unrestricted:
            # Allow all exchange reactions with no flux limits
            for reaction in self._mm.reactions:
                if self._mm.is_exchange(reaction):
                    del self._mm.limits[reaction].bounds

        loop_removal = self._get_loop_removal_option()
        enable_tfba = loop_removal == 'tfba'
        enable_fastcore = self._args.fastcore

        if enable_tfba and enable_fastcore:
            self.argument_error(
                'Using Fastcore with thermodynamic constraints'
                ' is not supported!')
        start_time = time.time()

        if enable_fastcore:
            solver = self._get_solver()
            try:
                inconsistent = set(fastcore.fastcc(
                    self._mm, epsilon, solver=solver))
            except fluxanalysis.FluxBalanceError as e:
                self.report_flux_balance_error(e)
        else:
            if enable_tfba:
                solver = self._get_solver(integer=True)
            else:
                solver = self._get_solver()

            if self._args.reduce_lp:
                logger.info('Running with reduced number of LP problems.')
                try:
                    inconsistent = set(
                        fluxanalysis.consistency_check(
                            self._mm, self._mm.reactions, epsilon,
                            tfba=enable_tfba, solver=solver))
                except fluxanalysis.FluxBalanceError as e:
                    self.report_flux_balance_error(e)
            else:
                logger.info('Using flux bounds to determine consistency.')
                try:
                    inconsistent = set(self._run_fva_fluxcheck(
                        self._mm, solver, enable_tfba, epsilon))
                except FluxCheckFVATaskError:
                    self.report_flux_balance_error()

        logger.info('Solving took {:.2f} seconds'.format(
            time.time() - start_time))

        # Count the number of reactions that are fixed at zero. While these
        # reactions are still inconsistent, they are inconsistent because they
        # have been explicitly disabled.
        disabled_exchange = 0
        disabled_internal = 0

        count_exchange = 0
        total_exchange = 0

        count_internal = 0
        total_internal = 0

        # Print result
        for reaction in sorted(self._mm.reactions):
            disabled = self._mm.limits[reaction].bounds == (0, 0)

            if self._mm.is_exchange(reaction):
                total_exchange += 1
                count_exchange += int(reaction in inconsistent)
                disabled_exchange += int(disabled)
            else:
                total_internal += 1
                count_internal += int(reaction in inconsistent)
                disabled_internal += int(disabled)

            if reaction in inconsistent:
                rx = self._mm.get_reaction(reaction)
                rxt = rx.translated_compounds(compound_name)
                print('{}\t{}'.format(reaction, rxt))

        logger.info('Model has {}/{} inconsistent internal reactions'
                    ' ({} disabled by user)'.format(
                        count_internal, total_internal, disabled_internal))
        logger.info('Model has {}/{} inconsistent exchange reactions'
                    ' ({} disabled by user)'.format(
                        count_exchange, total_exchange, disabled_exchange))
1050589
def parse_reaction_equation(equation_def, default_compartment):
    

    def parse_compound_list(l, compartment):
        """Parse a list of reactants or metabolites"""
        for compound_def in l:
            compound_id = compound_def.get('id')
            _check_id(compound_id, 'Compound')

            value = compound_def.get('value')
            if value is None:
                raise ParseError('Missing value for compound {}'.format(
                    compound_id))

            compound_compartment = compound_def.get('compartment')
            if compound_compartment is None:
                compound_compartment = compartment

            compound = Compound(compound_id, compartment=compound_compartment)
            yield compound, value

    if isinstance(equation_def, string_types):
        return parse_reaction_equation_string(
            equation_def, default_compartment)
    else:
        compartment = equation_def.get('compartment', default_compartment)
        reversible = bool(equation_def.get('reversible', True))
        left = equation_def.get('left', [])
        right = equation_def.get('right', [])
        if len(left) == 0 and len(right) == 0:
            raise ParseError('Reaction values are missing')

        return Reaction(Direction.Both if reversible else Direction.Forward,
                        parse_compound_list(left, compartment),
                        parse_compound_list(right, compartment))
1145724
def parse_model(self):
        """"""

        if self.has_model_definition():
            for reaction_id in parse_model_group_list(
                    self._context, self._model['model']):
                yield reaction_id
541421
def parse_reaction_table_file(path, f, default_compartment):
    

    context = FilePathContext(path)

    for lineno, row in enumerate(csv.DictReader(f, delimiter=str('\t'))):
        if 'id' not in row or row['id'].strip() == '':
            raise ParseError('Expected `id` column in table')

        props = {key: value for key, value in iteritems(row) if value != ''}

        if 'equation' in props:
            props['equation'] = parse_reaction_equation_string(
                props['equation'], default_compartment)

        mark = FileMark(context, lineno + 2, 0)
        yield ReactionEntry(props, mark)
1157459
@SuppressWarnings("unchecked")
	protected void calculateIndirectAmbiguities() {
		Map<NucleotideCompound, List<NucleotideCompound>> equivalentsMap = new HashMap<NucleotideCompound, List<NucleotideCompound>>();

		List<NucleotideCompound> ambiguousCompounds = new ArrayList<NucleotideCompound>();
		for(NucleotideCompound compound: getAllCompounds()) {
			if (!compound.isAmbiguous()) {
				continue;
			}
			ambiguousCompounds.add(compound);
		}

		for(NucleotideCompound sourceCompound: ambiguousCompounds) {
			Set<NucleotideCompound> compoundConstituents = sourceCompound.getConstituents();
			for(NucleotideCompound targetCompound: ambiguousCompounds) {
				Set<NucleotideCompound> targetConstituents = targetCompound.getConstituents();
				if(targetConstituents.containsAll(compoundConstituents)) {
					NucleotideCompound lcSourceCompound = toLowerCase(sourceCompound);
					NucleotideCompound lcTargetCompound = toLowerCase(targetCompound);

				//equivalentsMap.put(sourceCompound, targetCompound);
			//      equivalentsMap.put(sourceCompound, lcTargetCompound);


					checkAdd(equivalentsMap, sourceCompound, targetCompound);
					checkAdd(equivalentsMap, sourceCompound, lcTargetCompound);

					checkAdd(equivalentsMap,targetCompound,sourceCompound);
					checkAdd(equivalentsMap, lcTargetCompound, sourceCompound);

					checkAdd(equivalentsMap, lcSourceCompound, targetCompound);
					checkAdd(equivalentsMap, lcSourceCompound, lcTargetCompound);

				}
			}
		}

		//And once it's all done start adding them to the equivalents map

		for ( NucleotideCompound key: equivalentsMap.keySet()){
			List<NucleotideCompound> vals = equivalentsMap.get(key);
			for (NucleotideCompound value: vals){
				addEquivalent((C)key,(C)value);
				addEquivalent((C)value,(C)key);
			}
		}
	}
1171227
def construct_model(images,
                    actions=None,
                    context_frames=2,
                    hparams=None,
                    is_training=True):
  """"""

  pred_depth = 20

  enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [], [], [], []

  lstm_states = [None] * (pred_depth + 2)

  enc_out = encoder_vgg(
      images[0], hparams.enc_size, False, scope_prefix='timestep/',
      hparams=hparams, is_training=is_training)
  enc_out = tf.identity(enc_out, 'enc_out')
  enc_out_all.append(enc_out)

  num_timesteps = len(actions) - 1
  sum_freq = int(num_timesteps / 4 + 1)

  reuse = False
  for timestep, action in zip(range(len(actions) - 1), actions[:-1]):
    done_warm_start = timestep > context_frames - 1

    with tf.variable_scope('timestep', reuse=reuse):
      if done_warm_start:
        pred_input = pred_out_all[-1]
      else:
        pred_input = enc_out_all[-1]
      pred_out = predictor(
          pred_input, action, lstm_states, pred_depth, False, hparams=hparams)
      pred_out = tf.identity(pred_out, 'pred_out')
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('pred_out', pred_out)
      pred_out_all.append(pred_out)

      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('lstm_state', lstm_states[0])
      van_out, _, _ = van(
          enc_out_all[0],
          images[0],
          pred_out,
          images[timestep + 1],
          tf.AUTO_REUSE,
          hparams=hparams)
      van_out = tf.identity(van_out, 'van_out')
      van_out_all.append(van_out)

      enc_out = encoder_vgg(
          images[timestep + 1], hparams.enc_size, True, hparams=hparams,
          is_training=is_training)
      enc_out = tf.identity(enc_out, 'enc_out')
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('enc_out', enc_out)
      enc_out_all.append(enc_out)

      van_input = images[0]
      enc_noise = tf.zeros_like(enc_out)
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('enc_noise', enc_noise)
      van_on_enc, _, _ = van(
          enc_out_all[0],
          van_input,
          enc_out + enc_noise,
          images[timestep + 1],
          tf.AUTO_REUSE,
          hparams=hparams)
      van_on_enc = tf.identity(van_on_enc, 'van_on_enc')
      van_on_enc_all.append(van_on_enc)

      reuse = True

  return enc_out_all, pred_out_all, van_out_all, van_on_enc_all
1130060
def write_model(self, file, model, pretty=False):
        
        ET.register_namespace('mathml', MATHML_NS)
        ET.register_namespace('xhtml', XHTML_NS)
        ET.register_namespace('fbc', FBC_V2)

        # Load compound information
        compound_name = {}
        compound_properties = {}
        for compound in model.compounds:
            compound_name[compound.id] = (
                compound.name if compound.name is not None else compound.id)
            compound_properties[compound.id] = compound.properties

        model_reactions = set(model.model)

        reaction_properties = {}
        biomass_id = None
        for r in model.reactions:
            if (model_reactions is not None and
                    r.id not in model_reactions):
                continue

            reaction_id = util.create_unique_id(
                self._make_safe_id(r.id), reaction_properties)
            if r.id == model.biomass_reaction:
                biomass_id = reaction_id

            reaction_properties[reaction_id] = r.properties

        # Add exchange reactions to reaction_properties,
        # also add flux limit info to flux_limits
        flux_limits = {}
        for compound, reaction_id, lower, upper in itervalues(model.exchange):
            # Create exchange reaction
            if reaction_id is None:
                reaction_id = create_exchange_id(reaction_properties, compound)
            reaction_id = util.create_unique_id(
                self._make_safe_id(reaction_id), reaction_properties)

            reaction_properties[reaction_id] = {
                'id': reaction_id,
                'equation': Reaction(Direction.Both, {compound: -1})
            }

            if lower is None:
                lower = -model.default_flux_limit
            if upper is None:
                upper = model.default_flux_limit
            flux_limits[reaction_id] = (lower, upper)

            # Create a dummy properties dict for undefined compounds
            if compound.name not in compound_properties:
                compound_properties[compound.name] = {
                    'id': compound.name
                }

        root = ET.Element(self._sbml_tag('sbml'))
        root.set(self._sbml_tag('level'), '3')
        root.set(self._sbml_tag('version'), '1')
        root.set(_tag('required', FBC_V2), 'false')
        if model.version_string is not None:
            notes_tag = ET.SubElement(root, self._sbml_tag('notes'))
            body_tag = ET.SubElement(notes_tag, _tag('body', XHTML_NS))
            self._add_properties_notes(
                body_tag, {'model version': model.version_string})

        model_tag = ET.SubElement(root, self._sbml_tag('model'))
        model_tag.set(_tag('strict', FBC_V2), 'true')
        if model.name is not None:
            model_tag.set(self._sbml_tag('name'), model.name)

        # Build mapping from Compound to species ID
        model_compartments = {}
        model_species = {}
        species_ids = set()
        for _, properties in iteritems(reaction_properties):
            for compound, _ in properties['equation'].compounds:
                if compound in model_species:
                    continue

                # Create a dummy properties dict for undefined compounds
                if compound.name not in compound_properties:
                    compound_properties[compound.name] = {
                        'id': compound.name
                    }

                compound_id = util.create_unique_id(
                    self._make_safe_id(compound.name), species_ids)
                model_species[compound] = compound_id
                species_ids.add(compound_id)
                if compound.compartment not in model_compartments:
                    model_compartments[
                        compound.compartment] = 'C_' + util.create_unique_id(
                            self._make_safe_id(compound.compartment),
                            model_compartments)

        # Create list of compartments
        compartments = ET.SubElement(
            model_tag, self._sbml_tag('listOfCompartments'))
        for _, compartment_id in iteritems(model_compartments):
            compartment_tag = ET.SubElement(
                compartments, self._sbml_tag('compartment'))
            compartment_tag.set(self._sbml_tag('id'), compartment_id)
            compartment_tag.set(self._sbml_tag('constant'), 'true')

        # Create list of species
        species_list = ET.SubElement(
            model_tag, self._sbml_tag('listOfSpecies'))
        for species, species_id in sorted(
                iteritems(model_species), key=lambda x: x[1]):
            species_tag = ET.SubElement(species_list,
                                        self._sbml_tag('species'))
            species_tag.set(self._sbml_tag('id'), 'M_' + species_id)
            species_tag.set(
                self._sbml_tag('name'),
                compound_name.get(species.name, species.name))
            species_tag.set(
                self._sbml_tag('compartment'),
                model_compartments[species.compartment])
            species_tag.set(self._sbml_tag('constant'), 'false')
            species_tag.set(self._sbml_tag('boundaryCondition'), 'false')
            species_tag.set(self._sbml_tag('hasOnlySubstanceUnits'), 'true')
            if 'charge' in compound_properties[species.name]:
                species_tag.set(_tag('charge', FBC_V2), text_type(
                    compound_properties[species.name]['charge']))
            if 'formula' in compound_properties[species.name]:
                species_tag.set(_tag(
                    'chemicalFormula', FBC_V2), text_type(
                        compound_properties[species.name]['formula']))

            notes_tag = ET.SubElement(species_tag, self._sbml_tag('notes'))
            body_tag = ET.SubElement(notes_tag, _tag('body', XHTML_NS))
            self._add_properties_notes(
                body_tag, compound_properties[species.name])

        params_list = ET.SubElement(
            model_tag, self._sbml_tag('listOfParameters'))

        # Create mapping for reactions containing flux limit definitions
        for rxn_id, lower_lim, upper_lim in itervalues(model.limits):
            flux_limits[rxn_id] = lower_lim, upper_lim

        params = {}
        gene_ids = {}

        if biomass_id is not None:
            self._add_fbc_objective(model_tag, biomass_id)

        # Create list of reactions
        reactions = ET.SubElement(model_tag, self._sbml_tag('listOfReactions'))
        for eq_id, properties in sorted(iteritems(reaction_properties)):
            reaction_tag = ET.SubElement(reactions, self._sbml_tag('reaction'))
            equation = properties['equation']

            reaction_tag.set(self._sbml_tag('id'), 'R_' + eq_id)
            if 'name' in properties:
                reaction_tag.set(self._sbml_tag('name'), properties['name'])
            reaction_tag.set(self._sbml_tag('reversible'), text_type(
                equation.direction == Direction.Both).lower())
            reaction_tag.set(self._sbml_tag('fast'), 'false')
            lower_str, upper_str = self._get_flux_bounds(
                eq_id, model, flux_limits, equation)

            params[upper_str] = 'P_'+self._make_safe_numerical_id(upper_str)
            params[lower_str] = 'P_'+self._make_safe_numerical_id(lower_str)
            reaction_tag.set(
                _tag('upperFluxBound', FBC_V2), params[upper_str])
            reaction_tag.set(
                _tag('lowerFluxBound', FBC_V2), params[lower_str])

            if 'genes' in properties:
                self._add_gene_associations(
                    eq_id, properties['genes'], gene_ids, reaction_tag)

            if any(value < 0 for _, value in equation.compounds):
                reactants = ET.SubElement(
                    reaction_tag, self._sbml_tag('listOfReactants'))

            if any(value > 0 for _, value in equation.compounds):
                products = ET.SubElement(
                    reaction_tag, self._sbml_tag('listOfProducts'))

            for compound, value in sorted(equation.compounds):
                dest_list = reactants if value < 0 else products
                spec_ref = ET.SubElement(
                    dest_list, self._sbml_tag('speciesReference'))
                spec_ref.set(
                    self._sbml_tag('species'), 'M_' + model_species[compound])
                spec_ref.set(
                    self._sbml_tag('constant'), 'true')
                spec_ref.set(
                    self._sbml_tag('stoichiometry'), text_type(abs(value)))

            notes_tag = ET.SubElement(reaction_tag, self._sbml_tag('notes'))
            body_tag = ET.SubElement(notes_tag, _tag('body', XHTML_NS))
            self._add_properties_notes(body_tag, reaction_properties[eq_id])

            if self._cobra_flux_bounds is True:
                # Create COBRA-compliant parameter list
                kl_tag = ET.SubElement(
                    reaction_tag, self._sbml_tag('kineticLaw'))
                math_tag = ET.SubElement(kl_tag, self._sbml_tag('math'))
                ci_tag = ET.SubElement(math_tag, _tag('ci', MATHML_NS))
                ci_tag.text = 'FLUX_VALUE'
                param_list = ET.SubElement(
                    kl_tag, self._sbml_tag('listOfParameters'))

                ET.SubElement(param_list, self._sbml_tag('parameter'), {
                    self._sbml_tag('id'): 'LOWER_BOUND',
                    self._sbml_tag('name'): 'LOWER_BOUND',
                    self._sbml_tag('value'): lower_str,
                    self._sbml_tag('constant'): 'true'
                })
                ET.SubElement(param_list, self._sbml_tag('parameter'), {
                    self._sbml_tag('id'): 'UPPER_BOUND',
                    self._sbml_tag('name'): 'UPPER_BOUND',
                    self._sbml_tag('value'): upper_str,
                    self._sbml_tag('constant'): 'true'
                })

        for val, id in iteritems(params):
            param_tag = ET.SubElement(params_list, self._sbml_tag('parameter'))
            param_tag.set(self._sbml_tag('id'), id)
            param_tag.set(self._sbml_tag('value'), val)
            param_tag.set(self._sbml_tag('constant'), 'true')

        self._add_gene_list(model_tag, gene_ids)

        tree = ET.ElementTree(root)
        if pretty:
            self._indent(root)

        write_options = dict(
            encoding='utf-8',
            default_namespace=self._namespace)
        if PY3:
            write_options['encoding'] = 'unicode'
        tree.write(file, **write_options)
1200092
def getPyroleLikeAtoms(cycle):
    """"""    
    result = {}
    # the outgoing bonds might need to be single or aromatic
    for atom in cycle.atoms:
        lookup = (atom.symbol, atom.charge, atom.hcount, len(atom.bonds))
        if PyroleTable.get(lookup, 0):
            result[atom.handle] = atom

    return result
40469
def calculate_descriptors(self,mol):
		""""""
		#make dictionary
		self.ligand_atoms = {index:{"name":x.name} for index,x in enumerate(self.topology_data.universe.ligand_noH.atoms)}

		#Calculate logP and MR
		contribs = self.calculate_logP(mol)

		#Calculate Gasteiger charges
		self.calculate_Gasteiger_charges(mol)

		#Calculate formal charges
		fcharges = self.calculate_formal_charge(mol)

		for atom in self.ligand_atoms.keys():
			self.ligand_atoms[atom]["logP"]=contribs[atom][0]
			self.ligand_atoms[atom]["MR"]=contribs[atom][1]
			self.ligand_atoms[atom]["Gasteiger_ch"]=mol.GetAtomWithIdx(atom).GetProp("_GasteigerCharge")
			self.ligand_atoms[atom]["Formal charges"]=fcharges[atom]

		#Determine rotatable bonds
		self.rot_bonds=self.get_rotatable_bonds(mol)
1070027
def find_nonzero_constrained_reactions(model):
    """"""
    lower_bound, upper_bound = helpers.find_bounds(model)
    return [rxn for rxn in model.reactions if
            0 > rxn.lower_bound > lower_bound or
            0 < rxn.upper_bound < upper_bound]
1272695
private IChemModel readChemModel(IChemModel chemModel) throws CDKException {
        IReactionSet setOfReactions = chemModel.getReactionSet();
        if (setOfReactions == null) {
            setOfReactions = chemModel.getBuilder().newInstance(IReactionSet.class);
        }
        chemModel.setReactionSet(readReactionSet(setOfReactions));
        return chemModel;
    }