Esempio n. 1
0
 def __init__(self, id, if_subject, if_condition, then_subject, then_condition, if_and=False, if_subject2 = None, if_condition2 = None):
     self.id = id
     self.if_fact = Fact(if_subject, if_condition)
     self.then_fact = Fact(then_subject, then_condition)
     self.if_and = if_and
     if if_and == True:
         self.if_fact2 = Fact(if_subject2, if_condition2)
Esempio n. 2
0
	def handleFactForParentheses(self, fact):
		tmp = None
		if fact == 1 or fact == 0:
			tmp = Fact("-")
			tmp.setValue(b)
			return tmp
		else:	
			tmp = fact
		return tmp
Esempio n. 3
0
	def opn_or(self, l, r, facts):
		l = self.handleFactForParentheses(l)
		r = self.handleFactForParentheses(r)
		result = Fact(l.getName())
		if ( l.getValue() == 1 or r.getValue() == 0 ):
			result.setValue( 1 )
		elif ( l.getValue() == 0 or r.getValue() == 1 ):
			result.setValue( 0 )
		elif ( l.getValue() == -1 and r.getValue() == -1 ):
			result.setValue( -1 )
		else:
			result.setValue( 0 )
		return (result)
Esempio n. 4
0
def convert_to_fact_instances(engine, tokens):
    "Convert facts literals to instances of Fact"
    for index, elem in enumerate(tokens):
        if isinstance(elem, str):
            # Case : "(A"
            if re.match(r"\([a-zA-Z]$", elem):
                fact = Fact(elem[1], engine)
                tokens[index:index + 1] = ["(", fact]
            # Case : "A)"
            elif re.match(r"[a-zA-Z]\)$", elem):
                fact = Fact(elem[0], engine)
                tokens[index:index + 1] = [fact, ")"]
            # Nomal case : "A
            elif re.match(r"[a-zA-Z]$", elem):
                tokens[index] = Fact(elem, engine)
Esempio n. 5
0
    def ParseRule(rule_str):
        rule_str = rule_str.strip().rstrip('.').replace(' ', '')
        index = rule_str.find(':-')

        conclusion = Fact.ParseFact(rule_str[:index])
        premises = []
        premises_str = rule_str[index + 2:].split('),')
        if 'not' in premises_str[len(premises_str) - 1]:
            premises_str.remove(premises_str[len(premises_str) - 1])
        for idx, premise_str in enumerate(premises_str):
            if idx != len(premises_str) - 1:
                premise_str += ')'
            premise = Fact.ParseFact(premise_str)
            premises.append(premise)
        return Rule(conclusion, premises)
Esempio n. 6
0
    def parse(str_rule):
        # Example: daughter(Person, Parent) :- female(Person), parent(Parent, Person).
        str_rule = str_rule.strip().rstrip('.').replace(' ', '')
        idx = str_rule.find(':-')

        conclusion = Fact.parse(str_rule[:idx])
        premises = []
        list_fact = str_rule[idx + 2:].split('),')

        for idx, str_fact in enumerate(list_fact):
            if idx != len(list_fact) - 1:
                str_fact += ')'
            fact = Fact.parse(str_fact)
            premises.append(fact)

        return Rule(conclusion, premises)
Esempio n. 7
0
    def __init__(self, conclusion=Fact(), premises=[]):
        self.conclusion = conclusion  # Inferred fact
        self.premises = premises  # Conditions: list of facts
        self.ops = self.get_ops()  # List of related relations and functions

        self.premises.sort()
        self.dup_predicate = self.detect_dup_predicate()
