src/Tools/isac/Specify/o-model.sml
author Walther Neuper <walther.neuper@jku.at>
Sat, 30 May 2020 15:20:22 +0200
changeset 60011 25e6810ca0e7
parent 60010 b8307d4a83ad
child 60012 a2f52385a7bb
permissions -rw-r--r--
cleanup code after resolve hacks
     1 (* Title:  Specify/o-model.sml
     2    Author: Walther Neuper 110226
     3    (c) due to copyright terms
     4 
     5 An \<open>O_Model\<close> holds \<open>O\<close>riginal data, \<open>descriptor\<close> and \<open>values\<close> parsed from \<open>Formalise.model\<close>
     6 selected with respect to a \<open>Model_Pattern\<close> and combined with respective \<open>m_field\<close>s.
     7 \<open>complete_for\<close> a \<open>Model_Pattern\<close> is done by \<open>Tactic.Model_Problem\<close>
     8 (with defaults from \<open>Formalise\<close>refs), by \<open>Tactic.Specify_Problem\<close> and \<open>Tactic.Specify_Method\<close>
     9 
    10 \<open>O_Model\<close> serves efficiency of student's interactive modelling via \<open>I_Model\<close>.
    11 
    12 \<open>O_Model\<close> marks elements with  \<open>m_field\<close> \<open>#undef\<close>, which are not required by the \<open>Model_Pattern\<close>
    13 of the \<open>Problem\<close> or the \<open>Method\<close> .. TODO redes: \<open>m_field\<close> probably different in root..Subproblem
    14 
    15 TODO: revise with an example with more than 1 variant.
    16     + consider: drop m_field ?
    17 *)
    18 
    19 signature ORIGINAL_MODEL =
    20 sig
    21   type T
    22   type single
    23   type variants
    24   type m_field
    25   type descriptor
    26   type values
    27   type message
    28   val to_string: T -> string
    29   val single_to_string: single -> string
    30   val single_empty: single
    31 
    32 (*val init: theory -> Formalise.model -> Model_Pattern.T -> T ..TODO*)
    33   val init: Formalise.model -> theory -> Model_Pattern.T -> T
    34   val values : T -> term list
    35   val values': T -> Formalise.model * term list
    36   val complete_for: Model_Pattern.T -> T -> T * Proof.context -> T * Proof.context
    37 (*/------- rename -------\*)
    38 (*val seek_oridts: Proof.context -> ?/////? -> descriptor * values -> T -> message * single * values*)
    39   val seek_oridts: Proof.context -> m_field -> descriptor * values -> T -> message * single * values
    40 (*val single_for_values:!!! values -> Proof.context -> m_field -> T -> message * single * values*)
    41   val seek_orits: Proof.context -> m_field -> values -> T -> message * single * values
    42 (*val ?contains:!!! term -> Proof.context -> m_field -> T -> message * single * values*)
    43   val is_known: Proof.context -> m_field -> T -> term -> message * single * values
    44 (*val typeless: term -> term*)
    45   val typeless: term -> term
    46 (*val test_types: Proof.context -> descriptor * values -> string*)
    47   val test_types: Proof.context -> descriptor * values -> string
    48 
    49 (*put add_id into a new auxiliary fun, see ONLY call..*)
    50   val add_id: 'a list -> (int * 'a) list
    51   type preori
    52 (* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
    53 (*val cpy_nam: Model_Pattern.T -> preori list -> Model_Pattern.single -> preori*)
    54   val cpy_nam: Model_Pattern.T -> preori list -> Model_Pattern.single -> preori
    55   val is_copy_named: Model_Pattern.single -> bool
    56   val is_copy_named_idstr: string -> bool
    57   val is_copy_named_generating_idstr: string -> bool
    58   val is_copy_named_generating: Model_Pattern.single -> bool
    59 
    60   val preoris2str : preori list -> string
    61 (*val getr_ct: theory -> single -> m_field * UnparseC.term_as_string*)
    62   val getr_ct: theory -> single -> m_field * UnparseC.term_as_string
    63 
    64 (*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
    65   val add_field: theory -> Model_Pattern.T -> descriptor * values -> m_field * descriptor * values
    66   val add_variants: ('a * ''b * 'c) list -> (int * ('a * ''b * 'c)) list
    67 (*val max: variants -> int*)
    68   val max: variants -> int
    69 (*val coll_variants: ('a * ''b) list -> ('a list * ''b) list*)
    70   val coll_variants: ('a * ''b) list -> ('a list * ''b) list
    71 (*val replace_0: int -> int list -> int list*)
    72   val replace_0: int -> int list -> int list
    73   val flattup: 'a * ('b * ('c * 'd * 'e)) -> 'a * 'b * 'c * 'd * 'e
    74 (*val mark: ('a * 'a -> bool) -> 'a list -> (int * 'a) list*)
    75   val mark: ('a * 'a -> bool) -> 'a list -> (int * 'a) list
    76 (*\------- rename -------/*)
    77 ( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
    78 end
    79 
    80 (**)
    81 structure O_Model(**) : ORIGINAL_MODEL(**) =
    82 struct
    83 (**)
    84 
    85 (** types **)
    86 
    87 type variants =  Model_Def.variants;
    88 type m_field = Model_Def.m_field;
    89 type descriptor = Model_Def.descriptor;
    90 type values = Model_Def.values;
    91 type message = string;
    92 
    93 type T = Model_Def.o_model;
    94 type single = Model_Def.o_model_single
    95 val single_empty = Model_Def.o_model_empty;
    96 val single_to_string = Model_Def.o_model_single_to_string;
    97 val to_string = Model_Def.o_model_to_string;
    98 
    99 (* O_Model.single without leading integer *)
   100 type preori = (variants * m_field * term * term list);
   101 fun preori2str (vs, fi, t, ts) = 
   102   "(" ^ (strs2str o (map string_of_int)) vs ^ ", " ^ fi ^ ", " ^
   103   UnparseC.term t ^ ", " ^ (strs2str o (map UnparseC.term)) ts ^ ")";
   104 val preoris2str = (strs2str' o (map (linefeed o preori2str)));
   105 
   106 (* get the first term in ts from ori *)
   107 fun getr_ct thy (_, _, fd, d, ts) =
   108   (fd, ((UnparseC.term_in_thy thy) o Input_Descript.join) (d,[hd ts]))
   109 
   110 
   111 (** initialise O_Model **)
   112 
   113 (* compare d and dsc in pbt and transfer field to pre-ori *)
   114 fun add_field (_: theory) pbt (d,ts) = 
   115   let fun eq d pt = (d = (fst o snd) pt);
   116   in case filter (eq d) pbt of
   117        [(fi, (_, _))] => (fi, d, ts)
   118      | [] => ("#undef", d, ts)   (*may come with met.ppc*)
   119      | _ => raise ERROR ("add_field: " ^ UnparseC.term d ^ " more than once in pbt")
   120   end;
   121 
   122 (*
   123   mark an element with the position within a plateau;
   124   a plateau with length 1 is marked with 0
   125 *)
   126 fun mark _ [] = raise ERROR "mark []"
   127   | mark eq xs =
   128     let
   129       fun mar xx _ [x] n = xx @ [(if n = 1 then 0 else n, x)]
   130         | mar _ _ [] _ = raise ERROR "mark []"
   131         | mar xx eq (x:: x' :: xs) n = 
   132         if eq(x, x') then mar (xx @ [(n, x)]) eq (x' :: xs) (n + 1)
   133         else mar (xx @ [(if n = 1 then 0 else n, x)]) eq (x' :: xs) 1;
   134     in mar [] eq xs 1 end;
   135 
   136 (*
   137   assumes equal descriptions to be in adjacent 'plateaus',
   138   items at a certain position within the plateaus form a variant;
   139   length = 1 ... marked with 0: covers all variants
   140 *)
   141 fun add_variants fdts = 
   142   let 
   143     fun eq (a, b) = curry op= (snd3 a) (snd3 b);
   144   in mark eq fdts end;
   145 
   146 fun max [] = raise ERROR "max of []"
   147   | max (y :: ys) =
   148   let fun mx x [] = x
   149 	| mx x (y :: ys) = if x < y then mx y ys else mx x ys;
   150 in mx y ys end;
   151 
   152 fun coll_variants (((v,x) :: vxs)) =
   153     let
   154       fun col xs (vs, x) [] = xs @ [(vs, x)]
   155         | col xs (vs, x) ((v', x') :: vxs') = 
   156         if x = x' then col xs (vs @ [v'], x') vxs'
   157         else col (xs @ [(vs, x)]) ([v'], x') vxs';
   158     in col [] ([v], x) vxs end
   159   | coll_variants _ = raise ERROR "coll_variants: called with []";
   160 
   161 fun replace_0 vm [0] = intsto vm
   162   | replace_0 _ vs = vs;
   163 
   164 fun add_id [] = raise ERROR "O_Model.add_id []"
   165   | add_id xs =
   166     let
   167       fun add _ [] = []
   168         | add n (x :: xs) = (n, x) :: add (n + 1) xs;
   169     in add 1 xs end;
   170 
   171 fun flattup (a, (b, (c, d, e))) = (a, b, c, d, e);
   172 
   173 fun init [] _ _ = []
   174   | init fmz thy pbt =
   175     let
   176       val model =
   177         (map (fn str => str
   178           |> TermC.parseNEW'' thy
   179           |> Input_Descript.split
   180           |> add_field thy pbt) fmz)
   181         |> add_variants;
   182       val maxv = model |> map fst |> max;
   183       val maxv = if maxv = 0 then 1 else maxv;
   184       val model' = model
   185         |> coll_variants
   186         |> map (replace_0 maxv |> apfst)
   187         |> add_id
   188         |> map flattup;
   189     in model' end;
   190 
   191 
   192 (** get the values **)
   193 
   194 fun mkval _(*dsc*) [] = raise ERROR "mkval called with []"
   195   | mkval _ [t] = t
   196   | mkval _ ts = TermC.list2isalist ((type_of o hd) ts) ts;
   197 fun mkval' x = mkval TermC.empty x;
   198 (*TODO: unify with values'*)
   199 fun values (oris:T) =
   200   ((map (mkval' o (#5))) o (filter ((member_swap op= 1) o (#2)))) oris
   201 
   202 
   203 (** complete wrt. Model_Pattern.T by use of root's O_Model.T **)
   204 
   205 fun complete_for m_patt root_model (o_model, ctxt) =
   206   let
   207     val  missing = m_patt |> filter_out
   208       (fn (_, (descriptor, _)) => (Library.member op = (map #4 o_model) descriptor))
   209     val add = (root_model
   210       |> filter
   211         (fn (_, _, _, descriptor, _) => (Library.member op = (map (fst o snd) missing)) descriptor))
   212   in
   213     ((o_model @ add)
   214       |> map (fn (a, b, _, descr, e) =>
   215                case Model_Pattern.get_field descr m_patt of
   216                  SOME m_field => (a, b, m_field, descr, e)
   217                | NONE => (a, b, "#undef", descr, e))
   218       |> map (fn (_, b, c, d, e) => (b, c, d, e))      (* for correct enumeration *)
   219       |> add_id                                        (* for correct enumeration *)
   220       |> map (fn (a, (b, c, d, e)) => (a, b, c, d, e)), (* for correct enumeration *)
   221     ctxt |> ContextC.add_constraints (add |> values |> TermC.vars'))
   222   end
   223 
   224 
   225 (** ? ? ? **)
   226 
   227 (* make oris from args of the stac SubProblem and from pbt.
   228    can this formal argument (of a model-pattern) be omitted in the arg-list
   229    of a SubProblem ? see calcelems.sml 'type met '                        *)
   230 fun is_copy_named_idstr str =
   231   case (rev o Symbol.explode) str of
   232 	  "'" :: _ :: "'" :: _ => true
   233   | _ => false
   234 fun is_copy_named (_, (_, t)) = (is_copy_named_idstr o TermC.free2str) t
   235 
   236 (* should this formal argument (of a model-pattern) create a new identifier? *)
   237 fun is_copy_named_generating_idstr str =
   238   if is_copy_named_idstr str
   239   then
   240     case (rev o Symbol.explode) str of
   241 	    "'" :: "'" :: "'" :: _ => false
   242     | _ => true
   243   else false
   244 fun is_copy_named_generating (_, (_, t)) = (is_copy_named_generating_idstr o TermC.free2str) t
   245 
   246 (* generate a new variable "x_i" name from a related given one "x"
   247    by use of oris relating "v_v'i'" (is_copy_named!) to "v_v"
   248    e.g. (v_v, x) & (v_v'i', ?) --> (v_v'i', x_i),
   249    but leave is_copy_named_generating as is, e.t. ss''' *)
   250 fun cpy_nam pbt oris (p as (field, (dsc, t))) =
   251   (if is_copy_named_generating p
   252    then (*WN051014 kept strange old code ...*)
   253      let fun sel (_,_,d,ts) = Input_Descript.join'''' (d, ts) 
   254        val cy' = (implode o (drop_last_n 3) o Symbol.explode o TermC.free2str) t
   255        val ext = (last_elem o drop_last o Symbol.explode o TermC.free2str) t
   256        val vars' = map (Term.term_name o snd o snd) pbt (*cpy-nam filtered_out*)
   257        val vals = map sel oris
   258        val cy_ext = (Term.term_name o the) (assoc (vars' ~~ vals, cy')) ^ "_" ^ ext
   259      in ([1], field, dsc, [TermC.mk_free (type_of t) cy_ext]) end
   260    else ([1], field, dsc, [t])
   261 	) handle _ => raise ERROR ("cpy_nam: for "^ UnparseC.term t)
   262 
   263 (* ["BOOL (1+x=2)", "REAL x"] --match_ags--> oris 
   264    --values'--> ["equality (1+x=2)", "boundVariable x", "solutions L"] *)
   265 (*TODO: unify with values*)
   266 fun values' oris =
   267   let fun ori2fmz_vals (_, _, _, dsc, ts) = 
   268 	  ((UnparseC.term o Input_Descript.join') (dsc, ts), last_elem ts) 
   269 	  handle _ => raise ERROR ("ori2fmz_env called with " ^ UnparseC.terms ts)
   270   in (split_list o (map ori2fmz_vals)) oris end
   271 
   272 
   273 (** tools for I_Model **)
   274 
   275 (** )
   276 fun seek_oridts ctxt sel (d, ts) [] =
   277     ("seek_oridts: input ('" ^
   278         (UnparseC.term_in_ctxt ctxt (Input_Descript.join (d, ts))) ^ "') not found in oris (typed)",
   279       (0, [], sel, d, ts),
   280       [])
   281   | seek_oridts ctxt sel (d, ts) ((id, vat, sel', d', ts') :: oris) =
   282     if sel = sel' andalso d = d' andalso (inter op = ts ts') <> []
   283     then ("", (id, vat, sel, d, inter op = ts ts'), ts')
   284     else seek_oridts ctxt sel (d, ts) oris
   285 ( **)
   286 fun seek_oridts ctxt m_field (descript, vals) [] =
   287     ("seek_oridts: input ('" ^ UnparseC.term_in_ctxt ctxt (Input_Descript.join (descript, vals)) ^
   288       "') not found in oris (typed)", (0, [], m_field, descript, vals), [])
   289   | seek_oridts ctxt m_field (descript, vals) ((id, vat, m_field', descript', vals') :: oris) =
   290     if (inter op = vals vals') <> [] andalso descript = descript' then
   291       if m_field = "#undef" then (* m_field may change from root- to sub-Model_Pattern *)
   292         ("", (id, vat, m_field, descript, inter op = vals vals'), vals')
   293       else if m_field = m_field' then
   294         ("", (id, vat, m_field, descript, inter op = vals vals'), vals')
   295       else 
   296         (((strs2str' o map (UnparseC.term_in_ctxt ctxt)) vals) ^
   297           " not for " ^ m_field, single_empty, [])
   298     else seek_oridts ctxt m_field (descript, vals) oris
   299 
   300 (* to an input (_,ts) find the according ori and insert the ts *)
   301 fun seek_orits ctxt _ values [] = 
   302     ("seek_orits: input (_, '" ^ strs2str (map (UnparseC.term_in_ctxt ctxt) values) ^
   303       "') not found in oris (typed)", single_empty, [])
   304   | seek_orits ctxt sel values ((id, vat, sel', d, values') :: oris) =
   305     if (inter op = values values') <> [] then
   306       if sel = "#undef" then (* indicates that m_field changed from root- to sub-Model_Pattern *)
   307         ("", (id, vat, sel, d, inter op = values values'), values')
   308       else if sel = sel' then
   309         ("", (id, vat, sel, d, inter op = values values'), values')
   310       else 
   311         (((strs2str' o map (UnparseC.term_in_ctxt ctxt)) values) ^
   312           " not for " ^ sel, single_empty, [])
   313     else seek_orits ctxt sel values oris
   314 
   315 fun test_types ctxt (d,ts) =
   316   let 
   317     val opt = (try Input_Descript.join) (d, ts)
   318     val msg = case opt of 
   319       SOME _ => "" 
   320     | NONE => (UnparseC.term_in_ctxt ctxt d ^ " " ^
   321 	    (strs2str' o map (UnparseC.term_in_ctxt ctxt)) ts ^ " is illtyped")
   322   in msg end
   323 
   324 (* make a term 'typeless' for comparing with another 'typeless' term;
   325    'type-less' usually is illtyped                                  *)
   326 fun typeless (Const (s, _)) = (Const (s, TermC.typ_empty)) 
   327   | typeless (Free (s, _)) = (Free (s, TermC.typ_empty))
   328   | typeless (Var (n, _)) = (Var (n, TermC.typ_empty))
   329   | typeless (Bound i) = (Bound i)
   330   | typeless (Abs (s, _,t)) = Abs(s, TermC.typ_empty, typeless t)
   331   | typeless (t1 $ t2) = (typeless t1) $ (typeless t2)
   332 
   333 (* is the term t input (or taken from fmz) known in O_Model ?
   334    give feedback on all(?) strange input;
   335    return _all_ terms already input to this item (e.g. valuesFor a,b) *)
   336 fun is_known ctxt sel ori t =
   337   let
   338     val ots = (distinct o flat o (map #5)) ori
   339     val oids = ((map (fst o dest_Free)) o distinct o flat o (map TermC.vars)) ots
   340     val (d, ts) = Input_Descript.split t
   341     val ids = map (fst o dest_Free) ((distinct o (flat o (map TermC.vars))) ts)
   342   in
   343     if (subtract op = oids ids) <> []
   344     then ("identifiers " ^ strs2str' (subtract op = oids ids) ^ " not in example", single_empty, [])
   345     else 
   346 	    if d = TermC.empty
   347 	    then 
   348 	      if not (subset op = (map typeless ts, map typeless ots))
   349 	      then ("terms '" ^ (strs2str' o (map (UnparseC.term_in_ctxt ctxt))) ts ^
   350 		      "' not in example (typeless)", single_empty, [])
   351 	      else 
   352           (case seek_orits ctxt sel ts(*..values*) ori of
   353 		         ("", ori_ as (_, _, _, d, ts), all) =>
   354 		            (case test_types ctxt (d,ts) of
   355 		              "" => ("", ori_, all)
   356 		            | msg => (msg, single_empty, []))
   357 		       | (msg, _, _) => (msg, single_empty, []))
   358 	    else 
   359 	      if member op = (map #4 ori) d
   360 	      then seek_oridts ctxt sel (d, ts) ori
   361 	      else (UnparseC.term_in_ctxt ctxt d ^ " not in example", (0, [], sel, d, ts), [])
   362   end
   363 
   364 (**)end(**);