code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self._check_valid()
return self._problem._p.get_status() == qsoptex.SolutionStatus.OPTIMAL | def success(self) | Return boolean indicating whether a solution was found | 22.903812 | 16.854134 | 1.358943 |
self._check_valid()
return (self._problem._p.get_status() ==
qsoptex.SolutionStatus.UNBOUNDED) | def unbounded(self) | Whether the solution is unbounded | 22.207207 | 17.600256 | 1.261755 |
return self._problem._p.get_value(self._problem._variables[var]) | def _get_value(self, var) | Return value of variable in solution. | 12.662313 | 7.993752 | 1.584026 |
# 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.
buff.next_in = ctypes.c_char_... | def _execute(job, f, o=None) | Executes a librsync "job" by reading bytes from `f` and writing results to
`o` if provided. If `o` is omitted, the output is ignored. | 4.077456 | 3.96031 | 1.02958 |
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 s | def signature(f, s=None, block_size=RS_DEFAULT_BLOCK_LEN) | 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. | 5.379938 | 5.599312 | 0.960821 |
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)
r = _librsync.rs_bui... | def delta(f, s, d=None) | 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. | 4.032637 | 3.648157 | 1.10539 |
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
block = f.read(size)
... | def patch(f, d, o=None) | 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. | 3.778271 | 3.693845 | 1.022856 |
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 > {} to avoid numerical issues with this'
'... | def _find_integer_tolerance(epsilon, v_max, min_tol) | Find appropriate integer tolerance for gap-filling problems. | 4.821549 | 4.838279 | 0.996542 |
prob = solver.create_problem()
# Set integrality tolerance such that w constraints are correct
min_tol = prob.integrality_tolerance.min
int_tol = _find_integer_tolerance(epsilon, v_max, min_tol)
if int_tol < prob.integrality_tolerance.value:
prob.integrality_tolerance.value = int_tol
... | def gapfind(model, solver, epsilon=0.001, v_max=1000, implicit_sinks=True) | Identify compounds in the model that cannot be produced.
Yields all compounds that cannot be produced. This method
assumes implicit sinks for all compounds in the model so
the only factor that influences whether a compound can be
produced is the presence of the compounds needed to produce it.
Epsi... | 3.847718 | 3.763885 | 1.022273 |
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) | def float_constructor(loader, node) | Construct Decimal from YAML float encoding. | 2.326152 | 1.981706 | 1.173813 |
# 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, 'CSafeLoader')
if not _... | def yaml_load(stream) | Load YAML file using safe loader. | 3.578605 | 3.536772 | 1.011828 |
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 have accidentally used an ID value t... | def _check_id(entity, entity_type) | 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... | 3.859964 | 3.556868 | 1.085214 |
compound_id = compound_def.get('id')
_check_id(compound_id, 'Compound')
mark = FileMark(context, None, None)
return CompoundEntry(compound_def, mark) | def parse_compound(compound_def, context=None) | Parse a structured compound definition as obtained from a YAML file
Returns a CompoundEntry. | 7.250619 | 7.119547 | 1.01841 |
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_compound_file(include_context, file_format):
... | def parse_compound_list(path, compounds) | Parse a structured list of compounds as obtained from a YAML file
Yields CompoundEntries. Path can be given as a string or a context. | 3.474946 | 3.2839 | 1.058177 |
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 iteritems(row) if value != ''}
if '... | def parse_compound_table_file(path, f) | 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. | 4.571053 | 4.490274 | 1.01799 |
if format is None:
if (re.match(r'.+\.(yml|yaml)$', path)):
return 'yaml'
elif (re.match(r'.+\.tsv$', path)):
return 'tsv'
else:
return format.lower() | def resolve_format(format, path) | Looks at a file's extension and format (if any) and returns format. | 2.964272 | 2.877299 | 1.030227 |
context = FilePathContext(path)
# YAML files do not need to explicitly specify format
format = resolve_format(format, context.filepath)
if format == 'yaml':
logger.debug('Parsing compound file {} as YAML'.format(
context.filepath))
with context.open('r') as f:
... | def parse_compound_file(path, format) | Open and parse reaction file based on file extension or given format
Path can be given as a string or a context. | 2.782895 | 2.750639 | 1.011727 |
def _translate_compartments(reaction, compartment):
left = (((c.in_compartment(compartment), v)
if c.compartment is None else (c, v))
for c, v in reaction.left)
right = (((c.in_compartment(compartment), v)
if c.compartment is None else... | def parse_reaction_equation_string(equation, default_compartment) | Parse a string representation of a reaction equation.
Converts undefined compartments to the default compartment. | 3.716335 | 3.718766 | 0.999346 |
def parse_compound_list(l, compartment):
for compound_def in l:
compound_id = compound_def.get('id')
_check_id(compound_id, 'Compound')
value = compound_def.get('value')
if value is None:
raise ParseError('Missing value for comp... | def parse_reaction_equation(equation_def, default_compartment) | Parse a structured reaction equation as obtained from a YAML file
Returns a Reaction. | 2.390517 | 2.393275 | 0.998848 |
reaction_id = reaction_def.get('id')
_check_id(reaction_id, 'Reaction')
reaction_props = dict(reaction_def)
# Parse reaction equation
if 'equation' in reaction_def:
reaction_props['equation'] = parse_reaction_equation(
reaction_def['equation'], default_compartment)
m... | def parse_reaction(reaction_def, default_compartment, context=None) | Parse a structured reaction definition as obtained from a YAML file
Returns a ReactionEntry. | 4.312948 | 4.310348 | 1.000603 |
context = FilePathContext(path)
for reaction_def in reactions:
if 'include' in reaction_def:
include_context = context.resolve(reaction_def['include'])
for reaction in parse_reaction_file(
include_context, default_compartment):
yield rea... | def parse_reaction_list(path, reactions, default_compartment=None) | Parse a structured list of reactions as obtained from a YAML file
Yields tuples of reaction ID and reaction object. Path can be given as a
string or a context. | 3.241719 | 3.441624 | 0.941916 |
context = FilePathContext(path)
for lineno, row in enumerate(csv.DictReader(f, delimiter=str('\t'))):
if 'id' not in row or row['id'].strip() == '':
raise ParseError('Expected `id` column in table')
props = {key: value for key, value in iteritems(row) if value != ''}
... | def parse_reaction_table_file(path, f, default_compartment) | Parse a tab-separated file containing reaction IDs and properties
The reaction properties are parsed according to the header which specifies
which property is contained in each column. | 4.318374 | 4.48282 | 0.963317 |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing reaction file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for reaction in parse_reaction_table_file(
... | def parse_reaction_file(path, default_compartment=None) | Open and parse reaction file based on file extension
Path can be given as a string or a context. | 2.679572 | 2.726461 | 0.982802 |
default_compartment = exchange_def.get('compartment', default_compartment)
for compound_def in exchange_def.get('compounds', []):
compartment = compound_def.get('compartment', default_compartment)
compound = Compound(compound_def['id'], compartment=compartment)
reaction = compound... | def parse_exchange(exchange_def, default_compartment) | Parse a structured exchange definition as obtained from a YAML file.
Returns in iterator of compound, reaction, lower and upper bounds. | 2.722629 | 2.366487 | 1.150494 |
context = FilePathContext(path)
for exchange_def in exchange:
if 'include' in exchange_def:
include_context = context.resolve(exchange_def['include'])
for exchange_compound in parse_exchange_file(
include_context, default_compartment):
y... | def parse_exchange_list(path, exchange, default_compartment) | Parse a structured exchange list as obtained from a YAML file.
Yields tuples of compound, reaction ID, lower and upper flux bounds. Path
can be given as a string or a context. | 3.44256 | 3.389085 | 1.015779 |
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
# A line can specify lower limit only (useful for
# medium compounds), or both lower and upper limit.
fields = line.split(None)
if len(fields) ... | def parse_exchange_table_file(f) | Parse a space-separated file containing exchange compound flux limits.
The first two columns contain compound IDs and compartment while the
third column contains the lower flux limits. The fourth column is
optional and contains the upper flux limit. | 4.664621 | 3.857605 | 1.209201 |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing exchange file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for entry in parse_exchange_table_file(f):
... | def parse_exchange_file(path, default_compartment) | Parse a file as a list of exchange compounds with flux limits.
The file format is detected and the file is parsed accordingly. Path can
be given as a string or a context. | 2.966922 | 2.86059 | 1.037171 |
lower, upper = get_limits(limit_def)
reaction = limit_def.get('reaction')
return reaction, lower, upper | def parse_limit(limit_def) | Parse a structured flux limit definition as obtained from a YAML file
Returns a tuple of reaction, lower and upper bound. | 7.124299 | 3.9714 | 1.793901 |
context = FilePathContext(path)
for limit_def in limits:
if 'include' in limit_def:
include_context = context.resolve(limit_def['include'])
for limit in parse_limits_file(include_context):
yield limit
else:
yield parse_limit(limit_def) | def parse_limits_list(path, limits) | Parse a structured list of flux limits as obtained from a YAML file
Yields tuples of reaction ID, lower and upper flux bounds. Path can be
given as a string or a context. | 3.862053 | 4.098709 | 0.942261 |
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
# A line can specify lower limit only (useful for
# exchange reactions), or both lower and upper limit.
fields = line.split(None)
if len(fields... | def parse_limits_table_file(f) | Parse a space-separated file containing reaction flux limits
The first column contains reaction IDs while the second column contains
the lower flux limits. The third column is optional and contains the
upper flux limit. | 4.273271 | 3.694843 | 1.15655 |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing limits file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for limit in parse_limits_table_file(f):
yie... | def parse_limits_file(path) | Parse a file as a list of reaction flux limits
The file format is detected and the file is parsed accordingly. Path can
be given as a string or a context. | 2.988724 | 2.834608 | 1.05437 |
context = FilePathContext(path)
for reaction_id in group.get('reactions', []):
yield reaction_id
# Parse subgroups
for reaction_id in parse_model_group_list(
context, group.get('groups', [])):
yield reaction_id | def parse_model_group(path, group) | Parse a structured model group as obtained from a YAML file
Path can be given as a string or a context. | 5.83358 | 6.292858 | 0.927016 |
context = FilePathContext(path)
for model_group in groups:
if 'include' in model_group:
include_context = context.resolve(model_group['include'])
for reaction_id in parse_model_file(include_context):
yield reaction_id
else:
for reaction_i... | def parse_model_group_list(path, groups) | Parse a structured list of model groups as obtained from a YAML file
Yields reaction IDs. Path can be given as a string or a context. | 3.532367 | 2.845915 | 1.241206 |
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
yield line | def parse_model_table_file(path, f) | Parse a file as a list of model reactions
Yields reactions IDs. Path can be given as a string or a context. | 3.943663 | 4.476974 | 0.880877 |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing model file {} as TSV'.format(context.filepath))
with context.open('r') as f:
for reaction_id in parse_model_table_file(context, f):
yie... | def parse_model_file(path) | Parse a file as a list of model reactions
The file format is detected and the file is parsed accordinly. The file is
specified as a file path that will be opened for reading. Path can be given
as a string or a context. | 3.226306 | 2.96465 | 1.088259 |
if len(data.compounds) > _MAX_REACTION_LENGTH:
def dict_make(compounds):
for compound, value in compounds:
yield OrderedDict([
('id', text_type(compound.name)),
('compartment', compound.compartment),
('value', value... | def _reaction_representer(dumper, data) | Generate a parsable reaction representation to the YAML parser.
Check the number of compounds in the reaction, if it is larger than 10,
then transform the reaction data into a list of directories with all
attributes in the reaction; otherwise, just return the text_type format
of the reaction data. | 3.783244 | 3.512311 | 1.077138 |
context = FilePathContext(path)
try:
with open(context.filepath, 'r') as f:
return ModelReader(f, context)
except IOError:
# Try to open the default file
for filename in cls.DEFAULT_MODEL:
try:
conte... | def reader_from_path(cls, path) | Create a model from specified path.
Path can be a directory containing a ``model.yaml`` or ``model.yml``
file or it can be a path naming the central model file directly. | 3.387144 | 3.577344 | 0.946832 |
compartments = OrderedDict()
boundaries = set()
if 'compartments' in self._model:
boundary_map = {}
for compartment_def in self._model['compartments']:
compartment_id = compartment_def.get('id')
_check_id(compartment_id, 'Compart... | def parse_compartments(self) | Parse compartment information from model.
Return tuple of: 1) iterator of
:class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs
defining the compartment boundaries of the model. | 3.000103 | 2.720445 | 1.102798 |
# Parse reactions defined in the main model file
if 'reactions' in self._model:
for reaction in parse_reaction_list(
self._context, self._model['reactions'],
self.default_compartment):
yield reaction | def parse_reactions(self) | Yield tuples of reaction ID and reactions defined in the model | 7.120131 | 5.637885 | 1.262908 |
if self.has_model_definition():
for reaction_id in parse_model_group_list(
self._context, self._model['model']):
yield reaction_id | def parse_model(self) | Yield reaction IDs of model reactions | 14.688263 | 8.379711 | 1.752836 |
if 'limits' in self._model:
if not isinstance(self._model['limits'], list):
raise ParseError('Expected limits to be a list')
for limit in parse_limits_list(
self._context, self._model['limits']):
yield limit | def parse_limits(self) | Yield tuples of reaction ID, lower, and upper bound flux limits | 4.737484 | 4.194495 | 1.129453 |
if 'media' in self._model:
if 'exchange' in self._model:
raise ParseError('Both "media" and "exchange" are specified')
logger.warning(
'The "media" key is deprecated! Please use "exchange" instead:'
' https://psamm.readthedocs.io/... | def parse_exchange(self) | Yield tuples of exchange compounds.
Each exchange compound is a tuple of compound, reaction ID, lower and
upper flux limits. | 3.976017 | 3.21419 | 1.23702 |
if 'compounds' in self._model:
for compound in parse_compound_list(
self._context, self._model['compounds']):
yield compound | def parse_compounds(self) | Yield CompoundEntries for defined compounds | 6.998671 | 5.421135 | 1.290997 |
properties = {
'name': self.name,
'biomass': self.biomass_reaction,
'extracellular': self.extracellular_compartment,
'default_compartment': self.default_compartment,
'default_flux_limit': self.default_flux_limit
}
if self.con... | def create_model(self) | Return :class:`NativeModel` fully loaded into memory. | 2.34684 | 2.268515 | 1.034527 |
def _translate_compartments(reaction, compartment):
left = (((c.in_compartment(compartment), v)
if c.compartment is None else (c, v))
for c, v in reaction.left)
right = (((c.in_compartment(compartment), v)
... | def create_metabolic_model(self) | Create a :class:`psamm.metabolicmodel.MetabolicModel`. | 2.473289 | 2.469848 | 1.001394 |
d = OrderedDict()
d['id'] = compartment.id
if adjacencies is not None:
d['adjacent_to'] = adjacencies
order = {key: i for i, key in enumerate(['name'])}
prop_keys = set(compartment.properties)
for prop in sorted(prop_keys,
... | def convert_compartment_entry(self, compartment, adjacencies) | Convert compartment entry to YAML dict.
Args:
compartment: :class:`psamm.datasource.entry.CompartmentEntry`.
adjacencies: Sequence of IDs or a single ID of adjacent
compartments (or None). | 3.188457 | 3.137229 | 1.016329 |
d = OrderedDict()
d['id'] = compound.id
order = {
key: i for i, key in enumerate(
['name', 'formula', 'formula_neutral', 'charge', 'kegg',
'cas'])}
prop_keys = (
set(compound.properties) - {'boundary', 'compartment'})
... | def convert_compound_entry(self, compound) | Convert compound entry to YAML dict. | 4.410397 | 4.086256 | 1.079325 |
d = OrderedDict()
d['id'] = reaction.id
def is_equation_valid(equation):
# If the equation is a Reaction object, it must have non-zero
# number of compounds.
return (equation is not None and (
not isinstance(equation, Reaction) or... | def convert_reaction_entry(self, reaction) | Convert reaction entry to YAML dict. | 3.725765 | 3.575955 | 1.041894 |
def iter_entries():
for c in entries:
entry = converter(c)
if entry is None:
continue
if properties is not None:
entry = OrderedDict(
(key, value) for key, value in iteritems(entr... | def _write_entries(self, stream, entries, converter, properties=None) | Write iterable of entries as YAML object to stream.
Args:
stream: File-like object.
entries: Iterable of entries.
converter: Conversion function from entry to YAML object.
properties: Set of compartment properties to output (or None to
output all)... | 3.72824 | 3.950552 | 0.943726 |
def convert(entry):
return self.convert_compartment_entry(
entry, adjacencies.get(entry.id))
self._write_entries(stream, compartments, convert, properties) | def write_compartments(self, stream, compartments, adjacencies,
properties=None) | Write iterable of compartments as YAML object to stream.
Args:
stream: File-like object.
compartments: Iterable of compartment entries.
adjacencies: Dictionary mapping IDs to adjacent compartment IDs.
properties: Set of compartment properties to output (or None t... | 4.864297 | 4.729464 | 1.028509 |
self._write_entries(
stream, compounds, self.convert_compound_entry, properties) | def write_compounds(self, stream, compounds, properties=None) | Write iterable of compounds as YAML object to stream.
Args:
stream: File-like object.
compounds: Iterable of compound entries.
properties: Set of compound properties to output (or None to output
all). | 7.57921 | 7.966868 | 0.951341 |
self._write_entries(
stream, reactions, self.convert_reaction_entry, properties) | def write_reactions(self, stream, reactions, properties=None) | Write iterable of reactions as YAML object to stream.
Args:
stream: File-like object.
compounds: Iterable of reaction entries.
properties: Set of reaction properties to output (or None to output
all). | 8.212128 | 8.542165 | 0.961364 |
r
def api_errorhandler(e):
if isinstance(e, RESTException):
return e.get_response()
elif isinstance(e, HTTPException) and e.description:
kwargs['message'] = e.description
if kwargs.get('status', 400) >= 500 and hasattr(g, 'sentry_event_id'):
kwargs['er... | def create_api_errorhandler(**kwargs) | r"""Create an API error handler.
E.g. register a 404 error:
.. code-block:: python
app.errorhandler(404)(create_api_errorhandler(
status=404, message='Not Found'))
:param \*\*kwargs: It contains the ``'status'`` and the ``'message'``
to describe the error. | 2.969845 | 3.316381 | 0.895508 |
if http_method == 'HEAD' and 'HEAD' not in self.method_serializers:
http_method = 'GET'
return (
self.method_serializers.get(http_method, self.serializers),
self.default_method_media_type.get(
http_method, self.default_media_type)
) | def get_method_serializers(self, http_method) | Get request method serializers + default media type.
Grab serializers from ``method_serializers`` if defined, otherwise
returns the default serializers. Uses GET serializers for HEAD requests
if no HEAD serializers were specified.
The method also determines the default media type.
... | 3.305424 | 2.776968 | 1.1903 |
# if the format query argument is present, match the serializer
arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME')
if arg_name:
arg_value = request.args.get(arg_name, None)
if arg_value is None:
return None
# Search for... | def _match_serializers_by_query_arg(self, serializers) | Match serializer by query arg. | 5.148141 | 4.886134 | 1.053623 |
# Bail out fast if no accept headers were given.
if len(request.accept_mimetypes) == 0:
return serializers[default_media_type]
# Determine best match based on quality.
best_quality = -1
best = None
has_wildcard = False
for client_accept, qual... | def _match_serializers_by_accept_headers(self, serializers,
default_media_type) | Match serializer by `Accept` headers. | 3.40632 | 3.437289 | 0.99099 |
return self._match_serializers_by_query_arg(serializers) or self.\
_match_serializers_by_accept_headers(serializers,
default_media_type) | def match_serializers(self, serializers, default_media_type) | Choose serializer for a given request based on query arg or headers.
Checks if query arg `format` (by default) is present and tries to match
the serializer based on the arg value, by resolving the mimetype mapped
to the arg value.
Otherwise, chooses the serializer by retrieving the best... | 6.481647 | 4.822219 | 1.344121 |
serializer = self.match_serializers(
*self.get_method_serializers(request.method))
if serializer:
return serializer(*args, **kwargs)
abort(406) | def make_response(self, *args, **kwargs) | Create a Flask Response.
Dispatch the given arguments to the serializer best matching the
current request's Accept header.
:return: The response created by the serializing function.
:rtype: :class:`flask.Response`
:raises werkzeug.exceptions.NotAcceptable: If no media type
... | 7.814628 | 6.897231 | 1.13301 |
result = super(ContentNegotiatedMethodView, self).dispatch_request(
*args, **kwargs
)
if isinstance(result, Response):
return result
elif isinstance(result, (list, tuple)):
return self.make_response(*result)
else:
return s... | def dispatch_request(self, *args, **kwargs) | Dispatch current request.
Dispatch the current request using
:class:`flask.views.MethodView` `dispatch_request()` then, if the
result is not already a :py:class:`flask.Response`, search for the
serializing function which matches the best the current request's
Accept header and u... | 2.606122 | 2.481461 | 1.050237 |
# bool(:py:class:`werkzeug.datastructures.ETags`) is not consistent
# in Python 3. bool(Etags()) == True even though it is empty.
if len(request.if_match.as_set(include_weak=weak)) > 0 or \
request.if_match.star_tag:
contains_etag = (request.if_match.contains... | def check_etag(self, etag, weak=False) | Validate the given ETag with current request conditions.
Compare the given ETag to the ones in the request header If-Match
and If-None-Match conditions.
The result is unspecified for requests having If-Match and
If-None-Match being both set.
:param str etag: The ETag of the cu... | 3.399472 | 3.164088 | 1.074392 |
dt = dt.replace(microsecond=0)
if request.if_modified_since and dt <= request.if_modified_since:
raise SameContentException(etag, last_modified=dt) | def check_if_modified_since(self, dt, etag=None) | Validate If-Modified-Since with current request conditions. | 5.06499 | 4.240263 | 1.194499 |
default_compartment = 'c'
default_key = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
default_key.add(compound.compartment)
if None in default_key and default... | def get_default_compartment(model) | Return what the default compartment should be set to.
If some compounds have no compartment, unique compartment
name is returned to avoid collisions. | 3.043499 | 2.918264 | 1.042914 |
flux_limit_count = Counter()
for reaction in model.reactions:
if reaction.id not in model.limits:
continue
equation = reaction.properties['equation']
if equation is None:
continue
_, lower, upper = model.limits[reaction.id]
if upper is not ... | def detect_best_flux_limit(model) | Detect the best default flux limit to use for model output.
The default flux limit does not change the model but selecting a good
value reduced the amount of output produced and reduces clutter in the
output files. | 2.786516 | 2.985907 | 0.933223 |
def safe_file_name(origin_name):
safe_name = re.sub(
r'\W+', '_', origin_name, flags=re.UNICODE)
safe_name = re.sub(
r'_+', '_', safe_name.lower(), flags=re.UNICODE)
safe_name = safe_name.strip('_')
return safe_name
common_reactions = []
reaction... | def reactions_to_files(model, dest, writer, split_subsystem) | Turn the reaction subsystems into their own files.
If a subsystem has a number of reactions over the threshold, it gets its
own YAML file. All other reactions, those that don't have a subsystem or
are in a subsystem that falls below the threshold, get added to a common
reaction file.
Args:
... | 1.960368 | 1.920124 | 1.020959 |
# Use value + 0 to convert any -0.0 to 0.0 which looks better.
if lower is not None and upper is not None and lower == upper:
yield 'fixed', upper + 0
else:
if lower is not None:
yield 'lower', lower + 0
if upper is not None:
yield 'upper', upper + 0 | def _generate_limit_items(lower, upper) | Yield key, value pairs for limits dictionary.
Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed``.
A key, value pair is emitted if the bounds are not None. | 5.091497 | 3.870442 | 1.315482 |
# Determine the default flux limits. If the value is already at the
# default it does not need to be included in the output.
lower_default, upper_default = None, None
if model.default_flux_limit is not None:
lower_default = -model.default_flux_limit
upper_default = model.default_flu... | def model_exchange(model) | Return exchange definition as YAML dict. | 3.825143 | 3.688428 | 1.037066 |
for reaction in sorted(model.reactions, key=lambda r: r.id):
equation = reaction.properties.get('equation')
if equation is None:
continue
# Determine the default flux limits. If the value is already at the
# default it does not need to be included in the output.
... | def model_reaction_limits(model) | Yield model reaction limits as YAML dicts. | 2.941733 | 2.871046 | 1.02462 |
compartment_ids = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
compartment = compound.compartment
if compartment is None:
compartment = mo... | def infer_compartment_entries(model) | Infer compartment entries for model based on reaction compounds. | 2.661031 | 2.54981 | 1.043619 |
def reaction_compartments(seq):
for compound, _ in seq:
compartment = compound.compartment
if compartment is None:
compartment = model.default_compartment
if compartment is not None:
yield compartment
for reaction in model.reacti... | def infer_compartment_adjacency(model) | Infer compartment adjacency for model based on reactions. | 2.639467 | 2.602186 | 1.014327 |
genes = set()
for reaction in model.reactions:
if reaction.genes is None:
continue
if isinstance(reaction.genes, boolean.Expression):
genes.update(v.symbol for v in reaction.genes.variables)
else:
genes.update(reaction.genes)
return len(gene... | def count_genes(model) | Count the number of distinct genes in model reactions. | 3.452477 | 2.898621 | 1.191076 |
s = s.strip()
if s == '':
return None
try:
# Do not return the parsed formula. For now it is better to keep
# the original formula string unchanged in all cases.
formula.Formula.parse(s)
except formula.ParseError:
logg... | def _try_parse_formula(self, compound_id, s) | Try to parse the given compound formula string.
Logs a warning if the formula could not be parsed. | 5.612533 | 5.345117 | 1.05003 |
try:
return parser(s, **kwargs)
except ReactionParseError as e:
if e.indicator is not None:
logger.error('{}\n{}\n{}'.format(
str(e), s, e.indicator))
raise ParseError('Unable to parse reaction {}: {}'.format(
... | def _try_parse_reaction(self, reaction_id, s,
parser=parse_reaction, **kwargs) | Try to parse the given reaction equation string.
Returns the parsed Reaction object, or raises an error if the reaction
could not be parsed. | 3.371115 | 3.660975 | 0.920824 |
s = s.strip()
if s == '':
return None
try:
return boolean.Expression(s)
except boolean.ParseError as e:
msg = 'Failed to parse gene association for {}: {}'.format(
reaction_id, text_type(e))
if e.indicator is not N... | def _try_parse_gene_association(self, reaction_id, s) | Try to parse the given gene association rule.
Logs a warning if the association rule could not be parsed and returns
the original string. Otherwise, returns the boolean.Expression object. | 4.445673 | 3.639302 | 1.221573 |
# Run Fastcore and print the induced reaction set
logger.info('Calculating Fastcore induced set on model')
induced = fastcore(
model_extended, core, epsilon=epsilon, weights=weights, solver=solver)
logger.debug('Result: |A| = {}, A = {}'.format(len(induced), induced))
added_reactions =... | def fastgapfill(model_extended, core, solver, weights={}, epsilon=1e-5) | Run FastGapFill gap-filling algorithm by calling
:func:`psamm.fastcore.fastcore`.
FastGapFill will try to find a minimum subset of reactions that includes
the core reactions and it also has no blocked reactions.
Return the set of reactions in the minimum subset. An extended model that
includes arti... | 5.098803 | 4.694929 | 1.086023 |
r
def decorator(f):
@wraps(f)
def inner(*args, **kwargs):
if request.mimetype not in allowed_content_types:
raise InvalidContentType(allowed_content_types)
return f(*args, **kwargs)
return inner
return decorator | def require_content_types(*allowed_content_types) | r"""Decorator to test if proper Content-Type is provided.
:param \*allowed_content_types: List of allowed content types.
:raises invenio_rest.errors.InvalidContentType: It's rised if a content
type not allowed is required. | 2.580198 | 2.531113 | 1.019393 |
key = env.get('host_string'), kwargs.get('base_url', env.get('docker_base_url'))
default_config = _get_default_config(None)
if default_config:
if key not in self:
self[key] = default_config
return default_config.get_client()
config = self.... | def get_connection(self, *args, **kwargs) | Create a new connection, or return an existing one from the cache. Uses Fabric's current ``env.host_string``
and the URL to the Docker service.
:param args: Additional arguments for the client constructor, if a new client has to be instantiated.
:param kwargs: Additional keyword args for the cl... | 5.251728 | 4.800069 | 1.094094 |
for solver in solvers:
for req, value in iteritems(requirements):
if (req in ('integer', 'quadratic', 'rational', 'name') and
(req not in solver or solver[req] != value)):
break
else:
yield solver | def filter_solvers(solvers, requirements) | Yield solvers that fullfil the requirements. | 4.727871 | 4.067476 | 1.16236 |
try:
key, value = s.split('=', 1)
except ValueError:
key, value = s, 'yes'
if key in ('rational', 'integer', 'quadratic'):
value = value.lower() in ('1', 'yes', 'true', 'on')
elif key in ('threads',):
value = int(value)
elif key in ('feasibility_tolerance', 'op... | def parse_solver_setting(s) | Parse a string containing a solver setting | 2.895951 | 2.883131 | 1.004446 |
parser = argparse.ArgumentParser(
description='''List LP solver available in PSAMM. This will produce a
list of all of the available LP solvers in prioritized
order. Addtional requirements can be imposed with the
arguments (e.g. integ... | def list_solvers(args=None) | Entry point for listing available solvers. | 3.137923 | 3.118267 | 1.006304 |
# Converters for opeartor clauses
operators = {
'and': And,
'or': Or,
None: lambda *args: args[0]
}
# Pairing of end group symbols with start group symbols
group_pairs = {
')': '(',
']': '['
}
scanner = re.compile(r'''
(\s+) | ... | def _parse_expression(s) | Parse boolean expression containing and/or operators | 2.667528 | 2.632845 | 1.013173 |
'''Lower bound'''
try:
return self._model._limits_lower[self._reaction]
except KeyError:
if self._model.is_reversible(self._reaction):
return -self._model._v_max
else:
return 0 | def lower(self) | Lower bound | 6.302696 | 6.599351 | 0.955048 |
'''Upper bound'''
try:
return self._model._limits_upper[self._reaction]
except KeyError:
return self._model._v_max | def upper(self) | Upper bound | 12.870685 | 13.354375 | 0.96378 |
if reaction_id not in self._reaction_set:
raise ValueError('Unknown reaction: {}'.format(repr(reaction_id)))
return self._database.get_reaction_values(reaction_id) | def get_reaction_values(self, reaction_id) | Return stoichiometric values of reaction as a dictionary | 3.70676 | 3.591911 | 1.031974 |
if compound_id not in self._compound_set:
raise ValueError('Compound not in model: {}'.format(compound_id))
for reaction_id in self._database.get_compound_reactions(compound_id):
if reaction_id in self._reaction_set:
yield reaction_id | def get_compound_reactions(self, compound_id) | Iterate over all reaction ids the includes the given compound | 2.918107 | 2.709839 | 1.076856 |
if reaction_id not in self._reaction_set:
raise ValueError('Reaction not in model: {}'.format(reaction_id))
return self._database.is_reversible(reaction_id) | def is_reversible(self, reaction_id) | Whether the given reaction is reversible | 3.500288 | 3.404951 | 1.027999 |
reaction = self.get_reaction(reaction_id)
return (len(reaction.left) == 0) != (len(reaction.right) == 0) | def is_exchange(self, reaction_id) | Whether the given reaction is an exchange reaction. | 4.124874 | 3.634949 | 1.134782 |
if reaction_id in self._reaction_set:
return
reaction = self._database.get_reaction(reaction_id)
self._reaction_set.add(reaction_id)
for compound, _ in reaction.compounds:
self._compound_set.add(compound) | def add_reaction(self, reaction_id) | Add reaction to model | 2.928522 | 2.844837 | 1.029416 |
if reaction not in self._reaction_set:
return
self._reaction_set.remove(reaction)
self._limits_lower.pop(reaction, None)
self._limits_upper.pop(reaction, None)
# Remove compound from compound_set if it is not referenced
# by any other reactions in ... | def remove_reaction(self, reaction) | Remove reaction from model | 3.456575 | 3.336855 | 1.035878 |
model = self.__class__(self._database)
model._limits_lower = dict(self._limits_lower)
model._limits_upper = dict(self._limits_upper)
model._reaction_set = set(self._reaction_set)
model._compound_set = set(self._compound_set)
return model | def copy(self) | Return copy of model | 4.015056 | 3.499461 | 1.147335 |
model_args = {}
if v_max is not None:
model_args['v_max'] = v_max
model = cls(database, **model_args)
if reaction_iter is None:
reaction_iter = iter(database.reactions)
for reaction_id in reaction_iter:
model.add_reaction(reaction_id... | def load_model(cls, database, reaction_iter=None, exchange=None,
limits=None, v_max=None) | Get model from reaction name iterator.
The model will contain all reactions of the iterator. | 2.64888 | 2.667631 | 0.992971 |
if self._reaction in self._view._flipped:
return -super(FlipableFluxBounds, self).upper
return super(FlipableFluxBounds, self).lower | def lower(self) | Lower bound | 14.408751 | 12.656351 | 1.13846 |
# 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 genes information
def reaction_genes_string(id):
if id no... | def run(self) | Run flux analysis command. | 3.581607 | 3.510664 | 1.020208 |
epsilon = self._args.epsilon
solver = self._get_solver()
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
# Maximize reaction flux
try:
p.maximize(reaction)
except fluxanalysis.FluxBalanceError as e:
... | def run_fba_minimized(self, reaction) | Run normal FBA and flux minimization on model. | 3.770193 | 3.653072 | 1.032061 |
solver = self._get_solver(integer=True)
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
p.add_thermodynamic()
try:
p.maximize(reaction)
except fluxanalysis.FluxBalanceError as e:
self.report_flux_balance_... | def run_tfba(self, reaction) | Run FBA and tFBA on model. | 5.089223 | 4.956817 | 1.026712 |
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=1)
prob.set_objective(m.sum(mass_compounds))
# Define constraints
massbalance_lhs =... | def is_consistent(database, solver, exchange=set(), zeromass=set()) | Try to assign a positive mass to each compound
Return True if successful. The masses are simply constrained by m_i > 1 and
finding a solution under these conditions proves that the database is mass
consistent. | 6.071001 | 5.929087 | 1.023935 |
# Create Flux balance problem
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=1)
# Define residual mass variables and objective constri... | def check_reaction_consistency(database, solver, exchange=set(),
checked=set(), zeromass=set(), weights={}) | Check inconsistent reactions by minimizing mass residuals
Return a reaction iterable, and compound iterable. The reaction iterable
yields reaction ids and mass residuals. The compound iterable yields
compound ids and mass assignments.
Each compound is assigned a mass of at least one, and the masses ar... | 3.980709 | 3.919919 | 1.015508 |
# Create mass balance problem
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=0)
# Define z variables
z = prob.namespace(mass_compo... | def check_compound_consistency(database, solver, exchange=set(),
zeromass=set()) | Yield each compound in the database with assigned mass
Each compound will be assigned a mass and the number of compounds having a
positive mass will be approximately maximized.
This is an implementation of the solution originally proposed by
[Gevorgyan08]_ but using the new method proposed by [Thiele... | 4.482559 | 4.481721 | 1.000187 |
if prefix in existing_ids:
suffix = 1
while True:
new_id = '{}_{}'.format(prefix, suffix)
if new_id not in existing_ids:
return new_id
suffix += 1
return prefix | def create_unique_id(prefix, existing_ids) | Return a unique string ID from the prefix.
First check if the prefix is itself a unique ID in the set-like parameter
existing_ids. If not, try integers in ascending order appended to the
prefix until a unique ID is found. | 1.819927 | 2.147958 | 0.847282 |
try:
p = subprocess.Popen(['git', 'describe', '--always', '--dirty'],
cwd=repo_path, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, _ = p.communicate()
except:
return None
else:
if p.returncode == 0:
... | def git_try_describe(repo_path) | Try to describe the current commit of a Git repository.
Return a string containing a string with the commit ID and/or a base tag,
if successful. Otherwise, return None. | 1.937199 | 2.069411 | 0.936111 |
def convex_cardinality_wrapper(*args, **kwargs):
def dict_result(r):
if isinstance(r, tuple):
return dict(r[0])
return dict(r)
# Initial run with default weights
full_result = f(*args, **kwargs)
result = dict_result(full_result)
... | def convex_cardinality_relaxed(f, epsilon=1e-5) | Transform L1-norm optimization function into cardinality optimization.
The given function must optimize a convex problem with
a weighted L1-norm as the objective. The transformed function
will apply the iterated weighted L1 heuristic to approximately
optimize the cardinality of the solution. This metho... | 3.214482 | 2.962697 | 1.084985 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.