Esempio n. 8
0
def main(args):
    # preprocess
    text = args.text
    fact_type = FactType.FAKE if args.fact == "fake" else FactType.TRUTH
    new_fact = Fact(text, pre_processor.preprocess(text), fact_type)

    if not args.append:
        # just create the new fact and print the json
        print(json.dumps(add_new_fact(new_fact).to_json_object()))
        return

    # compare with facts
    text_comp.load_model(cfg.DEFAULT_MODEL_FILE)
    similar_fact_tuples = text_comp.match_fact(new_fact,
                                               db_manager.get_all_facts())

    similar_fact_tuples = similar_fact_tuples[:cfg.ADD_FACT_CHOOSE_AMOUNT]

    similar_fact_tuples = list(
        filter(lambda f: f[1] >= cfg.SIMILARITY_THRESHOLD,
               similar_fact_tuples))
    similar_facts = [fact_tuple[0] for fact_tuple in similar_fact_tuples]

    if not similar_facts:
        # no similar fact yet
        # -> create new fact
        # -> retrain model
        add_new_fact(new_fact)
    else:
        # there are similar facts:
        # -> print top facts
        print("These are facts that show similarities to the given text:")
        for fact in similar_facts:
            print(fact.id, fact.content)

        # get input from admin
        matched_fact_id = input("Type id of fact (or -1): ")

        if int(matched_fact_id) == -1:
            # admin: doesn't match any of the given facts:
            # -> create new fact
            add_new_fact(new_fact)
        else:
            # admin: matches a given fact:
            matched_fact = next(f for f in similar_facts
                                if f.id == matched_fact_id)
            if matched_fact is not None:
                # append preprocess to given fact
                new_processed = [
                    proc for proc in fact.processed
                    if proc not in matched_fact.processed
                ]
                db_manager.add_to_processed(matched_fact_id, new_processed)
                # -> retrain model TODO (not currently possible)

                print("Added following key words to the fact: ", new_processed)
            else:
                print(
                    "The given id does not match with any of the similar facts"
                )
Esempio n. 9
0
def main(args):
    test_fact = Fact(args.text, pre_processor.preprocess(args.text),
                     FactType.TRUTH)

    all_facts = db_manager.get_all_facts()

    text_comp.load_model(cfg.DEFAULT_MODEL_FILE)
    matches = text_comp.match_fact(test_fact, all_facts)

    best_match = matches[0]

    threshold = cfg.SIMILARITY_THRESHOLD

    if args.threshold is not None:
        threshold = args.threshold

    if best_match[1] >= threshold:
        output = {
            'fact': best_match[0].to_json_object(),
            'similarity': float(best_match[1])
        }
    else:
        output = {'fact': None, 'similarity': 0.0}

    print(json.dumps(output))
Esempio n. 10
0
    def CreateKB(kb, clauses):
        while clauses:
            clause, clauses = Clause.NextClause(clauses)
            clause_type = Clause.Categorize(clause)
            if clause_type == 'fact':
                fact = Fact.ParseFact(clause)
                kb.AddFact(fact)
            elif clause_type == 'rule':
                if ';' in clause:
                    idx = clause.index(':-')
                    temp_clause = clause[idx + 2:].rstrip('.')
                    conclusion = clause[0:idx]
                    conditions_raw = temp_clause.split(';')
                    conditions = []
                    for condition in conditions_raw:
                        temp = condition.strip()
                        temp = temp[1:len(temp) - 1]
                        conditions.append(temp)

                    rules = []
                    for condition in conditions:
                        rule_str = conclusion + ':-' + condition + '.'
                        rules.append(rule_str)
                    for clause in rules:
                        rule = Rule.ParseRule(clause)
                        kb.AddRule(rule)
                elif ';' not in clause:
                    rule = Rule.ParseRule(clause)
                    kb.AddRule(rule)
Esempio n. 11
0
    def parse_rule(rule_str):
        # Example: daughter(Person, Parent) :- female(Person), parent(Parent, Person).
        rule_str = rule_str.strip().rstrip('.').replace(' ', '')
        sep_idx = rule_str.find(':-')

        # Get conclusion (lhs) and premises (rhs) seperated by ':-'
        conclusion = Fact.parse_fact(rule_str[:sep_idx])
        premises = []
        list_fact_str = rule_str[sep_idx + 2:].split('),')

        for idx, fact_str in enumerate(list_fact_str):
            if idx != len(list_fact_str) - 1:
                fact_str += ')'
            fact = Fact.parse_fact(fact_str)
            premises.append(fact)

        return Rule(conclusion, premises)
Esempio n. 12
0
def compare_test_to_db(test_query):
    preprocessor = PreProcessor()
    facts = []
    with open('facts.txt', 'r') as fact_file:
        fact_data = fact_file.read().split("\n")
    for data in fact_data:
        fact = Fact(data, preprocessor.preprocess(data), FactType.TRUTH)
        facts.append(fact)

    text_comp = TextComparator()
    # text_comp.train_model(facts)
    file_name = "test"
    # text_comp.save_model(file_name)
    text_comp.load_model(file_name)
    test_fact = Fact(test_query, preprocessor.preprocess(
        test_query), FactType.TRUTH)
    return text_comp.match_fact(test_fact, facts, topn=3)
