text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Decrease the value at key ``name`` by ``amount``. If no key exists, the value <END_TASK> <USER_TASK:> Description: def decr(self, name, amount=1): """ Decrease the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` . Like **Redis.DECR** :param string name: the key name :param int amount: decrements :return: the integer value at key ``name`` :rtype: int >>> ssdb.decr('set_count', 3) 7 >>> ssdb.decr('set_count', 1) 6 >>> ssdb.decr('temp_count', 42) -42 """
amount = get_positive_integer('amount', amount) return self.execute_command('decr', name, amount)
<SYSTEM_TASK:> Returns a boolean indicating the value of ``offset`` in ``name`` <END_TASK> <USER_TASK:> Description: def getbit(self, name, offset): """ Returns a boolean indicating the value of ``offset`` in ``name`` Like **Redis.GETBIT** :param string name: the key name :param int offset: the bit position :param bool val: the bit value :return: the bit at the ``offset`` , ``False`` if key doesn't exist or offset exceeds the string length. :rtype: bool >>> ssdb.set('bit_test', 1) True >>> ssdb.getbit('bit_test', 0) True >>> ssdb.getbit('bit_test', 1) False """
offset = get_positive_integer('offset', offset) return self.execute_command('getbit', name, offset)
<SYSTEM_TASK:> Returns the count of set bits in the value of ``key``. Optional <END_TASK> <USER_TASK:> Description: def countbit(self, name, start=None, size=None): """ Returns the count of set bits in the value of ``key``. Optional ``start`` and ``size`` paramaters indicate which bytes to consider. Similiar with **Redis.BITCOUNT** :param string name: the key name :param int start: Optional, if start is negative, count from start'th character from the end of string. :param int size: Optional, if size is negative, then that many characters will be omitted from the end of string. :return: the count of the bit 1 :rtype: int >>> ssdb.set('bit_test', 1) True >>> ssdb.countbit('bit_test') 3 >>> ssdb.set('bit_test','1234567890') True >>> ssdb.countbit('bit_test', 0, 1) 3 >>> ssdb.countbit('bit_test', 3, -3) 16 """
if start is not None and size is not None: start = get_integer('start', start) size = get_integer('size', size) return self.execute_command('countbit', name, start, size) elif start is not None: start = get_integer('start', start) return self.execute_command('countbit', name, start) return self.execute_command('countbit', name)
<SYSTEM_TASK:> Return a substring of the string at key ``name``. ``start`` and ``size`` <END_TASK> <USER_TASK:> Description: def substr(self, name, start=None, size=None): """ Return a substring of the string at key ``name``. ``start`` and ``size`` are 0-based integers specifying the portion of the string to return. Like **Redis.SUBSTR** :param string name: the key name :param int start: Optional, the offset of first byte returned. If start is negative, the returned string will start at the start'th character from the end of string. :param int size: Optional, number of bytes returned. If size is negative, then that many characters will be omitted from the end of string. :return: The extracted part of the string. :rtype: string >>> ssdb.set('str_test', 'abc12345678') True >>> ssdb.substr('str_test', 2, 4) 'c123' >>> ssdb.substr('str_test', -2, 2) '78' >>> ssdb.substr('str_test', 1, -1) 'bc1234567' """
if start is not None and size is not None: start = get_integer('start', start) size = get_integer('size', size) return self.execute_command('substr', name, start, size) elif start is not None: start = get_integer('start', start) return self.execute_command('substr', name, start) return self.execute_command('substr', name)
<SYSTEM_TASK:> Return a list of the top ``limit`` keys between ``name_start`` and <END_TASK> <USER_TASK:> Description: def keys(self, name_start, name_end, limit=10): """ Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` Similiar with **Redis.KEYS** .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list >>> ssdb.keys('set_x1', 'set_x3', 10) ['set_x2', 'set_x3'] >>> ssdb.keys('set_x ', 'set_xx', 3) ['set_x1', 'set_x2', 'set_x3'] >>> ssdb.keys('set_x ', '', 3) ['set_x1', 'set_x2', 'set_x3', 'set_x4'] >>> ssdb.keys('set_zzzzz ', '', ) [] """
limit = get_positive_integer('limit', limit) return self.execute_command('keys', name_start, name_end, limit)
<SYSTEM_TASK:> Increase the value of ``key`` in hash ``name`` by ``amount``. If no key <END_TASK> <USER_TASK:> Description: def hincr(self, name, key, amount=1): """ Increase the value of ``key`` in hash ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` Like **Redis.HINCR** :param string name: the hash name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in hash ``name`` :rtype: int >>> ssdb.hincr('hash_2', 'key1', 7) 49 >>> ssdb.hincr('hash_2', 'key2', 3) 6 >>> ssdb.hincr('hash_2', 'key_not_exists', 101) 101 >>> ssdb.hincr('hash_not_exists', 'key_not_exists', 8848) 8848 """
amount = get_integer('amount', amount) return self.execute_command('hincr', name, key, amount)
<SYSTEM_TASK:> Decrease the value of ``key`` in hash ``name`` by ``amount``. If no key <END_TASK> <USER_TASK:> Description: def hdecr(self, name, key, amount=1): """ Decrease the value of ``key`` in hash ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` :param string name: the hash name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in hash ``name`` :rtype: int >>> ssdb.hdecr('hash_2', 'key1', 7) 35 >>> ssdb.hdecr('hash_2', 'key2', 3) 0 >>> ssdb.hdecr('hash_2', 'key_not_exists', 101) -101 >>> ssdb.hdecr('hash_not_exists', 'key_not_exists', 8848) -8848 """
amount = get_positive_integer('amount', amount) return self.execute_command('hdecr', name, key, amount)
<SYSTEM_TASK:> Return a list of the top ``limit`` keys between ``key_start`` and <END_TASK> <USER_TASK:> Description: def hkeys(self, name, key_start, key_end, limit=10): """ Return a list of the top ``limit`` keys between ``key_start`` and ``key_end`` in hash ``name`` Similiar with **Redis.HKEYS** .. note:: The range is (``key_start``, ``key_end``]. The ``key_start`` isn't in the range, but ``key_end`` is. :param string name: the hash name :param string key_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string key_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list >>> ssdb.hkeys('hash_1', 'a', 'g', 10) ['b', 'c', 'd', 'e', 'f', 'g'] >>> ssdb.hkeys('hash_2', 'key ', 'key4', 3) ['key1', 'key2', 'key3'] >>> ssdb.hkeys('hash_1', 'f', '', 10) ['g'] >>> ssdb.hkeys('hash_2', 'keys', '', 10) [] """
limit = get_positive_integer('limit', limit) return self.execute_command('hkeys', name, key_start, key_end, limit)
<SYSTEM_TASK:> Return a list of the top ``limit`` hash's name between ``name_start`` and <END_TASK> <USER_TASK:> Description: def hlist(self, name_start, name_end, limit=10): """ Return a list of the top ``limit`` hash's name between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of hash names to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of hash names to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of hash's name :rtype: list >>> ssdb.hlist('hash_ ', 'hash_z', 10) ['hash_1', 'hash_2'] >>> ssdb.hlist('hash_ ', '', 3) ['hash_1', 'hash_2'] >>> ssdb.hlist('', 'aaa_not_exist', 10) [] """
limit = get_positive_integer('limit', limit) return self.execute_command('hlist', name_start, name_end, limit)
<SYSTEM_TASK:> Return a list of the top ``limit`` hash's name between ``name_start`` and <END_TASK> <USER_TASK:> Description: def hrlist(self, name_start, name_end, limit=10): """ Return a list of the top ``limit`` hash's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of hash names to be returned, empty string ``''`` means +inf :param string name_end: The upper bound(included) of hash names to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a list of hash's name :rtype: list >>> ssdb.hrlist('hash_ ', 'hash_z', 10) ['hash_2', 'hash_1'] >>> ssdb.hrlist('hash_ ', '', 3) ['hash_2', 'hash_1'] >>> ssdb.hrlist('', 'aaa_not_exist', 10) [] """
limit = get_positive_integer('limit', limit) return self.execute_command('hrlist', name_start, name_end, limit)
<SYSTEM_TASK:> Set the score of ``key`` from the zset ``name`` to ``score`` <END_TASK> <USER_TASK:> Description: def zset(self, name, key, score=1): """ Set the score of ``key`` from the zset ``name`` to ``score`` Like **Redis.ZADD** :param string name: the zset name :param string key: the key name :param int score: the score for ranking :return: ``True`` if ``zset`` created a new score, otherwise ``False`` :rtype: bool >>> ssdb.zset("zset_1", 'z', 1024) True >>> ssdb.zset("zset_1", 'a', 1024) False >>> ssdb.zset("zset_2", 'key_10', -4) >>> >>> ssdb.zget("zset_2", 'key1') 42 """
score = get_integer('score', score) return self.execute_command('zset', name, key, score)
<SYSTEM_TASK:> Increase the score of ``key`` in zset ``name`` by ``amount``. If no key <END_TASK> <USER_TASK:> Description: def zincr(self, name, key, amount=1): """ Increase the score of ``key`` in zset ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` Like **Redis.ZINCR** :param string name: the zset name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in zset ``name`` :rtype: int >>> ssdb.zincr('zset_2', 'key1', 7) 49 >>> ssdb.zincr('zset_2', 'key2', 3) 317 >>> ssdb.zincr('zset_2', 'key_not_exists', 101) 101 >>> ssdb.zincr('zset_not_exists', 'key_not_exists', 8848) 8848 """
amount = get_integer('amount', amount) return self.execute_command('zincr', name, key, amount)
<SYSTEM_TASK:> Decrease the value of ``key`` in zset ``name`` by ``amount``. If no key <END_TASK> <USER_TASK:> Description: def zdecr(self, name, key, amount=1): """ Decrease the value of ``key`` in zset ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` :param string name: the zset name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in zset ``name`` :rtype: int >>> ssdb.zdecr('zset_2', 'key1', 7) 36 >>> ssdb.zdecr('zset_2', 'key2', 3) 311 >>> ssdb.zdecr('zset_2', 'key_not_exists', 101) -101 >>> ssdb.zdecr('zset_not_exists', 'key_not_exists', 8848) -8848 """
amount = get_positive_integer('amount', amount) return self.execute_command('zdecr', name, key, amount)
<SYSTEM_TASK:> Return a list of the top ``limit`` zset's name between ``name_start`` and <END_TASK> <USER_TASK:> Description: def zlist(self, name_start, name_end, limit=10): """ Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of zset names to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of zset names to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of zset's name :rtype: list >>> ssdb.zlist('zset_ ', 'zset_z', 10) ['zset_1', 'zset_2'] >>> ssdb.zlist('zset_ ', '', 3) ['zset_1', 'zset_2'] >>> ssdb.zlist('', 'aaa_not_exist', 10) [] """
limit = get_positive_integer('limit', limit) return self.execute_command('zlist', name_start, name_end, limit)
<SYSTEM_TASK:> Return a list of the top ``limit`` zset's name between ``name_start`` and <END_TASK> <USER_TASK:> Description: def zrlist(self, name_start, name_end, limit=10): """ Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of zset names to be returned, empty string ``''`` means +inf :param string name_end: The upper bound(included) of zset names to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a list of zset's name :rtype: list >>> ssdb.zlist('zset_ ', 'zset_z', 10) ['zset_2', 'zset_1'] >>> ssdb.zlist('zset_ ', '', 3) ['zset_2', 'zset_1'] >>> ssdb.zlist('', 'aaa_not_exist', 10) [] """
limit = get_positive_integer('limit', limit) return self.execute_command('zrlist', name_start, name_end, limit)
<SYSTEM_TASK:> Return a list of the top ``limit`` keys after ``key_start`` from zset <END_TASK> <USER_TASK:> Description: def zkeys(self, name, key_start, score_start, score_end, limit=10): """ Return a list of the top ``limit`` keys after ``key_start`` from zset ``name`` with scores between ``score_start`` and ``score_end`` .. note:: The range is (``key_start``+``score_start``, ``key_end``]. That means (key.score == score_start && key > key_start || key.score > score_start) :param string name: the zset name :param string key_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string key_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list >>> ssdb.zkeys('zset_1', '', 0, 200, 10) ['g', 'd', 'b', 'a', 'e', 'c'] >>> ssdb.zkeys('zset_1', '', 0, 200, 3) ['g', 'd', 'b'] >>> ssdb.zkeys('zset_1', 'b', 20, 200, 3) ['a', 'e', 'c'] >>> ssdb.zkeys('zset_1', 'c', 100, 200, 3) [] """
score_start = get_integer_or_emptystring('score_start', score_start) score_end = get_integer_or_emptystring('score_end', score_end) limit = get_positive_integer('limit', limit) return self.execute_command('zkeys', name, key_start, score_start, score_end, limit)
<SYSTEM_TASK:> Returns the number of elements in the sorted set at key ``name`` with <END_TASK> <USER_TASK:> Description: def zcount(self, name, score_start, score_end): """ Returns the number of elements in the sorted set at key ``name`` with a score between ``score_start`` and ``score_end``. Like **Redis.ZCOUNT** .. note:: The range is [``score_start``, ``score_end``] :param string name: the zset name :param int score_start: The minimum score related to keys(included), empty string ``''`` means -inf :param int score_end: The maximum score(included) related to keys, empty string ``''`` means +inf :return: the number of keys in specified range :rtype: int >>> ssdb.zount('zset_1', 20, 70) 3 >>> ssdb.zcount('zset_1', 0, 100) 6 >>> ssdb.zcount('zset_1', 2, 3) 0 """
score_start = get_integer_or_emptystring('score_start', score_start) score_end = get_integer_or_emptystring('score_end', score_end) return self.execute_command('zcount', name, score_start, score_end)
<SYSTEM_TASK:> Get the element of ``index`` within the queue ``name`` <END_TASK> <USER_TASK:> Description: def qget(self, name, index): """ Get the element of ``index`` within the queue ``name`` :param string name: the queue name :param int index: the specified index, can < 0 :return: the value at ``index`` within queue ``name`` , or ``None`` if the element doesn't exist :rtype: string """
index = get_integer('index', index) return self.execute_command('qget', name, index)
<SYSTEM_TASK:> Set the list element at ``index`` to ``value``. <END_TASK> <USER_TASK:> Description: def qset(self, name, index, value): """ Set the list element at ``index`` to ``value``. :param string name: the queue name :param int index: the specified index, can < 0 :param string value: the element value :return: Unknown :rtype: True """
index = get_integer('index', index) return self.execute_command('qset', name, index, value)
<SYSTEM_TASK:> Remove and return the first ``size`` item of the list ``name`` <END_TASK> <USER_TASK:> Description: def qpop_front(self, name, size=1): """ Remove and return the first ``size`` item of the list ``name`` Like **Redis.LPOP** :param string name: the queue name :param int size: the length of result :return: the list of pop elements :rtype: list """
size = get_positive_integer("size", size) return self.execute_command('qpop_front', name, size)
<SYSTEM_TASK:> Remove and return the last ``size`` item of the list ``name`` <END_TASK> <USER_TASK:> Description: def qpop_back(self, name, size=1): """ Remove and return the last ``size`` item of the list ``name`` Like **Redis.RPOP** :param string name: the queue name :param int size: the length of result :return: the list of pop elements :rtype: list """
size = get_positive_integer("size", size) return self.execute_command('qpop_back', name, size)
<SYSTEM_TASK:> Return a list of the top ``limit`` keys between ``name_start`` and <END_TASK> <USER_TASK:> Description: def qlist(self, name_start, name_end, limit): """ Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list >>> ssdb.qlist('queue_1', 'queue_2', 10) ['queue_2'] >>> ssdb.qlist('queue_', 'queue_2', 10) ['queue_1', 'queue_2'] >>> ssdb.qlist('z', '', 10) [] """
limit = get_positive_integer("limit", limit) return self.execute_command('qlist', name_start, name_end, limit)
<SYSTEM_TASK:> Return a list of the top ``limit`` keys between ``name_start`` and <END_TASK> <USER_TASK:> Description: def qrlist(self, name_start, name_end, limit): """ Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of keys to be returned, empty string ``''`` means +inf :param string name_end: The upper bound(included) of keys to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list >>> ssdb.qrlist('queue_2', 'queue_1', 10) ['queue_1'] >>> ssdb.qrlist('queue_z', 'queue_', 10) ['queue_2', 'queue_1'] >>> ssdb.qrlist('z', '', 10) ['queue_2', 'queue_1'] """
limit = get_positive_integer("limit", limit) return self.execute_command('qrlist', name_start, name_end, limit)
<SYSTEM_TASK:> Return a ``limit`` slice of the list ``name`` at position ``offset`` <END_TASK> <USER_TASK:> Description: def qrange(self, name, offset, limit): """ Return a ``limit`` slice of the list ``name`` at position ``offset`` ``offset`` can be negative numbers just like Python slicing notation Similiar with **Redis.LRANGE** :param string name: the queue name :param int offset: the returned list will start at this offset :param int limit: number of elements will be returned :return: a list of elements :rtype: list """
offset = get_integer('offset', offset) limit = get_positive_integer('limit', limit) return self.execute_command('qrange', name, offset, limit)
<SYSTEM_TASK:> Set the value of key ``name`` to ``value`` that expires in ``ttl`` <END_TASK> <USER_TASK:> Description: def setx(self, name, value, ttl): """ Set the value of key ``name`` to ``value`` that expires in ``ttl`` seconds. ``ttl`` can be represented by an integer or a Python timedelta object. Like **Redis.SETEX** :param string name: the key name :param string value: a string or an object can be converted to string :param int ttl: positive int seconds or timedelta object :return: ``True`` on success, ``False`` if not :rtype: bool >>> import time >>> ssdb.set("test_ttl", 'ttl', 4) True >>> ssdb.get("test_ttl") 'ttl' >>> time.sleep(4) >>> ssdb.get("test_ttl") >>> """
if isinstance(ttl, datetime.timedelta): ttl = ttl.seconds + ttl.days * 24 * 3600 ttl = get_positive_integer('ttl', ttl) return self.execute_command('setx', name, value, ttl)
<SYSTEM_TASK:> Extracts the IPv6 address for a particular interface from `ifconfig`. <END_TASK> <USER_TASK:> Description: def get_ip6_address(interface_name, expand=False): """ Extracts the IPv6 address for a particular interface from `ifconfig`. :param interface_name: Name of the network interface (e.g. ``eth0``). :type interface_name: unicode :param expand: If set to ``True``, an abbreviated address is expanded to the full address. :type expand: bool :return: IPv6 address; ``None`` if the interface is present but no address could be extracted. :rtype: unicode """
address = _get_address(interface_name, IP6_PATTERN) if address and expand: return ':'.join(_expand_groups(address)) return address
<SYSTEM_TASK:> Determines the list of roles, that the current host is assigned to. If ``env.roledefs`` is not set, an empty list <END_TASK> <USER_TASK:> Description: def get_current_roles(): """ Determines the list of roles, that the current host is assigned to. If ``env.roledefs`` is not set, an empty list is returned. :return: List of roles of the current host. :rtype: list """
current_host = env.host_string roledefs = env.get('roledefs') if roledefs: return [role for role, hosts in six.iteritems(roledefs) if current_host in hosts] return []
<SYSTEM_TASK:> Add all reactions from database that occur in given compartments. <END_TASK> <USER_TASK:> Description: def add_all_database_reactions(model, compartments): """Add all reactions from database that occur in given compartments. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`. """
added = set() for rxnid in model.database.reactions: reaction = model.database.get_reaction(rxnid) if all(compound.compartment in compartments for compound, _ in reaction.compounds): if not model.has_reaction(rxnid): added.add(rxnid) model.add_reaction(rxnid) return added
<SYSTEM_TASK:> Add all exchange reactions to database and to model. <END_TASK> <USER_TASK:> Description: def add_all_exchange_reactions(model, compartment, allow_duplicates=False): """Add all exchange reactions to database and to model. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`. """
all_reactions = {} if not allow_duplicates: # TODO: Avoid adding reactions that already exist in the database. # This should be integrated in the database. for rxnid in model.database.reactions: rx = model.database.get_reaction(rxnid) all_reactions[rx] = rxnid added = set() added_compounds = set() initial_compounds = set(model.compounds) reactions = set(model.database.reactions) for model_compound in initial_compounds: compound = model_compound.in_compartment(compartment) if compound in added_compounds: continue rxnid_ex = create_exchange_id(reactions, compound) reaction_ex = Reaction(Direction.Both, {compound: -1}) if reaction_ex not in all_reactions: model.database.set_reaction(rxnid_ex, reaction_ex) reactions.add(rxnid_ex) else: rxnid_ex = all_reactions[reaction_ex] if not model.has_reaction(rxnid_ex): added.add(rxnid_ex) model.add_reaction(rxnid_ex) added_compounds.add(compound) return added
<SYSTEM_TASK:> Add all transport reactions to database and to model. <END_TASK> <USER_TASK:> Description: def add_all_transport_reactions(model, boundaries, allow_duplicates=False): """Add all transport reactions to database and to model. Add transport reactions for all boundaries. Boundaries are defined by pairs (2-tuples) of compartment IDs. Transport reactions are added for all compounds in the model, not just for compounds in the two boundary compartments. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`. boundaries: Set of compartment boundary pairs. Returns: Set of IDs of reactions that were added. """
all_reactions = {} if not allow_duplicates: # TODO: Avoid adding reactions that already exist in the database. # This should be integrated in the database. for rxnid in model.database.reactions: rx = model.database.get_reaction(rxnid) all_reactions[rx] = rxnid boundary_pairs = set() for source, dest in boundaries: if source != dest: boundary_pairs.add(tuple(sorted((source, dest)))) added = set() added_pairs = set() initial_compounds = set(model.compounds) reactions = set(model.database.reactions) for compound in initial_compounds: for c1, c2 in boundary_pairs: compound1 = compound.in_compartment(c1) compound2 = compound.in_compartment(c2) pair = compound1, compound2 if pair in added_pairs: continue rxnid_tp = create_transport_id(reactions, compound1, compound2) reaction_tp = Reaction(Direction.Both, { compound1: -1, compound2: 1 }) if reaction_tp not in all_reactions: model.database.set_reaction(rxnid_tp, reaction_tp) reactions.add(rxnid_tp) else: rxnid_tp = all_reactions[reaction_tp] if not model.has_reaction(rxnid_tp): added.add(rxnid_tp) model.add_reaction(rxnid_tp) added_pairs.add(pair) return added
<SYSTEM_TASK:> Create an extended model for gap-filling. <END_TASK> <USER_TASK:> Description: def create_extended_model(model, db_penalty=None, ex_penalty=None, tp_penalty=None, penalties=None): """Create an extended model for gap-filling. Create a :class:`psamm.metabolicmodel.MetabolicModel` with all reactions added (the reaction database in the model is taken to be the universal database) and also with artificial exchange and transport reactions added. Return the extended :class:`psamm.metabolicmodel.MetabolicModel` and a weight dictionary for added reactions in that model. Args: model: :class:`psamm.datasource.native.NativeModel`. db_penalty: penalty score for database reactions, default is `None`. ex_penalty: penalty score for exchange reactions, default is `None`. tb_penalty: penalty score for transport reactions, default is `None`. penalties: a dictionary of penalty scores for database reactions. """
# Create metabolic model model_extended = model.create_metabolic_model() extra_compartment = model.extracellular_compartment compartment_ids = set(c.id for c in model.compartments) # Add database reactions to extended model if len(compartment_ids) > 0: logger.info( 'Using all database reactions in compartments: {}...'.format( ', '.join('{}'.format(c) for c in compartment_ids))) db_added = add_all_database_reactions(model_extended, compartment_ids) else: logger.warning( 'No compartments specified in the model; database reactions will' ' not be used! Add compartment specification to model to include' ' database reactions for those compartments.') db_added = set() # Add exchange reactions to extended model logger.info( 'Using artificial exchange reactions for compartment: {}...'.format( extra_compartment)) ex_added = add_all_exchange_reactions( model_extended, extra_compartment, allow_duplicates=True) # Add transport reactions to extended model boundaries = model.compartment_boundaries if len(boundaries) > 0: logger.info( 'Using artificial transport reactions for the compartment' ' boundaries: {}...'.format( '; '.join('{}<->{}'.format(c1, c2) for c1, c2 in boundaries))) tp_added = add_all_transport_reactions( model_extended, boundaries, allow_duplicates=True) else: logger.warning( 'No compartment boundaries specified in the model;' ' artificial transport reactions will not be used!') tp_added = set() # Add penalty weights on reactions weights = {} if db_penalty is not None: weights.update((rxnid, db_penalty) for rxnid in db_added) if tp_penalty is not None: weights.update((rxnid, tp_penalty) for rxnid in tp_added) if ex_penalty is not None: weights.update((rxnid, ex_penalty) for rxnid in ex_added) if penalties is not None: for rxnid, penalty in iteritems(penalties): weights[rxnid] = penalty return model_extended, weights
<SYSTEM_TASK:> Run formula balance command <END_TASK> <USER_TASK:> Description: def run(self): """Run formula balance command"""
# Create a set of excluded reactions exclude = set(self._args.exclude) count = 0 unbalanced = 0 unchecked = 0 for reaction, result in formula_balance(self._model): count += 1 if reaction.id in exclude or reaction.equation is None: continue if result is None: unchecked += 1 continue left_form, right_form = result if right_form != left_form: unbalanced += 1 right_missing, left_missing = Formula.balance( right_form, left_form) print('{}\t{}\t{}\t{}\t{}'.format( reaction.id, left_form, right_form, left_missing, right_missing)) logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count)) logger.info('Unchecked reactions due to missing formula: {}/{}'.format( unchecked, count)) logger.info('Reactions excluded from check: {}/{}'.format( len(exclude), count))
<SYSTEM_TASK:> Whether reaction in database is shadowed by another database <END_TASK> <USER_TASK:> Description: def _is_shadowed(self, reaction_id, database): """Whether reaction in database is shadowed by another database"""
for other_database in self._databases: if other_database == database: break if other_database.has_reaction(reaction_id): return True return False
<SYSTEM_TASK:> Prints the log as usual for fabric output, enhanced with the prefix "docker". <END_TASK> <USER_TASK:> Description: def push_log(self, info, level=None, *args, **kwargs): """ Prints the log as usual for fabric output, enhanced with the prefix "docker". :param info: Log output. :type info: unicode :param level: Logging level. Has no effect here. :type level: int """
if args: msg = info % args else: msg = info try: puts('docker: {0}'.format(msg)) except UnicodeDecodeError: puts('docker: -- non-printable output --')
<SYSTEM_TASK:> Prints progress information. <END_TASK> <USER_TASK:> Description: def push_progress(self, status, object_id, progress): """ Prints progress information. :param status: Status text. :type status: unicode :param object_id: Object that the progress is reported on. :type object_id: unicode :param progress: Progress bar. :type progress: unicode """
fastprint(progress_fmt(status, object_id, progress), end='\n')
<SYSTEM_TASK:> Closes the connection and any tunnels created for it. <END_TASK> <USER_TASK:> Description: def close(self): """ Closes the connection and any tunnels created for it. """
try: super(DockerFabricClient, self).close() finally: if self._tunnel is not None: self._tunnel.close()
<SYSTEM_TASK:> Decorator for creating ranged property with fixed bounds. <END_TASK> <USER_TASK:> Description: def ranged_property(min=None, max=None): """Decorator for creating ranged property with fixed bounds."""
min_value = -_INF if min is None else min max_value = _INF if max is None else max return lambda fget: RangedProperty( fget, fmin=lambda obj: min_value, fmax=lambda obj: max_value)
<SYSTEM_TASK:> Define variables within the namespace. <END_TASK> <USER_TASK:> Description: def define(self, names, **kwargs): """Define variables within the namespace. This is similar to :meth:`.Problem.define` except that names must be given as an iterable. This method accepts the same keyword arguments as :meth:`.Problem.define`. """
define_kwargs = dict(self._define_kwargs) define_kwargs.update(kwargs) self._problem.define( *((self, name) for name in names), **define_kwargs)
<SYSTEM_TASK:> Return a variable set of the given names in the namespace. <END_TASK> <USER_TASK:> Description: def set(self, names): """Return a variable set of the given names in the namespace. >>> v = prob.namespace(name='v') >>> v.define([1, 2, 5], lower=0, upper=10) >>> prob.add_linear_constraints(v.set([1, 2]) >= 4) """
return self._problem.set((self, name) for name in names)
<SYSTEM_TASK:> Return the sum of each name multiplied by a coefficient. <END_TASK> <USER_TASK:> Description: def expr(self, items): """Return the sum of each name multiplied by a coefficient. >>> v = prob.namespace(name='v') >>> v.define(['a', 'b', 'c'], lower=0, upper=10) >>> prob.set_objective(v.expr([('a', 2), ('b', 1)])) """
return Expression({(self, name): value for name, value in items})
<SYSTEM_TASK:> Get value of variable or expression in result <END_TASK> <USER_TASK:> Description: def get_value(self, expression): """Get value of variable or expression in result Expression can be an object defined as a name in the problem, in which case the corresponding value is simply returned. If expression is an actual :class:`.Expression` object, it will be evaluated using the values from the result. """
if isinstance(expression, Expression): return self._evaluate_expression(expression) elif not self._has_variable(expression): raise ValueError('Unknown expression: {}'.format(expression)) return self._get_value(expression)
<SYSTEM_TASK:> Open interactive python console <END_TASK> <USER_TASK:> Description: def open_python(self, message, namespace): """Open interactive python console"""
# Importing readline will in some cases print weird escape # characters to stdout. To avoid this we only import readline # and related packages at this point when we are certain # they are needed. from code import InteractiveConsole import readline import rlcompleter readline.set_completer(rlcompleter.Completer(namespace).complete) readline.parse_and_bind('tab: complete') console = InteractiveConsole(namespace) console.interact(message)
<SYSTEM_TASK:> Calculate the overall charge for the specified reaction. <END_TASK> <USER_TASK:> Description: def reaction_charge(reaction, compound_charge): """Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values. """
charge_sum = 0.0 for compound, value in reaction.compounds: charge = compound_charge.get(compound.name, float('nan')) charge_sum += charge * float(value) return charge_sum
<SYSTEM_TASK:> Calculate the overall charge for all reactions in the model. <END_TASK> <USER_TASK:> Description: def charge_balance(model): """Calculate the overall charge for all reactions in the model. Yield (reaction, charge) pairs. Args: model: :class:`psamm.datasource.native.NativeModel`. """
compound_charge = {} for compound in model.compounds: if compound.charge is not None: compound_charge[compound.id] = compound.charge for reaction in model.reactions: charge = reaction_charge(reaction.equation, compound_charge) yield reaction, charge
<SYSTEM_TASK:> Calculate formula compositions for both sides of the specified reaction. <END_TASK> <USER_TASK:> Description: def reaction_formula(reaction, compound_formula): """Calculate formula compositions for both sides of the specified reaction. If the compounds in the reaction all have formula, then calculate and return the chemical compositions for both sides, otherwise return `None`. Args: reaction: :class:`psamm.reaction.Reaction`. compound_formula: a map from compound id to formula. """
def multiply_formula(compound_list): for compound, count in compound_list: yield count * compound_formula[compound.name] for compound, _ in reaction.compounds: if compound.name not in compound_formula: return None else: left_form = reduce( operator.or_, multiply_formula(reaction.left), Formula()) right_form = reduce( operator.or_, multiply_formula(reaction.right), Formula()) return left_form, right_form
<SYSTEM_TASK:> Calculate formula compositions for each reaction. <END_TASK> <USER_TASK:> Description: def formula_balance(model): """Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`. """
# Mapping from compound id to formula compound_formula = {} for compound in model.compounds: if compound.formula is not None: try: f = Formula.parse(compound.formula).flattened() compound_formula[compound.id] = f except ParseError as e: msg = 'Error parsing formula for compound {}:\n{}\n{}'.format( compound.id, e, compound.formula) if e.indicator is not None: msg += '\n{}'.format(e.indicator) logger.warning(msg) for reaction in model.reactions: yield reaction, reaction_formula(reaction.equation, compound_formula)
<SYSTEM_TASK:> Run flux consistency check command <END_TASK> <USER_TASK:> Description: def run(self): """Run flux consistency check command"""
# Load compound information def compound_name(id): if id not in self._model.compounds: return id return self._model.compounds[id].properties.get('name', id) epsilon = self._args.epsilon if self._args.unrestricted: # Allow all exchange reactions with no flux limits for reaction in self._mm.reactions: if self._mm.is_exchange(reaction): del self._mm.limits[reaction].bounds loop_removal = self._get_loop_removal_option() enable_tfba = loop_removal == 'tfba' enable_fastcore = self._args.fastcore if enable_tfba and enable_fastcore: self.argument_error( 'Using Fastcore with thermodynamic constraints' ' is not supported!') start_time = time.time() if enable_fastcore: solver = self._get_solver() try: inconsistent = set(fastcore.fastcc( self._mm, epsilon, solver=solver)) except fluxanalysis.FluxBalanceError as e: self.report_flux_balance_error(e) else: if enable_tfba: solver = self._get_solver(integer=True) else: solver = self._get_solver() if self._args.reduce_lp: logger.info('Running with reduced number of LP problems.') try: inconsistent = set( fluxanalysis.consistency_check( self._mm, self._mm.reactions, epsilon, tfba=enable_tfba, solver=solver)) except fluxanalysis.FluxBalanceError as e: self.report_flux_balance_error(e) else: logger.info('Using flux bounds to determine consistency.') try: inconsistent = set(self._run_fva_fluxcheck( self._mm, solver, enable_tfba, epsilon)) except FluxCheckFVATaskError: self.report_flux_balance_error() logger.info('Solving took {:.2f} seconds'.format( time.time() - start_time)) # Count the number of reactions that are fixed at zero. While these # reactions are still inconsistent, they are inconsistent because they # have been explicitly disabled. disabled_exchange = 0 disabled_internal = 0 count_exchange = 0 total_exchange = 0 count_internal = 0 total_internal = 0 # Print result for reaction in sorted(self._mm.reactions): disabled = self._mm.limits[reaction].bounds == (0, 0) if self._mm.is_exchange(reaction): total_exchange += 1 count_exchange += int(reaction in inconsistent) disabled_exchange += int(disabled) else: total_internal += 1 count_internal += int(reaction in inconsistent) disabled_internal += int(disabled) if reaction in inconsistent: rx = self._mm.get_reaction(reaction) rxt = rx.translated_compounds(compound_name) print('{}\t{}'.format(reaction, rxt)) logger.info('Model has {}/{} inconsistent internal reactions' ' ({} disabled by user)'.format( count_internal, total_internal, disabled_internal)) logger.info('Model has {}/{} inconsistent exchange reactions' ' ({} disabled by user)'.format( count_exchange, total_exchange, disabled_exchange))
<SYSTEM_TASK:> Run charge balance command <END_TASK> <USER_TASK:> Description: def run(self): """Run charge balance command"""
# Load compound information def compound_name(id): if id not in self._model.compounds: return id return self._model.compounds[id].properties.get('name', id) # Create a set of excluded reactions exclude = set(self._args.exclude) count = 0 unbalanced = 0 unchecked = 0 for reaction, charge in charge_balance(self._model): count += 1 if reaction.id in exclude or reaction.equation is None: continue if math.isnan(charge): logger.debug('Not checking reaction {};' ' missing charge'.format(reaction.id)) unchecked += 1 elif abs(charge) > self._args.epsilon: unbalanced += 1 rxt = reaction.equation.translated_compounds(compound_name) print('{}\t{}\t{}'.format(reaction.id, charge, rxt)) logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count)) logger.info('Unchecked reactions due to missing charge: {}/{}'.format( unchecked, count)) logger.info('Reactions excluded from check: {}/{}'.format( len(exclude), count))
<SYSTEM_TASK:> Takes an iterable of trait names, and tries to compose a property type <END_TASK> <USER_TASK:> Description: def create_property_type_from_traits(trait_set): """Takes an iterable of trait names, and tries to compose a property type from that. Raises an exception if this is not possible. Extra traits not requested are not acceptable. If this automatic generation doesn't work for you for some reason, then compose your property types manually. The details of this composition should not be relied upon; it may change in future releases. However, a given normalize version should behave consistently for multiple runs, given the same starting sets of properties, the composition order will be the same every time. """
wanted_traits = set(trait_set) stock_types = dict( (k, v) for k, v in PROPERTY_TYPES.items() if set(k).issubset(wanted_traits) ) traits_available = set() for key in stock_types.keys(): traits_available.update(key) missing_traits = wanted_traits - traits_available if missing_traits: raise exc.PropertyTypeMixinNotPossible( traitlist=repr(trait_set), missing=repr(tuple(sorted(missing_traits))), ) made_types = [] # mix together property types, until we have made the right type. while trait_set not in PROPERTY_TYPES: # be somewhat deterministic: always start with types which provide the # 'first' trait on the list start_with = set( k for k in stock_types.keys() if k and k[0] == trait_set[0] ) # prefer extending already composed trait sets, by only adding to the # longest ones longest = max(len(x) for x in start_with) made_type = False for base in sorted(start_with): if len(base) != longest: continue # pick a type to join on which reduces the short-fall as much as # possible. shortfall = len(wanted_traits) - len(base) mix_in = None for other in sorted(stock_types.keys()): # skip mixes that will fail; this means that the type on the # list is a trait subset of 'base' mixed_traits = tuple(sorted(set(base) | set(other))) if mixed_traits in PROPERTY_TYPES: continue this_shortfall = len(wanted_traits - (set(base) | set(other))) if this_shortfall < shortfall: mix_in = other mixed_in_product = mixed_traits shortfall = this_shortfall if shortfall == 0: break if mix_in: base_type = PROPERTY_TYPES[base] other_type = PROPERTY_TYPES[other] new_name = _merge_camel_case_names( base_type.__name__, other_type.__name__, ) new_type = type(new_name, (base_type, other_type), {}) stock_types[mixed_in_product] = new_type made_types.append(new_type) made_type = True if not made_type: raise exc.PropertyTypeMixinFailure( traitlist=repr(trait_set), newtypelist=", ".join( "%r (%s)" % (x.traits, x.__name__) for x in made_types ) )
<SYSTEM_TASK:> Resolve source to filepath if it is a directory. <END_TASK> <USER_TASK:> Description: def _resolve_source(self, source): """Resolve source to filepath if it is a directory."""
if os.path.isdir(source): sources = glob.glob(os.path.join(source, '*.sbml')) if len(sources) == 0: raise ModelLoadError('No .sbml file found in source directory') elif len(sources) > 1: raise ModelLoadError( 'More than one .sbml file found in source directory') return sources[0] return source
<SYSTEM_TASK:> Return the flipped version of this direction. <END_TASK> <USER_TASK:> Description: def flipped(self): """Return the flipped version of this direction."""
forward, reverse = self.value return self.__class__((reverse, forward))
<SYSTEM_TASK:> Run flux variability command <END_TASK> <USER_TASK:> Description: def run(self): """Run flux variability command"""
# Load compound information def compound_name(id): if id not in self._model.compounds: return id return self._model.compounds[id].properties.get('name', id) reaction = self._get_objective() if not self._mm.has_reaction(reaction): self.fail( 'Specified reaction is not in model: {}'.format(reaction)) loop_removal = self._get_loop_removal_option() enable_tfba = loop_removal == 'tfba' if enable_tfba: solver = self._get_solver(integer=True) else: solver = self._get_solver() start_time = time.time() try: fba_fluxes = dict(fluxanalysis.flux_balance( self._mm, reaction, tfba=False, solver=solver)) except fluxanalysis.FluxBalanceError as e: self.report_flux_balance_error(e) threshold = self._args.threshold if threshold.relative: threshold.reference = fba_fluxes[reaction] logger.info('Setting objective threshold to {}'.format( threshold)) handler_args = ( self._mm, solver, enable_tfba, float(threshold), reaction) executor = self._create_executor( FVATaskHandler, handler_args, cpus_per_worker=2) def iter_results(): results = {} with executor: for (reaction_id, direction), value in executor.imap_unordered( product(self._mm.reactions, (1, -1)), 16): if reaction_id not in results: results[reaction_id] = value continue other_value = results[reaction_id] if direction == -1: bounds = value, other_value else: bounds = other_value, value yield reaction_id, bounds executor.join() for reaction_id, (lower, upper) in iter_results(): rx = self._mm.get_reaction(reaction_id) rxt = rx.translated_compounds(compound_name) print('{}\t{}\t{}\t{}'.format(reaction_id, lower, upper, rxt)) logger.info('Solving took {:.2f} seconds'.format( time.time() - start_time))
<SYSTEM_TASK:> Returns the EmptyVal instance for the given type <END_TASK> <USER_TASK:> Description: def placeholder(type_): """Returns the EmptyVal instance for the given type"""
typetuple = type_ if isinstance(type_, tuple) else (type_,) if any in typetuple: typetuple = any if typetuple not in EMPTY_VALS: EMPTY_VALS[typetuple] = EmptyVal(typetuple) return EMPTY_VALS[typetuple]
<SYSTEM_TASK:> Iterates over an iterable containing either type objects or tuples of <END_TASK> <USER_TASK:> Description: def itertypes(iterable): """Iterates over an iterable containing either type objects or tuples of type objects and yields once for every type object found."""
seen = set() for entry in iterable: if isinstance(entry, tuple): for type_ in entry: if type_ not in seen: seen.add(type_) yield type_ else: if entry not in seen: seen.add(entry) yield entry
<SYSTEM_TASK:> Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for temporary <END_TASK> <USER_TASK:> Description: def remove_ignore(path, use_sudo=False, force=False): """ Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for temporary files that can be assumed to be cleaned up at a later point. :param path: Path to file or directory to remove. :type path: unicode :param use_sudo: Use the `sudo` command. :type use_sudo: bool :param force: Force the removal. :type force: bool """
which = sudo if use_sudo else run which(rm(path, recursive=True, force=force), warn_only=True)
<SYSTEM_TASK:> Check if the remote path exists and is a directory. <END_TASK> <USER_TASK:> Description: def is_directory(path, use_sudo=False): """ Check if the remote path exists and is a directory. :param path: Remote path to check. :type path: unicode :param use_sudo: Use the `sudo` command. :type use_sudo: bool :return: `True` if the path exists and is a directory; `False` if it exists, but is a file; `None` if it does not exist. :rtype: bool or ``None`` """
result = single_line_stdout('if [[ -f {0} ]]; then echo 0; elif [[ -d {0} ]]; then echo 1; else echo -1; fi'.format(path), sudo=use_sudo, quiet=True) if result == '0': return False elif result == '1': return True else: return None
<SYSTEM_TASK:> Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do <END_TASK> <USER_TASK:> Description: def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False): """ Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :type apply_chmod: unicode :param remove_using_sudo: Use sudo for removing the directory. ``None`` (default) means it is used depending on whether ``apply_chown`` has been set. :type remove_using_sudo: bool | NoneType :param remove_force: Force the removal. :type remove_force: bool :return: Path to the temporary directory. :rtype: unicode """
path = get_remote_temp() try: if apply_chmod: run(chmod(apply_chmod, path)) if apply_chown: if remove_using_sudo is None: remove_using_sudo = True sudo(chown(apply_chown, path)) yield path finally: remove_ignore(path, use_sudo=remove_using_sudo, force=remove_force)
<SYSTEM_TASK:> Creates a local temporary directory. The directory is removed when no longer needed. Failure to do <END_TASK> <USER_TASK:> Description: def local_temp_dir(): """ Creates a local temporary directory. The directory is removed when no longer needed. Failure to do so will be ignored. :return: Path to the temporary directory. :rtype: unicode """
path = tempfile.mkdtemp() yield path shutil.rmtree(path, ignore_errors=True)
<SYSTEM_TASK:> Get a list of headers. <END_TASK> <USER_TASK:> Description: def get_response(self, environ=None): """Get a list of headers."""
response = super(SameContentException, self).get_response( environ=environ ) if self.etag is not None: response.set_etag(self.etag) if self.last_modified is not None: response.headers['Last-Modified'] = http_date(self.last_modified) return response
<SYSTEM_TASK:> Return a constant indicating the type of coupling. <END_TASK> <USER_TASK:> Description: def classify_coupling(coupling): """Return a constant indicating the type of coupling. Depending on the type of coupling, one of the constants from :class:`.CouplingClass` is returned. Args: coupling: Tuple of minimum and maximum flux ratio """
lower, upper = coupling if lower is None and upper is None: return CouplingClass.Uncoupled elif lower is None or upper is None: return CouplingClass.DirectionalReverse elif lower == 0.0 and upper == 0.0: return CouplingClass.Inconsistent elif lower <= 0.0 and upper >= 0.0: return CouplingClass.DirectionalForward elif abs(lower - upper) < 1e-6: return CouplingClass.Full else: return CouplingClass.Partial
<SYSTEM_TASK:> Return the flux coupling between two reactions <END_TASK> <USER_TASK:> Description: def solve(self, reaction_1, reaction_2): """Return the flux coupling between two reactions The flux coupling is returned as a tuple indicating the minimum and maximum value of the v1/v2 reaction flux ratio. A value of None as either the minimum or maximum indicates that the interval is unbounded in that direction. """
# Update objective for reaction_1 self._prob.set_objective(self._vbow(reaction_1)) # Update constraint for reaction_2 if self._reaction_constr is not None: self._reaction_constr.delete() self._reaction_constr, = self._prob.add_linear_constraints( self._vbow(reaction_2) == 1) results = [] for sense in (lp.ObjectiveSense.Minimize, lp.ObjectiveSense.Maximize): try: result = self._prob.solve(sense) except lp.SolverError: results.append(None) else: results.append(result.get_value(self._vbow(reaction_1))) return tuple(results)
<SYSTEM_TASK:> Performs an action on the given container map and configuration. <END_TASK> <USER_TASK:> Description: def perform(action_name, container, **kwargs): """ Performs an action on the given container map and configuration. :param action_name: Name of the action (e.g. ``update``). :param container: Container configuration name. :param kwargs: Keyword arguments for the action implementation. """
cf = container_fabric() cf.call(action_name, container, **kwargs)
<SYSTEM_TASK:> Create function for converting SBML IDs. <END_TASK> <USER_TASK:> Description: def create_convert_sbml_id_function( compartment_prefix='C_', reaction_prefix='R_', compound_prefix='M_', decode_id=entry_id_from_cobra_encoding): """Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes are common on IDs in SBML models because the IDs live in a global namespace. """
def convert_sbml_id(entry): if isinstance(entry, BaseCompartmentEntry): prefix = compartment_prefix elif isinstance(entry, BaseReactionEntry): prefix = reaction_prefix elif isinstance(entry, BaseCompoundEntry): prefix = compound_prefix new_id = entry.id if decode_id is not None: new_id = decode_id(new_id) if prefix is not None and new_id.startswith(prefix): new_id = new_id[len(prefix):] return new_id return convert_sbml_id
<SYSTEM_TASK:> Yield key, value pairs parsed from the XHTML notes section. <END_TASK> <USER_TASK:> Description: def parse_xhtml_notes(entry): """Yield key, value pairs parsed from the XHTML notes section. Each key, value pair must be defined in its own text block, e.g. ``<p>key: value</p><p>key2: value2</p>``. The key and value must be separated by a colon. Whitespace is stripped from both key and value, and quotes are removed from values if present. The key is normalized by conversion to lower case and spaces replaced with underscores. Args: entry: :class:`_SBMLEntry`. """
for note in entry.xml_notes.itertext(): m = re.match(r'^([^:]+):(.+)$', note) if m: key, value = m.groups() key = key.strip().lower().replace(' ', '_') value = value.strip() m = re.match(r'^"(.*)"$', value) if m: value = m.group(1) if value != '': yield key, value
<SYSTEM_TASK:> Return species properties defined in the XHTML notes. <END_TASK> <USER_TASK:> Description: def parse_xhtml_species_notes(entry): """Return species properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``PUBCHEM ID``, ``CHEBI ID``, ``FORMULA``, ``KEGG ID``, ``CHARGE``. Args: entry: :class:`SBMLSpeciesEntry`. """
properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) for key in ('pubchem_id', 'chebi_id'): if key in cobra_notes: properties[key] = cobra_notes[key] if 'formula' in cobra_notes: properties['formula'] = cobra_notes['formula'] if 'kegg_id' in cobra_notes: properties['kegg'] = cobra_notes['kegg_id'] if 'charge' in cobra_notes: try: value = int(cobra_notes['charge']) except ValueError: logger.warning( 'Unable to parse charge for {} as an' ' integer: {}'.format( entry.id, cobra_notes['charge'])) value = cobra_notes['charge'] properties['charge'] = value return properties
<SYSTEM_TASK:> Return reaction properties defined in the XHTML notes. <END_TASK> <USER_TASK:> Description: def parse_xhtml_reaction_notes(entry): """Return reaction properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``SUBSYSTEM``, ``GENE ASSOCIATION``, ``EC NUMBER``, ``AUTHORS``, ``CONFIDENCE``. Args: entry: :class:`SBMLReactionEntry`. """
properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) if 'subsystem' in cobra_notes: properties['subsystem'] = cobra_notes['subsystem'] if 'gene_association' in cobra_notes: properties['genes'] = cobra_notes['gene_association'] if 'ec_number' in cobra_notes: properties['ec'] = cobra_notes['ec_number'] if 'authors' in cobra_notes: properties['authors'] = [ a.strip() for a in cobra_notes['authors'].split(';')] if 'confidence' in cobra_notes: try: value = int(cobra_notes['confidence']) except ValueError: logger.warning( 'Unable to parse confidence level for {} as an' ' integer: {}'.format( entry.id, cobra_notes['confidence'])) value = cobra_notes['confidence'] properties['confidence'] = value return properties
<SYSTEM_TASK:> Return objective value for reaction entry. <END_TASK> <USER_TASK:> Description: def parse_objective_coefficient(entry): """Return objective value for reaction entry. Detect objectives that are specified using the non-standardized kinetic law parameters which are used by many pre-FBC SBML models. The objective coefficient is returned for the given reaction, or None if undefined. Args: entry: :class:`SBMLReactionEntry`. """
for parameter in entry.kinetic_law_reaction_parameters: pid, name, value, units = parameter if (pid == 'OBJECTIVE_COEFFICIENT' or name == 'OBJECTIVE_COEFFICIENT'): return value return None
<SYSTEM_TASK:> Return flux bounds for reaction entry. <END_TASK> <USER_TASK:> Description: def parse_flux_bounds(entry): """Return flux bounds for reaction entry. Detect flux bounds that are specified using the non-standardized kinetic law parameters which are used by many pre-FBC SBML models. The flux bounds are returned as a pair of lower, upper bounds. The returned bound is None if undefined. Args: entry: :class:`SBMLReactionEntry`. """
lower_bound = None upper_bound = None for parameter in entry.kinetic_law_reaction_parameters: pid, name, value, units = parameter if pid == 'UPPER_BOUND' or name == 'UPPER_BOUND': upper_bound = value elif pid == 'LOWER_BOUND' or name == 'LOWER_BOUND': lower_bound = value return lower_bound, upper_bound
<SYSTEM_TASK:> Detect the identifier for equations with extracellular compartments. <END_TASK> <USER_TASK:> Description: def detect_extracellular_compartment(model): """Detect the identifier for equations with extracellular compartments. Args: model: :class:`NativeModel`. """
extracellular_key = Counter() for reaction in model.reactions: equation = reaction.equation if equation is None: continue if len(equation.compounds) == 1: compound, _ = equation.compounds[0] compartment = compound.compartment extracellular_key[compartment] += 1 if len(extracellular_key) == 0: return None else: best_key, _ = extracellular_key.most_common(1)[0] logger.info('{} is extracellular compartment'.format(best_key)) return best_key
<SYSTEM_TASK:> Convert exchange reactions in model to exchange compounds. <END_TASK> <USER_TASK:> Description: def convert_exchange_to_compounds(model): """Convert exchange reactions in model to exchange compounds. Only exchange reactions in the extracellular compartment are converted. The extracelluar compartment must be defined for the model. Args: model: :class:`NativeModel`. """
# Build set of exchange reactions exchanges = set() for reaction in model.reactions: equation = reaction.properties.get('equation') if equation is None: continue if len(equation.compounds) != 1: # Provide warning for exchange reactions with more than # one compound, they won't be put into the exchange definition if (len(equation.left) == 0) != (len(equation.right) == 0): logger.warning('Exchange reaction {} has more than one' ' compound, it was not converted to' ' exchange compound'.format(reaction.id)) continue exchanges.add(reaction.id) # Convert exchange reactions into exchange compounds for reaction_id in exchanges: equation = model.reactions[reaction_id].equation compound, value = equation.compounds[0] if compound.compartment != model.extracellular_compartment: continue if compound in model.exchange: logger.warning( 'Compound {} is already defined in the exchange' ' definition'.format(compound)) continue # We multiply the flux bounds by value in order to create equivalent # exchange reactions with stoichiometric value of one. If the flux # bounds are not set but the reaction is unidirectional, the implicit # flux bounds must be used. lower_flux, upper_flux = None, None if reaction_id in model.limits: _, lower, upper = model.limits[reaction_id] if lower is not None: lower_flux = lower * abs(value) if upper is not None: upper_flux = upper * abs(value) if lower_flux is None and equation.direction == Direction.Forward: lower_flux = 0 if upper_flux is None and equation.direction == Direction.Reverse: upper_flux = 0 # If the stoichiometric value of the reaction is reversed, the flux # limits must be flipped. if value > 0: lower_flux, upper_flux = ( -upper_flux if upper_flux is not None else None, -lower_flux if lower_flux is not None else None) model.exchange[compound] = ( compound, reaction_id, lower_flux, upper_flux) model.reactions.discard(reaction_id) model.limits.pop(reaction_id, None)
<SYSTEM_TASK:> Get id of reaction or species element. <END_TASK> <USER_TASK:> Description: def _element_get_id(self, element): """Get id of reaction or species element. In old levels the name is used as the id. This method returns the correct attribute depending on the level. """
if self._reader._level > 1: entry_id = element.get('id') else: entry_id = element.get('name') return entry_id
<SYSTEM_TASK:> All species properties as a dict <END_TASK> <USER_TASK:> Description: def properties(self): """All species properties as a dict"""
properties = {'id': self._id, 'boundary': self._boundary} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if 'compartment' in self._root.attrib: properties['compartment'] = self._root.get('compartment') charge = self.charge if charge is not None: properties['charge'] = charge formula = self.formula if formula is not None: properties['formula'] = formula return properties
<SYSTEM_TASK:> Yield species id and parsed value for a speciesReference list <END_TASK> <USER_TASK:> Description: def _parse_species_references(self, name): """Yield species id and parsed value for a speciesReference list"""
for species in self._root.iterfind('./{}/{}'.format( self._reader._sbml_tag(name), self._reader._sbml_tag('speciesReference'))): species_id = species.get('species') if self._reader._level == 1: # In SBML level 1 only positive integers are allowed for # stoichiometry but a positive integer denominator can be # specified. try: value = int(species.get('stoichiometry', 1)) denom = int(species.get('denominator', 1)) species_value = Fraction(value, denom) except ValueError: message = ('Non-integer stoichiometry is not allowed in' ' SBML level 1 (reaction {})'.format(self.id)) if self._reader._strict: raise ParseError(message) else: logger.warning(message) species_value = Decimal(species.get('stoichiometry', 1)) elif self._reader._level == 2: # Stoichiometric value is a double but can alternatively be # specified using math (not implemented). value_str = species.get('stoichiometry', None) if value_str is None: if 'stoichiometryMath' in species: raise ParseError('stoichiometryMath in ' 'speciesReference is not implemented') species_value = 1 else: species_value = Decimal(value_str) elif self._reader._level == 3: # Stoichiometric value is a double but can alternatively be # specified using initial assignment (not implemented). value_str = species.get('stoichiometry', None) if value_str is None: raise ParseError('Missing stoichiometry in' ' speciesReference is not implemented') species_value = Decimal(value_str) if species_value % 1 == 0: species_value = int(species_value) yield species_id, species_value
<SYSTEM_TASK:> Iterator over the values of kinetic law reaction parameters <END_TASK> <USER_TASK:> Description: def kinetic_law_reaction_parameters(self): """Iterator over the values of kinetic law reaction parameters"""
for parameter in self._root.iterfind( './{}/{}/{}'.format(self._reader._sbml_tag('kineticLaw'), self._reader._sbml_tag('listOfParameters'), self._reader._sbml_tag('parameter'))): param_id = parameter.get('id') param_name = parameter.get('name') param_value = Decimal(parameter.get('value')) param_units = parameter.get('units') yield param_id, param_name, param_value, param_units
<SYSTEM_TASK:> All reaction properties as a dict <END_TASK> <USER_TASK:> Description: def properties(self): """All reaction properties as a dict"""
properties = {'id': self._id, 'reversible': self._rev, 'equation': self._equation} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if self._lower_flux is not None: properties['lower_flux'] = self._lower_flux if self._upper_flux is not None: properties['upper_flux'] = self._upper_flux return properties
<SYSTEM_TASK:> All compartment properties as a dict. <END_TASK> <USER_TASK:> Description: def properties(self): """All compartment properties as a dict."""
properties = {'id': self._id} if self._name is not None: properties['name'] = self._name return properties
<SYSTEM_TASK:> Returns a modified id that has been made safe for SBML. <END_TASK> <USER_TASK:> Description: def _make_safe_id(self, id): """Returns a modified id that has been made safe for SBML. Replaces or deletes the ones that aren't allowed. """
substitutions = { '-': '_DASH_', '/': '_FSLASH_', '\\': '_BSLASH_', '(': '_LPAREN_', ')': '_RPAREN_', '[': '_LSQBKT_', ']': '_RSQBKT_', ',': '_COMMA_', '.': '_PERIOD_', "'": '_APOS_' } id = re.sub(r'\(([a-z])\)$', '_\\1', id) for symbol, escape in iteritems(substitutions): id = id.replace(symbol, escape) id = re.sub(r'[^a-zA-Z0-9_]', '', id) return id
<SYSTEM_TASK:> Read reaction's limits to set up strings for limits in the output file. <END_TASK> <USER_TASK:> Description: def _get_flux_bounds(self, r_id, model, flux_limits, equation): """Read reaction's limits to set up strings for limits in the output file. """
if r_id not in flux_limits or flux_limits[r_id][0] is None: if equation.direction == Direction.Forward: lower = 0 else: lower = -model.default_flux_limit else: lower = flux_limits[r_id][0] if r_id not in flux_limits or flux_limits[r_id][1] is None: if equation.direction == Direction.Reverse: upper = 0 else: upper = model.default_flux_limit else: upper = flux_limits[r_id][1] if lower % 1 == 0: lower = int(lower) if upper % 1 == 0: upper = int(upper) return text_type(lower), text_type(upper)
<SYSTEM_TASK:> Adds all the different kinds of genes into a list. <END_TASK> <USER_TASK:> Description: def _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag): """Adds all the different kinds of genes into a list."""
genes = ET.SubElement( r_tag, _tag('geneProductAssociation', FBC_V2)) if isinstance(r_genes, list): e = Expression(And(*(Variable(i) for i in r_genes))) else: e = Expression(r_genes) gene_stack = [(e.root, genes)] while len(gene_stack) > 0: current, parent = gene_stack.pop() if isinstance(current, Or): gene_tag = ET.SubElement(parent, _tag('or', FBC_V2)) elif isinstance(current, And): gene_tag = ET.SubElement(parent, _tag('and', FBC_V2)) elif isinstance(current, Variable): gene_tag = ET.SubElement(parent, _tag( 'geneProductRef', FBC_V2)) if current.symbol not in gene_ids: id = 'g_' + util.create_unique_id( self._make_safe_id(current.symbol), gene_ids) gene_ids[id] = current.symbol gene_tag.set(_tag('geneProduct', FBC_V2), id) if isinstance(current, (Or, And)): for item in current: gene_stack.append((item, gene_tag))
<SYSTEM_TASK:> Create list of all gene products as sbml readable elements. <END_TASK> <USER_TASK:> Description: def _add_gene_list(self, parent_tag, gene_id_dict): """Create list of all gene products as sbml readable elements."""
list_all_genes = ET.SubElement(parent_tag, _tag( 'listOfGeneProducts', FBC_V2)) for id, label in sorted(iteritems(gene_id_dict)): gene_tag = ET.SubElement( list_all_genes, _tag('geneProduct', FBC_V2)) gene_tag.set(_tag('id', FBC_V2), id) gene_tag.set(_tag('label', FBC_V2), label)
<SYSTEM_TASK:> Subclassing hook to specialize how JSON data is converted <END_TASK> <USER_TASK:> Description: def json_to_initkwargs(self, json_data, kwargs): """Subclassing hook to specialize how JSON data is converted to keyword arguments"""
if isinstance(json_data, basestring): json_data = json.loads(json_data) return json_to_initkwargs(self, json_data, kwargs)
<SYSTEM_TASK:> Returns the group id to a given group name. Returns ``None`` if the group does not exist. <END_TASK> <USER_TASK:> Description: def get_group_id(groupname): """ Returns the group id to a given group name. Returns ``None`` if the group does not exist. :param groupname: Group name. :type groupname: unicode :return: Group id. :rtype: int """
gid = single_line_stdout('id -g {0}'.format(groupname), expected_errors=(1,), shell=False) return check_int(gid)
<SYSTEM_TASK:> Returns the user id to a given user name. Returns ``None`` if the user does not exist. <END_TASK> <USER_TASK:> Description: def get_user_id(username): """ Returns the user id to a given user name. Returns ``None`` if the user does not exist. :param username: User name. :type username: unicode :return: User id. :rtype: int """
uid = single_line_stdout('id -u {0}'.format(username), expected_errors=(1,), shell=False) return check_int(uid)
<SYSTEM_TASK:> Creates a new user group with a specific id. <END_TASK> <USER_TASK:> Description: def create_group(groupname, gid, system=True): """ Creates a new user group with a specific id. :param groupname: Group name. :type groupname: unicode :param gid: Group id. :type gid: int or unicode :param system: Creates a system group. """
sudo(addgroup(groupname, gid, system))
<SYSTEM_TASK:> Creates a new user with a specific id. <END_TASK> <USER_TASK:> Description: def create_user(username, uid, system=False, no_login=True, no_password=False, group=False, gecos=None): """ Creates a new user with a specific id. :param username: User name. :type username: unicode :param uid: User id. :type uid: int or unicode :param system: Creates a system user. :type system: bool :param no_login: Disallow login of this user and group, and skip creating the home directory. Default is ``True``. :type no_login: bool :param no_password: Do not set a password for the new user. :type: no_password: bool :param group: Create a group with the same id. :type group: bool :param gecos: Provide GECOS info and suppress prompt. :type gecos: unicode """
sudo(adduser(username, uid, system, no_login, no_password, group, gecos))
<SYSTEM_TASK:> Returns the id for the given group, and creates it first in case it does not exist. <END_TASK> <USER_TASK:> Description: def get_or_create_group(groupname, gid_preset, system=False, id_dependent=True): """ Returns the id for the given group, and creates it first in case it does not exist. :param groupname: Group name. :type groupname: unicode :param gid_preset: Group id to set if a new group is created. :type gid_preset: int or unicode :param system: Create a system group. :type system: bool :param id_dependent: If the group exists, but its id does not match `gid_preset`, an error is thrown. :type id_dependent: bool :return: Group id of the existing or new group. :rtype: int """
gid = get_group_id(groupname) if gid is None: create_group(groupname, gid_preset, system) return gid_preset elif id_dependent and gid != gid_preset: error("Present group id '{0}' does not match the required id of the environment '{1}'.".format(gid, gid_preset)) return gid
<SYSTEM_TASK:> Returns the id of the given user name, and creates it first in case it does not exist. A default group is created <END_TASK> <USER_TASK:> Description: def get_or_create_user(username, uid_preset, groupnames=[], system=False, no_password=False, no_login=True, gecos=None, id_dependent=True): """ Returns the id of the given user name, and creates it first in case it does not exist. A default group is created as well. :param username: User name. :type username: unicode :param uid_preset: User id to set in case a new user is created. :type uid_preset: int or unicode :param groupnames: Additional names of groups to assign the user to. If the user exists, these will be appended to existing group assignments. :type groupnames: iterable :param system: Create a system user. :type system: bool :param no_login: Disallow login of this user and group, and skip creating the home directory. Default is ``True``. :type no_login: bool :param no_password: Do not set a password for the new user. :type: no_password: bool :param gecos: Provide GECOS info and suppress prompt. :type gecos: unicode :param id_dependent: If the user exists, but its id does not match `uid_preset`, an error is thrown. :type id_dependent: bool :return: """
uid = get_user_id(username) gid = get_group_id(username) if id_dependent and gid is not None and gid != uid_preset: error("Present group id '{0}' does not match the required id of the environment '{1}'.".format(gid, uid_preset)) if gid is None: create_group(username, uid_preset, system) gid = uid_preset if uid is None: create_user(username, gid, system, no_login, no_password, False, gecos) if groupnames: assign_user_groups(username, groupnames) return uid elif id_dependent and uid != uid_preset: error("Present user id '{0}' does not match the required id of the environment '{1}'.".format(uid, uid_preset)) current_groups = get_user_groups(username) new_groups = set(groupnames).discard(tuple(current_groups)) if new_groups: assign_user_groups(username, new_groups) return uid
<SYSTEM_TASK:> Runs a command and returns the result, that would be written to `stdout`, as a string. The output itself can <END_TASK> <USER_TASK:> Description: def stdout_result(cmd, expected_errors=(), shell=True, sudo=False, quiet=False): """ Runs a command and returns the result, that would be written to `stdout`, as a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is returned in this case. :type expected_errors: tuple :param shell: Use a shell. :type shell: bool :param sudo: Use `sudo`. :type sudo: bool :param quiet: If set to ``True``, does not show any output. :type quiet: bool :return: The result of the command as would be written to `stdout`. :rtype: unicode """
which = operations.sudo if sudo else operations.run with hide('warnings'): result = which(cmd, shell=shell, quiet=quiet, warn_only=True) if result.return_code == 0: return result if result.return_code not in expected_errors: error("Received unexpected error code {0} while executing!".format(result.return_code)) return None
<SYSTEM_TASK:> Runs a command and returns the first line of the result, that would be written to `stdout`, as a string. <END_TASK> <USER_TASK:> Description: def single_line_stdout(cmd, expected_errors=(), shell=True, sudo=False, quiet=False): """ Runs a command and returns the first line of the result, that would be written to `stdout`, as a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is returned in this case. :type expected_errors: tuple :param shell: Use a shell. :type shell: bool :param sudo: Use `sudo`. :type sudo: bool :param quiet: If set to ``True``, does not show any output. :type quiet: bool :return: The result of the command as would be written to `stdout`. :rtype: unicode """
return single_line(stdout_result(cmd, expected_errors, shell, sudo, quiet))
<SYSTEM_TASK:> Add constraints to the model. <END_TASK> <USER_TASK:> Description: def add(self, *args): """Add constraints to the model."""
self._constrs.extend(self._moma._prob.add_linear_constraints(*args))
<SYSTEM_TASK:> Yield all the non exchange reactions in the model. <END_TASK> <USER_TASK:> Description: def _adjustment_reactions(self): """Yield all the non exchange reactions in the model."""
for reaction_id in self._model.reactions: if not self._model.is_exchange(reaction_id): yield reaction_id
<SYSTEM_TASK:> Remove old constraints and then solve the current problem. <END_TASK> <USER_TASK:> Description: def _solve(self, sense=None): """Remove old constraints and then solve the current problem. Args: sense: Minimize or maximize the objective. (:class:`.lp.ObjectiveSense) Returns: The Result object for the solved LP problem """
# Remove the constraints from the last run while len(self._remove_constr) > 0: self._remove_constr.pop().delete() try: return self._prob.solve(sense=sense) except lp.SolverError as e: raise_from(MOMAError(text_type(e)), e) finally: self._remove_constr = []
<SYSTEM_TASK:> Solve the wild type problem using FBA. <END_TASK> <USER_TASK:> Description: def solve_fba(self, objective): """Solve the wild type problem using FBA. Args: objective: The objective reaction to be maximized. Returns: The LP Result object for the solved FBA problem. """
self._prob.set_objective(self._v_wt[objective]) return self._solve(lp.ObjectiveSense.Maximize)
<SYSTEM_TASK:> Return a dictionary of all the fluxes solved by FBA. <END_TASK> <USER_TASK:> Description: def get_fba_flux(self, objective): """Return a dictionary of all the fluxes solved by FBA. Dictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma` to minimize changes in the flux distributions following model perturbation. Args: objective: The objective reaction that is maximized. Returns: Dictionary of fluxes for each reaction in the model. """
flux_result = self.solve_fba(objective) fba_fluxes = {} # Place all the flux values in a dictionary for key in self._model.reactions: fba_fluxes[key] = flux_result.get_value(self._v_wt[key]) return fba_fluxes
<SYSTEM_TASK:> Find the FBA solution that minimizes all the flux values. <END_TASK> <USER_TASK:> Description: def get_minimal_fba_flux(self, objective): """Find the FBA solution that minimizes all the flux values. Maximize the objective flux then minimize all other fluxes while keeping the objective flux at the maximum. Args: objective: The objective reaction that is maximized. Returns: A dictionary of all the reactions and their minimized fluxes. """
# Define constraints vs_wt = self._v_wt.set(self._model.reactions) zs = self._z.set(self._model.reactions) wt_obj_flux = self.get_fba_obj_flux(objective) with self.constraints() as constr: constr.add( zs >= vs_wt, vs_wt >= -zs, self._v_wt[objective] >= wt_obj_flux) self._prob.set_objective(self._z.sum(self._model.reactions)) result = self._solve(lp.ObjectiveSense.Minimize) fba_fluxes = {} for key in self._model.reactions: fba_fluxes[key] = result.get_value(self._v_wt[key]) return fba_fluxes
<SYSTEM_TASK:> Minimize the redistribution of fluxes using a linear objective. <END_TASK> <USER_TASK:> Description: def lin_moma(self, wt_fluxes): """Minimize the redistribution of fluxes using a linear objective. The change in flux distribution is mimimized by minimizing the sum of the absolute values of the differences of wild type FBA solution and the knockout strain flux solution. This formulation bases the solution on the wild type fluxes that are specified by the user. If these wild type fluxes were calculated using FBA, then an arbitrary flux vector that optimizes the objective function is used. See [Segre`_02] for more information. Args: wt_fluxes: Dictionary of all the wild type fluxes. Use :meth:`.get_fba_flux(objective)` to return a dictionary of fluxes found by FBA. """
reactions = set(self._adjustment_reactions()) z_diff = self._z_diff v = self._v with self.constraints() as constr: for f_reaction, f_value in iteritems(wt_fluxes): if f_reaction in reactions: # Add the constraint that finds the optimal solution, such # that the difference between the wildtype flux is similar # to the knockout flux. constr.add( z_diff[f_reaction] >= f_value - v[f_reaction], f_value - v[f_reaction] >= -z_diff[f_reaction]) # If we minimize the sum of the z vector then we will minimize # the |vs_wt - vs| from above self._prob.set_objective(z_diff.sum(reactions)) self._solve(lp.ObjectiveSense.Minimize)
<SYSTEM_TASK:> Find the smallest redistribution vector using a linear objective. <END_TASK> <USER_TASK:> Description: def lin_moma2(self, objective, wt_obj): """Find the smallest redistribution vector using a linear objective. The change in flux distribution is mimimized by minimizing the sum of the absolute values of the differences of wild type FBA solution and the knockout strain flux solution. Creates the constraint that the we select the optimal flux vector that is closest to the wildtype. This might still return an arbitrary flux vector the maximizes the objective function. Args: objective: Objective reaction for the model. wt_obj: The flux value for your wild type objective reactions. Can either use an expiremental value or on determined by FBA by using :meth:`.get_fba_obj_flux(objective)`. """
reactions = set(self._adjustment_reactions()) z_diff = self._z_diff v = self._v v_wt = self._v_wt with self.constraints() as constr: for f_reaction in reactions: # Add the constraint that finds the optimal solution, such # that the difference between the wildtype flux # is similar to the knockout flux. constr.add( z_diff[f_reaction] >= v_wt[f_reaction] - v[f_reaction], v_wt[f_reaction] - v[f_reaction] >= -z_diff[f_reaction]) # If we minimize the sum of the z vector then we will minimize # the |v_wt - v| from above self._prob.set_objective(z_diff.sum(reactions)) constr.add(self._v_wt[objective] >= wt_obj) self._solve(lp.ObjectiveSense.Minimize)
<SYSTEM_TASK:> Minimize the redistribution of fluxes using Euclidean distance. <END_TASK> <USER_TASK:> Description: def moma(self, wt_fluxes): """Minimize the redistribution of fluxes using Euclidean distance. Minimizing the redistribution of fluxes using a quadratic objective function. The distance is minimized by minimizing the sum of (wild type - knockout)^2. Args: wt_fluxes: Dictionary of all the wild type fluxes that will be used to find a close MOMA solution. Fluxes can be expiremental or calculated using :meth: get_fba_flux(objective). """
reactions = set(self._adjustment_reactions()) v = self._v obj_expr = 0 for f_reaction, f_value in iteritems(wt_fluxes): if f_reaction in reactions: # Minimize the Euclidean distance between the two vectors obj_expr += (f_value - v[f_reaction])**2 self._prob.set_objective(obj_expr) self._solve(lp.ObjectiveSense.Minimize)
<SYSTEM_TASK:> Find the smallest redistribution vector using Euclidean distance. <END_TASK> <USER_TASK:> Description: def moma2(self, objective, wt_obj): """Find the smallest redistribution vector using Euclidean distance. Minimizing the redistribution of fluxes using a quadratic objective function. The distance is minimized by minimizing the sum of (wild type - knockout)^2. Creates the constraint that the we select the optimal flux vector that is closest to the wildtype. This might still return an arbitrary flux vector the maximizes the objective function. Args: objective: Objective reaction for the model. wt_obj: The flux value for your wild type objective reactions. Can either use an expiremental value or on determined by FBA by using :meth:`.get_fba_obj_flux(objective)`. """
obj_expr = 0 for reaction in self._adjustment_reactions(): v_wt = self._v_wt[reaction] v = self._v[reaction] obj_expr += (v_wt - v)**2 self._prob.set_objective(obj_expr) with self.constraints(self._v_wt[objective] >= wt_obj): self._solve(lp.ObjectiveSense.Minimize)
<SYSTEM_TASK:> Connects to the SSDB server if not already connected <END_TASK> <USER_TASK:> Description: def connect(self): """ Connects to the SSDB server if not already connected """
if self._sock: return try: sock = self._connect() except socket.error: e = sys.exc_info()[1] raise ConnectionError(self._error_message(e)) self._sock = sock try: self.on_connect() except SSDBError: # clean up after any error in on_connect self.disconnect() raise # run any user callbacks. right now the only internal callback # is for pubsub channel/pattern resubscription for callback in self._connect_callbacks: callback(self)