JL ifcdZddlZddlZddlZddlZddlmZddlmZddl m Z m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZmZGddeZGdd eZd Zd Zd Zd Z Gdde!Z"ejFdZ$ejFdZ%ejFdejLZ'dZ(d"dZ)Gdde!Z*GddZ+dZ,d"dZ-d#dZ.d"dZ/d"dZ0d$dZ1e2dk(r e1d d!yy)%zK This module provides data structures for representing first-order models. Npformat) decorator)AbstractVariableExpression AllExpression AndExpressionApplicationExpressionEqualityExpressionExistsExpression Expression IffExpression ImpExpressionIndividualVariableExpressionIotaExpressionLambdaExpressionNegatedExpression OrExpressionVariable is_indvarc eZdZy)ErrorN__name__ __module__ __qualname__W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/sem/evaluate.pyrr,rrc eZdZy) UndefinedNrrrrr!r!0rrr!ctj|}tt|d|}|j ddr-t |j D]}t d|z||i|S)Nrtracez%s => %s)inspectgetfullargspecdictzippopprintitems)fargskwargspecditems rr#r#4sj$$Q'G ST "#AuuWd GGI %D *t# $ % d>b>rct|dk(rytd|Dr*tt|tt|k(ryt d|z)z Check whether a set represents a relation (of any arity). :param s: a set containing tuples of str elements :type s: set :rtype: bool rTc3<K|]}t|tywN) isinstancetuple).0els r zis_rel..Js /rZE " /sz.Set %r contains sequences of different lengths)lenallmaxmin ValueError)ss ris_relr?>sK 1v{ /Q / /CAK3s1v;4NIAMNNrct}|D]a}t|tr|j|f&t|tr|jt|Q|j|c|S)aR Convert a set containing individuals (strings or numbers) into a set of unary tuples. Any tuples of strings already in the set are passed through unchanged. For example: - set(['a', 'b']) => set([('a',), ('b',)]) - set([3, 27]) => set([('3',), ('27',)]) :type s: set :rtype: set of tuple of str )setr4straddint)r>newelems rset2relrGPs^ %C dC GGTG  c " GGCI  GGDM  JrcNt|dk(rytt|dS)ze Check the arity of a relation. :type rel: set of tuples :rtype: int of tuple of str r)r9list)rels rarityrKhs%  3x1} tCy| rc^eZdZdZfdZdZdZedZedZ e dZ xZ S) Valuationa A dictionary which represents a model-theoretic Valuation of non-logical constants. Keys are strings representing the constants to be interpreted, and values correspond to individuals (represented as strings) and n-ary relations (represented as sets of tuples of strings). An instance of ``Valuation`` will raise a KeyError exception (i.e., just behave like a standard dictionary) if indexed with an expression that is not in its list of symbols. ct||D]q\}}t|tst|tr|||<,t|t rt |||<Ktjd|d|d}t|y)z= :param xs: a list of (symbol, value) pairs. z@Error in initializing Valuation. Unrecognized value for symbol 'z': B)widthN) super__init__r4rBboolrArGtextwrapfillr=)selfxssymvalmsg __class__s rrRzValuation.__init__s~  &HC#s#z#t'<S C%#CLS mmADcK !o% &rcR||vrtj||Std|z)NzUnknown expression: '%s'r& __getitem__r!rVkeys rr^zValuation.__getitem__s- $;##D#. .6<= =rct|Sr3rrVs r__str__zValuation.__str__s t}rc g}|jD]`}t|tr|j|%t|tr6|j |Dcgc]}|D]}|| c}}bt |Scc}}w)z7Set-theoretic domain of the value-space of a Valuation.)valuesr4rBappendrSextendrA)rVdomrYtuple_rFs rdomainzValuation.domainsy;;= C#s# 3T* (+SfS$BRTSTS  3xTs  B &B c4t|jS)z9The non-logical constants which the Valuation recognizes.)sortedkeysrbs rsymbolszValuation.symbolssdiik""rct|Sr3)read_valuation)clsr>s r fromstringzValuation.fromstrings a  r) rrr__doc__rRr^rcpropertyrjrn classmethodrr __classcell__r[s@rrMrMssS &&>   ##!!rrMz \s*=+>\s*z\s*,\s*zg\s* (\([^)]+\)) # tuple-expression \s*c^tj|}|d}|d}|jdrz|dd}tj |}|r>g}|D]6}|dd}t t j|}|j|8nt j|}t|}||fS)a Read a line in a valuation file. Lines are expected to be of the form:: noosa => n girl => {g1, g2} chase => {(b1, g1), (b2, g1), (g1, d1), (g2, d2)} :param s: input line :type s: str :return: a pair (symbol, value) :rtype: tuple r{) _VAL_SPLIT_REsplit startswith _TUPLES_REfindallr5_ELEMENT_SPLIT_RErfrA)r>piecessymbolvalue tuple_strings set_elementstselements r_read_valuation_liners  #F AYF 1IE a "**51 L# -"X 1 7 7 ;<##G, - -2259LL! 5=rcN||j|}g}t|jD]G\}}|j}|j ds|dk(r- |j t |It|S#t$r}td|d||d}~wwxYw)a Convert a valuation string into a valuation. :param s: a valuation string :type s: str :param encoding: the encoding of the input string, if it is binary :type encoding: str :return: a ``nltk.sem`` valuation :rtype: Valuation N#zUnable to parse line z: ) decode enumerate splitlinesstripr~rfrr=rM)r>encoding statementslinenumlinees rrprps HHX J"1<<>2O zz| ??3 42:  O   248 9 O Z   O4WIRvFGQ N OsB B$ BB$cJeZdZdZd fd ZdZdZd dZdZdZ dZ xZ S) Assignmentae A dictionary which represents an assignment of values to variables. An assignment can only assign values from its domain. If an unknown expression *a* is passed to a model *M*\ 's interpretation function *i*, *i* will first check whether *M*\ 's valuation assigns an interpretation to *a* as a constant, and if this fails, *i* will delegate the interpretation of *a* to *g*. *g* only assigns values to individual variables (i.e., members of the class ``IndividualVariableExpression`` in the ``logic`` module. If a variable is not assigned a value by *g*, it will raise an ``Undefined`` exception. A variable *Assignment* is a mapping from individual variables to entities in the domain. Individual variables are usually indicated with the letters ``'x'``, ``'y'``, ``'w'`` and ``'z'``, optionally followed by an integer (e.g., ``'x0'``, ``'y332'``). Assignments are created using the ``Assignment`` constructor, which also takes the domain as a parameter. >>> from nltk.sem.evaluate import Assignment >>> dom = set(['u1', 'u2', 'u3', 'u4']) >>> g3 = Assignment(dom, [('x', 'u1'), ('y', 'u2')]) >>> g3 == {'x': 'u1', 'y': 'u2'} True There is also a ``print`` format for assignments which uses a notation closer to that in logic textbooks: >>> print(g3) g[u1/x][u2/y] It is also possible to update an assignment using the ``add`` method: >>> dom = set(['u1', 'u2', 'u3', 'u4']) >>> g4 = Assignment(dom) >>> g4.add('x', 'u1') {'x': 'u1'} With no arguments, ``purge()`` is equivalent to ``clear()`` on a dictionary: >>> g4.purge() >>> g4 {} :param domain: the domain of discourse :type domain: set :param assign: a list of (varname, value) associations :type assign: list ct|||_|rS|D]N\}}||jvs!Jdj||jt |s Jd|z|||<Pd|_|j y)Nz'{}' is not in the domain: {}-Wrong format for an Individual Variable: '%s')rQrRrjformatrvariant _addvariant)rVrjassignvarrYr[s rrRzAssignment.__init__0s  " Sdkk)+J+Q+QKK,)!~CcI~ S    rcR||vrtj||Std|z)Nz"Not recognized as a variable: '%s'r]r_s rr^zAssignment.__getitem__@s- $;##D#. .@3FG GrcRt|j}|j||Sr3)rrjupdate)rVrEs rcopyzAssignment.copyFs!% 4 rcP|r||=n|j|jy)z Remove one or all keys (i.e. logic variables) from an assignment, and update ``self.variant``. :param var: a Variable acting as a key for the assignment. N)clearr)rVrs rpurgezAssignment.purgeKs& S JJL rc`d}t|j}|D]\}}|d|d|dz }|S)zQ Pretty printing for assignments. {'x', 'u'} appears as 'g[u/x]' g[/])rlr)rVgstringrrYrs rrczAssignment.__str__YsH& (HC 3%qQ' 'G (rcvg}|jD]}|d|df}|j|||_y)zK Create a more pretty-printable version of the assignment. ryrN)r*rfr)rVlist_r0pairs rrzAssignment._addvariantdsHJJL DGT!W%D LL   rc||jvsJ|d|jt|s Jd|z|||<|j|S)zh Add a new variable-value pair to the assignment, and update ``self.variant``. z is not in the domain r)rjrr)rVrrYs rrCzAssignment.addos] dkk!NcU*@ #NN!~TNQTTT~S   rr3) rrrrsrRr^rrrcrrCrvrws@rrrs-2h H     rrcBeZdZdZdZdZdZd dZd dZd dZ d d Z y) Modela[ A first order model is a domain *D* of discourse and a valuation *V*. A domain *D* is a set, and a valuation *V* is a map that associates expressions with values in the model. The domain of *V* should be a subset of *D*. Construct a new ``Model``. :type domain: set :param domain: A set of entities representing the domain of discourse of the model. :type valuation: Valuation :param valuation: the valuation of the model. :param prop: If this is set, then we are building a propositional model and don't require the domain of *V* to be subset of *D*. ct|tsJ||_||_|j |jst d|jd|y)NzThe valuation domain, z*, must be a subset of the model's domain, )r4rArj valuation issupersetr)rVrjrs rrRzModel.__init__sV&#&&& "  !1!12##V- 3rc<d|jd|jdS)N(z, )rjrrbs r__repr__zModel.__repr__s 4;;/DNN#5Q77rc:d|jd|jS)Nz Domain = z, Valuation = rrbs rrcz Model.__str__s4;;-'88HIIrNc tj|}|j|||}|rttd|d|d||S#t$r |rttd|d|YywxYw)aA Read input expressions, and provide a handler for ``satisfy`` that blocks further propagation of the ``Undefined`` error. :param expr: An ``Expression`` of ``logic``. :type g: Assignment :param g: an assignment to individual variables. :rtype: bool or 'Undefined' r#'z' evaluates to z under M, z' is undefined under M, r!)r rrsatisfyr)r!)rVexprrr#parsedrs revaluatezModel.evaluates **40FLL%L8E$ugZsCDL $7s;<  sA A &A65A6c:t|tr|j\}}t|tr+j |}t fd|D}||vSj |j }j |j}||St|trj |j St|tr:j |jxrj |jSt|tr:j |jxsj |jSt|tr;j |j xsj |jSt|tr9j |jj |jk(St|t r9j |jj |jk(St|t"rfj%} j&D]F} | j)|j*j,| j |j| rFyyt|t.rfj%} j&D]F} | j)|j*j,| j |j| sFyyt|t0rfj%} j&D]F} | j)|j*j,| j |j| sFyyt|t2r\i} |j*j,} j&D]3} j |jj)| | } | | | <5| Sj5||S)a Recursive interpretation function for a formula of first-order logic. Raises an ``Undefined`` error when ``parsed`` is an atomic string but is not a symbol or an individual variable. :return: Returns a truth value or ``Undefined`` if ``parsed`` is complex, and calls the interpretation function ``i`` if ``parsed`` is atomic. :param parsed: An expression of ``logic``. :type g: Assignment :param g: an assignment to individual variables. c3BK|]}j|ywr3)r)r6argrrVs rr8z Model.satisfy..sJ S! 4JsFT)r4r uncurryrrr5functionargumentrtermrfirstsecondrrr r rrrjrCvariablenamer rri)rVrrr#r argumentsfunvalargvalsargvalnew_gucfrrYs` ` rrz Model.satisfys: f3 4"(.."2 Hi($>?h2J JJ&((fooq9fooq9f~%  1 2||FKK33 3  .<< a0ST\\&--QR5S S  -<< a0RDLLPQ4R R  . V\\155X$,,v}}VW:X X  .<< a0DLLPQ4RR R  2 3<< a0DLLPQ4RR R  .FFHE[[ ! &//..2||FKK7  !  0 1FFHE[[  &//..2<< U3   /FFHE[[  &//..2<< U3   0 1B//&&C[[ ll6;;c1 > 1  I66&!U+ +rc|jj|jjvr#|j|jjSt |t r||jjSt d|z)a An interpretation function. Assuming that ``parsed`` is atomic: - if ``parsed`` is a non-logical constant, calls the valuation *V* - else if ``parsed`` is an individual variable, calls assignment *g* - else returns ``Undefined``. :param parsed: an ``Expression`` of ``logic``. :type g: Assignment :param g: an assignment to individual variables. :return: a semantic value zCan't find a value for %s)rrrrnr4rr!)rVrrr#s rrzModel.isl$ ??  4>>#9#9 9>>&//"6"67 7  < =V__))* *7&@A Arc d}|||zz}g}t|tr t|} n|} | |jvr|r!t t ||zd|d|z|j D]} |j } | j| j| |r |dkDr|dz } nd} |j|| | } |rt |d| zz| dk(r|slt |d|d | d z|j| |st |d|d | d | z|Dchc]}|}}|St| jd |cc}w) a Generate the entities from the model's domain that satisfy an open formula. :param parsed: an open formula :type parsed: Expression :param varex: the relevant free individual variable in ``parsed``. :type varex: VariableExpression or str :param g: a variable assignment :type g: Assignment :return: a set of the entities that satisfy ``parsed``. z zOpen formula is 'z' with assignment ryrz(trying assignment %s)Fz value of 'z' under z is Falsez is z is not free in ) r4rBrfreer)rjrrCrrrfr!)rVrvarexrr#nestingspacerindent candidatesrrrlowtracercresults r satisfierszModel.satisfierss~6G+, eS !5/CC &++- g%)&1CA3GH[[ X #((A&UQY$qyH H VUH=&#;e#CCDE>fF88E7)'TTU%%a(fF88E7$ug'VVW+ X.",,Aa,F,  sxxj(8AB B-s Er3)F)Nr) rrrrsrRrrcrrrrrrrrr|s."8J,I,XB49rrc tgdatat ttat tattdtztdtdtztdttdt tdtzgd}|D]S}|r&tt j|t|+td|dt j|tUy ) z!Example of a propositional model.))PT)QT)RF*zPropositional Formulas Demoz7(Propositional constants treated as nullary predicates)z Model m1: )z(P & Q)z(P & R)z- Pz- Rz- - Pz - (P & R)z(P | R)z(R | P)z(R | R)z (- P | R)z (P | - P)z(P -> Q)z(P -> R)z(R -> P)z (P <-> P)z (R <-> R)z (P <-> R)The value of '' is: N) rMval1rAdom1rm1rg1r)multr)r# sentencessents rpropdemor_s = >D 5D tT B D B G #* '( #* CD G - #*I(H  G KKb% ( N4&r{{4/D.EF G Hrc ddddddhfddd hfd d hfd hd fgattatjat ttattddga|s ttdtztdtdtztdddt tdtgd}|Dcgc]}tj|}}t|D],} td|dt j|t.gd}|D]Z\}} t jtj|t} td|D} t|d|d| | v\yycc}w#t$rtd|zYwxYw#t$rt|d|dYwxYw) zExample of a first-order model.)adamb1)bettyr)fidod1girlrg2boyrb2dogrlove>rrrrrrrr)xr)yrrz Models Demoz Model m2: z-------------- zVariable assignment = )rrrwalksrrzzThe interpretation of 'z ' in m2 is z-The interpretation of '%s' in m2 is Undefined))rr)r)r)r)rr)r)rrc3vK|]1}tjtj|t3ywr3)m2rr rrr)r6rs rr8zfolmodel..s&UZ%:%:3%? DUs79rz) evaluates to z) evaluates to UndefinedN)v2rMval2rjdom2rrrrr)rr rrrr!r5) quietr#exprsr parsed_exprsr applicationsfunr,rargsvals rfolmodelrs  $ t   IJ B R=D ;;D tT B D; 4 5B   cDj m cDj mXtR0 &+?:?@Q --a0@ @ " PF PrttFB/1 P & ?IC ?j33C8"=UPTUUQtfOGv4E3FGH  ?9 A PENO P ?Qtf$<=> ?s+F2)F*AF$F! F!$GGc Ztdttdtztdtdtzgd}|D]]}tj |rt j |t|5td|dt j |t_y) zF Interpretation of closed expressions in a first-order model. Tr rzFOL Formulas Demo)zlove (adam, betty)z (adam = mia)z\x. (boy(x) | girl(x))z\x. boy(x)(adam)z\x y. love(x, y)z\x y. love(x, y)(adam)(betty)z\x y. love(x, y)(adam, betty)z\x y. (boy(x) & love(x, y))z#\x. exists y. (boy(x) & love(x, y))zexists z1. boy(z1)z!exists x. (boy(x) & -(x = adam))z&exists x. (boy(x) & all y. love(y, x))zall x. (boy(x) | girl(x))z1all x. (girl(x) -> exists y. boy(y) & love(x, y))z3exists x. (boy(x) & all y. (girl(y) -> love(y, x)))z3exists x. (boy(x) & all y. (girl(y) -> love(x, y)))zall x. (dog(x) -> - girl(x))z-exists x. exists y. (love(x, y) & love(x, y))rrN)rr)rrrrr)r#formulasfmlas rfoldemors 4 G #*  #*H*H   KKb% ( N4&r{{4/D.EF G Hrc ttdtztdtdtztdgd}|rtt|D]"}t|t j |$|Dcgc]}t j |}}|D]K}t jtdj|tj|dt |Mycc}w) z5Satisfiers of an open formula in a first order model.rzSatisfiers DemoTr)zboy(x)z(x = x)z(boy(x) | girl(x))z(boy(x) & girl(x))z love(adam, x)z love(x, adam)z -(x = adam)zexists z22. love(x, z22)exists y. love(y, x)zall y. (girl(y) -> love(x, y))zall y. (girl(y) -> love(y, x))z)all y. (girl(y) -> (boy(x) & love(y, x)))z)(boy(x) & all y. (girl(y) -> love(x, y)))z)(boy(x) & all y. (girl(y) -> love(y, x)))z+(boy(x) & exists y. (girl(y) & love(y, x)))z(girl(x) -> dog(x))zall y. (dog(y) -> (x = y))rz&exists y. (love(adam, y) & love(y, x))zThe satisfiers of '{}' are: {}rN) r)rrrr rrrrrr)r#rrrps rsatdemors G #*  #* 4H,  b $ d d#$7? ?dj##D) ?F ?     , 3 3Ar}}QRQV7W X  @sC5cttttd} |||y#t$r|D]}|||YywxYw)aO Run exists demos. - num = 1: propositional logic demo - num = 2: first order model demo (only if trace is set) - num = 3: first order sentences demo - num = 4: satisfaction of open formulas demo - any other value: run all the demos :param trace: trace = 1, or trace = 2 for more verbose tracing )ryrN)rrrrKeyError)numr#demoss rdemor"(sQX'g >E$c  $ $C E#JU # $$s &AA__main__rrr3)FN)rN)3rsr$resysrTpprintrnltk.decoratorsrnltk.sem.logicrrrr r r r r rrrrrrrr Exceptionrr!r#r?rGrKr&rMcompiler|rVERBOSErrrprrrrrrrr"rrrrr,s  %( I   O$0<!<!D <( BJJz* RZZ'JJ   F!2~~BWW|  *Hb5?x%HX- `$* z!r