def instantiate_free_variables(self, expr): vars = expr.collect_variables() instantiate_vars_subs = Substitution() for v in vars: instantiate_vars_subs.replace(v, self.introduce_constant()) return instantiate_vars_subs.apply(expr)
def unify(self, expr): subs = Substitution() eqs = [(self, expr)] while eqs: lhs, rhs = eqs.pop() if lhs is rhs: continue elif isinstance(lhs, Application) and isinstance(rhs, Application): eqs.extend(zip(lhs.elems, rhs.elems)) elif isinstance(lhs, Variable) or isinstance(rhs, Variable): if not isinstance(lhs, Variable): lhs, rhs = rhs, lhs if isinstance(rhs, Variable) or not rhs.contains_leaf(lhs): add_subs = Substitution() add_subs.replace(lhs, rhs) subs.compose(add_subs) eqs = [(add_subs.apply(lhs), add_subs.apply(rhs)) for lhs, rhs in eqs] else: return None else: return None return subs
def visit_App(self, node): m1 = self.visit(node.left_exp) if not isinstance(m1, Lambda): raise TypeError m2 = self.visit(node.right_exp) sub = Substitution(m2, m1.var) return self.visit(sub.subst(m1.exp))
def resolve(rgoal, clause): rgoal = rgoal.copy() clause = clause.copy() if len(rgoal.get_terms()) > len(clause.get_terms()): return resolve(clause, rgoal) if not is_suitable(rgoal, clause): return False theta = Substitution() for goal_term in rgoal.get_terms(): op = goal_term.get_op() suitable_terms = clause.find_term_by_op(op) if suitable_terms == False: continue for suitable_term in suitable_terms: if goal_term.isNegative == suitable_term.isNegative: continue theta = Substitution() unify(goal_term, suitable_term, theta) if theta is not False: clause.remove(suitable_term) rgoal.remove(goal_term) break result = CNF(rgoal.get_terms() + clause.get_terms()) for term in result.terms: theta.SUBST(term) return result
def key(self,text,enc): dict = {} with open(text,'r+b') as f: with open(enc,'r+b') as f1: while 1: read_data = f.read(1) read_enc = f1.read(1) if not read_data: break dict[ ord( read_data ) ] = ord( read_enc ) output = open("substituition_key.txt",'w+b') for key, value in dict.items(): output.write( chr( key ) ) output.write( chr( value ) ) output.write( "\n" ) output.flush() output.close() substitution = Substitution() test = substitution.decipher(enc,"substituition_key.txt")
def test_substitution_encrypt(): plaintext = ciphertexts['plaintext'] desired_ciphertext = ciphertexts['Substitution'] cipher = Substitution(30) encrypted_text = cipher.encrypt(plaintext) assert encrypted_text == desired_ciphertext
def fitness(position): key = "".join(alphabet[i] for i in position) substitution = Substitution(alphabet, key) original_text = substitution.decrypt(cyphertext) frequency = Frequency(n_gram, alphabet) frequency.get_frequency(original_text) res = 0 for i in range(len(n_gram)): for j in range(len(frequency.ftab[i])): res += alpha[i] * abs(frequency.ftab[i][j] - target.ftab[i][j]) return res
def visit_App(self, node): m1 = node.left_exp m2 = node.right_exp try: return App(self.visit(m1), m2) except Stuck: if not isinstance(m1, Lambda): raise TypeError try: return App(m1, self.visit(m2)) except Stuck: sub = Substitution(m2, m1.var) return sub.subst(m1.exp)
def unify(self, goal): subs = self.conclusion.unify(goal) if subs is not None and len(subs) == 1: x = list(self.variables)[0] lhs, rhs = list(subs.items())[0] if rhs is x: lhs, rhs = rhs, lhs if isinstance(rhs, Variable): res = Substitution() res.replace(rhs, self.rules_db.introduce_constant()) return res return None
def may_triggered(self, new_facts): # Check if any fact pi in new_facts is unified with a premise in rule for new_fact in new_facts: for premise in self.premises: if unify(new_fact, premise, Substitution()): return True return False
def subst(facts_1, facts_2): # Generalized Modus Ponens if len(facts_1) != len(facts_2): return False for f1, f2 in zip(facts_1, facts_2): if f1.get_predicate() != f2.get_predicate(): return False return unify(facts_1, facts_2, Substitution())
def fol_fc_ask(kb, alpha): res = set() while True: new_facts = set() for rule in KnowledgeBase.getRule(): count_premises = rule.count_premises() facts = kb.getFact() premises = itertools.permutations(facts, count_premises) for tuple_premises in premises: premises_ = [premise for premise in tuple_premises] theta = unify(rule.premise, premises_, Substitution()) if not theta: continue new_fact = rule.get_conclusion() theta.SUBST(new_fact) if new_fact not in new_facts and new_fact not in kb.getFact(): new_facts.add(new_fact) phi = unify(new_fact, alpha, Substitution()) if phi: if phi.empty(): for f in new_facts: kb.appendFact(f) res.add('true') return res res.add(phi) if not new_facts: if not res: res.add('false') return res for f in new_facts: kb.appendFact(f)
def is_suitable(rgoal, clause): if len(rgoal.get_terms()) > len(clause.get_terms()): return is_suitable(clause, rgoal) for goal_term in rgoal.get_terms(): op = goal_term.get_op() suitable_terms = clause.find_term_by_op(op) if suitable_terms == False: continue else: for suitable_term in suitable_terms: if goal_term.isNegative == suitable_term.isNegative: continue else: theta = Substitution() if unify(goal_term, suitable_term, theta) is not False: return True return False
def Replace(self, alpha): query_list = [] for i in self.facts: if alpha.predicate == i.predicate: query_list.append(alpha) return query_list if alpha.predicate in self.rules: # get rule of alpha # father -> parent, male rule = self.get_rule(alpha.predicate) num_premises = rule.get_num_premises() for i in range(num_premises): subs = Substitution() for j in range(len(rule.premises)): subs.add(rule.conclusion.args[j], alpha.args[j]) para = rule.premises[i].copy() subs.substitute(para) query_list.append(para) print('my list is: ', query_list) return query_list
n_gram_files = ["english_monograms.txt", "english_bigrams.txt"] target = Frequency(n_gram, alphabet) target.get_frequency_from_file(n_gram_files) # target.get_frequency(open("text_original.txt", "r").read()) read_cypher = False originaltext = "" cyphertext = "" if (read_cypher): cyphertext = open("text_cypher.txt", "r").read() else: # Create cypher text from originaltext_file originaltext_file = "text_original.txt" originaltext = plaintext(open(originaltext_file, "r").read(), alphabet) cyphertext = Substitution(alphabet, true_key).encrypt(originaltext) cyphertext_file = "text_cypher.txt" open(cyphertext_file, "w").write(cyphertext) # Initialize population population_size = 200 swarm = [] arr = [i for i in range(len(alphabet))] for i in range(population_size): random.shuffle(arr) swarm.append(Particle(len(alphabet), arr)) # PSO def fitness(position): key = "".join(alphabet[i] for i in position)
def refreshing_substitution(self, vars): refreshing_subs = Substitution() for v in vars: refreshing_subs.replace(v, self.introduce_variable(v)) return refreshing_subs
# # Main script to actually run cipher decryption # from utils import get_args, get_text_data from substitution import Substitution from vigenere import Vigenere from caesar import Caesar args = get_args() file_data = get_text_data(args['FILENAME']) text = file_data if args['CIPHER'] == 'SUBSTITUTION': substitution = Substitution() if args['SHOULD_ENCRYPT']: key = args['ENCRYPTION_KEY'] encrypted = substitution.encrypt(text, key) print(encrypted) elif args['SHOULD_DECRYPT']: decrypted = substitution.decrypt(text) print(decrypted) elif args['CIPHER'] == 'VIGENERE': vigenere = Vigenere() if args['SHOULD_ENCRYPT']: key = args['ENCRYPTION_KEY'] encrypted = vigenere.encrypt(text, key)
def backward_chaining(kb, alpha, theta): # check if alpha is empty if len(alpha) == 0: return theta # local variable to get answer answer = Substitution(); # pop a sub goal sub_goal = alpha.pop() # ********************************************************************* # if alpha is proved in knowledge base # check if alpha is a fact if sub_goal.predicate in kb.fact_predicate: # if theta set is include substitutions if len(theta) != 0: satisfy_element_index = [] sub_satisfied_theta_list = [] # substitute these substitution onto sub_goal k = 0 while k < len(theta): subst_value = theta[k] phi = sub_goal.copy() subst_value.substitute(phi) # check for if phi has a varialbe or not. Ex : "parent(X,harry_potter)." if utils.is_contain_variable(phi): for fact in kb.facts: sub_theta = unify(phi, fact, Substitution()) if not sub_theta: continue # if sub_theta is a successful substitution sub_phi = phi.copy() sub_theta.substitute(sub_phi) if sub_phi in kb.facts: if sub_theta not in sub_satisfied_theta_list: sub_satisfied_theta_list.append(sub_theta) k += 1 # else, phi is a fact to check true or false else: if phi in kb.facts: # if sub_goal is proven in kb, then return satisfy_element_index.append(k) k += 1 # add satisfied element with index in list if len(satisfy_element_index) != 0: new_theta = [] for i in satisfy_element_index: new_theta.append(theta[i]) # update theta theta = new_theta return backward_chaining(kb, alpha, theta) if len(sub_satisfied_theta_list) != 0: theta = sub_satisfied_theta_list return backward_chaining(kb, alpha, theta) # Pre-check if current facts are enough to answer/ find a substitution for sub_goal count = 0 for fact in kb.facts: phi = unify(fact, sub_goal, Substitution()) if phi: count += 1 if phi.empty(): # if sub_goal is proven in kb. There is no sub_goal adding. This sub_goal is done return backward_chaining(kb,alpha,theta) else: theta.append(phi) return backward_chaining(kb, alpha, theta) # ********************************************************************* # if alpha is a rule if sub_goal.predicate in kb.rule_conclusion_predicate: # get rule of sub_goal rule = kb.get_rule(sub_goal.predicate) num_premise = rule.get_num_premises() # get a list contains rule's premises premise_list = [] i = 0 while i < num_premise: premise_list.append(rule.premises[i]) i += 1 conclusion = rule.conclusion sub_theta = unify(conclusion, sub_goal, Substitution()) subs_value_for_premise = [] for premise in premise_list: temp_premise = premise.copy() sub_theta.substitute(temp_premise) subs_val = unify(premise, temp_premise, Substitution()) subs_value_for_premise.append(subs_val) i = 0 while i < len(premise_list): subs_val = subs_value_for_premise[i] premise = premise_list[i] subs_val.substitute(premise) alpha.append(premise) i += 1 return backward_chaining(kb, alpha, theta) #return res
from substitution import Substitution from transposition import Transposition test_message = "ABCD abcd ZYXW" sub_coded_message = Substitution.Encode(test_message, 4) sub_decoded_message = Substitution.Decode(sub_coded_message, 4) print("Encoding by Substitution: " + sub_coded_message) print("Decoding by Substitution: " + sub_decoded_message) trans_coded_message = Transposition.Encode(test_message, 3) print("Encoding by Transposition: " + trans_coded_message) trans_decoded_message = Transposition.Decode(trans_coded_message, 3) print("Decoding by Transposition: " + trans_decoded_message)
def visit_LetIn(self, node): sub = Substitution(self.visit(node.exp), node.var) return self.visit(sub.subst(node.body))
def visit_LetIn(self, node): try: return LetIn(node.var, self.visit(node.exp), node.body) except Stuck: sub = Substitution(node.exp, node.var) return sub.subst(node.body)
transposition = Transposition() if option == "c": transposition.cipher(from_file,int(key)) elif option == "d": transposition.decipher(from_file,int(key)) else: print "Option doesn't exist." elif algorithm == "v": vigenere = Vigenere() if option == "c": vigenere.cipher(from_file,key) elif option == "d": vigenere.decipher(from_file,key) else: print "Option doesn't exist." elif algorithm == "s": substitution = Substitution() if option == "c": substitution.cipher(from_file,key) elif option == "d": substitution.decipher(from_file,key) else: print "Option doesn't exist." else: print "Algorithm doesn't exist."
def run(): b = True while b: print '##########MENU##########' choise = \ raw_input('''What do you want to do? 1.Encrypt with caesar 2.Decrypt with caesar 3.Encrypt with subsitution 4.Decrypt with subsitution 5.Try to hack the substitution method 6.Vigener encrypt 7.Vigener decrypt 8. Diffi-Helmann keys 9.Exit ''') if choise == '9': b = False elif choise == '6': word = raw_input('Input word ').strip() key = raw_input('Input key ') vig = Vigener(word, key) print 'ENCRYPTED= ' + vig._encrypt() elif choise == '7': word = raw_input('Input word ').strip() key = raw_input('Input key ') vig = Vigener(word, key) print 'DECRYPTED= ' + vig._decrypt() elif choise == '1': word = raw_input('Input word ').strip() key = int(raw_input('Input key ')) caesa = Caesar(word, key) print 'ENCRYPTED= ' + caesa._encrypt() elif choise == '2': word = raw_input('Input word ').strip() key = int(raw_input('Input key ')) caesa = Caesar(word, key) print 'DECRYPTED= ' + caesa._decrypt() elif choise == '3': word = raw_input('Input word ').strip() subs = Substitution(word) print 'ENCRYPTED= ' + subs._encrypt() elif choise == '4': word = raw_input('Input word ').strip() subs = Substitution(word) print 'DECRYPTED= ' + subs._decrypt() elif choise == '5': word = raw_input('Input word ').strip() subs = Substitution(word) new = subs.frequency_analysis() print 'RESULT = ' + new while True: choise = \ raw_input('''What do you want to do? 1.Replace symbols 2.Exit ''') if choise == '1': a = raw_input('What to replace?') b = raw_input('With what to replace?') new = subs.repl(new, a, b) print 'RESULT = ' + new elif choise == '2': break elif choise == '8': a = int(raw_input('Secret value of first ')) g = int(raw_input('Value of g ')) p = int(raw_input('Value of p ')) b = int(raw_input('Secret value of second ')) diffi = DiffiHellmann(a, g, p, b) print 'Checking if keys is the same. It may take some time ' print str(diffi._get_keys()) else: print 'Make a right choise'
def forward_chaining(kb, alpha): res = set() ## Check if alpha is proved in knowledge base for fact in kb.facts: phi = unify(fact, alpha, Substitution()) if phi: if phi.empty(): res.add('true') return res res.add(phi) last_generated_facts = kb.facts.copy() while True: new_facts = set() # Optimize: Incremental forward chaining # At iteration t, check a rule only if its premises includes at least # a conjunct pi that unified with the fact pi' newly inferred at iteration t - 1 for rule_predicate in kb.rules: rule = kb.get_rule(rule_predicate) if not rule.may_triggered(last_generated_facts): continue num_premises = rule.get_num_premises() # Get facts that relevant to the current rule potential_facts = kb.get_potential_facts(rule) # Check if rule contains premises with the same predicate if not rule.dup_predicate: potential_premises = itertools.combinations( sorted(potential_facts), num_premises) else: # Assumption on order of premises may failed on something like grandparent rule with two parent relations potential_premises = itertools.permutations( potential_facts, num_premises) for tuple_premises in potential_premises: fact_premises = [premise for premise in tuple_premises] # get a subtitution of kb.facts (relevant to rule) in rule premises theta = subst(rule.premises, fact_premises) if not theta: continue # subtitute theta to conclusion new_fact = rule.conclusion.copy() theta.substitute(new_fact) # if new fact is not a changed_name clause from a clause in kb if new_fact not in new_facts and new_fact not in kb.facts: new_facts.add(new_fact) # add new fact to fact list phi = unify( new_fact, alpha, Substitution()) # unify new_fact with the query if phi: # if is a "true" answer or a substitution if phi.empty(): kb.facts.update(new_facts) res.add('true') return res res.add(phi) last_generated_facts = new_facts if not new_facts: # if new_facts is an empty set if not res: # if res is an empty set too. This mean no satisfied substitution res.add('false') return res kb.facts.update(new_facts)
def simulate(self, stat_writer=None): self.sort_plays() for i in range(len(self.plays)): play = self.plays[i] try: play_str = self.get_play_description_string(play) play_time = play.get_time() if self.num_ongoing_fouls < 0: raise Exception( "Number of on going fouls should never be negative and it is : ", self.num_ongoing_fouls) if play.event_msg_type == 1: #made field goal self.handle_point_scored(play, play.option1) elif play.event_msg_type == 4: #REBOUND rebounder = play.person1 self.tr += 1 elif play.event_msg_type == 5: #Turnover self.to += 1 elif play.event_msg_type == 6 or play.event_msg_type == 7: #Foul or Violation if play.will_result_in_ft(): self.num_ongoing_fouls += 1 elif play.event_msg_type == 3 and play.action_type != 0: #FREE THROW self.handle_ft(play) elif play.event_msg_type == 8: #SUBSTITUTION to_add = play.person2 to_bench = play.person1 # #only make sub until after free throw is completed if self.num_ongoing_fouls == 0: self.make_sub(self.get_team_id(to_add), to_add, to_bench) else: self.scorers_table.append( Substitution(to_add, to_bench)) elif play.event_msg_type == 12: #START period # print("STARTING QUARTER") self.team_fouls = [0, 0] self.active_players[0] = self.get_starters_for_period( play.period, 0) self.active_players[1] = self.get_starters_for_period( play.period, 1) elif play.event_msg_type == 16: #END OF GAME if stat_writer: self.write_all_ratings(stat_writer) if self.is_end_possession(play): self.switch_possession(play) self.prev_play = play except Exception as e: print("==============================") error_plays = self.plays[i - 5:i + 5] for error_play in error_plays: if error_play == play: print("******************************") play_str = self.get_play_description_string(error_play) play_time = error_play.get_time() print(play_time, play_str, error_play) if error_play == play: print("******************************") raise e
def forward_chaining(kb, alpha): res = set() # Pre-check if current facts are enough to answer for fact in kb.facts: phi = unify(fact, alpha, Substitution()) if phi: if phi.empty(): res.add('true') return res res.add(phi) last_generated_facts = kb.facts.copy() while True: new_facts = set() # Optimize: Incremental forward chaining # At iteration t, check a rule only if its premises includes at least # a conjunct pi that unified with the fact pi' newly inferred at iteration t - 1 for rule in kb.rules: if not rule.may_triggered(last_generated_facts): continue num_premises = rule.get_num_premises() # Get facts that relevant to the current rule potential_facts = kb.get_potential_facts(rule) # Check if rule contains premises with the same predicate if not rule.dup_predicate: potential_premises = itertools.combinations( sorted(potential_facts), num_premises) else: # Assumption on order of premises may failed on something like grandparent rule with two parent relations potential_premises = itertools.permutations( potential_facts, num_premises) for tuple_premises in potential_premises: premises = [premise for premise in tuple_premises] theta = subst(rule.premises, premises) if not theta: continue new_fact = rule.conclusion.copy() theta.substitute(new_fact) if new_fact not in new_facts and new_fact not in kb.facts: new_facts.add(new_fact) phi = unify(new_fact, alpha, Substitution()) if phi: if phi.empty(): kb.facts.update(new_facts) res.add('true') return res res.add(phi) last_generated_facts = new_facts if not new_facts: if not res: res.add('false') return res kb.facts.update(new_facts)