Code re-formatting

This commit is contained in:
Artur Meski
2019-02-23 14:41:36 +00:00
parent 59cbc00e7f
commit c3a19d81dc
21 changed files with 1333 additions and 1016 deletions

View File

@@ -10,18 +10,23 @@ C_UNDERLINE = '\033[4m'
C_MARK_INFO = C_BOLD + "[" + C_GREEN + "*" + C_ENDC + C_BOLD + "]" + C_ENDC C_MARK_INFO = C_BOLD + "[" + C_GREEN + "*" + C_ENDC + C_BOLD + "]" + C_ENDC
C_MARK_ERROR = C_BOLD + "[" + C_RED + "!" + C_ENDC + C_BOLD + "]" + C_ENDC C_MARK_ERROR = C_BOLD + "[" + C_RED + "!" + C_ENDC + C_BOLD + "]" + C_ENDC
def colour_str(col, s): def colour_str(col, s):
return col + s + C_ENDC return col + s + C_ENDC
def green_str(s): def green_str(s):
return C_GREEN + s + C_ENDC return C_GREEN + s + C_ENDC
def print_error(s): def print_error(s):
print(C_MARK_ERROR + " " + C_RED + s + C_ENDC) print(C_MARK_ERROR + " " + C_RED + s + C_ENDC)
def print_info(s): def print_info(s):
print("[" + colour_str(C_BOLD, "i") + "] {:s}".format(s)) print("[" + colour_str(C_BOLD, "i") + "] {:s}".format(s))
def print_positive(s): def print_positive(s):
print("[" + colour_str(C_BOLD, "+") + "] {:s}".format(s)) print("[" + colour_str(C_BOLD, "+") + "] {:s}".format(s))

View File

@@ -1,6 +1,7 @@
from enum import Enum from enum import Enum
ParamConstraint_oper = Enum( ParamConstraint_oper = Enum(
'ParamConstraint_oper', 'param_entity true l_and l_or l_not lt le eq ge gt') 'ParamConstraint_oper',
'param_entity true l_and l_or l_not lt le eq ge gt')
class ParamConstraint(object): class ParamConstraint(object):
@@ -49,7 +50,8 @@ class ParamConstraint(object):
@classmethod @classmethod
def f_param_ent(cls, param, entity_name): def f_param_ent(cls, param, entity_name):
return cls(ParamConstraint_oper.param_entity, param=param, entity=entity_name) return cls(ParamConstraint_oper.param_entity, param=param,
entity=entity_name)
@classmethod @classmethod
def f_TRUE(cls): def f_TRUE(cls):
@@ -64,25 +66,32 @@ class ParamConstraint(object):
return cls(ParamConstraint_oper.l_not, L_oper=arg) return cls(ParamConstraint_oper.l_not, L_oper=arg)
def __lt__(self, other): def __lt__(self, other):
return ParamConstraint(ParamConstraint_oper.lt, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.lt, L_oper=self, R_oper=other)
def __le__(self, other): def __le__(self, other):
return ParamConstraint(ParamConstraint_oper.le, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.le, L_oper=self, R_oper=other)
def __eq__(self, other): def __eq__(self, other):
return ParamConstraint(ParamConstraint_oper.eq, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.eq, L_oper=self, R_oper=other)
def __ge__(self, other): def __ge__(self, other):
return ParamConstraint(ParamConstraint_oper.ge, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.ge, L_oper=self, R_oper=other)
def __gt__(self, other): def __gt__(self, other):
return ParamConstraint(ParamConstraint_oper.gt, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.gt, L_oper=self, R_oper=other)
def __and__(self, other): def __and__(self, other):
return ParamConstraint(ParamConstraint_oper.l_and, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.l_and, L_oper=self, R_oper=other)
def __or__(self, other): def __or__(self, other):
return ParamConstraint(ParamConstraint_oper.l_or, L_oper=self, R_oper=other) return ParamConstraint(
ParamConstraint_oper.l_or, L_oper=self, R_oper=other)
def __invert__(self): def __invert__(self):
return ParamConstraint(ParamConstraint_oper.l_not, L_oper=self) return ParamConstraint(ParamConstraint_oper.l_not, L_oper=self)

View File

@@ -1,6 +1,7 @@
from logics.param_constr import * from logics.param_constr import *
from z3 import And, Not, Or from z3 import And, Not, Or
class ParamConstr_Encoder(object): class ParamConstr_Encoder(object):
"""Class for encoding parameter constraints""" """Class for encoding parameter constraints"""
@@ -24,7 +25,8 @@ class ParamConstr_Encoder(object):
raise RuntimeError("param_constr is None") raise RuntimeError("param_constr is None")
if param_constr.f_type == ParamConstraint_oper.param_entity: if param_constr.f_type == ParamConstraint_oper.param_entity:
return self.smt_checker.get_enc_param(param_constr.param.name, param_constr.entity) return self.smt_checker.get_enc_param(
param_constr.param.name, param_constr.entity)
if param_constr.f_type == ParamConstraint_oper.true: if param_constr.f_type == ParamConstraint_oper.true:
return True return True
@@ -41,19 +43,28 @@ class ParamConstr_Encoder(object):
return Not(self.encode(param_constr.left_operand)) return Not(self.encode(param_constr.left_operand))
if param_constr.f_type == ParamConstraint_oper.lt: if param_constr.f_type == ParamConstraint_oper.lt:
return self.encode(param_constr.left_operand) < int(param_constr.right_operand) return self.encode(
param_constr.left_operand) < int(
param_constr.right_operand)
if param_constr.f_type == ParamConstraint_oper.le: if param_constr.f_type == ParamConstraint_oper.le:
return self.encode(param_constr.left_operand) <= int(param_constr.right_operand) return self.encode(
param_constr.left_operand) <= int(
param_constr.right_operand)
if param_constr.f_type == ParamConstraint_oper.eq: if param_constr.f_type == ParamConstraint_oper.eq:
return self.encode(param_constr.left_operand) == int(param_constr.right_operand) return self.encode(
param_constr.left_operand) == int(
param_constr.right_operand)
if param_constr.f_type == ParamConstraint_oper.ge: if param_constr.f_type == ParamConstraint_oper.ge:
return self.encode(param_constr.left_operand) >= int(param_constr.right_operand) return self.encode(
param_constr.left_operand) >= int(
param_constr.right_operand)
if param_constr.f_type == ParamConstraint_oper.gt: if param_constr.f_type == ParamConstraint_oper.gt:
return self.encode(param_constr.left_operand) > int(param_constr.right_operand) return self.encode(
param_constr.left_operand) > int(
param_constr.right_operand)
assert False, "Unsupported case {:s}".format(param_constr.f_type) assert False, "Unsupported case {:s}".format(param_constr.f_type)

View File

@@ -1,8 +1,10 @@
from logics.rsltl import * from logics.rsltl import *
def simplify(x): def simplify(x):
return x return x
class rsLTL_Encoder(object): class rsLTL_Encoder(object):
"""Class for encoding rsLTL formulae for a given smt_checker instance""" """Class for encoding rsLTL formulae for a given smt_checker instance"""
@@ -96,30 +98,43 @@ class rsLTL_Encoder(object):
return True return True
if bag_formula.f_type == BagDesc_oper.l_and: if bag_formula.f_type == BagDesc_oper.l_and:
return And(self.encode_bag(bag_formula.left_operand, level, context), return And(
self.encode_bag(bag_formula.left_operand, level, context),
self.encode_bag(bag_formula.right_operand, level, context)) self.encode_bag(bag_formula.right_operand, level, context))
if bag_formula.f_type == BagDesc_oper.l_or: if bag_formula.f_type == BagDesc_oper.l_or:
return Or(self.encode_bag(bag_formula.left_operand, level, context), return Or(
self.encode_bag(bag_formula.left_operand, level, context),
self.encode_bag(bag_formula.right_operand, level, context)) self.encode_bag(bag_formula.right_operand, level, context))
if bag_formula.f_type == BagDesc_oper.l_not: if bag_formula.f_type == BagDesc_oper.l_not:
return Not(self.encode_bag(bag_formula.left_operand, level, context)) return Not(self.encode_bag(
bag_formula.left_operand, level, context))
if bag_formula.f_type == BagDesc_oper.lt: if bag_formula.f_type == BagDesc_oper.lt:
return self.encode_bag(bag_formula.left_operand, level, context) < int(bag_formula.right_operand) return self.encode_bag(
bag_formula.left_operand, level, context) < int(
bag_formula.right_operand)
if bag_formula.f_type == BagDesc_oper.le: if bag_formula.f_type == BagDesc_oper.le:
return self.encode_bag(bag_formula.left_operand, level, context) <= int(bag_formula.right_operand) return self.encode_bag(
bag_formula.left_operand, level, context) <= int(
bag_formula.right_operand)
if bag_formula.f_type == BagDesc_oper.eq: if bag_formula.f_type == BagDesc_oper.eq:
return self.encode_bag(bag_formula.left_operand, level, context) == int(bag_formula.right_operand) return self.encode_bag(
bag_formula.left_operand, level, context) == int(
bag_formula.right_operand)
if bag_formula.f_type == BagDesc_oper.ge: if bag_formula.f_type == BagDesc_oper.ge:
return self.encode_bag(bag_formula.left_operand, level, context) >= int(bag_formula.right_operand) return self.encode_bag(
bag_formula.left_operand, level, context) >= int(
bag_formula.right_operand)
if bag_formula.f_type == BagDesc_oper.gt: if bag_formula.f_type == BagDesc_oper.gt:
return self.encode_bag(bag_formula.left_operand, level, context) > int(bag_formula.right_operand) return self.encode_bag(
bag_formula.left_operand, level, context) > int(
bag_formula.right_operand)
assert False, "Unsupported case {:s}".format(bag_formula.f_type) assert False, "Unsupported case {:s}".format(bag_formula.f_type)
@@ -144,10 +159,12 @@ class rsLTL_Encoder(object):
enc = None enc = None
if not isinstance(formula, Formula_rsLTL): if not isinstance(formula, Formula_rsLTL):
raise NotImplementedError("Unsupported formula type: " + str(type(formula))) raise NotImplementedError(
"Unsupported formula type: " + str(type(formula)))
if level > bound: if level > bound:
raise RuntimeError("level > bound. Unexpected behaviour. The encoding does not support levels higher than a bound.") raise RuntimeError(
"level > bound. Unexpected behaviour. The encoding does not support levels higher than a bound.")
if formula.f_type == rsLTL_form_type.bag: if formula.f_type == rsLTL_form_type.bag:
enc = self.encode_bag_state(formula.bag_descr, level) enc = self.encode_bag_state(formula.bag_descr, level)
@@ -187,8 +204,8 @@ class rsLTL_Encoder(object):
# level == bound # level == bound
enc = False enc = False
for loop_level in range(1, bound+1): for loop_level in range(1, bound+1):
enc = simplify(Or(enc, And(self.loop_position == loop_level, enc = simplify(Or(enc, And(self.loop_position == loop_level, self.encode(
self.encode(formula.left_operand, loop_level, bound)))) formula.left_operand, loop_level, bound))))
enc = And(enc, self.encode_bag_ctx(formula.sub_operand, level)) enc = And(enc, self.encode_bag_ctx(formula.sub_operand, level))
enc = simplify(enc) enc = simplify(enc)
@@ -372,7 +389,8 @@ class rsLTL_Encoder(object):
enc = self.encode(formula.left_operand, bound, bound) enc = self.encode(formula.left_operand, bound, bound)
else: else:
raise NotImplementedError("Unsupported operator in approximation encoding") raise NotImplementedError(
"Unsupported operator in approximation encoding")
if enc is None: if enc is None:
raise RuntimeError("Encoding is NONE. Should never happen") raise RuntimeError("Encoding is NONE. Should never happen")

View File

@@ -1,6 +1,7 @@
from sys import exit from sys import exit
from colour import * from colour import *
class ContextAutomaton(object): class ContextAutomaton(object):
def __init__(self, reaction_system): def __init__(self, reaction_system):
@@ -99,13 +100,16 @@ class ContextAutomaton(object):
print("Contexts set must be of type set or list") print("Contexts set must be of type set or list")
if not self.is_valid_context(context_set): if not self.is_valid_context(context_set):
raise RuntimeError("one of the entities in the context set is unknown (undefined)!") raise RuntimeError(
"one of the entities in the context set is unknown (undefined)!")
if not self.is_state(src): if not self.is_state(src):
raise RuntimeError("\"" + src + "\" is an unknown (undefined) state") raise RuntimeError(
"\"" + src + "\" is an unknown (undefined) state")
if not self.is_state(dst): if not self.is_state(dst):
raise RuntimeError("\"" + dst + "\" is an unknown (undefined) state") raise RuntimeError(
"\"" + dst + "\" is an unknown (undefined) state")
new_context_set = set() new_context_set = set()
for e in set(context_set): for e in set(context_set):
@@ -113,7 +117,9 @@ class ContextAutomaton(object):
self._prod_entities |= new_context_set self._prod_entities |= new_context_set
self._transitions.append((self.get_state_id(src),new_context_set,self.get_state_id(dst))) self._transitions.append(
(self.get_state_id(src),
new_context_set, self.get_state_id(dst)))
def rsset2str(self, elements): def rsset2str(self, elements):
"""Converts the set of entities ids into the string with their names""" """Converts the set of entities ids into the string with their names"""

