src/Tools/isac/Specify/o-model.sml
author wneuper <Walther.Neuper@jku.at>
Mon, 11 Dec 2023 17:26:30 +0100
changeset 60782 e797d1bdfe37
parent 60778 41abd196342a
permissions -rw-r--r--
eliminate the intermediate *_POS
     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   val empty: T
    23   type single
    24   type variant
    25   type variants
    26   type m_field
    27   type descriptor
    28   type values
    29   type message
    30   val to_string: Proof.context -> T -> string
    31   val single_to_string: Proof.context -> single -> string
    32   val single_empty: single
    33 
    34   val init: theory -> Formalise.model -> Model_Pattern.T -> T * Proof.context
    35   val values : T -> term list
    36   val values': Proof.context -> T -> Formalise.model * term list
    37   val complete_for: Model_Pattern.T -> T -> T * Proof.context -> T * Proof.context
    38   val associate_input: Proof.context -> m_field(*del?*) -> descriptor * values -> T -> message * single * values
    39   val associate_input': Proof.context -> m_field -> values -> T -> message * single * values
    40   val contains: Proof.context -> m_field -> T -> term -> message * single * values
    41   val make_typeless: term -> term
    42   val test_types: Proof.context -> descriptor * values -> string
    43 
    44   val add_enumerate: 'a list -> (int * 'a) list
    45   type preori
    46   val copy_name: Model_Pattern.T -> preori list -> Model_Pattern.single -> preori
    47   val is_copy_named: Model_Pattern.single -> bool
    48   val is_copy_named': string -> bool
    49   val is_copy_named_generating: Model_Pattern.single -> bool
    50 
    51 \<^isac_test>\<open>
    52   val is_copy_named_generating_idstr: string -> bool
    53   val string_of_preoris : preori list -> string
    54   val add_field: theory -> Model_Pattern.T -> descriptor * values -> m_field * descriptor * values
    55 
    56   val add_variants: ('a * ''b * 'c) list -> (int * ('a * ''b * 'c)) list
    57   val get_max_variant: variants -> variant
    58   val partition_variants: ('a * 'a -> bool) -> 'a list -> (int * 'a) list
    59   val collect_variants: ('a * ''b) list -> ('a list * ''b) list
    60 
    61   val replace_0: int -> int list -> int list
    62   val flattup: 'a * ('b * ('c * 'd * 'e)) -> 'a * 'b * 'c * 'd * 'e
    63 \<close>
    64 end
    65 
    66 (**)
    67 structure O_Model(**) : ORIGINAL_MODEL(**) =
    68 struct
    69 (**)
    70 
    71 (** types **)
    72 
    73 type variant =  Model_Def.variant;
    74 type variants =  Model_Def.variants;
    75 type m_field = Model_Def.m_field;
    76 type descriptor = Model_Def.descriptor;
    77 type values = Model_Def.values;
    78 type message = string;
    79 
    80 type T = Model_Def.o_model;
    81 val empty = [] : Model_Def.o_model;
    82 type single = Model_Def.o_model_single
    83 val single_empty = Model_Def.o_model_empty;
    84 
    85 val single_to_string = Model_Def.o_model_single_to_string;
    86 val to_string = Model_Def.o_model_to_string;
    87 
    88 (* O_Model.single without leading integer *)
    89 type preori = (variants * m_field * term * term list);
    90 \<^isac_test>\<open>
    91 fun preori2str (vs, fi, t, ts) = 
    92   "(" ^ (strs2str o (map string_of_int)) vs ^ ", " ^ fi ^ ", " ^
    93     UnparseC.term (ContextC.for_ERROR ()) t ^ ", " ^ 
    94       (strs2str o (map (UnparseC.term (ContextC.for_ERROR ())) ) ) ts ^ ")";
    95 val string_of_preoris = (strs2str' o (map (linefeed o preori2str)));
    96 \<close>
    97 
    98 
    99 (** initialise O_Model **)
   100 
   101 (* compare d and dsc in pbt and transfer field to where_-ori *)
   102 fun add_field thy pbt (d,ts) = 
   103   let fun eq d pt = (d = (fst o snd) pt);
   104   in case filter (eq d) pbt of
   105        [(fi, (_, _))] => (fi, d, ts)
   106      | [] => ("#undef", d, ts)   (*may come with met.model*)
   107      | _ => raise ERROR ("add_field: " ^ UnparseC.term_in_thy thy d ^ " more than once in pbt")
   108   end;
   109 
   110 (*
   111   mark an element with the position within a plateau;
   112   a plateau with length 1 is marked with 0
   113 *)
   114 fun partition_variants _ [] = raise ERROR "partition_variants []"
   115   | partition_variants eq xs =
   116     let
   117       fun mar xx _ [x] n = xx @ [(if n = 1 then 0 else n, x)]
   118         | mar _ _ [] _ = raise ERROR "partition_variants []"
   119         | mar xx eq (x :: x' :: xs) n = 
   120         if eq (x, x') then mar (xx @ [(n, x)]) eq (x' :: xs) (n + 1)
   121         else mar (xx @ [(if n = 1 then 0 else n, x)]) eq (x' :: xs) 1;
   122     in mar [] eq xs 1 end;
   123 
   124 (*
   125   assumes equal descriptions to be in adjacent 'plateaus',
   126   items at a certain position within the plateaus form a variant;
   127   length = 1 ... marked with 0: covers all variants
   128 *)
   129 fun add_variants fdts = 
   130   let 
   131     fun eq (a, b) = curry op= (snd3 a) (snd3 b);
   132   in partition_variants eq fdts end;
   133 
   134 fun get_max_variant [] = raise ERROR "get_max_variant of []"
   135   | get_max_variant (y :: ys) =
   136   let fun mx x [] = x
   137 	| mx x (y :: ys) = if x < y then mx y ys else mx x ys;
   138 in mx y ys end;
   139 
   140 fun collect_variants (((v,x) :: vxs)) =
   141     let
   142       fun col xs (vs, x) [] = xs @ [(vs, x)]
   143         | col xs (vs, x) ((v', x') :: vxs') = 
   144         if x = x' then col xs (vs @ [v'], x') vxs'
   145         else col (xs @ [(vs, x)]) ([v'], x') vxs';
   146     in col [] ([v], x) vxs end
   147   | collect_variants _ = raise ERROR "collect_variants: called with []";
   148 
   149 fun replace_0 vm [0] = intsto vm
   150   | replace_0 _ vs = vs;
   151 
   152 fun add_enumerate [] = raise ERROR "O_Model.add_enumerate []"
   153   | add_enumerate xs =
   154     let
   155       fun add _ [] = []
   156         | add n (x :: xs) = (n, x) :: add (n + 1) xs;
   157     in add 1 xs end;
   158 
   159 fun flattup (a, (b, (c, d, e))) = (a, b, c, d, e);
   160 
   161 fun init _ []  _ = ([], ContextC.empty)
   162   | init thy fmz pbt =
   163     let
   164       val (ts, ctxt) = ContextC.init_while_parsing fmz thy
   165       val model =
   166         (map (fn t => t
   167           |> Input_Descript.split
   168           |> add_field thy pbt) ts)
   169         |> add_variants;
   170       val maxv = model |> map fst |> get_max_variant;
   171       val maxv = if maxv = 0 then 1 else maxv;
   172       val model' = model
   173         |> collect_variants
   174         |> map (replace_0 maxv |> apfst)
   175         |> add_enumerate
   176         |> map flattup
   177     in (model', ctxt) end
   178 
   179 (** get the values **)
   180 
   181 fun mkval _(*dsc*) [] = raise ERROR "mkval called with []"
   182   | mkval _ [t] = t
   183   | mkval _ ts = TermC.list2isalist ((type_of o hd) ts) ts;
   184 fun mkval' x = mkval TermC.empty x;
   185 (* from an O_Model create values for ctxt *)
   186 fun values oris =
   187   ((map (mkval' o (#5))) o (filter ((member_swap op= 1) o (#2)))) oris
   188 
   189 (* from an O_Model create (Formalise.model, values)
   190   e.g. Subproblem ["BOOL (1+x=2)", "REAL x"] 
   191                  --match_ags--> O_Model.T
   192        O_Model.T --values'--> (["equality (1+x=2)", "boundVariable x", "solutions L"], values)
   193 *)
   194 fun values' ctxt oris =
   195   let
   196     fun ori2fmz_vals (_, _, _, dsc, ts) = 
   197       case \<^try>\<open>(((UnparseC.term ctxt) o Input_Descript.join') (dsc, ts), last_elem ts)\<close> of
   198         SOME x => x
   199       | NONE => raise ERROR ("O_Model.values' called with " ^ UnparseC.terms ctxt ts)
   200   in (split_list o (map ori2fmz_vals)) oris end
   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, _)) => (member op = (map #4 o_model) descriptor))
   209     val add = (root_model
   210       |> filter
   211         (fn (_, _, _, descriptor, _) => (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_enumerate                                  (* 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' str =
   231   case (rev o Symbol.explode) str of
   232 	  "'" :: _ :: "'" :: _ => true
   233   | _ => false
   234 fun is_copy_named (_, (_, t)) = (is_copy_named' 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' 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 copy_name pbt oris (p as (field, (dsc, t))) =
   251   case \<^try>\<open>
   252     if is_copy_named_generating p
   253     then (*WN051014 kept strange old code ...*)
   254       let fun sel (_,_,d,ts) = Input_Descript.join'''' (d, ts) 
   255         val cy' = (implode o (drop_last_n 3) o Symbol.explode o TermC.free2str) t
   256         val ext = (last_elem o drop_last o Symbol.explode o TermC.free2str) t
   257         val vars' = map (Term.term_name o snd o snd) pbt (*cpy-nam filtered_out*)
   258         val vals = map sel oris
   259         val cy_ext = (Term.term_name o the) (assoc (vars' ~~ vals, cy')) ^ "_" ^ ext
   260       in ([1], field, dsc, [TermC.mk_free (type_of t) cy_ext]) end
   261     else ([1], field, dsc, [t])
   262 	\<close> of
   263     SOME x => x
   264   | NONE => raise ERROR ("copy_name: for " ^ UnparseC.term (ContextC.for_ERROR ()) t)
   265 
   266 
   267 (** tools for I_Model **)
   268 
   269 (* to an input (_ $ values) find the according O_Model.single and insert the values *)
   270 fun associate_input ctxt m_field (descript, vals) [] =
   271     ("associate_input: input ('" ^
   272         (UnparseC.term ctxt (Input_Descript.join (descript, vals))) ^
   273           "') not found in oris (typed)", (0, [], m_field, descript, vals), [])
   274   | associate_input ctxt sel (d, ts) ((id, vat, sel', d', ts') :: oris) =
   275     if sel = sel' andalso d = d' andalso (inter op = ts ts') <> []
   276     then ("", (id, vat, sel, d, inter op = ts ts'), ts')
   277     else associate_input ctxt sel (d, ts) oris
   278 
   279 (* to an input (_ $ values) find the according O_Model.single and insert the values *)
   280 fun associate_input' ctxt _ vals [] = 
   281     ("associate_input': input (_, '" ^ strs2str (map (UnparseC.term ctxt) vals) ^
   282       "') not found in oris (typed)", single_empty, [])
   283   | associate_input' ctxt m_field vals ((id, vat, m_field', descr, vals') :: oris) =
   284     if m_field = m_field' andalso (inter op = vals vals') <> [] 
   285     then
   286       if m_field = m_field' 
   287       then ("", (id, vat, m_field, descr, inter op = vals vals'), vals')
   288       else ((strs2str' o map (UnparseC.term ctxt)) vals ^
   289         " not for " ^ m_field, single_empty, [])
   290     else associate_input' ctxt m_field vals oris
   291 
   292 fun test_types ctxt (d,ts) =
   293   let 
   294     val opt = (try Input_Descript.join) (d, ts)
   295     val msg = case opt of 
   296       SOME _ => "" 
   297     | NONE => (UnparseC.term ctxt d ^ " " ^
   298 	    (strs2str' o map (UnparseC.term ctxt)) ts ^ " is illtyped")
   299   in msg end
   300 
   301 (* make a term 'typeless' for comparing with another 'typeless' term;
   302    'type-less' usually is illtyped                                  *)
   303 fun make_typeless (Const (s, _)) = (Const (s, TermC.typ_empty)) 
   304   | make_typeless (Free (s, _)) = (Free (s, TermC.typ_empty))
   305   | make_typeless (Var (n, _)) = (Var (n, TermC.typ_empty))
   306   | make_typeless (Bound i) = (Bound i)
   307   | make_typeless (Abs (s, _,t)) = Abs(s, TermC.typ_empty, make_typeless t)
   308   | make_typeless (t1 $ t2) = (make_typeless t1) $ (make_typeless t2)
   309 
   310 (* is the term t input (or taken from fmz) known in O_Model ?
   311    give feedback on all(?) strange input;
   312    return _all_ terms already input to this item (e.g. valuesFor a,b) *)
   313 fun contains ctxt sel ori t =
   314   let
   315     val ots = ((distinct op =) o flat o (map #5)) ori
   316     val oids = ((map (fst o dest_Free)) o (distinct op =) o flat o (map TermC.vars)) ots
   317     val (d, ts) = Input_Descript.split t
   318     val ids = map (fst o dest_Free) (((distinct op =) o (flat o (map TermC.vars))) ts)
   319   in
   320     if (subtract op = oids ids) <> []
   321     then ("identifiers " ^ strs2str' (subtract op = oids ids) ^ " not in example", single_empty, [])
   322     else 
   323 	    if d = TermC.empty
   324 	    then 
   325 	      if not (subset op = (map make_typeless ts, map make_typeless ots))
   326 	      then ("terms '" ^ (strs2str' o (map (UnparseC.term ctxt))) ts ^
   327 		      "' not in example (make_typeless)", single_empty, [])
   328 	      else 
   329           (case associate_input' ctxt sel ts(*..values*) ori of
   330 		         ("", ori_ as (_, _, _, d, ts), all) =>
   331 		            (case test_types ctxt (d,ts) of
   332 		              "" => ("", ori_, all)
   333 		            | msg => (msg, single_empty, []))
   334 		       | (msg, _, _) => (msg, single_empty, []))
   335 	    else 
   336 	      if member op = (map #4 ori) d
   337 	      then associate_input ctxt sel (d, ts) ori
   338 	      else (UnparseC.term ctxt d ^ " not in example", (0, [], sel, d, ts), [])
   339   end
   340 
   341 (**)end(**);