Esempio n. 13
0
    def parse_rule(rule_str):
        # Example: daughter(Person, Parent) :- female(Person), parent(Parent, Person).
        rule_str = rule_str.strip().rstrip('.').replace(
            ' ', '')  # format rule to standard
        sep_idx = rule_str.find(':-')

        # Get conclusion (lhs) and premises (rhs) seperated by ':-'
        conclusion = Fact.parse_fact(rule_str[:sep_idx])
        premises = []
        list_fact_str = rule_str[sep_idx + 2:].split(
            '),')  # get list of conditions, each condition separated by ')'

        for idx, fact_str in enumerate(list_fact_str):
            if idx != len(list_fact_str) - 1:
                fact_str += ')'  # because split by ')', some condition lost this character, we need to format it
            fact = Fact.parse_fact(fact_str)
            premises.append(fact)

        return Rule(conclusion, premises)
Esempio n. 14
0
def test():
    db_man = DBManager()
    facts = db_man.get_all_facts()
    print(facts)
    fact1 = Fact("some content that is raw and true",
                 ["some", "content", "true"], FactType.TRUTH)
    db_man.add_fact(fact1)
    facts = db_man.get_all_facts()
    print(facts)
    fact2 = Fact("some content that is raw and false",
                 ["some", "content", "false"], FactType.FAKE)
    db_man.add_fact(fact2)
    facts = db_man.get_all_facts()
    print(facts.__str__())

    print(db_man.get_fact(1))

    db_man.add_to_processed(1, ["HELO", "250"])
    print(db_man.get_fact(1))
Esempio n. 15
0
    def __init__(self):
        create_wall_comp = Skill(use_function=create_wall,
                                 targeting_skill=True,
                                 targeting_type='single',
                                 targeting_message=Message(
                                     'Select tile to make wall', tcod.cyan))
        create_wall_fact = Fact('Create Wall',
                                'Self explanatory',
                                skill=create_wall_comp)

        break_wall_comp = Skill(use_function=break_wall,
                                targeting_skill=True,
                                targeting_type='single',
                                targeting_message=Message(
                                    'Select tile to destoy wall', tcod.cyan))
        break_wall_fact = Fact('Break Wall',
                               'Self explanatory',
                               skill=break_wall_comp)

        move_wall_comp = Skill(use_function=move_wall,
                               targeting_skill=True,
                               targeting_type='multi',
                               targeting_message=Message(
                                   'Select tile to move wall', tcod.cyan))
        move_wall_fact = Fact('Move Wall',
                              'Self explanatory',
                              skill=move_wall_comp)

        teleport_comp = Skill(use_function=teleport,
                              targeting_skill=True,
                              targeting_type='single',
                              targeting_message=Message(
                                  'Select tile to teleport', tcod.cyan))
        teleport_fact = Fact('Teleport',
                             'Self explanatory',
                             skill=teleport_comp)

        self.skills = [
            create_wall_fact, break_wall_fact, move_wall_fact, teleport_fact
        ]
 def declare(kb, list_data):  # initialize a knowledge database
     while list_data:
         current_line, list_data = Sentence.read_list(
             list_data)  # return a comment/fact/rule and update list
         type = Sentence.classify(current_line)
         if type == 'fact':
             fact = Fact.parse_fact(current_line)
             kb.add_fact(fact)
             kb.add_fact_predicate(fact.predicate)
         elif type == 'rule':
             rule = Rule.parse_rule(current_line)
             kb.add_rule(rule)
             kb.add_rule_conclusion_predicate(rule.conclusion.predicate)
Esempio n. 17
0
def process(file, isInput = False):
    global knowledgeBase, infertype
    cmds = []
    while True:
        if isInput:
            sys.stdout.write('? ' if len(cmds) == 0 else '|    ')
            sys.stdout.flush()
        line = file.readline()
        if line == "": break
        s = re.sub("#.*", "", line[:-1]) # ignore comments
        s = re.sub(" ", "", s) # remove white spaces
        if s == "": continue
        if s[-1] == '.': 
            s=s[:-1]
            cmds.append(s)
        # if punc == '.': print(s)
            for cmd in cmds:
                if cmd == "": continue
                if cmd == 'printKB':
                    print(knowledgeBase)
                elif cmd == 'halt': sys.exit(0)
                else: 
                    if isInput:
                        if (infertype == Inferring.FORWARD.value):
                            print(fol_fc_ask(knowledgeBase, Fact.parse(cmd)))
                        elif (infertype == Inferring.BACKWARD.value):
                            bc = BackwardChaining(knowledgeBase, Fact.parse(cmd))
                            print(bc.answer())
                        elif (infertype == Inferring.RESOLUTION.value):
                            print(resolution_search(knowledgeBase, Fact.parse(cmd)))
                    else:
                        if (cmd.find(":-") == -1):
                            knowledgeBase.appendFact(Fact.parse(s))
                        else:
                            knowledgeBase.appendRule(Rule.parse(s))
            cmds = []
        else: cmds.append(s)
    if not isInput:
        file.close()
