def testrunexpe(): from experiment.ExperimentWrapper import executepoissionexpe, executemodelchecking from util.util import interval from module.Module import Constant params = [] for i in interval(0.5, 5, 0.1): params.append(Constant('r', i)) result = executepoissionexpe([params]) # {paramsdict: prob} cases = map(lambda tuple: tuple[0], result) labels = map(lambda tuple: tuple[1], result) regressor = BPNeuralNetwork() regressor.setup(1, 5, 1) regressor.train(cases, labels) test_cases = map(lambda v: Constant('r', v), interval(0.5, 5, 0.05)) test_labels = [regressor.predict(test_case) for test_case in test_cases] # 对多组参数进行模型验证 mcresult = executemodelchecking([test_cases]) # mc_labels = map(lambda tuple: tuple[1], mcresult) plt.plot(map(lambda const: const.get_value(), test_cases), test_labels, label='predict') # plt.plot(map(lambda const: const.get_value(), test_cases), mc_labels, label='mc') plt.show()
def testSPS(): from util.util import interval from module.Module import Constant config = SPSConfig.SPSConfig() moduleFactory = ModuleFactory(config) modelfactory = ModelFactory(moduleFactory) model = modelfactory.get_built() ltl = ['U[1, {0}]'.format(730), 'T', 'failure'] # 一年之内系统失效 checker = Checker(model, ltl, duration=730, fb=False) wrapper = ExperimentWrapper(checker, samples_per_param=100) trainx = interval(1, 10, 0.5) testx = interval(1, 10, 0.1) thickness_params = [Constant('SCREEN_THICKNESS', st) for st in trainx] wrapper.setconstants([thickness_params]) result = wrapper.do_expe() cases = map(lambda tuple: tuple[0], result) labels = map(lambda tuple: tuple[1], result) regressor = BPNeuralNetwork() regressor.setup(1, 5, 1) regressor.train(cases, labels) test_cases = map(lambda c: Constant('SCREEN_THICKNESS', c), testx) test_labels = [regressor.predict(test_case) for test_case in testx] # 对多组参数进行模型验证 # logger.info("mc begin") # wrapper.setconstants([test_cases]) # mcresult = wrapper.modelcheck() # mc_labels = map(lambda tuple: tuple[1], mcresult) plt.plot(testx, [i[0] for i in test_labels], label='predict') # plt.plot(map(lambda const: const.get_value(), test_cases), mc_labels, label='mc') plt.show()
def _to_constant_objs(self): ''' 将self.expr_params转化为[[constant_obj]] :return: [[constant_obj]] ''' result = [] for n, vl in self.expr_params: objs = [] for v in vl: objs.append(Constant(n, v)) result.append(objs) return result
def test_checking(self): thickness_vals = range(1, 10, 1) constant_objs = [Constant("SCREEN_THICKNESS", v) for v in thickness_vals] for obj in constant_objs: self.model_constructor._parser.vcf_map[obj.get_name()].set_value( obj.get_value()) self.model.commPrepared = False logger.info( "param={}, checker's result={}".format( obj.get_value(), self.checker.run_checker()))
def main(): from test.PoissionProcess import poission_model from util.util import interval from module.Module import Constant model = poission_model() ltl = ['!', 'U[0,1]', None, 'T', 'nge4', None, None] # 一秒之内n<4 checker = Checker.Checker(model, ltl) wrapper = ExperimentWrapper(checker) constants = [] for value in interval(0.5, 5, 0.1): constants.append(Constant('r', value)) wrapper.setconstants([constants]) # results = wrapper.experiment() wrapper.modelcheck()
def check(): config = SPSConfig() built = get_built_model() parsed = get_parsed_model() rslt1 = [] rslt2 = [] thickness = range(1, 10, 4) for t in thickness: config.setParam(THICKNESS, Constant(THICKNESS, t)) parsed.setConstant(THICKNESS, t) checker1 = get_checker(built, ltl, DURATION) checker2 = get_checker(parsed, ltl, DURATION) rslt1.append(checker1.run()) rslt2.append(checker2.run()) precision = 2e-2 for v1, v2 in zip(rslt1, rslt2): assert fabs(v1 - v2) < precision, "v1:{}, v2:{}".format(v1, v2)
def testChecking(self): ''' verify the difference between smc and provided prism_data is within checking_delta :return: None ''' checked_result_map = {} for name, values in self.params.items(): self.model.commPrepared = False constant_obj = Constant(name, ) set_result = self.model.set_constant(constant_obj) assert set_result result = self.checker.run_checker() checked_result_map[thickness] = result error_map = {} self.logger.info("check result: %s", str(checked_result_map)) for k, v in checked_result_map.items(): error_map[float(k)] = fabs(v - self.prism_data_map[float(k)]) self.logger.info("error_map: %s", str(error_map)) self.assertGreaterEqual(0.01, sum(error_map.values()) / len(checked_result_map))
def test(): results = [] logger.info("===============built===============") for t in range(4, 5): sb.setConstant(Constant('SCREEN_THICKNESS', t)) ps = [] doses = [] std_xs = [] for v in [Variable('day', i) for i in interval(1, 365 * YEAR, 1)]: dose = v.getValue() / 365.0 * sb.getConstant("SB_K").getValue( ) * sb.getConstant("SCREEN_THICKNESS").getValue() doses.append(dose) x = (1 - sb.getConstant("SB_P_THRESHOLD").getValue()) / ( log(1 + sb.getConstant("SB_B").getValue() * dose)) std_x = (x - sb.getConstant("SB_A_MU").getValue() ) / sb.getConstant("SB_A_SIGMA").getValue() p = 1 - pcf(std_x) ps.append(p) std_xs.append(std_x) results.append(ps) logger.info("thickness={}, p_max={}".format(t, ps[-1])) return results
from config.SPSConfig import SPSConfig from module.Module import Module, Constant, Variable, Command, CommandKind from util.MathUtils import * from util.util import * logger = logging.getLogger("test fail prob sb.py") logger.addHandler(logging.StreamHandler(sys.stdout)) logger.addHandler(logging.FileHandler("../log/testsbfail.log", "w")) logger.setLevel(logging.DEBUG) from compiler.PRISMParser import ModelConstructor YEAR = 5 # timer module of the system timer = Module('timer_module') timer.addConstant(Constant('TIME_LIMIT', YEAR * 365)) # 2 years day = Variable('day', 1, range(timer.getConstant('TIME_LIMIT').getValue() + 1), int, True) timer_turn = Variable('timer_turn', True, set([True, False]), bool, True) timer.addVariable(day) timer.addVariable(timer_turn) def incdayaction(vs, cs): vs['day'].setValue(vs['day'].getValue() + 1) vs['timer_turn'].setValue(False) inc_day = Command( 'inc day', lambda vs, cs: vs['timer_turn'] == True and vs['day'] <= timer. getConstant('TIME_LIMIT').getValue(), incdayaction, timer, 1.0)
def __init__(self): self.params = {} self.params['SB_K'] = Constant('SB_K', 0.0039) self.params['SB_B'] = Constant('SB_B', 1.8) self.params['SB_P_THRESHOLD'] = Constant('SB_P_THRESHOLD', 0.78 * 1.05) self.params['SB_A_MU'] = Constant('SB_A_MU', 0.1754) self.params['SB_A_SIGMA'] = Constant('SB_A_SIGMA', 0.02319029 * 21) self.params['S3R_K'] = Constant('S3R_K', 200.5 / 3.0) # s3r, bdr, bcr三个模块均摊电离能损 self.params['S3R_DELTAV_THRESHOLD'] = Constant('S3R_DELTAV_THRESHOLD', 880 * (10.0 / 880)) self.params['S3R_A_MU'] = Constant('S3R_A_MU', 570.8 * 18 - 570.8 * 5) self.params['S3R_A_SIGMA'] = Constant('S3R_A_SIGMA', 6.7471 * 220) self.params['S3R_B'] = Constant('S3R_B', 0.0131 * 0.57 * 0.1) self.params['SCREEN_THICKNESS'] = Constant('SCREEN_THICKNESS', 6) self.params['DURATION_IN_DAY'] = Constant('DURATION_IN_DAY', 365 * 2)
from util.CsvFileHelper import parse_csv_cols logger = logging.getLogger("test parsed regressor log") logger.addHandler(logging.FileHandler(get_log_dir() + get_sep() + "testparsedregre.log", "w")) logger.setLevel(logging.INFO) def get_expr_result_prism(filepath): return parse_csv_cols(filepath) TIME_LIMIT_IN_DAYS = 365 ltl = ["U[1, {}]".format(int(TIME_LIMIT_IN_DAYS * 2)), "T", "failure"] prism_data_path = get_prism_model_dir() + get_sep() + "YEAR1_T_1_5_1" TEST_DATA_X, TEST_DATA_Y = get_expr_result_prism(prism_data_path) thickness_cnsts = map(lambda v: Constant("SCREEN_THICKNESS", v), TEST_DATA_X) SAMPLES_PER_PARAM = 400 def do_expr_built(): model = ModelFactory.get_built() checker = Checker(model=model, ltl=ltl, duration=TIME_LIMIT_IN_DAYS*2) # wrapper = ExperimentWrapper(checker, samples_per_param=SAMPLES_PER_PARAM) wrapper = ExperimentWrapper(checker) wrapper.setconstants([thickness_cnsts,]) logger.info("Built model expr began.") result = wrapper.do_expe() logger.info("Built model expr end.") return result
# -*- coding: utf-8 -*- from module.Module import Constant c1 = Constant('c', 10) c2 = Constant('c', 3) def testConstantArithmatics(): assert c1 + c2 == 13 assert c1 + 3 == 13 assert c1 / 5 == 2 assert -c1 + 9 == -1 assert 1.0 / (c1 / 5) == 0.5 assert -c1 + 9 == -1 assert c1 / c1 == 1 def testConstantCompare(): assert c1 < 11 assert c2 < c1 assert c1 > c2 assert c1 > 9 assert c1 == 10 assert 10 == c1 if __name__ == '__main__': testConstantArithmatics() testConstantCompare()