def aporte_idiomas_aux(self,idioma,idiomas,test=False): X = pyDatalog.Variable() Result = pyDatalog.Variable() Porcentajes = pyDatalog.Variable() lan_kb = [] inferences=[] idiomas_lista=[] percentages=[] total = 0 pyDatalog.create_terms('lista_vacia') pyDatalog.create_terms('lista_porcentaje') for i in idiomas: if(i!=idioma): if(not test): self.kb = [] self.lan = [i] self.load_db_by_language() (lista_vacia(Relation.proportionPerLan(X,idioma,i))==Result) if(not Result.v()): inferences += [Relation.proportionPerLan(X,idioma,i)] idiomas_lista += [i] total += len(Relation.proportionPerLan(X,idioma,i)) percentages += [len(Relation.proportionPerLan(X,idioma,i))] (lista_porcentaje(percentages,total)==Porcentajes) return inferences,idiomas_lista,Porcentajes
def uncle(word1, idiom1, word2, idiom2, console, data, relations): """Checks if the first word (Son) is the second word's (Father) child""" pyDatalog.create_terms('console') pyDatalog.Logic(data) if word1=="" or word2=="": return "Fill all the spaces, please." query = createQuery(word1, idiom1, word2, idiom2, "uncle", relations) print("Query: ",query) return executeQuery(query, console)
def brother(word1, idiom1, word2, idiom2, console, data, relations): """Checks if two given words are brothers in the current data's context""" pyDatalog.create_terms('console') pyDatalog.Logic(data) if word1=="" or word2=="": return "Fill all the spaces, please." query = createQuery(word1, idiom1, word2, idiom2, "brother", relations) print("Query: ",query) return executeQuery(query, console)
def cousin_level(word1, idiom1, word2, idiom2, console, data, relations): """Checks if two given words are cousins and returns their cousin level""" pyDatalog.create_terms('console') pyDatalog.Logic(data) pyDatalog.create_terms('console') if word1=="" or word2=="": return "Fill all the spaces, please." query = createQuery(word1, idiom1, word2, idiom2, "cousin_level", relations) print("Query: ",query) return executeQuery(query, console)
''' Created on 2 avr. 2013 The HASHTAG problem was the subject of a contest at PyCon 2013. Problem description : https://picasaweb.google.com/lh/photo/u_6ZWCrTUNVADkPAyyFvfKbReIcFkkE5l5WZw-QBbLc Discussion : http://uthcode.appspot.com/2013/03/Hashtag-at-pycon Below is a solution based on pyDatalog @author: pcarbonn ''' from pyDatalog import pyDatalog, pyEngine import time pyDatalog.create_terms('solution,move,X,Y,Z, Path,Path2, Steps,Steps1,Steps2') # valid moves are exchange of 1<->2, 1<->4, ... @pyDatalog.predicate() def move3(X,N,Y): for n1,n2 in ((0,1),(0,3),(1,2),(1,4),(2,5),(3,4),(3,6),(4,5),(4,7),(5,8),(6,7),(7,8)): if X.id[n1]=='*' or X.id[n2]=='*': y = list(X.id) y[n1], y[n2] = y[n2], y[n1] yield (X.id, '%s-%s,' % (n1+1, n2+1), ''.join(y)) # a solution to go from X to Y is a direct move, # or a solution from X to Z, followed by a direct move from Z to Y (solution[X,Y]==(Steps,Path)) <= ( move(X,Steps1,Z) & (solution[Z,Y]==(Steps2,Path2)) & (X!=Y) & (X._not_in(Path2)) & (Y._not_in(Path2))
import string import itertools as it from pyDatalog import pyDatalog # -------------------------------------------------------------------- # create lots of variable names for convenience. # A-Z, A1-A9 ... Z1-Z9 for s in string.uppercase[:26]: pyDatalog.create_terms(s) for n in range(1,9): pyDatalog.create_terms(s+str(n)) # -------------------------------------------------------------------- # LogKB Fact management def loadFacts(fileName): """ Convenience function to open a fact file and load it into the LogKB. """ facts = open(fileName) pyDatalog.load(facts.read()) facts.close() def retractAll(pname, arity): """ retract all facts of given predicate name and arity from the LogKB. """ vnames = ["V" + str(x) for x in range(0,arity)]
from pyDatalog import pyDatalog as pl #MINIPROJEKT #komis samochodowy pl.create_terms( 'car, X, Marka, Model, Rok, Moc, TypPaliwa, Przebieg, searchForCars, searchYoungCars, searchSmallPrzebieg' ) +car('Mazda', '3', 2010, 150, 'benzyna', 45000) +car('Renault', 'Megane', 2008, 115, 'benzyna', 140000) +car('BMW', 'X5', 2007, 210, 'diesel', 180000) +car('Peugeot', '307', 2005, 110, 'gaz', 120000) +car('Renault', 'Scenic', 2008, 120, 'diesel', 250000) +car('Peugeot', '206', 1999, 90, 'gaz', 300000) +car('BMW', 'X3', 2008, 190, 'diesel', 175000) +car('Audi', 'A4', 2002, 140, 'benzyna', 250000) +car('Audi', 'A6', 2005, 170, 'diesel', 190000) +car('Toyota', 'Yaris', 2009, 80, 'gaz', 130000) +car('Ford', 'Galaxy', 2000, 130, 'benzyna', 140000) +car('Tesla', 'Model S', 2013, 300, 'elektryczny', 80000) +car('Volkswagen', 'Passat', 2001, 100, 'gaz', 230000) +car('Volkswagen', 'Beetle', 1963, 60, 'benzyna', 130000) +car('Ford', 'Focus', 1999, 90, 'diesel', 260000) +car('Mitsubishi', 'Eclipse', 2005, 160, 'benzyna', 130000) +car('Mazda', 'RX-7', 2005, 130, 'benzyna', 160000) +car('Seat', 'Leon', 2002, 150, 'benzyna', 150000) +car('Opel', 'Astra', 1997, 80, 'gaz', 280000) +car('Mercedes', 'GLK 220', 2009, 180, 'diesel', 50000) searchForCars(Marka, Model, Rok, Moc, TypPaliwa, Przebieg) <= car( Marka, Model, Rok, Moc, TypPaliwa, Przebieg)
from pyDatalog import pyDatalog from sympy import * import string import math import csv from collections import defaultdict fictionFile = 'scene.csv' MAX_WIDTH = 3872.0 MAX_HEIGHT = 2592.0 UNIT = 16.0 #pyDatalog.create_terms('math') pyDatalog.create_terms('X', 'Y', 'Z', 'A', 'B', 'C') class CsvToDatalog(object): """docstring for CsvToDatalog""" def __init__(self): self.statements = [] self.terms= [] def create_terms(self,row): pred= row[0].replace('-','_') self.terms.append(pred) def create_statement(self, row): subject=row.pop(0) pred= row.pop(0).replace('-','_') objs = ["'{}'".format(v) for v in row] statement = "+ {pred}('{subject}', {objs})".format(pred=pred, subject=subject, objs=",".join(objs)) self.statements.append(statement)
from pyDatalog.pyDatalog import create_terms create_terms('X,Y,Z,N0,N1,N2') create_terms('abc,answer') +abc('a','b','c') abc(X,Y,Z) <= abc(X[0],Y[0],Z[0]) & abc(X[1:],Y[1:],Z[1:]) print(abc('aa','bb','cc')) create_terms('len0, len1') answer(X,N1,N2) <= (abc(X[0:N1],X[N1:N2],X[N2:])) (X=='aabbcc') & (N0.in_(range(len(X.data[0])))) & (N1.in_(range(len(X.data[0])))) & answer(X,N0,N1) create_terms('rep1,N') rep1(X,Y,N) <= rep1(X[N:], X[:N], N0) #len0(X, N0) <= (0 <= N0) & (N0 < len(X)) #len0('', X) <= 0
from pyDatalog import pyDatalog pyDatalog.create_terms('A','B','C','V','trans') # facts trans[1,1] = 1 trans[1,2] = 2/3 trans[1,3] = 2 trans[1,4] = 1/2 # rules trans[A,B] = 1 / trans[B,A] # inverse trans[A,B] = trans[A,C] * trans[C,B] # transitive print(trans[3,2] == V) # posicion M(3,2) print(trans[2,3] == V) # posicion M(2,3) # Calculemos los autovalores y autovectores import numpy as NM # Generar la matriz con la primera fila (al ser consistente se puede hacer) # Si no fuese consistente habria que ponerla a mano A = [] for i in range(1,5): A.append([]) for j in range(1,5): data = (trans[i,j] == V).data[0][0] A[i-1].append(data)
# character equality function # this is a python function, so in true pythonic fashion, the comparison is very general # here, we just mean to use it as character comparison def match(a,b): return a==b # Smith-Waterman wrapper def sw_wrapper(a,b): print('{0} : {1}'.format(a,b)) score = Alignment.SmithWaterman(a,b) print('score = {0}'.format(score)) return score # create required terms # variables pyDatalog.create_terms('X,Y,Z,LX,LY') # data tables pyDatalog.create_terms('seqs,cross_seqs,cross_seqs_lens,matches,seqlens,sw') # python functions pyDatalog.create_terms('strlen,match,sw_wrapper') # assert some facts (i.e. add some sequences to the 'seqs' 'table') sequences = ['ATA','ACGA','ATTCGAA','GGAGA','TTTACC','ACTGGAG','TGGACC'] for s in sequences: + seqs(s) print('seqs') print(seqs(X)) seqlens(X,Y) <= seqs(X) & (Y==strlen(X)) print(seqlens(X,Y))
from pyDatalog import pyDatalog pyDatalog.create_terms('X,Y,Z, salary, tax_rate, tax_rate_for_salary_above, net_salary') salary['foo'] = 60 salary['bar'] = 110 print(salary[X]==Y) salary['foo']==Y # give me all the X that have a salary of 110 print(salary[X]==110) # not Y? print((salary[X]==Y) & ~(Y==110)) +(tax_rate[None]==0.33) # give me the net salary for all X print((Z==salary[X]*(1-tax_rate[None]))) pyDatalog.create_atoms('factorial, N, F') # gives datalog capability to these words def run_program():
import time import random from algorithms import Alignment from pyDatalog import pyDatalog # create some python functions as helpers, because pyDatalog allows this # string length function def strlen(x): if isinstance(x, basestring): return len(x) return 0 pyDatalog.clear() pyDatalog.create_terms("seeds,r,strlen,ss,Z,X,Y,N,SL,W") def build(args): ref = args[0] query = args[1] sl = len(query) # different implementation of all substrings (seeds) of length SL # creates table of (Z,X) pairs where Z is original sequence and X is seed of length SL +r(ref) # seeds(Z,N,X) <= r(Z) & (SL==sl) & (N.in_(range_(strlen(Z)))) & (X==Z[N:N+SL]) & (strlen(X)==SL) # print(seeds(Z,N,X)) seeds(Z, X) <= r(Z) & (SL == sl) & (N.in_(range_(strlen(Z)))) & (X == Z[N : N + SL]) & (strlen(X) == SL) # print(seeds(Z,X))
''' Created on 2 avr. 2013 The HASHTAG problem was the subject of a contest at PyCon 2013. Problem description : https://picasaweb.google.com/lh/photo/u_6ZWCrTUNVADkPAyyFvfKbReIcFkkE5l5WZw-QBbLc Discussion : http://uthcode.appspot.com/2013/03/Hashtag-at-pycon Below is a solution based on pyDatalog @author: pcarbonn ''' from pyDatalog import pyDatalog, pyEngine import time pyDatalog.create_terms('star, move,solution,X,Y,N,N1,N2') pyDatalog.create_terms('X1,X2,X3,X4,X5,X6,X7,X8,X9') pyDatalog.create_terms('Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9') # X has a star in position N1 or N2 star(X,N1,N2) <= (X[N1]=='*') star(X,N1,N2) <= (X[N2]=='*') # valid moves are exchange of 1<->2, 1<->4, ... X19 = (X1,X2,X3,X4,X5,X6,X7,X8,X9) # short hand move(X19, '1-2,', Y) <= star(X19, 0, 1) & (Y==(X2,X1,X3,X4,X5,X6,X7,X8,X9)) move(X19, '1-4,', Y) <= star(X19, 0, 3) & (Y==(X4,X2,X3,X1,X5,X6,X7,X8,X9)) move(X19, '2-3,', Y) <= star(X19, 1, 2) & (Y==(X1,X3,X2,X4,X5,X6,X7,X8,X9)) move(X19, '2-5,', Y) <= star(X19, 1, 4) & (Y==(X1,X5,X3,X4,X2,X6,X7,X8,X9))
{"name": "Mary", "diploma": "EE"}, {"name": "Sam", "diploma": "MBA"}] profiles.insert(profiles_to_insert) """ 2. define a predicate resolver for Employee.diploma """ from SQLAlchemy import Employee # import the SQLAlchemy example def _pyD_diploma2(cls, employee, diploma): global profiles if employee.is_const(): r = profiles.find_one({"name": employee.id.name}) if r: yield (employee, r["diploma"]) return raise AttributeError Employee._pyD_diploma2 = classmethod(_pyD_diploma2) # attach the resolver to the Employee class """ 3. query data from both Mongo DB and SQLite """ from pyDatalog import pyDatalog print("\n *** combined SQLite and Mongo query :\n") pyDatalog.create_terms('X, N, Diploma') # Who has a salary of 6800 and a MSc. diploma (Employee.salary[X]==6800) & (Employee.diploma[X]=="MSc.") print(X)
import logging from pyDatalog import pyDatalog from pyDatalog import pyEngine pyEngine.Logging = True logging.basicConfig(level=logging.INFO) pyDatalog.create_terms( 'isConnected,hostACL,A,existsRoute,knows,hasAccount,H,K,M,hasUser,N,Q,P,S,listeningOn,U,T,V,X,isRouter,ID6,ID4,ID5,ID2,ID3,ID1,R' ) ## videoserver_1 ## # videoserver_system_1 (sdl.nodes.System.Linux),isConnected +isConnected(1, 'videoserver_1', 'Server_subnet_1') ## Firewall_1 ## # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Server_subnet_1', 'Server_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Server_subnet_1', 'Outside_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Server_subnet_1', 'DMZ_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Server_subnet_1', 'IoT_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Outside_subnet_1', 'Server_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Outside_subnet_1', 'Outside_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute +existsRoute(2, 'Outside_subnet_1', 'DMZ_subnet_1', 'Firewall_1') # Firewall_UFW_1 (sdl.nodes.Firewall.UFW),existsRoute
from pyDatalog import pyDatalog import time pyDatalog.create_terms('N,X0,X1,X2,X3,X4,X5,X6,X7') pyDatalog.create_terms('ok,queens,next_queen') # when is it ok to have a queen in row X1 and another in row X2, separated by N columns # this is memoized ! ok(X1, N, X2) <= (X1 != X2) & (X1 != X2+N) & (X1 != X2-N) queens(X0) <= (X0._in(range(8))) queens(X0,X1) <= queens(X0) & next_queen(X0,X1) queens(X0,X1,X2) <= queens(X0,X1) & next_queen(X0,X1,X2) queens(X0,X1,X2,X3) <= queens(X0,X1,X2) & next_queen(X0,X1,X2,X3) queens(X0,X1,X2,X3,X4) <= queens(X0,X1,X2,X3) & next_queen(X0,X1,X2,X3,X4) queens(X0,X1,X2,X3,X4,X5) <= queens(X0,X1,X2,X3,X4) & next_queen(X0,X1,X2,X3,X4,X5) queens(X0,X1,X2,X3,X4,X5,X6) <= queens(X0,X1,X2,X3,X4,X5) & next_queen(X0,X1,X2,X3,X4,X5,X6) queens(X0,X1,X2,X3,X4,X5,X6,X7) <= queens(X0,X1,X2,X3,X4,X5,X6) & next_queen(X0,X1,X2,X3,X4,X5,X6,X7) next_queen(X0,X1) <= queens(X1) & ok(X0,1,X1) next_queen(X0,X1,X2) <= next_queen(X1,X2) & ok(X0,2,X2) next_queen(X0,X1,X2,X3) <= next_queen(X1,X2,X3) & ok(X0,3,X3) next_queen(X0,X1,X2,X3,X4) <= next_queen(X1,X2,X3,X4) & ok(X0,4,X4) next_queen(X0,X1,X2,X3,X4,X5) <= next_queen(X1,X2,X3,X4,X5) & ok(X0,5,X5) next_queen(X0,X1,X2,X3,X4,X5,X6) <= next_queen(X1,X2,X3,X4,X5,X6) & ok(X0,6,X6) next_queen(X0,X1,X2,X3,X4,X5,X6,X7) <= next_queen(X1,X2,X3,X4,X5,X6,X7) & ok(X0,7,X7) # counting is 0-based, so this is actually the 8-queens solution start_time = time.time() print(queens(X0,X1,X2,X3,X4,X5,X6,X7))
# This centralized (in other words, simulated) shortest path routing from pyDatalog import pyDatalog pyDatalog.create_terms("Src, Dest, Cost, Cost1, Cost2, Next, Path, Path2, path, link, a, b, c, d, e, shortestPath") #links with cost +link(e, a, 1) +link(a, b, 5) +link(a, c, 1) +link(b, d, 1) +link(c, b, 1) #recursive rules to define paths with cost path(Src, Dest, Path, Cost) <= link(Src, Dest, Cost) & (Path == [Src] + [Dest]) path(Src, Dest, Path, Cost) <= link(Src, Next, Cost1) & path(Next, Dest, Path2, Cost2) & (Src != Dest) & (Src._not_in(Path2) ) & (Path == [Src] + Path2) & (Cost == Cost1 + Cost2) (shortestPath[Src, Dest]==min_( Path, order_by=Cost)) <= (path(Src, Dest, Path, Cost)) print ( (shortestPath [Src, Dest] == Path) & (path (Src, Dest, Path, Cost)) ) & (Src == e) & (Dest == d)
import random import time from pyDatalog import pyDatalog from sequence_datalog_base import * alphabet = ['A','T','G','C','N'] # 1. testing fsm pyDatalog.create_terms('initial,final,arc') +initial(1) +final(4) +arc(1,2,'h') +arc(2,3,'a') +arc(3,4,'!') +arc(3,1,'#') pyDatalog.create_terms('recognize1, traverse1, N, N1, N2, S, S1, S2') # the '#' symbol matches the empty character. # the '*' symbol matches any character. # citation: http://cs.union.edu/~striegnk/courses/nlp-with-prolog/html/node5.html # this allows for the construction of nondeterministic fsms recognize1(N,'') <= final(N) recognize1(N1,S) <= (arc(N1,N2,S[0]) & recognize1(N2,S[1:])) recognize1(N1,S) <= (arc(N1,N2,'#') & recognize1(N2,S)) recognize1(N1,S) <= (arc(N1,N2,'*') & recognize1(N2,S[1:])) # this works!!!
import random from pyDatalog import pyDatalog alphabet = ['A','T','G','C','N'] # string length function def strlen(x): if isinstance(x,basestring): return len(x) return 0 # character equality function # this is a python function, so in true pythonic fashion, the comparison is very general # here, we just mean to use it as character comparison def match(a,b): return a==b pyDatalog.create_terms('strlen, match') def rand_string_n(n): """ Returns a random string of A,T,G,C characters of length n. """ return ''.join([random.choice(['A','T','G','C']) for i in range(n)])
(Employee.report_count[X] == len(Y)) <= Employee.indirect_manager(Y,X) """ 2. create python objects for 3 employees """ # John is the manager of Mary, who is the manager of Sam John = Employee('John', None, 6800) Mary = Employee('Mary', John, 6300) Sam = Employee('Sam', Mary, 5900) """ 3. Query the objects using the datalog engine """ # the following python statements implicitly use the datalog clauses in the class definition # What is the salary class of John ? print(John.salary_class) # prints 6 # who has a salary of 6300 ? pyDatalog.create_terms('X') Employee.salary[X] == 6300 # notice the similarity to a pyDatalog query print(X) # prints [Mary] print(X.v()) # prints Mary # who are the indirect managers of Mary ? Employee.indirect_manager(Mary, X) print(X) # prints [John] # Who are the employees of John with a salary below 6000 ? result = (Employee.salary[X] < 6000) & Employee.indirect_manager(X, John) print(result) # Sam is in the result print(X) # prints [Sam] print((Employee.salary_class[X] == 5) & Employee.indirect_manager(X, John) >= X) # Sam # verify that the manager of Mary is John
""" Created on 2 avr. 2013 The HASHTAG problem was the subject of a contest at PyCon 2013. Problem description : https://picasaweb.google.com/lh/photo/u_6ZWCrTUNVADkPAyyFvfKbReIcFkkE5l5WZw-QBbLc Discussion : http://uthcode.appspot.com/2013/03/Hashtag-at-pycon Below is a solution based on pyDatalog @author: pcarbonn """ from pyDatalog import pyDatalog, pyEngine import time pyDatalog.create_terms("solution,move,X,Y,Z, Path,Path1,Path2, Steps,Steps1,Steps2") # valid moves are exchange of 1<->2, 1<->4, ... @pyDatalog.predicate() def move3(X, N, Y): for n1, n2 in ((0, 1), (0, 3), (1, 2), (1, 4), (2, 5), (3, 4), (3, 6), (4, 5), (4, 7), (5, 8), (6, 7), (7, 8)): if X.id[n1] == "*" or X.id[n2] == "*": y = list(X.id) y[n1], y[n2] = y[n2], y[n1] yield (X.id, "%s-%s," % (n1 + 1, n2 + 1), "".join(y)) # a solution to go from X to Y is a direct move, # or a solution from X to Z, followed by a direct move from Z to Y (solution[X, Y] == (Steps, Path)) <= ( (solution[X, Z] == (Steps1, Path1))
from __main__ import * from stale import * from pyDatalog import pyDatalog pyDatalog.create_terms('X, Y, NazwaGrupy, odpowiedz_datalog, choroba_datalog, liczba_odp_tak') import kalkulacja_chorob import ast wyniki_datalog = ast.literal_eval(kalkulacja_chorob.dane_wejsciowe) for grupa in nazwy_grup: for i in range(len(wyniki_datalog[grupa])): odpowiedz_datalog[grupa,i] = wyniki_datalog[grupa][i] # Regula zliczajaca ilosc jedynek w liscie (liczba_odp_tak[NazwaGrupy]==len_(Y)) <= (odpowiedz_datalog[NazwaGrupy,Y]==1) # Depresja (ICD-10) 1 (choroba_datalog[nazwy[1]]==True) <= (liczba_odp_tak['ICD10_g1']>=MIN_GRUPA_1_DEPRESJA_ICD10)\ & (liczba_odp_tak['ICD10_g2']>=MIN_GRUPA_2_DEPRESJA_ICD10) # Depresja (DSM-5) 2 (choroba_datalog[nazwy[2]]==True) <= (liczba_odp_tak['DSM5_g3']>=MIN_GRUPA_3_DEPRESJA_DSM5)\ & ((odpowiedz_datalog['DSM5_11',0]==1) or (odpowiedz_datalog['DSM5_12',0]==1))\ & (odpowiedz_datalog['DSM5_20',0]==1)\ & (odpowiedz_datalog['DSM5_21',0]==0) # Anankastyczne zaburzenie osobowosci (ICD-10) 3 (choroba_datalog[nazwy[3]]==True) <= (liczba_odp_tak['ICD10_g4']>=MIN_GRUPA_4_ANANKASTYCZNE_ICD10) # Anankastyczne zaburzenie osobowosci (DSM-IV) 4 (choroba_datalog[nazwy[4]]==True) <= (liczba_odp_tak['DSMIV_g5']>=MIN_GRUPA_5_ANANKASTYCZNE_DSMIV) # Paranoidalne zaburzenie osobowosci (ICD-10) 5 (choroba_datalog[nazwy[5]]==True) <= (liczba_odp_tak['ICD10_g6']>=MIN_GRUPA_6_PARANOICZNA_ICD10) # Paranoidalne zaburzenie osobowosci (DSM-IV) 6
# create table Base.metadata.create_all(engine) # create rows for 3 employees # John is the manager of Mary, who is the manager of Sam John = Employee('John', None, 6800) Mary = Employee('Mary', 'John', 6300) Sam = Employee('Sam', 'Mary', 5900) session.add(John) session.add(Mary) session.add(Sam) session.commit() """ 4. Query the objects using the datalog engine """ pyDatalog.create_terms('X, Y, N, lowest') # the following python statements implicitly use the datalog clauses in the class definition # What is the salary class of John ? print(John.salary_class) # prints 6 # who has a salary of 6300 ? Employee.salary[X] == 6300 # notice the similarity to a pyDatalog query print(X) # prints [Employee: Mary] print(X.v()) # prints Employee:Mary # who are the indirect managers of Mary ? Employee.indirect_manager(Mary, X) print(X) # prints [Employee: John]
# -*- coding: utf-8 -*- """ Created on Thu Dec 5 15:51:33 2019 @author: Nicolas """ from pyDatalog import pyDatalog pyDatalog.clear() pyDatalog.create_terms( 'X, G001, G002, G003, G004, G005, G006, G007, G008, G009, G010, G011, G012, G013, G014, G015, G016, G017, G018, G019, G020, G021, G022, G023, P01, P02, P03, P04, P05, P06, P07, P08' ) ''' P0X : Maladies G0XX : Symptômes ''' P01(X) <= G001(X) & G002(X) & G003(X) & G004(X) P02(X) <= G001(X) & G002(X) & G005(X) & G006(X) P03(X) <= G007(X) & G008(X) P04(X) <= G009(X) & G010(X) & G011(X) & G012(X) P05(X) <= G013(X) & G014(X) & G015(X) & G016(X) P06(X) <= G010(X) & G015(X) & G016(X) & G017(X) & G018(X) & G019(X) P07(X) <= G010(X) & G019(X) & G020(X) & G021(X) P08(X) <= G001(X) & G010(X) & G019(X) & G022(X) & G023(X) +G001('default') +G002('default') +G003('default') +G004('default')
""" This file illustrates algorithms that can be used with graphs, trees, hierarchies, ... * which nodes can be reached from another node * what are the possible paths between 2 nodes * give me one path between 2 nodes (more efficient) * what is the shortest path between 2 nodes, given a cost function """ from pyDatalog import pyDatalog pyDatalog.create_terms('link, can_reach, path, all_path, safe_path, path_with_cost, shortest_path') pyDatalog.create_terms('X, Y, Z, P, P2, C, C2') # 4 # / # 1 - 2 - 3 # / \ # 7 5 # \ / # 6 8 - 9 +link(1,2) +link(2,3) +link(2,4) +link(2,5) +link(5,6) +link(6,7) +link(7,2) +link(8,9)
from pyDatalog import pyDatalog import time pyDatalog.create_terms('N,N1, X,Y, X0,X1,X2,X3,X4,X5,X6,X7') pyDatalog.create_terms('ok,queens, next_queen, pred, pred2') size=8 # when is it ok to have a queen in row X1 and another in row X2, separated by N columns # this is memoized ! queens(N, X) <= (N>1) & queens(N-1, X[:-1]) & next_queen(N, X) queens(1, X) <= (X1._in(range(size))) & (X[0]==X1) next_queen(N, X) <= (N>2) & next_queen(N-1, X[1:]) & ok(X[0], N-1, X[-1]) next_queen(2, X) <= queens(1,(X1,)) & ok(X[0], 1, X1) & (X[1] == X1) ok(X1, N, X2) <= (X1 != X2) & (X1 != X2+N) & (X1 != X2-N) start_time = time.time() print(queens(size, (X0,X1,X2,X3,X4,X5,X6,X7))) print("First datalog run in %f seconds" % (time.time() - start_time)) start = time.time() for i in range(20): # there is a warm-up period for the JIT --> let's compute it again start_time = time.time() datalog_count = len(queens(size, (X0,X1,X2,X3,X4,X5,X6,X7)).data) datalog_time = (time.time() - start_time) print(datalog_time) print("Average : %s" % ((time.time() - start)/20))
profiles.insert(profiles_to_insert) """ 2. define a predicate resolver for Employee.diploma """ from SQLAlchemy import Employee # import the SQLAlchemy example def _pyD_diploma2(cls, employee, diploma): global profiles if employee.is_const(): r = profiles.find_one({"name": employee.id.name}) if r: yield (employee, r["diploma"]) return raise AttributeError Employee._pyD_diploma2 = classmethod(_pyD_diploma2) # attach the resolver to the Employee class """ 3. query data from both Mongo DB and SQLite """ from pyDatalog import pyDatalog print("\n *** combined SQLite and Mongo query :\n") pyDatalog.create_terms("X, N, Diploma") # Who has a salary of 6800 and a MSc. diploma (Employee.salary[X] == 6800) & (Employee.diploma[X] == "MSc.") print(X)
class Ingredient(Base): __tablename__ = 'Lebensmittel' __table_args__ = {'autoload':True} def __repr__(self): return self.Name class containRecipe(Base): __tablename__ = 'enthaeltRezept' __table_args__ = {'autoload':True} class containIngredient(Base): __tablename__ = 'enthaeltLebensmittel' __table_args__ = {'autoload':True} pyDatalog.create_terms('I, A, X, Y, Z, N') # get all ingredients of an recipe pyDatalog.create_terms('hasIngredient, recipeIngredients') hasIngredient(X, Y, Z) <= (containIngredient.RezeptId[A] == X) & (containIngredient.LebensmittelId[A] == Y) & (containIngredient.Menge[A] == Z) Recipe.recipeIngredients(X, Y) <= (containRecipe.RezeptId[A] == X) & (containRecipe.KomponentenRezeptId[A] == Z) & (Recipe.hasIngredient(Z, Y)) # get weight of recipe pyDatalog.create_terms('weight') #weight(X) <= # get Calories of Recipes pyDatalog.create_terms('calorie') #calorie(X) <=
sys.path.append("/home/kook/pyDatalog-0.14.5") from pyDatalog import pyDatalog class Node(pyDatalog.Mixin): banana = True class Text(Node): def __init__(self): super(self, Text).__init__() class Number(Node): def __init__(self): super(self, Number).__init__() class Type(Node): def __init__(self): super(self, Type).__init__() def node(X): return isinstance(X, Node) pyDatalog.create_terms('node, works_as, works_ass, node_works_as, X, Y, Z') works_as(Number, Type) works_as(Text, Type) works_ass(X, Y) <= works_as(X, Y) works_ass(X, Y) <= works_as(X, Z) & works_ass(Z, Y) node_works_as(X, Y) <= works_ass(X, Y) & node(X) node_works_as(X, X) <= node(X) #can_reach(X,Y) <= link(X,Z) & can_reach(Z,Y) & (X!=Y) print (node_works_as(X, 'type')) #pyDatalog.create_terms('works_as') #works_as(Assignment, 'assignment') #sum([])
"""My blog discussion: http://wp.me/p2eZvw-Nn Discussion on Stackoverflow: http://is.gd/oPKAtg """ from pyDatalog import pyDatalog from pyDatalog.pyDatalog import create_terms as terms from pyDatalog.pyDatalog import ask pyDatalog.create_terms('scale') # the long way of doing it terms('A, B, C, V') scale['meter', 'inch'] = 39.3700787 scale['mile', 'inch'] = 63360.0 scale['feet', 'inch'] = 12.0 scale[A, B] = 1/scale[B, A] scale[A,B] = scale[A,C] * scale[C, B] print(scale['inch', 'meter'] == V) print(scale['mile', 'meter'] == V) scale['league', 'mile'] = 3.45233834 print(scale['league', 'meter'] == V) terms('conv') conv[V, A, B] = V * scale[A, B] print(conv[3, 'mile', 'meter'] == V) print(conv[1, 'meter', 'feet'] == V)
import ecmp import action as ovsaction import match as ovsmatch import time from pyDatalog import pyDatalog from tp_utils.run_env import is_gateway_chassis, get_extra import tunnel logger = logging.getLogger(__name__) prev_zoo_ver = 0 # it should be 0 which same as entity_zoo's zoo_ver had_clean_tunnel_ports = False had_clean_ovs_flows = False # NOTE: DO NOT revise the filename MAC_IP_BIND_FILE = os.path.join(get_extra()['options']['TUPLENET_RUNDIR'], 'mac_ip_bind.data') pyDatalog.create_terms('Table, Priority, Match, Action, State') pyDatalog.create_terms('PORT_NAME, IP, UUID_CHASSIS') def update_lsp_chassis(entity_set, system_id): lsp_chassis_changed = [] lsp_portset = entity_set['lsp'] ovsport_set = entity_set['ovsport'] for _, ovsport in ovsport_set.items(): key = ovsport.iface_id if lsp_portset.has_key(key) and \ lsp_portset[key].chassis != system_id: lsp_chassis_changed.append(lsp_portset[key]) logger.info('should update lsp %s chassis %s', key, system_id) return lsp_chassis_changed def generate_lsp_kv(lsp_array, system_id):
idx = self._get_free_idx(ILKEntity._ilk_group[etype][key]) if idx < 0: raise Exception("too many ilk, entity:%s" % self.uuid) ILKEntity._ilk_group[etype][key].add(idx) else: ILKEntity._ilk_group[etype][key] = set([idx]) return idx # NOTE: please do NOT change the function name, it is consumed by # LogicalEntity def _eliminate(self): ilk_idx = self._free_ilk_idx() logger.debug("entity %s free ilk idx %u", self, ilk_idx) pyDatalog.create_terms('lsp_array, exchange_lsp_array') pyDatalog.create_terms('lrp_array, ls_array, chassis_array') pyDatalog.create_terms('_lr_array, lr_array') pyDatalog.create_terms('lroute_array, Route, lnat_array') pyDatalog.create_terms('lroute_lrp') pyDatalog.create_terms('ovsport, ovsport_chassis') LSP_UUID = 0 LSP_IP = 1 LSP_IP_INT = 2 LSP_MAC = 3 LSP_MAC_INT = 4 LSP_CHASSIS_UUID = 5 LSP_LS_UUID = 6 LSP_PEER = 7 LSP_PORTID = 8
# -*- coding: utf-8 -*- """ Created on Thu Dec 5 16:39:11 2019 @author: delan """ from pyDatalog import pyDatalog pyDatalog.clear() pyDatalog.create_terms('X, triangle, cote_egaux_2, cote_egaux_3, angle_droit, rectangle, isocele, equilateral, quelconque, angle_3, polygone_1, polygone_2, polygone_3, polygone_4') rectangle(X) <= triangle(X) & angle_droit(X) isocele(X) <= triangle(X) & cote_egaux_2(X) equilateral(X) <= triangle(X) & cote_egaux_3(X) quelconque(X) <= triangle(X) & ~cote_egaux_3(X) & ~cote_egaux_2(X) & ~angle_droit(X) triangle(X) <= angle_3(X) +triangle(polygone_1) +angle_droit(polygone_1) +triangle(polygone_2) +cote_egaux_2(polygone_2) +triangle(polygone_3) +cote_egaux_3(polygone_3) +triangle(polygone_4) +angle_3(polygone_4) print(pyDatalog.ask('rectangle(X)'))
from pyDatalog import pyDatalog pyDatalog.create_terms('enfermo, sintoma, elimina') # REGLAS pyDatalog.create_terms('como_curar') # VARIABLES pyDatalog.create_terms('Enfermo, Sintoma, Cura') # ENFERMO +enfermo('manuel', 'gripe') # SINTOMA +sintoma('alicia', 'cansancio') +sintoma('fiebre', 'gripe') +sintoma('tos', 'gripe') +sintoma('cansancio', 'anemia') # CURA +elimina('vitaminas', 'cansancio') +elimina('aspirinas', 'fiebre') +elimina('jarabe', 'tos') # REGLAS
self.time_in_h = time_in_h self.time_in_m = time_in_m self.time_out_h = time_out_h self.time_out_m = time_out_m self.visitor = Visitor(visitor, document) + visit(visitor, number) def __repr__(self): return str(self.number) def print_beautiful(data): for i in data: print(i[0]) if __name__ == "__main__": pyDatalog.create_terms('X, visit, own, visitors_doc') r = [] r.append(Room(103, 'Назарова', 22, 5, 10, 8, 'Рассохин', 'Паспорт')) r.append(Room(603, 'Баринов', 20, 50, 23, 0, 'Боронников', 'Снилс')) r.append(Room(304, 'Балезина', 21, 10, 22, 15, 'Яковлева', 'Пропуск')) r.append(Room(404, 'Малышев', 19, 4, 22, 40, 'Морозов', 'Паспорт')) print('Кто из посетителей сдавал паспорт?') print_beautiful(visitors_doc(X, 'Паспорт')) print('________________________') print('Какую комнату посещал Рассохин?') print_beautiful(visit('Рассохин', X)) print('________________________') print('Кто живет в комнате 404?')
""" This file contains the code for the interactive online datalog tutorial. https://sites.google.com/site/pydatalog/Online-datalog-tutorial """ from pyDatalog import pyDatalog pyDatalog.create_terms('parent,bill,ancestor,descendents,manager, X,Y,Z,N,N1,F, factorial, first_remainder, odd,even, _split') + parent(bill,'John Adams') print(parent(bill,X)) # prints [('John Adams',)] # specify what an ancestor is ancestor(X,Y) <= parent(X,Y) ancestor(X,Y) <= parent(X,Z) & ancestor(Z,Y) print(ancestor(bill, X)) # prints [('John Adams',)] # the manager of bill is John Adams. Bill has only one manager. + (manager[bill]=='John Adams') print(manager[bill]==X) # prints [('John Adams',)] # use expressions and recursion to evaluate factorials (factorial[N] == F) <= (N < 1) & (F==-factorial[-N]) + (factorial[1]==1) (factorial[N] == F) <= (N > 1) & (F == N*factorial[N-1]) print(factorial[3]==F) # prints [(6,)] # (nested) list
import sys import time import random from algorithms import Alignment from pyDatalog import pyDatalog # create some python functions as helpers, because pyDatalog allows this # string length function def strlen(x): if isinstance(x,basestring): return len(x) return 0 pyDatalog.clear() pyDatalog.create_terms('seedsa,seedsb,r,s,strlen,X,Y,Z,res,A,B,SL,N') def build(a,b,k): # creates table of (Z,X) pairs where Z is original sequence and X is seed (kmer) of length SL + r(a) seedsa(Z,X) <= r(Z) & (SL==k) & (N.in_(range_(strlen(Z)))) & (X==Z[N:N+SL]) & (strlen(X)==SL) #print(seedsa(Z,X)) + s(b) seedsb(Z,X) <= s(Z) & (SL==k) & (N.in_(range_(strlen(Z)))) & (X==Z[N:N+SL]) & (strlen(X)==SL) #print(seedsb(Z,X)) def ask(): # seeds query function res(X) <= seedsa(A,Y) & seedsb(B,Z) & (Z==Y) & (X==Z) #print(res(X)) print(len_(res(X))==Y)
from pyDatalog import pyDatalog pyDatalog.clear() pyDatalog.create_terms('rectangle, isocele, equi, isoRect, P, TroiscotesPareil, angles60, DeuxcotesPareil, angleDroit, deuxAngles45, X') equi(P) <= TroiscotesPareil(P) & angles60(P) isocele(P) <= DeuxcotesPareil(P) rectangle(P) <= angleDroit(P) isoRect(P) <= angleDroit(P) & deuxAngles45(P) pyDatalog.assert_fact('angleDroit', 'Triangle rectangle') pyDatalog.assert_fact('angleDroit', 'Triangle rectangle isocèle') pyDatalog.assert_fact('deuxAngles45', 'Triangle rectangle isocèle') print(pyDatalog.ask('angleDroit(X)')) print(pyDatalog.ask('deuxAngles45(X)'))
''' Created on 2 avr. 2013 The HASHTAG problem was the subject of a contest at PyCon 2013. Problem description : https://picasaweb.google.com/lh/photo/u_6ZWCrTUNVADkPAyyFvfKbReIcFkkE5l5WZw-QBbLc Discussion : http://uthcode.appspot.com/2013/03/Hashtag-at-pycon Below is a solution based on pyDatalog @author: pcarbonn ''' from pyDatalog import pyDatalog, pyEngine import time pyDatalog.create_terms( 'solution,move,X,Y,Z, Path,Path1,Path2, Steps,Steps1,Steps2') # valid moves are exchange of 1<->2, 1<->4, ... @pyDatalog.predicate() def move3(X, N, Y): for n1, n2 in ((0, 1), (0, 3), (1, 2), (1, 4), (2, 5), (3, 4), (3, 6), (4, 5), (4, 7), (5, 8), (6, 7), (7, 8)): if X.id[n1] == '*' or X.id[n2] == '*': y = list(X.id) y[n1], y[n2] = y[n2], y[n1] yield (X.id, '%s-%s,' % (n1 + 1, n2 + 1), ''.join(y)) # a solution to go from X to Y is a direct move, # or a solution from X to Z, followed by a direct move from Z to Y
from pyDatalog import pyDatalog from pyDatalog.pyDatalog import assert_fact, load, ask # COMIDA # Tipos de comida pyDatalog.create_terms('raices, verduras, frutas, carnes, lacteos, granos') # Tabla nutricional pyDatalog.create_terms( 'vitamina_a, vitamina_b, vitamina_c, calorias, carbohidratos, proteinas') pyDatalog.create_terms('cantidad_calorias') # ----------------------------------------------------------------------------------------------- # PERSONAS # Datos pyDatalog.create_terms('genero, edad, peso, estatura, sedentarismo') # Enfermedades pyDatalog.create_terms('gastrointestinales, diabetes, desnutricion, obesidad') # Sintomas y soluciones pyDatalog.create_terms('tiene_sintoma, solucion') # ---------------------------------------------------------------------------------------------- # REGLAS
# PEP8 from datetime import date from gradebook import Gradebook from grades import Grades from student import Student from subject import Subject from pyDatalog import pyDatalog def Show(Obj): print(repr(Obj)) if (__name__ == "__main__"): pyDatalog.create_terms( 'X,Y,book, Show, grades, hasGrades, hasKurs, passedSubject') s = Student("Аюпов", "Александр", "Дамирович", date(1997, 6, 19), "Электротехнический", "АСУ2-19-1м", 1) book = Gradebook("19-ЭТФ-1248", s) grades = book.grades kurs1 = dict() kurs2 = dict() kurs3 = dict() kurs4 = dict() subject1 = Subject("Философия", "Экзамен", 5) subject2 = Subject("Высшая математика", "Экзамен", 4) subject3 = Subject("Базы данных", "Экзамен", 5) subject4 = Subject("АСОИИУ", "Диф. зачёт", 5) kurs1.update({subject1.name: subject1}) kurs2.update({subject2.name: subject2}) kurs3.update({subject3.name: subject3})
# -*- coding: utf-8 -*- """ Created on Thu Nov 7 10:49:15 2019 @author: Moi """ from pyDatalog import pyDatalog pyDatalog.create_terms('factorial, N') factorial[N] = N*factorial[N-1] factorial[1] = 1 print(factorial[3]==N) pyDatalog.create_atoms('salary', 'manager') # John is the manager of Mary, who is the manager of Sam + (salary['John'] == 6800) + (manager['Mary'] == 'John') + (salary['Mary'] == 6300)
Action_bundle: 'bundle(nw_dst,0,active_backup,ofport,slaves:{})', Action_bundle_load: 'bundle_load(nw_dst,0,hrw,ofport,{},slaves:{})', Action_note: 'note:{:02x}', #self define Action_resubmit_next: 'resubmit(,{})', Action_exchange: 'push:{},push:{},pop:{},pop:{}', Action_upload_arp: 'controller(userdata=00.00.00.01.00.00.00.00)', Action_generate_arp: 'controller(userdata=00.00.00.02.00.00.00.00.ff.ff.00.10.00.00.23.20.00.0e.ff.f8.{:02x}.00.00.00)', Action_upload_trace: 'controller(userdata=00.00.00.03.00.00.00.00)', Action_upload_unknow_dst: 'controller(userdata=00.00.00.04.00.00.00.00)', } pyDatalog.create_terms( 'A, B, C, D, E, F, G, H, I, J, K, L, N, M, O, P, Q, R, S, T, U, V, W, X, Y, Z' ) pyDatalog.create_terms('resubmit_table') pyDatalog.create_terms('move') pyDatalog.create_terms('load') pyDatalog.create_terms('output') pyDatalog.create_terms('output_reg') pyDatalog.create_terms('bundle') pyDatalog.create_terms('bundle_load') pyDatalog.create_terms('drop') pyDatalog.create_terms('mod_nw_dst') pyDatalog.create_terms('mod_nw_src') pyDatalog.create_terms('mod_dl_src') pyDatalog.create_terms('mod_dl_dst') pyDatalog.create_terms('mod_nw_tos') pyDatalog.create_terms('mod_nw_ecn')
from pyDatalog import pyDatalog import json import psutil pyDatalog.create_terms( 'jointable, Nest_Cam, Network, Location, Floor, ID,L1,L2,L3,L4') for i in range(10001): +Nest_Cam('NC' + str(i), 'LAN' + str(i // 10)) for i in range(2001): +Floor('LAN' + str(i), 'Floor' + str(i // 5)) for i in range(501): +Network('Floor' + str(i), 'Building' + str(i // 3)) for j in range(251): +Location('Building' + str(j), 'Campus' + str(j // 2)) start = psutil.cpu_times() jointable(ID, L1, L2, L3, L4) <= Location(L1, ID) & Network(L2, L1) & Floor( L3, L2) & Nest_Cam(L4, L3) Networks = {} for i in jointable(ID, L1, L2, L3, L4): Networks[i[0]] = Networks.get(i[0], {"Elevel": 2}) Networks[i[0]][i[1]] = Networks[i[0]].get(i[1], {}) Networks[i[0]][i[1]][i[2]] = Networks[i[0]][i[1]].get(i[2], {}) Networks[i[0]][i[1]][i[2]][i[3]] = Networks[i[0]][i[1]][i[2]].get(i[3], {}) Networks[i[0]][i[1]][i[2]][i[3]][i[4]] = Networks[i[0]][i[1]][i[2]][ i[3]].get(i[4], {}) Networks[i[0]][i[1]][i[2]][i[3]][i[4]] = i[4]
def initialize(): variables = 'V, W, X, Y, Z' functions = 'gender, buendia_blood, buendia, bastard, inbred, parent, mother, father, sibling, brother, sister, child, daughter, son, married, wife, husband, decendent, ancestor, aunt, uncle, cousin' pyDatalog.create_terms(variables + ', ' + functions)
self.name = name self.manager = manager # direct manager of the employee, or None self.salary = salary # monthly salary of the employee def __repr__(self): # specifies how to display an Employee return self.name John = Employee('John', None, 6800) Mary = Employee('Mary', John, 6300) Sam = Employee('Sam', Mary, 5900) print(pyDatalog.ask('Employee.salary[X]==6300')) # prints a set with 1 element : the (Mary, 6300) tuple pyDatalog.create_terms('has_car, X') + has_car(Mary) print(has_car(X)) # prints a list with one answer: the (Mary,) tuple # all the indirect managers Y of X are derived from his manager, recursively Employee.indirect_manager(X,Y) <= (Employee.manager[X]==Y) & (Y != None) Employee.indirect_manager(X,Y) <= (Employee.manager[X]==Z) & Employee.indirect_manager(Z,Y) & (Y != None) # the salary class N of employee X is a function of his/her salary # this statement is a logic equality, not an assignment ! Employee.salary_class[X] = Employee.salary[X]//1000 # What is the salary class of John ? print(John.salary_class) # prints 6
from pyDatalog import pyDatalog pyDatalog.create_terms('X, Y, Z, H, doctor, spec, simpt, patient, depart, dep_simpt, pat_doc, pat_dep') pyDatalog.create_terms('K, L, nurse, helps_the_doctor) +(doctor['Dr. Alex'] == 'Lor') +(doctor['Dr. Mary'] == 'Oculist') +(doctor['Dr. Mitch'] == 'Therapist') +(doctor['Dr. Marty'] == 'Orthopedist') +(doctor['Dr. Kenny'] == 'Cardiologist') +(nurse ['Mary']=='Dr. Alex') +(nurse ['John']=='Dr. Mary') +(nurse ['Mary']=='Dr. Alex') +(nurse ['Mary']=='Dr. Alex') +(nurse ['Mary']=='Dr. Alex') +(spec['Nose'] == 'Lor') +(spec['Ears'] == 'Lor') +(spec['Throat'] =='Lor') +(spec['Eye'] == 'Oculist') +(spec['Stomach'] == 'Therapist') +(spec['Liver'] == 'Therapist') +(spec['Foot'] == 'Orthopedist') +(spec['Back'] == 'Orthopedist') +(spec['Heart'] == 'Cardiologist') +(depart['Dr. Alex'] == '1') +(depart['Dr. Mary'] == '1') +(depart['Dr. Mitch'] == '2') +(depart['Dr. Marty'] =='2') +(depart['Dr. Kenny'] == '3') (simpt[X] == Y) <= (spec[X] == Z) & (doctor[Y] == Z) #print(simpt[X] == Y) (dep_simpt[X] == Y) <= (simpt[X] == Z) & (depart[Z] == Y)
from pymetamap import MetaMap from pandas import Series, DataFrame import pandas as pd import numpy as np import os from pyDatalog import pyDatalog # initialize mm = MetaMap.get_instance('/Users/sileshu/Downloads/public_mm/bin/metamap16') pyDatalog.create_terms('RH, PH, C, BR, P, BL, op, Y') # clauses (op[RH,PH,C,BR,P,BL] == 'Eliminate_Hazard') <= (True == RH) (op[RH,PH,C,BR,P,BL] == 'Eliminate_Hazard') <= (False == RH) & (True == PH) (op[RH,PH,C,BR,P,BL] == 'Secondary_Survey') <= (False == RH) & (False == PH) & \ (True == C) & (False == BL) (op[RH,PH,C,BR,P,BL] == 'Control_Bleeding') <= (False == RH) & (False == PH) & \ (True == C) & (True == BL) (op[RH,PH,C,BR,P,BL] == 'Open_the_Airway, Secondary_Survey') <= (False == RH) & \ (False == PH) & (False == C) & (True == BR) & \ (True == P) & (False == BL) (op[RH,PH,C,BR,P,BL] == 'Open_the_Airway, Control_Bleeding') <= (False == RH) & \ (False == PH) & (False == C) & (True == BR) & \ (True == P) & (True == BL) (op[RH,PH,C,BR,P,BL] == 'Open_the_Airway, Start_Artificial_Ventilation, Secondary_Survey') <= (False == RH) & \ (False == PH) & (False == C) & (False == BR) & \ (True == P) & (False == BL) (op[RH,PH,C,BR,P,BL] == 'Open_the_Airway, Start_Artificial_Ventilation, Control_Bleeding') <= (False == RH) & \ (False == PH) & (False == C) & (False == BR) & \ (True == P) & (True == BL) (op[RH,PH,C,BR,P,BL] == 'Open_the_Airway, Start_External_Cardiac_Compressions, Secondary_Survey') \
from pyDatalog import pyDatalog pyDatalog.create_terms('croakes, eatflies, frog, chrips, sings, canary, green, yellow, P, X') pyDatalog.load(""" frog(X) <= croakes(X) & eatflies(X) canary(X) <= sings(X) & chrips(X) green(X) <= frog(X) yellow(X) <= canary(X) """) pyDatalog.assert_fact('croakes', 'Fritz') pyDatalog.assert_fact('eatflies', 'Fritz') pyDatalog.assert_fact('sings', 'Paul') pyDatalog.assert_fact('chrips', 'Paul') query = 'yellow(X)' answers = pyDatalog.ask(query).answers print(answers) print(pyDatalog.ask('green(X)'))
from pyDatalog import pyDatalog from pyDatalog import Logic import logging from pyDatalog import pyEngine pyEngine.Trace = True import copy import itertools import gc import sys from operator import itemgetter import pprint import time #This is the risk metric Logic() pyDatalog.create_terms('connectsTo,residesOn,runs,TargetHost,SourceHost,DestHost,TargetService,SourceService,compromised,connectsToWithPrivileges,questionableWithinRisk,functionQuestionableWithinRisk','allAttackerPathsCostPlus','F','F2','FuncName','U','U2','Util','allAttackerPathsCostPlus','SS','TS','IS1','functionDown','functionalityFree','Prob') pyDatalog.create_terms('cTo,cToWithPrivileges,ServiceA,ServiceB,HostA,HostB,localRootExploit,remoteRootExploit,attackerConnectsToWithPrivileges,attackerReachable') pyDatalog.create_terms('allPaths,allAttackerPaths,P,P2,IntermediateService1,attackerCanReachOneStep,ok,attackerCanReachTwoSteps,oneStepToBadness,twoStepsToBadness','shortestAttackerPathsPlus') pyDatalog.create_terms('requires,Task,Hostname','remoteUserExploit','vulnExists','RiskForFunction','MaxR','OtherService','functionDownOrCompromised','probCompromised') pyDatalog.create_terms('cutConnection','VulnType','isAccount','C','C2','cost','TotalC','TotalC2','E','E2','notConnectsTo','notResidesOn','notCompromised','notRemoteUserExploit','notRemoteRootExploit','notLocalRootExploit''a','b','c','suspicious','t1','t2','t3','t4','t5','TacticNumber','moveHostTo','transitiveConnects','transitiveConnectsSecure') pyDatalog.create_terms('TestA','TestB','utility','FunctionA','resultingUtil','functionCompromised','functionUncompromised','FuncAUtil','allConnectionPaths','questionable','functionQuestionable','U','requiresConnection','networkConnectsTo','adHost','missingConnection','isType','allAttackerPathsWithTyping','ExploitAndTarget','ExploitAndTarget2','TargetType','questionableAtRisk','allAttackerPathsPlus','functionQuestionableWithinRiskPlus') pyDatalog.create_terms('Functionality','Attribute','Data','Service','Impact','requiresSecurityAttribute','FunctionB','FunctionC','functionRequires','implements','implementedF','requiresAllConnections') pyDatalog.create_terms('isType','validNewConnectsTo') pyDatalog.create_terms('vulnExistsWithAttributes','remoteRootExploitWithAttributes','compromisedWithAttributes','functionCompromisedWithAttributes') pyDatalog.create_terms('requiresSecurityAttribute','consumesDataWithAttributes','transitiveConnectsWithAttributes','producesData','requiresDataWithAttributes','C*K','IOK','AOK','CRequired','IRequired','ARequired','CImpact','IImpact','AImpact') pyDatalog.create_terms('CProvided','IProvided','AProvided','CProvided1','IProvided1','AProvided1','CProvided2','IProvided2','AProvided2','connectsToWithAttributes','consumesData','networkConnectsToWithAttributes','requiresFunction','transitiveConnectsWithAttributesOnPath') pyDatalog.create_terms('consumesDataWithC','consumesDataWithI','consumesDataWithA','consumesDataWithAttributeProblems','consumesDataWithAttributesNoAlternative','allCompromised','someCompromised','attackPaths','pathCompromisesFunctionWithCost','pathCompromisesService') pyDatalog.create_terms('isPath','X','Y','Z','pathCompromisesUtilities','pathCompromisesWithCost','worstCasePath','UtilPathPair','pathCompromisesFunctions','FList','worstCasePathValue','weightedWorstCastPath','probCapability','estimatedUtility','worstCasePathFromSource','SourceCost','compromisedCombo') #Logic for Below Cases @pyDatalog.predicate()
import random import time from pyDatalog import pyDatalog from sequence_datalog_base import * alphabet = ['A','T','G','C','N'] # implementing tries in datalog as FSMs pyDatalog.create_terms('trie_root,trie_edge,trie_final,N,N1,N2') # trie_edge(a,b,c): there is an edge from node a to node b labeled with # character c. +trie_root(0) +trie_edge(-1,-2,'') root_node = 0 # because python is weird max_node = {0:0} def add_string_to_trie(s): """ Adds a string to the trie TODO: is there a way to do this only using datalog? """ n1 = root_node for c in s: if not trie_edge(n1, N, c): +trie_edge(n1,max_node[0]+1,c) max_node[0]+=1
from pyDatalog import pyDatalog from timeit import default_timer as timer import json pyDatalog.create_terms('jointable, Nest_Cam, Location, ID,L1,L2') #s = 'Nest_Cams(Nest_Cam{0},NC{1},Building{2}).' # + Nest_Cam('NC1','B1') # + Location('B1','C1') for i in range(501): +Nest_Cam('NC ' + str(i), 'Building ' + str(i // 10)) for j in range(51): +Location('Building ' + str(j), 'Campus ' + str(j // 10)) start = timer() jointable(ID, L1, L2) <= Nest_Cam(ID, L1) & Location(L1, L2) # print(timer()-start) #print(jointable(ID,L1,L2)) Vendors = {} for i in jointable(ID, L1, L2): Vendors[i[2]] = Vendors.get(i[2], {}) Vendors[i[2]][i[1]] = Vendors[i[2]].get(i[1], {}) Vendors[i[2]][i[1]][i[0]] = i[0] # print(Vendors) # save to file: with open('abs.json', 'w') as f: json.dump(Vendors, f) print(timer() - start)
from pyDatalog import pyDatalog pyDatalog.create_terms('fritz,X,croakes,eatFlies,frog,chirps,sings,canary,green,yellow') #pyDatalog.create_atoms('croakes','eatFlies','frog','chirps','sings','canary','green','yellow') frog(X) <= croakes(X) & eatFlies(X) canary(X) <= sings(X) & chirps(X) #frog(X) <= green(X) green(X) <= frog(X) canary(X) <= yellow(X) # fritz is a frog #+ (frog(fritz)) pyDatalog.assert_fact('croakes','fritz') pyDatalog.assert_fact('eatFlies','fritz') print("Frog :",pyDatalog.ask('frog(X)').answers) print("Green :",pyDatalog.ask('green(X)').answers)
import cProfile, pstats, StringIO # create some python functions as helpers, because pyDatalog allows this # string length function def strlen(x): if isinstance(x, basestring): return len(x) return 0 # create required terms # variables pyDatalog.clear() pyDatalog.create_terms("X,Y,Z,LX,LY,N") def score(a, b): if a == b: return 0 return 1 pyDatalog.create_terms("hamming,words,w,score,hammingscores,S,HS,K,hs,strlen") # w = ['hello','helps','world','worne'] def build(args): w = args for ww in w: +words(ww)
@option('-T', '--to-days', type=int, help='The relative end date expressed in number of days after the current date (takes precedence over --to-date).') @option('--no-status', type=bool, is_flag=True, help='Discard the STATUS columns.') @option('--no-score', type=bool, is_flag=True, help='Discard the SCORE columns.') @pass_obj def summary(obj, from_date, to_date, from_days, to_days, no_status, no_score): if from_days is not None: from_date = prev_weekday(curr_weekday(), n=from_days) if to_days is not None: to_date = next_weekday(curr_weekday(), n=to_days) r = Rota().load(obj.file) r.assign_until(to_date) # display(schedule(from_date, to_date, no_status, no_score)) @cli.command(help='Print the a sample file to help you getting started.') @pass_obj def sample_file(obj): print(SAMPLE_FILE) # # Main # # To define the aggregate functions (eg len_, min_) and link PDL to the functions that are decorated with @for_pdl. pdl.create_terms(*for_pdl.registered_funcs) if __name__ == '__main__': cli()