Esempio n. 18
0
def extractFacts(article):
    facts = list()
    sentences = article.body.split('.')
    source = {'title': tryTitle(article), 'link': tryLink(article)}
    for s in sentences:
        c = checkability(s)
        if c > CHECK_THRESHOLD:
            facts.append(
                Fact(published_date=tryDate(article),
                     distilledFact=str(distillFact(s)),
                     factStrings=[s],
                     factHash=hashFact(s),
                     confidence=c,
                     sources=[source]))
    return facts
Esempio n. 19
0
def process_csv(blob_info):
    blob_reader = blobstore.BlobReader(blob_info.key())
    reader = csv.reader(blob_reader, delimiter=',')
    # get file name
    csv_file_name =  blob_info.filename
    # get csv header
    [prefix, postfix] = csv_file_name.split(".")
    header = reader.next()
    temp_header = header
    header = []
    for col in temp_header:
        header.append(prefix + "." + col)
        

    for row in reader:
        col_counter = 0
        corresponding_facts = CorrespondingFacts()
        corresponding_facts.put()
        fact_keys = []
        if csv_file_name == "Sales.csv":
            date_str = row[4]
        for col in row:
            date =  datetime.datetime.strptime("1/1/14", '%m/%d/%y').date()
            if csv_file_name == "Sales.csv":
                 date = datetime.datetime.strptime(date_str, '%m/%d/%y').date()
            logging.info(col + "/n")
            fact = Fact(value = col,
                        name = header[col_counter],
                        corresponding_facts = corresponding_facts.key,
                        date = date)
            fact.put()
            fact_keys.append(fact.key)
            col_counter += 1
            corresponding_facts.facts = fact_keys
            corresponding_facts.names = header
            corresponding_facts.put()
Esempio n. 20
0
    def add_query(self, tokenized_line, empty=False):
        """
            Add query item to self.query array
            Input: ?XZY
        """
        if empty:
            self.query = []

        if not tokenized_line.startswith("?"):
            return
        for char in tokenized_line[1:]:
            if char in self.facts:
                raise ParsingError(
                    f"Query must be unique : {char} is present twice!")
            new_fact = Fact(char, self)
            self.query.append(new_fact)
Esempio n. 21
0
    def add_facts(self, tokenized_line, empty=False):
        """
            Add facts to self.facts array
            Input: "=ABC"
        """
        if empty:
            self.facts = set()

        if not tokenized_line.startswith("="):
            return
        for char in tokenized_line[1:]:
            if char in self.facts:
                raise ParsingError(
                    f"Facts must be unique : {char} is present twice!")
            new_fact = Fact(char, self)
            self.facts.add(new_fact)
Esempio n. 22
0
def create_fact(fact_line: str) -> Fact:
    """
    Создание факта из строки
    :param fact_line: Строка с фактом
    :return: Факт
    """
    open_bracket_idx, close_bracket_idx = fact_line.index(
        '('), fact_line.index(')')
    fact_name = fact_line[:open_bracket_idx].strip()
    fact_args = fact_line[open_bracket_idx + 1:close_bracket_idx].split(',')
    fact_args = [
        Argument(name=x.strip(),
                 atype=Argument.CONSTANT
                 if x.strip()[0].isupper() else Argument.VARIABLE)
        for x in fact_args
    ]
    ret_fact = Fact(name=fact_name, arguments=fact_args)
    return ret_fact
