def configure_weights(): weight_counts = load_weights() weights = Weights(weight_counts) weight_objects = [weights] possible_total_weights = wt.possible_weights(weight_objects) double_weights = wt.possible_double_weights(weight_objects) input_weights = [] keep_going = True while len(possible_total_weights) > 1 and keep_going: print() print("possible total weights:") for w in possible_total_weights: double_indicator = " " if w in double_weights: double_indicator = "* " print("{}{:4.1f} kg".format(double_indicator, w)) while True: try: # enter any non-number to stop total_weight = float(input("choose total weight: ")) if total_weight in possible_total_weights: input_weights.append(total_weight) break print("invalid input") except ValueError: # non-number entered, stopping total_weight = 0 keep_going = False break if keep_going: weight_objects = wt.reduced_weight_objects(weight_objects, total_weight) possible_total_weights = wt.possible_weights(weight_objects) double_weights = wt.possible_double_weights(weight_objects) # print("===========================") print("selected weights:") print(input_weights) print() print("weight combos:") weight_counts = load_weights() weights = Weights(weight_counts) if len(input_weights): combos = wt.get_combos(weights, input_weights) for w, c in combos: weight = "{:4.1f} kg".format(w) # weights_asc = sorted(c) weights_dsc = sorted(c, reverse=True) print("{}: {}".format(weight, weights_dsc))
def enumerate_TTAs(self, formula, weights, domA=None, domX=None): """Enumerates the total truth assignments for WMI(formula, weights, X, A). Keyword arguments: formula -- pysmt formula weights -- Weights instance encoding the FIUC weight function domA -- set of pysmt vars encoding the Boolean integration domain (optional) domX -- set of pysmt vars encoding the real integration domain (optional) """ if isinstance(weights, FNode): weights = Weights(weights) A = {x for x in get_boolean_variables(formula) if not is_label(x)} x = get_real_variables(formula) dom_msg = "The domain of integration of the numerical variables" +\ " should be x. The domain of integration of the Boolean" +\ " variables should be a superset of A." if domA != None: if len(A - domA) > 0: self.logger.error(dom_msg) raise WMIRuntimeException(dom_msg) if domX != None and not set(domX) == x: self.logger.error(dom_msg) raise WMIRuntimeException(dom_msg) formula = And(formula, weights.labelling) return len(self._compute_TTAs(formula, weights)[0])
def __parse_lpad(self, lpad): self.__weights = Weights() self.__logicProgram = LogicProgram() self.__constraints = [] self.__rule_counter = 0 for line in open(lpad): line = line.strip() self.__parse_AD(line)
def __init__(self, threadID, dataSet, minStartWeight, maxStartWeight): Process.__init__(self) self.threadID = threadID self.weights = Weights(dataSet.getDataPoint(0).dimension()) self.weights.generateRandom(minStartWeight, maxStartWeight) weight = """*****\nThread {0} initial weights:\n{1}\n*****""" print(weight.format(self.threadID, self.weights.vector)) self.trainingErrors = Errors(dataSet.trainingDataPoints, dataSet.trainingActualValues) self.testingErrors = Errors(dataSet.testingDataPoints, dataSet.testingActualValues) self.hypothesis = Hypothesis() self.trainingErrors.updateToLower(self.weights, self.hypothesis) self.iterations = 0 self.alpha = STARTING_ALPHA
def __init__(self, go_engine, board, debug_mode=False): """ Manage a GTP connection for a Go-playing engine Parameters ---------- go_engine: a program that can reply to a set of GTP commandsbelow board: Represents the current board state. """ self._debug_mode = debug_mode self.go_engine = go_engine self.board = board self.pattern_table = Weights() self.commands = { "protocol_version": self.protocol_version_cmd, "quit": self.quit_cmd, "name": self.name_cmd, "boardsize": self.boardsize_cmd, "showboard": self.showboard_cmd, "clear_board": self.clear_board_cmd, "komi": self.komi_cmd, "version": self.version_cmd, "known_command": self.known_command_cmd, "genmove": self.genmove_cmd, "list_commands": self.list_commands_cmd, "play": self.play_cmd, "legal_moves": self.legal_moves_cmd, "gogui-rules_game_id": self.gogui_rules_game_id_cmd, "gogui-rules_board_size": self.gogui_rules_board_size_cmd, "gogui-rules_legal_moves": self.gogui_rules_legal_moves_cmd, "gogui-rules_side_to_move": self.gogui_rules_side_to_move_cmd, "gogui-rules_board": self.gogui_rules_board_cmd, "gogui-rules_final_result": self.gogui_rules_final_result_cmd, "gogui-analyze_commands": self.gogui_analyze_cmd, "policy": self.policy_cmd, "selection": self.selection_cmd, "policy_moves": self.policy_moves_cmd, "num_sim": self.num_sim_cmd } # used for argument checking # values: (required number of arguments, # error message on argnum failure) self.argmap = { "boardsize": (1, 'Usage: boardsize INT'), "komi": (1, 'Usage: komi FLOAT'), "known_command": (1, 'Usage: known_command CMD_NAME'), "genmove": (1, 'Usage: genmove {w,b}'), "play": (2, 'Usage: play {b,w} MOVE'), "legal_moves": (1, 'Usage: legal_moves {w,b}'), "policy": (1, 'Usage: policy POLICYTYPE'), "selection": (1, 'Usage: selection SELECTIONTYPE'), "num_sim": (1, 'Usage: num_sim INT') }
def __call__(self, logic_program, weights, literals): self.__logic_program = logic_program self.__weights = weights self.__new_weights = Weights() self.__translation = KeyIndexDict() self.__done = [] self.__leafs = {} self.__completion = CNF() for lit in literals: self.__get_completion(lit) return self.__completion, self.__translation, self.__new_weights
def __call__(self,logic_program,weights,queries,evidence): self.__original_program = logic_program self.__original_weights = weights self.__new_program = LogicProgram() self.__new_weights = Weights() self.__built_rules = {} for lit in queries | evidence: self.__get_rule(lit) new_evidence = set([]) for lit in evidence: if lit.truth_value: for (new_lit,_) in self.__built_rules[lit]: new_evidence.add(new_lit) else: for (new_lit,_) in self.__built_rules[-lit]: new_evidence.add(-new_lit) return self.__new_program, self.__new_weights, new_evidence
def __init__(self, support, weights, check_consistency=False): """Default constructor. Keyword arguments: support -- pysmt formula encoding the support weights -- pysmt formula encoding the FIUC weight function check_consistency -- if True, raises a WMIRuntimeException if the model is inconsistent (default: False) """ self.init_sublogger(__name__) # check if the support and weight function contain reserved names if contains_labels(support): msg = "The support contains variables with reserved names." self.logger.error(msg) raise WMIRuntimeException(msg) if contains_labels(weights): msg = "The weight function contains variables with reserved names." self.logger.error(msg) raise WMIRuntimeException(msg) # labelling the weight function conditions self.weights = Weights(weights) self.support = And(support, self.weights.labelling) self.logger.debug("Support: {}".format(serialize(support))) self.logger.debug("Weights: {}".format(serialize(weights))) # initialize the WMI engine self.wmi = WMI() # check support consistency if requested if check_consistency and not WMI.check_consistency(support): raise WMIRuntimeException(WMIInference.MSG_INCONSISTENT_SUPPORT)
def train(self, ensemble_size=SIZE): """ To train the model using Adaboost algorithm. :param ensemble_size: the size of the stumps :return: """ entries = self.train_file features = set(entries[0].features.keys()) weights = Weights(entries) self.ensemble = [] # create and store each stump for i in range(ensemble_size): stump = tree.make_tree(entries, features, [], 1) error = 0 for entry in entries: decision = stump.decide_classification(entry) if decision != entry.target: error += entry.weight for j in range(len(entries)): entry = entries[j] decision = stump.decide_classification(entry) if decision == entry.target: new_weight = entry.weight * error / (weights.total - error) weights.update_weight(j, new_weight) weights.normalization() stump.weight = math.log(weights.total - error) / error self.ensemble.append(stump) # store the model to a binary file file = open(self.out_file, "wb") pickle.dump(self, file) file.close()
def __init__(self, key, initial_value, final_value): self.key = key self.initial_value = initial_value self.final_value = final_value self.weight = Weights.get(self.key, 1)
# variables definition a = Symbol("A", BOOL) x = Symbol("x", REAL) # formula definition phi = And(Iff(a, GE(x, Real(0))), GE(x, Real(-1)), LE(x, Real(1))) print "Formula:", serialize(phi) # weight function definition w = Ite(GE(x, Real(0)), x, Times(Real(-1), x)) chi = Bool(True) print "Weight function:", serialize(w) print "Support:", serialize(chi) weights = Weights(w, chi) chi = And(chi, weights.labelling) wmi = WMI() print for mode in [WMI.MODE_ALLSMT, WMI.MODE_PA]: result, n_integrations = wmi.compute(And(chi,phi), weights, mode) print "WMI with mode {} \t result = {}, \t # integrations = {}".format(mode, result, n_integrations)
class Run (Process): def __init__(self, threadID, dataSet, minStartWeight, maxStartWeight): Process.__init__(self) self.threadID = threadID self.weights = Weights(dataSet.getDataPoint(0).dimension()) self.weights.generateRandom(minStartWeight, maxStartWeight) weight = """*****\nThread {0} initial weights:\n{1}\n*****""" print(weight.format(self.threadID, self.weights.vector)) self.trainingErrors = Errors(dataSet.trainingDataPoints, dataSet.trainingActualValues) self.testingErrors = Errors(dataSet.testingDataPoints, dataSet.testingActualValues) self.hypothesis = Hypothesis() self.trainingErrors.updateToLower(self.weights, self.hypothesis) self.iterations = 0 self.alpha = STARTING_ALPHA # __init__ def run(self): while(self.trainingErrors.greaterThan(ALLOWABLE_MSE_DELTA) and self.iterations < MAX_ITERATIONS and self.alpha > 0): self.iterations += 1 self.weights.update(self.alpha, self.trainingErrors) if (not self.trainingErrors.updateToLower(self.weights, self.hypothesis)): self.alpha /= ALPHA_BASE self.weights.revert() # if if (self.iterations % 10 == 0): self.alpha *= 1.1 # if # while self.print() # run def print(self): output = """ ========================================================================================================================================== RUN RESULTS for thread {0}: ALPHA and ITERATIONS: {1} {2} ---------------------------------------------------------------------------------- WEIGHT VECTOR: {3} ---------------------------------------------------------------------------------- Lowest training data MSE: {4} ---------------------------------------------------------------------------------- Test data MSE: {5} ========================================================================================================================================== """ self.testingErrors.updateToLower(self.weights, self.hypothesis) print(output.format(self.threadID, self.alpha, self.iterations, self.weights.vector, self.trainingErrors.mse, self.testingErrors.mse))
def __init__(self): """Here, all commandline arguments are checked and used.""" # Check if enough commandline args are given if len(sys.argv) is 1: print("python main.py <1, 2, 3> <algorithm> <iterations>") sys.exit() else: # Check if neighbourhood input is correct if sys.argv[1] in ["1", "2", "3"]: self.input = int(sys.argv[1]) neighbourhood = self.input else: print("please insert either a valid neighbourhood number " "as 1st argument") print("select from: 1, 2, 3") sys.exit(2) # If user wants plots if "plot" in sys.argv: plot = "y" else: plot = "n" # Check if correct algorithm is given in third argument if sys.argv[2] in [ "stepdown", "greedy", "hill", "dfs", "random", "bnb" ]: algorithm = sys.argv[2] cluster_option = None if sys.argv[2] in ["stepdown", "dfs", "bnb"]: iterations = 0 # Initialize n iterations, if any elif len(sys.argv) > 3 and sys.argv[3].isnumeric(): iterations = int(sys.argv[3]) else: print("No #iteration given, will be set to 1000") iterations = 1000 # Call cluster algorithm if ("cluster" in sys.argv) and not ("configure" in sys.argv): cluster = Cluster(neighbourhood) min_cost = 999999 index = 0 # Find cheapest positions for battery for i in cluster.options_list: print(f"Checking option {i}...") smart = Smartgrid(neighbourhood, "greedy", 1000, "n", i, "cluster") if smart.cost < min_cost: file = smart.pickle_file min_cost = smart.cost index = i # Call specified algorithm for cheapest option Smartgrid(neighbourhood, algorithm, iterations, "n", index, "cluster") time_var = time.strftime("%d%m%Y") file = os.path.join(*[ cwd, 'results', f"wijk_{self.input}", algorithm, "cluster", f"{algorithm}_lowest_WIJK{self.input}" + f"_{time_var}.dat" ]) # Load pickle so cheapest option can be plotted load_pickle(self, file) sys.exit() # If not cluster, use configure and find cheapest configuration # for this neighbourhood elif ("configure" in sys.argv) and not ("cluster" in sys.argv): # Calculate configurations Configure(neighbourhood) # First test so lowest configuration is saved Weights(neighbourhood, "test", iterations, "configure") # Run algorithm on lowest solution Weights(neighbourhood, algorithm, iterations, "configure") sys.exit() # Else algorithm argument was incorrect else: print("please insert the preferred algorithm as 2nd argument") print("select from: \"stepdown\", \"greedy\", \"hill\", " "\"cluster\", \"configure\", \"random\"") sys.exit(2) # No cluster or configure, so use fixed battery locations Smartgrid(neighbourhood, algorithm, iterations, plot, cluster_option, "fixed")