code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ability = Ability(user, get_authorization_method())
return ability.can(action, subject) | def can(user, action, subject) | Checks if a given user has the ability to perform the action on a subject
:param user: A user object
:param action: an action string, typically 'read', 'edit', 'manage'. Use bouncer.constants for readability
:param subject: the resource in question. Either a Class or an instance of a class. Pass the cla... | 9.676394 | 20.194878 | 0.479151 |
ability = Ability(user, get_authorization_method())
return ability.cannot(action, subject) | def cannot(user, action, subject) | inverse of ``can`` | 10.642392 | 13.078506 | 0.813732 |
ability = Ability(user, get_authorization_method())
if ability.cannot(action, subject):
raise AccessDenied() | def ensure(user, action, subject) | Similar to ``can`` but will raise a AccessDenied Exception if does not have access | 11.646205 | 14.152231 | 0.822924 |
def can(self, action, subject):
ability = Ability(self, get_authorization_method())
return ability.can(action, subject)
def cannot(self, action, subject):
return not can(self, action, subject)
setattr(original_class, 'can', can)
setattr(original_class, 'cannot', cannot)
... | def authorization_target(original_class) | Add bouncer goodness to the model. This is a class decorator, when added to your User model if will add
``can`` and ``cannot`` methods to the class
:param original_class: the User class to be decorated | 3.461431 | 3.330768 | 1.039229 |
return ctx.gi.annotations.set_translation_start(feature_id, start, organism=organism, sequence=sequence) | def cli(ctx, feature_id, start, organism="", sequence="") | Set the translation start of a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]}) | 3.610755 | 4.014916 | 0.899335 |
return ctx.gi.annotations.update_dbxref(feature_id, old_db, old_accession, new_db, new_accession, organism=organism, sequence=sequence) | def cli(ctx, feature_id, old_db, old_accession, new_db, new_accession, organism="", sequence="") | Delete a dbxref from a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]}) | 2.381499 | 2.814816 | 0.846058 |
if self.id is None:
raise ValueError("Cannot dump an annotation with no ID.")
pattern = re.compile("{(.*?)}")
dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern)
destination = os.path.dirname(dest_pattern)
... | def dump(self, dest_pattern="{id}.jpg", override=True, mask=False, alpha=False, bits=8,
zoom=None, max_size=None, increase_area=None, contrast=None, gamma=None, colormap=None, inverse=None) | Download the annotation crop, with optional image modifications.
Parameters
----------
dest_pattern : str, optional
Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute
if it exists.
override : bool, optional
... | 2.610393 | 2.459807 | 1.061218 |
return ctx.gi.annotations.set_sequence(organism, sequence) | def cli(ctx, 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 | 7.191318 | 13.542651 | 0.531013 |
return ctx.gi.annotations.get_features(organism=organism, sequence=sequence) | def cli(ctx, organism="", sequence="") | Get the features for an organism / sequence
Output:
A standard apollo feature dictionary ({"features": [{...}]}) | 5.204278 | 5.625277 | 0.925159 |
return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata) | def cli(ctx, comment, metadata="") | Add a canned comment
Output:
A dictionnary containing canned comment description | 9.020914 | 7.583422 | 1.189557 |
return ctx.gi.users.update_organism_permissions(user, organism, administrate=administrate, write=write, export=export, read=read) | def cli(ctx, user, organism, administrate=False, write=False, export=False, read=False) | Update the permissions of a user on a specified organism
Output:
a dictionary containing user's organism permissions | 2.730621 | 2.647631 | 1.031345 |
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()
) + ")" | def path(self) | The path attribute returns a stringified, concise representation of
the MultiFieldSelector. It can be reversed by the ``from_path``
constructor. | 3.514736 | 3.12616 | 1.124298 |
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 = self.heads[None]
... | def get(self, obj) | 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. | 2.652968 | 2.511451 | 1.056349 |
# 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:
fs.delete(obj)
... | def delete(self, obj, force=False) | 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... | 5.354226 | 5.876976 | 0.911051 |
# 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))
except FieldSelectorException:
... | def patch(self, target, source, copy=False) | 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*
... | 5.216205 | 4.842889 | 1.077085 |
# 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)
# Calculate penalty if penalty file exists
penalties = {}
if self._args.... | def run(self) | Run GapFill command | 3.337211 | 3.277437 | 1.018238 |
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) | def reset_socat(use_sudo=False) | 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 | 5.336706 | 5.947727 | 0.897268 |
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) | def version() | Shows version information of the remote Docker service, similar to ``docker version``. | 6.783775 | 6.152771 | 1.102556 |
images = docker_fabric().images(all=list_all)
_format_output_table(images, IMAGE_COLUMNS, full_ids) | def list_images(list_all=False, full_ids=False) | 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... | 9.229024 | 16.32795 | 0.565229 |
containers = docker_fabric().containers(all=list_all)
_format_output_table(containers, CONTAINER_COLUMNS, full_ids, full_cmd, short_image) | def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False) | 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
:... | 5.71358 | 10.7119 | 0.533386 |
networks = docker_fabric().networks()
_format_output_table(networks, NETWORK_COLUMNS, full_ids) | def list_networks(full_ids=False) | 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 | 13.167139 | 22.52067 | 0.584669 |
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') | def cleanup_containers(**kwargs) | Removes all containers that have finished running. Similar to the ``prune`` functionality in newer Docker versions. | 7.425718 | 7.350825 | 1.010188 |
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 images:')
for image_name in removed_images:
... | def cleanup_images(remove_old=False, **kwargs) | 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 | 5.517709 | 5.384231 | 1.024791 |
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') | def remove_all_containers(**kwargs) | Stops and removes all containers from the remote. Use with caution outside of a development environment!
:return: | 10.673662 | 11.708424 | 0.911622 |
local_name = filename or '{0}.tar.gz'.format(image)
cli.save_image(image, local_name) | def save_image(image, filename=None) | 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... | 7.724384 | 7.174512 | 1.076642 |
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 | def load_image(filename, timeout=120) | 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 | 6.02003 | 5.719215 | 1.052597 |
"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_connection('batch')
# assign to ... | def execute(self, raise_on_error=True) | Execute all the commands in the current pipeline | 4.628036 | 4.20343 | 1.101014 |
from normalize.diff import diff_iter
return diff_iter(self, other, **kwargs) | def 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*
... | 6.703488 | 10.18384 | 0.658248 |
from normalize.diff import diff
return diff(self, other, **kwargs) | def 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` | 9.694362 | 7.206707 | 1.345186 |
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 weight assignment: {}'.format(weight_assignment))
... | def _parse_weights(weight_args, default_weight=0.6) | Parse list of weight assignments. | 2.843617 | 2.649304 | 1.073345 |
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 iteritems(transfers):
yield re... | def _combine_transfers(self, result) | Combine multiple pair transfers into one. | 4.158514 | 3.862491 | 1.07664 |
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, base_name)
archive_name = 'container_{0}.tar.gz'.format(container)... | def copy_resource(container, resource, local_filename, contents_only=True) | 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... | 3.057856 | 3.195232 | 0.957006 |
def _copy_resource(resource):
default_dest_path = generic_path if generic_path is not None else resource
dest_path = directories.get(resource, default_dest_path).strip(posixpath.sep)
head, tail = posixpath.split(dest_path)
rel_path = posixpath.join(storage_dir, head)
run... | def copy_resources(src_container, src_resources, storage_dir, dst_directories=None, apply_chown=None, apply_chmod=None) | Copies files and directories from a Docker container. Multiple resources can be copied and additional options are
available than in :func:`copy_resource`. Unlike in :func:`copy_resource`, Resources are copied as they are and not
compressed to a tarball, and they are left on the remote machine.
:param src_c... | 3.590923 | 3.266045 | 1.099471 |
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_resources, copy_path, **kwargs)
with cd(copy_path):
sudo(targz(... | def isolate_and_get(src_container, src_resources, local_dst_dir, **kwargs) | 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... | 3.510787 | 3.671857 | 0.956134 |
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)) | def isolate_to_image(src_container, src_resources, dst_image, **kwargs) | 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... | 4.434345 | 5.543294 | 0.799948 |
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, archive), shell=False)
get(archive, ... | def save_image(image, local_filename) | 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... | 5.391053 | 4.570895 | 1.17943 |
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, dest_image), shell=False) | def flatten_image(image, dest_image=None, no_op_cmd='/bin/true', create_kwargs={}, start_kwargs={}) | 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 ... | 2.895592 | 3.396891 | 0.852424 |
# Some names contain XML-like entity codes
return re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), s) | def decode_name(s) | Decode names in ModelSEED files | 5.793248 | 6.181956 | 0.937122 |
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 at
# the end of formulas. This seem... | def parse_compound_file(f, context=None) | Iterate over the compound entries in the given file | 5.207946 | 5.073058 | 1.026589 |
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_argument(
'--id', ... | def init_parser(cls, parser) | Initialize argument parser | 1.944927 | 1.928186 | 1.008682 |
which_command = self._args.which
if which_command == 'compound':
self._search_compound()
elif which_command == 'reaction':
self._search_reaction() | def run(self) | Run search command. | 6.219566 | 4.338937 | 1.433431 |
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(propval, extraneous) | def to_json(self, propval, extraneous=False, to_json_func=None) | 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. | 3.309037 | 2.804391 | 1.179948 |
self.init_config(app)
# Enable CORS support if desired
if app.config['REST_ENABLE_CORS']:
from flask_cors import CORS
CORS(app)
# CORS can be configured using CORS_* configuration variables.
app.errorhandler(400)(create_api_errorhandler(
... | def init_app(self, app) | Flask application initialization.
Initialize the Rate-Limiter, CORS and error handlers.
:param app: An instance of :class:`flask.Flask`. | 1.40229 | 1.411706 | 0.99333 |
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)) | def init_config(self, app) | Initialize configuration.
.. note:: Change Flask-CORS and Flask-Limiter defaults.
:param app: An instance of :class:`flask.Flask`. | 5.37625 | 5.938339 | 0.905346 |
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
return Compound(compound_id, compartment=compartme... | def parse_compound(s, global_compartment=None) | Parse a compound specification.
If no compartment is specified in the string, the global compartment
will be used. | 2.168333 | 2.155232 | 1.006079 |
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)) | def parse_compound_count(s) | Parse a compound count (number of compounds). | 3.794462 | 3.57201 | 1.062276 |
global_comp = None
if self._parse_global:
# Split by colon for global compartment information
m = re.match(r'^\s*\[(\w+)\]\s*:\s*(.*)', s)
if m is not None:
global_comp = m.group(1)
s = m.group(2)
expect_operator = Fa... | def parse(self, s) | Parse reaction string. | 2.593772 | 2.533879 | 1.023637 |
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(g) for g in reaction.genes]
... | def get_gene_associations(model) | 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... | 4.364989 | 3.76375 | 1.159745 |
essential = set()
deleted = set()
for entity, deleted_reactions in strategy.iter_tests():
if obj_reaction in deleted_reactions:
logger.info(
'Marking entity {} as essential because the objective'
' reaction depends on this entity...'.format(entity))
... | def random_sparse(strategy, prob, obj_reaction, flux_threshold) | Find a random minimal network of model reactions.
Given a reaction to optimize and a threshold, delete entities randomly
until the flux of the reaction to optimize falls under the threshold.
Keep deleting until no more entities can be deleted. It works
with two strategies: deleting reactions or deletin... | 3.198649 | 3.017498 | 1.060033 |
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], lower=lower, upper=upper)
# Build mass balance constraints
m... | def run_sink_check(self, model, solver, threshold, implicit_sinks=True) | Run sink production check method. | 4.066484 | 4.087348 | 0.994895 |
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], lower=lower, upper=upper)
# Build mass balance constraints
m... | def run_reaction_production_check(self, model, solver, threshold,
implicit_sinks=True) | Run reaction production check method. | 3.525341 | 3.529527 | 0.998814 |
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.973565 | 2.778949 | 1.070032 |
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.SparsePair(ind=ind, val=val))
... | def _add_constraints(self, relation) | Add the given relation as one or more constraints
Return a list of the names of the constraints added. | 4.882079 | 4.717515 | 1.034883 |
constraints = []
for relation in relations:
if self._check_relation(relation):
constraints.append(Constraint(self, None))
else:
for name in self._add_constraints(relation):
constraints.append(Constraint(self, name))
... | def add_linear_constraints(self, *relations) | Add constraints to the problem
Each constraint is represented by a Relation, and the
expression in that relation can be a set expression. | 3.92124 | 4.039125 | 0.970814 |
if isinstance(expression, numbers.Number):
# Allow expressions with no variables as objective,
# represented as a number
expression = Expression(offset=expression)
linear = []
quad = []
# Reset previous objective.
for var in self._n... | def set_objective(self, expression) | Set objective expression of the problem. | 3.357634 | 3.342023 | 1.004671 |
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:
raise ValueError('Invalid objective sense... | def set_objective_sense(self, sense) | Set type of problem (maximize or minimize) | 1.996566 | 2.084377 | 0.957872 |
# Only need to reset the type after the first solve. This also works
# around a bug in Cplex where get_num_binary() is some rare cases
# causes a segfault.
if self._solve_count > 0:
integer_count = 0
for func in (self._cp.variables.get_num_binary,
... | def _reset_problem_type(self) | Reset problem type to whatever is appropriate. | 3.021729 | 2.963077 | 1.019794 |
if sense is not None:
self.set_objective_sense(sense)
self._solve()
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. | 4.999859 | 4.734641 | 1.056017 |
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) | def success(self) | Return boolean indicating whether a solution was found | 4.840445 | 3.890403 | 1.244201 |
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 to obtain a definiti... | def unbounded(self) | Whether solution is unbounded | 4.013773 | 3.750154 | 1.070296 |
return self._problem._cp.solution.get_values(
self._problem._variables[var]) | def _get_value(self, var) | Return value of variable in solution. | 11.92392 | 7.133532 | 1.671531 |
self._check_valid()
return super(Result, self).get_value(expression) | def get_value(self, expression) | Return value of expression. | 7.37019 | 5.680176 | 1.297528 |
obj_reaction = self._get_objective()
genes = set()
gene_assoc = {}
for reaction in self._model.reactions:
assoc = None
if reaction.genes is None:
continue
elif isinstance(reaction.genes, string_types):
assoc = ... | def run(self) | Delete the specified gene and solve using the desired method. | 3.021508 | 2.928985 | 1.031589 |
scanner = re.compile(r'''
(\s+) | # whitespace
(\(|\)) | # group
([A-Z][a-z]*) | # element
(\d+) | # number
([a-z]) | # variable
(\Z) | # end
(.) # error
''', re.DOTALL | re.VERBOSE)
def transform_... | def _parse_formula(s) | Parse formula string. | 2.659284 | 2.627023 | 1.01228 |
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,
visit_filter... | def copy(self) | Be sure to implement this method when sub-classing, otherwise you
will lose any specialization context. | 5.361611 | 5.284733 | 1.014547 |
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 TypeError(
"Cannot visit %s instance" ... | def visit(cls, value, value_type=None, **kwargs) | 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
... | 4.594405 | 4.863782 | 0.944616 |
if issubclass(value_type, Collection):
try:
generator = value.itertuples()
except AttributeError:
if isinstance(value, value_type.colltype):
generator = value_type.coll_to_tuples(value)
else:
... | def unpack(cls, value, value_type, visitor) | 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 ... | 4.930838 | 4.578102 | 1.077049 |
return (
None if isinstance(value, (AttributeError, KeyError)) else
value
) | def apply(cls, value, prop, visitor) | 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``.
... | 10.901197 | 11.525827 | 0.945806 |
return coll_type.tuples_to_coll(mapped_coll_generator, coerce=False) | def aggregate(self, mapped_coll_generator, coll_type, visitor) | 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... | 11.482015 | 7.093901 | 1.618576 |
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
value_type.properties.values()):
... | def reduce(self, mapped_props, aggregated, value_type, visitor) | 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... | 5.246161 | 5.077368 | 1.033244 |
if visitor is None:
visitor = cls.Visitor(
cls.grok, cls.reverse, cls.collect, cls.produce,
**kwargs)
return cls.map(visitor, value, value_type) | def cast(cls, value_type, value, visitor=None, **kwargs) | 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*
... | 7.998065 | 10.522207 | 0.760113 |
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, cls.grok_mapping_types):
raise ... | def grok(cls, value, value_type, visitor) | 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... | 3.255203 | 3.330108 | 0.977507 |
return (
None if isinstance(value, (AttributeError, KeyError)) else
value
) | def reverse(cls, value, prop, visitor) | Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called
for ``cast`` operations. The default implementation passes through but
squashes exceptions, just like apply. | 11.163012 | 12.29318 | 0.908065 |
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) | def produce(cls, mapped_props, aggregated, value_type, visitor) | Like :py:meth:`normalize.visitor.VisitorPattern.reduce`, but
constructs instances rather than returning plain dicts. | 3.788604 | 3.941344 | 0.961247 |
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__)
visitor = cls.Visitor(
... | def reflect(cls, X, **kwargs) | 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... | 5.396242 | 5.133571 | 1.051167 |
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
for vt in value_type.itemtype:
... | def scantypes(cls, value, value_type, visitor) | 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. | 4.068422 | 3.813759 | 1.066775 |
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:
rv['type'] = prop.valuetype.__n... | def propinfo(cls, value, prop, visitor) | 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. | 2.922758 | 2.603723 | 1.12253 |
rv = list(v for k, v in mapped_types)
return rv[0] if len(rv) == 1 else rv | def itemtypes(cls, mapped_types, coll_type, visitor) | Like :py:meth:`normalize.visitor.VisitorPattern.aggregate`, but
returns . This will normally only get called with a single type. | 5.228674 | 4.876634 | 1.072189 |
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_parameters
return ts | def typeinfo(cls, propinfo, type_parameters, value_type, visitor) | 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. | 4.372443 | 3.581435 | 1.220863 |
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, coll = unpacked
else:
... | def map(cls, visitor, value, value_type) | 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... | 3.504242 | 3.600923 | 0.973151 |
p = FluxBalanceProblem(model, solver)
if tfba:
p.add_thermodynamic()
return p | def _get_fba_problem(model, tfba, solver) | Convenience function for returning the right FBA problem instance | 9.59503 | 9.053088 | 1.059863 |
fba = _get_fba_problem(model, tfba, solver)
fba.maximize(reaction)
for reaction in model.reactions:
yield reaction, fba.get_flux(reaction) | def flux_balance(model, reaction, tfba, solver) | 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... | 4.984293 | 4.163081 | 1.197261 |
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 direction in (-1, 1):
yield fba.flux_bound(reaction_id, ... | def flux_variability(model, reactions, fixed, tfba, solver) | 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 (... | 4.67206 | 4.861794 | 0.960975 |
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(reaction_id))
for reaction_id in model.reactio... | def flux_minimization(model, fixed, solver, weights={}) | 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... | 5.583335 | 4.815365 | 1.159483 |
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(model, tfba, solver)
for reaction_id, value in iterit... | def flux_randomization(model, threshold, tfba, solver) | 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... | 3.529041 | 3.36288 | 1.04941 |
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)
subset = set(reaction_id for reaction_id in subset
... | def consistency_check(model, subset, epsilon, tfba, solver) | 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... | 3.393738 | 3.169207 | 1.070848 |
internal = set(r for r in self._model.reactions
if not self._model.is_exchange(r))
# Reaction fluxes
v = self._v
# Indicator variable
alpha = self._prob.namespace(internal, types=lp.VariableType.Binary)
# Delta mu is the stoichiometrica... | def add_thermodynamic(self, em=1000) | Apply thermodynamic constraints to the model.
Adding these constraints restricts the solution space to only
contain solutions that have no internal loops [Schilling00]_. This is
solved as a MILP problem as described in [Muller13]_. The time to solve
a problem with thermodynamic constrai... | 4.547278 | 4.364541 | 1.041869 |
self._prob.set_objective(self.flux_expr(reaction))
self._solve() | def maximize(self, reaction) | 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). | 13.440014 | 13.583224 | 0.989457 |
try:
self.maximize({reaction: direction})
except FluxBalanceError as e:
if not e.result.unbounded:
raise
return direction * _INF
else:
return self.get_flux(reaction) | def flux_bound(self, reaction, direction) | 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. | 9.042981 | 8.997209 | 1.005087 |
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) | def _add_minimization_vars(self) | Add variables and constraints for L1 norm minimization. | 7.997657 | 7.299222 | 1.095686 |
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._solve() | def minimize_l1(self, weights={}) | 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). | 7.248859 | 6.534676 | 1.109291 |
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 reactions}
# Add constraints on th... | def max_min_l1(self, reaction, weights={}) | 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 ... | 4.511921 | 4.096081 | 1.101521 |
# 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 solve: {}'.format(
... | def _solve(self) | Solve the problem with the current objective. | 6.146836 | 5.68096 | 1.082007 |
if isinstance(reaction, dict):
return self._v.expr(iteritems(reaction))
return self._v(reaction) | def flux_expr(self, reaction) | Get LP expression representing the reaction flux. | 11.449545 | 10.525956 | 1.087744 |
return self._prob.result.get_value(self._v(reaction)) | def get_flux(self, reaction) | Get resulting flux value for reaction. | 25.638939 | 19.39184 | 1.322151 |
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.723909 | 2.593341 | 1.050348 |
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)
sense = self.CONSTR_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. | 4.965108 | 4.665682 | 1.064176 |
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))
for var, lp_name in ite... | def set_objective(self, expression) | Set linear objective of problem | 10.425368 | 9.812626 | 1.062444 |
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 ValueError('Invalid objective sense') | def set_objective_sense(self, sense) | Set type of problem (maximize or minimize) | 2.71314 | 2.826568 | 0.959871 |
if sense is not None:
self.set_objective_sense(sense)
self._p.solve()
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.164243 | 5.002772 | 1.032276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.