File size: 82,717 Bytes
5697766 | 1 2 3 4 5 | {"text": "program change; /* sample2a.mpl */ { compute change program. What is change? }\r\n { no 5, 50, 500, & 5000 yen used }\r\n var n, count : integer;\r\nbegin\r\n writeln('please input change'); readln(n); count := 0;\r\nwhile n>0 do begin\r\n while n>=10 do begin\r\n while n>= 100 do begin\r\n while n>=1000 do begin \r\n while n >=10000 do begin\r\n count := count +1; n := n-10000;\r\n end;\r\n if count >0 then writeln('10000 yen : ', count);\r\n count := 0;\r\n if n < 1000 then break;\r\n count := count +1; n := n-1000;\r\n end;\r\n if count >0 then writeln(' 1000 yen : ', count);\r\n count := 0;\r\n if n < 100 then break;\r\n count := count +1; n := n-100;\r\n end;\r\n if count >0 then writeln(' 100 yen : ', count);\r\n count := 0;\r\n if n < 10 then break;\r\n count := count +1; n := n-10;\r\n end;\r\n if count >0 then writeln(' 10 yen : ', count);\r\n count := 0;\r\n if n < 1 then break;\r\n count := count +1; n := n-1;\r\n end;\r\n if count > 0 then writeln(' 1 yen : ', count);\r\n/* if n !=0 then break; */\r\nend.", "meta": {"hexsha": "47b6836a5196d93f283fd45bc1ca468cb7654280", "size": 1286, "ext": "mpl", "lang": "Maple", "max_stars_repo_path": "data/sample2a.mpl", "max_stars_repo_name": "naru380/SoftwareExperience5", "max_stars_repo_head_hexsha": "89020bf73d9fc6b58f8d564c7aaed52a0e02f371", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/sample2a.mpl", "max_issues_repo_name": "naru380/SoftwareExperience5", "max_issues_repo_head_hexsha": "89020bf73d9fc6b58f8d564c7aaed52a0e02f371", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/sample2a.mpl", "max_forks_repo_name": "naru380/SoftwareExperience5", "max_forks_repo_head_hexsha": "89020bf73d9fc6b58f8d564c7aaed52a0e02f371", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7428571429, "max_line_length": 80, "alphanum_fraction": 0.432348367, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.06560484385324576, "lm_q1q2_score": 0.03203375590451591}}
{"text": "# Teach Maple (through depends and eval) about our new binding forms.\n# forall bind from 1st arg to 2nd arg.\n# Ints,Sums,ints,sums bind from 2nd arg to 1st arg, and also from each element\n# of the 4th arg to the other elements on the left and to the 3rd arg.\n\n`depends/forall` := proc(bvar, pred, x, $)\n depends(pred, x minus convert(bvar, 'set'))\nend proc:\n\n`depends/Ints` := proc(body, bvar, rng, loops, x, y, $)\n local xx, i;\n if nargs = 5 then\n xx := x; # y is ununsed and x lists the variables to look for\n else\n xx := y; # x is some KB and y lists the variables to look for\n if depends(x, y) then return true end if;\n end if;\n # don't remove bvar from xx!\n if depends(body, xx minus {bvar}) then return true end if;\n for i from nops(loops) to 1 by -1 do\n if depends(op([i,2],loops), xx) then return true end if;\n xx := xx minus {op([i,1],loops)};\n end do;\n depends(rng, xx)\nend proc:\n`depends/Sums` := eval(`depends/Ints`):\n`depends/ints` := eval(`depends/Ints`):\n`depends/sums` := eval(`depends/Ints`):\n\n`eval/forall` := proc(e, eqs, $)\n local bvar, pred;\n bvar, pred := op(e);\n eval(op(0,e), eqs)(BindingTools:-generic_evalat(bvar, pred, eqs))\nend proc:\n\n`eval/Ints` := proc(e, eqs, $)\n local body, bvar, rng, loops, n, i;\n body, bvar, rng, loops := op(1..4, e);\n bvar, body := BindingTools:-generic_evalat(bvar, body, eqs);\n eval(op(0,e), eqs)(body, bvar,\n BindingTools:-generic_evalatstar(rng, loops, eqs),\n op(5..-1,e))\nend proc:\n`eval/Sums` := eval(`eval/Ints`):\n`eval/ints` := eval(`eval/Ints`):\n`eval/sums` := eval(`eval/Ints`):\n\n`eval/Int` := proc(e, eqs, $)\n local body, bound, bvar;\n body, bound := op(1..2, e);\n if bound :: name then\n bound, body := BindingTools:-generic_evalat(bound, body, eqs);\n elif bound :: `=` then\n bvar := lhs(bound);\n bvar, body := BindingTools:-generic_evalat(bvar, body, eqs);\n bound := bvar = eval(rhs(bound), eqs);\n else\n body, bound := BindingTools:-generic_evalatstar(body, bound, eqs);\n end if;\n eval(op(0,e), eqs)(body, bound, op(eval([op(3..-1,e)], eqs)))\nend proc:\n`eval/Sum` := eval(`eval/Int`):\n`eval/Product` := eval(`eval/Int`):\n`eval/int` := eval(`eval/Int`):\n`eval/sum` := eval(`eval/Int`):\n`eval/product` := eval(`eval/Int`):\n\n#############################################################################\n\nLoop := module ()\n option package;\n local intssums, enter_piecewise, wrap,\n t_peel, do_peel, do_split, do_graft, do_rebase_lower, do_rebase_upper,\n Binder, Stmt, t_binder, t_stmt, t_exp,\n ModuleLoad;\n export\n # These first few are smart constructors (for themselves):\n ints, sums,\n # while these are \"proper functions\"\n mk_HArray, genLoop, unproducts, unproduct,\n peel, split, graft, rebase_lower, rebase_upper, Print;\n # these names are not assigned (and should not be). But they are\n # used as global names, so document that here.\n global Ints, Sums, csgn, sum;\n uses Hakaru, KB;\n\n t_binder := 'Binder(identical(product, Product, sum, Sum), t_kb)';\n t_stmt := 'Stmt(anything, list, list)';\n t_exp := '{Stmt(identical(exp), [], []),\n Stmt(identical(`^`), [anything], [])}';\n\n ints := proc() intssums('ints', 'int', _passed) end proc;\n sums := proc() intssums('sums', 'sum', _passed) end proc;\n\n Print := proc(kind::identical(Ints,Sums,ints,sums),e,v::name,r0::range,rs::list(name=range),$)\n local k;\n k := StringTools[Capitalize](StringTools[Chop](convert(kind,string)));\n k := parse(cat(\"`print/\",eval(k),\"`\"));\n eval(k)(e,v[op(rs)]=r0);\n end proc;\n\n intssums := proc(makes::name, make::name,\n e::anything, x::name, rr::range, ll::list(name=range),\n kb::t_kb:=empty, $)\n local t, r, l, kb2, w0, pp, i;\n t := `if`(make=int, HReal(open_bounds(rr)), HInt(closed_bounds(rr)));\n r, l, kb2 := genLoop(rr, ll, kb, 'Integrand'(x,e));\n w0, pp := unproducts(e, x, l, kb2);\n if depends(w0, x) then\n 'makes(e, x, rr, ll)'\n else\n pp := 'make'(pp, x=r);\n for i in l do pp := 'product'(pp, i) end do;\n NewSLO:-simplify_factor_assuming(w0 * pp, kb);\n end if\n end proc;\n\n mk_HArray := proc(t::t_type, loops::list(name=range), $)\n local res, i;\n res := t;\n for i in loops do res := HArray(res) end do;\n res\n end proc;\n\n genLoop := proc(e, loops::list(name=range), kb::t_kb)\n local kb1, rng, ind, do_subst, i;\n kb1 := kb;\n rng := table();\n ind := table();\n do_subst := e -> foldl(((e,eq) -> eval(e, op([lhs(eq),1],loops)=rhs(eq))),\n e, entries(ind, 'pairs'));\n for i from nops(loops) to 1 by -1 do\n rng[i] := do_subst(op([i,2],loops));\n ind[i], kb1 := genType(op([i,1],loops), HInt(closed_bounds(rng[i])),\n kb1, _rest);\n end do;\n do_subst(e), zip(`=`, [entries(ind, 'nolist')],\n [entries(rng, 'nolist')]), kb1\n end proc;\n\n unproducts := proc(w, x::name, loops::list(name=range), kb::t_kb, $)\n local w0, pp, j, w1, w2, loop;\n w0 := 1;\n pp := w;\n for j from nops(loops) to 1 by -1 do\n w1, pp := op(unproduct(pp, x, op(j,loops), [], `*`, kb, kb));\n # separate out each of the factors in w1, as they might have different\n # variable dependencies, which can be exploited by other routines\n w2 := convert(w1, 'list', '`*`');\n for loop in [op(j+1..-1, loops)] do\n w2 := map((w -> product(eval(w, x=idx(x,lhs(loop))), loop)), w2);\n end do;\n w0 := w0 * `*`(op(w2));\n # w0 := w0 * foldl(product, w1, op(j+1..-1, loops));\n end do;\n # Rewrite ... * piecewise(i<=kk-1, xs^2, 1)\n # to ... * xs ^ (2*piecewise(i<=kk-1, 1))\n # because the latter is easier to integrate and recognize with respect to xs\n pp := for_poly(pp, # TODO: move this rewrite into eval_factor (then remove for_poly?)?\n proc (p)\n local n, s, r;\n if p :: 'And(specfunc(piecewise), anyfunc(freeof(x), anything, 1))' then\n n := indets(op(1,p),name);\n if op(2,p) :: {'exp(anything)', '`^`'('freeof'(n),'anything')} then\n s, r := selectremove(depends, convert(op([2,-1],p),'list','`*`'), n);\n subsop(-1 = `*`(piecewise(op(1,p), `*`(op(s))), op(r)), op(2,p))\n else\n s, r := selectremove(depends, convert(op(2,p),'list','`*`'), n);\n `*`(op(r)) ^ piecewise(op(1,p), 1)\n * `if`(nops(s) > 0, piecewise(op(1,p), `*`(op(s)), 1), 1)\n end if\n else\n p\n end if\n end proc);\n w0, pp\n end proc;\n\n # Find [w1,pp] so that\n # wrap(heap,w,mode,kb1,kb0)\n # = w1*product(eval(pp,var=idx(var,lhs(loop))),loop)\n # making w1 depend on var as little as possible.\n # The flag \"mode\" should be `+` if \"heap\" contains an entry of the form\n # t_exp, or `*` otherwise.\n unproduct := proc(w, var::name, loop::(name=range),\n heap::list, mode::identical(`*`,`+`),\n kb1::t_kb, kb0::t_kb, $)\n local ind, res, dummy, kb, kbThen, i, w1, pp, s, r, x;\n if not depends(w, var) then\n return [wrap(heap, w, mode, kb1, kb0), 1]\n end if;\n # The `..' (indices) of all occurences of `idx(var,..)'\n ind := map2(op, 2, indets(w, idx(identical(var), anything)));\n if nops(ind) = 1 then\n ind := op(ind);\n # Make sure ind contains no bound variables before lifting it!\n # So, check that \"extract using indets\" and \"rename using eval\" commute.\n s := indets(ind, 'name');\n s := map(proc(x,$) local y; `if`(depends(ind,x), x=y, NULL) end proc, s);\n if indets(eval(w, s), idx(identical(var), anything))\n = {idx(var, eval(ind, s))} then\n # use kb as a local context, and 'solve' for the innermost bound var\n # used in ind.\n kb := assert(lhs(loop)=ind, kb1); # BUG! bijectivity assumed!\n # if the assertion makes the KB false, it isn't needed(?)\n ASSERT(type(kb, t_kb),\n sprintf(\"assert(%a,%a) produced a false KB!\\n\", lhs(loop)=ind,kb1)):\n res := subs(idx(var,ind) = idx(var,lhs(loop)), w);\n res := wrap(heap, res, mode, kb, kb0);\n res := subs(idx(var,lhs(loop))=dummy, res);\n if not depends(res, var) then\n return [1, subs(dummy=var, res)]\n end if\n end if\n end if;\n # distribute the unproduct over each part\n if w :: mode then\n res := map(unproduct, `if`(mode=`*`, list_of_mul(w), [op(w)]),\n var, loop, heap, mode, kb1, kb0);\n return [`*`(op(map2(op,1,res))), `*`(op(map2(op,2,res)))]\n end if;\n # for piecewise, just map right in (using KB for context tracking)\n if w :: 'specfunc(piecewise)' then\n kb := kb1;\n for i from 1 to nops(w) do\n if i :: even then\n kbThen := assert( op(i-1,w) , kb);\n # accumulate the rest, regardless\n kb := assert(Not(op(i-1,w)), kb);\n\n # if kbThen is invalid, deal appropriately\n if not type(kbThen,t_kb) then next end if;\n\n w1[i], pp[i] := op(unproduct(op(i,w),var,loop,heap,mode,kbThen,kb0));\n # if kb is inconsistent, we're done\n if not type(kb,t_kb) then break end if;\n elif i = nops(w) then\n if not type(kb,t_kb) then next end if;\n w1[i], pp[i] := op(unproduct(op(i,w),var,loop,heap,mode,kb ,kb0))\n end if\n end do;\n return [`*`(entries(w1,'nolist')), `*`(entries(pp,'nolist'))]\n end if;\n if mode = `*` then\n if w :: (anything^freeof(var)) then\n return unproduct(op(1,w), var, loop,\n [op(heap), Stmt(`^`, [], [op(2,w)])], `*`, kb1, kb0)\n elif w :: exp(anything) then\n return unproduct(op(1,w), var, loop,\n [op(heap), Stmt(exp, [], [])], `+`, kb1, kb0)\n elif w :: (freeof(var)^anything) then\n return unproduct(op(2,w), var, loop,\n [op(heap), Stmt(`^`, [op(1,w)], [])], `+`, kb1, kb0)\n end if\n end if;\n if mode = `+` and w :: `*` then\n s, r := selectremove(depends, w, var);\n if s :: `*` then\n # Nonlinear %1 (time to reread kiselyov-lifted?)\n else\n return unproduct(s, var, loop,\n [op(heap), Stmt(`*`, [], [r])], `+`, kb1, kb0)\n end if\n end if;\n if w :: And(specfunc(`if`(mode = `*`, {product, Product}, {sum, Sum})),\n anyfunc(anything, name=range(freeof(var)))) then\n x, kb := genType(op([2,1],w), HInt(closed_bounds(op([2,2],w))), kb1,\n w, var, loop, heap);\n return unproduct(eval(op(1,w), op([2,1],w)=x), var, loop,\n [op(heap), Binder(op(0,w), kb1)], mode, kb, kb0)\n end if;\n if mode = `*` and w :: '{`+`, specfunc({sum, Sum})}' then\n # Maybe this w is one of those big sums involving products that are\n # always equal to 1, left behind by the density of Categorical\n w1 := graft(split(peel(w)));\n w1 := combine(rebase_upper(w1));\n w1 := combine(rebase_lower(w1));\n return [wrap(heap, w1, mode, kb1, kb0), 1]\n end if;\n return [wrap(heap, w, mode, kb1, kb0), 1]\n end proc;\n\n enter_piecewise := proc(ee, kb0::t_kb, mode::identical(`*`,`+`), $)\n local e, kb, mo;\n e := ee;\n kb := kb0;\n mo := mode();\n while e :: 'specfunc(piecewise)' and nops(e) = 3 do\n if op(3,e) = mo then\n kb := assert(op(1,e), kb);\n e := op(2,e);\n elif op(2,e) = mo then\n kb := assert(Not(op(1,e)), kb);\n e := op(3,e);\n else\n break;\n end if;\n end do;\n ASSERT(type(kb,t_kb), \"enter_piecewise: KB of piecewise conditions is not valid, so the input piecewise must not be valid.\");\n e, kb\n end proc;\n\n # heap is a list of t_binder and t_stmt\n # one invariant to maintain:\n # wrap(heap, mode(a,b)) = wrap(heap,a) * wrap(heap,b)\n\n # Also, a t_binder is a Product/product/Sum/sum.\n # And, a t_stmt is a 1-hole context of a (multiplicative) AST,\n # used for [a ^ hole, hole ^ b, exp(hole), c * hole].\n\n wrap := proc(heap::list, e1, mode1::identical(`*`,`+`),\n kb1::t_kb, kb0::t_kb, $)\n local e, kb, mode, i, entry, rest, var, new_rng, make, logmake,\n dom_spec, w, wPow, wExp, arrrgs;\n e := e1;\n kb := kb1;\n mode := mode1;\n for i from nops(heap) to 1 by -1 do\n entry := op(i,heap);\n if entry :: t_binder then\n if not (op(1,entry) in `if`(mode=`+`, {sum,Sum},\n {product,Product})) then\n print(\"Warning: heap mode inconsistency\", heap, mode1)\n end if;\n e, kb := enter_piecewise(e, kb, mode);\n rest := kb_subtract(kb, op(2,entry));\n new_rng, rest := selectremove(type, rest,\n {[identical(genType), name, specfunc(HInt)],\n [identical(genLet), name, anything]});\n if not (new_rng :: [list]) then\n error \"kb_subtract should return exactly one gen*\"\n end if;\n new_rng := op(new_rng);\n var := op(2,new_rng);\n if op(1,new_rng) = genType then\n make := op(1,entry);\n new_rng := range_of_HInt(op(3,new_rng));\n else # op(1,new_rng) = genLet\n make := eval;\n new_rng := op(3,new_rng);\n end if;\n dom_spec, rest := selectremove(depends,\n map(proc(a::[identical(assert),anything],$) op(2,a) end proc, rest),\n var);\n\n # Like e := make(piecewise(And(op(dom_spec)), e, mode()), var=new_rng);\n # but try to simplify by pushing the make and the piecewise into e\n (e, w) := selectremove(depends, convert(e, 'list', `*`), var);\n w := `*`(op(w));\n if mode = `*` then\n (wPow, e) := selectremove(type, e, '`^`'('freeof'(var), 'anything'));\n (wExp, e) := selectremove(type, e, 'exp(anything)');\n wExp := `+`(op(map2(op, 1, wExp)));\n logmake := t -> `if`(make=eval,eval,Sum)\n (piecewise_And(dom_spec,t,0), var=new_rng);\n w := `*`( `if`(w = 1, 1, w ^ logmake(1))\n , op(map((f -> op(1,f) ^ logmake(op(2,f))), wPow))\n , `if`(wExp = 0, 1, exp(logmake(wExp))) );\n end if;\n e := w * make(piecewise_And(dom_spec, `*`(op(e)), mode()), var=new_rng);\n\n # `rest' originally comes from `entry', and this reinserts it after some\n # processing. The original KB was valid, so this one should also be valid.\n kb := foldr(assert, op(2,entry), op(rest));\n ASSERT(type(kb,t_kb), \"Loop/wrap{t_binder}: rebuilding kb produced contradiction\");\n\n elif entry :: t_stmt then\n # We evaluate arrrgs first, in case op(1,stmt) is an operation (such as\n # piecewise) that looks ahead at how many arguments it is passed before\n # they are evaluated.\n arrrgs := op(op(2,entry)), e, op(op(3,entry));\n e := op(1,entry)(arrrgs);\n if entry :: t_exp then\n if mode <> `+` then\n print(\"Warning: heap mode inconsistency?\", heap, mode1)\n end if;\n mode := `*`;\n end if\n else error \"Malformed heap entry %1\", entry end if\n end do;\n if mode <> `*` then\n print(\"Warning: heap mode inconsistency??\", heap, mode1)\n end if;\n e, kb := enter_piecewise(e, kb, mode);\n rest := kb_subtract(kb, kb0);\n rest := map(proc(a::[identical(assert),anything],$) op(2,a) end proc, rest);\n piecewise_And(rest,e,mode())\n end proc;\n\n # Rewrite product(...piecewise(i+42=lo+42,th,el)...,i=lo..hi)\n # to eval(...th...,i=lo)*product(...el...,i=lo+1..hi)\n t_peel := 'And(specfunc({sum,Sum,product,Product}),\n anyfunc(anything, name=range))';\n peel := proc(e, $)\n subsindets(e, t_peel, do_peel);\n end proc;\n do_peel := proc(e, $)\n local make, body, x, r, cond, line, test, x0, r0, cond0, here, rest;\n if not (e :: t_peel) then return e end if;\n if op(0,e) in '{sum ,Sum }' then make := `+`;\n elif op(0,e) in '{product,Product}' then make := `*`; end if;\n body, r := op(e);\n x, r := op(r);\n for cond in indets(body, '{`=`(algebraic),`<`,`<=`}') do\n line := `-`(op(cond));\n if 1 <> degree(line, x) then next end if;\n if cond :: `=` then\n cond0 := true;\n if Testzero(eval(line, x=lhs(r))) then\n x0 := lhs(r); r0 := applyop(`+`, 1, r, 1);\n elif Testzero(eval(line, x=rhs(r))) then\n x0 := rhs(r); r0 := applyop(`-`, 2, r, 1);\n else next end if;\n else\n test := proc(x0, x1, $)\n local res;\n res := evalb(not op(0,cond)(eval(line, x=x1), 0));\n `if`(res in '{true,false}'\n and evalb(op(0,cond)(eval(line, x=x0), 0)) = res,\n res,\n FAIL)\n end proc;\n cond0 := test(lhs(r), lhs(r)+1);\n if cond0 <> FAIL then\n x0 := lhs(r); r0 := applyop(`+`, 1, r, 1);\n else\n cond0 := test(rhs(r), rhs(r)-1);\n if cond0 <> FAIL then\n x0 := rhs(r); r0 := applyop(`-`, 2, r, 1);\n else next end if;\n end if;\n end if;\n here := subs(cond = cond0 , body);\n rest := subs(cond = evalb(not cond0), body);\n return make(eval(here, x=x0), do_peel(eval(subsop(1=rest, [2,2]=r0, e))));\n end do;\n return e;\n end proc;\n\n # Expand sum(a*(b-c),q) to sum(a*b,q)-sum(a*c,q)\n split := proc(e, $)\n subsindets(e, 'And(specfunc({sum,Sum}),\n anyfunc(And(`*`,Not(`*`(Not(`+`)))),name=anything))',\n do_split);\n end proc;\n do_split := proc(e, $)\n local terms, x;\n terms := convert(expand(op(1,e), op(indets(op(1,e), function))),\n 'list', `+`);\n x := op([2,1],e);\n `+`(op(map(proc(term, $)\n local s, r;\n s, r := selectremove(depends, convert(term, 'list', `*`), x);\n `*`(op(r), subsop(1=`*`(op(s)),e))\n end proc, terms)))\n end proc;\n\n # Simplify f(lo-1)*product(f(i),i=lo..hi) to product(f(i),i=lo-1..hi)\n graft := proc(e, $)\n subsindets(e, 'Or(And(`*`,Not(`*`(Not(specfunc({product,Product}))))),\n And(`+`,Not(`+`(Not(specfunc({sum ,Sum }))))))',\n do_graft);\n end proc;\n do_graft := proc(e, $)\n local produce, factors, i, j;\n produce := `if`(e::`*`, '{product,Product}',\n '{sum ,Sum }');\n factors := sort(convert(e,'list'),\n key = (factor -> -numboccur(factor,produce)));\n for i from nops(factors) to 2 by -1 do\n for j from i-1 to 1 by -1 do\n if op(j,factors) :: 'And'('specfunc'(produce),\n 'anyfunc(anything,name=range)') then\n if Testzero(op(i,factors) - eval(op([j,1],factors),\n op([j,2,1],factors)=op([j,2,2,1],factors)-1)) then\n factors := subsop(i=NULL,applyop(`-`,[j,2,2,1],factors,1));\n break\n elif Testzero(op(i,factors) - eval(op([j,1],factors),\n op([j,2,1],factors)=op([j,2,2,2],factors)+1)) then\n factors := subsop(i=NULL,applyop(`+`,[j,2,2,2],factors,1));\n break\n end if\n end if\n end do\n end do;\n op(0,e)(op(factors))\n end proc;\n\n # Normalize sum(f(i),i=2..hi) to sum(f(i+2),i=0..hi-2)\n rebase_lower := proc(e, $)\n subsindets(e, 'And(specfunc({sum,Sum,product,Product}),\n anyfunc(anything,\n name=Not({0,SymbolicInfinity,undefined})..anything))',\n do_rebase_lower);\n end proc;\n do_rebase_lower := proc(e, $)\n subsop([2,2,1]=0,\n applyop(`-`,\n [2,2,2],\n applyop(eval, 1, e, op([2,1],e)=op([2,1],e)+op([2,2,1],e)),\n op([2,2,1],e)))\n end proc;\n\n # Normalize sum(f(i),i=lo..2) to sum(f(i+2),i=lo-2..0)\n rebase_upper := proc(e, $)\n subsindets(e, 'And(specfunc({sum,Sum,product,Product}),\n anyfunc(anything,\n name=anything..Not({0,SymbolicInfinity,undefined})))',\n do_rebase_upper);\n end proc;\n do_rebase_upper := proc(e, $)\n subsop([2,2,2]=0,\n applyop(`-`,\n [2,2,1],\n applyop(eval, 1, e, op([2,1],e)=op([2,1],e)+op([2,2,2],e)),\n op([2,2,2],e)))\n end proc;\n\n ModuleLoad := proc($)\n # Override csgn to work a little bit harder on piecewise and sum\n # (to get rid of csgn(1/2+1/2*sum(piecewise(...,1,0),...))\n # produced by int on a Gaussian mixture model)\n unprotect(csgn);\n csgn := overload([\n # Handle if the csgn of a piecewise doesn't depend on which branch\n proc(a :: specfunc(piecewise), $)\n option overload;\n local r, i;\n r := {seq(`if`(i::even or i=nops(a), csgn(op(i,a)), NULL),\n i=1..nops(a))};\n if nops(r)=1 then return op(r) end if;\n if not assigned(_Envsignum0) then\n r := r minus {0};\n if nops(r)=1 then return op(r) end if;\n end if;\n error \"invalid input: cannot csgn %1\", a;\n end proc,\n # Handle if the csgn of a sum doesn't depend on the bound variable\n proc(a :: And(specfunc({sum, Sum}), anyfunc(anything, name=range)), $)\n option overload;\n local r;\n r := csgn(op(1,a));\n if not depends(r,op([2,1],a)) then\n return signum(op([2,2,2],a)+1-op([2,2,1],a)) * r\n end if;\n error \"invalid input: cannot csgn %1\", a;\n end proc,\n csgn]);\n protect(csgn);\n\n # Override sum to fail faster\n unprotect(sum);\n sum := overload([\n proc(f :: Not({`+`,`+`^integer}),\n k :: name=And(range,Not(range(rational))), $)\n option overload;\n if not (`-`(op(rhs(k))) :: 'rational')\n and not (subsindets(f, 'anything^integer', f->op(1,f))\n :: '{`+`,And(`*`,Not(`*`(Not(`+`))))}')\n and depends(indets(f, '{specfunc(idx), specindex(idx)}'), op(1,k))\n then\n 'procname(_passed)'\n else\n error \"invalid input: cannot fast-fail sum(%1, %2)\", _passed\n end if\n end proc,\n sum]);\n protect(sum);\n\n :-`print/Ints` := curry(thismodule:-Print,Ints);\n :-`print/Sums` := curry(thismodule:-Print,Sums);\n :-`print/ints` := curry(thismodule:-Print,ints);\n :-`print/sums` := curry(thismodule:-Print,sums);\n\n end proc;\n ModuleLoad():\nend module; # Loop\n", "meta": {"hexsha": "be1c470b934376f19a5947fcbe5be05d903c864c", "size": 22446, "ext": "mpl", "lang": "Maple", "max_stars_repo_path": "maple/Loop.mpl", "max_stars_repo_name": "zaxtax/hakaru", "max_stars_repo_head_hexsha": "03ac5b645815e99437e28d228e6c668753b2640e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-02-07T17:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-29T19:40:24.000Z", "max_issues_repo_path": "maple/Loop.mpl", "max_issues_repo_name": "zaxtax/hakaru", "max_issues_repo_head_hexsha": "03ac5b645815e99437e28d228e6c668753b2640e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maple/Loop.mpl", "max_forks_repo_name": "zaxtax/hakaru", "max_forks_repo_head_hexsha": "03ac5b645815e99437e28d228e6c668753b2640e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8339100346, "max_line_length": 129, "alphanum_fraction": 0.5251269714, "num_tokens": 7078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03114382727498988, "lm_q1q2_score": 0.014963944958439487}}
{"text": "# Teach Maple (through depends and eval) about our new binding forms.\n# lam binds from 1st arg to 3rd arg.\n# Branch binds from 1st arg (a pattern) to 2nd arg.\n# Bind and ary bind from 2nd arg to 3rd arg.\n\n# note that v _can_ in principle occur in t.\n`depends/lam` := proc(v::name, t, e, x, $)\n depends(t, x) or depends(e, x minus {v})\nend proc:\n\n`depends/Branch` := proc(p, e, x, $)\n depends(e, x minus {Hakaru:-pattern_binds(p)})\nend proc:\n\n# note that v _can_ occur in m1.\n`depends/Bind` := proc(m1, v::name, m2, x, $)\n depends(m1, x) or depends(m2, x minus {v})\nend proc:\n\n# note that i _can_ occur in n.\n`depends/ary` := proc(n, i::name, e, x, $)\n depends(n, x) or depends(e, x minus {i})\nend proc:\n`depends/Plate` := eval(`depends/ary`):\n\n`eval/lam` := proc(e, eqs, $)\n local v, t, ee;\n v, t, ee := op(e);\n v, ee := BindingTools:-generic_evalat(v, ee, eqs);\n t := eval(t, eqs);\n eval(op(0,e), eqs)(v, t, ee)\nend proc:\n\n`eval/Branch` := proc(e, eqs, $)\n local p, ee, vBefore, vAfter;\n p, ee := op(e);\n vBefore := [Hakaru:-pattern_binds(p)];\n vAfter, ee := BindingTools:-generic_evalat(vBefore, ee, eqs);\n eval(op(0,e), eqs)(subs(op(zip(`=`, vBefore, vAfter)), p), ee)\nend proc:\n\n`eval/Bind` := proc(e, eqs, $)\n local m1, v, m2;\n m1, v, m2 := op(e);\n eval(op(0,e), eqs)(eval(m1, eqs), BindingTools:-generic_evalat(v, m2, eqs))\nend proc:\n\n`eval/ary` := proc(e, eqs, $)\n local n, i, ee;\n n, i, ee := op(e);\n eval(op(0,e), eqs)(eval(n, eqs), BindingTools:-generic_evalat(i, ee, eqs))\nend proc:\n`eval/Plate` := eval(`eval/ary`):\n\n#############################################################################\nHakaru := module ()\n option package;\n local p_true, p_false, make_piece, Mk_Plus, lift1_piecewise,\n ModuleLoad, ModuleUnload;\n export\n # These first few are smart constructors (for themselves):\n case, app, ary, idx, fst, snd, size, Datum,\n # while these are \"proper functions\"\n verify_measure, verify_hboolean, pattern_equiv,\n piecewise_And, map_piecewiselike, lift_piecewise, foldr_piecewise,\n flatten_piecewise,\n pattern_match, pattern_binds,\n closed_bounds, open_bounds,\n htype_patterns,\n bool_And, bool_Or, bool_Not,\n UpdateArchive;\n # These names are not assigned (and should not be). But they are\n # used as global names, so document that here.\n global\n # Basic syntax for composing measures\n Bind, Weight, Ret, Msum, Plate, Context, Pair, _Unit, PARTITION,\n # Primitive (known) measures\n Lebesgue, Uniform, Gaussian, Cauchy, StudentT, BetaD,\n GammaD, ChiSquared,\n Counting, Categorical, NegativeBinomial, PoissonD,\n # Functions, annotated with argument type, applied using \"app\"\n lam,\n # Term constructors for Datum (algebraic data type)\n Inr, Inl, Et, Done, Konst, Ident,\n # The parts of \"case\" besides the scrutinee\n Branches, Branch,\n # Pattern constructors\n PWild, PVar, PDatum, PInr, PInl, PEt, PDone, PKonst, PIdent,\n # Verification of alpha-equivalence among measures\n measure,\n # Punctuation for matching free variables with measures for disintegration\n `&M`,\n # Structure types for Hakaru types and Hakaru \"case\" expressions\n known_continuous, known_discrete, t_Hakaru, t_type, t_case,\n # Structure types for piecewise-like expressions:\n # piecewise, case, and idx into literal array\n t_pw, t_piecewiselike,\n #other types\n `&implies`,\n # Type constructors for Hakaru\n AlmostEveryReal, HReal, HInt, HData, HMeasure, HArray, HFunction,\n Bound, DatumStruct;\n p_true := 'PDatum(true,PInl(PDone))';\n p_false := 'PDatum(false,PInr(PInl(PDone)))';\n\n case := proc(e, bs :: specfunc(Branch(anything, anything), Branches), $)\n local ret, b, substs, eSubst, pSubst, p, binds, uncertain;\n if e :: 't_piecewiselike' then\n map_piecewiselike(procname, _passed)\n else\n ret := Branches();\n for b in bs do\n substs := pattern_match(e, e, op(1,b));\n if substs <> NULL then\n eSubst, pSubst := substs;\n p := subs(pSubst, op(1,b));\n binds := {pattern_binds(p)};\n uncertain := remove((eq -> lhs(eq) in binds), eSubst);\n if nops(uncertain) = 0 then p := PWild end if;\n ret := Branches(op(ret),\n Branch(p, eval(eval(op(2,b), pSubst), eSubst)));\n if nops(uncertain) = 0 then break end if;\n end if\n end do;\n if ret :: Branches(Branch(identical(PWild), anything)) then\n op([1,2], ret)\n elif ret :: Branches(Branch(identical(p_true), anything),\n Branch({identical(p_false),\n identical(PWild),\n PVar(anything)}, anything)) then\n piecewise(make_piece(e), op([1,2], ret), op([2,2], ret))\n elif ret :: Branches(Branch(identical(p_false), anything),\n Branch({identical(p_true),\n identical(PWild),\n PVar(anything)}, anything)) then\n piecewise(make_piece(e), op([2,2], ret), op([1,2], ret))\n else\n 'case'(e, ret)\n end if\n end if\n end proc;\n\n pattern_match := proc(e0, e, p, $)\n local x, substs, eSubst, pSubst;\n if p = PWild then return {}, {}\n elif p :: PVar(anything) then\n x := op(1,p);\n pSubst := {`if`(depends(e0,x), x=gensym(x), NULL)};\n return {subs(pSubst,x)=e}, pSubst;\n elif p = p_true then\n if e = true then return {}, {}\n elif e = false then return NULL\n end if\n elif p = p_false then\n if e = false then return {}, {}\n elif e = true then return NULL\n end if\n elif p :: PDatum(anything, anything) then\n if e :: Datum(anything, anything) then\n if op(1,e) = op(1,p) then return pattern_match(e0, op(2,e), op(2,p))\n else return NULL\n end if\n end if\n elif p :: PInl(anything) then\n if e :: Inl(anything) then return pattern_match(e0, op(1,e), op(1,p))\n elif e :: Inr(anything) then return NULL\n end if\n elif p :: PInr(anything) then\n if e :: Inr(anything) then return pattern_match(e0, op(1,e), op(1,p))\n elif e :: Inl(anything) then return NULL\n end if\n elif p :: PEt(anything, anything) then\n if e :: Et(anything, anything) then\n substs := pattern_match(e0, op(1,e), op(1,p));\n if substs = NULL then return NULL end if;\n eSubst, pSubst := substs;\n substs := pattern_match(e0, eval(op(2,e),eSubst), op(2,p));\n if substs = NULL then return NULL end if;\n return eSubst union substs[1], pSubst union substs[2];\n elif e = Done then return NULL\n end if\n elif p = PDone then\n if e = Done then return {}, {}\n elif e :: Et(anything, anything) then return NULL\n end if\n elif p :: PKonst(anything) then\n if e :: Konst(anything) then return pattern_match(e0, op(1,e), op(1,p))\n end if\n elif p :: PIdent(anything) then\n if e :: Ident(anything) then return pattern_match(e0, op(1,e), op(1,p))\n end if\n else\n error \"pattern_match: %1 is not a pattern\", p\n end if;\n pSubst := map((x -> `if`(depends(e0,x), x=gensym(x), NULL)),\n {pattern_binds(p)});\n eSubst := {e=subsindets(\n subsindets[nocache](\n subs(pSubst,\n p_true=true,\n p_false=false,\n PDatum=Datum, PInr=Inr, PInl=Inl, PEt=Et, PDone=Done,\n PKonst=Konst, PIdent=Ident,\n p),\n identical(PWild),\n p -> gensym(_)),\n PVar(anything),\n p -> op(1,p))};\n eSubst, pSubst\n end proc;\n\n make_piece := proc(rel, $)\n # Try to prevent PiecewiseTools:-Is from complaining\n # \"Wrong kind of parameters in piecewise\"\n if rel :: {specfunc(anything, {And,Or,Not}), `and`, `or`, `not`} then\n map(make_piece, rel)\n elif rel :: {'`::`', 'boolean', '`in`'} then\n rel\n else\n rel = true\n end if\n end proc;\n\n pattern_binds := proc(p, $)\n if p = PWild or p = PDone then\n NULL\n elif p :: PVar(anything) then\n op(1,p)\n elif p :: PDatum(anything, anything) then\n pattern_binds(op(2,p))\n elif p :: {PInl(anything), PInr(anything),\n PKonst(anything), PIdent(anything)} then\n pattern_binds(op(1,p))\n elif p :: PEt(anything, anything) then\n pattern_binds(op(1,p)), pattern_binds(op(2,p))\n else\n error \"pattern_binds: %1 is not a pattern\", p\n end if\n end proc:\n\n verify_hboolean := proc(a, b, $)\n local x,y,conv_tbl,and_fn,or_fn,not_fn;\n and_fn := ((x->AND({op(x)}))@`bool_And`);\n or_fn := ((x->OR({op(x)}))@`bool_Or`);\n not_fn := bool_Not;\n conv_tbl := table([`and`=and_fn,`And`=and_fn,`Or`=or_fn,`or`=or_fn,`Not`=not_fn,`not`=not_fn]);\n x,y := subsindets([a,b], Or(`and`,`or`,`not`, specfunc({`And`,`Or`,`Not`})), x->conv_tbl[op(0,x)](op(x)))[];\n evalb(x=y);\n end proc;\n\n verify_measure := proc(m, n, v:='hboolean', $)\n local mv, x, i, j, k;\n mv := measure(v);\n if m :: specfunc({Bind, Plate}) and n :: specfunc({Bind, Plate}) and\n (verify(m, n, 'Bind'(mv, true, true))\n or verify(m, n, 'Plate'(v, true, true))) then\n x := gensym(cat(op(2,m), \"_\", op(2,n), \"_\"));\n thisproc(subs(op(2,m)=x, op(3,m)),\n subs(op(2,n)=x, op(3,n)), v)\n elif m :: 'specfunc(Msum)' and n :: 'specfunc(Msum)'\n and nops(m) = nops(n) then\n k := nops(m);\n verify(k, GraphTheory[BipartiteMatching](GraphTheory[Graph]({\n seq(seq(`if`(thisproc(op(i,m), op(j,n), v), {i,-j}, NULL),\n j=1..k), i=1..k)}))[1]);\n elif andmap(type, [m,n], 'specfunc(piecewise)') and nops(m) = nops(n) then\n k := nops(m);\n verify(m, n, 'piecewise'(seq(`if`(i::even or i=k, mv, hboolean), i=1..k)));\n\n elif andmap(type, [m,n], 'specfunc(PARTITION)') then\n Partition:-SamePartition(verify_hboolean, verify_measure, m, n);\n\n elif m :: specfunc('case') and\n verify(m, n, 'case'(v, specfunc(Branch(true, true), Branches))) then\n # This code unfortunately only handles alpha-equivalence for 'case' along\n # the control path -- not if 'case' occurs in the argument to 'Ret', say.\n k := nops(op(2,m));\n for i from 1 to k do\n j := pattern_equiv(op([2,i,1],m), op([2,i,1],n));\n if j = false then return j end if;\n j := map(proc(eq, $)\n local x;\n x := gensym(cat(lhs(eq), \"_\", rhs(eq), \"_\"));\n [lhs(eq)=x, rhs(eq)=x]\n end proc, j);\n j := thisproc(subs(map2(op,1,j), op([2,i,2],m)),\n subs(map2(op,2,j), op([2,i,2],n)), v);\n if j = false then return j end if;\n end do;\n true\n elif m :: 'LO(name, anything)' and n :: 'LO(name, anything)' then\n x := gensym(cat(op(1,m), \"_\", op(1,n), \"_\"));\n verify(subs(op(1,m)=x, op(2,m)),\n subs(op(1,n)=x, op(2,n)), v)\n elif m :: specfunc('lam') and n :: specfunc('lam') and\n verify(m, n, 'lam'(true, v, true)) then\n # m and n are not even measures, but we verify them anyway...\n x := gensym(cat(op(1,m), \"_\", op(1,n), \"_\"));\n thisproc(subs(op(1,m)=x, op(2,m)),\n subs(op(1,n)=x, op(2,n)), v)\n else\n verify(m, n, {v, Ret(v), Weight(v, mv), Context(v, mv)})\n end if\n end proc;\n\n pattern_equiv := proc(p, q, $) :: {identical(false),set(`=`)};\n local r, s;\n if ormap((t->andmap(`=`, [p,q], t)), [PWild, PDone]) then\n {}\n elif andmap(type, [p,q], PVar(anything)) then\n {op(1,p)=op(1,q)}\n elif andmap(type, [p,q], PDatum(anything,anything)) and op(1,p)=op(1,q) then\n pattern_equiv(op(2,p),op(2,q))\n elif ormap((t->andmap(type, [p,q], t(anything))),\n [PInl, PInr, PKonst, PIdent]) then\n pattern_equiv(op(1,p),op(1,q))\n elif andmap(type, [p,q], PEt(anything, anything)) then\n r := pattern_equiv(op(1,p),op(1,q));\n s := pattern_equiv(op(2,p),op(2,q));\n if map(lhs,r) intersect map(lhs,s) = {} and\n map(rhs,r) intersect map(rhs,s) = {} then\n r union s\n else\n false\n end if\n else\n false\n end if\n end proc;\n\n piecewise_And := proc(cond::{list,set,specfunc(`And`),`and`}, th, el, $)\n if nops(cond) = 0 or th = el then\n th\n else\n piecewise(And(op(cond)), th, el)\n end if\n end proc;\n\n map_piecewiselike := proc(f, p::t_piecewiselike)\n local i, g, h;\n if p :: 'specfunc(piecewise)' then\n piecewise(seq(`if`(i::even or i=nops(p), f(op(i,p),_rest), op(i,p)),\n i=1..nops(p)))\n elif p :: 't_case' then\n # Mind the hygiene\n subsindets(eval(subsop(2 = map[3](applyop, g, 2, op(2,p)), p),\n g=h(f,_rest)),\n 'typefunc(specfunc(h))',\n (e -> op([0,1],e)(op(1,e), op(2..-1,op(0,e)))))\n elif p :: 'idx(list, anything)' then\n idx(map(f,op(1,p),_rest), op(2,p))\n else\n error \"map_piecewiselike: %1 is not t_piecewiselike\", p\n end if\n end proc;\n\n lift_piecewise := proc(e, extra:={}, $)\n local e1, e2;\n e2 := e;\n while e1 <> e2 do\n e1 := e2;\n e2 := subsindets(e1,\n '{extra,\n And(`+`, Not(specop(Not(specfunc(piecewise)), `+`))),\n And(`*`, Not(specop(Not(specfunc(piecewise)), `*`))),\n And(`^`, Not(specop(Not(specfunc(piecewise)), `^`))),\n exp(specfunc(piecewise))}',\n lift1_piecewise)\n end do\n end proc;\n\n lift1_piecewise := proc(e, $)\n local i, p;\n if membertype(t_piecewiselike, [op(e)], i) then\n p := op(i,e);\n if nops(p) :: even and not (e :: `*`) and op(-1,p) <> 0 then\n p := piecewise(op(p), 0);\n end if;\n map_piecewiselike((arm->lift1_piecewise(subsop(i=arm,e))), p)\n else\n e\n end if\n end proc;\n\n foldr_piecewise := proc(cons, nil, pw, $) # pw may or may not be piecewise\n # View pw as a piecewise and foldr over its arms\n if pw :: 'specfunc(piecewise)' then\n foldr(proc(i,x) cons(op(i,pw), op(i+1,pw), x) end proc,\n `if`(nops(pw)::odd, cons(true, op(-1,pw), nil), nil),\n seq(1..nops(pw)-1, 2))\n else\n cons(true, pw, nil)\n end if\n end proc;\n\n #Take a piecewise: If some of the branches also contain piecewises, attempt\n #to re-express the whole as a single piecewise. In short: fewer piecewises, more\n #branches, more complex conditions.--Carl 2016Sep09\n flatten_piecewise:= proc(PW::specfunc(piecewise), $)::specfunc(piecewise);\n local\n pwL:= [op(PW)],\n nP:= nops(pwL),\n conds:= pwL[[seq(1..nP-1, 2)]],\n branches:= pwL[[seq(2..nP-1, 2), nP]],\n innerPW:= indets(branches, specfunc(piecewise)),\n outerPW, C_O, C_I, B_I, r\n ;\n if indets(conds, specfunc(piecewise)) <> {} then\n userinfo(2, procname, \"Case of inner pw in a condition not yet handled.\");\n return PW\n end if;\n if innerPW = {} then\n userinfo(3, procname, \"No inner pw.\");\n return PW\n end if;\n if nops~(innerPW) <> {3} then\n userinfo(2, procname, \"Case of inner pw of other than 3 ops not yet handled.\");\n return PW\n end if;\n if nops(PW) <> 3 then\n userinfo(2, procname, \"Case of outer pw of other than 3 ops not yet handled.\");\n return PW\n end if;\n outerPW:= applyop(lift_piecewise, {2,3}, PW);\n if membertype(\n And(\n satisfies(e-> indets(e, specfunc(piecewise)) <> {}),\n Not(specfunc(piecewise))\n ),\n {op(2..3, outerPW)}\n )\n then\n userinfo(1, procname, \"Unliftable pw.\");\n return PW\n end if;\n C_O:= op(1,outerPW);\n C_I:= map(e-> `if`(e::specfunc(piecewise), op(1,e), true), [op(2..3, outerPW)]);\n B_I:= map(e-> `if`(e::specfunc(piecewise), [op(2..3, e)], [e$2])[], [op(2..3, outerPW)]);\n #For debugging purposes, I want to show the proposed output before it's passed to\n #piecewise.\n r:= [\n And(C_O, C_I[1]), B_I[1],\n And(C_O, KB:-negate_rel(C_I[1])), B_I[2],\n And(KB:-negate_rel(C_O), C_I[2]), B_I[3],\n And(KB:-negate_rel(C_O), KB:-negate_rel(C_I[2])), B_I[4]\n ];\n userinfo(3, procname, \"Proposed ouput: \", print(%piecewise(r[])));\n piecewise(r[])\n end proc;\n\n app := proc (func, argu, $)\n if func :: 'lam(name, anything, anything)' then\n eval(op(3,func), op(1,func)=argu)\n elif func :: 't_piecewiselike' then\n map_piecewiselike(procname, _passed)\n else\n 'procname(_passed)'\n end if\n end proc;\n\n ary := proc (n, i, e, $)\n local j;\n if e :: 'idx'('freeof'(i), 'identical'(i)) then\n # Array eta-reduction. Assume the size matches. (We should keep array\n # size information in the KB and use it here, but we don't currently.)\n op(1,e)\n elif n :: nonnegint then\n [seq(eval(e,i=j), j=0..n-1)] # Unroll array with literal size\n else\n 'procname(_passed)'\n end if\n end proc;\n\n idx := proc (a, i, $)\n if a :: 'ary(anything, name, anything)' then\n eval(op(3,a), op(2,a)=i)\n elif a :: 'list' and i::nonnegint then\n a[i+1]\n elif a :: 'list' and nops(convert(a,'set')) = 1 then\n a[1] # Indexing into a literal array whose elements are all the same\n elif a :: 't_piecewiselike' then\n map_piecewiselike(procname, _passed)\n else\n 'procname(_passed)'\n end if\n end proc;\n\n #Extract the first member of a Pair.\n fst:= proc(p, $)\n if p :: 'Pair'('anything'$2) then\n op(1,p)\n elif p :: t_piecewiselike then\n map_piecewiselike(fst, p)\n else\n 'procname'(p)\n end if;\n end proc;\n\n #Extract the second member of a Pair.\n snd:= proc(p, $)\n if p :: 'Pair'('anything'$2) then\n op(2,p)\n elif p :: t_piecewiselike then\n map_piecewiselike(snd, p)\n else\n 'procname'(p)\n end if;\n end proc;\n\n size := proc(a, $)\n local res;\n if a :: 'ary(anything, name, anything)' then\n op(1,a)\n elif a :: 'list' then\n nops(a)\n elif a :: 't_piecewiselike' then\n map_piecewiselike(procname, _passed)\n else\n 'procname(_passed)'\n end if\n end proc;\n\n Datum := proc(hint, payload, $)\n # Further cheating to equate Maple booleans and Hakaru booleans\n if hint = true and payload = Inl(Done) or\n hint = false and payload = Inr(Inl(Done)) then\n hint\n else\n 'procname(_passed)'\n end if\n end proc;\n\n closed_bounds := proc(r::range, $)\n Bound(`>=`, lhs(r)), Bound(`<=`, rhs(r))\n end proc;\n\n open_bounds := proc(r::range, $)\n Bound(`>`, lhs(r)), Bound(`<`, rhs(r))\n end proc;\n\n # Creates an N-ary operator `Plus` such:\n # Plus(Plus(a,b),c)=Plus(a,Plus(a,b))\n # Plus(a,Zero)=a\n # Plus(a)=a\n # Plus(x,x)=x\n Mk_Plus := proc(plus,zero,$) proc()\n local as := {args};\n as := map(a->if op(0,a)=plus then op(a) else a end if, as);\n if nops(as)=0 then zero\n elif nops(as)=1 then op(1,as)\n else plus(op(as))\n end if;\n end proc; end proc;\n\n # Replacements for `and` and `or` which do not\n # evaluate \"x = y\" to \"false\" when \"x,y\" are unbound vars.\n bool_And := Mk_Plus('And','true' );\n bool_Or := Mk_Plus('Or' ,'false');\n\n bool_Not := proc(a,$)\n if a :: t_kb_atom then\n subsindets(KB:-negate_rel(a), `not`, Not@op);\n else\n Not(a)\n end if;\n end proc;\n\n # Enumerate patterns for a given Hakaru type\n htype_patterns := proc(t::t_type, $)\n :: specfunc(Branch(anything, list(t_type)), Branches);\n local struct;\n uses StringTools;\n if t :: specfunc(DatumStruct(anything, list(Konst(anything))), HData) then\n foldr(proc(struct,ps,$) Branches(\n op(map((p -> Branch(PDatum(op(1,struct), PInl(op(1,p))),\n op(2,p))),\n foldr(proc(kt,qs,$)\n local p, q;\n Branches(seq(seq(Branch(PEt(PKonst(op(1,p)),\n op(1,q)),\n [op(op(2,p)),op(op(2,q))]),\n q in qs),\n p in htype_patterns(op(1,kt))))\n end proc,\n Branches(Branch(PDone, [])), op(op(2,struct))))),\n op(map[3](applyop, PInr, [1,2], ps)))\n end proc,\n Branches(), op(t))\n else\n Branches(Branch(PVar(gensym(convert(LowerCase(op(-1, [\"x\", op(\n `if`(t::function,\n select(IsUpper, Explode(op(0,t))),\n []))])),\n name))),\n [t]))\n end if\n end proc;\n\n ModuleLoad := proc($)\n local g; #Iterator over thismodule's globals\n ModuleUnload();\n VerifyTools[AddVerification](measure = eval(verify_measure));\n VerifyTools[AddVerification](hboolean = eval(verify_hboolean));\n\n TypeTools:-AddType(\n `&implies`,\n proc(e, t1, t2, $) type(e, Or(Not(t1), t2)) end proc\n );\n TypeTools:-AddType(Name, And(name, Not({constant,undefined})));\n TypeTools:-AddType(known_continuous,\n '{\n Lebesgue(anything, anything), Uniform(anything, anything),\n Gaussian(anything, anything), Cauchy(anything, anything),\n StudentT(anything, anything, anything), ChiSquared(anything),\n BetaD(anything, anything), GammaD(anything, anything),\n InverseGammaD(anything, anything)\n }'\n );\n TypeTools:-AddType(known_discrete,\n '{\n Counting(anything, anything),\n Categorical(anything),\n Binomial(anything,anything),\n NegativeBinomial(anything,anything),\n PoissonD(anything)\n }'\n );\n #This type t_Hakaru is the basic syntax checker for that part of the\n #Maple/Hakaru language accessible by the external user.--Carl 2016Sep20\n TypeTools:-AddType(t_Hakaru,\n #Alternation/conjunction of types via {} or And follows the McCarthy\n #short-cut rule: Proceeding left to right, once satisfaction of the type\n #can be determined, the remaining elements aren't evaluated. Therefore,\n #recursive types are possible by placing the base cases at the beginning.\n #But use Or instead of {} because you can't control the order of\n #expressions with {}.\n Or(\n 'known_continuous', 'known_discrete',\n t_pw, #Needs to be more specific!\n t_partition,\n t_case,\n 'Ret(anything)',\n 'Bind(t_Hakaru, name, t_Hakaru)',\n 'specfunc(t_Hakaru, Msum)',\n 'Weight(algebraic, t_Hakaru)',\n 'Plate(algebraic, name, t_Hakaru)',\n t_lam\n )\n );\n TypeTools:-AddType(t_type,\n '{specfunc(Bound(identical(`<`,`<=`,`>`,`>=`), anything),\n {AlmostEveryReal, HReal, HInt}),\n specfunc(DatumStruct(anything, list({Konst(t_type), Ident(t_type)})),\n HData),\n HMeasure(t_type),\n HArray(t_type),\n HFunction(t_type, t_type)}');\n TypeTools:-AddType(t_case,\n 'case(anything, specfunc(Branch(anything, anything), Branches))');\n TypeTools:-AddType(t_pw, 'specfunc(piecewise)');\n TypeTools:-AddType(t_partition, 'specfunc(PARTITION)'); #Appropriate to put this here?\n TypeTools:-AddType(t_piecewiselike,\n '{specfunc(piecewise), t_case, idx(list, anything)}');\n TypeTools:-AddType(t_lam, 'lam(name, t_type, t_Hakaru)');\n\n # A temporary type which should be removed when piecewise is gone\n TypeTools:-AddType(t_pw_or_part, Or(t_pw,t_partition));\n\n #Protect the keywords of the Hakaru language.\n #op([2,6], ...) of a module is its globals.\n for g in op([2,6], thismodule) do\n if g <> eval(g) then\n unassign(g);\n WARNING(\"Previous value of Hakaru keyword '%1' erased.\", g);\n end if;\n protect(g)\n end do\n end proc;\n\n ModuleUnload := proc($)\n map(proc(x::uneval) try eval(x) catch: NULL; end try end proc,\n ['TypeTools:-RemoveType(`&implies`)'\n ,'TypeTools:-RemoveType(Name)'\n ,'TypeTools:-RemoveType(known_continuous)'\n ,'TypeTools:-RemoveType(known_discrete)'\n ,'TypeTools:-RemoveType(t_Hakaru)'\n ,'TypeTools:-RemoveType(t_pw)'\n ,'TypeTools:-RemoveType(t_partition)'\n ,'TypeTools:-RemoveType(t_pw_or_part)'\n ,'TypeTools:-RemoveType(t_piecewiselike)'\n ,'TypeTools:-RemoveType(t_case)'\n ,'TypeTools:-RemoveType(t_type)'\n ,'TypeTools:-RemoveType(t_lam)'\n ,'VerifyTools[RemoveVerification](measure)'\n ]);\n unprotect(op([2,6], thismodule)); #See comment in ModuleLoad.\n #Skip restoring the globals to any prior value they had.\n end proc;\n ModuleLoad();\nend module; # Hakaru\n", "meta": {"hexsha": "28c882de08f9b3f69fd14927a62c350ad6be81ba", "size": 25230, "ext": "mpl", "lang": "Maple", "max_stars_repo_path": "maple/Hakaru.mpl", "max_stars_repo_name": "zaxtax/hakaru", "max_stars_repo_head_hexsha": "03ac5b645815e99437e28d228e6c668753b2640e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-02-07T17:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-29T19:40:24.000Z", "max_issues_repo_path": "maple/Hakaru.mpl", "max_issues_repo_name": "zaxtax/hakaru", "max_issues_repo_head_hexsha": "03ac5b645815e99437e28d228e6c668753b2640e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maple/Hakaru.mpl", "max_forks_repo_name": "zaxtax/hakaru", "max_forks_repo_head_hexsha": "03ac5b645815e99437e28d228e6c668753b2640e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9914407989, "max_line_length": 112, "alphanum_fraction": 0.5529924693, "num_tokens": 7514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.03789242527149358, "lm_q1q2_score": 0.01458525520567376}}
{"text": "# Various utilities used by Hakaru which don't fit logically elsewhere\nUtilities := module ()\n option package;\n\n # Returns true for a sequence for which all the elements are equal up to the\n # specified equality, or false otherwise. A 0-length sequence produces an\n # error.\n export the := proc(as, eq:=`=`, $)\n if nops(as)=0 then error \"sequence %1 must have at least one operand\", as; end if;\n andmap(x -> eq(x,op(1,as)), [op(2..-1,as)]);\n end proc;\n\n # zip together an arbitrary number of lists;\n # - if any lists are shorter, the function recieves all available arguments\n # e.g. zip_k(F, [a,b], [c]) -> [F(a, c), F(b)]\n # - if any lists contain subslists, those are also zipped together, so\n # zip_k(F, as) and zip_k(F, [as]) are equivalent. To avoid this, use a 0-th\n # operand other than `[]`.\n # e.g. zip_k(F, [a,b], [ [c,d], [e,f] ]) -> [F(a, c, d), F(b, e, f)]\n export zip_k := proc(f)\n map(f@op@ListTools[Flatten], foldl((a,b)->zip(`[]`,a,b,[]), _rest));\n end proc;\n\n # Merges two records, `rspec' and `rdef'. If `rspec' contains any fields of\n # `rdef', the fields of `rspec' are taken.\n export merge_record_default := proc(rdef::record, rspec::record, $)\n local s;\n s := {exports(rdef)} intersect {exports(rspec)};\n Record[ Record[rdef](op(map(`-`,s))) , rspec ]();\n end proc;\n\n # Creates a new record with `field' updated to the given function applied to\n # `field' of the given record.\n export upd_field := proc(r::record, field::name, k, $)\n Record[r](-field,field=k(r[field]))\n end proc;\n\n # Simplistic negation of relations. Used by Hakaru:-flatten_piecewise, KB, and\n # Domain.\n export negated_relation:= table([`<`, `<=`, `=`, `<>`] =~ [`>=`, `>`, `<>`, `=`]);\n\n # Takes the bool type (true/false) to mean universal and empty relations\n # respectively. i.e. negate R, where R is an 'atomic' relation of a KB.\n # This is used by KB and Partition\n export negate_rel:= proc(R::Relation, $)::Relation;\n if R :: truefalse then\n not R\n elif R :: relation then\n negated_relation[op(0,R)](op(R));\n else\n # This is to appease 'piecewise', which won't be happy with Not\n # However, KB doesn't really care - it's already expecting {Not,not}\n # 'Technically' this is a KB 'constructor'!\n not(R);\n end if;\n end proc;\n\n # Differs from negate_rel in that\n # [ negate_rel (x) ] = \"Not x\" but\n # [ negate_rels(x) ] = \"x\"\n export negate_rels := proc(e, $)\n subsindets(e, { specfunc(relation, `Not`), `not`(relation) }, negate_rel@op );\n end proc;\n\n # Creates an N-ary operator `Plus` such:\n # Plus(Plus(a,b),c)=Plus(a,Plus(a,b))\n # Plus(a,Iden)=a\n # Plus(a,Zero)=Zero\n # Plus(a)=a\n # Plus(x,x)=x\n export Mk_Plus := proc(plus,iden,zero,$) proc()\n local as := {args};\n as := map(a->if op(0,a)=plus then op(a) else a end if, as);\n if zero in as then return zero end if;\n as := remove(`=`,as,iden);\n if nops(as)=0 then iden\n elif nops(as)=1 then op(1,as)\n else plus(op(as))\n end if;\n end proc; end proc;\n\n # Replacements for `and`, `or`, `not` which do not\n # evaluate \"x = y\" to \"false\" when \"x,y\" are unbound vars.\n export bool_And := Mk_Plus(And,true ,false);\n export bool_Or := Mk_Plus(Or ,false,true);\n export bool_Not := proc(a,$)\n if a :: Relation and not (a :: `::`) then\n subsindets(negate_rel(a), `not`, Not@op);\n else\n Not(a)\n end if;\n end proc;\n\n # boolean_if should be equivalent to `if`, but it assumes\n # all its arguments are boolean conditions, so it basically\n # simplifies \"cond and th or not cond and el\"\n export boolean_if := proc(cond, th, el, $)\n use\n a = ((x,y)-> `if`(x=true,y, `if`(x=false,x,\n `if`(y=true,x, `if`(y=false,y, And(x,y)))))),\n o = ((x,y)-> `if`(x=false,y, `if`(x=true,x,\n `if`(y=false,x, `if`(y=true,y, Or (x,y)))))),\n n = (x -> `if`(x=false,true,\n `if`(x=true,false, Not(x))))\n in\n o(a(cond,th), a(n(cond),el))\n end use\n end proc;\n\n # In order to hopefully produce a simplification,\n # assert_deny will on some occasions repeatedly apply\n # `simplify@ln` in the hopes of producing an 'improved'\n # constraint. This metric gives the stopping condition\n # - when the simplification ceases to improve the constraint\n # - which is when the metric is made no less by the `simplify@ln`.\n # Since this is a `length`, this is strictly decreasing,\n # so such a loop will 'provably' always terminate\n export log_metric := proc(e, x, $)\n local m, L;\n m := select(depends, indets(e, 'exp(anything)'), indets(x,name));\n length(subsindets(map2(op, 1, m), name, _->L));\n end proc;\n\n # Used by both KB and Domain\n export try_improve_exp := proc(b0, x, ctx, $)\n local b := b0, log_b;\n do\n try log_b := map(simplify@ln, b) assuming op(ctx); catch: break; end try;\n\n if log_metric(log_b, x) < log_metric(b, x)\n and (andmap(e->is(e,real)=true, log_b) assuming op(ctx)) then\n b := log_b;\n else\n break;\n end if;\n end do;\n b;\n end proc;\n\n # Given an expression containing products and sums, i.e. polynomials\n # and a function , applies this expression to each factor and summand\n export for_poly := proc(e, f, $)\n if e :: '{`+`,`*`}' then map(for_poly, e, f)\n elif e :: 'specfunc({product,Product,sum,Sum})' then\n applyop(for_poly, 1, e, f)\n else f(e)\n end if\n end proc;\n\n # Apply a function to each summand at the top level of the expression\n export distrib_over_sum := proc(f,e,$) `+`(op(map(f,convert(e, 'list',`+`)))) end proc;\n\n # Like convert(e, 'list', `*`) but tries to keep the elements positive\n export list_of_mul := proc(e, $)\n local rest, should_negate, can_negate, fsn;\n rest := convert(e, 'list', `*`);\n rest := map((f -> [f, signum(f),\n `if`(f::'{specfunc({Sum,sum}),anything^odd}',\n applyop(`-`,1,f),\n `if`(f::'specfunc(ln)',\n applyop(`/`,1,f),\n -f))]),\n rest);\n should_negate, rest := selectremove(type, rest,\n '[anything, -1, Not(`*`)]');\n if nops(should_negate) :: even then\n [seq(op(3,fsn), fsn=should_negate),\n seq(op(1,fsn), fsn=rest)]\n else\n can_negate, rest := selectremove(type, rest,\n '[{`+`, specfunc({Sum,sum,ln}), `^`}, Not(1), Not(`*`)]');\n if nops(can_negate) > 0 then\n [seq(op(3,fsn), fsn=should_negate),\n op([1,3], can_negate),\n seq(op(1,fsn), fsn=subsop(1=NULL, can_negate)),\n seq(op(1,fsn), fsn=rest)]\n else\n [seq(op(3,fsn), fsn=subsop(-1=NULL, should_negate)),\n op([-1,1], should_negate),\n seq(op(1,fsn), fsn=rest)]\n end if\n end if\n end proc;\n\n export mysolve := proc(constraints)\n # This wrapper around \"solve\" works around the problem that Maple sometimes\n # thinks there is no solution to a set of constraints because it doesn't\n # recognize the solution to each constraint is the same. For example--\n # This fails : solve({c*2^(-1/2-alpha) = sqrt(2)/2, c*4^(-alpha) = 2^(-alpha)}, {c}) assuming alpha>0;\n # This also fails: solve(simplify({c*2^(-1/2-alpha) = sqrt(2)/2, c*4^(-alpha) = 2^(-alpha)}), {c}) assuming alpha>0;\n # But this works : map(solve, {c*2^(-1/2-alpha) = sqrt(2)/2, c*4^(-alpha) = 2^(-alpha)}, {c}) assuming alpha>0;\n # And the difference of the two solutions returned simplifies to zero.\n\n local result;\n if nops(constraints) = 0 then return NULL end if;\n result := solve(constraints, _rest);\n if result <> NULL or not (constraints :: {set,list}) then\n return result\n end if;\n result := mysolve(subsop(1=NULL,constraints), _rest);\n if result <> NULL\n and op(1,constraints) :: 'anything=anything'\n and simplify(eval(op([1,1],constraints) - op([1,2],constraints),\n result)) <> 0 then\n return NULL\n end if;\n result\n end proc;\n\n # A debugging utility that's like `and` except it calls `userinfo` if there is\n # disagreement\n export and_info := proc(e :: {list,set})\n local s, r;\n s, r := selectremove(evalb, e);\n if nops(r) = 0 then return true end if;\n if nops(s) > 0 then userinfo(op([_rest, s, r])) end if;\n return false;\n end proc;\n\n # Simplifies relations using `Logic:-Normalize' and places the result in a\n # canonical form. The input can be {and,not,or} but the output is always\n # {And,Or,Not}.\n # - false, true are expressed as And and Or\n # - When `norty' is DNF/CNF then the outer constructor is always Or/And\n #\n # TODO:\n # A better interface for `simpl_relation` - something that allows it to treat\n # arbitrary constructor forms as And, Or, Not. Typically, we do a `subs` right\n # before the call to `simpl_relation` to put things in the right form, then\n # another `subs` immediately inside `simpl_relation` to turn `And,Or` into `&and,&or`.\n export simpl_relation :=\n proc( expr_ :: {relation, boolean, specfunc({`And`,`Not`,`Or`}), `and`, `not`, `or`}\n , { norty := 'DNF' }\n , $) :: { specfunc(specfunc({Relation, specfunc(relation, Not)}, `Or`), `And`)\n , specfunc(specfunc({Relation, specfunc(relation, Not)}, `And`), `Or`)\n };\n local expr := expr_, outty, outmk, inty, inmk, ty_ord ;\n\n # Necessary because we convert `And' (etc.) to `Logic:-&and' (etc.), and\n # e.g. `Logic:-&and(a<b,c<d)' is not a valid piecewise condition.\n expr := chillFns('piecewise', expr);\n\n expr := foldr( proc(v,e) subsindets(e, op(v)) end proc\n , expr\n , [ { specfunc(relation, `Not`), `not`(relation) }\n , x-> negate_rel(op(1,x)) ]\n , [ { specfunc(`Not`), `not` }\n , x->Logic:-`¬`(op(1,x)) ]\n , [ { specfunc(`Or`), `or` }\n , x->Logic:-`&or`(op(x)) ]\n , [ { specfunc(`And`), `and` }\n , x->Logic:-`&and`(op(x)) ] );\n expr := Logic:-Normalize(expr, form=norty);\n expr := foldr( proc(v,e) subsindets(e, op(v)) end proc\n , expr\n , [ specfunc(Logic:-`&and`), x->`And`(op(x)) ]\n , [ specfunc(Logic:-`&or`) , x->`Or`(op(x)) ]\n , [ specfunc(Logic:-`¬`), x->negate_rel(op(1,x)) ] );\n\n if expr :: identical(false) then\n return `if`(norty='DNF', `Or`(), `And`(`Or`()));\n elif expr :: identical(true) then\n return `if`(norty='DNF', `Or`(`And`()), `And`());\n end if;\n\n ty_ord := `if`(norty='DNF', [1,2], [2,1]);\n outty, inty := [ 'specfunc(Or)', 'specfunc(And)' ][ty_ord][];\n outmk, inmk := [ `Or`, `And` ][ty_ord][];\n\n if not expr :: outty then expr := outmk(expr) end if;\n expr := map(x -> if not x :: inty then inmk(x) else x end if, expr);\n expr := warmFns('piecewise', expr);\n end proc;\n\n # Classify a relation by matching either the LHS or RHS against\n # a given predicate, and placing the relation in a canonical form\n # where the LHS (3rd component of the result) is the side matching\n # the predicate, or FAIL of neither side matches.\n export classify_relation := proc(r0::relation, vars0, $)\n ::{identical(FAIL), [identical(B_LO,B_HI,B_EQ,B_NEQ),\n satisfies(q->q in {indices(flip_relation,nolist)}),\n anything, anything]};\n local r_k, r_s, in_vars, vars := vars0, r := r0;\n if vars :: ({set,list})({name,list(name)}) then\n vars := map(x->`if`(x::list,op(1,x),x),vars);\n vars := {op(vars)}; in_vars := x->x in vars;\n elif vars :: procedure then\n in_vars := vars;\n elif vars :: type then\n in_vars := x->type(x,vars);\n else error \"unknown argument: %1 \"\n \"(expecting variables, variable membership check)\"\n , vars;\n end if;\n if r :: {`<=`,`<`, `=`, `<>`} then\n if in_vars(rhs(r)) then\n r_k := flip_relation[op(0,r)]; r_s := rhs(r), lhs(r);\n elif in_vars(lhs(r)) then\n r_k := op(0,r); r_s := op(r);\n else return FAIL end if;\n [ classify_relop[r_k], r_k, r_s ];\n else FAIL\n end if;\n end proc;\n local flip_relation := table([`=`=`=`,`<>`=`<>`,`<=`=`>=`,\n `<`=`>`,`>=`=`<=`,`>`=`<`]);\n local classify_relop := table([`=`=B_EQ,`<>`=B_NEQ,`<=`=B_HI,\n `<`=B_HI,`>=`=B_LO,`>`=B_LO]);\n\n # Functionalized, curried `if' statement\n export Case :=\n proc(ty,f,g)\n proc(x)\n if x::ty then f(x) else g(x) end if\n end proc\n end proc;\n\n # A replacement for `coulditbe .. assuming ..' which uses `is' internally\n # (since `is' is actually stronger than `coulditbe'); tries to handle `Or`s\n # correctly (which don't do well with `assuming'); and catches some exceptions\n # which we are reasonably sure have a valid interpretation.\n local do_rel_coulditbe := proc(a,as_::{set,list,Relation},$)\n option remember, system;\n local os, rs, as := as_;\n if as::{set,list} then\n as := And(op(as));\n end if;\n as := simpl_relation(as,norty='DNF');\n\n if nops(as)=1 then\n try\n not(is(bool_Not(a)) assuming op(1,as));\n catch \"when calling '%1'. Received: 'contradictory assumptions'\" :\n # technically this means the KB was already contradictory, we\n # just didn't know?\n return false;\n catch \"when calling '%1'. Received: \"\n \"'side relations must be polynomials in\"\n \" (name or function) variables'\":\n # This is seemingly a Maple bug - the condition could still be, but we\n # don't know, so conservatively return true.\n WARNING( sprintf( \"siderels bug:\\n\\t'%s'\\n\"\n \"when calling coulditbe(%%1) assuming (%%2)\"\n , StringTools[FormatMessage](lastexception[2..-1])),\n a, as_ );\n return true;\n catch \"when calling '%3'. Received: \"\n \"'when calling '%2'. Received: \"\n \"'expression independent of, %0''\":\n error expr_indp_errMsg(), a, as_;\n catch \"when calling '%2'. Received: 'expression independent of, %0'\":\n error expr_indp_errMsg(), a, as_;\n end try;\n else\n ormap(o1->rel_coulditbe(a,o1)=true, as);\n end if;\n end proc;\n\n local expr_indp_errMsg := proc($)\n sprintf(\"Something strange happened(%s)\\n\"\n \"\\tin coulditbe(%%1) assuming %%2\"\n ,StringTools[FormatMessage](lastexception[2..-1]))\n end proc;\n\n # Given a symmetric relation `x0', applies `test' the operands of the relation\n # in a symmetric manner. If it succeeds, returns `x0' with the side satisifying\n # `test' on the left-hand. If neither side satisfies `test', returns FAIL.\n # e.g.:\n # is_lhs(x=3, (a,_)->type(a,integer)) = 3=x\n # is_lhs(x=3, (a,_)->type(a,name)) = x=3\n # is_lhs(x=3, (a,_)->type(a,complex)) = FAIL\n export is_lhs := proc(test,x)\n if test(lhs(x), rhs(x),_rest) then return x end if;\n if test(rhs(x), lhs(x),_rest) then return op(0,x)(rhs(x),lhs(x)) end if;\n FAIL;\n end proc;\n\n # `curry(chillFns,foo)' is the function which converts all occurences of\n # `foo(as)' to `f[as]' in the given expression. `warmFns' is the inverse.\n #\n # For some reason making these curried also requires `KB:-chill' and\n # `KB:-warm' to be eta-expanded (i.e. `chill := x->chillFns(chilled)(x)')\n export chillFns := (fns, e) -> subsindets(e, 'specfunc'(fns), c->op(0,c)[op(c)]);\n export warmFns := (fns, e) -> subsindets(e, 'specindex'(fns), c->map(curry(warmFns,fns), op(0,c)(op(c))));\n\n # Print profiling information for a function when `infolevel' for that\n # function is set to at least 3, and assertlevel>0; e.g.\n # > do_func := proc() .. func .. end: func := ProfileFn(do_func):\n # > infolevel[func] := 3:\n # > kernelopts(assertlevel) := 1:\n # > func(a,b,c);\n #\n # - profiling information is only printed for runs of the function\n # which use a minimum amount of time, bytesalloc, or bytesused\n # - setting infolevel >= 5 prints profiling information for all runs of the\n # function.\n # - less than a minimum amount of a resource consumed omits the actual usage\n # with both infolevel >= 3 < 5 and infolevel >= 5 (just \"less than <min>\"\n # is printed instead)\n # - profiling information is not printed for recursives calls of a function\n # (in other words, if a recursive function is profiled, only non-recursive\n # instances will have profiling attached)\n export ProfileFn := module()\n local get_prof := proc()\n [ time[real](), kernelopts(bytesalloc)/2^20, kernelopts(bytesused)/2^20 ];\n end proc;\n local ppr_prof1 := proc(m,a,nm,fmt0,$)\n local v,p,fmt;\n v,p,fmt := `if`(a>=m, [\"\",a,fmt0], [\"less than \",m,\"%a\"])[];\n cat(v,sprintf(fmt,p),\" \",nm);\n end proc;\n local ppr_prof := proc(min_t, t, nms, $)\n local prefix, prefixl, strs;\n prefix := \"took \"; prefixl := length(prefix);\n strs :=\n zip_k(ppr_prof1, min_t, t, nms);\n cat(op(\n ListTools:-Interleave(\n [\"\\n\\t\"$nops(strs)],\n [prefix,cat(\" \"$prefixl)$(nops(strs)-1)],\n strs)));\n end proc;\n export ModuleApply :=\n proc(fn,min_t:=0.1,min_ba:=100,min_bu:=100)\n proc()\n local t, min_prof, profs, res, ctx, fncall;\n if kernelopts(assertlevel) > 0 and\n not (assigned(_Env_ProfileFn_inside[fn])) and\n assigned(infolevel['procname']) and\n infolevel['procname'] >= 3\n then\n _Env_ProfileFn_inside[fn] := true;\n t[0] := get_prof();\n res := fn(args);\n t[1] := get_prof();\n t[2] := zip(`-`,t[1],t[0]);\n ctx := map(op@getassumptions,indets([fn,args],Name));\n fncall := sprintf(\"%a(%q)\",'procname',args);\n ctx := sprintf(\"assuming (%q)\", op(ctx));\n min_prof := [min_t,min_ba,min_bu];\n profs := ppr_prof(min_prof, t[2],\n [[\"seconds\",\"%.3f\"],\n [\"MiB alloc\", \"%.3f\"],\n [\"MiB total used\", \"%.3f\"]]);\n userinfo(`if`(`or`(zip(`>`,t[2], min_prof)[]),3,5),\n 'procname',\n printf(\"Evaluating\\n\\t%s\\n\\t%s%s\\n\",fncall,ctx,profs));\n res;\n else\n fn(args)\n end if;\n end proc;\n end proc;\n end module;\n\n export rel_coulditbe := ProfileFn(do_rel_coulditbe, 1);\n\n # The closure of `f:set->set' with respect to `x:set'. That is, all values\n # which are outputs of `f' applied to `x' or an output of `f'.\n export cl := proc(f,x,$)\n local rs := f(x) minus x;\n if rs={} then x else cl(f,rs) union x end if;\n end proc;\n\n # The first `n' elements of a list, or the entire list if it has fewer than\n # `n' elements.\n export take := proc(xs,n,$)\n op(1,[ListTools[LengthSplit](xs,n)]);\n end proc;\n\n # A copy of `:-profile' with\n # - better pretty printing of the result\n # - bug fix for the fact that multiple names of sub-modules with the same\n # 'root' name cannot be profiled (e.g. M1:-x and M2:-x, commonly an issue\n # with ModuleApply)\n # - automatic collection of the names present in the Hakaru library\n # To profile `f(as)', call `Profile(f,_args=[as])'. Profiling information\n # if printed to stdout\n # Extra arguments to `Profile' are passed to `GetProf' and `PPrProf', which\n # determine which stats to profile and how to pretty print profiling\n # information.\n # Environment variables affecting this function:\n # _Env_Profile_count_ppr = number of profiled names to print\n # _Env_Profile_remove_ppr = selector function (: name->bool) to omit\n # certain names from the profiling output\n export Profile := module()\n option package;\n export ModuleApply, GetProf, PPrProf, modules_to_profile, names_to_profile;\n local ModuleLoad, profile_flag_to_ord, name_to_string;\n\n modules_to_profile := proc()\n kernelopts(opaquemodules=false):\n { 'BindingTools'\n # , 'Hakaru'\n , 'KB'\n , 'Partition'\n , 'Partition:-Simpl'\n , 'Loop'\n , 'Domain'\n # , 'NewSLO'\n , 'NewSLO:-fromLO'\n , 'NewSLO:-toLO'\n , 'NewSLO:-reduce'\n , 'NewSLO:-reduce_Integrals'\n , 'NewSLO:-reduce_Partition'\n , 'NewSLO:-simplify_factor_assuming'\n , 'Summary'\n , entries(Domain:-Improve:-Simplifiers, nolist)\n };\n end proc;\n\n names_to_profile := proc()\n option remember, system;\n local ns;\n kernelopts(opaquemodules=false):\n ns := cl(curry(map,x->CodeTools:-Profiling:-getMemberFuncs(x,true)),\n modules_to_profile());\n map(proc(n)\n if n::`module`('ModuleApply') then 'n[ModuleApply]' elif n::procedure then n else NULL end if\n end proc, ns);\n end proc;\n\n name_to_string := (x->convert(x,'string'));\n\n profile_flag_to_ord := table(\n ['alpha' = (proc (a, b) lexorder(a[1],b[1]) end proc)\n ,'ralpha' = (proc (a, b) not lexorder(a[1],b[1]) end proc)\n ,'time' = (proc (a, b) evalb(a[4] < b[4]) end proc)\n ,'rtime' = (proc (a, b) evalb(b[4] < a[4]) end proc)\n ,'bytes' = (proc (a, b) evalb(a[6] < b[6]) end proc)\n ,'rbytes' = (proc (a, b) evalb(b[6] < a[6]) end proc)\n ,'load' = (proc (a, b) evalb(a[6]*a[6]*a[4] < b[6]*b[6]*b[4]) end proc)\n ,'rload' = (proc (a, b) evalb(b[6]*b[6]*b[4] < a[6]*a[6]*a[4]) end proc)\n ]);\n\n GetProf := proc(fns::({list,set})(satisfies(x->member(x,:-profile_profiled)))\n ,{_flag:='rload'}\n )\n local i, totaltime, totalbytes, totaldepth, totalcalls, timepc, bytespc, numargs, displist, totaltimepc, totalbytespc\n , ix, get_timepc, get_bytespc, get_nm, nm, flag ;\n global profile_time, profile_bytes, profile_maxdepth, profile_calls, profile_profiled;\n\n flag := _flag;\n totaltime, totalbytes, totalcalls, totaldepth := 0$4;\n numargs := nops(fns);\n\n for i to nops(profile_profiled) do\n ix := name_to_string(profile_profiled[i]);\n totaltime := totaltime+profile_time[ix];\n totalbytes := totalbytes+profile_bytes[ix];\n totalcalls := totalcalls+profile_calls[ix];\n totaldepth := totaldepth+profile_maxdepth[ix];\n end do;\n\n if totaltime = 0 then\n get_timepc := i->0;\n totaltimepc := 0;\n else\n get_timepc := i->100*profile_time[name_to_string(profile_profiled[i])]/totaltime;\n totaltimepc := 100;\n end if;\n for i to nops(profile_profiled) do\n timepc[name_to_string(profile_profiled[i])] := get_timepc(i);\n end do;\n\n if totalbytes = 0 then\n get_bytespc := i->0;\n totalbytespc := 0;\n else\n get_bytespc := i->100*profile_bytes[name_to_string(profile_profiled[i])]/totalbytes;\n totalbytespc := 100;\n end if;\n for i to nops(profile_profiled) do\n bytespc[name_to_string(profile_profiled[i])] := get_bytespc(i);\n end do;\n\n displist := [];\n if 0 < numargs then\n get_nm := i->op(i,fns);\n else\n numargs := nops(profile_profiled);\n get_nm := i->profile_profiled[i];\n end if;\n for i to numargs do\n nm := get_nm(i); ix := name_to_string(nm);\n displist := [op(displist),\n [nm, map(q->q[ix],[profile_maxdepth, profile_calls,\n profile_time, timepc, profile_bytes, bytespc])[] ]];\n end do;\n\n displist := sort(displist, profile_flag_to_ord[flag]);\n displist, [totaldepth,totalcalls,totaltime,totaltimepc,totalbytes,totalbytespc];\n end proc;\n\n PPrProf := proc(dat,tot,{_max_name_len:=55,_prof_name:=`function`})\n local i, k, pr_nm;\n k := _max_name_len; pr_nm := _prof_name;\n\n printf(cat(pr_nm,(\" \"$k-StringTools[Length](convert(pr_nm,string))),\n `depth calls time time%% `));\n printf(` bytes bytes%%\\n`);\n printf(cat(\"--\"$k+1,`\\n`));\n for i from 1 to nops(dat) do\n printf(cat(`%-`,convert(k,string),`a%7d%9d%9.3f%9.2f%14d%9.2f\\n`),\n op(1..7,dat[i]));\n end do;\n printf(cat(\"--\"$k+1,`\\n`));\n printf(cat(`%-`,convert(k,string),`a%7d%9d%9.3f%9.2f%14d%9.2f\\n\\n`),\n `total:`,op(1..6,tot));\n return NULL\n end proc;\n\n ModuleApply := proc(f,{_args:=[]})\n local names_prof, res, nppr, rm_ppr, prf, tot, as; as := _args;\n if assigned(_Env_Profile_count_ppr) then\n nppr := _Env_Profile_count_ppr;\n else nppr := 25; end if;\n if assigned(_Env_Profile_remove_ppr) then\n rm_ppr := _Env_Profile_remove_ppr;\n else rm_ppr := (x->andmap(q->op(q,x)<0.001,[3,4,6])); end if;\n\n unprofile();\n names_prof := names_to_profile();\n profile(op(names_prof));\n if f::string then res := NULL; read(f);\n else res := f(op(as)); end if;\n prf, tot := GetProf(names_prof,_rest);\n unprofile();\n prf := remove(rm_ppr, prf);\n PPrProf(take(prf,nppr),tot,_rest);\n res;\n end proc;\n\n ModuleLoad := proc($)\n unprotect(:-convert);\n :-convert := overload([proc(x::name,_::identical(string),$) option overload(callseq_only); sprintf(\"%a\",x) end proc\n ,:-convert]);\n protect(:-convert);\n NULL;\n end proc;\n ModuleLoad();\n end module;\n\n local ModuleLoad := proc($)\n BindingTools:-load_types_from_table(\n table(\n [(Relation=\n ''{`::`, boolean, `in`, specfunc(anything,{Or,Not,And})}'')\n ,(Name = 'And(name, Not({constant,undefined}))')\n ]));\n end proc;\n ModuleLoad();\nend module;\n", "meta": {"hexsha": "49337f6badbb2fe57b837e35ad002311415fa93a", "size": 25789, "ext": "mpl", "lang": "Maple", "max_stars_repo_path": "maple/Utilities.mpl", "max_stars_repo_name": "vmchale/hakaru", "max_stars_repo_head_hexsha": "78922e13876e449d6812a55a11bf84c8eb0af4d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-03T08:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:12:06.000Z", "max_issues_repo_path": "maple/Utilities.mpl", "max_issues_repo_name": "vmchale/hakaru", "max_issues_repo_head_hexsha": "78922e13876e449d6812a55a11bf84c8eb0af4d6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 155, "max_issues_repo_issues_event_min_datetime": "2015-05-05T17:57:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:43:39.000Z", "max_forks_repo_path": "maple/Utilities.mpl", "max_forks_repo_name": "vmchale/hakaru", "max_forks_repo_head_hexsha": "78922e13876e449d6812a55a11bf84c8eb0af4d6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2015-01-23T16:25:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T15:09:12.000Z", "avg_line_length": 39.4327217125, "max_line_length": 123, "alphanum_fraction": 0.5738880918, "num_tokens": 7724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889433, "lm_q2_score": 0.042722192671187154, "lm_q1q2_score": 0.010104492683124515}}
|