View File

@@ -3,13 +3,17 @@ from colour import *
from rs.context_automaton import ContextAutomaton from rs.context_automaton import ContextAutomaton
class ContextAutomatonWithConcentrations(ContextAutomaton): class ContextAutomatonWithConcentrations(ContextAutomaton):
def __init__(self, reaction_system): def __init__(self, reaction_system):
super(ContextAutomatonWithConcentrations, self).__init__(reaction_system) super(ContextAutomatonWithConcentrations,
self).__init__(reaction_system)
def is_valid_context(self, context): def is_valid_context(self, context):
if set([e for e,lvl in context]).issubset(self._reaction_system.background_set): if set(
[e for e, lvl in context]).issubset(
self._reaction_system.background_set):
return True return True
else: else:
return False return False
@@ -28,19 +32,25 @@ class ContextAutomatonWithConcentrations(ContextAutomaton):
print("Contexts set must be of type set or list") print("Contexts set must be of type set or list")
if not self.is_valid_context(context_set): if not self.is_valid_context(context_set):
raise RuntimeError("one of the entities in the context set is unknown (undefined)!") raise RuntimeError(
"one of the entities in the context set is unknown (undefined)!")
if not self.is_state(src): if not self.is_state(src):
raise RuntimeError("\"" + src + "\" is an unknown (undefined) state") raise RuntimeError(
"\"" + src + "\" is an unknown (undefined) state")
if not self.is_state(dst): if not self.is_state(dst):
raise RuntimeError("\"" + dst + "\" is an unknown (undefined) state") raise RuntimeError(
"\"" + dst + "\" is an unknown (undefined) state")
new_context_set = set() new_context_set = set()
for ent, lvl in set(context_set): for ent, lvl in set(context_set):
new_context_set.add((self._reaction_system.get_entity_id(ent),lvl)) new_context_set.add(
(self._reaction_system.get_entity_id(ent), lvl))
self._transitions.append((self.get_state_id(src),new_context_set,self.get_state_id(dst))) self._transitions.append(
(self.get_state_id(src),
new_context_set, self.get_state_id(dst)))
def get_automaton_with_flat_contexts(self, ordinary_reaction_system): def get_automaton_with_flat_contexts(self, ordinary_reaction_system):
@@ -54,11 +64,14 @@ class ContextAutomatonWithConcentrations(ContextAutomaton):
for ent, conc in ctx: for ent, conc in ctx:
for i in range(1, conc+1): for i in range(1, conc+1):
n = self._reaction_system.get_entity_name(ent) + "#" + str(i) n = self._reaction_system.get_entity_name(
ent) + "#" + str(i)
ca._reaction_system.ensure_bg_set_entity(n) ca._reaction_system.ensure_bg_set_entity(n)
new_ctx.add(n) new_ctx.add(n)
ca.add_transition(ca.get_state_name(src),new_ctx,ca.get_state_name(dst)) ca.add_transition(
ca.get_state_name(src),
new_ctx, ca.get_state_name(dst))
return ca return ca

View File

@@ -3,6 +3,7 @@ from colour import *
from rs.context_automaton import ContextAutomaton from rs.context_automaton import ContextAutomaton
class ExtendedContextAutomaton(ContextAutomaton): class ExtendedContextAutomaton(ContextAutomaton):
"""Extended Context Automaton """Extended Context Automaton
@@ -73,19 +74,24 @@ class ExtendedContextAutomaton(ContextAutomaton):
print("Contexts set (context products) must be of type set or list") print("Contexts set (context products) must be of type set or list")
if not self.is_valid_rs_set(ctx_reactants): if not self.is_valid_rs_set(ctx_reactants):
raise RuntimeError("one of the entities in the reactants set is unknown (undefined)!") raise RuntimeError(
"one of the entities in the reactants set is unknown (undefined)!")
if not self.is_valid_rs_set(ctx_inhibitors): if not self.is_valid_rs_set(ctx_inhibitors):
raise RuntimeError("one of the entities in the inhibitors set is unknown (undefined)!") raise RuntimeError(
"one of the entities in the inhibitors set is unknown (undefined)!")
if not self.is_valid_rs_set(ctx_products): if not self.is_valid_rs_set(ctx_products):
raise RuntimeError("one of the entities in the context set is unknown (undefined)!") raise RuntimeError(
"one of the entities in the context set is unknown (undefined)!")
if not self.is_state(src): if not self.is_state(src):
raise RuntimeError("\"" + src + "\" is an unknown (undefined) state") raise RuntimeError(
"\"" + src + "\" is an unknown (undefined) state")
if not self.is_state(dst): if not self.is_state(dst):
raise RuntimeError("\"" + dst + "\" is an unknown (undefined) state") raise RuntimeError(
"\"" + dst + "\" is an unknown (undefined) state")
src_id = self.get_state_id(src) src_id = self.get_state_id(src)
dst_id = self.get_state_id(dst) dst_id = self.get_state_id(dst)
@@ -113,7 +119,8 @@ class ExtendedContextAutomaton(ContextAutomaton):
for src_id, act_id, reaction, dst_id in self._transitions: for src_id, act_id, reaction, dst_id in self._transitions:
str_transition = self.get_state_name(src_id) + " --( " str_transition = self.get_state_name(src_id) + " --( "
str_transition += "<" + self.get_actions_str(act_id) + "> | " str_transition += "<" + self.get_actions_str(act_id) + "> | "
str_transition += "( " + self.rsset2str(reaction[0]) + "," + self.rsset2str(reaction[1]) + "," + self.rsset2str(reaction[2]) + " )" str_transition += "( " + self.rsset2str(reaction[0]) + "," + self.rsset2str(
reaction[1]) + "," + self.rsset2str(reaction[2]) + " )"
str_transition += " )--> " + self.get_state_name(dst_id) str_transition += " )--> " + self.get_state_name(dst_id)
print(" - " + str_transition) print(" - " + str_transition)
@@ -131,7 +138,8 @@ class ExtendedContextAutomaton(ContextAutomaton):
try: try:
return self._actions.index(action_name) return self._actions.index(action_name)
except ValueError: except ValueError:
print_error("Undefined context automaton action: " + repr(action_name)) print_error("Undefined context automaton action: " +
repr(action_name))
exit(1) exit(1)
def get_action_name(self, action_id): def get_action_name(self, action_id):

View File

@@ -1,6 +1,7 @@
from sys import exit from sys import exit
from colour import * from colour import *
class NetworkOfContextAutomata(object): class NetworkOfContextAutomata(object):
def __init__(self, reaction_system, context_automata): def __init__(self, reaction_system, context_automata):
@@ -42,11 +43,15 @@ class NetworkOfContextAutomata(object):
for automaton in self.automata: for automaton in self.automata:
if automaton.reaction_system != self._reaction_system: if automaton.reaction_system != self._reaction_system:
print_error("Mismatching reaction system used in \"" + str(automaton.name) + "\"!!!") print_error(
"Mismatching reaction system used in \"" +
str(automaton.name) + "\"!!!")
exit(1) exit(1)
def show_prod_entities(self): def show_prod_entities(self):
print(C_MARK_INFO + " Possible context-products for the network of automata:") print(
C_MARK_INFO +
" Possible context-products for the network of automata:")
for entity in self.prod_entities: for entity in self.prod_entities:
print(" - " + self._reaction_system.get_entity_name(entity)) print(" - " + self._reaction_system.get_entity_name(entity))
@@ -90,7 +95,8 @@ class NetworkOfContextAutomata(object):
for entity in aut.prod_entities: for entity in aut.prod_entities:
self._actions_for_products.setdefault(entity, set()) self._actions_for_products.setdefault(entity, set())
self._actions_for_products[entity] |= aut.get_actions_producing_entity(entity) self._actions_for_products[entity] |= aut.get_actions_producing_entity(
entity)
def show(self): def show(self):
print() print()

View File

@@ -1,6 +1,7 @@
from sys import exit from sys import exit
from colour import * from colour import *
class ReactionSystem(object): class ReactionSystem(object):
def __init__(self): def __init__(self):
@@ -11,7 +12,7 @@ class ReactionSystem(object):
# self.reactions_by_agents = [] # each element is 'reactions_by_prod' # self.reactions_by_agents = [] # each element is 'reactions_by_prod'
self.reactions_by_prod = None self.reactions_by_prod = None
## legacy: # legacy:
self.init_contexts = [] self.init_contexts = []
self.context_entities = [] self.context_entities = []
@@ -29,7 +30,8 @@ class ReactionSystem(object):
def assume_not_in_bgset(self, name): def assume_not_in_bgset(self, name):
if self.is_in_background_set(name): if self.is_in_background_set(name):
raise RuntimeError("The entity " + name + " is already on the list") raise RuntimeError(
"The entity " + name + " is already on the list")
def add_bg_set_entity(self, name): def add_bg_set_entity(self, name):
self.assume_not_in_bgset(name) self.assume_not_in_bgset(name)
@@ -129,9 +131,11 @@ class ReactionSystem(object):
def show_reactions(self, soft=False): def show_reactions(self, soft=False):
print(C_MARK_INFO + " Reactions:") print(C_MARK_INFO + " Reactions:")
if soft and len(self.reactions) > 50: if soft and len(self.reactions) > 50:
print(" -> there are more than 50 reactions (" + str(len(self.reactions)) + ")") print(" -> there are more than 50 reactions (" +
str(len(self.reactions)) + ")")
else: else:
print(" "*4 + "{0: ^35}{1: ^25}{2: ^15}".format("reactants"," inhibitors"," products")) print(
" "*4 + "{0: ^35}{1: ^25}{2: ^15}".format("reactants", " inhibitors", " products"))
for reaction in self.reactions: for reaction in self.reactions:
# print("\t( R={" + self.state_to_str(reaction[0]) + "}, I={" + self.state_to_str(reaction[1]) + "}, P={" + self.state_to_str(reaction[2]) + "} )") # print("\t( R={" + self.state_to_str(reaction[0]) + "}, I={" + self.state_to_str(reaction[1]) + "}, P={" + self.state_to_str(reaction[2]) + "} )")
print(" " + "- {0: ^35}{1: ^25}{2: ^15}".format("{ " + self.state_to_str(reaction[0]) + " }", print(" " + "- {0: ^35}{1: ^25}{2: ^15}".format("{ " + self.state_to_str(reaction[0]) + " }",
@@ -139,7 +143,8 @@ class ReactionSystem(object):
" { " + self.state_to_str(reaction[2]) + " }")) " { " + self.state_to_str(reaction[2]) + " }"))
def show_background_set(self): def show_background_set(self):
print(C_MARK_INFO + " Background set: {" + self.entities_names_set_to_str(self.background_set) + "}") print(
C_MARK_INFO + " Background set: {" + self.entities_names_set_to_str(self.background_set) + "}")
def show_initial_contexts(self): def show_initial_contexts(self):
if len(self.init_contexts) > 0: if len(self.init_contexts) > 0:
@@ -149,7 +154,8 @@ class ReactionSystem(object):
def show_context_entities(self): def show_context_entities(self):
if len(self.context_entities) > 0: if len(self.context_entities) > 0:
print(C_MARK_INFO + " Context entities: " + self.entities_ids_set_to_str(self.context_entities)) print(
C_MARK_INFO + " Context entities: " + self.entities_ids_set_to_str(self.context_entities))
def show(self, soft=False): def show(self, soft=False):
@@ -175,7 +181,8 @@ class ReactionSystem(object):
reactions_by_prod[prod_entity] = [] reactions_by_prod[prod_entity] = []
for reaction in self.reactions: for reaction in self.reactions:
if prod_entity in reaction[2]: if prod_entity in reaction[2]:
reactions_by_prod[prod_entity].append([reaction[0],reaction[1]]) reactions_by_prod[prod_entity].append(
[reaction[0], reaction[1]])
# save in cache # save in cache
self.reactions_by_prod = reactions_by_prod self.reactions_by_prod = reactions_by_prod

