Got a fresh wind on Knuckledragger https://www.kdrag.com https://github.com/philzook58/knuckledragger , my shallow z3 proof assistant as a python library.
TLDR:
- Autoformalized Halmos Naive Set Theory and 1/2 of AbbottβsUnderstanding Analysis . This is the least surprising thing AI has demonstrated in the last year, but good to know whatβs possible.
- New formula and goal pretty printer. Holy shit, itβs so much better. I should have prioritized this way earlier. It look like this:
aβ bβ cβ : β€ β β
xβ Ξ΅β : β
Nβ Nβ : β€
0: βn : β€, n β₯ 0 β aβ[n] β€ cβ[n] β§ cβ[n] β€ bβ[n]
1: βn : β€, n > Nβ β |aβ[n] - xβ| < Ξ΅β
2: βn : β€, n > Nβ β |bβ[n] - xβ| < Ξ΅β
3: Ξ΅β > 0
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β’ βn : β€, n > (if Nβ β₯ Nβ then Nβ else Nβ) β |cβ[n] - xβ| < Ξ΅β
- Auto suggest lemmas on failure via tf-idf on symbols
- Theorem search andjupyterlite examples in docs
- More cleanup and syntactic niceties
- Wired in cvc5, eprover, vampire as available by default, although they are basically not that useful overtop z3 (see below).
- https://github.com/philzook58/knuckledragger/pull/89#issuecomment-7068674786 expandable proof traces in PRs
- Playing around with using manim. I think this is more flashy than it is educational or useful.
I had kind of been off Knuckledragger for 6 months.
I had been trying to do things adjacent to Knuckledragger at work, using it for binary verification and TLA model validation, but that project was cancelled (which feels ironic given the recent hype cycle that occurred only months later). It was very draining to try and manually apply knuckledragger to these gnarly awful symbolic execution goals, so I think that drained enthusiasm
This past week has also been very tough in regards to AI news (the Riemann hypothesis thing). I was in full non stop panic mode for about 5 days, but now Iβm coming out of it I think. I wonder if you weighed benefits to society of current AI against the mental health toll and demotivation youβd come out ahead or not. Personally, I think it is a net negative because the trends and uncertainty make me so stressed and sad.
I got a little pep in my step just setting up PyPI packages for vampire and eprover as a treat. There is something that really excites me about having something packaged on PyPI or available in WASM. It is a totally irrational nerd impulse and Iβm grateful for it. Joy is good.
So I replaced my nasty build scripts that nobody had ever used with these dependencies and then one thing led to another with more cleanups, features and stuff as I said above.
Why Knuckledragger? #
You know, Knuckledragger is pretty fucking cool. And I donβt expect anybody to ever use it and that is fine.
Hereβs a question: how does one do or try anything when most new things fail? Donβt listen to me, Iβm depressed, and it is my explicit goal not to spread that. The point of life is to be happy and share it with others.
At the outset of Knuckledragger, I knew the project is on the face of it completely deluded. Lean was already hot by then, and there are a number of systems with decades of work by smart hardworking people in them.
I have found that regardless how the world changes or the news cycle, I can come up with some new story about how it could make sense to build this thing. So I guess Iβm just building it because Iβm building it, not for some coherent constant reason.
At the beginning, I had just come off a project developing verification tooling for a hacker crowd and it was legitamately a major downside for our tooling to be in OCaml if that was our audience, in terms of their familarity with the ecosystem or language or willingness to type opam install.
So at one point, a hypothesis was that if I built knuckledragger, a different sort of community with a different sort of problems might be engaged. The kinds of people who are using matplotlib, scipy, numpy etc.
This has not born out and to my knowledge no one has ever used knuckledragger. I have not produced the necessary educational material so I donβt know how that would have magically happened anyway.
At another point, we thought that it might be that AI would be vastly superior at Python compared to other languages because of the larger dataset. AI has shown itself to be basically good at all languages. It does appear use little python snippets to achieve tasks? I do not expect AI to be superior at knuckledragger compared to Lean and Lean has a much better soundness story by design + comparator. The case for knuckledragger is close to vanishingly small
The biggest problem AI has right now in regards to verification is how to keep the human in the driver seat on top of the bucking bronco. How to funnel the mass of confusion to a simple thing the human tracks. Roughly, this is in the form of specs and the model, which the human needs to kind of check off on. Maybe a python native form of this is useful because many humans are currently good at python and I think this is partially because of an intrinsic friendliness of the system / language compared to some alternatives for many people (yeah yea yea, show me you weird variable binding examples or dense inscrutable walrus, mutation, comprehension examples, Fuck off.).
Building knuckledragger has been one of the most educational and fun projects Iβve ever done. Iβve learned so much more about logic and have a way better context for discussions about how other systems work. That is a reason to build it, but that is not a reason for anyone else to use it.
I have always found it interesting and educational to strip out complexity. Many quantum phenomenon have classical counterparts, continuous or infinite have finite counterparts, noncomputational stuff has computational, etc. A good method for understanding and solving is to strip out so much complexity that it becomes really trivial and then if you still care you can try and put the complexity back in. There is a quote about βmake explanations as simple as possible, but no simplerβ, but I disagree. Completely mangle all nuance beyond recognition. Go simpler than is reasonable.
I do like having a system I understand the entirety of and can change anything about. That is not the case of Lean or Isabelle or Rocq. So maybe for some of you, I recommend you build your own knuckledragger more so than use mine. I do think the shallow smt design gets you far fast and I do wonder what kinds of idioms might be nice for embedding in other languages.
Surprising Lessons #
A happy accident in knuckledragger was when I early on switched from my own AST to just reusing Z3βs. This removed a lot of boiler plat.
At the same time, I have been very frustrated by the foundations of knuckledragger as z3 is missing notions or is not extensible in ways I wanted. Parametric types currently do not work at the level of thoroughness or correctness Iβd need them too to more closely hew to some of Isabelle or HOL-lightβs designs for abstractions (locales, typeclasses, etc). Trying to do it from the outisde is in principle possible, but self defeating in terms of bloat and reliability and wasted computational effort.
My current thinking though that this accidental restriction is kind of beautiful and the main draw to me of knuckledragger over other systems. You like canβt abstract, so you canβt be distracted or confused by it. Itβs kind of like C vs Haskell or something. C offers very low abstraction capabilities, so in the good case you just solve your actual problem and move on. Haskell is super fun and beautiful but more prone to abstraction naval gazing and eventually gains an inscrutable web of stacked concepts if you do not practice restraint. I mean, if you donβt practice restraint, youβll end up fucked in every system (or full AI I donβt understand anything about the code bankrupt, which might be the perfectly economically viable normal future).
I find it simpler, illuminating and intuitive to see how a problem can be formulated in simply typed higher order logic with built in Int, Real, and Bool than it is to see a problem formulated in dependent type theory using inductives. I donβt think I will ever not think those are less weird. All we really should have ever needed for normal math was second order arithmetic anyway right?
Another surprise was that external solvers has by an large been useless. Z3 is so good (but not perfect) that again the reliability, soundness, and slowness of shelling out to vampire or cvc5 has basically never been worth it except for fun. It is my policy that every z3 call should solve in ~1ms since I need to do a lot of them. This means that really the calls I make are pretty βeasyβ mostly and ones you expect not to have much delta between solvers anyhow.
Another frustration is that the python->C interop and the z3py rewrappings are slow slow slow slow (compared to even pure python AST manipulation). This is scary for the viability of knuckledragger because at a certain point, spelling out manual proof steps is more expensive than a z3 solver call. The nuclear option here is to eventually move more bulk operations like the kernel or rewriting into an external c++ or rust side car project. I think showing restraint here has thus far been the right move. It is a big jump in project complexity. If Knuckledragger becomes complex, it is self defeated. But also I should do whatever is fun for me.
The herband and skolem axiom schema for dealing with binders is kind of working pretty well despite being extremely dirty. I keep being tempted to add a context to my protected Proof judgement, but it just doesnβt seem worth it so far.
AI Thoughts #
So yea, I was trying to really keep a handle on using AI with knuckledragger. I was trying to make sure I understand and walked through every proof. It was excrutiatingly slow and really not that fun :( . Like, on one hand proving stuff sucks. Remembering the lemmas, realizing how many lemmas youβre missing when you start a problem that really youβd like to just take for granted. On the other hand, the process is a thing to do, a thing to be engaged with, and does add precision and missing understanding. I guarantee you will misformulate your theoremβs statements or even definitions all the time and only realize once you go to actually prove them.
I donβt really understand mathematicianβs math. I like literally canβt parse the homework problems in textbooks as an activity. I need the computer arbiter to agree that we are doing an activity that makes sense.
So I just let the thing loose and started burning tokens. One thing that helps me mentally is to keep the output in a different folder than what I was working on and have a handle on. I am keeping the ai output in kdrag.contrib and will move it if and when I understand it, which I may never do if it isnβt enriching or useful work.
AI feels like a tragedy because it is destroying the point to problems I thought were fun, but I only was in the equilibrium I was because of circumstances. Problems that were already completely solved I enjoyed mostly ignoring (like anything z3 can handle automatically). Having a useful library of lemmas to get to actually interesting physics or engineering problems was years away if it ever happened. So I guess Iβm thinking Iβll just put my foot on the gas and see where I end up. What is the new equilibrium?
On the other hand, it is so so emotionally draining to hear the news and also watch the thing use my system to prove a stream of theorems that I probably could do eventually, but at a rate 10000x what I can do.
I also see that the thing just plows through ergonomic issues that I would stop and fix. I am missing the opportunity to feel friction.
Ergonomics and UI are more important than ever. A possible pitch for Knuckledragger now is that AI can do all theorem proving if you donβt care about the details of it. We have basically perfect (minus efficiency) automated theorem provers available now. There is no prospect for for automated theorem provers to ever be superior to AI based systems ever again in terms of generality and flexibility.
It is possible that the basis in z3 means that Knuckledragger could be more token efficient. It is possible that human ergonomic ~ token efficient. Good error messages, difficult to do the wrong thing, traditional automation.
A better exact?
lim_lemma(ctx : list[var], e) It should be a contextual term yeah?
Do I also want the unfolded lim lemmas?
Hmm. So lean olean files are compiled and assumed trust by default. Makes perfect sense
a pickle cache in kernel?
thm.sepxr() might be espnsive too.
Itβs interesting how the naive definitions are probably the ones I want. Maybe specializing the abstract things to them Filter -> eventually
Generate C++ https://www.youtube.com/watch?v=ERemvvBxlxo . Yeah, why didnβt i try this? Too scared of C++
iunion
sunion
Revamp simp Wait, didnβt I have a rewrite set? Not as a named thing
class Simp: data : dict[FuncDeclRef, ]
get_implied_equalities + oritent according to depth and ground. -> substitute. Thatβd be kind of a nice simp
https://github.com/Copilot-Language/copilot use case of C backend https://ivorylang.org/ivory-fib.html
cast huh. bidirectioanl typing. cast ~ check? cast ~ ann? Why in the world is the sort first py2expr is synth (?)
py2sexpr -> (list[BoolRef], Expr) # a list of validity conditions?
synth(object) -> SortRef, ctx ~ {Int | x >= 0} ctx ~pre |- object ==> {Sort | post} check(object, ctx, SortRef) ~ β¦ Hmm. Thatβs kind of interesting. check(ctx, object, SortRef, post) ~ ctx |- object <== {Sort | post} ctx : list[Hyp | Var]
I can spec a recursive definition, but then need to prove it exists and then obtain ?
How could I prove such a thing though⦠?
elaboration inside Maybe I should really overload how Function works from scratch. Take over coerce Take over other things. Avoid redundant ctypes calls.
solve for metavars too? When do I actually care about that. Maybe vec operations?
, data : Seq(Real)
Model 2
kd.tuple(coord : Seq(Int) -> Int, : data : RSeq)
Tensor = Struct(coord)
coord : Seq(Int) -> Int, data : SeqSort(Real). dom is implicitly if coord(idx) is greater than data size or less than zero
Model 1 tensor = SeqSort(Int) -> Real Itβs total. Sry not sry I guess this is an assumed convention for casting? Or the assume convention is in the contruction. tesnro SeqSort(Int) -> Option(Real) SeqSort(Int) -> Real, dom : SetSort(SeqSort)
ones = K(, 1) zeros = K(, 0) matmul = # yikes
broadcasting. Weβre always broadcasting in infinite spaceβ¦
broadcast = Lambda([idx], A[thin(idx)]) tensor_eq = dom1 == dom2 & forall idx, dom1[idx] => data1[idx] == data2[idx]
Is there a point to all this?
resize()
[[shape]] = Set(SeqSort(Int)), not (Int,Int,Int). Thatβs a first order syntactic. Akin to Intervals as tuples vs sets
zeros(shape) = Lambda(idx, If(shape(idx), 0, undef_zeros(shape)))
matmul isnβt even sensical without sizes. Weβre assuming they are rank 2 now? Well, remora wants prefix broadcasting, so it pulls out 2 dims from each and
matmal(n,A,B) = Lambda(idx, Length(idx) >= 2, recdef of matmul , undef_matmul())
matmul(n, A, B) im2col conv
tensor = Index -> A
Do induction right with a ForAll(P, ) axiom. Also maybe swithc
Traces as Seq(Result). But thatβs only true for Int/Nat indexed stuff.
Seq(Unit) = Nat. Is that crazy? Yeah prob
Look at Tao examples O(n^3) etc
ass_eq(a,b,3) Oeq(a,b,3)
plazter
deriv(y) = f(y,t)
1d forall t, has_deriv_at(y, t, f(y,t)) => y = solution?
has_deriv_at(y,t,f(y,t)) => Safetyprop(y,t)
internalized
GAT facilitie
body = f <= Not(f)
not a => a is obviously not allowed. Hmm. So even => is not enough.
Might want to
Theorem([x,y,z], hyp1,hyp2) Theorem(ForAll([x,y,z], hyp1, hyp2))
When we close, maybe we want to always strip off the shitty ! of freshvar
Better get_lemma. Maybe get_lemma should start reporting it as an error.
x,y,z = fixes() # but this is repetitive usually h1,h2,h3 = intros() # not previously named
Things to copy rom other interesting tactics?
Take halmos and intersperse proofs
Analysis Open Texts euclidβs elements? Do symbolic exploration of a binary via z3 pathways? knuth spivak multivariable munkres, topology spivak axler hyperreals
constructive analysis - intervals traat
measure functional analysis? proof mining reverse mathematics
categories? manifolds exteriorir calculus complex anlaysis
Nand2tetris
kalman filters etc
ok
but what is it for then. I think holding suspecion of dispbelief is fine for now. But if Iβm not gonna look at it, why not lean? It is a little interesting to see fully concrete implementations without abstraction How to fomrulate Data set (although skewed because itβs using the tools as they exist)
Do videos on halmos? I did write the first stuff. Can I understand the later stuff? Maybe videos is an inspiration
iprove
class IProof thm
def check_inuitionistics(thm, **kwargs): return prove(thm,**kwargs)
One liners
= Lemma().fix(lambda x,y,z: l.auto()).qed()
Lemma().fix(lambda x,y,z: l.unfold(, )) forallI(2, lambda x, prove())
The exact tactic is pretty weird
move tele and contracts to junk
arbtitrary bitwidth as Int -> Bool
def fun(goal, k):
n = inspect.sginature(k)
herb, vars_and_hyps = _open_binder(goal, n)
pf = k(vars_and_hyp,s, newgoal)
return modus(pf, herb)
BoolRef.fun
foo = ForAll(x, x > 0).by(lemma1, lemma2)
Exists(x, x > 0).intro(17, 17 > 0) #.mk .sigma? I don't think we really need to offer the thing? It's inferrable
ForAll(x, x > 0).exact(lemma(a))
Domain specific vis? For just real analysis. There probably is some way to visualize eps-delta proofsβ¦
Outside the box thinking of ways to show me. Visualization? Using 3 blue 1 brown https://github.com/3b1b/manim
Does that actually help?
Theory of UI. affordances
Hammering toards QED https://www.cl.cam.ac.uk/~lp15/papers/Automation/h4qed-clean.pdf MePo SinE symbol counts + tf-idf
Maybe this is a totally different tact, but Iβve heard of and not understood the βwaterfall methodβ of acl2 / boyer moore https://github.com/samth/waterfall and not rwally understood what it is. Also Bundyβs rippling in reagrds to improving induction proving. And or help me learn about them?
is_finite_set (a) is_finite_set_sort (s) FiniteSetSort (elem_sort) FiniteSetEmpty (set_sort) Singleton (elem) FiniteSetUnion (s1, s2) FiniteSetIntersect (s1, s2) FiniteSetDifference (s1, s2 FiniteSetMember (elem, set) In (elem, set) FiniteSetSize (set) FiniteSetSubset (s1, s2) FiniteSetMap (f, set) FiniteSetFilter (f, set) FiniteSetRange (low, high)
from kdrag.all import *
from kdrag.theories.real import *
RSeqFSet = FiniteSetSort(RSeq)
or_ = kd.notation.or_.register(RSeqFSet, FiniteSetUnion)
and_ = kd.notation.and_.register(RSeqFSet, FiniteSetIntersect)
sub = kd.notation.sub.register(RSeqFSet, FiniteSetDifference)
le = kd.notation.le.register(RSeqFSet, FiniteSetSubset)
empty = FiniteSetEmpty(RSeqFSet)
def finset_induct(S, P):
S1 = FreshConst(RSeqSeq, prefix="S")
v = FreshConst(RSeq, prefix="v")
return axiom(Implies(
And(
P(empty),
ForAll([f, S], P(S1), Not(S[v]), P(Singleton(v) | S1))
))
P(S)
))
A = Const("A", RSeqFSet)
span = define("spac", A, Lambda(v, Exists(x, span(A)[v]))) # Set of vectors RSeqSet
is_basis = define("is_basis", ForAll(u,v,w))
from kdrag.all import *
from kdrag.theories.real import *
from kdrag.theories.real.seq import *
n = Int("n")
#in = Const("I", ArraySort(IntSort(),RSet))
a,b,c = Consts("a b c", RSeq)
x,y,z = Reals("x y z")
@PTheorem(ForAll([a,b, c, x],
ForAll(n, n >= 0, And(a[n] <= c[n], c[n] <= b[n])),
has_lim(a,x),
has_lim(b,x),
has_lim(c,x)))
def squeeze(l):
a,b,c,x = l.fixes()
l.unfold(has_lim)
squeeze, lima, limb = l.intros()
eps = l.fix()
eps_pos = l.intro()
l.specialize(lima, eps, eps_pos)
l.specialize(limb, eps, eps_pos)
N1 = l.obtain(1)
N2 = l.obtain(2)
N = If(N1 >= N2, N1, N2)
l.exists(N)
l.
Next Goal:
aβ bβ cβ : β€ β β
xβ Ξ΅β : β
Nβ Nβ : β€
0: βn : β€, n β₯ 0 β aβ[n] β€ cβ[n] β§ cβ[n] β€ bβ[n]
1: βn : β€, n > Nβ β |aβ[n] - xβ| < Ξ΅β
2: βn : β€, n > Nβ β |bβ[n] - xβ| < Ξ΅β
3: Ξ΅β > 0
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β’ βn : β€, n > (if Nβ β₯ Nβ then Nβ else Nβ) β |cβ[n] - xβ| < Ξ΅β
search("squeeze")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[17], line 1
----> 1 search("squeeze")
File ~/vibe_coding/knuckledragger/src/kdrag/utils.py:1435, in search(db, *es)
1433 results.append(search_expr(e, db))
1434 else:
-> 1435 raise ValueError("Unsupported type for search", e)
1436 return {k: v for k, v in results[0].items() if all(k in db for db in results)}
ValueError: ('Unsupported type for search', 'squeeze')
from kdrag.all import *
from kdrag.theories.real import *
from kdrag.theories.real.rset import *
n = Int("n")
#in = Const("I", ArraySort(IntSort(),RSet))
a,b = Consts("a b", RSeq)
x,y = Reals("x y")
@PTheorem(
ForAll([a, b], nested(I),
ForAll(n, n >= 0, a[n] <= b[n]),
Exists(x, iinter(I)[x]))
)
def nonempty_iinter_icc_of_nested(l):
a, b = l.fixes()
l.intros()
lower = Lambda(x, Exists(n, n >= 0, a[n] == x))
bounds = l.have(ForAll(m, m >= 0, is_ub(lower, b[m])))
j = l.fix()
l.intro()
l.unfold(is_ub)
point = l.fix()
l.beta()
member = l.intro()
k = l.obtain(member)
l.auto(by=[nested_icc_bounds(a, b, k, j)])
l.have(lower[a[0]], by=[])
l.have(Exists(x, lower[x]), by=[])
l.specialize(bounds, 0, keep=True)
l.have(bdd_above(lower), by=[bdd_above.defn(lower)])
supremum = l.have(
Exists(u, is_lub(lower, u)), by=[exists_is_lub_of_bdd_above(lower)]
)
s = l.obtain(supremum)
l.exists(s)
l.unfold(iinter)
l.beta()
j = l.fix()
l.intro()
l.specialize(bounds, j)
l.have(lower[a[j]], by=[])
l.have(is_ub(lower, s), by=[is_ub_of_is_lub(lower, s)])
l.have(a[j] <= s, by=[le_of_mem_of_is_ub(lower, a[j], s)])
l.have(s <= b[j], by=[le_of_is_lub_of_is_ub(lower, s, b[j])])
l.auto(by=[icc.defn(a[j], b[j])])
#search(bdd_above)
is_lub
bdd_above
icc
n = Int("n")
#in = Const("I", ArraySort(IntSort(),RSet))
a,b = Consts("a b", RSeq)
x,y = Reals("x y")
#def I()
#def I(n):
@Theorem(ForAll([x,y], is_ub(icc(x,y), y)))
def is_ub_icc(l):
x,y = l.fixes()
l.unfold(is_ub, icc)
l.auto()
@Theorem(ForAll([x,y], is_lb(icc(x,y), x)))
def is_lb_icc(l):
x,y = l.fixes()
l.unfold(is_lb, icc)
l.auto()
@Theorem(ForAll([x,y], x <= y, is_lub(icc(x,y), y)))
def t(l):
x,y = l.fixes()
l.unfold(is_lub)
l.intro()
l.split()
l.auto(by=[is_ub_icc(x,y)])
l.unfold(is_ub, icc)
l.auto()
I = Lambda(n, icc(a[n], b[n]))
@PTheorem(ForAll([a,b],
ForAll(n, n >= 0, I(n) >= I(n+1)),
ForAll(n, n >= 0, Exists(x, I(n)[x])),
Exists(x, iinter(I)[x])))
def t(l):
a,b = l.fixes()
dec, nonemp = l.intros()
A = Lambda(x, Exists(n, a[n] == x))
l.have((is_ub(A, b[0])))
l.unfold(is_ub)
#l.fix()
#A[a[0]]
pretty_expr(is_lub.defn.thm)
'βA : β β Bool, u : β,\n RSet.is_lub(A, u) = (RSet.is_ub(A, u) β§ (βv : β, RSet.is_ub(A, v) β u β€ v))'
Next Goal:
aβ bβ : β€ β β
0: βn : β€, n β₯ 0 β RSet.icc(aβ[n + 1], bβ[n + 1]) β RSet.icc(aβ[n], bβ[n])
1: βn : β€, n β₯ 0 β βx : β, RSet.icc(aβ[n], bβ[n])[x]
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β’ βx : β, (Ξ»xβ²1 : β, βn : β€, aβ[n] = xβ²1)[x] β x β€ bβ[0]
iinter(I)
RSet.iinter(Ξ»n : RSet.icc(a[n], b[n]))
class Function:
decl : FuncDeclRef
defn : Proof | None
pointwise : bool = True
set_lift : bool = True
_def __call__(self, *args, **kwargs) -> Any:
...
python
def indrel(name, args,body ):
assert body.sort() == BoolSort()
sorts = [x.sort() for x in args]
f = Function(name, *[x.sort() for x in args], BoolSort())
defn = axiom(ForAll(args, body, f(*args)))
f.defn = defn # Allow implies defns?
R = FreshConst(ArraySort(*sorts, BoolSort()) prefix="R")
smt.substittue(body, (R,R))
ind = ForAll([R], ForAll(args, Implies(R[args], body)), f <= R) # least
return defn, ind
sort = DecalreSort("Sort")
item = DeclareSort("Item") # Term? Element? Expr?
Int, Real, Bool = Consts("Int Real Bool")
Arr = Function("Arr", sort, sort, sort)
has_type = Function("has_type", item, sort, Bool)
from_int = Function("from_int", Int, item)
from_real = Function("from_real", Real, item)
from_bool = Function("from_bool", Bool, item)
has_type_from_int = axiom(ForAll([n], has_type(from_int(n), Int)))
axiom(ForAll([r], has_type(from_real(r), Real)))
axiom(ForAll([b], has_type(from_bool(b), Bool)))
def to_item(x: ExprRef) -> item:
if x.sort() == Int:
return from_int(x)
if x.sort() == Real:
return from_real(x)
if x.sort() == Bool:
return from_bool(x)
def synth(x) -> tuple[ExprRef, Proof
def check(x, T : ExprRef) -> Proof | None:
decl = x.decl()
if decl == from_int:
has_type_from_int(x.arg(0))
...
constants = {
}
synth = {
}
check = {
}
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[10], line 1
----> 1 sort = DecalreSort("Sort")
2 item = DeclareSort("Item")
3
4 Int, Real, Bool = Consts("Int Real Bool")
NameError: name 'DecalreSort' is not defined
class App:
f : FuncDeclRef | ExprRef | object
args : list
class Partial
type Term = App | Emb
class Term:
ctx :
f :
class Emb:
e : ExprRef
from kdrag.all import *
Z
f = Const("f",Z >> Z)
n = Const("n", Z)
fact_spec = Exists(f, ForAll(n, f(n) == If(n >= 0, 1, n * f(n-1))))
print(pretty_expr(fact_spec))
fact_spec
βf : β€ β β€, βn : β€, f[n] = (if n β₯ 0 then 1 else n * f[n - 1])
βf : βn : f[n] = If(n β₯ 0, 1, nΒ·f[n - 1])
import kdrag as kd
from kdrag.smt import *
R = RealSort()
RSet = SetSort(R)
RSetSeq = ArraySort(IntSort(), RSet)
RSetSet = SetSort(RSet)
S, T, U = Consts("S T U", RSet)
F = Const("F", RSetSeq)
A = Const("A", RSetSet)
a, b, x, y, r, eps, u, v = Reals("a b x y r eps u v")
i, n = Ints("i n")
empty = EmptySet(R)
univ = FullSet(R)
iunion = kd.define("RSet.iunion", F, Lambda(x, Exists(i, i >= 0, F[i][x])))
The Kernel crashed while executing code in the current cell or a previous cell.
Please review the code in the cell(s) to identify a possible cause of the failure.
Click <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info.
View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details.
python
import kdrag as kd
from kdrag.smt import *
R = RealSort()
RSet = SetSort(R)
RSetSeq = ArraySort(IntSort(), RSet)
RSetSet = SetSort(RSet)
S, T, U = Consts("S T U", RSet)
F = Const("F", RSetSeq)
A = Const("A", RSetSet)
a, b, x, y, r, eps, u, v = Reals("a b x y r eps u v")
i, n = Ints("i n")
empty = EmptySet(R)
univ = FullSet(R)
nonempty = kd.define(
"RSet.nonempty", S,
Exists(x, S[x]),
)
iunion = kd.define(
"RSet.iunion", F,
Lambda(x, Exists(i, i >= 0, F[i][x])),
)
iinter = kd.define(
"RSet.iinter", F,
Lambda(x, ForAll(i, i >= 0, F[i][x])),
)
sunion = kd.define(
"RSet.sunion", A,
Lambda(x, Exists(S, A[S], S[x])),
)
sinter = kd.define(
"RSet.sinter", A,
Lambda(x, ForAll(S, A[S], S[x])),
)
icc = kd.define(
"RSet.icc", [a, b],
Lambda(x, And(a <= x, x <= b)),
)
ioo = kd.define(
"RSet.ioo", [a, b],
Lambda(x, And(a < x, x < b)),
)
ball = kd.define(
"RSet.ball", [x, r],
ioo(x - r, x + r),
)
interior = kd.define(
"RSet.interior", S,
Lambda(x, Exists(eps, eps > 0, ball(x, eps) <= S)),
)
is_open = kd.define(
"RSet.is_open", S,
ForAll(x, S[x], interior(S)[x]),
)
is_closed = kd.define(
"RSet.is_closed", S,
is_open(~S),
)
closure = kd.define(
"RSet.closure", S,
Lambda(x,
ForAll(eps, eps > 0,
Exists(y, S[y], ball(x, eps)[y]))),
)
upper_bounds = kd.define(
"RSet.upper_bounds", S,
Lambda(u, ForAll(x, S[x], x <= u)),
)
lower_bounds = kd.define(
"RSet.lower_bounds", S,
Lambda(u, ForAll(x, S[x], u <= x)),
)
bdd_above = kd.define(
"RSet.bdd_above", S,
nonempty(upper_bounds(S)),
)
bdd_below = kd.define(
"RSet.bdd_below", S,
nonempty(lower_bounds(S)),
)
is_lub = kd.define(
"RSet.is_lub", [S, u],
And(
upper_bounds(S)[u],
ForAll(v, upper_bounds(S)[v], u <= v),
),
)
is_glb = kd.define(
"RSet.is_glb", [S, u],
And(
lower_bounds(S)[u],
ForAll(v, lower_bounds(S)[v], v <= u),
),
)
finite_cover = kd.define(
"RSet.finite_cover", [S, F, n],
And(
n >= 0,
ForAll(x, S[x],
Exists(i, i >= 0, i < n, F[i][x])),
),
)
is_compact = kd.define(
"RSet.is_compact", S,
ForAll(A,
S <= sunion(A),
ForAll(U, A[U], is_open(U)),
Exists([F, n],
finite_cover(S, F, n),
ForAll(i, i >= 0, i < n, A[F[i]]))),
)
exists_is_lub = kd.axiom(
ForAll(S,
nonempty(S),
bdd_above(S),
Exists(u, is_lub(S, u))),
)
python
from kdrag.all import *
import kdrag.theories.real as real
from kdrag.theories.real import *
RSetFam = ArraySort(IntSort(), RSet) # RSetSeq
PowerRSet = SetSort(RSet) # ? RSetSet
#bigunion
countunion = kd.declare("countunion", RSetFam, RSet)
countunion = kd.define("countunion", F, Lambda(x, Exists(i, i >= 0, F[i][x])))
countinter = kd.define("countinter", F, Lambda(x, ForAll(i, i >= 0, F[i][x])))
#countunion(F)[x] == Exists(i, F[i][x])
prove(countunion(F | G)== countunion(F) | countunion(G))
countunion(shift(F)) == countunion(F) # useful? i dunno
#prove(countunion(F & G) == countunion(F) & countunion(G))
bigunion = kd.declare("bigunion", PowerRSet, RSet)
bigunion = kd.define("bigunion", F, Lambda(x, Exists(S, And(SetMember(S, F), SetMember(x, S)))))
a,b,x = Reals("a b x")
icc = kd.define("icc", [a,b], Lambda(x, And(a <= x, x <= b)))
ioo = kd.define("ioo", [a,b], Lambda(x, And(a < x, x < b)))
le_ioo_icc = prove(ForAll([a,b], ioo(a,b) <= icc(a,b)))
ball = kd.define("ball", [x, r], Lambda(y, real.Abs(y - x) < r)) # use abs? use near?
cantorn = kd.define("cantorn", Lambda(n, If(n <= 0, ..., shift(cantor(n-1)) | shift(cantor(n-1)0))
cantor = countinter(Lambda(n, cantorn(n)))
interior_point = define("interior_point", [S, x], Exists(eps, eps > 0, Ball(x, eps) <= S))
open = define("open", S, ForAll(x, S[x], Exists(eps, eps > 0, Ball(x, eps) <= S)))
emp_open = prove(open(emp))
full_open = prove(open(full))
union_open = prove(open(S | T) == open(S) & open(T))
inter_open = prove(open(S & T) == open(S) & open(T))
interior = define("interior", [S], Lambda(x, interior_point(S, x)))
closure = define("closure", [S], Lambda(x, ForAll(U, open(U) & S <= U, U[x])))
open_interval = prove(open(icc(a,b)))
compact = define("compact", S, )
bigunion_open = prove(ForAll(F, ForAll(S, F[S], open(S))), open(bigunion(F)))
#countinter_open = prove(ForAll(n, open(F[n]), open(countinter(F))))
has_ub = define("has_ub", [S, u], ForAll(x, S[x], x <= u))
has_lb = define("has_lb", [S, l], ForAll(x, S[x], l <= x))
has_sup = define("has_sup", [S, u], has_ub(S, u) & ForAll(v, has_ub(S, v), u <= v))
has_ub(S, u) => Exists(v, has_sup(S, v)) # can I prove this or is this the axion?
has_lb(S, l) => Exists(v, has_inf(S, v))
#ub = has_ub(x,u) ==
has_meas = define("has_meas", [S, mu], )
#meas = define("meas", [S, mu], has_meas(S, mu) => meas(S) == mu))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[16], line 8
4 from kdrag.theories.real import *
5
6 RSetFam = ArraySort(IntSort(), RSet)
7 #bigunion
----> 8 countunion = kd.declare("countunion", RSetFam, RSet)
AttributeError: module 'kdrag' has no attribute 'declare'
"""z3 answers `sat` on an unsat query with a lambda passed to an uninterpreted function.
forall eps. eps > 0 -> f(lambda n. g(n) < eps)
e > 0
not f(lambda n. g(n) < e)
Unsat: take eps := e. Which random_seed triggers it depends on the z3 build and on how the
terms are built: with this script, 5.3.3 fails at 19 and 5.4.1 at 41. The same query as
SMT-LIB is in z3-lambda-wrong-sat.smt2 (`z3 smt.random_seed=41` on master f46b3c58e).
"""
import z3
f = z3.Function("f", z3.ArraySort(z3.IntSort(), z3.BoolSort()), z3.BoolSort())
g = z3.Function("g", z3.IntSort(), z3.RealSort())
e, eps = z3.Reals("e eps")
n = z3.Int("n")
print(z3.get_full_version())
for seed in range(150):
#print(seed)
s = z3.Solver()
s.set(random_seed=seed, timeout=5000)
s.add(z3.ForAll([eps], z3.Implies(eps > 0, f(z3.Lambda([n], g(n) < eps)))))
s.add(e > 0)
s.add(z3.Not(f(z3.Lambda([n], g(n) < e))))
res = s.check()
if res == z3.sat:
m = s.model()
print(f"random_seed={seed}: sat (wrong)")
print(" e =", m[e], " f =", m[f], " g =", m[g])
break
else:
print(f"random_seed={seed}: {res}")
else:
print("no wrong sat in seeds 0..149")
5.3.3.0
random_seed=0: unknown
random_seed=1: unsat
random_seed=2: unknown
random_seed=3: unknown
random_seed=4: unsat
random_seed=5: unsat
random_seed=6: unknown
random_seed=7: unsat
random_seed=8: unsat
random_seed=9: unknown
random_seed=10: sat (wrong)
e = 5/16 f = [as-array -> False, else -> True] g = [2 -> 7/16,
3 -> 5/16,
4 -> 7/16,
5 -> 3/8,
6 -> 2,
7 -> 2,
8 -> 7/16,
9 -> 7/16,
else -> -1/8]
python
import gc
import random
import sys
import z3
gc.disable()
def search(seed, rounds=80):
rng = random.Random(seed)
ctx = z3.Context()
I, R, B = z3.IntSort(ctx), z3.RealSort(ctx), z3.BoolSort(ctx)
eventually = z3.Function("eventually", z3.ArraySort(I, B), B)
absR = z3.Function("absR", R, R)
has_lim = z3.Function("has_lim", z3.ArraySort(I, R), R, B)
dumps = set()
for k in range(rounds):
shift = rng.randrange(0, 300)
rlimit = rng.choice([rng.randrange(1000, 20000), rng.randrange(20000, 1_000_000)])
junk = [z3.Int(f"junk{j}", ctx) + j for j in range(shift)]
a = z3.Array("a", I, R)
y, eps, e = z3.Reals("y eps e", ctx)
n = z3.Int("n", ctx)
def near(eps):
return z3.Lambda([n], absR(a[n] - y) < eps)
s = z3.Solver(ctx=ctx)
s.set(rlimit=rlimit)
s.add(has_lim(a, y) == z3.ForAll([eps], z3.Implies(eps > 0, eventually(near(eps)))))
s.add(z3.Not(z3.Implies(has_lim(a, y), z3.Implies(e > 0, eventually(near(e))))))
dumps.add(s.sexpr())
assert len(dumps) == 1, "rounds asserted different queries"
if s.check() == z3.sat:
print(f"seed {seed} round {k}: sat (wrong); eventually := {s.model()[eventually]}")
return True
del junk, s, a, y, eps, e, n, near
return False
if __name__ == "__main__":
print(z3.get_full_version())
seeds = range(1, int(sys.argv[1]) + 1) if len(sys.argv) > 1 else range(1, 21)
for seed in seeds:
if search(seed):
break
else:
print("no wrong sat found")
5.3.3.0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[1], line 44
40
41
42 if __name__ == "__main__":
43 print(z3.get_full_version())
---> 44 seeds = range(1, int(sys.argv[1]) + 1) if len(sys.argv) > 1 else range(1, 21)
45 for seed in seeds:
46 if search(seed):
47 break
ValueError: invalid literal for int() with base 10: '--f=/run/user/1000/jupyter/runtime/kernel-v34bdef7f9dd8fc6bed59a6bb63e761006b002ed03.json'
print(z3.get_version())
(5, 3, 3, 0)
cache = pickle.read("cache.pkl")
secret = "mysecret"
class Proof:
thm :
hash : int
reasons
def prove(thm, by=[]):
assert all(isinstance(b, str) for b in by) # merkle tree
hash = hash(thm.sexpr(), [b.hash], z3.version, python.version, secret)
if hash in cache:
return Proof(thm, hash=hash, by=[])
else:
#do it
def Theorem:
from kdrag.all import *
from kdrag.theories.real import *
from kdrag.theories.real.seq import *
from kdrag.theories.real.lim_algebra import *
lim_lemmas = {
neg : has_lim_neg,
add : has_lim_add,
mul : has_lim_mul,
inv : has_lim_inv,
sub : has_lim_sub,
div : has_lim_div,
const :
}
def lim_lemma(e : smt.ExprRef, n : smt.ArithRef) -> Proof:
todo = [e]
lemmas = []
hyps = {}
def worker(e):
f = e.decl()
if f in lim_lemmas:
children = e.cchildren()
ys = map(worker, e)
lemmas.append(lim_lemmas[f](*children, *ys))
else:
if e in hyps:
return hyps[e][1]
else:
y = FreshReal()
hyps[e] = (has_lim(e,y), y)
return y
y = worker(e)
return prove(ForAll(list(*hyps.values()), And(*hyps.keys()), has_lim(Lambda(n, e), y), by=[lemmas]))
def lim_lemma(e : smt.ExprRef) -> Proof:
todo = [e]
lemmas = []
hyps = {}
def worker(e):
f = e.decl()
if f in lim_lemmas:
children = e.cchildren()
ys = map(worker, e)
lemmas.append(lim_lemmas[f](*children, *ys))
else:
y = FreshReal()
hyps[e] = (has_lim(e,y), y)
return y
return prove(ForAll(list(*hyps.values()), And(*hyps.keys()), has_lim(e)), by=[lemmas])
β¨ForAll([a, y], Implies(has_lim(a, y), Implies(ForAll(n, Implies(n >= 0, a[n] >= 0)), y >= 0)))
P,Q = Consts("P Q", SetSort(IntSort()))
N = Int("N")
eventually = define("eventually", [P], Exists(N, ForAll(n, Implies(n >= N, P[n]))))
prove(ForAll([P,Q], P <= Q, eventually(P), eventually(Q)), by=[eventually.defn])
β¨ForAll([P, Q], Implies(subset(P, Q), Implies(eventually(P), eventually(Q))))
from kdrag.all import *
from kdrag.theories.real import *
from kdrag.theories.real.seq import *
from kdrag.theories.real.lim_algebra import *
Int("x")
lim.domain(0)
lim_of_nonneg_seq
#lim_zero
n = Int("n")
n.assumes = n >= 0
a,b = Consts("a b", ArraySort(IntSort(), RealSort()))
x,y = Reals("x y")
sub_add_neg = prove(ForAll([a,b],a - b == (a + (-b))), unfold=True)
@Theorem(ForAll([a,x], has_lim(a, x),has_lim(-a, -x)))
def has_lim_neg(l):
a,x = l.fixes()
l.unfold(has_lim)
l.unfold(kd.notation.neg[RSeq])
l.intros()
l.auto(by=[abs.defn])
@Theorem(ForAll([a,b,x,y], has_lim(a, x),has_lim(b,y), has_lim(a - b, x - y)))
def has_lim_sub(l):
a,b,x,y = l.fixes()
l.rw(sub_add_neg)
l.auto(by=[has_lim_add(a,-b,x, -y), has_lim_neg(b, y)])
@Theorem(ForAll([a,b], has_lim(a, x), has_lim(b,y), ForAll(n, a[n] >= b[n]), x >= y))
def lim_le(l):
a,b = l.fixes()
ha = l.intros()
hb = l.intros()
pos = l.intros()
l.have(ForAll(n, (a - b)[n] >= 0), by=[kd.notation.sub[RSeq].defn])
l.have(has_lim(a - b, x - y), by=[has_lim_sub(a, b, x, y)])
l.auto(by=[lim_of_nonneg_seq(a - b, x - y)])
#l.auto(by=[lim_of_nonneg_seq(Lambda(n, a[n] - b[n]), x - y)])
#l.have(lim_of_nonneg_seq(a - b))
python
@PTheorem(ForAll([a,x], has_lim(a, x),has_lim(-a, -x)))
def has_lim_neg(l):
a,x = l.fixes()
ha = l.intros()
l.unfold(kd.notation.neg[RSeq])
l.auto(lim_at_mul(a))
Next Goal:
aβ : β€ β β
xβ : β
0: has_lim(aβ, xβ)
ββββββββββββββββββββββββββββββ
β’ has_lim(Ξ»i : β€, -aβ[i], -xβ)
kd.notation.add[RSeq]
(Array Int Real).add
@PTheorem(ForAll([a,b, x, y], has_lim(a, x), has_lim(b,y), has_lim(a - b, x - y)))
def has_lim_sub(l):
a,bx,y = l.fixes()
ha = l.intros()
hb = l.intros()
has_lim_add(a, Lambda(n, -b[n]), x, -y)
β¨Implies(has_lim(a, x), Implies(has_lim(Lambda(n, -b[n]), -y), has_lim((Array Int Real).add(a, Lambda(n, -b[n])), x + -y)))
lim_of_nonneg_seq
has_lim_add
β¨ForAll([a, b, x, y], Implies(has_lim(a, x), Implies(has_lim(b, y), has_lim((Array Int Real).add(a, b), x + y))))
from kdrag.all import *
from kdrag.smt import *
class Theory:
def __init__(self, name : str):
self.name = name
self.decls = []
self.defns = {}
self.axioms = []
self.theorems = []
def define(self, name, definition):
def declare(self, ):
def axiom(self, formula : smt.BoolRef):
a = kd.axiom(formula)
self.axioms.append(a)
return a
def prove(self, *args, **kwargs):
p = kd.prove(*args, **kwargs)
self.theorems.append(p)
return p
def Theorem(self, *args, **kwargs):
t = kd.Theorem(*args, **kwargs)
self.theorems.append(t)
return t
But then what is the point? I should just do my lean playing to understand wha a bog standard reals would like like. It might be nice to just back m theorems with lean anyway. leanpy is dead? grind can probably solve many of the style of problem Iβm doing. https://github.com/kiranandcode/lean.py yeah dead Iβd say
specialize should take multiple args and formulas to discharge implies.
Maybe I should get rid of complexity in Calc
Why did i make QForAll an implicit And instead of curried?
f(β¦, x) == Lambda(y, f(y, x)) as akin to leanβs . + . notation. Thatβs a fun idea.
iteration out of formulas an proofs
x,y,z = prove(And(a,b,c)) p, (q,r) =
pf.exists([term1, term2]) = Proof(Exists([a,b], pf.bodysubst))
What more do I need to be able to completely build explicit proof terms?
& & & of Proof | | | of Proof? a β-
| a | b |
Add more variable control with free_in checks.
class Hyp:
class Var:
def partial_instan(self, *args):
trail = []
fm = self.fm
pos = 0
while pos < len(args):
if smt.is_implies(fm):
pos += 1
if isinstance()
if isinstance(arg[pos], Ellispse):
trail.append(arg[pos])
print_table : dict[smt.FuncDeclRef, Callable] = {
}
prec_table : {
}
def printer(e : smt.ExprRef, prec : int) -> str: # indent, other data?
if isinstance(e, smt.QuantifierRef):
vs, body = kd.utils.open_binder_unhygienic(e)
vs_str =
for v in vs:
vs_str.append(str(v) + " : " + str(v.sort()))
vs_str = " ".join(vs_str)
if e.is_forall():
binder = "β"
elif e.is_exists():
binder = "β"
else:
binder = "Ξ»"
return binder + vs_str + ", " + printer(body, prec)
elif smt.is_and(e):
elif smt.is_or(e):
elif smt.is_not(e):
elif smt.is_app(e):
func, args = e.decl(), e.children()
if func in print_table:
return print_table[func](e, prec)
else:
args_str = [printer(arg, prec) for arg in args]
return str(func) + " ".join(args_str)
{}
php
base_derive = {
cos : deriv_cos,
sin : deriv_sin,
}
def derive(f, x) -> tuple[smt.ExprRef, Proof]:
if smt.is_add(f):
deriv_add()
elif smt.is_mul(f):
deriv_mul()
else:
d = base_derive.get(f)
if d is not None:
d()
else:
raise ValueError(f"Cannot derive function: {f}")
def cont_tac():
def lim_tac():
def prop_fun(p):
if
well formed term judgement Is it meaningful to have this? What is the interpretation? Is it a function? Iβm internalizing an LCF function into a judgement?
Should I disallow
How do you introduce a WFTerm ?
| x,y,hyp | - t, Prop is kind of a refinement |
| x,y,hyp | - t, p,q ~~~ forall x y, hyp => exists t, p /\ q |
Existential internalizes the right of substitutions ? Internalizes how? |- t, p βββββ
| exists t, p | - |
or |- t, p βββ
| - exists x, p(x) |
|- exists x, p βββββ this seems true and non lossy
|- x, p
x |- p -------------- lossy |- exists x, p
| Well forall | - weak | - exists or something right? Adjunction? |
exists_f ?
import dataclasses import dataclass
import z3
@dataclass
class Term:
ctx : tuple[CtxItem, ...]
term : ExprRef
class Function:
f : z3.FuncDeclRef
class Ctx(Judgement):
ctx : tuple[CtxItem, ...]
python
from z3 import *
from dataclasses import dataclass
@dataclass
class Var: # Term?
vs : tuple[ExprRef, ...]
def __eq__(self, other):
if not isinstance(other, Var):
return False
if len(self.vs) != len(other.vs):
return False
return all(v1.eq(v2) for v1, v2 in zip(self.vs, other.vs))
class Term: ...
@dataclass
class Hyp: # Prop?
fm : BoolRef
type CtxItem = Var | Hyp
@dataclass
class Proof:
ctx : tuple[CtxItem, ...]
conc : BoolRef # CtxIitem? Term | Prop
def forall(self):
assert isinstance(self.ctx[-1], Var)
return Proof(ctx=self.ctx[:-1], conc=ForAll(self.ctx[-1].vs, self.conc))
def open_forall(self):
assert isinstance(self.conc, QuantifierRef) and self.conc.is_forall()
vs, body = open_binder(self.conc)
return Proof(ctx=self.ctx + (Var(vs),), conc=body)
def implies(self, hyp: BoolRef):
assert isinstance(self.ctx[-1], Hyp)
return Proof(ctx=self.ctx[:-1], conc=Implies(hyp, self.conc))
def open_implies(self):
assert isinstance(self.conc, BoolRef) and self.conc.decl().kind() == Z3_OP_IMPLIES
hyp, body = self.conc.children()
return Proof(ctx=self.ctx + (Hyp(hyp),), conc=body)
def open(self):
if isinstance(self.conc, QuantifierRef) and self.conc.is_forall():
return self.open_forall()
elif isinstance(self.conc, BoolRef) and self.conc.decl().kind() == Z3_OP_IMPLIES:
return self.open_implies()
else:
raise ValueError("Cannot open the current conclusion")
def close(self):
if isinstance(self.ctx[-1], Var):
return self.forall()
elif isinstance(self.ctx[-1], Hyp):
return self.implies(self.ctx[-1].fm)
else:
raise ValueError("Cannot close the current context item")
def weaken(self, thin : list[CtxItem | None]): # Or should I give it all. Take in Ctx and reconcile automatically?
newctx = []
ctx = self.ctx
pos = 0
for t in thin:
if t is None:
ctx.append(self.ctx[pos])
pos += 1
else:
match t:
case Var(vs):
assert all(free_in(self.conc, v) for v in vs)
for s in ctx[pos:]:
match s:
case Var(vs2):
assert all(not v1.eq(v2) for v1 in vs for v2 in vs2)
case Hyp(fm2):
...
case Hyp(fm): ... # Check that we're not campturing somerhing in here in prefix?
newctx.append(t)
return Proof(ctx=tuple(newctx), conc=self.conc)
def perm(self, order: list[int]):
assert sorted(order) == range(len(self.ctx))
newctx = tuple(self.ctx[i] for i in order)
return Proof(ctx=newctx, conc=self.conc)
@dataclass
class MetaVars:
vs : tuple[ExprRef, ...]
class Goal:
ctx : tuple[CtxItem | MetaVar, ...]
conc : BoolRef
def axiom(ctx : tuple[CtxItem, ...], conc : BoolRef) -> Proof:
return Proof(ctx=ctx, conc=conc)
def prove(ctx : Ctx, conc : BoolRef, by=[]) -> Proof:
s = Solver()
for h in ctx:
match h:
case Hyp(fm):
s.add(fm)
case Var(vs):
continue
case _:
raise ValueError(f"Unexpected context item: {h}")
for l in by:
assert isinstance(l, Proof)
l.weaken(ctx) # show that it can be weakened into this
s.add(l.conc)
s.add(Not(conc))
s.check()
@dataclass
class Var:
vs : tuple[ExprRef, ...]
@dataclass
class Prop:
fm : BoolRef
type JudgeItem = Var | Hyp
@dataclass
class WFSubst:
ctx : tuple[JudgeItem, ...]
subst : tuple[JudgeItem, ...]
def __matmul__(self, other: "WFSubst") -> "WFSubst": ...
class Var:
v : smt.ExprRef # vs ?
class Hyp:
h : smt.BoolRef
class MetaVar:
v : smt.ExprRef
class Goal:
ctx : list[Var | Hyp | MetaVar]
conc : smt.BoolRef
def formula_of(ctx, conc):
f = conc
for item in reversed(ctx):
if isinstance(item, Hyp):
f = smt.Implies(item.h, f)
elif isinstance(item, Var):
f = smt.ForAll(item.v, f)
elif isinstance(item, MetaVar):
f = smt.Exists(item.v, f)
return f
def prove(ctx, conc):
blahblahblah
s.add(formula_of(ctx, conc))
class Proof:
ctx : list[Var | Hyp]
conc : smt.BoolRef
def weaken(self, vs):
smt.is_free_in(self.conc)
def assume(self, hyp): # always allowed
Proof(self.ctx + (hyp,), conc=self.conc)
def forallI(self):
assert isinstance(self.ctx[-1], Var)
v = self.ctx.pop()
return Proof(ctx=self.ctx, conc=smt.ForAll(v.v, self.conc))
def forallE(self, t : smt.ExprRef): # instan
@dataclass
class ProofZipper:
ctx : ProofZipper | None
goal : Goal
left : list[Goal | Proof] # if we force left to right this would be just Proof
right : list[Goal | Proof]
#children : list[Goal | Proof | None] # None to mark a hole
class TopGoal(ProofZipper):
class Intro(ProofZipper):
class
class ProofState:
def __init__(self, goal):
self.ctx = None
self.goal = goal
def intros(self):
...
x = ...
x is ...
True
python
def papply(f, *args):
if len(arg) == 0:
return f
else:
papply(f(arg[0]), *args[1:])
if x is ...:
type(...)
ellipsis
prove(cont_at(Lambda([x], x), 0), unfold=True)
β¨cont_at(Lambda(x, x), 0)
from kdrag.theories.real import *
from kdrag.solvers import VampireSolver
from kdrag import *
x, y,a,b = Reals("x y a b")
prove(Implies(x > 0, x + 1 > 0), solver=VampireSolver)
prove(Lambda([x], RealVal(0)) != Lambda([x], x), solver=VampireSolver)
has_lim_at(Lambda([x], sin(x)), 0, 0)
@Theorem(ForAll([a,y], cont_at(Lambda(x, a), y)))
def cont_at_constant(l):
l.unfold(cont_at).unfold(abs).auto()
#prove(ForAll(a, cont_at(Lambda(x, a), 0)), unfold=True, solver="vampire")
prove(ForAll(a, cont_at(Lambda(x, a), 0)), by=[abs.defn, cont_at.defn])
#prove(ForAll(a, cont_at(Lambda(x, a), 0)), by=[cont_at.defn], solver="vampire")
#prove(ForAll([a], cont_at(Lambda([x], RealVal(a)), 0)), unfold=True)
β¨ForAll(a, cont_at(Lambda(x, a), 0))
More kdrag.theories.real to kdrag.real. Iβm tired of typing that shit
lean(ForAll(a, foo(x)), by=βgrindβ) just a paste in proof scipt with mathlib avaiable. That would enable us to ground ourselves to lean and mathlib.
Could be ask the AI to see if there is an easy way to improve z3py perf
typ theory as a theory
a simple type theory prover def has_type()
G groups subgroup() + operator. But then why not be in set theory?
Ask for is_ground
from kdrag.all import *
ForAll
<function kdrag.smt.ForAll(vs: list[z3.z3.ExprRef] | z3.z3.ExprRef, *hyp_conc, **kwargs) -> z3.z3.QuantifierRef>
python
from kdrag import *
from kdrag.smt import *
from kdrag import FreshVars, Theorem, prove
from kdrag.smt import And, Consts, ForAll, Implies, Lambda, RealSort, Reals, Store, IntSort
from kdrag.theories.real import *
import kdrag.theories.real as real
from kdrag.theories.real.seq import *
a = Const("a", RSeq)
n = Const("n", IntSort())
y = Const("y", RealSort())
abs_lt = prove(ForAll(y, y < 0, real.abs(y) > 0), by=[real.abs.defn])
@PTheorem(ForAll([a,y], has_lim(a,y), ForAll(n, n >= 0, a[n] >= 0), y >= 0))
def lim_of_nonneg_seq(l):
a,y = l.fixes()
lim_ay = l.intros()
pos = l.intros()
l.unfold(has_lim, at=lim_ay)
l.contra()
l.specialize(0, real.abs(y))
absypos = l.have(real.abs(y) > 0, by=[abs_lt(y)])
l.specialize(0, absypos)
N = l.obtain(0)
l.have(a[N] >= 0, by=[real.abs.defn])
l.specialize(1, N)
#l.contra() # should return h2
#h1 = l.have(ForAll(y, Or(y <= 0, ~has_lim(a, y))), by=[])
#l.clear(-2)
#l.specialize(h1)
#l.unfold(has_lim, at=h1)
Next Goal:
aβ : β€ β β
yβ : β
Nβ : β€
0: βn : β€, n > Nβ β |aβ[n] - yβ| < |yβ|
1: Nβ β₯ 0 β aβ[Nβ] β₯ 0
2: Β¬(yβ β₯ 0)
3: |yβ| > 0
4: aβ[Nβ] β₯ 0
βββββββββββββββββββββββββββββββββββββββ
β’ false
"""Continuity and limit lemmas for real functions.
Prove pointwise closure first, then derive global continuity and limit rules.
"""
from kdrag import *
from kdrag.smt import *
from kdrag import FreshVars, Theorem, prove
from kdrag.smt import And, Consts, ForAll, Implies, Lambda, RealSort, Reals, Store
from kdrag.theories.real import (
RFun,
abs,
cont_at,
fadd,
fmul,
has_lim_at,
is_cont,
min,
)
f, g = Consts("f g", RFun)
x, p, L, M = Reals("x p L M")
cont_at_of_is_cont = prove(
ForAll([f, x], is_cont(f), cont_at(f, x)),
by=[is_cont.defn],
)
@PTheorem(ForAll([f, x], cont_at(f, x), has_lim_at(f, x, f[x])))
def has_lim_at_of_cont_at(l):
f,x = l.fixes()
l.unfold(cont_at, has_lim_at)
continuity = l.intros()
eps = l.fix()
l.intros()
l.specialize(continuity, eps)
delta = Real("delta")
delta.assumes = delta > 0
y = Real("y")
l.have(Exists(delta, ForAll(y, abs(x - y) < delta, abs(f[x] - f[y]) < eps)), by=[])
delta = l.obtain(-1)
l.exists(delta)
l.auto(by=[abs.defn])
Lemma Complete! Change PTheorem to Theorem