File size: 17,834 Bytes
5697766
 
1
2
3
{"text": "# Teach Maple (through depends and eval) about our new binding forms.\n# Integrand and LO bind from 1st arg to 2nd arg.\n\n`depends/Integrand` := proc(v, e, x) depends(e, x minus {v}) end proc:\n`depends/LO`        := proc(v, e, x) depends(e, x minus {v}) end proc:\n\n`eval/Integrand` := proc(e, eqs)\n  local v, ee;\n  v, ee := op(e);\n  eval(op(0,e), eqs)(BindingTools:-generic_evalat(v, ee, eqs))\nend proc:\n\n`eval/LO` := proc(e, eqs)\n  local v, ee;\n  v, ee := op(e);\n  eval(op(0,e), eqs)(BindingTools:-generic_evalat(v, ee, eqs))\nend proc:\n\n#############################################################################\n\nNewSLO := module ()\n  option package;\n  local\n        t_sum, t_product,\n        mysolve, Shiftop, Diffop, Recognized,\n        bind, weight,\n        reduce_IntsSums, reduce_Integrals,\n        elim_intsum, int_assuming, sum_assuming,\n        banish, isBound_IntsSums, isBound_IntSum,\n        mk_sym, mk_ary, mk_idx, innermostIntSum, ChangeVarInt, SimplifyKB_,\n        ModuleLoad;\n  export\n     # These first few are smart constructors (for themselves):\n         integrate, applyintegrand,\n     # while these are \"proper functions\"\n         RoundTrip, Simplify, SimplifyKB,  apply_LO,\n         TestSimplify, TestHakaru, TestDisint, Efficient, TestEfficient,\n         Concrete,\n         toLO, fromLO, improve, reduce,\n         density, bounds, unweight,\n\n     # Like simplify_assuming, but also applies `hack_Beta` and `eval_factor`\n     # which helps some things simplify.\n         simplify_factor_assuming,\n\n         ReparamDetermined, determined, reparam, disint ;\n  # these names are not assigned (and should not be).  But they are\n  # used as global names, so document that here.\n  global LO, Integrand, SumIE, ProductIE;\n  uses Hakaru, KB, Loop, Partition, Domain, disint;\n\n  t_sum     := 'specfunc({sum    ,Sum    })';\n  t_product := 'specfunc({product,Product})';\n\n$include \"NewSLO/Interface.mpl\"\n$include \"NewSLO/To.mpl\"\n$include \"NewSLO/From.mpl\"\n$include \"NewSLO/Banish.mpl\"\n$include \"NewSLO/Improve.mpl\"\n$include \"NewSLO/Disint.mpl\"\n$include \"NewSLO/Reparam.mpl\"\n$include \"NewSLO/Factor.mpl\"\n\n  # This is for backwards compatibility; do not use them directly,\n  # instead use the symbols exported from inner modules of NewSLO\n  `integrate` := toLO:-integrate;\n  `unweight`  := fromLO:-unweight;\n\n  apply_LO := proc(e::specfunc(LO),f,$) unapply(op(2,e),op(1,e))(f) end proc;\n\n# An integrand h is either an Integrand (our own binding construct for a\n# measurable function to be integrated) or something that can be applied\n# (probably proc, which should be applied immediately, or a generated symbol).\n  applyintegrand := proc(h, x, $)\n    local var, body, dummy;\n    if h :: 'Integrand(name, anything)' then\n      var, body := op(h);\n      if x :: {boolean, specfunc({And,Or,Not})} then\n        body := eval(body, var=dummy);\n        var  := dummy;\n        body := subs((var=true)=var, body);\n      end if;\n      eval(body, var=x)\n    elif h :: appliable then\n      h(x)\n    else\n      'procname(_passed)'\n    end if\n  end proc;\n\n  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  ###\n  # smart constructors for our language\n\n  bind := proc(m, x, n, $)\n    if n = 'Ret'(x) then\n      m # monad law: right identity\n    elif m :: 'Ret(anything)' then\n      eval(n, x = op(1,m)) # monad law: left identity\n    else\n      'Bind(_passed)'\n    end if;\n  end proc;\n\n  weight := proc(p, m, $)\n    #Trying to make the below into an ASSERT statement results in a kernel\n    #crash, even though the condition is caught, the message printed, and\n    #the error generated.\n    if kernelopts(assertlevel) > 0 then\n         if not p::\n              (complexcons &implies ((numeric &implies {0,1}) &under csgn))\n         then\n              userinfo(\n                   1, SLO,\n                   proc()\n                   uses LL= ListTools:-LengthSplit;\n                   local\n                        S:= Matrix([LL(debugopts(callstack)[2..], 3)]),\n                        rts:= interface(rtablesize= infinity)\n                   ;\n                        print(S);\n                        interface(rtablesize= rts);\n                        NULL\n                   end proc()\n              );\n              error \"Negative weight %1 not allowed\", p\n         end if\n    end if;\n    if p = 1 then\n      m\n    elif p = 0 then\n      Msum()\n    elif m :: 'Weight(anything, anything)' then\n      weight(p * op(1,m), op(2,m))\n    else\n      'Weight(_passed)'\n    end if;\n  end proc;\n\n  density[Lebesgue] := proc(lo,hi,$) proc(x,$) 1 end proc end proc;\n  density[Uniform] := proc(a,b,$) proc(x,$)\n    1/(b-a)\n  end proc end proc;\n  density[Gaussian] := proc(mu, sigma, $) proc(x,$)\n    1/sigma/sqrt(2)/sqrt(Pi)*exp(-(x-mu)^2/2/sigma^2)\n  end proc end proc;\n  density[Cauchy] := proc(loc, scale, $) proc(x,$)\n    1/Pi/scale/(1+((x-loc)/scale)^2)\n  end proc end proc;\n  density[StudentT] := proc(nu, loc, scale, $) proc(x,$)\n    GAMMA((nu+1)/2) / GAMMA(nu/2) / sqrt(Pi*nu) / scale\n    * (1 + ((x-loc)/scale)^2/nu)^(-(nu+1)/2)\n  end proc end proc;\n  density[BetaD] := proc(a, b, $) proc(x,$)\n    x^(a-1)*(1-x)^(b-1)/Beta(a,b)\n  end proc end proc;\n  # Hakaru uses the alternate definition of gamma, so the args are backwards\n  density[GammaD] := proc(shape, scale, $) proc(x,$)\n    x^(shape-1)/scale^shape*exp(-x/scale)/GAMMA(shape);\n  end proc end proc;\n  density[InverseGammaD]:= proc(shape, scale, $)\n       proc(x,$) scale^shape/GAMMA(shape)/x^(shape+1)/exp(scale/x) end proc\n  end proc;\n  density[Counting] := proc(lo, hi, $) proc(k,$)\n    1\n  end proc end proc;\n  density[Categorical] := proc(a, $) proc(k,$)\n    idx(a,k)\n  end proc end proc;\n  density[Binomial]:= proc(n,p,$)\n       proc(k,$) p^k*(1-p)^(n-k)*GAMMA(n+1)/GAMMA(k+1)/GAMMA(n-k+1) end proc\n  end proc;\n  density[NegativeBinomial] := proc(r, p, $) proc(k,$)\n    p^k * (1-p)^r * GAMMA(r+k) / GAMMA(k+1) / GAMMA(r)\n  end proc end proc;\n  density[PoissonD] := proc(lambda, $) proc(k,$)\n    lambda^k/exp(lambda)/k!\n  end proc end proc;\n  density[ChiSquared] := proc(k, $) proc(x,$)\n    x^((1/2)*k-1)*exp(-(1/2)*x)/(2^((1/2)*k)*GAMMA((1/2)*k))\n  end proc end proc:\n\n  bounds[Lebesgue] := `..`;\n  bounds[Uniform] := proc(a, b, $) a .. b end proc;\n  bounds[Gaussian] := proc(mu, sigma, $) -infinity .. infinity end proc;\n  bounds[Cauchy] := proc(loc, scale, $) -infinity .. infinity end proc;\n  bounds[StudentT] := proc(nu, loc, scale, $) -infinity .. infinity end proc;\n  bounds[BetaD] := proc(a, b, $) 0 .. 1 end proc;\n  bounds[GammaD] := proc(shape, scale, $) 0 .. infinity end proc;\n  bounds[InverseGammaD]:= proc(shape, scale, $) 0..infinity end proc;\n  bounds[Counting] := proc(lo, hi, $) lo..hi-1 end proc;\n  bounds[Categorical] := proc(a, $) 0 .. size(a)-1 end proc;\n  bounds[Binomial]:= proc(n,p,$) 0..n end proc;\n  bounds[NegativeBinomial] := proc(r, p, $) 0 .. infinity end proc;\n  bounds[PoissonD] := proc(lambda, $) 0 .. infinity end proc;\n  bounds[ChiSquared] := proc(k, $) 0 .. infinity end proc;\n\n  mk_sym := proc(var :: name, h, $)\n    local x;\n    x := var;\n    if h :: 'Integrand(name, anything)' then\n      x := op(1,h);\n    elif h :: 'procedure' then\n      x := op(1, [op(1,h), x]);\n    end if;\n    gensym(x)\n  end proc;\n\n  mk_ary := proc(e, loops :: list(name = range), $)\n    foldl((res, i) -> ary(op([2,2],i) - op([2,1],i) + 1,\n                          op(1,i),\n                          eval(res, op(1,i) = op(1,i) + op([2,1],i))),\n          e, op(loops));\n  end proc;\n\n  mk_idx := proc(e, loops :: list(name = range), $)\n    foldr((i, res) -> idx(res, op(1,i) - op([2,1],i)),\n          e, op(loops));\n  end proc;\n\n  ModuleLoad := proc($)\n    local prev, ex;\n    ModuleUnload();\n    Hakaru; # Make sure the Hakaru module is loaded for the types t_type and t_Hakaru.\n    KB;     # Make sure the KB module is loaded, for the type t_kb\n    prev := kernelopts(opaquemodules=false);\n    try\n      PiecewiseTools:-InertFunctions := PiecewiseTools:-InertFunctions\n        union '{# Do not lift piecewise over a binder\n                Integrand,LO,lam,Branch,Bind,ary,Plate,\n                forall,Ints,Sums,ints,sums,`..`}';\n    catch:\n         userinfo(\n              1, NewSLO,\n              \"Redefinition of PiecewiseTools:-InertFunctions failed.\",\n              StringTools:-FormatMessage(lastexception[2..-1])\n         )\n    finally\n      kernelopts(opaquemodules=prev);\n    end try;\n\n    for ex in [ [`Int`,isBound_IntSum], [`Sum`,isBound_IntSum]\n              , [`Ints`,isBound_IntsSums], [`Sums`,isBound_IntsSums] ] do\n      Domain:-Set_ExtBound(op(1,ex), op(2,ex)(op(1,ex)));\n    end do;\n\n    for ex in [ [`PARTITION`, Partition:-isShape] , [ 'piecewise', Partition:-isShape] ] do\n      Domain:-Set_ExtShape(op(1,ex), op(2,ex)(op(1,ex)));\n    end do;\n\n  end proc; #ModuleLoad\n  ModuleLoad():\nend module; # NewSLO\n", "meta": {"hexsha": "8a363af91e1e60de2e663627d85d26c39e92b4ce", "size": 9949, "ext": "mpl", "lang": "Maple", "max_stars_repo_path": "maple/NewSLO.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/NewSLO.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/NewSLO.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.7877697842, "max_line_length": 120, "alphanum_fraction": 0.5858880289, "num_tokens": 3076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23960216046857674}}
{"text": "# Class: Event\n#\n# Description:\n#  Implementation of events -- a real algebraic number and list of associated quadrics.\n#\n# Author:\n#  Kacper Pluta - kacper.pluta@esiee.fr\n#  Laboratoire d'Informatique Gaspard-Monge - LIGM, A3SI, France\n#\n# Date:\n#  29/12/2016\n#\n# License:\n#  Simplified BSD License\n#\n# Copyright (c) 2016, Kacper Pluta\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#   * Redistributions of source code must retain the above copyright\n#     notice, this list of conditions and the following disclaimer.\n#   * Redistributions in binary form must reproduce the above copyright\n#     notice, this list of conditions and the following disclaimer in the\n#     documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL Kacper Pluta BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nEventType := module()\n  option object;\n   \n  (*Real Algebraic Number*)\n  local ranum::RealAlgebraicNumber;\n  \n  (*List of indices of associeted quadrics*)\n  local quadrics::list;\n\n\n# Method: ModuleCopy\n#   Standard constructor / copy constructor\n#\n# Parameters:\n#   self::EventType                   - a new object to be constructed\n#   proto::EventType                  - a prototype object from which self is derived\n#   ranum::RealAlgebraicNumber    - a real algebraic number\n#   quadrics::rational            - a list of indices which corresponds to associated quadrics\n#\n# Output:\n#   An object of type RealAlgebraicNumber.\n#\n# Exceptions:\n#  \"Invalid range. A range is valid when: a <= b.\"\n#  \"Degree of %1 is invalid.\"\n#\n  export ModuleCopy::static := proc( self::EventType,\n                                     proto::EventType,\n                                     ranum::RealAlgebraicNumber,\n                                     quadrics::list, $ )\n    if _passed = 2 then\n      self:-ranum := proto:-ranum;\n      self:-quadrics := proto:-quadrics;\n    else\n      self:-ranum := ranum;\n      self:-quadrics := quadrics;\n    fi;\n  end proc;\n\n\n# Method: ModulePrint\n#   Standard printout of an object of type EventType.\n#\n# Parameters:\n#   self::EventType                  - an event\n#\n  export ModulePrint::static := proc( self::EventType )\n   nprintf(\"(%a, %a)\", self:-ranum, self:-quadrics); \n  end proc;\n\n\n# Method: ModuleApply\n#   Define standard constructor.\n#\n  export ModuleApply::static := proc()\n   Object(EventType, args)\n  end proc;\n\n\n# Method: ModuleDeconstruct\n#   Provides information how to recreate an object after being serialized.\n#\n# Parameters:\n#   self::EventType                  - an event\n#\n  export ModuleDeconstruct::static := proc( self::EventType )\n    ('EventType')(('RealAlgebraicNumber')(GetPolynomial(self:-ranum), GetInterval(self:-ranum)[1],\n    GetInterval(self:-ranum)[2]), self:-quadrics)\n  end proc;\n\n# Method: GetRealAlgebraicNumber\n#   Getter of the real algebraic number.\n#\n# Parameters:\n#   self::EventType                  - an event\n# Output:\n#   Associated real algebraic number.\n  export GetRealAlgebraicNumber::static := proc(self::EventType)\n    return self:-ranum;\n  end proc;\n\n\n# Method: GetQuadrics\n#   Getter of the list of indices.\n#\n# Parameters:\n#   self::EventType                  - an event\n# Output:\n#   Associated quadrics' indices.\n  export GetQuadrics::static := proc(self::EventType)\n    return self:-quadrics;\n  end proc;\n\n\n# Method: Compare\n#   A method used to compare two events.\n#\n# Parameters:\n#   l::EventType      - an event\n#   r::EventType      - an event\n#\n# Output:\n#   -1 when l is smaller than r, 0 when they are equal and 1 when l is bigger than r.\n#\n  export Compare::static := proc( l::EventType, r::EventType, $ )\n    return RealAlgebraicNumber:-Compare(l:-ranum, r:-ranum);\n  end proc;\n\nend module;\n\n", "meta": {"hexsha": "7aff34d236ac27810b715906c655f7598be1a09a", "size": 4513, "ext": "mpl", "lang": "Maple", "max_stars_repo_path": "RigidMotionsParameterSpaceEvent.mpl", "max_stars_repo_name": "copyme/MapleTools", "max_stars_repo_head_hexsha": "7491d0d2cab715e2dd984ce7ba0fb8db46cbe73f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RigidMotionsParameterSpaceEvent.mpl", "max_issues_repo_name": "copyme/MapleTools", "max_issues_repo_head_hexsha": "7491d0d2cab715e2dd984ce7ba0fb8db46cbe73f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2016-04-14T11:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T13:48:01.000Z", "max_forks_repo_path": "RigidMotionsParameterSpaceEvent.mpl", "max_forks_repo_name": "copyme/MapleTools", "max_forks_repo_head_hexsha": "7491d0d2cab715e2dd984ce7ba0fb8db46cbe73f", "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": 30.4932432432, "max_line_length": 98, "alphanum_fraction": 0.6800354531, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2057658573258315}}