View File

@@ -2,6 +2,7 @@ from rs.reaction_system_with_concentrations import ReactionSystemWithConcentrati
from rs.reaction_system_with_concentrations_param import ReactionSystemWithConcentrationsParam from rs.reaction_system_with_concentrations_param import ReactionSystemWithConcentrationsParam
from rs.context_automaton_with_concentrations import ContextAutomatonWithConcentrations from rs.context_automaton_with_concentrations import ContextAutomatonWithConcentrations
class ReactionSystemWithAutomaton(object): class ReactionSystemWithAutomaton(object):
def __init__(self, reaction_system, context_automaton): def __init__(self, reaction_system, context_automaton):
@@ -42,4 +43,3 @@ class ReactionSystemWithAutomaton(object):
oca = self.ca.get_automaton_with_flat_contexts(ors) oca = self.ca.get_automaton_with_flat_contexts(ors)
return ReactionSystemWithAutomaton(ors, oca) return ReactionSystemWithAutomaton(ors, oca)

View File

@@ -3,6 +3,7 @@ from colour import *
from rs.reaction_system import ReactionSystem from rs.reaction_system import ReactionSystem
class ReactionSystemWithConcentrations(ReactionSystem): class ReactionSystemWithConcentrations(ReactionSystem):
def __init__(self): def __init__(self):
@@ -25,7 +26,8 @@ class ReactionSystemWithConcentrations(ReactionSystem):
name = e name = e
print("\nWARNING: no maximal concentration level specified for:", e, "\n") print("\nWARNING: no maximal concentration level specified for:", e, "\n")
else: else:
raise RuntimeError("Bad entity type when adding background set element") raise RuntimeError(
"Bad entity type when adding background set element")
self.assume_not_in_bgset(name) self.assume_not_in_bgset(name)
self.background_set.append(name) self.background_set.append(name)
@@ -67,7 +69,8 @@ class ReactionSystemWithConcentrations(ReactionSystem):
def has_non_zero_concentration(self, elem): def has_non_zero_concentration(self, elem):
if elem[1] < 1: if elem[1] < 1:
raise RuntimeError("Unexpected concentration level in state: " + str(elem)) raise RuntimeError(
"Unexpected concentration level in state: " + str(elem))
def process_rip(self, R, I, P, ignore_empty_R=False): def process_rip(self, R, I, P, ignore_empty_R=False):
"""Chcecks concentration levels and converts entities names into their ids""" """Chcecks concentration levels and converts entities names into their ids"""
@@ -119,18 +122,22 @@ class ReactionSystemWithConcentrations(ReactionSystem):
def add_reaction_inc(self, incr_entity, incrementer, R, I): def add_reaction_inc(self, incr_entity, incrementer, R, I):
"""Adds a macro/meta reaction for increasing the value of incr_entity""" """Adds a macro/meta reaction for increasing the value of incr_entity"""
reactants,inhibitors,products = self.process_rip(R,I,[],ignore_empty_R=True) reactants, inhibitors, products = self.process_rip(
R, I, [], ignore_empty_R=True)
incr_entity_id = self.get_entity_id(incr_entity) incr_entity_id = self.get_entity_id(incr_entity)
self.meta_reactions.setdefault(incr_entity_id, []) self.meta_reactions.setdefault(incr_entity_id, [])
self.meta_reactions[incr_entity_id].append(("inc", self.get_entity_id(incrementer), reactants, inhibitors)) self.meta_reactions[incr_entity_id].append(
("inc", self.get_entity_id(incrementer), reactants, inhibitors))
def add_reaction_dec(self, decr_entity, decrementer, R, I): def add_reaction_dec(self, decr_entity, decrementer, R, I):
"""Adds a macro/meta reaction for decreasing the value of incr_entity""" """Adds a macro/meta reaction for decreasing the value of incr_entity"""
reactants,inhibitors,products = self.process_rip(R,I,[],ignore_empty_R=True) reactants, inhibitors, products = self.process_rip(
R, I, [], ignore_empty_R=True)
decr_entity_id = self.get_entity_id(decr_entity) decr_entity_id = self.get_entity_id(decr_entity)
self.meta_reactions.setdefault(decr_entity_id, []) self.meta_reactions.setdefault(decr_entity_id, [])
self.meta_reactions[decr_entity_id].append(("dec", self.get_entity_id(decrementer), reactants, inhibitors)) self.meta_reactions[decr_entity_id].append(
("dec", self.get_entity_id(decrementer), reactants, inhibitors))
def add_permanency(self, ent, I): def add_permanency(self, ent, I):
"""Sets entity to be permanent unless it is inhibited""" """Sets entity to be permanent unless it is inhibited"""
@@ -138,7 +145,8 @@ class ReactionSystemWithConcentrations(ReactionSystem):
ent_id = self.get_entity_id(ent) ent_id = self.get_entity_id(ent)
if ent_id in self.permanent_entities: if ent_id in self.permanent_entities:
raise RuntimeError("Permanency for {0} already defined.".format(ent)) raise RuntimeError(
"Permanency for {0} already defined.".format(ent))
inhibitors = self.process_rip([], I, [], ignore_empty_R=True)[1] inhibitors = self.process_rip([], I, [], ignore_empty_R=True)[1]
self.permanent_entities[ent_id] = inhibitors self.permanent_entities[ent_id] = inhibitors
@@ -168,27 +176,32 @@ class ReactionSystemWithConcentrations(ReactionSystem):
return s return s
def show_background_set(self): def show_background_set(self):
print(C_MARK_INFO + " Background set: {" + self.entities_names_set_to_str(self.background_set) + "}") print(
C_MARK_INFO + " Background set: {" + self.entities_names_set_to_str(self.background_set) + "}")
def show_meta_reactions(self): def show_meta_reactions(self):
print(C_MARK_INFO + " Meta reactions:") print(C_MARK_INFO + " Meta reactions:")
for param_ent, reactions in self.meta_reactions.items(): for param_ent, reactions in self.meta_reactions.items():
for r_type, command, reactants, inhibitors in reactions: for r_type, command, reactants, inhibitors in reactions:
if r_type == "inc" or r_type == "dec": if r_type == "inc" or r_type == "dec":
print(" - [ Type=" + repr(r_type) + " Operand=( " + self.get_entity_name(param_ent) + \ print(" - [ Type=" + repr(r_type) + " Operand=( " + self.get_entity_name(param_ent) + " ) Command=( " + self.get_entity_name(
" ) Command=( " + self.get_entity_name(command) + " ) ] -- ( R={" + self.state_to_str(reactants) + "}, I={" + self.state_to_str(inhibitors) + "} )") command) + " ) ] -- ( R={" + self.state_to_str(reactants) + "}, I={" + self.state_to_str(inhibitors) + "} )")
else: else:
raise RuntimeError("Unknown meta-reaction type: " + repr(r_type)) raise RuntimeError(
"Unknown meta-reaction type: " + repr(r_type))
def show_max_concentrations(self): def show_max_concentrations(self):
print(C_MARK_INFO + " Maximal allowed concentration levels (for optimized translation to RS):") print(
C_MARK_INFO +
" Maximal allowed concentration levels (for optimized translation to RS):")
for e, max_conc in self.max_conc_per_ent.items(): for e, max_conc in self.max_conc_per_ent.items():
print(" - {0:^20} = {1:<6}".format(self.get_entity_name(e), max_conc)) print(" - {0:^20} = {1:<6}".format(self.get_entity_name(e), max_conc))
def show_permanent_entities(self): def show_permanent_entities(self):
print(C_MARK_INFO + " Permanent entities:") print(C_MARK_INFO + " Permanent entities:")
for e, inhibitors in self.permanent_entities.items(): for e, inhibitors in self.permanent_entities.items():
print(" - {0:^20}{1:<6}".format(self.get_entity_name(e) + ": ","I={" + self.state_to_str(inhibitors) + "}")) print(" - {0:^20}{1:<6}".format(self.get_entity_name(e) + ": ",
"I={" + self.state_to_str(inhibitors) + "}"))
def show(self, soft=False): def show(self, soft=False):
self.show_background_set() self.show_background_set()
@@ -207,7 +220,8 @@ class ReactionSystemWithConcentrations(ReactionSystem):
for reaction in self.reactions: for reaction in self.reactions:
product_entities = [e for e, c in reaction[2]] product_entities = [e for e, c in reaction[2]]
producible_entities = producible_entities.union(set(product_entities)) producible_entities = producible_entities.union(
set(product_entities))
reactions_by_prod = {} reactions_by_prod = {}
@@ -235,10 +249,11 @@ class ReactionSystemWithConcentrations(ReactionSystem):
break break
if insert_place == None: # empty or the is only one element which is smaller than the element being added if insert_place == None: # empty or the is only one element which is smaller than the element being added
rcts_for_p_e.append((reactants, inhibitors, products)) # we append (to the end) # we append (to the end)
rcts_for_p_e.append((reactants, inhibitors, products))
else: else:
rcts_for_p_e.insert(insert_place,(reactants, inhibitors, products)) rcts_for_p_e.insert(
insert_place, (reactants, inhibitors, products))
# save in cache # save in cache
self.reactions_by_prod = reactions_by_prod self.reactions_by_prod = reactions_by_prod
@@ -295,7 +310,9 @@ class ReactionSystemWithConcentrations(ReactionSystem):
if command in self.max_conc_per_ent: if command in self.max_conc_per_ent:
max_cmd_c = self.max_conc_per_ent[command] max_cmd_c = self.max_conc_per_ent[command]
else: else:
print("WARNING:\n\tThere is no maximal concentration level defined for " + self.get_entity_name(command)) print(
"WARNING:\n\tThere is no maximal concentration level defined for "
+ self.get_entity_name(command))
print("\tThis is a very bad idea -- expect degraded performance\n") print("\tThis is a very bad idea -- expect degraded performance\n")
for l in range(1, max_cmd_c+1): for l in range(1, max_cmd_c+1):
@@ -314,12 +331,16 @@ class ReactionSystemWithConcentrations(ReactionSystem):
new_products = [] new_products = []
succ_value = i+l succ_value = i+l
for j in range(1, succ_value+1): for j in range(1, succ_value+1):
if j > self.max_concentration: break if j > self.max_concentration:
break
new_p = param_ent_name + "#" + str(j) new_p = param_ent_name + "#" + str(j)
rs.ensure_bg_set_entity(new_p) rs.ensure_bg_set_entity(new_p)
new_products.append(new_p) new_products.append(new_p)
if new_products != []: if new_products != []:
rs.add_reaction(set(new_reactants + [pre_conc,cmd_ent]), set(new_inhibitors), set(new_products)) rs.add_reaction(
set(new_reactants + [pre_conc, cmd_ent]),
set(new_inhibitors),
set(new_products))
elif r_type == "dec": elif r_type == "dec":
for i in range(1, self.max_concentration+1): for i in range(1, self.max_concentration+1):
@@ -328,15 +349,20 @@ class ReactionSystemWithConcentrations(ReactionSystem):
new_products = [] new_products = []
succ_value = i-l succ_value = i-l
for j in range(1, succ_value+1): for j in range(1, succ_value+1):
if j > self.max_concentration: break if j > self.max_concentration:
break
new_p = param_ent_name + "#" + str(j) new_p = param_ent_name + "#" + str(j)
rs.ensure_bg_set_entity(new_p) rs.ensure_bg_set_entity(new_p)
new_products.append(new_p) new_products.append(new_p)
if new_products != []: if new_products != []:
rs.add_reaction(set(new_reactants + [pre_conc,cmd_ent]), set(new_inhibitors), set(new_products)) rs.add_reaction(
set(new_reactants + [pre_conc, cmd_ent]),
set(new_inhibitors),
set(new_products))
else: else:
raise RuntimeError("Unknown meta-reaction type: " + repr(r_type)) raise RuntimeError(
"Unknown meta-reaction type: " + repr(r_type))
for ent, inhibitors in self.permanent_entities.items(): for ent, inhibitors in self.permanent_entities.items():
@@ -344,7 +370,9 @@ class ReactionSystemWithConcentrations(ReactionSystem):
if ent in self.max_conc_per_ent: if ent in self.max_conc_per_ent:
max_c = self.max_conc_per_ent[ent] max_c = self.max_conc_per_ent[ent]
else: else:
print("WARNING:\n\tThere is no maximal concentration level defined for " + self.get_entity_name(ent)) print(
"WARNING:\n\tThere is no maximal concentration level defined for "
+ self.get_entity_name(ent))
print("\tThis is a very bad idea -- expect degraded performance\n") print("\tThis is a very bad idea -- expect degraded performance\n")
def e_value(i): def e_value(i):
@@ -403,4 +431,3 @@ class ReactionSystemWithAutomaton(object):
# EOF # EOF

