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