Search is not available for this dataset
text stringlengths 75 104k |
|---|
def require_authentication(self, realm, environ):
"""Return True if this realm requires authentication (grant anonymous access otherwise)."""
realm_entry = self._get_realm_entry(realm)
if realm_entry is None:
_logger.error(
'Missing configuration simple_dc.user_mappin... |
def basic_auth_user(self, realm, user_name, password, environ):
"""Returns True if this user_name/password pair is valid for the realm,
False otherwise. Used for basic authentication."""
user = self._get_realm_entry(realm, user_name)
if user is not None and password == user.get("passwor... |
def digest_auth_user(self, realm, user_name, environ):
"""Computes digest hash A1 part."""
user = self._get_realm_entry(realm, user_name)
if user is None:
return False
password = user.get("password")
environ["wsgidav.auth.roles"] = user.get("roles", [])
return... |
def get(self, token):
"""Return a lock dictionary for a token.
If the lock does not exist or is expired, None is returned.
token:
lock token
Returns:
Lock dictionary or <None>
Side effect: if lock is expired, it will be purged and None is returned.
... |
def create(self, path, lock):
"""Create a direct lock for a resource path.
path:
Normalized path (utf8 encoded string, no trailing '/')
lock:
lock dictionary, without a token entry
Returns:
New unique lock token.: <lock
**Note:** the lock dic... |
def refresh(self, token, timeout):
"""Modify an existing lock's timeout.
token:
Valid lock token.
timeout:
Suggested lifetime in seconds (-1 for infinite).
The real expiration time may be shorter than requested!
Returns:
Lock dictionary.
... |
def delete(self, token):
"""Delete lock.
Returns True on success. False, if token does not exist, or is expired.
"""
self._lock.acquire_write()
try:
lock = self._dict.get(token)
_logger.debug("delete {}".format(lock_string(lock)))
if lock is N... |
def get_lock_list(self, path, include_root, include_children, token_only):
"""Return a list of direct locks for <path>.
Expired locks are *not* returned (but may be purged).
path:
Normalized path (utf8 encoded string, no trailing '/')
include_root:
False: don't ... |
def _flush(self):
"""Write persistent dictionary to disc."""
_logger.debug("_flush()")
self._lock.acquire_write() # TODO: read access is enough?
try:
self._dict.sync()
finally:
self._lock.release() |
def clear(self):
"""Delete all entries."""
self._lock.acquire_write() # TODO: read access is enough?
try:
was_closed = self._dict is None
if was_closed:
self.open()
if len(self._dict):
self._dict.clear()
self._d... |
def _fail(self, value, context_info=None, src_exception=None, err_condition=None):
"""Wrapper to raise (and log) DAVError."""
e = DAVError(value, context_info, src_exception, err_condition)
if self.verbose >= 4:
_logger.warning(
"Raising DAVError {}".format(
... |
def begin_write(self, content_type=None):
"""Open content as a stream for writing.
See DAVResource.begin_write()
"""
assert not self.is_collection
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
# _logger.debug("begin_write: {}, {}".format(self._fil... |
def delete(self):
"""Remove this resource or collection (recursive).
See DAVResource.delete()
"""
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
os.unlink(self._file_path)
self.remove_all_properties(True)
self.remove_all_locks(True) |
def copy_move_single(self, dest_path, is_move):
"""See DAVResource.copy_move_single() """
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
fpDest = self.provider._loc_to_file_path(dest_path, self.environ)
assert not util.is_equal_or_child_uri(self.path, dest_path)
... |
def move_recursive(self, dest_path):
"""See DAVResource.move_recursive() """
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
fpDest = self.provider._loc_to_file_path(dest_path, self.environ)
assert not util.is_equal_or_child_uri(self.path, dest_path)
assert ... |
def set_last_modified(self, dest_path, time_stamp, dry_run):
"""Set last modified time for destPath to timeStamp on epoch-format"""
# Translate time from RFC 1123 to seconds since epoch format
secs = util.parse_time_string(time_stamp)
if not dry_run:
os.utime(self._file_path,... |
def get_member_names(self):
"""Return list of direct collection member names (utf-8 encoded).
See DAVCollection.get_member_names()
"""
# On Windows NT/2k/XP and Unix, if path is a Unicode object, the result
# will be a list of Unicode objects.
# Undecodable filenames wil... |
def get_member(self, name):
"""Return direct collection member (DAVResource or derived).
See DAVCollection.get_member()
"""
assert compat.is_native(name), "{!r}".format(name)
fp = os.path.join(self._file_path, compat.to_unicode(name))
# name = name.encode("utf8")
... |
def create_empty_resource(self, name):
"""Create an empty (length-0) resource.
See DAVResource.create_empty_resource()
"""
assert "/" not in name
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
path = util.join_uri(self.path, name)
fp = self... |
def create_collection(self, name):
"""Create a new collection as member of self.
See DAVResource.create_collection()
"""
assert "/" not in name
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
path = util.join_uri(self.path, name)
fp = self.p... |
def delete(self):
"""Remove this resource or collection (recursive).
See DAVResource.delete()
"""
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
shutil.rmtree(self._file_path, ignore_errors=False)
self.remove_all_properties(True)
self.remov... |
def copy_move_single(self, dest_path, is_move):
"""See DAVResource.copy_move_single() """
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
fpDest = self.provider._loc_to_file_path(dest_path, self.environ)
assert not util.is_equal_or_child_uri(self.path, dest_path)
... |
def _loc_to_file_path(self, path, environ=None):
"""Convert resource path to a unicode absolute file path.
Optional environ argument may be useful e.g. in relation to per-user
sub-folder chrooting inside root_folder_path.
"""
root_path = self.root_folder_path
assert root_... |
def get_resource_inst(self, path, environ):
"""Return info dictionary for path.
See DAVProvider.get_resource_inst()
"""
self._count_get_resource_inst += 1
fp = self._loc_to_file_path(path, environ)
if not os.path.exists(fp):
return None
if os.path.is... |
def lock_string(lock_dict):
"""Return readable rep."""
if not lock_dict:
return "Lock: None"
if lock_dict["expire"] < 0:
expire = "Infinite ({})".format(lock_dict["expire"])
else:
expire = "{} (in {} seconds)".format(
util.get_log_time(lock_dict["expire"]), lock_dict... |
def _generate_lock(
self, principal, lock_type, lock_scope, lock_depth, lock_owner, path, timeout
):
"""Acquire lock and return lock_dict.
principal
Name of the principal.
lock_type
Must be 'write'.
lock_scope
Must be 'shared' or 'exclusiv... |
def acquire(
self,
url,
lock_type,
lock_scope,
lock_depth,
lock_owner,
timeout,
principal,
token_list,
):
"""Check for permissions and acquire a lock.
On success return new lock dictionary.
On error raise a DAVError wit... |
def refresh(self, token, timeout=None):
"""Set new timeout for lock, if existing and valid."""
if timeout is None:
timeout = LockManager.LOCK_TIME_OUT_DEFAULT
return self.storage.refresh(token, timeout) |
def get_lock(self, token, key=None):
"""Return lock_dict, or None, if not found or invalid.
Side effect: if lock is expired, it will be purged and None is returned.
key:
name of lock attribute that will be returned instead of a dictionary.
"""
assert key in (
... |
def get_url_lock_list(self, url):
"""Return list of lock_dict, if <url> is protected by at least one direct, valid lock.
Side effect: expired locks for this url are purged.
"""
url = normalize_lock_root(url)
lockList = self.storage.get_lock_list(
url, include_root=Tr... |
def get_indirect_url_lock_list(self, url, principal=None):
"""Return a list of valid lockDicts, that protect <path> directly or indirectly.
If a principal is given, only locks owned by this principal are returned.
Side effect: expired locks for this path and all parents are purged.
"""
... |
def is_url_locked_by_token(self, url, lock_token):
"""Check, if url (or any of it's parents) is locked by lock_token."""
lockUrl = self.get_lock(lock_token, "root")
return lockUrl and util.is_equal_or_child_uri(lockUrl, url) |
def _check_lock_permission(
self, url, lock_type, lock_scope, lock_depth, token_list, principal
):
"""Check, if <principal> can lock <url>, otherwise raise an error.
If locking <url> would create a conflict, DAVError(HTTP_LOCKED) is
raised. An embedded DAVErrorCondition contains the... |
def _sync(self):
"""Write persistent dictionary to disc."""
_logger.debug("_sync()")
self._lock.acquire_write() # TODO: read access is enough?
try:
if self._loaded:
self._dict.sync()
finally:
self._lock.release() |
def acquire_read(self, timeout=None):
"""Acquire a read lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout is <= 0.
In case timeout is None, the call to acquire_read blocks until the
lock request can be serviced.
In case t... |
def acquire_write(self, timeout=None):
"""Acquire a write lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout is <= 0.
In case the write lock cannot be serviced due to the deadlock
condition mentioned above, a ValueError is raised.
... |
def release(self):
"""Release the currently held lock.
In case the current thread holds no lock, a ValueError is thrown."""
me = currentThread()
self.__condition.acquire()
try:
if self.__writer is me:
# We are the writer, take one nesting depth away.... |
def _parse_gmt_time(timestring):
"""Return a standard time tuple (see time and calendar), for a date/time string."""
# Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
try:
return time.strptime(timestring, "%a, %d %b %Y %H:%M:%S GMT")
except Exception:
pass
# Sunday, 06... |
def init_logging(config):
"""Initialize base logger named 'wsgidav'.
The base logger is filtered by the `verbose` configuration option.
Log entries will have a time stamp and thread id.
:Parameters:
verbose : int
Verbosity configuration (0..5)
enable_loggers : string list
... |
def get_module_logger(moduleName, defaultToVerbose=False):
"""Create a module logger, that can be en/disabled by configuration.
@see: unit.init_logging
"""
# moduleName = moduleName.split(".")[-1]
if not moduleName.startswith(BASE_LOGGER_NAME + "."):
moduleName = BASE_LOGGER_NAME + "." + mo... |
def dynamic_import_class(name):
"""Import a class from a module string, e.g. ``my.module.ClassName``."""
import importlib
module_name, class_name = name.rsplit(".", 1)
try:
module = importlib.import_module(module_name)
except Exception as e:
_logger.exception("Dynamic import of {!r}... |
def dynamic_instantiate_middleware(name, args, expand=None):
"""Import a class and instantiate with custom args.
Example:
name = "my.module.Foo"
args_dict = {
"bar": 42,
"baz": "qux"
}
=>
from my.module import Foo
return Foo(bar=42, ba... |
def save_split(s, sep, maxsplit):
"""Split string, always returning n-tuple (filled with None if necessary)."""
tok = s.split(sep, maxsplit)
while len(tok) <= maxsplit:
tok.append(None)
return tok |
def pop_path(path):
"""Return '/a/b/c' -> ('a', '/b/c')."""
if path in ("", "/"):
return ("", "")
assert path.startswith("/")
first, _sep, rest = path.lstrip("/").partition("/")
return (first, "/" + rest) |
def pop_path2(path):
"""Return '/a/b/c' -> ('a', 'b', '/c')."""
if path in ("", "/"):
return ("", "", "")
first, rest = pop_path(path)
second, rest = pop_path(rest)
return (first, second, "/" + rest) |
def shift_path(script_name, path_info):
"""Return ('/a', '/b/c') -> ('b', '/a/b', 'c')."""
segment, rest = pop_path(path_info)
return (segment, join_uri(script_name.rstrip("/"), segment), rest.rstrip("/")) |
def split_namespace(clarkName):
"""Return (namespace, localname) tuple for a property name in Clark Notation.
Namespace defaults to ''.
Example:
'{DAV:}foo' -> ('DAV:', 'foo')
'bar' -> ('', 'bar')
"""
if clarkName.startswith("{") and "}" in clarkName:
ns, localname = clarkName.spl... |
def to_unicode_safe(s):
"""Convert a binary string to Unicode using UTF-8 (fallback to ISO-8859-1)."""
try:
u = compat.to_unicode(s, "utf8")
except ValueError:
_logger.error(
"to_unicode_safe({!r}) *** UTF-8 failed. Trying ISO-8859-1".format(s)
)
u = compat.to_uni... |
def safe_re_encode(s, encoding_to, errors="backslashreplace"):
"""Re-encode str or binary so that is compatible with a given encoding (replacing
unsupported chars).
We use ASCII as default, which gives us some output that contains \x99 and \u9999
for every character > 127, for easier debugging.
(e.... |
def string_repr(s):
"""Return a string as hex dump."""
if compat.is_bytes(s):
res = "{!r}: ".format(s)
for b in s:
if type(b) is str: # Py2
b = ord(b)
res += "%02x " % b
return res
return "{}".format(s) |
def byte_number_string(
number, thousandsSep=True, partition=False, base1024=True, appendBytes=True
):
"""Convert bytes into human-readable representation."""
magsuffix = ""
bytesuffix = ""
if partition:
magnitude = 0
if base1024:
while number >= 1024:
ma... |
def read_and_discard_input(environ):
"""Read 1 byte from wsgi.input, if this has not been done yet.
Returning a response without reading from a request body might confuse the
WebDAV client.
This may happen, if an exception like '401 Not authorized', or
'500 Internal error' was raised BEFORE anythin... |
def fail(value, context_info=None, src_exception=None, err_condition=None):
"""Wrapper to raise (and log) DAVError."""
if isinstance(value, Exception):
e = as_DAVError(value)
else:
e = DAVError(value, context_info, src_exception, err_condition)
_logger.error("Raising DAVError {}".format(... |
def join_uri(uri, *segments):
"""Append segments to URI.
Example: join_uri("/a/b", "c", "d")
"""
sub = "/".join(segments)
if not sub:
return uri
return uri.rstrip("/") + "/" + sub |
def is_child_uri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri.
This function accounts for the fact that '/a/b/c' and 'a/b/c/' are
children of '/a/b' (and also of '/a/b/').
Note that '/a/b/cd' is NOT a child of 'a/b/c'.
"""
return (
parentUri
and chil... |
def is_equal_or_child_uri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri or maps to the same resource.
Similar to <util.is_child_uri>_ , but this method also returns True, if parent
equals child. ('/a/b' is considered identical with '/a/b/').
"""
return (
parentU... |
def make_complete_url(environ, localUri=None):
"""URL reconstruction according to PEP 333.
@see https://www.python.org/dev/peps/pep-3333/#url-reconstruction
"""
url = environ["wsgi.url_scheme"] + "://"
if environ.get("HTTP_HOST"):
url += environ["HTTP_HOST"]
else:
url += environ... |
def parse_xml_body(environ, allow_empty=False):
"""Read request body XML into an etree.Element.
Return None, if no request body was sent.
Raise HTTP_BAD_REQUEST, if something else went wrong.
TODO: this is a very relaxed interpretation: should we raise HTTP_BAD_REQUEST
instead, if CONTENT_LENGTH i... |
def send_status_response(environ, start_response, e, add_headers=None, is_head=False):
"""Start a WSGI response for a DAVError or status code."""
status = get_http_status_string(e)
headers = []
if add_headers:
headers.extend(add_headers)
# if 'keep-alive' in environ.get('HTTP_CONNECTION',... |
def add_property_response(multistatusEL, href, propList):
"""Append <response> element to <multistatus> element.
<prop> node depends on the value type:
- str or unicode: add element with this content
- None: add an empty element
- etree.Element: add XML element as child
- DAVError: add ... |
def calc_base64(s):
"""Return base64 encoded binarystring."""
s = compat.to_bytes(s)
s = compat.base64_encodebytes(s).strip() # return bytestring
return compat.to_native(s) |
def get_etag(file_path):
"""Return a strong Entity Tag for a (file)path.
http://www.webdav.org/specs/rfc4918.html#etag
Returns the following as entity tags::
Non-file - md5(pathname)
Win32 - md5(pathname)-lastmodifiedtime-filesize
Others - inode-lastmodifiedtime-filesize
"""
... |
def obtain_content_ranges(rangetext, filesize):
"""
returns tuple (list, value)
list
content ranges as values to their parsed components in the tuple
(seek_position/abs position of first byte, abs position of last byte, num_of_bytes_to_read)
value
total length for Content-Length
""... |
def read_timeout_value_header(timeoutvalue):
"""Return -1 if infinite, else return numofsecs."""
timeoutsecs = 0
timeoutvaluelist = timeoutvalue.split(",")
for timeoutspec in timeoutvaluelist:
timeoutspec = timeoutspec.strip()
if timeoutspec.lower() == "infinite":
return -1
... |
def evaluate_http_conditionals(dav_res, last_modified, entitytag, environ):
"""Handle 'If-...:' headers (but not 'If:' header).
If-Match
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
Only perform the action if the client supplied entity matches the
same entity on... |
def parse_if_header_dict(environ):
"""Parse HTTP_IF header into a dictionary and lists, and cache the result.
@see http://www.webdav.org/specs/rfc4918.html#HEADER_If
"""
if "wsgidav.conditions.if" in environ:
return
if "HTTP_IF" not in environ:
environ["wsgidav.conditions.if"] = No... |
def guess_mime_type(url):
"""Use the mimetypes module to lookup the type for an extension.
This function also adds some extensions required for HTML5
"""
(mimetype, _mimeencoding) = mimetypes.guess_type(url)
if not mimetype:
ext = os.path.splitext(url)[1]
mimetype = _MIME_TYPES.get(... |
def add_members(self, new_members):
"""
Add objects to the group.
Parameters
----------
new_members : list
A list of cobrapy objects to add to the group.
"""
if isinstance(new_members, string_types) or \
hasattr(new_members, "id"):
... |
def remove_members(self, to_remove):
"""
Remove objects from the group.
Parameters
----------
to_remove : list
A list of cobra objects to remove from the group
"""
if isinstance(to_remove, string_types) or \
hasattr(to_remove, "id"):
... |
def geometric_fba(model, epsilon=1E-06, max_tries=200, processes=None):
"""
Perform geometric FBA to obtain a unique, centered flux distribution.
Geometric FBA [1]_ formulates the problem as a polyhedron and
then solves it by bounding the convex hull of the polyhedron.
The bounding forms a box arou... |
def _generate_index(self):
"""rebuild the _dict index"""
self._dict = {v.id: k for k, v in enumerate(self)} |
def get_by_any(self, iterable):
"""
Get a list of members using several different ways of indexing
Parameters
----------
iterable : list (if not, turned into single element list)
list where each element is either int (referring to an index in
in this Dict... |
def query(self, search_function, attribute=None):
"""Query the list
Parameters
----------
search_function : a string, regular expression or function
Used to find the matching elements in the list.
- a regular expression (possibly compiled), in which case the
... |
def _replace_on_id(self, new_object):
"""Replace an object by another with the same id."""
the_id = new_object.id
the_index = self._dict[the_id]
list.__setitem__(self, the_index, new_object) |
def append(self, object):
"""append object to end"""
the_id = object.id
self._check(the_id)
self._dict[the_id] = len(self)
list.append(self, object) |
def union(self, iterable):
"""adds elements with id's not already in the model"""
_dict = self._dict
append = self.append
for i in iterable:
if i.id not in _dict:
append(i) |
def extend(self, iterable):
"""extend list by appending elements from the iterable"""
# Sometimes during initialization from an older pickle, _dict
# will not have initialized yet, because the initialization class was
# left unspecified. This is an issue because unpickling calls
... |
def _extend_nocheck(self, iterable):
"""extends without checking for uniqueness
This function should only be used internally by DictList when it
can guarantee elements are already unique (as in when coming from
self or other DictList). It will be faster because it skips these
ch... |
def index(self, id, *args):
"""Determine the position in the list
id: A string or a :class:`~cobra.core.Object.Object`
"""
# because values are unique, start and stop are not relevant
if isinstance(id, string_types):
try:
return self._dict[id]
... |
def insert(self, index, object):
"""insert object before index"""
self._check(object.id)
list.insert(self, index, object)
# all subsequent entries now have been shifted up by 1
_dict = self._dict
for i, j in iteritems(_dict):
if j >= index:
_di... |
def pop(self, *args):
"""remove and return item at index (default last)."""
value = list.pop(self, *args)
index = self._dict.pop(value.id)
# If the pop occured from a location other than the end of the list,
# we will need to subtract 1 from every entry afterwards
if len(... |
def sort(self, cmp=None, key=None, reverse=False):
"""stable sort *IN PLACE*
cmp(x, y) -> -1, 0, 1
"""
if key is None:
def key(i):
return i.id
if PY3:
list.sort(self, key=key, reverse=reverse)
else:
list.sort(self, cmp... |
def elements(self):
""" Dictionary of elements as keys and their count in the metabolite
as integer. When set, the `formula` property is update accordingly """
tmp_formula = self.formula
if tmp_formula is None:
return {}
# necessary for some old pickles which use the ... |
def shadow_price(self):
"""
The shadow price in the most recent solution.
Shadow price is the dual value of the corresponding constraint in the
model.
Warnings
--------
* Accessing shadow prices through a `Solution` object is the safer,
preferred, and ... |
def to_yaml(model, sort=False, **kwargs):
"""
Return the model as a YAML document.
``kwargs`` are passed on to ``yaml.dump``.
Parameters
----------
model : cobra.Model
The cobra model to represent.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes ... |
def save_yaml_model(model, filename, sort=False, **kwargs):
"""
Write the cobra model to a file in YAML format.
``kwargs`` are passed on to ``yaml.dump``.
Parameters
----------
model : cobra.Model
The cobra model to represent.
filename : str or file-like
File path or descri... |
def load_yaml_model(filename):
"""
Load a cobra model from a file in YAML format.
Parameters
----------
filename : str or file-like
File path or descriptor that contains the YAML document describing the
cobra model.
Returns
-------
cobra.Model
The cobra model as... |
def pfba(model, fraction_of_optimum=1.0, objective=None, reactions=None):
"""Perform basic pFBA (parsimonious Enzyme Usage Flux Balance Analysis)
to minimize total flux.
pFBA [1] adds the minimization of all fluxes the the objective of the
model. This approach is motivated by the idea that high fluxes ... |
def add_pfba(model, objective=None, fraction_of_optimum=1.0):
"""Add pFBA objective
Add objective to minimize the summed flux of all reactions to the
current objective.
See Also
-------
pfba
Parameters
----------
model : cobra.Model
The model to add the objective to
ob... |
def metabolite_summary(met, solution=None, threshold=0.01, fva=False,
names=False, floatfmt='.3g'):
"""
Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
so... |
def model_summary(model, solution=None, threshold=0.01, fva=None, names=False,
floatfmt='.3g'):
"""
Print a summary of the input and output fluxes of the model.
Parameters
----------
solution: cobra.Solution, optional
A previously solved model solution to use for generatin... |
def _process_flux_dataframe(flux_dataframe, fva, threshold, floatfmt):
"""Some common methods for processing a database of flux information into
print-ready formats. Used in both model_summary and metabolite_summary. """
abs_flux = flux_dataframe['flux'].abs()
flux_threshold = threshold * abs_flux.max(... |
def linear_reaction_coefficients(model, reactions=None):
"""Coefficient for the reactions in a linear objective.
Parameters
----------
model : cobra model
the model object that defined the objective
reactions : list
an optional list for the reactions to get the coefficients for. All... |
def _valid_atoms(model, expression):
"""Check whether a sympy expression references the correct variables.
Parameters
----------
model : cobra.Model
The model in which to check for variables.
expression : sympy.Basic
A sympy expression.
Returns
-------
boolean
T... |
def set_objective(model, value, additive=False):
"""Set the model objective.
Parameters
----------
model : cobra model
The model to set the objective for
value : model.problem.Objective,
e.g. optlang.glpk_interface.Objective, sympy.Basic or dict
If the model objective is... |
def interface_to_str(interface):
"""Give a string representation for an optlang interface.
Parameters
----------
interface : string, ModuleType
Full name of the interface in optlang or cobra representation.
For instance 'optlang.glpk_interface' or 'optlang-glpk'.
Returns
------... |
def get_solver_name(mip=False, qp=False):
"""Select a solver for a given optimization problem.
Parameters
----------
mip : bool
Does the solver require mixed integer linear programming capabilities?
qp : bool
Does the solver require quadratic programming capabilities?
Returns
... |
def choose_solver(model, solver=None, qp=False):
"""Choose a solver given a solver name and model.
This will choose a solver compatible with the model and required
capabilities. Also respects model.solver where it can.
Parameters
----------
model : a cobra model
The model for which to ... |
def add_cons_vars_to_problem(model, what, **kwargs):
"""Add variables and constraints to a Model's solver object.
Useful for variables and constraints that can not be expressed with
reactions and lower/upper bounds. Will integrate with the Model's context
manager in order to revert changes upon leaving... |
def remove_cons_vars_from_problem(model, what):
"""Remove variables and constraints from a Model's solver object.
Useful to temporarily remove variables and constraints from a Models's
solver object.
Parameters
----------
model : a cobra model
The model from which to remove the variable... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.