View File

@@ -3,6 +3,7 @@ from colour import *
from rs.reaction_system import ReactionSystem from rs.reaction_system import ReactionSystem
class ParameterObj(object): class ParameterObj(object):
def __init__(self, name): def __init__(self, name):
@@ -11,12 +12,14 @@ class ParameterObj(object):
def __repr__(self): def __repr__(self):
return "@{0}".format(self.name) return "@{0}".format(self.name)
def is_param(some_object): def is_param(some_object):
if isinstance(some_object, ParameterObj): if isinstance(some_object, ParameterObj):
return True return True
else: else:
return False return False
class ReactionSystemWithConcentrationsParam(ReactionSystem): class ReactionSystemWithConcentrationsParam(ReactionSystem):
def __init__(self): def __init__(self):
@@ -182,18 +185,22 @@ class ReactionSystemWithConcentrationsParam(ReactionSystem):
def add_reaction_inc(self, incr_entity, incrementer, R, I): def add_reaction_inc(self, incr_entity, incrementer, R, I):
"""Adds a macro/meta reaction for increasing the value of incr_entity""" """Adds a macro/meta reaction for increasing the value of incr_entity"""
reactants,inhibitors,products = self.process_rip(R,I,[],ignore_empty_R=True) reactants, inhibitors, products = self.process_rip(
R, I, [], ignore_empty_R=True)
incr_entity_id = self.get_entity_id(incr_entity) incr_entity_id = self.get_entity_id(incr_entity)
self.meta_reactions.setdefault(incr_entity_id, []) self.meta_reactions.setdefault(incr_entity_id, [])
self.meta_reactions[incr_entity_id].append(("inc", self.get_entity_id(incrementer), reactants, inhibitors)) self.meta_reactions[incr_entity_id].append(
("inc", self.get_entity_id(incrementer), reactants, inhibitors))
def add_reaction_dec(self, decr_entity, decrementer, R, I): def add_reaction_dec(self, decr_entity, decrementer, R, I):
"""Adds a macro/meta reaction for decreasing the value of incr_entity""" """Adds a macro/meta reaction for decreasing the value of incr_entity"""
reactants,inhibitors,products = self.process_rip(R,I,[],ignore_empty_R=True) reactants, inhibitors, products = self.process_rip(
R, I, [], ignore_empty_R=True)
decr_entity_id = self.get_entity_id(decr_entity) decr_entity_id = self.get_entity_id(decr_entity)
self.meta_reactions.setdefault(decr_entity_id, []) self.meta_reactions.setdefault(decr_entity_id, [])
self.meta_reactions[decr_entity_id].append(("dec", self.get_entity_id(decrementer), reactants, inhibitors)) self.meta_reactions[decr_entity_id].append(
("dec", self.get_entity_id(decrementer), reactants, inhibitors))
def add_permanency(self, ent, I): def add_permanency(self, ent, I):
"""Sets entity to be permanent unless it is inhibited""" """Sets entity to be permanent unless it is inhibited"""
@@ -201,7 +208,8 @@ class ReactionSystemWithConcentrationsParam(ReactionSystem):
ent_id = self.get_entity_id(ent) ent_id = self.get_entity_id(ent)
if ent_id in self.permanent_entities: if ent_id in self.permanent_entities:
raise RuntimeError("Permanency for {0} already defined.".format(ent)) raise RuntimeError(
"Permanency for {0} already defined.".format(ent))
inhibitors = self.process_rip([], I, [], ignore_empty_R=True)[1] inhibitors = self.process_rip([], I, [], ignore_empty_R=True)[1]
self.permanent_entities[ent_id] = inhibitors self.permanent_entities[ent_id] = inhibitors
@@ -239,17 +247,19 @@ class ReactionSystemWithConcentrationsParam(ReactionSystem):
return s return s
def show_background_set(self): def show_background_set(self):
print(C_MARK_INFO + " Background set: {" + self.entities_names_set_to_str(self.background_set) + "}") print(
C_MARK_INFO + " Background set: {" + self.entities_names_set_to_str(self.background_set) + "}")
def show_meta_reactions(self): def show_meta_reactions(self):
print(C_MARK_INFO + " Meta reactions:") print(C_MARK_INFO + " Meta reactions:")
for param_ent, reactions in self.meta_reactions.items(): for param_ent, reactions in self.meta_reactions.items():
for r_type, command, reactants, inhibitors in reactions: for r_type, command, reactants, inhibitors in reactions:
if r_type == "inc" or r_type == "dec": if r_type == "inc" or r_type == "dec":
print(" - [ Type=" + repr(r_type) + " Operand=( " + self.get_entity_name(param_ent) + \ print(" - [ Type=" + repr(r_type) + " Operand=( " + self.get_entity_name(param_ent) + " ) Command=( " + self.get_entity_name(
" ) Command=( " + self.get_entity_name(command) + " ) ] -- ( R={" + self.state_to_str(reactants) + "}, I={" + self.state_to_str(inhibitors) + "} )") command) + " ) ] -- ( R={" + self.state_to_str(reactants) + "}, I={" + self.state_to_str(inhibitors) + "} )")
else: else:
raise RuntimeError("Unknown meta-reaction type: " + repr(r_type)) raise RuntimeError(
"Unknown meta-reaction type: " + repr(r_type))
def show_max_concentrations(self): def show_max_concentrations(self):
print(C_MARK_INFO + " Maximal allowed concentration levels:") print(C_MARK_INFO + " Maximal allowed concentration levels:")
@@ -259,7 +269,8 @@ class ReactionSystemWithConcentrationsParam(ReactionSystem):
def show_permanent_entities(self): def show_permanent_entities(self):
print(C_MARK_INFO + " Permanent entities:") print(C_MARK_INFO + " Permanent entities:")
for e, inhibitors in self.permanent_entities.items(): for e, inhibitors in self.permanent_entities.items():
print(" - {0:^20}{1:<6}".format(self.get_entity_name(e) + ": ","I={" + self.state_to_str(inhibitors) + "}")) print(" - {0:^20}{1:<6}".format(self.get_entity_name(e) + ": ",
"I={" + self.state_to_str(inhibitors) + "}"))
def show(self, soft=False): def show(self, soft=False):
self.show_background_set() self.show_background_set()
@@ -279,7 +290,8 @@ class ReactionSystemWithConcentrationsParam(ReactionSystem):
for reaction in self.reactions: for reaction in self.reactions:
product_entities = [e for e, c in reaction[2] if c > 0] product_entities = [e for e, c in reaction[2] if c > 0]
producible_entities = producible_entities.union(set(product_entities)) producible_entities = producible_entities.union(
set(product_entities))
return producible_entities return producible_entities

View File

@@ -1,23 +1,28 @@
from logics import * from logics import *
##### SHORTCUTS # SHORTCUTS
def bag_True(): def bag_True():
return BagDescription.f_TRUE() return BagDescription.f_TRUE()
def bag_entity(name): def bag_entity(name):
return BagDescription.f_entity(name) return BagDescription.f_entity(name)
def get_bag_if_str(arg): def get_bag_if_str(arg):
if isinstance(arg, str): if isinstance(arg, str):
return bag_entity(arg) > 0 return bag_entity(arg) > 0
else: else:
return arg return arg
def bag_Not(a0): def bag_Not(a0):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
return BagDescription.f_Not(a0) return BagDescription.f_Not(a0)
def bag_And(*args): def bag_And(*args):
assert len(args) > 1 assert len(args) > 1
last = get_bag_if_str(args[0]) last = get_bag_if_str(args[0])
@@ -26,6 +31,7 @@ def bag_And(*args):
last, get_bag_if_str(arg)) last, get_bag_if_str(arg))
return last return last
def exact_state(contained_entities, all_entities): def exact_state(contained_entities, all_entities):
""" """
Assumes 0 concentration level for all the Assumes 0 concentration level for all the
@@ -49,23 +55,28 @@ def exact_state(contained_entities, all_entities):
else: else:
assert False assert False
def ltl_F(ctx_arg, a0): def ltl_F(ctx_arg, a0):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
return Formula_rsLTL.f_F(ctx_arg, a0) return Formula_rsLTL.f_F(ctx_arg, a0)
def ltl_G(ctx_arg, a0): def ltl_G(ctx_arg, a0):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
return Formula_rsLTL.f_G(ctx_arg, a0) return Formula_rsLTL.f_G(ctx_arg, a0)
def ltl_X(ctx_arg, a0): def ltl_X(ctx_arg, a0):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
return Formula_rsLTL.f_X(ctx_arg, a0) return Formula_rsLTL.f_X(ctx_arg, a0)
def ltl_U(ctx_arg, a0, a1): def ltl_U(ctx_arg, a0, a1):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
a1 = get_bag_if_str(a1) a1 = get_bag_if_str(a1)
return Formula_rsLTL.f_U(ctx_arg, a0, a1) return Formula_rsLTL.f_U(ctx_arg, a0, a1)
def ltl_And(*args): def ltl_And(*args):
assert len(args) > 1 assert len(args) > 1
last = get_bag_if_str(args[0]) last = get_bag_if_str(args[0])
@@ -73,22 +84,25 @@ def ltl_And(*args):
last = Formula_rsLTL.f_And(last, get_bag_if_str(arg)) last = Formula_rsLTL.f_And(last, get_bag_if_str(arg))
return last return last
def ltl_Not(a0): def ltl_Not(a0):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
return Formula_rsLTL.f_Not(a0) return Formula_rsLTL.f_Not(a0)
def ltl_Implies(a0, a1): def ltl_Implies(a0, a1):
a0 = get_bag_if_str(a0) a0 = get_bag_if_str(a0)
a1 = get_bag_if_str(a1) a1 = get_bag_if_str(a1)
return Formula_rsLTL.f_Implies(a0, a1) return Formula_rsLTL.f_Implies(a0, a1)
def param_entity(param, entity_name): def param_entity(param, entity_name):
return ParamConstraint.f_param_ent(param, entity_name) return ParamConstraint.f_param_ent(param, entity_name)
def param_And(*args): def param_And(*args):
assert len(args) > 1 assert len(args) > 1
last = args[0] last = args[0]
for arg in args[1:]: for arg in args[1:]:
last = ParamConstraint.f_And(last, arg) last = ParamConstraint.f_And(last, arg)
return last return last

View File

@@ -51,8 +51,10 @@ def main():
parser.add_argument("-v", "--verbose", parser.add_argument("-v", "--verbose",
help="turn verbosity on", action="store_true") help="turn verbosity on", action="store_true")
parser.add_argument("-o", "--optimise", parser.add_argument("-o", "--optimise",
help="minimise the parametric computation result", action="store_true") help="minimise the parametric computation result",
parser.add_argument("-n", "--scaling-parameter", action="store_true")
parser.add_argument(
"-n", "--scaling-parameter",
help="scaling parameter value (used in some benchmarks)") help="scaling parameter value (used in some benchmarks)")
parser.add_argument("-s", "--special_mode", parser.add_argument("-s", "--special_mode",
help="special mode (used in some benchmarks)") help="special mode (used in some benchmarks)")
@@ -64,6 +66,7 @@ def main():
################################################################## ##################################################################
if __name__ == "__main__": if __name__ == "__main__":
try: try:
if profiling: if profiling:

View File

