%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Training a weighted automata. % Input % - a directed acyclic automata represented as a set of edges 'E', % where each edge is a tuple 't(Start,End,Char)' % - a set of samples of the form 't(String,Cost)' where % 'String' is a list of characters and 'Cost' is an integer % representing the desired weight for such string. % Output: % - an automata 'W': a weighted version of the input automata 'E' % where each edge is a tuple 't(Start,End,Char,cost(EdgeCost))' % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% training(E,Samples,W):- create_automata(E,W)! & forall(X in Samples, exists([String,Cost], X = t(String,Cost) & validate(W,String,Cost))). %create_automata(A,W) %'A' is a directed acyclic automata and %'W' is its weighted version. Weights are restricted %to the range 1-100. create_automata({},{}). create_automata({t(Start,End,Char)\Rest},{t(Start,End,Char,cost(X))\NewRest}):- X in int(1,100) & t(Start,End,Char) nin Rest & create_automata(Rest,NewRest). %validate(W,String,Cost) %'W' is a weighted automata accepting the string 'String' %with total cost 'Cost' validate(W,String,Cost):- make_path(String,Path,q0,Cost) & subset(Path,W)!. %make_path(String,Path,State,Cost) %'Path' is the collection of (abstract) edges, starting from %node 'State', required to process the string 'String', %with total cost 'Cost' make_path([],{},_,0). make_path([Char|Rest],{t(State,End,Char,cost(EdgeCost))\PathRest},State,TotalCost):- TotalCost is EdgeCost + Cost & make_path(Rest,PathRest,End,Cost). %%%%%%%%%%%%%%%%%%%%%% Sample input and goals %%%%%%%%%%%%%%%%%%%% input(E,Samples):- E = {t(q0,q1,a), t(q0,q2,b), t(q2,q1,a), t(q2,q3,b), t(q1,q4,a), t(q1,q4,b), t(q4,q5,a)} & Samples = {t([a,a],5), t([b,a,b],14), t([b,b],8), t([a,a,a],11), t([a,b],6)}. /* Sample goal: {log}=> input(A,Samples) & training(A,Samples,WeightedA). A = {t(q0,q1,a),t(q0,q2,b),t(q2,q1,a),t(q2,q3,b),t(q1,q4,a),t(q1,q4,b),t(q4,q5,a)}, WeightedA = {t(q0,q1,a,cost(1)),t(q0,q2,b,cost(1)),t(q2,q1,a,cost(8)), t(q2,q3,b,cost(7)),t(q1,q4,a,cost(4)),t(q1,q4,b,cost(5)), t(q4,q5,a,cost(6))}, Another solution? (y/n)y A = {t(q0,q1,a),t(q0,q2,b),t(q2,q1,a),t(q2,q3,b),t(q1,q4,a),t(q1,q4,b),t(q4,q5,a)}, WeightedA = {t(q0,q1,a,cost(1)),t(q0,q2,b,cost(2)),t(q2,q1,a,cost(7)), t(q2,q3,b,cost(6)),t(q1,q4,a,cost(4)),t(q1,q4,b,cost(5)), t(q4,q5,a,cost(6))}, Another solution? (y/n)y A = {t(q0,q1,a),t(q0,q2,b),t(q2,q1,a),t(q2,q3,b),t(q1,q4,a),t(q1,q4,b),t(q4,q5,a)}, WeightedA = {t(q0,q1,a,cost(1)),t(q0,q2,b,cost(3)),t(q2,q1,a,cost(6)), t(q2,q3,b,cost(5)),t(q1,q4,a,cost(4)),t(q1,q4,b,cost(5)), t(q4,q5,a,cost(6))}, Another solution? (y/n) ... */