src/Tools/isac/Interpret/inform.sml
author Walther Neuper <neuper@ist.tugraz.at>
Mon, 22 Jul 2013 13:52:18 +0200
changeset 52070 77138c64f4f6
parent 48763 9b9936d79dbe
child 52161 8e11b1c9af61
permissions -rw-r--r--
--- Test_Isac.thy runs all tests

NOTEs:
(1) inserted many "trace_rewrite := false" ...
(2) ...nevertheless needs manual interaction at "Tracing paused. Stop, or continue with next 100, 1000, 10000 messages?"
(3) state of tests see respective section in Test_Isac.thy
     1 (* Handle user-input during the specify- and the solve-phase. 
     2    author: Walther Neuper
     3    0603
     4    (c) due to copyright terms
     5 
     6 use"ME/inform.sml";
     7 use"inform.sml";
     8 *)
     9 
    10 signature INFORM =
    11   sig 
    12 
    13     type castab
    14     type icalhd
    15 
    16    (* type iitem *)
    17     datatype
    18       iitem =
    19           Find of cterm' list
    20         | Given of cterm' list
    21         | Relate of cterm' list
    22     type imodel
    23     val imodel2fstr : iitem list -> (string * cterm') list
    24 
    25     
    26     val Isac : 'a -> theory
    27     val appl_add' :
    28        theory' ->
    29        SpecifyTools.ori list ->
    30        SpecifyTools.itm list ->
    31        ('a * (Term.term * Term.term)) list ->
    32        string * cterm' -> SpecifyTools.itm
    33   (*  val appl_adds :
    34        theory' ->
    35        SpecifyTools.ori list ->
    36        SpecifyTools.itm list ->
    37        (string * (Term.term * Term.term)) list ->
    38        (string * string) list -> SpecifyTools.itm list *)
    39    (* val cas_input : string -> ptree * ocalhd *)
    40    (* val cas_input_ :
    41        spec ->
    42        (Term.term * Term.term list) list ->
    43        pblID * SpecifyTools.itm list * metID * SpecifyTools.itm list *
    44        (bool * Term.term) list  *)
    45     val castab : castab Unsynchronized.ref
    46     val compare_step :
    47        calcstate' -> Term.term -> string * calcstate'
    48    (* val concat_deriv :
    49        'a * ((Term.term * Term.term) list -> Term.term * Term.term -> bool)
    50        ->
    51        rls ->
    52        rule list ->
    53        Term.term ->
    54        Term.term ->
    55        bool * (Term.term * rule * (Term.term * Term.term list)) list *)
    56     val dropwhile' :   (* systest/auto-inform.sml *)
    57        ('a -> 'b -> bool) -> 'a list -> 'b list -> 'a list * 'b list
    58    (* val dtss2itm_ :
    59        pbt_ list ->
    60        Term.term * Term.term list ->
    61        int list * bool * string * SpecifyTools.itm_ *)
    62    (* val e_icalhd : icalhd *)
    63     val eq7 : ''a * ''b -> ''a * (''b * 'c) -> bool
    64     val equal : ''a -> ''a -> bool
    65    (* val filter_dsc :
    66        SpecifyTools.ori list -> SpecifyTools.itm -> SpecifyTools.ori list *)
    67    (* val filter_sep : ('a -> bool) -> 'a list -> 'a list * 'a list *)
    68    (* val flattup2 : 'a * ('b * 'c * 'd * 'e) -> 'a * 'b * 'c * 'd * 'e *)
    69    (* val fstr2itm_ :
    70        theory ->
    71        (''a * (Term.term * Term.term)) list ->
    72        ''a * string -> int list * bool * ''a * SpecifyTools.itm_ *)
    73     val inform :
    74        calcstate' -> cterm' -> string * calcstate'   
    75     val input_icalhd : ptree -> icalhd -> ptree * ocalhd
    76    (* val is_Par : SpecifyTools.itm -> bool *)
    77    (* val is_casinput : cterm' -> fmz -> bool *)
    78    (* val is_e_ts : Term.term list -> bool *)
    79    (* val itms2fstr : SpecifyTools.itm -> string * string *)
    80    (* val mk_tacis :
    81        rew_ord' * 'a ->
    82        rls ->
    83        Term.term * rule * (Term.term * Term.term list) ->
    84        tac * tac_ * (pos' * istate)      *)
    85     val oris2itms :
    86        'a -> int -> SpecifyTools.ori list -> SpecifyTools.itm list
    87    (* val par2fstr : SpecifyTools.itm -> string * cterm' *)
    88    (* val parsitm : theory -> SpecifyTools.itm -> SpecifyTools.itm *)
    89     val rev_deriv' : 'a * rule * ('b * 'c) -> 'b * rule * ('a * 'c)
    90    (* val unknown_expl :
    91        theory' ->
    92        (string * (Term.term * Term.term)) list ->
    93        (string * string) list -> SpecifyTools.itm list *)
    94   end
    95 
    96 
    97 
    98 
    99 
   100 
   101 (***. handle an input calc-head .***)
   102 
   103 (*------------------------------------------------------------------(**)
   104 structure inform :INFORM =
   105 struct
   106 (**)------------------------------------------------------------------*)
   107 
   108 datatype iitem = 
   109   Given of cterm' list
   110 (*Where is never input*) 
   111 | Find  of cterm' list
   112 | Relate  of cterm' list;
   113 
   114 type imodel = iitem list;
   115 
   116 (*calc-head as input*)
   117 type icalhd =
   118      pos' *     (*the position of the calc-head in the calc-tree
   119 		 pos' as (p,p_) where p_ is neglected due to pos_ below*) 
   120      cterm' *   (*the headline*)
   121      imodel *   (*the model (without Find) of the calc-head*)
   122      pos_ *     (*model belongs to Pbl or Met*)
   123      spec;      (*specification: domID, pblID, metID*)
   124 val e_icalhd = (e_pos', "", [Given [""]], Pbl, e_spec): icalhd;
   125 
   126 fun is_casinput (hdf: cterm') ((fmz_, spec): fmz) =
   127     hdf <> "" andalso fmz_ = [] andalso spec = e_spec;
   128 
   129 (*.handle an input as into an algebra system.*)
   130 fun dtss2itm_ ppc (d, ts) =
   131     let val (f, (d, id)) = the (find_first ((curry op= d) o 
   132 					    (#1: (term * term) -> term) o
   133 					    (#2: pbt_ -> (term * term))) ppc)
   134     in ([1], true, f, Cor ((d, ts), (id, ts))) end;
   135 
   136 fun flattup2 (a,(b,c,d,e)) = (a,b,c,d,e);
   137 
   138 
   139 
   140 (*.association list with cas-commands, for generating a complete calc-head.*)
   141 type castab = 
   142      (term *         (*cas-command, eg. 'solve'*)
   143       (spec * 	     (*theory, problem, method*)
   144 
   145        		     (*the function generating a kind of formalization*)
   146        (term list -> (*the arguments of the cas-command, eg. (x+1=2, x)*)
   147 	(term *      (*description of an element*)
   148 	 term list)  (*value of the element (always put into a list)*)
   149 	    list)))  (*of elements in the formalization*)
   150 	 list;       (*of cas-entries in the association list*)
   151 
   152 val castab = Unsynchronized.ref ([]: castab);
   153 
   154 
   155 fun cas_input_ ((dI,pI,mI): spec) dtss = (*WN110515 reconsider thy..ctxt*)
   156   let
   157     val thy = assoc_thy dI
   158 	  val {ppc, ...} = get_pbt pI
   159 	  val its_ = map (dtss2itm_ ppc) dtss (*([1],true,"#Given",Cor (...))*)
   160 	  val its = add_id its_
   161 	  val pits = map flattup2 its
   162 	  val (pI, mI) =
   163       if mI <> ["no_met"]
   164       then (pI, mI)
   165 		  else
   166         case refine_pbl thy pI pits of
   167 			    SOME (pI,_) => (pI, (hd o #met o get_pbt) pI)
   168 			  | NONE => (pI, (hd o #met o get_pbt) pI)
   169 	  val {ppc, pre, prls, ...} = get_met mI
   170 	  val its_ = map (dtss2itm_ ppc) dtss (*([1],true,"#Given",Cor (...))*)
   171 	  val its = add_id its_
   172 	  val mits = map flattup2 its
   173 	  val pre = check_preconds thy prls pre mits
   174     val ctxt = e_ctxt (*WN110515 cas_input_ DOESNT WORK*)
   175   in (pI, pits: itm list, mI, mits: itm list, pre, ctxt) end;
   176 
   177 
   178 (* check if the input term is a CAScmd and return a ptree with a _complete_ calchead *)
   179 fun cas_input hdt =
   180   let val (h,argl) = strip_comb hdt
   181   in
   182     case assoc (!castab, h) of
   183      NONE => NONE
   184    | SOME (spec as (dI,_,_), argl2dtss) =>
   185 	      let
   186           val dtss = argl2dtss argl
   187 	        val (pI, pits, mI, mits, pre, ctxt) = cas_input_ spec dtss
   188 	        val spec = (dI, pI, mI)
   189 	        val (pt,_) = 
   190 		        cappend_problem e_ptree [] (e_istate, e_ctxt) ([], e_spec) ([], e_spec, hdt)
   191 	        val pt = update_spec pt [] spec
   192 	        val pt = update_pbl pt [] pits
   193 	        val pt = update_met pt [] mits
   194 	        val pt = update_ctxt pt [] ctxt
   195 	      in SOME (pt, (true, Met, hdt, mits, pre, spec) : ocalhd) end
   196   end;
   197 
   198 (*lazy evaluation for (Thy_Info.get_theory "Isac")*)
   199 fun Isac _  = assoc_thy "Isac";
   200 
   201 (*re-parse itms with a new thy and prepare for checking with ori list*)
   202 fun parsitm dI (itm as (i,v,b,f, Cor ((d,ts),_)):itm) =
   203     (let
   204       val t = comp_dts (d,ts);
   205       val s = term_to_string''' dI t;
   206        (*this    ^ should raise the exn on unability of re-parsing dts*)
   207     in itm end
   208     handle _ => ((i,v,false,f, Syn (term2str t)):itm))
   209   | parsitm dI (itm as (i,v,b,f, Syn str)) =
   210     (let val t = (term_of o the o (parse dI)) str
   211     in (i,v,b,f, Par str) end
   212     handle _ => (i,v,b,f, Syn str))
   213   | parsitm dI (itm as (i,v,b,f, Typ str)) =
   214     (let val t = (term_of o the o (parse dI)) str
   215      in (i,v,b,f, Par str) end
   216      handle _ => (i,v,b,f, Syn str))
   217   | parsitm dI (itm as (i,v,_,f, Inc ((d,ts),_))) =
   218     (let val t = comp_dts (d,ts);
   219 	       val s = term_to_string''' dI t;
   220      (*this    ^ should raise the exn on unability of re-parsing dts*)
   221      in itm end
   222      handle _ => ((i,v,false,f, Syn (term2str t)):itm))
   223   | parsitm dI (itm as (i,v,_,f, Sup (d,ts))) =
   224     (let val t = comp_dts (d,ts);
   225 	       val s = term_to_string''' dI t;
   226      (*this    ^ should raise the exn on unability of re-parsing dts*)
   227     in itm end
   228     handle _ => ((i,v,false,f, Syn (term2str t)):itm))
   229   | parsitm dI (itm as (i,v,_,f, Mis (d,t'))) =
   230     (let val t = d $ t';
   231 	       val s = term_to_string''' dI t;
   232      (*this    ^ should raise the exn on unability of re-parsing dts*)
   233     in itm end
   234     handle _ => ((i,v,false,f, Syn (term2str t)):itm))
   235   | parsitm dI (itm as (i,v,_,f, Par _)) = 
   236     error ("parsitm (" ^ itm2str_ (thy2ctxt dI) itm ^ "): Par should be internal");
   237 
   238 (*separate a list to a pair of elements that do NOT satisfy the predicate,
   239  and of elements that satisfy the predicate, i.e. (false, true)*)
   240 fun filter_sep pred xs =
   241   let fun filt ab [] = ab
   242         | filt (a,b) (x :: xs) = if pred x 
   243 				 then filt (a,b@[x]) xs 
   244 				 else filt (a@[x],b) xs
   245   in filt ([],[]) xs end;
   246 fun is_Par ((_,_,_,_,Par _):itm) = true
   247   | is_Par _ = false;
   248 
   249 fun is_e_ts [] = true
   250   | is_e_ts [Const ("List.list.Nil", _)] = true
   251   | is_e_ts _ = false;
   252 
   253 (*WN.9.11.03 copied from fun appl_add (in modspec.sml)*)
   254 (* val (sel,ct) = selct;
   255    val (dI, oris, ppc, pbt, (sel, ct))=
   256        (#1 (some_spec ospec spec), oris, []:itm list,
   257 	((#ppc o get_pbt) (#2 (some_spec ospec spec))),
   258 	hd (imodel2fstr imodel));
   259    *)
   260 fun appl_add' dI oris ppc pbt (sel, ct) = 
   261     let 
   262       val ctxt = assoc_thy dI |> thy2ctxt;
   263     in case parseNEW ctxt ct of
   264 	   NONE => (0,[],false,sel, Syn ct):itm
   265 	 | SOME t => (case is_known ctxt sel oris t of
   266          ("", ori', all) =>
   267            (case is_notyet_input ctxt ppc all ori' pbt of
   268 	         ("",itm)  => itm
   269 	       | (msg,_) => error ("appl_add': " ^ msg))
   270      | (_, (i, v, _, d, ts), _) => if is_e_ts ts then
   271          (i, v, false, sel, Inc ((d, ts), (e_term, []))) else
   272          (i, v, false, sel, Sup (d, ts)))
   273     end;
   274 
   275 (*.generate preliminary itm_ from a strin (with field "#Given" etc.).*)
   276 (* val (f, str) = hd selcts;
   277    *)
   278 fun eq7 (f, d) (f', (d', _)) = f=f' andalso d=d';
   279 fun fstr2itm_ thy pbt (f, str) =
   280     let val topt = parse thy str
   281     in case topt of
   282 	   NONE => ([], false, f, Syn str)
   283 	 | SOME ct => 
   284 (* val SOME ct = parse thy str;
   285    *)
   286 	   let val (d,ts) = (split_dts o term_of) ct
   287 	       val popt = find_first (eq7 (f,d)) pbt
   288 	   in case popt of
   289 		  NONE => ([1](*??*), true(*??*), f, Sup (d,ts))
   290 		| SOME (f, (d, id)) => ([1], true, f, Cor ((d,ts), (id, ts))) 
   291 	   end
   292     end; 
   293 
   294 
   295 (*.input into empty PblObj, i.e. empty fmz+origin (unknown example).*)
   296 fun unknown_expl dI pbt selcts =
   297   let
   298     val thy = assoc_thy dI
   299     val its_ = map (fstr2itm_ thy pbt) selcts (*([1],true,"#Given",Cor (...))*)
   300     val its = add_id its_ 
   301 in (map flattup2 its): itm list end;
   302 
   303 
   304 
   305 
   306 (*WN.11.03 for input_icalhd, ~ specify_additem for Add_Given/_Find/_Relation
   307  appl_add': generate 1 item 
   308  appl_add' . is_known: parse, get data from oris (vats, all (elems if list)..)
   309  appl_add' . is_notyet_input: compare with items in model already input
   310  insert_ppc': insert this 1 item*)
   311 (* val (dI,oris,ppc,pbt,selcts) =((#1 (some_spec ospec spec)),oris,[(*!!*)],
   312 			       ((#ppc o get_pbt) (#2 (some_spec ospec spec))),
   313 			       (imodel2fstr imodel));
   314    *)
   315 fun appl_adds dI [] _ pbt selcts = unknown_expl dI pbt selcts
   316   (*already present itms in model are being overwritten*)
   317   | appl_adds dI oris ppc pbt [] = ppc
   318   | appl_adds dI oris ppc pbt (selct::ss) =
   319     (* val selct = (sel, string_of_cterm ct);
   320        *)
   321     let val itm = appl_add' dI oris ppc pbt selct;
   322     in appl_adds dI oris (insert_ppc' itm ppc) pbt ss end;
   323 (* val (dI, oris, ppc, pbt, selct::ss) = 
   324        (dI, pors, probl, ppc, map itms2fstr probl);
   325    ...vvv
   326    *)
   327 (* val (dI, oris, ppc, pbt, (selct::ss))=
   328        (#1 (some_spec ospec spec), oris, []:itm list,
   329 	((#ppc o get_pbt) (#2 (some_spec ospec spec))),(imodel2fstr imodel));
   330    val iii = appl_adds dI oris ppc pbt (selct::ss); 
   331    tracing(itms2str_ thy iii);
   332 
   333  val itm = appl_add' dI oris ppc pbt selct;
   334  val ppc = insert_ppc' itm ppc;
   335 
   336  val _::selct::ss = (selct::ss);
   337  val itm = appl_add' dI oris ppc pbt selct;
   338  val ppc = insert_ppc' itm ppc;
   339 
   340  val _::selct::ss = (selct::ss);
   341  val itm = appl_add' dI oris ppc pbt selct;
   342  val ppc = insert_ppc' itm ppc;
   343  tracing(itms2str_ thy ppc);
   344 
   345  val _::selct::ss = (selct::ss);
   346  val itm = appl_add' dI oris ppc pbt selct;
   347  val ppc = insert_ppc' itm ppc;
   348    *)
   349 
   350 
   351 fun oris2itms _ _ ([]:ori list) = ([]:itm list)
   352   | oris2itms pbt vat ((i,v,f,d,ts)::(os: ori list)) =
   353     if member op = vat v 
   354     then (i,v,true,f,Cor ((d,ts),(e_term,[])))::(oris2itms pbt vat os)
   355     else oris2itms pbt vat os;
   356 
   357 fun filter_dsc oris itm = 
   358     filter_out ((curry op= ((d_in o #5) (itm:itm))) o 
   359 		(#4:ori -> term)) oris;
   360 
   361 
   362 
   363 
   364 fun par2fstr ((_,_,_,f, Par s):itm) = (f, s)
   365   | par2fstr itm = error ("par2fstr: called with " ^
   366 			      itm2str_ (thy2ctxt' "Isac") itm);
   367 fun itms2fstr ((_,_,_,f, Cor ((d,ts),_)):itm) = (f, comp_dts'' (d,ts))
   368   | itms2fstr (_,_,_,f, Syn str) = (f, str)
   369   | itms2fstr (_,_,_,f, Typ str) = (f, str)
   370   | itms2fstr (_,_,_,f, Inc ((d,ts),_)) = (f, comp_dts'' (d,ts))
   371   | itms2fstr (_,_,_,f, Sup (d,ts)) = (f, comp_dts'' (d,ts))
   372   | itms2fstr (_,_,_,f, Mis (d,t)) = (f, term2str (d $ t))
   373   | itms2fstr (itm as (_,_,_,f, Par _)) = 
   374     error ("parsitm ("^itm2str_ (thy2ctxt' "Isac") itm ^
   375 		 "): Par should be internal");
   376 
   377 fun imodel2fstr iitems = 
   378   let 
   379     fun xxx is [] = is
   380 	    | xxx is ((Given strs)::iis) = xxx (is @ (map (pair "#Given") strs)) iis
   381 	    | xxx is ((Find strs)::iis) = xxx (is @ (map (pair "#Find") strs)) iis
   382 	    | xxx is ((Relate strs)::iis) = xxx (is @ (map (pair "#Relate") strs)) iis
   383   in xxx [] iitems end;
   384 
   385 (* input a calchead, WN110505 "prep_oris -> (_, ctxt)" not handled properly *)
   386 fun input_icalhd pt (((p,_), hdf, imodel, Pbl, spec as (dI,pI,mI)):icalhd) =
   387     let val PblObj {fmz = fmz as (fmz_,_), origin = (oris, ospec, hdf'), 
   388 		      spec = sspec as (sdI,spI,smI), probl, meth, ...} = get_obj I pt p;
   389     in if is_casinput hdf fmz then the (cas_input (str2term hdf)) 
   390        else        (*hacked WN0602 ~~~            ~~~~~~~~~,   ..dropped !*)
   391          let val (pos_, pits, mits) = 
   392 	         if dI <> sdI
   393 	         then let val its = map (parsitm (assoc_thy dI)) probl;
   394 			            val (its, trms) = filter_sep is_Par its;
   395 			            val pbt = (#ppc o get_pbt) (#2(some_spec ospec sspec));
   396 		            in (Pbl, appl_adds dI oris its pbt  (map par2fstr trms), meth) end 
   397            else if pI <> spI 
   398 	              then if pI = snd3 ospec then (Pbl, probl, meth) 
   399                      else
   400 		                   let val pbt = (#ppc o get_pbt) pI
   401 			                   val dI' = #1 (some_spec ospec spec)
   402 			                   val oris = if pI = #2 ospec then oris 
   403 				                            else prep_ori fmz_(assoc_thy"Isac") pbt |> #1;
   404 		                   in (Pbl, appl_adds dI' oris probl pbt 
   405 				                 (map itms2fstr probl), meth) end 
   406                 else if mI <> smI (*FIXME.WN0311: what if probl is incomplete?!*)
   407 	                   then let val met = (#ppc o get_met) mI
   408 		                        val mits = complete_metitms oris probl meth met
   409 		                      in if foldl and_ (true, map #3 mits)
   410 		                         then (Pbl, probl, mits) else (Met, probl, mits) 
   411 		                      end 
   412                      else (Pbl, appl_adds (#1 (some_spec ospec spec)) oris [(*!!!*)]
   413 			                     ((#ppc o get_pbt) (#2 (some_spec ospec spec)))
   414 			                     (imodel2fstr imodel), meth);
   415 	         val pt = update_spec pt p spec;
   416          in if pos_ = Pbl
   417 	          then let val {prls,where_,...} = get_pbt (#2 (some_spec ospec spec))
   418 		               val pre =check_preconds(assoc_thy"Isac")prls where_ pits
   419 	               in (update_pbl pt p pits,
   420 		                 (ocalhd_complete pits pre spec, Pbl, hdf', pits, pre, spec):ocalhd) 
   421                  end
   422 	           else let val {prls,pre,...} = get_met (#3 (some_spec ospec spec))
   423 		                val pre = check_preconds (assoc_thy"Isac") prls pre mits
   424 	                in (update_met pt p mits,
   425 		                  (ocalhd_complete mits pre spec, Met, hdf', mits, pre, spec):ocalhd)
   426                   end
   427          end 
   428     end
   429   | input_icalhd pt ((p,_), hdf, imodel, _(*Met*), spec as (dI,pI,mI)) =
   430     error "input_icalhd Met not impl.";
   431 
   432 
   433 (***. handle an input formula .***)
   434 (*
   435 Untersuchung zur Formeleingabe (appendFormula, replaceFormla) zu einer Anregung von Alan Krempler:
   436 Welche RICHTIGEN Formeln koennen NICHT abgeleitet werden, 
   437 wenn Abteilungen nur auf gleichem Level gesucht werden ?
   438 WN.040216 
   439 
   440 Beispiele zum Equationsolver von Richard Lang aus /src/sml/kbtest/rlang.sml
   441 
   442 ------------------------------------------------------------------------------
   443 "Schalk I s.87 Bsp 52a ((5*x)/(x - 2) - x/(x+2)=4)";
   444 ------------------------------------------------------------------------------
   445 1. "5 * x / (x - 2) - x / (x + 2) = 4"
   446 ...
   447 4. "12 * x + 4 * x ^^^ 2 = 4 * (-4 + x ^^^ 2)",Subproblem["normalize", "poly"..
   448 ...
   449 4.3. "16 + 12 * x = 0", Subproblem["degree_1", "polynomial", "univariate"..
   450 ...
   451 4.3.3. "[x = -4 / 3]")), Check_elementwise "Assumptions"
   452 ...
   453 "[x = -4 / 3]"
   454 ------------------------------------------------------------------------------
   455 (1)..(6): keine 'richtige' Eingabe kann abgeleitet werden, die einen Summanden auf die andere Seite verschiebt [Ableitung ware in 4.3.n]
   456 
   457 (4.1)..(4.3): keine 'richtige' Eingabe kann abgeleitet werden, die einen Summanden auf die andere Seite verschiebt [Ableitung ware in 4.3.n]
   458 ------------------------------------------------------------------------------
   459 
   460 
   461 ------------------------------------------------------------------------------
   462 "Schalk I s.87 Bsp 55b (x/(x^^^2 - 6*x+9) - 1/(x^^^2 - 3*x) =1/x)";
   463 ------------------------------------------------------------------------------
   464 1. "x / (x ^^^ 2 - 6 * x + 9) - 1 / (x ^^^ 2 - 3 * x) = 1 / x"
   465 ...
   466 4. "(3 + (-1 * x + x ^^^ 2)) * x = 1 * (9 * x + (x ^^^ 3 + -6 * x ^^^ 2))"
   467                          Subproblem["normalize", "polynomial", "univariate"..
   468 ...
   469 4.4. "-6 * x + 5 * x ^^^ 2 = 0", Subproblem["bdv_only", "degree_2", "poly"..
   470 ...
   471 4.4.4. "[x = 0, x = 6 / 5]", Check_elementwise "Assumptions"
   472 4.4.5. "[x = 0, x = 6 / 5]"
   473 ...
   474 5. "[x = 0, x = 6 / 5]", Check_elementwise "Assumptions"
   475    "[x = 6 / 5]"
   476 ------------------------------------------------------------------------------
   477 (1)..(4): keine 'richtige' Eingabe kann abgeleitet werden, die einen Summanden auf die andere Seite schiebt [Ableitung waere in 4.4.x]
   478 
   479 (4.1)..(4.4.5): keine 'richtige' Eingabe kann abgeleitet werden, die dem Ergebnis "[x = 6 / 5]" aequivalent ist [Ableitung waere in 5.]
   480 ------------------------------------------------------------------------------
   481 
   482 
   483 ------------------------------------------------------------------------------
   484 "Schalk II s.56 Bsp 73b (sqrt(x+1)+sqrt(4*x+4)=sqrt(9*x+9))";
   485 ------------------------------------------------------------------------------
   486 1. "sqrt (x + 1) + sqrt (4 * x + 4) = sqrt (9 * x + 9)"
   487 ...
   488 6. "13 + 13 * x + -2 * sqrt ((4 + 4 * x) * (9 + 9 * x)) = 1 + x"
   489                              Subproblem["sq", "root'", "univariate", "equation"]
   490 ...
   491 6.6. "144 + 288 * x + 144 * x ^^^ 2 = 144 + x ^^^ 2 + 288 * x + 143 * x ^^^ 2"
   492                 Subproblem["normalize", "polynomial", "univariate", "equation"]
   493 ...
   494 6.6.3 "0 = 0"    Subproblem["degree_0", "polynomial", "univariate", "equation"]
   495 ...                                       Or_to_List
   496 6.6.3.2 "UniversalList"
   497 ------------------------------------------------------------------------------
   498 (1)..(6): keine 'richtige' Eingabe kann abgeleitet werden, die eine der Wurzeln auf die andere Seite verschieb [Ableitung ware in 6.6.n]
   499 
   500 (6.1)..(6.3): keine 'richtige' Eingabe kann abgeleitet werden, die einen Summanden auf die andere Seite verschiebt [Ableitung ware in 6.6.n]
   501 ------------------------------------------------------------------------------
   502 *)
   503 (*sh. comments auf 498*)
   504 
   505 fun equal a b = a=b;
   506 
   507 (*the lists contain eq-al elem-pairs at the beginning;
   508   return first list reverted (again) - ie. in order as required subsequently*)
   509 fun dropwhile' equal (f1::f2::fs) (i1::i2::is) =
   510     if equal f1 i1 then
   511 	 if equal f2 i2 then dropwhile' equal (f2::fs) (i2::is)
   512 	 else (rev (f1::f2::fs), i1::i2::is)
   513     else error "dropwhile': did not start with equal elements"
   514   | dropwhile' equal (f::fs) [i] =
   515     if equal f i then (rev (f::fs), [i])
   516     else error "dropwhile': did not start with equal elements"
   517   | dropwhile' equal [f] (i::is) =
   518     if equal f i then ([f], i::is)
   519     else error "dropwhile': did not start with equal elements";
   520 (*
   521  fun equal a b = a=b;
   522  val foder = [0,1,2,3,4,5]; val ifoder = [11,12,3,4,5];
   523  val r_foder = rev foder;  val r_ifoder = rev ifoder;
   524  dropwhile' equal r_foder r_ifoder;
   525 > vval it = ([0, 1, 2, 3], [3, 12, 11]) : int list * int list
   526 
   527  val foder = [3,4,5]; val ifoder = [11,12,3,4,5];
   528  val r_foder = rev foder;  val r_ifoder = rev ifoder;
   529  dropwhile' equal r_foder r_ifoder;
   530 > val it = ([3], [3, 12, 11]) : int list * int list
   531 
   532  val foder = [5]; val ifoder = [11,12,3,4,5];
   533  val r_foder = rev foder;  val r_ifoder = rev ifoder;
   534  dropwhile' equal r_foder r_ifoder;
   535 > val it = ([5], [5, 4, 3, 12, 11]) : int list * int list
   536 
   537  val foder = [10,11,12,13,14,15]; val ifoder = [11,12,3,4,5];
   538  val r_foder = rev foder;  val r_ifoder = rev ifoder;
   539  dropwhile' equal r_foder r_ifoder;
   540 > *** dropwhile': did not start with equal elements*)
   541 
   542 (*040214: version for concat_deriv*)
   543 fun rev_deriv' (t, r, (t', a)) = (t', sym_Thm r, (t, a));
   544 
   545 fun mk_tacis ro erls (t, r as Thm _, (t', a)) = 
   546       (Rewrite (rule2thm' r), 
   547          Rewrite' ("Isac", fst ro, erls, false, rule2thm' r, t, (t', a)),
   548        (e_pos'(*to be updated before generate tacis!!!*), (Uistate, e_ctxt)))
   549   | mk_tacis ro erls (t, r as Rls_ rls, (t', a)) = 
   550       (Rewrite_Set (rule2rls' r), 
   551          Rewrite_Set' ("Isac", false, rls, t, (t', a)),
   552        (e_pos'(*to be updated before generate tacis!!!*), (Uistate, e_ctxt)));
   553 
   554 (*fo = ifo excluded already in inform*)
   555 fun concat_deriv rew_ord erls rules fo ifo =
   556     let fun derivat ([]:(term * rule * (term * term list)) list) = e_term
   557 	  | derivat dt = (#1 o #3 o last_elem) dt
   558         fun equal (_,_,(t1, _)) (_,_,(t2, _)) = t1=t2
   559 	val  fod = make_deriv (Isac"") erls rules (snd rew_ord) NONE  fo
   560 	val ifod = make_deriv (Isac"") erls rules (snd rew_ord) NONE ifo
   561     in case (fod, ifod) of
   562 	   ([], []) => if fo = ifo then (true, [])
   563 		       else (false, [])
   564 	 | (fod, []) => if derivat fod = ifo 
   565 			then (true, fod) (*ifo is normal form*)
   566 			else (false, [])
   567 	 | ([], ifod) => if fo = derivat ifod 
   568 			 then (true, ((map rev_deriv') o rev) ifod)
   569 			 else (false, [])
   570 	 | (fod, ifod) =>
   571 	   if derivat fod = derivat ifod (*common normal form found*)
   572 	   then let val (fod', rifod') = 
   573 			dropwhile' equal (rev fod) (rev ifod)
   574 		in (true, fod' @ (map rev_deriv' rifod')) end
   575 	   else (false, [])
   576     end;
   577 (*
   578  val ({rew_ord, erls, rules,...}, fo, ifo) = 
   579      (rep_rls Test_simplify, str2term "x+1+ -1*2=0", str2term "-2*1+(x+1)=0");
   580  (tracing o trtas2str) fod';
   581 > ["
   582 (x + 1 + -1 * 2 = 0, Thm ("radd_commute","?m + ?n = ?n + ?m"), (-1 * 2 + (x + 1) = 0, []))","
   583 (-1 * 2 + (x + 1) = 0, Thm ("radd_commute","?m + ?n = ?n + ?m"), (-1 * 2 + (1 + x) = 0, []))","
   584 (-1 * 2 + (1 + x) = 0, Thm ("radd_left_commute","?x + (?y + ?z) = ?y + (?x + ?z)"), (1 + (-1 * 2 + x) = 0, []))","
   585 (1 + (-1 * 2 + x) = 0, Thm ("#mult_Float ((~1,0), (0,0)) __ ((2,0), (0,0))","-1 * 2 = -2"), (1 + (-2 + x) = 0, []))"]
   586 val it = () : unit
   587  (tracing o trtas2str) (map rev_deriv' rifod');
   588 > ["
   589 (1 + (-2 + x) = 0, Thm ("sym_#mult_Float ((~2,0), (0,0)) __ ((1,0), (0,0))","-2 = -2 * 1"), (1 + (-2 * 1 + x) = 0, []))","
   590 (1 + (-2 * 1 + x) = 0, Thm ("sym_radd_left_commute","?y + (?x + ?z) = ?x + (?y + ?z)"), (-2 * 1 + (1 + x) = 0, []))","
   591 (-2 * 1 + (1 + x) = 0, Thm ("sym_radd_commute","?n + ?m = ?m + ?n"), (-2 * 1 + (x + 1) = 0, []))"]
   592 val it = () : unit
   593 *)
   594 
   595 
   596 (* compare inform with ctree.form at current pos by nrls;
   597    if found, embed the derivation generated during comparison
   598    if not, let the mat-engine compute the next ctree.form *)
   599 (*structure copied from complete_solve
   600   CAUTION: tacis in returned calcstate' do NOT construct resulting ptp --
   601            all_modspec etc. has to be inserted at Subproblem'*)
   602 fun compare_step ((tacis, c, ptp as (pt, pos as (p,p_))): calcstate') ifo =
   603   let
   604     val fo =
   605       case p_ of
   606         Frm => get_obj g_form pt p
   607 			| Res => (fst o (get_obj g_result pt)) p
   608 			| _ => e_term (*on PblObj is fo <> ifo*);
   609 	  val {nrls, ...} = get_met (get_obj g_metID pt (par_pblobj pt p))
   610 	  val {rew_ord, erls, rules, ...} = rep_rls nrls
   611 	  val (found, der) = concat_deriv rew_ord erls rules fo ifo; (*<---------------*)
   612   in
   613     if found
   614     then
   615        let
   616          val tacis' = map (mk_tacis rew_ord erls) der;
   617 		     val (c', ptp) = embed_deriv tacis' ptp;
   618 	     in ("ok", (tacis (*@ tacis'?WN050408*), c @ c', ptp)) end
   619      else 
   620 	     if pos = ([], Res) 
   621 	     then ("no derivation found", (tacis, c, ptp): calcstate') 
   622 	     else
   623          let
   624            val cs' as (tacis, c', ptp) = nxt_solve_ ptp; (*<---------------------*)
   625 		       val cs' as (tacis, c'', ptp) = 
   626 			       case tacis of
   627 			         ((Subproblem _, _, _)::_) => 
   628 			           let
   629                    val ptp as (pt, (p,_)) = all_modspec ptp
   630 				           val mI = get_obj g_metID pt p
   631 			           in
   632 			             nxt_solv (Apply_Method' (mI, NONE, e_istate, e_ctxt)) (e_istate, e_ctxt) ptp
   633                  end
   634 			       | _ => cs';
   635 		     in compare_step (tacis, c @ c' @ c'', ptp) ifo end
   636   end;
   637 
   638 (* check if (agreed result, input formula) matches the error pattern "pat" modulo simplifier rls *)
   639 fun check_err_patt (res, inf) (subst: subst) (errpatID: errpatID, pat) rls =
   640   let 
   641     val (res', _, _, rewritten) =
   642       rew_sub (Isac()) 1 subst e_rew_ord e_rls false [] (Trueprop $ pat) res;
   643   in
   644     if rewritten
   645     then 
   646       let
   647         val norm_res = case rewrite_set_inst_ (Isac()) false subst rls  res' of
   648           NONE => res'
   649         | SOME (norm_res, _) => norm_res
   650         val norm_inf = case rewrite_set_inst_ (Isac()) false subst rls inf of
   651           NONE => inf
   652         | SOME (norm_inf, _) => norm_inf
   653       in if norm_res = norm_inf then SOME errpatID else NONE
   654       end
   655     else NONE
   656   end;
   657 
   658 (* check if (agreed result, input formula) matches SOME error pattern modulo simplifier rls;
   659    (prog, env) for retrieval of casual substitution for bdv in the pattern. *)
   660 fun check_error_patterns (res, inf) (prog, env) (errpats, rls) =
   661   let
   662     val (_, subst) = get_bdv_subst prog env
   663     fun scan (_, [], _) = NONE
   664       | scan (errpatID, errpat :: errpats, _) =
   665           case check_err_patt (res, inf) (subst: subst) (errpatID, errpat) rls of
   666             NONE => scan (errpatID, errpats, [])
   667           | SOME errpatID => SOME errpatID
   668     fun scans [] = NONE
   669       | scans (group :: groups) =
   670           case scan group of
   671             NONE => scans groups
   672           | SOME errpatID => SOME errpatID
   673   in scans errpats end;
   674 
   675 (*.handle a user-input formula, which may be a CAS-command, too.
   676 CAS-command:
   677    create a calchead, and do 1 step
   678    TOOODO.WN0602 works only for the root-problem !!!
   679 formula, which is no CAS-command:
   680    compare iform with calc-tree.form at pos by equ_nrls and all subsequent pos;
   681    collect all the tacs applied by the way;
   682    if "no derivation found" then check_error_patterns.
   683    ALTERNATIVE: check_error_patterns _within_ compare_step seems too expensive.*)
   684 fun inform (cs as (_, _, ptp as (pt, pos as (p, p_))): calcstate') istr =
   685   case parse (assoc_thy "Isac") istr of
   686 	  SOME f_in =>
   687 	    let
   688 	      val f_in = term_of f_in
   689 	      val f_succ = get_curr_formula (pt, pos);
   690 			in
   691 			  if f_succ = f_in
   692 			  then ("same-formula", cs) (* ctree not cut with replaceFormula *)
   693 			  else
   694 			    case cas_input f_in of
   695 			      SOME (pt, _) => ("ok",([], [], (pt, (p, Met))))
   696 			    | NONE =>
   697 			        let
   698 			          val pos_pred = lev_back' pos
   699 			          (* f_pred ---"step pos cs"---> f_succ in appendFormula *)
   700 			          val f_pred = get_curr_formula (pt, pos_pred)
   701 			          val msg_calcstate' = compare_step ([], [], (pt, pos_pred)) f_in (*<<=====*)
   702 			          (*last step re-calc in compare_step TODO before WN09*)
   703 			        in
   704 			          case msg_calcstate' of
   705 			            ("no derivation found", calcstate') => 
   706 			               let
   707 			                 val pp = par_pblobj pt p
   708 			                 val {errpats, nrls, scr = Prog prog, ...} = get_met (get_obj g_metID pt pp)
   709 			                 val ScrState (env, _, _, _, _, _) = get_istate pt pos
   710 			               in
   711 			                 case check_error_patterns (f_pred, f_in) (prog, env) (errpats, nrls) of
   712 			                   SOME errpatID => ("error pattern #" ^ errpatID ^ "#", calcstate')
   713 			                 | NONE => msg_calcstate'
   714 			               end
   715 			          | _ => msg_calcstate'
   716 			        end
   717 			end
   718     | NONE => ("syntax error in '" ^ istr ^ "'", e_calcstate');
   719 
   720 (* fill-in patterns an forms.
   721   returns thm required by "fun in_fillform *)
   722 fun get_fillform (subs_opt, subst) (thm, form) errpatID ((fillpatID, pat, erpaID): fillpat) =
   723   let
   724     val (form', _, _, rewritten) =
   725       rew_sub (Isac()) 1 subst e_rew_ord e_rls false [] (Trueprop $ pat) form;
   726   in (*the fillpat of the thm must be dedicated to errpatID*)
   727     if errpatID = erpaID andalso rewritten
   728     then SOME (fillpatID, HOLogic.mk_eq (form, form'), thm, subs_opt) else NONE end;
   729 
   730 fun get_fillpats subst form errpatID thm =
   731       let
   732         val thmDeriv = Thm.get_name_hint thm
   733         val (part, thyID) = thy_containing_thm thmDeriv
   734         val theID = [part, thyID, "Theorems", thmID_of_derivation_name thmDeriv]
   735         val Hthm {fillpats, ...} = get_the theID
   736         val some = map (get_fillform subst (thm, form) errpatID) fillpats
   737       in some |> filter is_some |> map the end;
   738 
   739 fun find_fillpatterns (pt, pos as (p, _): pos') errpatID =
   740   let 
   741     val f_curr = get_curr_formula (pt, pos);
   742     val pp = par_pblobj pt p
   743 			    val {errpats, scr = Prog prog, ...} = get_met (get_obj g_metID pt pp)
   744     val ScrState (env, _, _, _, _, _) = get_istate pt pos
   745     val subst = get_bdv_subst prog env
   746     val errpatthms = errpats
   747       |> filter ((curry op = errpatID) o (#1: errpat -> errpatID))
   748       |> map (#3: errpat -> thm list)
   749       |> flat
   750   in map (get_fillpats subst f_curr errpatID) errpatthms |> flat end;
   751 
   752 (* check if an input formula is exactly equal the rewrite from a rule
   753    which is stored at the pos where the input is stored of "ok". *)
   754 fun is_exactly_equal (pt, pos as (p, _)) istr =
   755   case parseNEW (assoc_thy "Isac" |> thy2ctxt) istr of
   756     NONE => ("syntax error in '" ^ istr ^ "'", Tac "")
   757   | SOME ifo => 
   758       let
   759         val p' = lev_on p;
   760         val tac = get_obj g_tac pt p';
   761       in 
   762         case applicable_in pos pt tac of
   763           Notappl msg => (msg, Tac "")
   764         | Appl rew =>
   765             let
   766               val res = case rew of
   767                   Rewrite_Inst' (_, _, _, _, _, _, _, (res, _)) => res
   768                 | Rewrite' (_, _, _, _, _, _, (res, _)) => res
   769             in 
   770               if not (ifo = res)
   771               then ("input does not exactly fill the gaps", Tac "")
   772               else ("ok", tac)
   773             end
   774       end
   775 
   776 (* fetch errpatIDs from an arbitrary tactic *)
   777 fun fetchErrorpatterns tac =
   778   let
   779     val rlsID =
   780       case tac of
   781         Rewrite_Set rlsID => rlsID
   782       | Rewrite_Set_Inst (_, rlsID) => rlsID
   783       | _ => "list_rls" (*WN120806 "e_rls" is appropriate, but raises exn 'get_pbt not found: ?!?*)
   784     val (part, thyID) = thy_containing_rls "Isac" rlsID;
   785     val Hrls {thy_rls = (_, rls), ...} = get_the [part, thyID, "Rulesets", rlsID]
   786   in case rls of
   787         Rls {errpatts, ...} => errpatts
   788       | Seq {errpatts, ...} => errpatts
   789       | Rrls {errpatts, ...} => errpatts
   790       | Erls => []
   791   end
   792 
   793 (*------------------------------------------------------------------(**)
   794 end
   795 open inform; 
   796 (**)------------------------------------------------------------------*)