@@ -3,6 +3,7 @@
import sys import sys
from os import listdir from os import listdir
def proc_files(files): def proc_files(files):
fs = [] fs = []
@@ -45,6 +46,7 @@ def proc_files(files):
result.append("") result.append("")
return result return result
def proc_dirs(dirs): def proc_dirs(dirs):
first_dir = dirs[0] first_dir = dirs[0]
@@ -55,6 +57,7 @@ def proc_dirs(dirs):
with open(f, "w") as outfile: with open(f, "w") as outfile:
outfile.write("\n".join(avg_out)) outfile.write("\n".join(avg_out))
def main(): def main():
proc_dirs(sys.argv[1:]) proc_dirs(sys.argv[1:])
@@ -64,4 +67,3 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -7,6 +7,7 @@ from time import time
from sys import stdout from sys import stdout
import resource import resource
class SmtCheckerRS(object): class SmtCheckerRS(object):
def __init__(self, rsca): def __init__(self, rsca):
@@ -71,7 +72,8 @@ class SmtCheckerRS(object):
rs_init_state_enc = True rs_init_state_enc = True
for v in self.v[level]: for v in self.v[level]:
rs_init_state_enc = simplify(And(rs_init_state_enc, Not(v))) # the initial state is empty # the initial state is empty
rs_init_state_enc = simplify(And(rs_init_state_enc, Not(v)))
return rs_init_state_enc return rs_init_state_enc
def enc_context_controller_init_state(self, level): def enc_context_controller_init_state(self, level):
@@ -82,7 +84,8 @@ class SmtCheckerRS(object):
def enc_init_state(self, level): def enc_init_state(self, level):
"""Encodes the initial state at the given level""" """Encodes the initial state at the given level"""
init_state_enc = simplify(And(self.enc_rs_init_state(level), self.enc_context_controller_init_state(level))) init_state_enc = simplify(And(self.enc_rs_init_state(
level), self.enc_context_controller_init_state(level)))
return init_state_enc return init_state_enc
@@ -99,13 +102,14 @@ class SmtCheckerRS(object):
enc_reactants = True enc_reactants = True
enc_inhibitors = True enc_inhibitors = True
for reactant in reactants: for reactant in reactants:
enc_reactants = simplify(And(enc_reactants, enc_reactants = simplify(And(enc_reactants, Or(
Or(self.v[level][reactant], self.v_ctx[level][reactant]))) self.v[level][reactant], self.v_ctx[level][reactant])))
for inhibitor in inhibitors: for inhibitor in inhibitors:
enc_inhibitors = simplify(And(enc_inhibitors, enc_inhibitors = simplify(And(enc_inhibitors, Not(
Not(Or(self.v[level][inhibitor], self.v_ctx[level][inhibitor])))) Or(self.v[level][inhibitor], self.v_ctx[level][inhibitor]))))
enc_rct_prod = simplify(Or(enc_rct_prod, And(enc_reactants, enc_inhibitors))) enc_rct_prod = simplify(
Or(enc_rct_prod, And(enc_reactants, enc_inhibitors)))
return enc_rct_prod return enc_rct_prod
@@ -114,15 +118,19 @@ class SmtCheckerRS(object):
enc_enab_cond = self.enc_enabledness(level, prod_entity) enc_enab_cond = self.enc_enabledness(level, prod_entity)
enc_ent_prod = Or(And(enc_enab_cond, self.v[level+1][prod_entity]), enc_ent_prod = Or(
And(Not(enc_enab_cond), Not(self.v[level+1][prod_entity]))) And(enc_enab_cond, self.v[level + 1][prod_entity]),
And(Not(enc_enab_cond),
Not(self.v[level + 1][prod_entity])))
return simplify(enc_ent_prod) return simplify(enc_ent_prod)
def enc_transition_relation(self, level): def enc_transition_relation(self, level):
"""Encodes the combined transition relation""" """Encodes the combined transition relation"""
return simplify(And(self.enc_rs_trans(level), self.enc_automaton_trans(level))) return simplify(
And(self.enc_rs_trans(level),
self.enc_automaton_trans(level)))
def enc_rs_trans(self, level): def enc_rs_trans(self, level):
"""Encodes the transition relation""" """Encodes the transition relation"""
@@ -134,10 +142,12 @@ class SmtCheckerRS(object):
for prod_entity in self.rs.get_reactions_by_product(): for prod_entity in self.rs.get_reactions_by_product():
unused_entities.remove(prod_entity) unused_entities.remove(prod_entity)
enc_trans = simplify(And(enc_trans, self.enc_entity_production(level, prod_entity))) enc_trans = simplify(
And(enc_trans, self.enc_entity_production(level, prod_entity)))
for prod_entity in unused_entities: for prod_entity in unused_entities:
enc_trans = simplify(And(enc_trans, Not(self.v[level+1][prod_entity]))) enc_trans = simplify(
And(enc_trans, Not(self.v[level+1][prod_entity])))
return enc_trans return enc_trans
@@ -168,7 +178,8 @@ class SmtCheckerRS(object):
enc_trans = False enc_trans = False
for transition in self.ca.transitions: for transition in self.ca.transitions:
enc_trans = simplify(Or(enc_trans, self.enc_automaton_single_trans(level, transition))) enc_trans = simplify(
Or(enc_trans, self.enc_automaton_single_trans(level, transition)))
return enc_trans return enc_trans
@@ -219,7 +230,6 @@ class SmtCheckerRS(object):
return simplify(enc) return simplify(enc)
def decode_witness(self, max_level, print_model=False): def decode_witness(self, max_level, print_model=False):
m = self.solver.model() m = self.solver.model()
@@ -245,7 +255,8 @@ class SmtCheckerRS(object):
print(" " + self.rs.get_entity_name(var_id), end="") print(" " + self.rs.get_entity_name(var_id), end="")
print(" }") print(" }")
def check_reachability(self, state, print_witness=True, print_time=True, print_mem=True): def check_reachability(
self, state, print_witness=True, print_time=True, print_mem=True):
"""Main testing function""" """Main testing function"""
if not type(state) is tuple: if not type(state) is tuple:
@@ -293,7 +304,11 @@ class SmtCheckerRS(object):
print("[i] Time: " + repr(self.verification_time)) print("[i] Time: " + repr(self.verification_time))
if print_mem: if print_mem:
print("[i] Memory: " + repr(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/(1024*1024)) + " MB") print(
"[i] Memory: " +
repr(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss /
(1024 * 1024)) + " MB")
def get_verification_time(self): def get_verification_time(self):
return self.verification_time return self.verification_time

View File

