code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def cli(ctx, feature_id, start, organism="", sequence=""): return ctx.gi.annotations.set_translation_start(feature_id, start, organism=organism, sequence=sequence)
Set the translation start of a feature Output: A standard apollo feature dictionary ({"features": [{...}]})
def cli(ctx, feature_id, old_db, old_accession, new_db, new_accession, organism="", sequence=""): return ctx.gi.annotations.update_dbxref(feature_id, old_db, old_accession, new_db, new_accession, organism=organism, sequence=sequence)
Delete a dbxref from a feature Output: A standard apollo feature dictionary ({"features": [{...}]})
def cli(ctx, organism, sequence): return ctx.gi.annotations.set_sequence(organism, sequence)
Set the sequence for subsequent requests. Mostly used in client scripts to avoid passing the sequence and organism on every function call. Output: None
def cli(ctx, organism="", sequence=""): return ctx.gi.annotations.get_features(organism=organism, sequence=sequence)
Get the features for an organism / sequence Output: A standard apollo feature dictionary ({"features": [{...}]})
def cli(ctx, comment, metadata=""): return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata)
Add a canned comment Output: A dictionnary containing canned comment description
def cli(ctx, user, organism, administrate=False, write=False, export=False, read=False): return ctx.gi.users.update_organism_permissions(user, organism, administrate=administrate, write=write, export=export, read=read)
Update the permissions of a user on a specified organism Output: a dictionary containing user's organism permissions
def path(self): if len(self.heads) == 1: return _fmt_mfs_path(self.heads.keys()[0], self.heads.values()[0]) else: return "(" + "|".join( _fmt_mfs_path(k, v) for (k, v) in self.heads.items() ) + ")"
The path attribute returns a stringified, concise representation of the MultiFieldSelector. It can be reversed by the ``from_path`` constructor.
def get(self, obj): ctor = type(obj) if isinstance(obj, (list, ListCollection)): if self.has_string: raise TypeError( "MultiFieldSelector has string in list collection context" ) if self.has_none: tail =...
Creates a copy of the passed object which only contains the parts which are pointed to by one of the FieldSelectors that were used to construct the MultiFieldSelector. Can be used to produce 'filtered' versions of objects.
def delete(self, obj, force=False): # TODO: this could be a whole lot more efficient! if not force: for fs in self: try: fs.get(obj) except FieldSelectorException: raise for fs in self: try:...
Deletes all of the fields at the specified locations. args: ``obj=``\ *OBJECT* the object to remove the fields from ``force=``\ *BOOL* if True, missing attributes do not raise errors. Otherwise, the first failure raises an exception wit...
def patch(self, target, source, copy=False): # TODO: this could also be a whole lot more efficient! fs_val = [] for fs in self: try: fs_val.append((fs, fs.get(source))) except AttributeError: fs_val.append((fs, _None)) ...
Copies fields from ``obj`` to ``target``. If a matched field does not exist in ``obj``, it will be deleted from ``target``, otherwise it will be assigned (or copied). args: ``target=``\ *OBJECT* the object to set the fields in ``source=``\ *OBJECT* ...
def reset_socat(use_sudo=False): output = stdout_result('ps -o pid -C socat', quiet=True) pids = output.split('\n')[1:] puts("Removing process(es) with id(s) {0}.".format(', '.join(pids))) which = sudo if use_sudo else run which('kill {0}'.format(' '.join(pids)), quiet=True)
Finds and closes all processes of `socat`. :param use_sudo: Use `sudo` command. As Docker-Fabric does not run `socat` with `sudo`, this is by default set to ``False``. Setting it to ``True`` could unintentionally remove instances from other users. :type use_sudo: bool
def version(): output = docker_fabric().version() col_len = max(map(len, output.keys())) + 1 puts('') for k, v in six.iteritems(output): fastprint('{0:{1}} {2}'.format(''.join((k, ':')), col_len, v), end='\n', flush=False) fastprint('', flush=True)
Shows version information of the remote Docker service, similar to ``docker version``.
def list_images(list_all=False, full_ids=False): images = docker_fabric().images(all=list_all) _format_output_table(images, IMAGE_COLUMNS, full_ids)
Lists images on the Docker remote host, similar to ``docker images``. :param list_all: Lists all images (e.g. dependencies). Default is ``False``, only shows named images. :type list_all: bool :param full_ids: Shows the full ids. When ``False`` (default) only shows the first 12 characters. :type full_i...
def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False): containers = docker_fabric().containers(all=list_all) _format_output_table(containers, CONTAINER_COLUMNS, full_ids, full_cmd, short_image)
Lists containers on the Docker remote host, similar to ``docker ps``. :param list_all: Shows all containers. Default is ``False``, which omits exited containers. :type list_all: bool :param short_image: Hides the repository prefix for preserving space. Default is ``True``. :type short_image: bool :...
def list_networks(full_ids=False): networks = docker_fabric().networks() _format_output_table(networks, NETWORK_COLUMNS, full_ids)
Lists networks on the Docker remote host, similar to ``docker network ls``. :param full_ids: Shows the full network ids. When ``False`` (default) only shows the first 12 characters. :type full_ids: bool
def cleanup_containers(**kwargs): containers = docker_fabric().cleanup_containers(**kwargs) if kwargs.get('list_only'): puts('Existing containers:') for c_id, c_name in containers: fastprint('{0} {1}'.format(c_id, c_name), end='\n')
Removes all containers that have finished running. Similar to the ``prune`` functionality in newer Docker versions.
def cleanup_images(remove_old=False, **kwargs): keep_tags = env.get('docker_keep_tags') if keep_tags is not None: kwargs.setdefault('keep_tags', keep_tags) removed_images = docker_fabric().cleanup_images(remove_old=remove_old, **kwargs) if kwargs.get('list_only'): puts('Unused image...
Removes all images that have no name, and that are not references as dependency by any other named image. Similar to the ``prune`` functionality in newer Docker versions, but supports more filters. :param remove_old: Also remove images that do have a name, but no `latest` tag. :type remove_old: bool
def remove_all_containers(**kwargs): containers = docker_fabric().remove_all_containers(**kwargs) if kwargs.get('list_only'): puts('Existing containers:') for c_id in containers[1]: fastprint(c_id, end='\n')
Stops and removes all containers from the remote. Use with caution outside of a development environment! :return:
def save_image(image, filename=None): local_name = filename or '{0}.tar.gz'.format(image) cli.save_image(image, local_name)
Saves a Docker image from the remote to a local files. For performance reasons, uses the Docker command line client on the host, generates a gzip-tarball and downloads that. :param image: Image name or id. :type image: unicode :param filename: File name to store the local file. If not provided, will us...
def load_image(filename, timeout=120): c = docker_fabric() with open(expand_path(filename), 'r') as f: _timeout = c._timeout c._timeout = timeout try: c.load_image(f) finally: c._timeout = _timeout
Uploads an image from a local file to a Docker remote. Note that this temporarily has to extend the service timeout period. :param filename: Local file name. :type filename: unicode :param timeout: Timeout in seconds to set temporarily for the upload. :type timeout: int
def execute(self, raise_on_error=True): "Execute all the commands in the current pipeline" stack = self.command_stack if not stack: return [] execute = self._execute_pipeline conn = self.connection if not conn: conn = self.connection_pool.get_conn...
Execute all the commands in the current pipeline
def diff_iter(self, other, **kwargs): from normalize.diff import diff_iter return diff_iter(self, other, **kwargs)
Generator method which returns the differences from the invocant to the argument. args: ``other=``\ *Record*\ \|\ *Anything* The thing to compare against; the types must match, unless ``duck_type=True`` is passed. *diff_option*\ =\ *value* ...
def diff(self, other, **kwargs): from normalize.diff import diff return diff(self, other, **kwargs)
Compare an object with another and return a :py:class:`DiffInfo` object. Accepts the same arguments as :py:meth:`normalize.record.Record.diff_iter`
def _parse_weights(weight_args, default_weight=0.6): weights_dict = {} r_group_weight = default_weight for weight_arg in weight_args: for weight_assignment in weight_arg.split(','): if '=' not in weight_assignment: raise ValueError( 'Invalid weigh...
Parse list of weight assignments.
def _combine_transfers(self, result): transfers = {} for reaction_id, c1, c2, form in result: key = reaction_id, c1, c2 combined_form = transfers.setdefault(key, Formula()) transfers[key] = combined_form | form for (reaction_id, c1, c2), form in iter...
Combine multiple pair transfers into one.
def copy_resource(container, resource, local_filename, contents_only=True): with temp_dir() as remote_tmp: base_name = os.path.basename(resource) copy_path = posixpath.join(remote_tmp, 'copy_tmp') run(mkdir(copy_path, check_if_exists=True)) remote_name = posixpath.join(copy_path...
Copies a resource from a container to a compressed tarball and downloads it. :param container: Container name or id. :type container: unicode :param resource: Name of resource to copy. :type resource: unicode :param local_filename: Path to store the tarball locally. :type local_filename: unicod...
def isolate_and_get(src_container, src_resources, local_dst_dir, **kwargs): with temp_dir() as remote_tmp: copy_path = posixpath.join(remote_tmp, 'copy_tmp') archive_path = posixpath.join(remote_tmp, 'container_{0}.tar.gz'.format(src_container)) copy_resources(src_container, src_resourc...
Uses :func:`copy_resources` to copy resources from a container, but afterwards generates a compressed tarball and downloads it. :param src_container: Container name or id. :type src_container: unicode :param src_resources: Resources, as (file or directory) names to copy. :type src_resources: iterab...
def isolate_to_image(src_container, src_resources, dst_image, **kwargs): with temp_dir() as remote_tmp: copy_resources(src_container, src_resources, remote_tmp, **kwargs) with cd(remote_tmp): sudo('tar -cz * | docker import - {0}'.format(dst_image))
Uses :func:`copy_resources` to copy resources from a container, but afterwards imports the contents into a new (otherwise empty) Docker image. :param src_container: Container name or id. :type src_container: unicode :param src_resources: Resources, as (file or directory) names to copy. :type src_re...
def save_image(image, local_filename): r_name, __, i_name = image.rpartition('/') i_name, __, __ = i_name.partition(':') with temp_dir() as remote_tmp: archive = posixpath.join(remote_tmp, 'image_{0}.tar.gz'.format(i_name)) run('docker save {0} | gzip --stdout > {1}'.format(image, archi...
Saves a Docker image as a compressed tarball. This command line client method is a suitable alternative, if the Remove API method is too slow. :param image: Image id or tag. :type image: unicode :param local_filename: Local file name to store the image into. If this is a directory, the image will be st...
def flatten_image(image, dest_image=None, no_op_cmd='/bin/true', create_kwargs={}, start_kwargs={}): dest_image = dest_image or image with temp_container(image, no_op_cmd=no_op_cmd, create_kwargs=create_kwargs, start_kwargs=start_kwargs) as c: run('docker export {0} | docker import - {1}'.format(c,...
Exports a Docker image's file system and re-imports it into a new (otherwise new) image. Note that this does not transfer the image configuration. In order to gain access to the container contents, the image is started with a non-operational command, such as ``/bin/true``. The container is removed once the new ...
def decode_name(s): # Some names contain XML-like entity codes return re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), s)
Decode names in ModelSEED files
def parse_compound_file(f, context=None): f.readline() # Skip header for lineno, row in enumerate(csv.reader(f, delimiter='\t')): compound_id, names, formula = row[:3] names = (decode_name(name) for name in names.split(',<br>')) # ModelSEED sometimes uses an asterisk and number a...
Iterate over the compound entries in the given file
def init_parser(cls, parser): subparsers = parser.add_subparsers(title='Search domain') # Compound subcommand parser_compound = subparsers.add_parser( 'compound', help='Search in compounds') parser_compound.set_defaults(which='compound') parser_compound.add_...
Initialize argument parser
def run(self): which_command = self._args.which if which_command == 'compound': self._search_compound() elif which_command == 'reaction': self._search_reaction()
Run search command.
def to_json(self, propval, extraneous=False, to_json_func=None): if self.json_out: return self.json_out(propval) else: if not to_json_func: from normalize.record.json import to_json to_json_func = to_json return to_json_func(pr...
This function calls the ``json_out`` function, if it was specified, otherwise continues with JSON conversion of the value in the slot by calling ``to_json_func`` on it.
def init_config(self, app): config_apps = ['REST_', 'CORS_', ] for k in dir(config): if any([k.startswith(prefix) for prefix in config_apps]): app.config.setdefault(k, getattr(config, k))
Initialize configuration. .. note:: Change Flask-CORS and Flask-Limiter defaults. :param app: An instance of :class:`flask.Flask`.
def parse_compound(s, global_compartment=None): m = re.match(r'^\|(.*)\|$', s) if m: s = m.group(1) m = re.match(r'^(.+)\[(\S+)\]$', s) if m: compound_id = m.group(1) compartment = m.group(2) else: compound_id = s compartment = global_compartment re...
Parse a compound specification. If no compartment is specified in the string, the global compartment will be used.
def parse_compound_count(s): m = re.match(r'^\((.*)\)$', s) if m: s = m.group(1) for count_type in (int, Decimal, affine.Expression): try: return count_type(s) except: pass raise ValueError('Unable to parse compound count: {}'.format(s))
Parse a compound count (number of compounds).
def get_gene_associations(model): for reaction in model.reactions: assoc = None if reaction.genes is None: continue elif isinstance(reaction.genes, string_types): assoc = boolean.Expression(reaction.genes) else: variables = [boolean.Variable(...
Create gene association for class :class:`.GeneDeletionStrategy`. Return a dict mapping reaction IDs to :class:`psamm.expression.boolean.Expression` objects, representing relationships between reactions and related genes. This helper function should be called when creating :class:`.GeneDeletionStrategy...
def run_sink_check(self, model, solver, threshold, implicit_sinks=True): prob = solver.create_problem() # Create flux variables v = prob.namespace() for reaction_id in model.reactions: lower, upper = model.limits[reaction_id] v.define([reaction_id], lowe...
Run sink production check method.
def run_reaction_production_check(self, model, solver, threshold, implicit_sinks=True): prob = solver.create_problem() # Create flux variables v = prob.namespace() for reaction_id in model.reactions: lower, upper = model.limits[...
Run reaction production check method.
def define(self, *names, **kwargs): 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) vartyp...
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 ...
def _add_constraints(self, relation): expression = relation.expression pairs = [] for value_set in expression.value_sets(): ind, val = zip(*((self._variables[variable], float(value)) for variable, value in value_set)) pairs.append(cp....
Add the given relation as one or more constraints Return a list of the names of the constraints added.
def add_linear_constraints(self, *relations): constraints = [] for relation in relations: if self._check_relation(relation): constraints.append(Constraint(self, None)) else: for name in self._add_constraints(relation): ...
Add constraints to the problem Each constraint is represented by a Relation, and the expression in that relation can be a set expression.
def set_objective(self, expression): if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression(offset=expression) linear = [] quad = [] # Reset previous ...
Set objective expression of the problem.
def set_objective_sense(self, sense): if sense == ObjectiveSense.Minimize: self._cp.objective.set_sense(self._cp.objective.sense.minimize) elif sense == ObjectiveSense.Maximize: self._cp.objective.set_sense(self._cp.objective.sense.maximize) else: rai...
Set type of problem (maximize or minimize)
def solve_unchecked(self, sense=None): if sense is not None: self.set_objective_sense(sense) self._solve() self._result = Result(self) return self._result
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.
def success(self): self._check_valid() return self._problem._cp.solution.get_status() in ( self._problem._cp.solution.status.optimal, self._problem._cp.solution.status.optimal_tolerance, self._problem._cp.solution.status.MIP_optimal)
Return boolean indicating whether a solution was found
def unbounded(self): self._check_valid() cp = self._problem._cp status = cp.solution.get_status() presolve = cp.parameters.preprocessing.presolve.get() if (status == cp.solution.status.infeasible_or_unbounded and presolve): # Disable presolve...
Whether solution is unbounded
def _get_value(self, var): return self._problem._cp.solution.get_values( self._problem._variables[var])
Return value of variable in solution.
def get_value(self, expression): self._check_valid() return super(Result, self).get_value(expression)
Return value of expression.
def copy(self): doppel = type(self)( self.unpack, self.apply, self.collect, self.reduce, apply_empty_slots=self.apply_empty_slots, extraneous=self.extraneous, ignore_empty_string=self.ignore_empty_string, ignore_none=self.ignore_none, ...
Be sure to implement this method when sub-classing, otherwise you will lose any specialization context.
def visit(cls, value, value_type=None, **kwargs): visitor = cls.Visitor( cls.unpack, cls.apply, cls.aggregate, cls.reduce, **kwargs) if not value_type: value_type = type(value) if not issubclass(value_type, Record): raise TypeErro...
A value visitor, which visits instances (typically), applies :py:meth:`normalize.visitor.VisitorPattern.apply` to every attribute slot, and returns the reduced result. Like :py:func:`normalize.diff.diff`, this function accepts a series of keyword arguments, which are passed through to ...
def unpack(cls, value, value_type, visitor): if issubclass(value_type, Collection): try: generator = value.itertuples() except AttributeError: if isinstance(value, value_type.colltype): generator = value_type.coll_to_tuples(val...
Unpack a value during a 'visit' args: ``value=``\ *object* The instance being visited ``value_type=``\ *RecordType* The expected type of the instance ``visitor=``\ *Visitor* The context/options returns a tuple with ...
def apply(cls, value, prop, visitor): return ( None if isinstance(value, (AttributeError, KeyError)) else value )
apply' is a general place to put a function which is called on every extant record slot. This is usually the most important function to implement when sub-classing. The default implementation passes through the slot value as-is, but expected exceptions are converted to ``None``. ...
def aggregate(self, mapped_coll_generator, coll_type, visitor): return coll_type.tuples_to_coll(mapped_coll_generator, coerce=False)
Hook called for each normalize.coll.Collection, after mapping over each of the items in the collection. The default implementation calls :py:meth:`normalize.coll.Collection.tuples_to_coll` with ``coerce=False``, which just re-assembles the collection into a native python collect...
def reduce(self, mapped_props, aggregated, value_type, visitor): reduced = None if mapped_props: reduced = dict((k.name, v) for k, v in mapped_props) if issubclass(value_type, Collection) and aggregated is not None: if all(visitor.is_filtered(prop) for prop in ...
This reduction is called to combine the mapped slot and collection item values into a single value for return. The default implementation tries to behave naturally; you'll almost always get a dict back when mapping over a record, and list or some other collection when mapping over colle...
def cast(cls, value_type, value, visitor=None, **kwargs): if visitor is None: visitor = cls.Visitor( cls.grok, cls.reverse, cls.collect, cls.produce, **kwargs) return cls.map(visitor, value, value_type)
Cast is for visitors where you are visiting some random data structure (perhaps returned by a previous ``VisitorPattern.visit()`` operation), and you want to convert back to the value type. This function also takes positional arguments: ``value_type=``\ *RecordType* ...
def grok(cls, value, value_type, visitor): is_coll = issubclass(value_type, Collection) is_record = issubclass(value_type, Record) and any( not visitor.is_filtered(prop) for prop in value_type.properties.values() ) if is_record and not isinstance(value, ...
Like :py:meth:`normalize.visitor.VisitorPattern.unpack` but called for ``cast`` operations. Expects to work with dictionaries and lists instead of Record objects. Reverses the transform performed in :py:meth:`normalize.visitor.VisitorPattern.reduce` for collections with propert...
def reverse(cls, value, prop, visitor): return ( None if isinstance(value, (AttributeError, KeyError)) else value )
Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply.
def produce(cls, mapped_props, aggregated, value_type, visitor): kwargs = {} if not mapped_props else dict( (k.name, v) for k, v in mapped_props ) if issubclass(value_type, Collection): kwargs['values'] = aggregated return value_type(**kwargs)
Like :py:meth:`normalize.visitor.VisitorPattern.reduce`, but constructs instances rather than returning plain dicts.
def reflect(cls, X, **kwargs): if isinstance(X, type): value = None value_type = X else: value = X value_type = type(X) if not issubclass(value_type, Record): raise TypeError("Cannot reflect on %s" % value_type.__name__) ...
Reflect is for visitors where you are exposing some information about the types reachable from a starting type to an external system. For example, a front-end, a REST URL router and documentation framework, an avro schema definition, etc. X can be a type or an instance. This AP...
def scantypes(cls, value, value_type, visitor): item_type_generator = None if issubclass(value_type, Collection): def get_item_types(): if isinstance(value_type.itemtype, tuple): # not actually supported by Collection yet, but whatever ...
Like :py:meth:`normalize.visitor.VisitorPattern.unpack`, but returns a getter which just returns the property, and a collection getter which returns a set with a single item in it.
def propinfo(cls, value, prop, visitor): if not prop: return {"name": value.__name__} rv = {"name": prop.name} if prop.valuetype: if isinstance(prop.valuetype, tuple): rv['type'] = [typ.__name__ for typ in prop.valuetype] else: ...
Like :py:meth:`normalize.visitor.VisitorPattern.apply`, but takes a property and returns a dict with some basic info. The default implementation returns just the name of the property and the type in here.
def itemtypes(cls, mapped_types, coll_type, visitor): rv = list(v for k, v in mapped_types) return rv[0] if len(rv) == 1 else rv
Like :py:meth:`normalize.visitor.VisitorPattern.aggregate`, but returns . This will normally only get called with a single type.
def typeinfo(cls, propinfo, type_parameters, value_type, visitor): propspec = dict((prop.name, info) for prop, info in propinfo) ts = {'name': value_type.__name__} if propspec: ts['properties'] = propspec if type_parameters: ts['itemtype'] = type_paramete...
Like :py:meth:`normalize.visitor.VisitorPattern.reduce`, but returns the final dictionary to correspond to a type definition. The default implementation returns just the type name, the list of properties, and the item type for collections.
def map(cls, visitor, value, value_type): unpacked = visitor.unpack(value, value_type, visitor) if unpacked == cls.StopVisiting or isinstance( unpacked, cls.StopVisiting ): return unpacked.return_value if isinstance(unpacked, tuple): props, ...
The common visitor API used by all three visitor implementations. args: ``visitor=``\ *Visitor* Visitor options instance: contains the callbacks to use to implement the visiting, as well as traversal & filtering options. ``value=``\ *Obj...
def _get_fba_problem(model, tfba, solver): p = FluxBalanceProblem(model, solver) if tfba: p.add_thermodynamic() return p
Convenience function for returning the right FBA problem instance
def flux_balance(model, reaction, tfba, solver): fba = _get_fba_problem(model, tfba, solver) fba.maximize(reaction) for reaction in model.reactions: yield reaction, fba.get_flux(reaction)
Run flux balance analysis on the given model. Yields the reaction id and flux value for each reaction in the model. This is a convenience function for sertting up and running the FluxBalanceProblem. If the FBA is solved for more than one parameter it is recommended to setup and reuse the FluxBalancePr...
def flux_variability(model, reactions, fixed, tfba, solver): fba = _get_fba_problem(model, tfba, solver) for reaction_id, value in iteritems(fixed): flux = fba.get_flux_var(reaction_id) fba.prob.add_linear_constraints(flux >= value) def min_max_solve(reaction_id): for directi...
Find the variability of each reaction while fixing certain fluxes. Yields the reaction id, and a tuple of minimum and maximum value for each of the given reactions. The fixed reactions are given in a dictionary as a reaction id to value mapping. This is an implementation of flux variability analysis (...
def flux_minimization(model, fixed, solver, weights={}): fba = FluxBalanceProblem(model, solver) for reaction_id, value in iteritems(fixed): flux = fba.get_flux_var(reaction_id) fba.prob.add_linear_constraints(flux >= value) fba.minimize_l1() return ((reaction_id, fba.get_flux(r...
Minimize flux of all reactions while keeping certain fluxes fixed. The fixed reactions are given in a dictionary as reaction id to value mapping. The weighted L1-norm of the fluxes is minimized. Args: model: MetabolicModel to solve. fixed: dict of additional lower bounds on reaction fluxes...
def flux_randomization(model, threshold, tfba, solver): optimize = {} for reaction_id in model.reactions: if model.is_reversible(reaction_id): optimize[reaction_id] = 2*random.random() - 1.0 else: optimize[reaction_id] = random.random() fba = _get_fba_problem(m...
Find a random flux solution on the boundary of the solution space. The reactions in the threshold dictionary are constrained with the associated lower bound. Args: model: MetabolicModel to solve. threshold: dict of additional lower bounds on reaction fluxes. tfba: If True enable th...
def consistency_check(model, subset, epsilon, tfba, solver): fba = _get_fba_problem(model, tfba, solver) subset = set(subset) while len(subset) > 0: reaction = next(iter(subset)) logger.info('{} left, checking {}...'.format(len(subset), reaction)) fba.maximize(reaction) ...
Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and also allows the reaction in question to have non-zero flux. Th...
def maximize(self, reaction): self._prob.set_objective(self.flux_expr(reaction)) self._solve()
Solve the model by maximizing the given reaction. If reaction is a dictionary object, each entry is interpreted as a weight on the objective for that reaction (non-existent reaction will have zero weight).
def flux_bound(self, reaction, direction): try: self.maximize({reaction: direction}) except FluxBalanceError as e: if not e.result.unbounded: raise return direction * _INF else: return self.get_flux(reaction)
Return the flux bound of the reaction. Direction must be a positive number to obtain the upper bound or a negative number to obtain the lower bound. A value of inf or -inf is returned if the problem is unbounded.
def _add_minimization_vars(self): self._z = self._prob.namespace(self._model.reactions, lower=0) # Define constraints v = self._v.set(self._model.reactions) z = self._z.set(self._model.reactions) self._prob.add_linear_constraints(z >= v, v >= -z)
Add variables and constraints for L1 norm minimization.
def minimize_l1(self, weights={}): if self._z is None: self._add_minimization_vars() objective = self._z.expr( (reaction_id, -weights.get(reaction_id, 1)) for reaction_id in self._model.reactions) self._prob.set_objective(objective) self._s...
Solve the model by minimizing the L1 norm of the fluxes. If the weights dictionary is given, the weighted L1 norm if minimized instead. The dictionary contains the weights of each reaction (default 1).
def max_min_l1(self, reaction, weights={}): self.maximize(reaction) if isinstance(reaction, dict): reactions = list(reaction) else: reactions = [reaction] # Save flux values before modifying the LP problem fluxes = {r: self.get_flux(r) for r in...
Maximize flux of reaction then minimize the L1 norm. During minimization the given reaction will be fixed at the maximum obtained from the first solution. If reaction is a dictionary object, each entry is interpreted as a weight on the objective for that reaction (non-existent reaction ...
def _solve(self): # Remove temporary constraints while len(self._remove_constr) > 0: self._remove_constr.pop().delete() try: self._prob.solve(lp.ObjectiveSense.Maximize) except lp.SolverError as e: raise_from(FluxBalanceError('Failed to solv...
Solve the problem with the current objective.
def flux_expr(self, reaction): if isinstance(reaction, dict): return self._v.expr(iteritems(reaction)) return self._v(reaction)
Get LP expression representing the reaction flux.
def get_flux(self, reaction): return self._prob.result.get_value(self._v(reaction))
Get resulting flux value for reaction.
def define(self, *names, **kwargs): 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) vartyp...
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 ...
def _add_constraints(self, relation): expression = relation.expression names = [] for value_set in expression.value_sets(): values = ((self._variables[variable], value) for variable, value in value_set) constr_name = next(self._constr_names)...
Add the given relation as one or more constraints Return a list of the names of the constraints added.
def set_objective(self, expression): if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression() self._p.set_linear_objective( (lp_name, expression.value(var)...
Set linear objective of problem
def set_objective_sense(self, sense): if sense == ObjectiveSense.Minimize: self._p.set_objective_sense(qsoptex.ObjectiveSense.MINIMIZE) elif sense == ObjectiveSense.Maximize: self._p.set_objective_sense(qsoptex.ObjectiveSense.MAXIMIZE) else: raise Val...
Set type of problem (maximize or minimize)
def solve_unchecked(self, sense=None): if sense is not None: self.set_objective_sense(sense) self._p.solve() self._result = Result(self) return self._result
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.
def success(self): self._check_valid() return self._problem._p.get_status() == qsoptex.SolutionStatus.OPTIMAL
Return boolean indicating whether a solution was found
def unbounded(self): self._check_valid() return (self._problem._p.get_status() == qsoptex.SolutionStatus.UNBOUNDED)
Whether the solution is unbounded
def _get_value(self, var): return self._problem._p.get_value(self._problem._variables[var])
Return value of variable in solution.
def _execute(job, f, o=None): # Re-use the same buffer for output, we will read from it after each # iteration. out = ctypes.create_string_buffer(RS_JOB_BLOCKSIZE) while True: block = f.read(RS_JOB_BLOCKSIZE) buff = Buffer() # provide the data block via input buffer. ...
Executes a librsync "job" by reading bytes from `f` and writing results to `o` if provided. If `o` is omitted, the output is ignored.
def signature(f, s=None, block_size=RS_DEFAULT_BLOCK_LEN): if s is None: s = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+') job = _librsync.rs_sig_begin(block_size, RS_DEFAULT_STRONG_LEN) try: _execute(job, f, s) finally: _librsync.rs_job_free(job) return ...
Generate a signature for the file `f`. The signature will be written to `s`. If `s` is omitted, a temporary file will be used. This function returns the signature file `s`. You can specify the size of the blocks using the optional `block_size` parameter.
def delta(f, s, d=None): if d is None: d = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+') sig = ctypes.c_void_p() try: job = _librsync.rs_loadsig_begin(ctypes.byref(sig)) try: _execute(job, s) finally: _librsync.rs_job_free(job) ...
Create a delta for the file `f` using the signature read from `s`. The delta will be written to `d`. If `d` is omitted, a temporary file will be used. This function returns the delta file `d`. All parameters must be file-like objects.
def patch(f, d, o=None): if o is None: o = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+') @patch_callback def read_cb(opaque, pos, length, buff): f.seek(pos) size_p = ctypes.cast(length, ctypes.POINTER(ctypes.c_size_t)).contents size = size_p.value ...
Patch the file `f` using the delta `d`. The patched file will be written to `o`. If `o` is omitted, a temporary file will be used. This function returns the be patched file `o`. All parameters should be file-like objects. `f` is required to be seekable.
def _find_integer_tolerance(epsilon, v_max, min_tol): int_tol = min(epsilon / (10 * v_max), 0.1) min_tol = max(1e-10, min_tol) if int_tol < min_tol: eps_lower = min_tol * 10 * v_max logger.warning( 'When the maximum flux is {}, it is recommended that' ' epsilon >...
Find appropriate integer tolerance for gap-filling problems.
def float_constructor(loader, node): s = loader.construct_scalar(node) if s == '.inf': return Decimal('Infinity') elif s == '-.inf': return -Decimal('Infinity') elif s == '.nan': return Decimal('NaN') return Decimal(s)
Construct Decimal from YAML float encoding.
def yaml_load(stream): # Surprisingly, the CSafeLoader does not seem to be used by default. # Check whether the CSafeLoader is available and provide a log message # if it is not available. global _HAS_YAML_LIBRARY if _HAS_YAML_LIBRARY is None: _HAS_YAML_LIBRARY = hasattr(yaml, 'CSafeLo...
Load YAML file using safe loader.
def _check_id(entity, entity_type): if entity is None: raise ParseError('{} ID missing'.format(entity_type)) elif not isinstance(entity, string_types): msg = '{} ID must be a string, id was {}.'.format(entity_type, entity) if isinstance(entity, bool): msg += (' You may ...
Check whether the ID is valid. First check if the ID is missing, and then check if it is a qualified string type, finally check if the string is empty. For all checks, it would raise a ParseError with the corresponding message. Args: entity: a string type object to be checked. entity_t...
def parse_compound(compound_def, context=None): compound_id = compound_def.get('id') _check_id(compound_id, 'Compound') mark = FileMark(context, None, None) return CompoundEntry(compound_def, mark)
Parse a structured compound definition as obtained from a YAML file Returns a CompoundEntry.
def parse_compound_list(path, compounds): context = FilePathContext(path) for compound_def in compounds: if 'include' in compound_def: file_format = compound_def.get('format') include_context = context.resolve(compound_def['include']) for compound in parse_comp...
Parse a structured list of compounds as obtained from a YAML file Yields CompoundEntries. Path can be given as a string or a context.
def parse_compound_table_file(path, f): context = FilePathContext(path) for i, 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 iter...
Parse a tab-separated file containing compound IDs and properties The compound properties are parsed according to the header which specifies which property is contained in each column.