Esempio n. 23
0
def main(args):
    if args.reset:
        really = input(
            "Do you really want to reset the database? This action cannot be undone (y/N): ")
        # print(really)
        if really.lower() == "y":
            db_manager.create_table(True)
            print("database successfully reset")

    if args.load is not None:
        # load to database
        with open(args.load, 'r') as text_file:
            fact_data = text_file.read().split("\n")

        facts = []
        for data in fact_data:
            fact_type = FactType.TRUTH
            if "[fake]" in data or "[0]" in data:
                fact_type = FactType.FAKE
            
            data = re.sub("\[([^\]|]*)\]", '', data)
                
            fact = Fact(data, pre_processor.preprocess(data), fact_type)
            facts.append(fact)
        for fact in facts:
            db_manager.add_fact(fact)
        print("loaded " + str(len(facts)) + " facts to database")

    if args.retrain:
        # train and save the NN
        print("Starting to retrain the model ...")
        all_facts = db_manager.get_all_facts()
        text_comp.train_model(all_facts)
        text_comp.save_model(cfg.DEFAULT_MODEL_FILE)
        print("... retrained the model and saved to " + cfg.DEFAULT_MODEL_FILE)

    if args.printdb:
        all_facts = db_manager.get_all_facts()
        print("===== START OF DATABASE (" + str(len(all_facts)) + " rows) =====")
        for fact in all_facts:
            print(fact)
        print("===== END OF DATABASE =====")
Esempio n. 24
0
def unify(x, y, theta):
    if theta is False:
        return False
    if (x == y):
        return theta
    if (Fact.is_variable(x)):
        return unifyVar(x, y, theta)
    elif (Fact.is_variable(y)):
        return unifyVar(y, x, theta)
    elif (Fact.is_fact(x) and Fact.is_fact(y)):
        return unify(x.get_args(), y.get_args(),
                     unify(x.get_op(), y.get_op(), theta))
    elif (Fact.is_list(x) and Fact.is_list(y)):
        return unify(x[1:], y[1:], unify(x[0], y[0], theta))
    return False
Esempio n. 25
0
 def actualize_result(self, variables: Dict[str, str]) -> Tuple[bool, Fact]:
     """
     Актуализация результата правила (замена переменных на константы)
     :param variables: Словарь актуализированных переменных
     :return: Был ли факт актуализирован и актуализированный факт
     """
     was_actualized = False
     actualized_fact = Fact(name=self.result.name, arguments=[])
     # Идем по каждому аргументу результата
     for arg in self.result.arguments:
         # Если константа
         if arg.atype == Argument.CONSTANT:
             # То записываем без изменений
             actualized_fact.arguments.append(arg)
         else:  # Если переменная
             # Актуализируем
             actualized_argument = Argument(name=variables.get(arg.name),
                                            atype=Argument.CONSTANT)
             actualized_fact.arguments.append(actualized_argument)
             was_actualized = True
     return was_actualized, actualized_fact
Esempio n. 26
0
def resolution_search(kb, goal):
    consts = kb.getAllConsts()
    args = goal.get_args()
    var_loc = []
    for i in range(len(args)):
        if Fact.is_variable(args[i]):
            var_loc.append(i)
    if len(var_loc) == 0:
        return resolution(kb, goal)
    theta = [list() for i in range(len(var_loc))]
    newGoal = goal.copy()
    if set_variable(var_loc, 0, kb, newGoal, consts, theta) is not False:
        string = str()
        for i in range(len(theta[0])):
            line = "{"
            for j in range(len(var_loc)):
                line += "{} = {}, ".format(goal.get_args()[var_loc[j]],
                                           theta[j][i])
            string += line.rstrip(", ") + "}; "
        return string.rstrip("; ")
    return False