@@ -14,6 +14,7 @@ from logics import rsLTL_Encoder
# def simplify(x): # def simplify(x):
# return x # return x
class SmtCheckerRSC(object): class SmtCheckerRSC(object):
def __init__(self, rsca): def __init__(self, rsca):
@@ -90,7 +91,8 @@ class SmtCheckerRSC(object):
v = self.v[level][e_i] v = self.v[level][e_i]
v_ctx = self.v_ctx[level][e_i] v_ctx = self.v_ctx[level][e_i]
e_max = self.rs.get_max_concentration_level(e_i) e_max = self.rs.get_max_concentration_level(e_i)
enc_nz = simplify(And(enc_nz, v >= 0, v_ctx >= 0, v <= e_max, v_ctx <= e_max)) enc_nz = simplify(
And(enc_nz, v >= 0, v_ctx >= 0, v <= e_max, v_ctx <= e_max))
return enc_nz return enc_nz
@@ -100,7 +102,8 @@ class SmtCheckerRSC(object):
rs_init_state_enc = True rs_init_state_enc = True
for v in self.v[level]: for v in self.v[level]:
rs_init_state_enc = simplify(And(rs_init_state_enc, v == 0)) # the initial concentration levels are zeroed # the initial concentration levels are zeroed
rs_init_state_enc = simplify(And(rs_init_state_enc, v == 0))
ca_init_state_enc = self.ca_state[level] == self.ca.get_init_state_id() ca_init_state_enc = self.ca_state[level] == self.ca.get_init_state_id()
@@ -113,7 +116,8 @@ class SmtCheckerRSC(object):
rcts_for_prod_entity = [] rcts_for_prod_entity = []
if prod_entity in self.rs.get_reactions_by_product(): if prod_entity in self.rs.get_reactions_by_product():
rcts_for_prod_entity = self.rs.get_reactions_by_product()[prod_entity] rcts_for_prod_entity = self.rs.get_reactions_by_product()[
prod_entity]
meta_reactions = [] meta_reactions = []
if prod_entity in self.rs.meta_reactions: if prod_entity in self.rs.meta_reactions:
@@ -124,7 +128,8 @@ class SmtCheckerRSC(object):
permanency_inhibition = self.rs.permanent_entities[prod_entity] permanency_inhibition = self.rs.permanent_entities[prod_entity]
if rcts_for_prod_entity == [] and meta_reactions == []: if rcts_for_prod_entity == [] and meta_reactions == []:
return simplify(self.v[level+1][prod_entity] == 0) # this should never happen # this should never happen
return simplify(self.v[level+1][prod_entity] == 0)
enc_enabledness = False enc_enabledness = False
@@ -138,20 +143,22 @@ class SmtCheckerRSC(object):
enc_reactants = True enc_reactants = True
for reactant, concentration in reactants: for reactant, concentration in reactants:
enc_reactants = simplify(And(enc_reactants, enc_reactants = simplify(And(enc_reactants, Or(
Or(self.v[level][reactant] >= concentration, self.v_ctx[level][reactant] >= concentration))) self.v[level][reactant] >= concentration, self.v_ctx[level][reactant] >= concentration)))
enc_inhibitors = True enc_inhibitors = True
for inhibitor, concentration in inhibitors: for inhibitor, concentration in inhibitors:
enc_inhibitors = simplify(And(enc_inhibitors, enc_inhibitors = simplify(And(enc_inhibitors, And(
And(self.v[level][inhibitor] < concentration, self.v_ctx[level][inhibitor] < concentration))) self.v[level][inhibitor] < concentration, self.v_ctx[level][inhibitor] < concentration)))
enc_rct_enabled = And(enc_reactants, enc_inhibitors) enc_rct_enabled = And(enc_reactants, enc_inhibitors)
enc_products = self.v[level+1][products[0][0]] == products[0][1] enc_products = self.v[level+1][products[0][0]] == products[0][1]
enc_rct_prod = simplify(If(enc_rct_enabled, enc_products, enc_rct_prod)) enc_rct_prod = simplify(
If(enc_rct_enabled, enc_products, enc_rct_prod))
enc_enabledness = simplify(Or(enc_enabledness, enc_rct_enabled)) enc_enabledness = simplify(Or(enc_enabledness, enc_rct_enabled))
enc_ordinary_reactions_enabledness = simplify(Or(enc_ordinary_reactions_enabledness,enc_rct_enabled)) enc_ordinary_reactions_enabledness = simplify(
Or(enc_ordinary_reactions_enabledness, enc_rct_enabled))
# -------- meta reactions --------------------------------------------------- # -------- meta reactions ---------------------------------------------------
@@ -164,61 +171,100 @@ class SmtCheckerRSC(object):
enc_inhibitors = True enc_inhibitors = True
for reactant, concentration in reactants: for reactant, concentration in reactants:
enc_reactants = simplify(And(enc_reactants, enc_reactants = simplify(And(enc_reactants, Or(
Or(self.v[level][reactant] >= concentration, self.v_ctx[level][reactant] >= concentration))) self.v[level][reactant] >= concentration, self.v_ctx[level][reactant] >= concentration)))
# command entity needs to be present (with concentration level > 0) in order to perform the operation # command entity needs to be present (with concentration level > 0) in order to perform the operation
enc_reactants = simplify(And(enc_reactants, enc_reactants = simplify(And(enc_reactants, Or(
Or(self.v[level][command_entity] > 0, self.v_ctx[level][command_entity] > 0))) self.v[level][command_entity] > 0, self.v_ctx[level][command_entity] > 0)))
for inhibitor, concentration in inhibitors: for inhibitor, concentration in inhibitors:
enc_inhibitors = simplify(And(enc_inhibitors, enc_inhibitors = simplify(And(enc_inhibitors, And(
And(self.v[level][inhibitor] < concentration, self.v_ctx[level][inhibitor] < concentration))) self.v[level][inhibitor] < concentration, self.v_ctx[level][inhibitor] < concentration)))
if r_type == "inc": if r_type == "inc":
value_after_inc = If(self.v[level][prod_entity]>self.v_ctx[level][prod_entity],self.v[level][prod_entity],self.v_ctx[level][prod_entity]) + \ value_after_inc = If(
If(self.v[level][command_entity]>self.v_ctx[level][command_entity],self.v[level][command_entity],self.v_ctx[level][command_entity]) self.v[level][prod_entity] > self.v_ctx[level]
[prod_entity],
self.v[level][prod_entity],
self.v_ctx[level][prod_entity]) + If(
self.v[level][command_entity] > self.
v_ctx[level][command_entity],
self.v[level][command_entity],
self.v_ctx[level][command_entity])
enc_products = self.v[level+1][prod_entity] == value_after_inc enc_products = self.v[level+1][prod_entity] == value_after_inc
elif r_type == "dec": elif r_type == "dec":
value_after_dec = simplify(If(self.v[level][prod_entity]>self.v_ctx[level][prod_entity],self.v[level][prod_entity],self.v_ctx[level][prod_entity]) - \ value_after_dec = simplify(
If(self.v[level][command_entity]>self.v_ctx[level][command_entity],self.v[level][command_entity],self.v_ctx[level][command_entity])) If(
enc_products = self.v[level+1][prod_entity] == If(value_after_dec < 0, 0, value_after_dec) self.v[level][prod_entity] >
self.v_ctx[level]
[prod_entity],
self.v[level][prod_entity],
self.v_ctx[level]
[prod_entity]) -
If(
self.v[level]
[command_entity] > self.
v_ctx[level][command_entity],
self.v[level]
[command_entity],
self.v_ctx[level]
[command_entity]))
enc_products = self.v[level+1][prod_entity] == If(
value_after_dec < 0, 0, value_after_dec)
else: else:
raise RuntimeError("Unknown meta-reaction type: " + repr(r_type)) raise RuntimeError(
"Unknown meta-reaction type: " + repr(r_type))
enc_meta_reaction_enabledness = And(enc_reactants, enc_inhibitors, Not(enc_ordinary_reactions_enabledness)) enc_meta_reaction_enabledness = And(
enc_enabledness = simplify(Or(enc_enabledness, enc_meta_reaction_enabledness)) enc_reactants, enc_inhibitors,
enc_rct_prod = simplify(Or(enc_rct_prod, And(enc_meta_reaction_enabledness, enc_products))) Not(enc_ordinary_reactions_enabledness))
enc_enabledness = simplify(
Or(enc_enabledness, enc_meta_reaction_enabledness))
enc_rct_prod = simplify(Or(enc_rct_prod, And(
enc_meta_reaction_enabledness, enc_products)))
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
if not permanency_inhibition == None: if not permanency_inhibition == None:
enc_reactants = Or(self.v[level][prod_entity] >= concentration, self.v_ctx[level][prod_entity] >= concentration) enc_reactants = Or(self.v[level][prod_entity] >= concentration,
self.v_ctx[level][prod_entity] >= concentration)
enc_inhibitors = True enc_inhibitors = True
for inhibitor, concentration in permanency_inhibition: for inhibitor, concentration in permanency_inhibition:
enc_inhibitors = simplify(And(enc_inhibitors, enc_inhibitors = simplify(And(enc_inhibitors, And(
And(self.v[level][inhibitor] < concentration, self.v_ctx[level][inhibitor] < concentration))) self.v[level][inhibitor] < concentration, self.v_ctx[level][inhibitor] < concentration)))
enc_products = simplify(self.v[level+1][prod_entity] == \ enc_products = simplify(
If(self.v[level][prod_entity] > self.v_ctx[level][prod_entity],self.v[level][prod_entity],self.v_ctx[level][prod_entity])) self.v[level + 1][prod_entity] ==
If(
self.v[level][prod_entity] > self.v_ctx[level]
[prod_entity],
self.v[level][prod_entity],
self.v_ctx[level][prod_entity]))
enc_permanency_enabledness = And(enc_reactants, enc_inhibitors, Not(enc_ordinary_reactions_enabledness)) enc_permanency_enabledness = And(
enc_enabledness = simplify(Or(enc_enabledness, enc_permanency_enabledness)) enc_reactants, enc_inhibitors,
Not(enc_ordinary_reactions_enabledness))
enc_enabledness = simplify(
Or(enc_enabledness, enc_permanency_enabledness))
enc_permanency = And(enc_permanency_enabledness, enc_products) enc_permanency = And(enc_permanency_enabledness, enc_products)
enc_rct_prod = simplify(Or(enc_rct_prod, enc_permanency)) enc_rct_prod = simplify(Or(enc_rct_prod, enc_permanency))
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
enc_when_to_produce_zero_conc = simplify(And(Not(enc_enabledness), self.v[level+1][prod_entity] == 0)) enc_when_to_produce_zero_conc = simplify(
And(Not(enc_enabledness), self.v[level+1][prod_entity] == 0))
enc_rct_prod = Or(enc_rct_prod, enc_when_to_produce_zero_conc) enc_rct_prod = Or(enc_rct_prod, enc_when_to_produce_zero_conc)
return enc_rct_prod return enc_rct_prod
def enc_transition_relation(self, level): def enc_transition_relation(self, level):
return simplify(And(self.enc_rs_trans(level), self.enc_automaton_trans(level))) return simplify(
And(self.enc_rs_trans(level),
self.enc_automaton_trans(level)))
def enc_rs_trans(self, level): def enc_rs_trans(self, level):
"""Encodes the transition relation""" """Encodes the transition relation"""
@@ -232,10 +278,12 @@ class SmtCheckerRSC(object):
for prod_entity in chain(reactions, meta_reactions): for prod_entity in chain(reactions, meta_reactions):
unused_entities.discard(prod_entity) unused_entities.discard(prod_entity)
enc_trans = simplify(And(enc_trans, self.enc_produced_concentration(level, prod_entity))) enc_trans = simplify(
And(enc_trans, self.enc_produced_concentration(level, prod_entity)))
for prod_entity in unused_entities: for prod_entity in unused_entities:
enc_trans = simplify(And(enc_trans, self.v[level+1][prod_entity] == 0)) enc_trans = simplify(
And(enc_trans, self.v[level+1][prod_entity] == 0))
return enc_trans return enc_trans
@@ -312,9 +360,12 @@ class SmtCheckerRSC(object):
for var_id in range(len(self.v[level])): for var_id in range(len(self.v[level])):
var_rep = repr(m[self.v[level][var_id]]) var_rep = repr(m[self.v[level][var_id]])
if not var_rep.isdigit(): if not var_rep.isdigit():
raise RuntimeError("unexpected: representation is not a positive integer") raise RuntimeError(
"unexpected: representation is not a positive integer")
if int(var_rep) > 0: if int(var_rep) > 0:
print(" " + self.rs.get_entity_name(var_id) + "=" + var_rep, end="") print(
" " + self.rs.get_entity_name(var_id) + "=" + var_rep,
end="")
# print(" " + repr(m[self.v[level][var_id]]), end="") # print(" " + repr(m[self.v[level][var_id]]), end="")
print(" }") print(" }")
@@ -324,17 +375,23 @@ class SmtCheckerRSC(object):
for var_id in range(len(self.v[level])): for var_id in range(len(self.v[level])):
var_rep = repr(m[self.v_ctx[level][var_id]]) var_rep = repr(m[self.v_ctx[level][var_id]])
if not var_rep.isdigit(): if not var_rep.isdigit():
raise RuntimeError("unexpected: representation is not a positive integer") raise RuntimeError(
"unexpected: representation is not a positive integer")
if int(var_rep) > 0: if int(var_rep) > 0:
print(" " + self.rs.get_entity_name(var_id) + "=" + var_rep, end="") print(
" " + self.rs.get_entity_name(var_id) + "=" + var_rep,
end="")
print(" }") print(" }")
def check_rsltl(self, formula, print_witness=True, print_time=True, print_mem=True, max_level=None): def check_rsltl(
self, formula, print_witness=True, print_time=True, print_mem=True,
max_level=None):
"""Bounded Model Checking for rsLTL properties""" """Bounded Model Checking for rsLTL properties"""
self.reset() self.reset()
print("[" + colour_str(C_BOLD, "i") + "] Running rsLTL bounded model checking") print("[" + colour_str(C_BOLD, "i") +
"] Running rsLTL bounded model checking")
print("[" + colour_str(C_BOLD, "i") + "] Formula: " + str(formula)) print("[" + colour_str(C_BOLD, "i") + "] Formula: " + str(formula))
if print_time: if print_time:
@@ -357,31 +414,42 @@ class SmtCheckerRSC(object):
while True: while True:
self.prepare_all_variables() self.prepare_all_variables()
self.solver.add(self.enc_concentration_levels_assertion(self.current_level+1)) self.solver.add(
self.enc_concentration_levels_assertion(
self.current_level + 1))
print("\n{:-^70}".format("[ Working at level=" + str(self.current_level) + " ]")) print(
"\n{:-^70}".format("[ Working at level=" + str(self.current_level) + " ]"))
stdout.flush() stdout.flush()
# reachability test: # reachability test:
self.solver.push() self.solver.push()
print("[" + colour_str(C_BOLD, "i") + "] Generating the formula encoding...") print("[" + colour_str(C_BOLD, "i") +
"] Generating the formula encoding...")
f = encoder.get_encoding(formula, self.current_level) f = encoder.get_encoding(formula, self.current_level)
ncalls = encoder.get_ncalls() ncalls = encoder.get_ncalls()
print("[" + colour_str(C_BOLD, "i") + "] Cache hits: " + str(encoder.get_cache_hits()) + ", encode calls: " + str(ncalls[0]) + " (approx: " + str(ncalls[1]) + ")") print("[" + colour_str(C_BOLD, "i") + "] Cache hits: " +
print("[" + colour_str(C_BOLD, "i") + "] Adding the formula to the solver...") str(encoder.get_cache_hits()) + ", encode calls: " +
str(ncalls[0]) + " (approx: " + str(ncalls[1]) + ")")
print("[" + colour_str(C_BOLD, "i") +
"] Adding the formula to the solver...")
encoder.flush_cache() encoder.flush_cache()
self.solver.add(f) self.solver.add(f)
print("[" + colour_str(C_BOLD, "i") + "] Adding the loops encoding...") print("[" + colour_str(C_BOLD, "i") +
"] Adding the loops encoding...")
self.solver.add(self.get_loop_encodings()) self.solver.add(self.get_loop_encodings())
result = self.solver.check() result = self.solver.check()
if result == sat: if result == sat:
print("[" + colour_str(C_BOLD, "+") + "] " + colour_str(C_GREEN, "SAT at level=" + str(self.current_level))) print(
"[" + colour_str(C_BOLD, "+") + "] " +
colour_str(
C_GREEN, "SAT at level=" + str(self.current_level)))
if print_witness: if print_witness:
print("\n{:=^70}".format("[ WITNESS ]")) print("\n{:=^70}".format("[ WITNESS ]"))
self.decode_witness(self.current_level) self.decode_witness(self.current_level)
@@ -389,10 +457,12 @@ class SmtCheckerRSC(object):
else: else:
self.solver.pop() self.solver.pop()
print("[" + colour_str(C_BOLD, "i") + "] Unrolling the transition relation") print("[" + colour_str(C_BOLD, "i") +
"] Unrolling the transition relation")
self.solver.add(self.enc_transition_relation(self.current_level)) self.solver.add(self.enc_transition_relation(self.current_level))
print("{:->70}".format("[ level=" + str(self.current_level) + " done ]")) print(
"{:->70}".format("[ level=" + str(self.current_level) + " done ]"))
self.current_level += 1 self.current_level += 1
if not max_level is None and self.current_level > max_level: if not max_level is None and self.current_level > max_level:
@@ -404,10 +474,17 @@ class SmtCheckerRSC(object):
stop = resource.getrusage(resource.RUSAGE_SELF).ru_utime stop = resource.getrusage(resource.RUSAGE_SELF).ru_utime
self.verification_time = stop-start self.verification_time = stop-start
print() print()
print("\n[i] {: >60}".format(" Time: " + repr(self.verification_time) + " s")) print(
"\n[i] {: >60}".format(
" Time: " + repr(self.verification_time) + " s"))
if print_mem: if print_mem:
print("[i] {: >60}".format(" Memory: " + repr(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/(1024*1024)) + " MB")) print(
"[i] {: >60}".format(
" Memory: " +
repr(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss /
(1024 * 1024)) + " MB"))
def dummy_unroll(self, levels): def dummy_unroll(self, levels):
"""Unrolls the variables for testing purposes""" """Unrolls the variables for testing purposes"""
@@ -447,7 +524,8 @@ class SmtCheckerRSC(object):
""" """
for i in range(1, k+1): for i in range(1, k+1):
loop_enc = simplify(And(loop_enc, Implies( loop_var == i, self.state_equality(i-1, k) ))) loop_enc = simplify(And(loop_enc, Implies(
loop_var == i, self.state_equality(i-1, k))))
return loop_enc return loop_enc
@@ -471,20 +549,28 @@ class SmtCheckerRSC(object):
while True: while True:
self.prepare_all_variables() self.prepare_all_variables()
self.solver.add(self.enc_concentration_levels_assertion(self.current_level+1)) self.solver.add(
self.enc_concentration_levels_assertion(
self.current_level + 1))
print("\n{:-^70}".format("[ Working at level=" + str(self.current_level) + " ]")) print(
"\n{:-^70}".format("[ Working at level=" + str(self.current_level) + " ]"))
stdout.flush() stdout.flush()
# reachability test: # reachability test:
print("[" + colour_str(C_BOLD, "i") + "] Adding the reachability test...") print("[" + colour_str(C_BOLD, "i") +
"] Adding the reachability test...")
self.solver.push() self.solver.push()
self.solver.add(self.enc_state_with_blocking(self.current_level,state)) self.solver.add(self.enc_state_with_blocking(
self.current_level, state))
result = self.solver.check() result = self.solver.check()
if result == sat: if result == sat:
print("[" + colour_str(C_BOLD, "+") + "] " + colour_str(C_GREEN, "SAT at level=" + str(self.current_level))) print(
"[" + colour_str(C_BOLD, "+") + "] " +
colour_str(
C_GREEN, "SAT at level=" + str(self.current_level)))
if print_witness: if print_witness:
print("\n{:=^70}".format("[ WITNESS ]")) print("\n{:=^70}".format("[ WITNESS ]"))
self.decode_witness(self.current_level) self.decode_witness(self.current_level)
@@ -492,10 +578,12 @@ class SmtCheckerRSC(object):
else: else:
self.solver.pop() self.solver.pop()
print("[" + colour_str(C_BOLD, "i") + "] Unrolling the transition relation") print("[" + colour_str(C_BOLD, "i") +
"] Unrolling the transition relation")
self.solver.add(self.enc_transition_relation(self.current_level)) self.solver.add(self.enc_transition_relation(self.current_level))
print("{:->70}".format("[ level=" + str(self.current_level) + " done ]")) print(
"{:->70}".format("[ level=" + str(self.current_level) + " done ]"))
self.current_level += 1 self.current_level += 1
if self.current_level > max_level: if self.current_level > max_level:
@@ -507,10 +595,17 @@ class SmtCheckerRSC(object):
stop = resource.getrusage(resource.RUSAGE_SELF).ru_utime stop = resource.getrusage(resource.RUSAGE_SELF).ru_utime
self.verification_time = stop-start self.verification_time = stop-start
print() print()
print("\n[i] {: >60}".format(" Time: " + repr(self.verification_time) + " s")) print(
"\n[i] {: >60}".format(
" Time: " + repr(self.verification_time) + " s"))
if print_mem: if print_mem:
print("[i] {: >60}".format(" Memory: " + repr(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/(1024*1024)) + " MB")) print(
"[i] {: >60}".format(
" Memory: " +
repr(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss /
(1024 * 1024)) + " MB"))
def get_verification_time(self): def get_verification_time(self):
return self.verification_time return self.verification_time
@@ -532,7 +627,8 @@ class SmtCheckerRSC(object):
while True: while True:
self.prepare_all_variables() self.prepare_all_variables()
print("-----[ Working at level=" + str(self.current_level) + " ]-----") print(
"-----[ Working at level=" + str(self.current_level) + " ]-----")
stdout.flush() stdout.flush()
# reachability test: # reachability test:
@@ -546,7 +642,10 @@ class SmtCheckerRSC(object):
result = self.solver.check() result = self.solver.check()
if result == sat: if result == sat:
print("\n[+] " + colour_str(C_RED, "SAT at level=" + str(self.current_level))) print(
"\n[+] " +
colour_str(
C_RED, "SAT at level=" + str(self.current_level)))
if print_witness: if print_witness:
self.decode_witness(self.current_level) self.decode_witness(self.current_level)
break break
@@ -569,4 +668,3 @@ class SmtCheckerRSC(object):
x = x.lower() x = x.lower()
if not (x == "y" or x == "yes"): if not (x == "y" or x == "yes"):
break break

