code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
define_kwargs = dict(self._define_kwargs) define_kwargs.update(kwargs) self._problem.define( *((self, name) for name in names), **define_kwargs)
def define(self, names, **kwargs)
Define variables within the namespace. This is similar to :meth:`.Problem.define` except that names must be given as an iterable. This method accepts the same keyword arguments as :meth:`.Problem.define`.
4.758469
4.723336
1.007438
return self._problem.set((self, name) for name in names)
def set(self, names)
Return a variable set of the given names in the namespace. >>> v = prob.namespace(name='v') >>> v.define([1, 2, 5], lower=0, upper=10) >>> prob.add_linear_constraints(v.set([1, 2]) >= 4)
16.009785
32.125935
0.498345
return Expression({(self, name): value for name, value in items})
def expr(self, items)
Return the sum of each name multiplied by a coefficient. >>> v = prob.namespace(name='v') >>> v.define(['a', 'b', 'c'], lower=0, upper=10) >>> prob.set_objective(v.expr([('a', 2), ('b', 1)]))
14.779688
31.824951
0.464406
def cast_value(v): # Convert Decimal to Fraction to allow successful multiplication # by either float (most solvers) or Fraction (exact solver). # Multiplying Fraction and float results in a float, and # multiplying Fraction and Fraction result in Fractio...
def _evaluate_expression(self, expr)
Evaluate an :class:`.Expression` using :meth:`_get_value`.
6.068674
5.830991
1.040762
if isinstance(expression, Expression): return self._evaluate_expression(expression) elif not self._has_variable(expression): raise ValueError('Unknown expression: {}'.format(expression)) return self._get_value(expression)
def get_value(self, expression)
Get value of variable or expression in result Expression can be an object defined as a name in the problem, in which case the corresponding value is simply returned. If expression is an actual :class:`.Expression` object, it will be evaluated using the values from the result.
3.745317
3.571086
1.048789
names = tuple(names) for name in names: if name in self._variables: raise ValueError('Variable already defined: {!r}'.format(name)) lower = kwargs.get('lower', None) upper = kwargs.get('upper', None) vartype = kwargs.get('types', None) ...
def define(self, *names, **kwargs)
Define a variable in the problem. Variables must be defined before they can be accessed by var() or set(). This function takes keyword arguments lower and upper to define the bounds of the variable (default: -inf to inf). The keyword argument types can be used to select the type of the ...
2.34289
2.200072
1.064915
names = [] expression = relation.expression for value_set in expression.value_sets(): name = next(self._constr_names) self._p.addConstr( self._grb_expr_from_value_set(value_set), self.CONSTR_SENSE_MAP[relation.sense], ...
def _add_constraints(self, relation)
Add the given relation as one or more constraints. Return a list of the names of the constraints added.
6.361283
5.844769
1.088372
if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression() self._p.setObjective( self._grb_expr_from_value_set(expression.values()))
def set_objective(self, expression)
Set linear objective of problem.
12.60507
11.503744
1.095736
if sense not in (ObjectiveSense.Minimize, ObjectiveSense.Maximize): raise ValueError('Invalid objective sense') self._p.ModelSense = self.OBJ_SENSE_MAP[sense]
def set_objective_sense(self, sense)
Set type of problem (maximize or minimize).
4.509742
4.632243
0.973555
if sense is not None: self.set_objective_sense(sense) self._p.optimize() self._result = Result(self) return self._result
def solve_unchecked(self, sense=None)
Solve problem and return result. The user must manually check the status of the result to determine whether an optimal solution was found. A :class:`SolverError` may still be raised if the underlying solver raises an exception.
5.618875
5.589491
1.005257
self._check_valid() return self._problem._p.Status == gurobipy.GRB.OPTIMAL
def success(self)
Return boolean indicating whether a solution was found.
13.232251
8.065564
1.640586
self._check_valid() status = self._problem._p.Status if (status == gurobipy.GRB.INF_OR_UNBD and self._problem._p.params.DualReductions): # Disable dual reductions to obtain a definitve answer self._problem._p.params.DualReductions = 0 ...
def unbounded(self)
Whether solution is unbounded
3.746434
3.457201
1.083661
return self._problem._p.getVarByName(self._problem._variables[var]).x
def _get_value(self, var)
Return value of variable in solution.
18.058706
11.582295
1.559165
# Importing readline will in some cases print weird escape # characters to stdout. To avoid this we only import readline # and related packages at this point when we are certain # they are needed. from code import InteractiveConsole import readline impor...
def open_python(self, message, namespace)
Open interactive python console
5.033104
4.873885
1.032668
def compounds_sig(compounds): if stoichiometry: return tuple(sorted(compounds)) else: return tuple(sorted(compound for compound, _ in compounds)) left = compounds_sig(eq.left) right = compounds_sig(eq.right) if left < right: reaction_sig = left, rig...
def reaction_signature(eq, direction=False, stoichiometry=False)
Return unique signature object for :class:`Reaction`. Signature objects are hashable, and compare equal only if the reactions are considered the same according to the specified rules. Args: direction: Include reaction directionality when considering equality. stoichiometry: Include stoichi...
2.904545
2.982258
0.973942
# Create dictonary of signatures database_signatures = {} for entry in self._model.reactions: signature = reaction_signature( entry.equation, direction=self._args.compare_direction, stoichiometry=self._args.compare_stoichiometry) ...
def run(self)
Run check for duplicates
4.125792
3.793783
1.087514
charge_sum = 0.0 for compound, value in reaction.compounds: charge = compound_charge.get(compound.name, float('nan')) charge_sum += charge * float(value) return charge_sum
def reaction_charge(reaction, compound_charge)
Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values.
3.564966
3.722464
0.95769
compound_charge = {} for compound in model.compounds: if compound.charge is not None: compound_charge[compound.id] = compound.charge for reaction in model.reactions: charge = reaction_charge(reaction.equation, compound_charge) yield reaction, charge
def charge_balance(model)
Calculate the overall charge for all reactions in the model. Yield (reaction, charge) pairs. Args: model: :class:`psamm.datasource.native.NativeModel`.
3.558111
3.04239
1.169512
def multiply_formula(compound_list): for compound, count in compound_list: yield count * compound_formula[compound.name] for compound, _ in reaction.compounds: if compound.name not in compound_formula: return None else: left_form = reduce( o...
def reaction_formula(reaction, compound_formula)
Calculate formula compositions for both sides of the specified reaction. If the compounds in the reaction all have formula, then calculate and return the chemical compositions for both sides, otherwise return `None`. Args: reaction: :class:`psamm.reaction.Reaction`. compound_formula: a map...
4.177404
3.81408
1.095259
# Mapping from compound id to formula compound_formula = {} for compound in model.compounds: if compound.formula is not None: try: f = Formula.parse(compound.formula).flattened() compound_formula[compound.id] = f except ParseError as e: ...
def formula_balance(model)
Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`.
3.389448
3.319232
1.021154
# 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 al...
def run(self)
Run flux consistency check command
3.784203
3.723606
1.016274
# 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) c...
def run(self)
Run charge balance command
4.072176
3.806517
1.069791
if args: raise exc.PositionalArgumentsProhibited() extra_traits = set(kwargs.pop('traits', tuple())) safe_unless_ro = self.__safe_unless_ro__ or any( x in kwargs for x in ("required", "isa", "check") ) # detect initializer arguments only supported by a subclass and add # th...
def has(selfie, self, args, kwargs)
This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appropriate Property subclass. As such it i...
4.35029
4.339642
1.002454
wanted_traits = set(trait_set) stock_types = dict( (k, v) for k, v in PROPERTY_TYPES.items() if set(k).issubset(wanted_traits) ) traits_available = set() for key in stock_types.keys(): traits_available.update(key) missing_traits = wanted_traits - traits_available ...
def create_property_type_from_traits(trait_set)
Takes an iterable of trait names, and tries to compose a property type from that. Raises an exception if this is not possible. Extra traits not requested are not acceptable. If this automatic generation doesn't work for you for some reason, then compose your property types manually. The details ...
4.140645
4.159386
0.995494
if os.path.isdir(source): sources = glob.glob(os.path.join(source, '*.sbml')) if len(sources) == 0: raise ModelLoadError('No .sbml file found in source directory') elif len(sources) > 1: raise ModelLoadError( 'More ...
def _resolve_source(self, source)
Resolve source to filepath if it is a directory.
2.501136
2.175246
1.149817
source = self._resolve_source(source) self._context = FilePathContext(source) with self._context.open() as f: self._reader = self._open_reader(f) return self._reader.create_model()
def import_model(self, source)
Import and return model instance.
6.223585
5.646504
1.102201
model = super(StrictImporter, self).import_model(source) # Translate entries into dict-based entries. sbml.convert_model_entries( model, convert_id=lambda entry: entry.id, translate_compartment=self._translate_compartment, translate_compound=self._tr...
def import_model(self, source)
Import and return model instance.
5.755734
5.23653
1.099151
model = super(NonstrictImporter, self).import_model(source) sbml.convert_sbml_model(model) return model
def import_model(self, source)
Import and return model instance.
7.806392
6.897592
1.131756
forward, reverse = self.value return self.__class__((reverse, forward))
def flipped(self)
Return the flipped version of this direction.
18.138638
11.902932
1.52388
# 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) reaction = self._get_objective() if not self._mm.has_reaction(reaction): ...
def run(self)
Run flux variability command
4.436
4.403786
1.007315
typetuple = type_ if isinstance(type_, tuple) else (type_,) if any in typetuple: typetuple = any if typetuple not in EMPTY_VALS: EMPTY_VALS[typetuple] = EmptyVal(typetuple) return EMPTY_VALS[typetuple]
def placeholder(type_)
Returns the EmptyVal instance for the given type
4.868474
3.431779
1.418644
seen = set() for entry in iterable: if isinstance(entry, tuple): for type_ in entry: if type_ not in seen: seen.add(type_) yield type_ else: if entry not in seen: seen.add(entry) ...
def itertypes(iterable)
Iterates over an iterable containing either type objects or tuples of type objects and yields once for every type object found.
1.955209
1.84677
1.058718
which = sudo if use_sudo else run which(rm(path, recursive=True, force=force), warn_only=True)
def remove_ignore(path, use_sudo=False, force=False)
Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for temporary files that can be assumed to be cleaned up at a later point. :param path: Path to file or directory to remove. :type path: unicode :param use_sudo: Use the `sudo` command. :type use_sudo: ...
7.169835
11.62457
0.616783
result = single_line_stdout('if [[ -f {0} ]]; then echo 0; elif [[ -d {0} ]]; then echo 1; else echo -1; fi'.format(path), sudo=use_sudo, quiet=True) if result == '0': return False elif result == '1': return True else: return None
def is_directory(path, use_sudo=False)
Check if the remote path exists and is a directory. :param path: Remote path to check. :type path: unicode :param use_sudo: Use the `sudo` command. :type use_sudo: bool :return: `True` if the path exists and is a directory; `False` if it exists, but is a file; `None` if it does not exist. ...
2.864195
3.300566
0.867789
path = get_remote_temp() try: if apply_chmod: run(chmod(apply_chmod, path)) if apply_chown: if remove_using_sudo is None: remove_using_sudo = True sudo(chown(apply_chown, path)) yield path finally: remove_ignore(path, u...
def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False)
Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :...
2.992598
3.216167
0.930486
path = tempfile.mkdtemp() yield path shutil.rmtree(path, ignore_errors=True)
def local_temp_dir()
Creates a local temporary directory. The directory is removed when no longer needed. Failure to do so will be ignored. :return: Path to the temporary directory. :rtype: unicode
2.864713
4.344638
0.659367
with tarfile.open(filename, 'r', **kwargs) as tf: safe_members = [name for name in tf.getmembers() if _safe_name(name)] if safe_members: tf.extractall(dest_path, safe_members)
def extract_tar(filename, dest_path, **kwargs)
Extracts a TAR archive. All element names starting with ``/`` (indicating an absolute path) or that contain ``..`` as references to a parent directory are not extracted. :param filename: Path to the tar file. :type filename: unicode :param dest_path: Destination path to extract the contents to. :ty...
3.103113
3.833269
0.809521
body = dict( status=self.code, message=self.get_description(environ), ) errors = self.get_errors() if self.errors: body['errors'] = errors if self.code and (self.code >= 500) and hasattr(g, 'sentry_event_id'): body['error...
def get_body(self, environ=None)
Get the request body.
3.443249
3.402159
1.012077
response = super(SameContentException, self).get_response( environ=environ ) if self.etag is not None: response.set_etag(self.etag) if self.last_modified is not None: response.headers['Last-Modified'] = http_date(self.last_modified) re...
def get_response(self, environ=None)
Get a list of headers.
2.887446
2.911393
0.991775
if type_ is None or isinstance(type_, tuple): type_ = type(object_) key_vals = list() if hasattr(type_, "primary_key"): pk_cols = type_.primary_key elif object_.__hash__: return object_ else: raise exc.IdentityCrisis( val=object_, val_rep...
def record_id(object_, type_=None, selector=None, normalize_object_slot=None)
Implementation of id() which is overridable and knows about record's primary_key property. Returns if the two objects may be the "same"; returns None for other types, meaning all bets about identity are off. Curiously, this function resembles conversion between a "record" and a "tuple": stripping the ...
3.330174
3.314837
1.004627
lower, upper = coupling if lower is None and upper is None: return CouplingClass.Uncoupled elif lower is None or upper is None: return CouplingClass.DirectionalReverse elif lower == 0.0 and upper == 0.0: return CouplingClass.Inconsistent elif lower <= 0.0 and upper >= 0...
def classify_coupling(coupling)
Return a constant indicating the type of coupling. Depending on the type of coupling, one of the constants from :class:`.CouplingClass` is returned. Args: coupling: Tuple of minimum and maximum flux ratio
2.696521
2.762808
0.976007
# Update objective for reaction_1 self._prob.set_objective(self._vbow(reaction_1)) # Update constraint for reaction_2 if self._reaction_constr is not None: self._reaction_constr.delete() self._reaction_constr, = self._prob.add_linear_constraints( ...
def solve(self, reaction_1, reaction_2)
Return the flux coupling between two reactions The flux coupling is returned as a tuple indicating the minimum and maximum value of the v1/v2 reaction flux ratio. A value of None as either the minimum or maximum indicates that the interval is unbounded in that direction.
3.960181
3.956081
1.001036
cf = container_fabric() cf.call(action_name, container, **kwargs)
def perform(action_name, container, **kwargs)
Performs an action on the given container map and configuration. :param action_name: Name of the action (e.g. ``update``). :param container: Container configuration name. :param kwargs: Keyword arguments for the action implementation.
12.324904
16.749004
0.735859
full_script_path = os.path.abspath(script_path) prefix, name = os.path.split(full_script_path) with temp_dir() as remote_tmp: if upload_dir: prefix_path, prefix_name = os.path.split(prefix) remote_script = posixpath.join(remote_tmp, prefix_name, name) put(pre...
def script(container, script_path, fail_nonzero=False, upload_dir=False, **kwargs)
Runs a script inside a container, which is created with all its dependencies. The container is removed after it has been run, whereas the dependencies are not destroyed. The output is printed to the console. :param container: Container configuration name. :param script_path: Local path to the script file. ...
3.643176
3.465277
1.051337
with temp_dir() as remote_tmp: kwargs.setdefault('command_format', ['-c', command]) results = [output.result for output in container_fabric().run_script(container, script_path=remote_tmp, **kwargs) if o.action_type == ContainerUtilAction.SCRIPT] if ...
def single_cmd(container, command, fail_nonzero=False, download_result=None, **kwargs)
Runs a script inside a container, which is created with all its dependencies. The container is removed after it has been run, whereas the dependencies are not destroyed. The output is printed to the console. :param container: Container configuration name. :param command: Command line to run. :param fai...
6.700765
6.543928
1.023967
ci = kwargs.get('client_implementation') or env.get('docker_fabric_implementation') or CLIENT_API if ci == CLIENT_API: return docker_api(*args, **kwargs) elif ci == CLIENT_CLI: return docker_cli(*args, **kwargs) raise ValueError("Invalid client implementation.", ci)
def docker_fabric(*args, **kwargs)
:param args: Positional arguments to Docker client. :param kwargs: Keyword arguments to Docker client. :return: Docker client. :rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient
4.442412
4.388603
1.012261
ci = client_implementation or env.get('docker_fabric_implementation') or CLIENT_API if ci == CLIENT_API: return ContainerApiFabricClient(container_maps, docker_client, clients) elif ci == CLIENT_CLI: return ContainerCliFabricClient(container_maps, docker_client, clients) raise Value...
def container_fabric(container_maps=None, docker_client=None, clients=None, client_implementation=None)
:param container_maps: Container map or a tuple / list thereof. :type container_maps: list[dockermap.map.config.main.ContainerMap] | dockermap.map.config.main.ContainerMap :param docker_client: Default Docker client instance. :type docker_client: dockerfabric.base.FabricClientConfiguration or docker.docker....
4.353156
3.879296
1.122151
biomass_reactions = set() for reaction in model.reactions: # Extract limits if reaction.id not in model.limits: lower, upper = parse_flux_bounds(reaction) if lower is not None or upper is not None: model.limits[reaction.id] = reaction.id, lower, upper...
def convert_sbml_model(model)
Convert raw SBML model to extended model. Args: model: :class:`NativeModel` obtained from :class:`SBMLReader`.
3.070912
3.153559
0.973793
for escape, symbol in iteritems(_COBRA_DECODE_ESCAPES): cobra_id = cobra_id.replace(escape, symbol) return cobra_id
def entry_id_from_cobra_encoding(cobra_id)
Convert COBRA-encoded ID string to decoded ID string.
4.709534
3.881514
1.213324
def convert_sbml_id(entry): if isinstance(entry, BaseCompartmentEntry): prefix = compartment_prefix elif isinstance(entry, BaseReactionEntry): prefix = reaction_prefix elif isinstance(entry, BaseCompoundEntry): prefix = compound_prefix new_id...
def create_convert_sbml_id_function( compartment_prefix='C_', reaction_prefix='R_', compound_prefix='M_', decode_id=entry_id_from_cobra_encoding)
Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes are common on IDs in SBML models because the IDs live in a global namespace.
1.798853
1.980446
0.908307
new_entry = DictReactionEntry(entry, id=new_id) # Convert compound IDs in reaction equation if new_entry.equation is not None: compounds = [] for compound, value in new_entry.equation.compounds: # Translate compartment to new ID, if available. compartment = comp...
def translate_sbml_reaction(entry, new_id, compartment_map, compound_map)
Translate SBML reaction entry.
4.021797
3.981639
1.010086
new_entry = DictCompoundEntry(entry, id=new_id) if 'compartment' in new_entry.properties: old_compartment = new_entry.properties['compartment'] new_entry.properties['compartment'] = compartment_map.get( old_compartment, old_compartment) # Get XHTML notes properties for...
def translate_sbml_compound(entry, new_id, compartment_map)
Translate SBML compound entry.
3.224268
3.209832
1.004498
for note in entry.xml_notes.itertext(): m = re.match(r'^([^:]+):(.+)$', note) if m: key, value = m.groups() key = key.strip().lower().replace(' ', '_') value = value.strip() m = re.match(r'^"(.*)"$', value) if m: value ...
def parse_xhtml_notes(entry)
Yield key, value pairs parsed from the XHTML notes section. Each key, value pair must be defined in its own text block, e.g. ``<p>key: value</p><p>key2: value2</p>``. The key and value must be separated by a colon. Whitespace is stripped from both key and value, and quotes are removed from values if pr...
2.458568
2.259245
1.088225
properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) for key in ('pubchem_id', 'chebi_id'): if key in cobra_notes: properties[key] = cobra_notes[key] if 'formula' in cobra_notes: properties['formula'] ...
def parse_xhtml_species_notes(entry)
Return species properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``PUBCHEM ID``, ``CHEBI ID``, ``FORMULA``, ``...
2.496823
2.142299
1.165487
properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) if 'subsystem' in cobra_notes: properties['subsystem'] = cobra_notes['subsystem'] if 'gene_association' in cobra_notes: properties['genes'] = cobra_notes['gene_asso...
def parse_xhtml_reaction_notes(entry)
Return reaction properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``SUBSYSTEM``, ``GENE ASSOCIATION``, ``EC NU...
2.454951
2.045795
1.199998
for parameter in entry.kinetic_law_reaction_parameters: pid, name, value, units = parameter if (pid == 'OBJECTIVE_COEFFICIENT' or name == 'OBJECTIVE_COEFFICIENT'): return value return None
def parse_objective_coefficient(entry)
Return objective value for reaction entry. Detect objectives that are specified using the non-standardized kinetic law parameters which are used by many pre-FBC SBML models. The objective coefficient is returned for the given reaction, or None if undefined. Args: entry: :class:`SBMLReactio...
6.742041
5.077259
1.32789
lower_bound = None upper_bound = None for parameter in entry.kinetic_law_reaction_parameters: pid, name, value, units = parameter if pid == 'UPPER_BOUND' or name == 'UPPER_BOUND': upper_bound = value elif pid == 'LOWER_BOUND' or name == 'LOWER_BOUND': low...
def parse_flux_bounds(entry)
Return flux bounds for reaction entry. Detect flux bounds that are specified using the non-standardized kinetic law parameters which are used by many pre-FBC SBML models. The flux bounds are returned as a pair of lower, upper bounds. The returned bound is None if undefined. Args: entry: :c...
3.488537
3.351117
1.041007
extracellular_key = Counter() for reaction in model.reactions: equation = reaction.equation if equation is None: continue if len(equation.compounds) == 1: compound, _ = equation.compounds[0] compartment = compound.compartment extrace...
def detect_extracellular_compartment(model)
Detect the identifier for equations with extracellular compartments. Args: model: :class:`NativeModel`.
2.819544
3.075541
0.916763
# Build set of exchange reactions exchanges = set() for reaction in model.reactions: equation = reaction.properties.get('equation') if equation is None: continue if len(equation.compounds) != 1: # Provide warning for exchange reactions with more than ...
def convert_exchange_to_compounds(model)
Convert exchange reactions in model to exchange compounds. Only exchange reactions in the extracellular compartment are converted. The extracelluar compartment must be defined for the model. Args: model: :class:`NativeModel`.
3.266332
3.11742
1.047767
if self._reader._level > 1: entry_id = element.get('id') else: entry_id = element.get('name') return entry_id
def _element_get_id(self, element)
Get id of reaction or species element. In old levels the name is used as the id. This method returns the correct attribute depending on the level.
5.094223
4.139241
1.230714
if self._reader._level == 3: # Look for FBC charge for ns in (FBC_V2, FBC_V1): charge = self._root.get(_tag('charge', ns)) if charge is not None: return self._parse_charge_string(charge) else: charge = self....
def charge(self)
Species charge
5.159027
4.896255
1.053668
if self._reader._level == 3: for ns in (FBC_V2, FBC_V1): formula = self._root.get(_tag('chemicalFormula', ns)) if formula is not None: return formula return None
def formula(self)
Species formula
10.890827
8.961143
1.215339
properties = {'id': self._id, 'boundary': self._boundary} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if 'compartment' in self._root.attrib: properties['compartment'] = self._root.get('compartment') c...
def properties(self)
All species properties as a dict
2.632224
2.487505
1.058179
for species in self._root.iterfind('./{}/{}'.format( self._reader._sbml_tag(name), self._reader._sbml_tag('speciesReference'))): species_id = species.get('species') if self._reader._level == 1: # In SBML level 1 only positive int...
def _parse_species_references(self, name)
Yield species id and parsed value for a speciesReference list
2.849916
2.7441
1.038561
for parameter in self._root.iterfind( './{}/{}/{}'.format(self._reader._sbml_tag('kineticLaw'), self._reader._sbml_tag('listOfParameters'), self._reader._sbml_tag('parameter'))): param_id = parameter.ge...
def kinetic_law_reaction_parameters(self)
Iterator over the values of kinetic law reaction parameters
3.174717
2.970122
1.068884
properties = {'id': self._id, 'reversible': self._rev, 'equation': self._equation} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if self._lower_flux is not None: properties['lower_flux'] = ...
def properties(self)
All reaction properties as a dict
3.056179
2.544665
1.201014
properties = {'id': self._id} if self._name is not None: properties['name'] = self._name return properties
def properties(self)
All compartment properties as a dict.
4.264898
3.560163
1.19795
return (c for c in itervalues(self._model_species) if not self._ignore_boundary or not c.boundary)
def species(self)
Iterator over :class:`SpeciesEntries <.SpeciesEntry>` This will not yield boundary condition species if those are ignored.
13.112116
9.238012
1.419365
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) ...
def create_model(self)
Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`.
2.648002
2.652619
0.99826
substitutions = { '-': '_DASH_', '/': '_FSLASH_', '\\': '_BSLASH_', '(': '_LPAREN_', ')': '_RPAREN_', '[': '_LSQBKT_', ']': '_RSQBKT_', ',': '_COMMA_', '.': '_PERIOD_', "'": '_APOS_'...
def _make_safe_id(self, id)
Returns a modified id that has been made safe for SBML. Replaces or deletes the ones that aren't allowed.
2.898672
2.747259
1.055114
if r_id not in flux_limits or flux_limits[r_id][0] is None: if equation.direction == Direction.Forward: lower = 0 else: lower = -model.default_flux_limit else: lower = flux_limits[r_id][0] if r_id not in flux_limits or...
def _get_flux_bounds(self, r_id, model, flux_limits, equation)
Read reaction's limits to set up strings for limits in the output file.
1.917569
1.904972
1.006612
genes = ET.SubElement( r_tag, _tag('geneProductAssociation', FBC_V2)) if isinstance(r_genes, list): e = Expression(And(*(Variable(i) for i in r_genes))) else: e = Expression(r_genes) gene_stack = [(e.root, genes)] while len(gene_stack)...
def _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag)
Adds all the different kinds of genes into a list.
2.881791
2.854375
1.009605
objective_list = ET.SubElement(model_tag, _tag( 'listOfObjectives', FBC_V2)) objective_list.set(_tag('activeObjective', FBC_V2), 'O_1') objective_tag = ET.SubElement( objective_list, _tag('objective', FBC_V2)) objective_tag.set(_tag('id', FBC_V2), 'O_1') ...
def _add_fbc_objective(self, model_tag, obj_id)
Adds the objective(s) to the sbml document.
2.140743
2.064385
1.036988
list_all_genes = ET.SubElement(parent_tag, _tag( 'listOfGeneProducts', FBC_V2)) for id, label in sorted(iteritems(gene_id_dict)): gene_tag = ET.SubElement( list_all_genes, _tag('geneProduct', FBC_V2)) gene_tag.set(_tag('id', FBC_V2), id) ...
def _add_gene_list(self, parent_tag, gene_id_dict)
Create list of all gene products as sbml readable elements.
3.034277
2.614492
1.160561
if kwargs is None: kwargs = {} if json_struct is None: json_struct = {} if not isinstance(json_struct, dict): raise exc.JsonRecordCoerceError( passed=json_struct, recordtype=record_type, ) unknown_keys = set(json_struct.keys()) for propnam...
def json_to_initkwargs(record_type, json_struct, kwargs=None)
This function converts a JSON dict (json_struct) to a set of init keyword arguments for the passed Record (or JsonRecord). It is called by the JsonRecord constructor. This function takes a JSON data structure and returns a keyword argument list to be passed to the class constructor. Any keys in the i...
3.105104
3.008609
1.032073
if issubclass(record_type, JsonRecord): return record_type(json_struct) elif issubclass(record_type, Record): # do what the default JsonRecord __init__ does init_kwargs = json_to_initkwargs(record_type, json_struct) instance = record_type(**init_kwargs) return insta...
def from_json(record_type, json_struct)
JSON marshall in function: a 'visitor' function which looks for JSON types/hints on types being converted to, but does not require them. Args: ``record_type=``\ *TYPE* Record type to convert data to ``json_struct=``\ *DICT|LIST* a loaded (via ``json.loads``) data struct...
4.434423
5.147873
0.861409
if type(x) in has_json_data and has_json_data[type(x)]: if json_data_takes_extraneous[type(x)]: return x.json_data(extraneous=extraneous) else: return x.json_data() else: htj = hasattr(x, "json_data") and callable(x.json_data) has_json_data[type(x)] ...
def _json_data(x, extraneous)
This function calls a json_json method, if the type has one, otherwise calls back into to_json(). It also check whether the method takes an 'extraneous' argument and passes that through if possible.
2.728553
2.413592
1.130495
if prop: if isinstance(prop, basestring): prop = type(record).properties[prop] val = prop.__get__(record) if hasattr(prop, "to_json"): return prop.to_json(val, extraneous, _json_data) else: return _json_data(val, extraneous) elif isinstan...
def to_json(record, extraneous=True, prop=None)
JSON conversion function: a 'visitor' function which implements marshall out (to JSON data form), honoring JSON property types/hints but does not require them. To convert to an actual JSON document, pass the return value to ``json.dumps`` or a similar function. args: ``record=``\ *anything* ...
2.290264
2.280199
1.004414
if isinstance(json_data, basestring): json_data = json.loads(json_data) return json_to_initkwargs(self, json_data, kwargs)
def json_to_initkwargs(self, json_data, kwargs)
Subclassing hook to specialize how JSON data is converted to keyword arguments
2.254504
2.381665
0.946608
jd = to_json(self, extraneous) if hasattr(self, "unknown_json_keys"): prop = type(self).properties['unknown_json_keys'] if extraneous or not prop.extraneous: for k, v in self.unknown_json_keys.iteritems(): if k not in jd: ...
def json_data(self, extraneous=False)
Returns the JSON data form of this ``JsonRecord``. The 'unknown' JSON keys will be merged back in, if: 1. the ``extraneous=True`` argument is passed. 2. the ``unknown_json_keys`` property on this class is replaced by one not marked as ``extraneous``
3.805476
3.437106
1.107174
for diff in super(JsonRecord, self).diff_iter(other, **kwargs): # TODO: object copy/upgrade constructor newargs = diff.__getstate__() yield JsonDiffInfo(**(newargs))
def diff_iter(self, other, **kwargs)
Generator method which returns the differences from the invocant to the argument. This specializes :py:meth:`Record.diff_iter` by returning :py:class:`JsonDiffInfo` objects.
16.073656
10.269512
1.565182
return JsonDiff( base_type_name=type(self).__name__, other_type_name=type(other).__name__, values=self.diff_iter(other, **kwargs), )
def diff(self, other, **kwargs)
Compare an object with another. This specializes :py:meth:`Record.diff` by returning a :py:class:`JsonDiff` object.
5.189363
3.879935
1.337487
gid = single_line_stdout('id -g {0}'.format(groupname), expected_errors=(1,), shell=False) return check_int(gid)
def get_group_id(groupname)
Returns the group id to a given group name. Returns ``None`` if the group does not exist. :param groupname: Group name. :type groupname: unicode :return: Group id. :rtype: int
11.514682
15.762361
0.730518
uid = single_line_stdout('id -u {0}'.format(username), expected_errors=(1,), shell=False) return check_int(uid)
def get_user_id(username)
Returns the user id to a given user name. Returns ``None`` if the user does not exist. :param username: User name. :type username: unicode :return: User id. :rtype: int
12.308228
15.496895
0.794238
sudo(addgroup(groupname, gid, system))
def create_group(groupname, gid, system=True)
Creates a new user group with a specific id. :param groupname: Group name. :type groupname: unicode :param gid: Group id. :type gid: int or unicode :param system: Creates a system group.
12.207417
34.863567
0.350148
sudo(adduser(username, uid, system, no_login, no_password, group, gecos))
def create_user(username, uid, system=False, no_login=True, no_password=False, group=False, gecos=None)
Creates a new user with a specific id. :param username: User name. :type username: unicode :param uid: User id. :type uid: int or unicode :param system: Creates a system user. :type system: bool :param no_login: Disallow login of this user and group, and skip creating the home directory. De...
3.67687
5.557125
0.66165
gid = get_group_id(groupname) if gid is None: create_group(groupname, gid_preset, system) return gid_preset elif id_dependent and gid != gid_preset: error("Present group id '{0}' does not match the required id of the environment '{1}'.".format(gid, gid_preset)) return gid
def get_or_create_group(groupname, gid_preset, system=False, id_dependent=True)
Returns the id for the given group, and creates it first in case it does not exist. :param groupname: Group name. :type groupname: unicode :param gid_preset: Group id to set if a new group is created. :type gid_preset: int or unicode :param system: Create a system group. :type system: bool ...
3.902864
4.628338
0.843254
uid = get_user_id(username) gid = get_group_id(username) if id_dependent and gid is not None and gid != uid_preset: error("Present group id '{0}' does not match the required id of the environment '{1}'.".format(gid, uid_preset)) if gid is None: create_group(username, uid_preset, sys...
def get_or_create_user(username, uid_preset, groupnames=[], system=False, no_password=False, no_login=True, gecos=None, id_dependent=True)
Returns the id of the given user name, and creates it first in case it does not exist. A default group is created as well. :param username: User name. :type username: unicode :param uid_preset: User id to set in case a new user is created. :type uid_preset: int or unicode :param groupnames: Add...
2.5971
2.647211
0.98107
section_id = None entry_line = None properties = {} for lineno, line in enumerate(f): if line.strip() == '///': # End of entry mark = FileMark(context, entry_line, 0) yield KEGGEntry(properties, filemark=mark) properties = {} sect...
def parse_kegg_entries(f, context=None)
Iterate over entries in KEGG file.
3.093983
2.991611
1.03422
def parse_count(s): m = re.match(r'^\((.+)\)$', s) if m is not None: s = m.group(1) m = re.match(r'^\d+$', s) if m is not None: return int(m.group(0)) return Expression(s) def parse_compound(s): m = re.match(r'(.+)\((.+)\)', s) ...
def parse_reaction(s)
Parse a KEGG reaction string
2.321968
2.305753
1.007032
which = operations.sudo if sudo else operations.run with hide('warnings'): result = which(cmd, shell=shell, quiet=quiet, warn_only=True) if result.return_code == 0: return result if result.return_code not in expected_errors: error("Received unexpected error code {0} while e...
def stdout_result(cmd, expected_errors=(), shell=True, sudo=False, quiet=False)
Runs a command and returns the result, that would be written to `stdout`, as a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is returned in t...
4.628139
5.314865
0.870792
return single_line(stdout_result(cmd, expected_errors, shell, sudo, quiet))
def single_line_stdout(cmd, expected_errors=(), shell=True, sudo=False, quiet=False)
Runs a command and returns the first line of the result, that would be written to `stdout`, as a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is ...
5.664054
9.252439
0.612169
if not hasattr(source, 'read'): # Not a File-like object with open(self._resolve_source(source), 'r') as f: return self._import(f) else: return self._import(source)
def import_model(self, source)
Import and return model instance.
3.604677
3.441689
1.047357
# Create solver solver = self._get_solver() # 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) # TODO: The exchange and tr...
def run(self)
Run FastGapFill command
3.725661
3.540486
1.052302
self._constrs.extend(self._moma._prob.add_linear_constraints(*args))
def add(self, *args)
Add constraints to the model.
26.710642
15.985576
1.670921
for reaction_id in self._model.reactions: if not self._model.is_exchange(reaction_id): yield reaction_id
def _adjustment_reactions(self)
Yield all the non exchange reactions in the model.
5.272375
2.904414
1.815297
# Remove the constraints from the last run while len(self._remove_constr) > 0: self._remove_constr.pop().delete() try: return self._prob.solve(sense=sense) except lp.SolverError as e: raise_from(MOMAError(text_type(e)), e) finally: ...
def _solve(self, sense=None)
Remove old constraints and then solve the current problem. Args: sense: Minimize or maximize the objective. (:class:`.lp.ObjectiveSense) Returns: The Result object for the solved LP problem
5.847845
5.486959
1.065772
self._prob.set_objective(self._v_wt[objective]) return self._solve(lp.ObjectiveSense.Maximize)
def solve_fba(self, objective)
Solve the wild type problem using FBA. Args: objective: The objective reaction to be maximized. Returns: The LP Result object for the solved FBA problem.
18.116535
16.783968
1.079395
flux_result = self.solve_fba(objective) fba_fluxes = {} # Place all the flux values in a dictionary for key in self._model.reactions: fba_fluxes[key] = flux_result.get_value(self._v_wt[key]) return fba_fluxes
def get_fba_flux(self, objective)
Return a dictionary of all the fluxes solved by FBA. Dictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma` to minimize changes in the flux distributions following model perturbation. Args: objective: The objective reaction that is maximized. Returns: ...
4.991878
6.039925
0.82648
# Define constraints vs_wt = self._v_wt.set(self._model.reactions) zs = self._z.set(self._model.reactions) wt_obj_flux = self.get_fba_obj_flux(objective) with self.constraints() as constr: constr.add( zs >= vs_wt, vs_wt >= -zs, ...
def get_minimal_fba_flux(self, objective)
Find the FBA solution that minimizes all the flux values. Maximize the objective flux then minimize all other fluxes while keeping the objective flux at the maximum. Args: objective: The objective reaction that is maximized. Returns: A dictionary of all the rea...
5.84957
5.697316
1.026724