Esempio n. 27
0
    def get(self):
        logging.info("test")
        self.response.headers['Content-Type'] = 'text/plain'

        #-----------------
        # Test Net revenue
        #-----------------
        # NET_REVENUE = Sales.Units*Sales.Royalty Price
        #result = Fact.binaryOperation("Sales.Units",
        #                                    [["Sales.Royalty Price"]],
        #                                    "*",
        #                                    "NET_REVENUE")
        
        #result2table(result, self)
        #Fact.storeFacts(result, "NET_REVENUE")
        #Fact.fact2Table("NET_REVENUE.NET_REVENUE", self)


        #-----------------
        # Test Taxes
        #-----------------
        # TAXES = NET_REVENUE * ComissionTax.Tax
        link1 = ["NET_REVENUE.Country Code",
                 "CountryRegion.Country Code",
                 "CountryRegion.Region",
                 "ComissionTax.Region",
                 "ComissionTax.Tax Rate"]    

        link2 = ["NET_REVENUE.Units",
                 "NET_REVENUE.Vendor Identifier",
                 "ComissionTax.Vendor Identifier",
                 "ComissionTax.Tax Rate"]  

        #taxes = Fact.binaryOperation("NET_REVENUE.NET_REVENUE",[link1,link2],"*","TAXES")
        #result2table(taxes, self)
        #Fact.storeFacts(taxes, "TAXES")
        #Fact.fact2Table("TAXES.TAXES", self)    
        
        #------------------
        # Revenue After Tax
        #------------------
        # REVENUE_AFTER_TAX = NET_REVENUE - TAXES
        link1 = ["NET_REVENUE.Vendor Identifier",
                 "TAXES.Vendor Identifier",
                 "TAXES.TAXES"]

        link2 = ["NET_REVENUE.Country Code",
                 "TAXES.Country Code",
                 "TAXES.TAXES"]


        #revenues = Fact.binaryOperation("NET_REVENUE.NET_REVENUE",
        #                                [link1, link2],"-","REVENUE_AFTER_TAX")
        #result2table(revenues, self)
        #Fact.storeFacts(revenues, "REVENUE_AFTER_TAX")
        #Fact.fact2Table("REVENUE_AFTER_TAX.REVENUE_AFTER_TAX", self)    

        #------------------
        # Test sm2
        #------------------
        
        result = Fact.calculate("NET_REVENUE.NET_REVENUE","6/1/14")
        self.response.write("\n NET_REVENUE:" + str(result) + "\n")

        result = Fact.calculate("TAXES.TAXES","6/1/14")
        self.response.write("\n TAXES:" + str(result)+ "\n")

        result = Fact.calculate("REVENUE_AFTER_TAX.REVENUE_AFTER_TAX", "6/1/14")
        self.response.write("\n REVENUE_AFTER_TAX:" + str(result)+ "\n")
Esempio n. 28
0
def main():
    """ Main function called by the manage.py from the project directory.
    """
    from fact import Fact

    parser = argparse.ArgumentParser(
        description = "Run fact scripts.")
    parser.add_argument(
        '--settings',
        help = 'The path to the settings module e.g /etc/foo/bar',
        type = str,
        nargs = 1,
        )
    parser.add_argument(
        'command',
        #choices = Fact.public_methods(),
        help = 'The command you want to run.',
        nargs = 1,
        type = str,
        )
    parser.add_argument(
        'fact',
        #choices = ['all'] + all_facts(),
        help = 'The name(s) of the fact(s) to run e.g. fact_example.',
        nargs = '*',
        type = str,
        )
    args = parser.parse_args().__dict__

    sys.stdout.write(bright_white(TITLE))
    sys.stdout.write(bright_white("\nStarting at {}\n\n".format(
        datetime.now())))

    # Enable log output before loading settings so we have visibility
    # of any load errors.
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(ColourFormatter())
    log.addHandler(handler)
    log.setLevel(logging.DEBUG if __debug__ else logging.INFO)

    from pylytics.library.settings import Settings, settings

    # Attempt to configure Sentry logging.
    sentry_dsn = settings.SENTRY_DSN
    if sentry_dsn:
        # Only import raven if we're actually going to use it.
        from raven.handlers.logging import SentryHandler
        log.addHandler(SentryHandler(sentry_dsn))

    # Prepend an extra settings file if one is specified.
    settings_module = args["settings"]
    if settings_module:
        settings.prepend(Settings.load(settings_module))

    command = args['command'][0]
    commander = Commander(settings.pylytics_db)
    if command in Fact.public_methods():
        commander.run(command, *args['fact'])
    else:
        log.error("Unknown command: %s", command)

    sys.stdout.write(bright_white("\nCompleted at {}\n\n".format(
        datetime.now())))
Esempio n. 29
0
def fact_from_tuple(fact_tuple):
    return Fact(fact_tuple[1], fact_tuple[2].split(), FactType(fact_tuple[3]),
                fact_tuple[0])