View File

@@ -17,9 +17,11 @@ from rs.reaction_system_with_concentrations_param import ParameterObj, is_param
# def simplify(x): # def simplify(x):
# return x # return x
def z3_max(a, b): def z3_max(a, b):
return If(a > b, a, b) return If(a > b, a, b)
class SmtCheckerRSCParam(object): class SmtCheckerRSCParam(object):
def __init__(self, rsca, optimise=False): def __init__(self, rsca, optimise=False):
@@ -27,7 +29,8 @@ class SmtCheckerRSCParam(object):
rsca.sanity_check() rsca.sanity_check()
if not rsca.is_concentr_and_param_compatible(): if not rsca.is_concentr_and_param_compatible():
raise RuntimeError("RS and CA with concentrations (and parameters) expected") raise RuntimeError(
"RS and CA with concentrations (and parameters) expected")
self.rs = rsca.rs self.rs = rsca.rs
self.ca = rsca.ca self.ca = rsca.ca
@@ -39,7 +42,7 @@ class SmtCheckerRSCParam(object):
def initialise(self): def initialise(self):
"""Initialises all the variables used by the checker""" """Initialises all the variables used by the checker"""
### "Currently" used variables (loaded from self.path_v...) # "Currently" used variables (loaded from self.path_v...)
self.v = None self.v = None
self.v_ctx = None self.v_ctx = None
self.ca_state = None self.ca_state = None
@@ -48,7 +51,7 @@ class SmtCheckerRSCParam(object):
self.v_improd = None self.v_improd = None
self.v_improd_for_entities = None self.v_improd_for_entities = None
### Per-path variables # Per-path variables
self.path_v = dict() self.path_v = dict()
self.path_v_ctx = dict() self.path_v_ctx = dict()
self.path_ca_state = dict() self.path_ca_state = dict()
@@ -97,7 +100,8 @@ class SmtCheckerRSCParam(object):
def prepare_all_path_variables(self, path_idx): def prepare_all_path_variables(self, path_idx):
"""Prepares the variables for a given path index""" """Prepares the variables for a given path index"""
print_info("Preparing variables for path={:d} (level={:d})".format(path_idx, self.next_level_to_encode)) print_info("Preparing variables for path={:d} (level={:d})".format(
path_idx, self.next_level_to_encode))
self.prepare_state_variables(path_idx) self.prepare_state_variables(path_idx)
self.prepare_context_variables(path_idx) self.prepare_context_variables(path_idx)
@@ -107,7 +111,8 @@ class SmtCheckerRSCParam(object):
def prepare_loop_position_variables(self, path_idx): def prepare_loop_position_variables(self, path_idx):
"""Prepares the variables for loop positions""" """Prepares the variables for loop positions"""
self.path_loop_position[path_idx] = Int("p{:d}_loop_pos".format(path_idx)) self.path_loop_position[path_idx] = Int(
"p{:d}_loop_pos".format(path_idx))
def prepare_context_variables(self, path_idx): def prepare_context_variables(self, path_idx):
"""Prepares all the context variables""" """Prepares all the context variables"""
@@ -186,7 +191,8 @@ class SmtCheckerRSCParam(object):
for entity in self.rs.set_of_bgset_ids: for entity in self.rs.set_of_bgset_ids:
entity_name = self.rs.get_entity_name(entity) entity_name = self.rs.get_entity_name(entity)
new_var = Int("p{:d}L{:d}_ImProd_r{:d}_{:s}".format(path_idx, level, reaction_id, entity_name)) new_var = Int("p{:d}L{:d}_ImProd_r{:d}_{:s}".format(
path_idx, level, reaction_id, entity_name))
entities_dict[entity] = new_var entities_dict[entity] = new_var
all_entities_dict.setdefault(entity, []) all_entities_dict.setdefault(entity, [])
@@ -196,7 +202,8 @@ class SmtCheckerRSCParam(object):
for entity, conc in products: for entity, conc in products:
entity_name = self.rs.get_entity_name(entity) entity_name = self.rs.get_entity_name(entity)
new_var = Int("p{:d}L{:d}_ImProd_r{:d}_{:s}".format(path_idx, level, reaction_id, entity_name)) new_var = Int("p{:d}L{:d}_ImProd_r{:d}_{:s}".format(
path_idx, level, reaction_id, entity_name))
entities_dict[entity] = new_var entities_dict[entity] = new_var
all_entities_dict.setdefault(entity, []) all_entities_dict.setdefault(entity, [])
@@ -222,7 +229,9 @@ class SmtCheckerRSCParam(object):
vars_for_param = [] vars_for_param = []
for entity in self.rs.ordered_list_of_bgset_ids: for entity in self.rs.ordered_list_of_bgset_ids:
new_var = Int("Pm{:s}_{:s}".format(param_name, self.rs.get_entity_name(entity))) new_var = Int(
"Pm{:s}_{:s}".format(
param_name, self.rs.get_entity_name(entity)))
vars_for_param.append(new_var) vars_for_param.append(new_var)
self.v_param[param_name] = vars_for_param self.v_param[param_name] = vars_for_param
@@ -262,10 +271,13 @@ class SmtCheckerRSCParam(object):
for pvar in param_vars: for pvar in param_vars:
# TODO: fixed upper limit: 100 (have a per-param setting for that) # TODO: fixed upper limit: 100 (have a per-param setting for that)
enc_param_gz = simplify(And(enc_param_gz, pvar >= 0, pvar < 100)) enc_param_gz = simplify(
enc_param_at_least_one = simplify(Or(enc_param_at_least_one, pvar > 0)) And(enc_param_gz, pvar >= 0, pvar < 100))
enc_param_at_least_one = simplify(
Or(enc_param_at_least_one, pvar > 0))
enc_non_empty = simplify(And(enc_non_empty, enc_param_at_least_one)) enc_non_empty = simplify(
And(enc_non_empty, enc_param_at_least_one))
return simplify(And(enc_param_gz, enc_non_empty)) return simplify(And(enc_param_gz, enc_non_empty))
@@ -284,7 +296,8 @@ class SmtCheckerRSCParam(object):
only those that can possibly go below 0. only those that can possibly go below 0.
""" """
print_info("Concentration level assertions for path={:d} (level={:d})".format(path_idx, level)) print_info("Concentration level assertions for path={:d} (level={:d})".format(
path_idx, level))
enc_gz = True enc_gz = True
@@ -292,12 +305,15 @@ class SmtCheckerRSCParam(object):
var = self.path_v[path_idx][level][e_i] var = self.path_v[path_idx][level][e_i]
var_ctx = self.path_v_ctx[path_idx][level][e_i] var_ctx = self.path_v_ctx[path_idx][level][e_i]
e_max = self.rs.get_max_concentration_level(e_i) e_max = self.rs.get_max_concentration_level(e_i)
enc_gz = simplify(And(enc_gz, var >= 0, var_ctx >= 0, var <= e_max, var_ctx <= e_max)) enc_gz = simplify(And(enc_gz, var >= 0, var_ctx >=
0, var <= e_max, var_ctx <= e_max))
vars_per_reaction = self.path_v_improd_for_entities[path_idx][level + 1] vars_per_reaction = self.path_v_improd_for_entities[path_idx][
level + 1]
if e_i in vars_per_reaction: if e_i in vars_per_reaction:
for var_improd in vars_per_reaction[e_i]: for var_improd in vars_per_reaction[e_i]:
enc_gz = simplify(And(enc_gz, var_improd >= 0, var_improd <= e_max)) enc_gz = simplify(
And(enc_gz, var_improd >= 0, var_improd <= e_max))
return enc_gz return enc_gz
@@ -310,7 +326,8 @@ class SmtCheckerRSCParam(object):
# the initial concentration levels are zeroed # the initial concentration levels are zeroed
rs_init_state_enc = simplify(And(rs_init_state_enc, v == 0)) rs_init_state_enc = simplify(And(rs_init_state_enc, v == 0))
ca_init_state_enc = self.path_ca_state[path_idx][level] == self.ca.get_init_state_id() ca_init_state_enc = self.path_ca_state[path_idx][level] == self.ca.get_init_state_id(
)
init_state_enc = simplify(And(rs_init_state_enc, ca_init_state_enc)) init_state_enc = simplify(And(rs_init_state_enc, ca_init_state_enc))
@@ -337,28 +354,35 @@ class SmtCheckerRSCParam(object):
for entity in self.rs.set_of_bgset_ids: for entity in self.rs.set_of_bgset_ids:
rct_inh_constr = And(rct_inh_constr, rct_inh_constr = And(rct_inh_constr,
Implies(self.v_param[inh_param_name][entity] > 0, Implies(
self.v_param[rct_param_name][entity] < self.v_param[inh_param_name][entity])) self.v_param
[inh_param_name][entity] > 0,
self.v_param
[rct_param_name][entity] <
self.v_param
[inh_param_name][entity]))
elif (not is_param(reactants)) and is_param(inhibitors): elif (not is_param(reactants)) and is_param(inhibitors):
inh_param_name = inhibitors.name inh_param_name = inhibitors.name
for entity, conc in reactants: for entity, conc in reactants:
assert conc > 0, "Unexpected concentration level!" assert conc > 0, "Unexpected concentration level!"
rct_inh_constr = And(rct_inh_constr, rct_inh_constr = And(
Implies(self.v_param[inh_param_name][entity] > 0, rct_inh_constr,
conc < self.v_param[inh_param_name][entity])) Implies(
self.v_param[inh_param_name][entity] > 0, conc <
self.v_param[inh_param_name][entity]))
elif is_param(reactants) and (not is_param(inhibitors)): elif is_param(reactants) and (not is_param(inhibitors)):
rct_param_name = reactants.name rct_param_name = reactants.name
for entity, conc in inhibitors: for entity, conc in inhibitors:
assert conc > 0, "Unexpected concentration level!" assert conc > 0, "Unexpected concentration level!"
rct_inh_constr = And(rct_inh_constr, self.v_param[rct_param_name][entity] < conc) rct_inh_constr = And(
rct_inh_constr, self.v_param[rct_param_name][entity] < conc)
return rct_inh_constr return rct_inh_constr
def enc_single_reaction(self, level, path_idx, reaction): def enc_single_reaction(self, level, path_idx, reaction):
""" """
Encodes a single reaction Encodes a single reaction
@@ -412,24 +436,28 @@ class SmtCheckerRSCParam(object):
if is_param(products): if is_param(products):
param_name = products.name param_name = products.name
for entity in self.rs.set_of_bgset_ids: for entity in self.rs.set_of_bgset_ids:
enc_products = simplify(And(enc_products, enc_products = simplify(
self.path_v_improd[path_idx][level + 1][reaction_id][entity] == self.v_param[param_name][entity])) And(
enc_products, self.
path_v_improd[path_idx]
[level + 1][reaction_id]
[entity] == self.v_param
[param_name][entity]))
else: else:
for entity, conc in products: for entity, conc in products:
enc_products = simplify(And(enc_products, enc_products = simplify(And(
self.path_v_improd[path_idx][level + 1][reaction_id][entity] == conc)) enc_products, self.path_v_improd[path_idx][level + 1][reaction_id][entity] == conc))
# Nothing is produced (when the reaction is disabled) # Nothing is produced (when the reaction is disabled)
enc_no_prod = True enc_no_prod = True
if is_param(products): if is_param(products):
for entity in self.rs.set_of_bgset_ids: for entity in self.rs.set_of_bgset_ids:
enc_no_prod = And(enc_no_prod, enc_no_prod = And(
self.path_v_improd[path_idx][level + 1][reaction_id][entity] == 0) enc_no_prod, self.path_v_improd[path_idx][level + 1][reaction_id][entity] == 0)
else: else:
for entity, _ in products: for entity, _ in products:
enc_no_prod = simplify(And(enc_no_prod, enc_no_prod = simplify(And(
self.path_v_improd[path_idx][level + 1][reaction_id][entity] == 0)) enc_no_prod, self.path_v_improd[path_idx][level + 1][reaction_id][entity] == 0))
# #
# (R and I) iff P # (R and I) iff P
@@ -439,7 +467,8 @@ class SmtCheckerRSCParam(object):
# #
# ~(R and I) iff P_zero # ~(R and I) iff P_zero
# #
enc_not_enabled = Not(And(enc_reactants, enc_inhibitors)) == enc_no_prod enc_not_enabled = Not(
And(enc_reactants, enc_inhibitors)) == enc_no_prod
enc_reaction = And(enc_enabled, enc_not_enabled) enc_reaction = And(enc_enabled, enc_not_enabled)
@@ -461,7 +490,8 @@ class SmtCheckerRSCParam(object):
enc_cond = False enc_cond = False
for entity in self.rs.set_of_bgset_ids: for entity in self.rs.set_of_bgset_ids:
enc_cond = simplify(Or(enc_cond, self.path_v[path_idx][level][entity] > 0, self.path_v_ctx[path_idx][level][entity] > 0)) enc_cond = simplify(
Or(enc_cond, self.path_v[path_idx][level][entity] > 0, self.path_v_ctx[path_idx][level][entity] > 0))
return enc_cond return enc_cond
@@ -506,13 +536,15 @@ class SmtCheckerRSCParam(object):
current_v_improd_for_entities = self.path_v_improd_for_entities[path_idx][level + 1] current_v_improd_for_entities = self.path_v_improd_for_entities[path_idx][level + 1]
for entity in self.rs.set_of_bgset_ids: for entity in self.rs.set_of_bgset_ids:
per_reaction_vars = current_v_improd_for_entities.get(entity, []) per_reaction_vars = current_v_improd_for_entities.get(entity, [])
enc_max_prod = simplify( enc_max_prod = simplify(And(
And(enc_max_prod, self.path_v[path_idx][level + 1][entity] == self.enc_max(per_reaction_vars))) enc_max_prod, self.path_v[path_idx][level + 1][entity] == self.enc_max(per_reaction_vars)))
# make sure at least one entity is >0 # make sure at least one entity is >0
enc_general_cond = self.enc_general_reaction_enabledness(level, path_idx) enc_general_cond = self.enc_general_reaction_enabledness(
level, path_idx)
enc_trans_with_max = simplify(And(enc_general_cond, enc_max_prod, enc_trans)) enc_trans_with_max = simplify(
And(enc_general_cond, enc_max_prod, enc_trans))
# print(enc_trans_with_max) # print(enc_trans_with_max)
@@ -553,10 +585,12 @@ class SmtCheckerRSCParam(object):
ctx_enc = True ctx_enc = True
for e, c in ctx: for e, c in ctx:
ctx_enc = simplify(And(ctx_enc, self.path_v_ctx[path_idx][level][e] == c)) ctx_enc = simplify(
And(ctx_enc, self.path_v_ctx[path_idx][level][e] == c))
for e in excl_ctx: for e in excl_ctx:
ctx_enc = simplify(And(ctx_enc, self.path_v_ctx[path_idx][level][e] == 0)) ctx_enc = simplify(
And(ctx_enc, self.path_v_ctx[path_idx][level][e] == 0))
cur_trans = simplify(And(src_enc, ctx_enc, dst_enc)) cur_trans = simplify(And(src_enc, ctx_enc, dst_enc))
enc_trans = simplify(Or(enc_trans, cur_trans)) enc_trans = simplify(Or(enc_trans, cur_trans))
@@ -690,18 +724,22 @@ class SmtCheckerRSCParam(object):
"unexpected: representation is not a positive integer") "unexpected: representation is not a positive integer")
if int(var_rep) > 0: if int(var_rep) > 0:
print( print(
" " + str(self.rs.get_entity_name(entity)) + "=" + str(var_rep), " " + str(self.rs.get_entity_name(entity)) + "=" +
str(var_rep),
end="") end="")
print(" }") print(" }")
print() print()
def enc_concentration_levels_assertions_for_paths(self, level, num_of_paths): def enc_concentration_levels_assertions_for_paths(
self, level, num_of_paths):
additional_assertions = [] additional_assertions = []
for path_idx in range(num_of_paths): for path_idx in range(num_of_paths):
additional_assertions.append(self.enc_concentration_levels_assertion(level, path_idx)) additional_assertions.append(
additional_assertions.append(self.enc_param_concentration_levels_assertion()) self.enc_concentration_levels_assertion(level, path_idx))
additional_assertions.append(
self.enc_param_concentration_levels_assertion())
return additional_assertions return additional_assertions
@@ -765,7 +803,9 @@ class SmtCheckerRSCParam(object):
self.current_level = 0 self.current_level = 0
# assertions for all the paths and parameters # assertions for all the paths and parameters
self.solver_add(self.enc_concentration_levels_assertions_for_paths(0, num_of_paths)) self.solver_add(
self.enc_concentration_levels_assertions_for_paths(
0, num_of_paths))
self.solver_add(self.enc_param_concentration_levels_assertion()) self.solver_add(self.enc_param_concentration_levels_assertion())
self.solver_add(self.enc_param_sanity_for_reactions()) self.solver_add(self.enc_param_sanity_for_reactions())
@@ -819,10 +859,13 @@ class SmtCheckerRSCParam(object):
self.prepare_all_variables(num_of_paths) self.prepare_all_variables(num_of_paths)
# assertions for all the paths # assertions for all the paths
self.solver_add(self.enc_concentration_levels_assertions_for_paths(self.current_level + 1, num_of_paths)) self.solver_add(
self.enc_concentration_levels_assertions_for_paths(
self.current_level + 1, num_of_paths))
print_info("Unrolling the transition relation") print_info("Unrolling the transition relation")
self.solver_add(self.enc_transition_relation_for_paths(self.current_level, num_of_paths)) self.solver_add(self.enc_transition_relation_for_paths(
self.current_level, num_of_paths))
self.print_level() self.print_level()
@@ -886,7 +929,8 @@ class SmtCheckerRSCParam(object):
""" """
for i in range(1, k+1): for i in range(1, k+1):
loop_enc = simplify(And(loop_enc, Implies( loop_var == i, self.state_equality(i-1, k) ))) loop_enc = simplify(And(loop_enc, Implies(
loop_var == i, self.state_equality(i-1, k))))
return loop_enc return loop_enc
@@ -923,20 +967,28 @@ class SmtCheckerRSCParam(object):
while True: while True:
self.prepare_all_variables() self.prepare_all_variables()
self.solver_add(self.enc_concentration_levels_assertion(self.current_level+1)) self.solver_add(
self.enc_concentration_levels_assertion(
self.current_level + 1))
print("\n{:-^70}".format("[ Working at level=" + str(self.current_level) + " ]")) print(
"\n{:-^70}".format("[ Working at level=" + str(self.current_level) + " ]"))
stdout.flush() stdout.flush()
# reachability test: # reachability test:
print("[" + colour_str(C_BOLD, "i") + "] Adding the reachability test...") print("[" + colour_str(C_BOLD, "i") +
"] Adding the reachability test...")
self.solver.push() self.solver.push()
self.solver_add(self.enc_state_with_blocking(self.current_level,state)) self.solver_add(self.enc_state_with_blocking(
self.current_level, state))
result = self.solver.check() result = self.solver.check()
if result == sat: if result == sat:
print("[" + colour_str(C_BOLD, "+") + "] " + colour_str(C_GREEN, "SAT at level=" + str(self.current_level))) print(
"[" + colour_str(C_BOLD, "+") + "] " +
colour_str(
C_GREEN, "SAT at level=" + str(self.current_level)))
if print_witness: if print_witness:
print("\n{:=^70}".format("[ WITNESS ]")) print("\n{:=^70}".format("[ WITNESS ]"))
self.decode_witness(self.current_level) self.decode_witness(self.current_level)
@@ -944,10 +996,12 @@ class SmtCheckerRSCParam(object):
else: else:
self.solver.pop() self.solver.pop()
print("[" + colour_str(C_BOLD, "i") + "] Unrolling the transition relation") print("[" + colour_str(C_BOLD, "i") +
"] Unrolling the transition relation")
self.solver_add(self.enc_transition_relation(self.current_level)) self.solver_add(self.enc_transition_relation(self.current_level))
print("{:->70}".format("[ level=" + str(self.current_level) + " done ]")) print(
"{:->70}".format("[ level=" + str(self.current_level) + " done ]"))
self.current_level += 1 self.current_level += 1
if self.current_level > max_level: if self.current_level > max_level:
@@ -959,16 +1013,21 @@ class SmtCheckerRSCParam(object):
stop = resource.getrusage(resource.RUSAGE_SELF).ru_utime stop = resource.getrusage(resource.RUSAGE_SELF).ru_utime
self.verification_time = stop-start self.verification_time = stop-start
print() print()
print("\n[i] {: >60}".format(" Time: " + repr(self.verification_time) + " s")) print(
"\n[i] {: >60}".format(
" Time: " + repr(self.verification_time) + " s"))
if print_mem: if print_mem:
print("[i] {: >60}".format(" Memory: " + repr(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/(1024*1024)) + " MB")) print(
"[i] {: >60}".format(
" Memory: " +
repr(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss /
(1024 * 1024)) + " MB"))
def get_verification_time(self): def get_verification_time(self):
return self.verification_time return self.verification_time
def show_encoding(self, state, print_witness=True, def show_encoding(self, state, print_witness=True,
print_time=False, print_mem=False, max_level=100): print_time=False, print_mem=False, max_level=100):
"""Encoding debug function""" """Encoding debug function"""
@@ -986,7 +1045,8 @@ class SmtCheckerRSCParam(object):
while True: while True:
self.prepare_all_variables() self.prepare_all_variables()
print("-----[ Working at level=" + str(self.current_level) + " ]-----") print(
"-----[ Working at level=" + str(self.current_level) + " ]-----")
stdout.flush() stdout.flush()
# reachability test: # reachability test:
@@ -1000,7 +1060,10 @@ class SmtCheckerRSCParam(object):
result = self.solver.check() result = self.solver.check()
if result == sat: if result == sat:
print("\n[+] " + colour_str(C_RED, "SAT at level=" + str(self.current_level))) print(
"\n[+] " +
colour_str(
C_RED, "SAT at level=" + str(self.current_level)))
if print_witness: if print_witness:
self.decode_witness(self.current_level) self.decode_witness(self.current_level)
break break