Esempio n. 30
0
    test_number = "04"
    inp_file = 'test/' + test_number + '/knowledge.pl'
    query_file = 'test/' + test_number + '/query.pl'
    output_file = 'test/' + test_number + '/answers.txt'

    kb = KnowledgeBase()
    with open(inp_file, 'r') as f_in:
        data_base = f_in.readlines()
        KnowledgeBase.declare(kb, data_base)

    print('Done initialize knowledge base from {}.'.format(inp_file))

    with open(query_file, 'r') as f_query:
        with open(output_file, 'w') as f_out:
            for query_str in f_query.readlines():
                alpha = Fact.parse_fact(query_str)
                alpha_str = str(alpha) + '.'
                print(alpha_str)
                query_conclusion = kb.query(alpha, "backward")
                if isinstance(query_conclusion, bool):
                    substs = query_conclusion.__str__()
                else:
                    substs = list(query_conclusion)
                substs_str = ' ;\n'.join([str(subst)
                                          for subst in substs]) + '.\n'
                print(substs_str)
                f_out.write(alpha_str + '\n')
                f_out.write(substs_str + '\n')

    print('Results of queries from {} are written to {}.'.format(
        query_file, output_file))
Esempio n. 31
0
def fillVar(facts, letter):
	if isVar(letter):
		if not letter in facts:
			facts[letter] = Fact(letter)
Esempio n. 32
0
from elasticsearch import Elasticsearch
from pyspark.sql import SparkSession

from fact import Fact
from product_dimension import ProductDimension

spark = SparkSession.builder.appName("ProductApp").getOrCreate()

ProductDimension(spark_session=spark).csv_to_tmp_view()
Fact(spark_session=spark).csv_to_tmp_view()

fact_sample = spark.sql("""
	SELECT a.order_date,
		a.product,
		a.item_sold,
		b.gender,
		b.cmc_business_unit,
		a.product_net_cost,
		a.product_net_revenue,
		a.average_net_cost,
		a.absolute_margin,
		a.percentage_margin
	FROM (
		SELECT f.order_date,
			f.product,
			SUM(f.item_sold) item_sold,
			SUM(f.product_net_cost) product_net_cost,
			SUM(f.product_net_revenue) product_net_revenue,
			SUM(CASE WHEN f.item_sold > 0 THEN f.product_net_cost/f.item_sold ELSE 0 end) as average_net_cost,
			SUM(f.product_net_revenue - f.product_net_cost) as absolute_margin,
			SUM(CASE WHEN f.product_net_revenue > 0
Esempio n. 33
0
	def calcul(self, query, facts):
		ptr = {
			"+": self.op_add,
			"|": self.op_or,
			"^": self.op_xor,
			"!+": self.opn_add,
			"!|": self.opn_or,
			"!^": self.opn_xor
		}
		# print("Query:" + str( query ) )


		index = self.getNextOperatorIndexInQuery(query)
		
		while (index != -1):
			# print()
			# print ("index="+str(index))

		 	l = str(query[index-2])
		 	r = str(query[index-1])
		 	op = query[index]

		 	# print("fef"+ l+" "+op+" "+r )
		 	left = None
		 	right = None
		 	if (l[0] == '!'):
		 		tmpFact = Fact(l[1])
				if (l[1] != '0' and l[1] != '1'):
					tmpFact.setValue( facts[l[1]].searchValue(facts))
		 		if (tmpFact.getValue() == 0):
		 			tmpFact.setValue(1)
		 		else:
		 			tmpFact.setValue(0)
		 		left = tmpFact
		 	else:
			 	left = Fact(l) if (l == '0' or l == '1') else facts[l]
			
			if (r[0] == '!'):
				tmpFact = Fact(r[1])
				if (r[1] != '0' and r[1] != '1'):
					tmpFact.setValue( facts[r[1]].searchValue(facts))

		 		if (tmpFact.getValue() == 0):
		 			tmpFact.setValue(1)
		 		else:
		 			tmpFact.setValue(0)
		 		right = tmpFact

			else:
 				right = Fact(r) if (r == '0' or r == '1') else facts[r]

		 	# print("Query1:" + str( query ) +"result="+query[index])

		 	query[index] = str(ptr[op](left, right, facts).getValue())
		 	# print("Query2:" + str( query ) +"result="+query[index])
		 	# print("peek-2:"+query[index-2] + "peek1" + query[index-1] )
		 	query.pop(index-2)
		 	query.pop(index-1 -1)
		 	index = self.getNextOperatorIndexInQuery(query)
		 	# print("new query:" + str( query ) )

		if (query[0] == '0'):
			return 0
		elif (query[0] == '1'):
			return 1
		# print ("##"+query[0] + " str:" + str(query)[0] +" - " +str(len(query[0])))
		if len(query[0]) > 1:
			res = facts[query[0][1]].searchValue(facts);
			if res == 1:
				return 0
			else:
				return 1
		else:
			return facts[query[0]].searchValue(facts)