Debian Codegraph @

src/Arithmetic/Core.v

raw
1 (* Following http://adam.chlipala.net/theses/andreser.pdf chapter 3 *)
2 From Coq Require Import ZArith Lia.
3 From Coq Require Import Orders.
4 From Coq Require Import List.
5 Require Import Crypto.Algebra.Nsatz.
6 Require Import Crypto.Arithmetic.ModularArithmeticTheorems.
7 Require Import Crypto.Util.Decidable.
8 Require Import Crypto.Util.LetIn.
9 Require Import Crypto.Util.ListUtil.
10 Import Crypto.Util.ListUtil.Reifiable.
11 Require Import Crypto.Util.NatUtil.
12 Require Import Crypto.Util.Prod.
13 Require Import Crypto.Util.Decidable.Bool2Prop.
14 Require Import Crypto.Util.Tactics.SpecializeBy.
15 Require Import Crypto.Util.Tactics.UniquePose.
16 Require Import Crypto.Util.ZUtil.Definitions.
17 Require Import Crypto.Util.ZUtil.EquivModulo.
18 Require Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.
19 Require Import Crypto.Util.ZUtil.Zselect.
20 Require Import Crypto.Util.ZUtil.Hints.Core.
21 Require Import Crypto.Util.ZUtil.Modulo.PullPush.
22 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
23 Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
24 Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.
25 Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
26 Require Import Crypto.Util.Notations.
27 Import ListNotations. Local Open Scope Z_scope.
28
29 Module Associational.
30 Definition eval (p:list (Z*Z)) : Z :=
31 fold_right (fun x y => x + y) 0%Z (map (fun t => fst t * snd t) p).
32
33 Lemma eval_nil : eval nil = 0.
34 Proof. trivial. Qed.
35 Lemma eval_cons p q : eval (p::q) = fst p * snd p + eval q.
36 Proof. trivial. Qed.
37 Lemma eval_app p q: eval (p++q) = eval p + eval q.
38 Proof. induction p; rewrite <-?List.app_comm_cons;
39 rewrite ?eval_nil, ?eval_cons; nsatz. Qed.
40
41 #[global]
42 Hint Rewrite eval_nil eval_cons eval_app : push_eval.
43 Local Ltac push := autorewrite with
44 push_eval push_map push_partition push_flat_map
45 push_fold_right push_nth_default cancel_pair.
46
47 Lemma eval_map_mul (a x:Z) (p:list (Z*Z))
48 : eval (List.map (fun t => (a*fst t, x*snd t)) p) = a*x*eval p.
49 Proof. induction p; push; nsatz. Qed.
50 #[global]
51 Hint Rewrite eval_map_mul : push_eval.
52
53 Definition mul (p q:list (Z*Z)) : list (Z*Z) :=
54 flat_map (fun t =>
55 map (fun t' =>
56 (fst t * fst t', snd t * snd t'))
57 q) p.
58 Lemma eval_mul p q : eval (mul p q) = eval p * eval q.
59 Proof. induction p; cbv [mul]; push; nsatz. Qed.
60 #[global]
61 Hint Rewrite eval_mul : push_eval.
62
63 Definition square (p:list (Z*Z)) : list (Z*Z) :=
64 list_rect
65 _
66 nil
67 (fun t ts acc
68 => (dlet two_t2 := 2 * snd t in
69 (fst t * fst t, snd t * snd t)
70 :: (map (fun t'
71 => (fst t * fst t', two_t2 * snd t'))
72 ts))
73 ++ acc)
74 p.
75 Lemma eval_square p : eval (square p) = eval p * eval p.
76 Proof. induction p; cbv [square list_rect Let_In]; push; nsatz. Qed.
77 #[global]
78 Hint Rewrite eval_square : push_eval.
79
80 Definition negate_snd (p:list (Z*Z)) : list (Z*Z) :=
81 map (fun cx => (fst cx, -snd cx)) p.
82 Lemma eval_negate_snd p : eval (negate_snd p) = - eval p.
83 Proof. induction p; cbv [negate_snd]; push; nsatz. Qed.
84 #[global]
85 Hint Rewrite eval_negate_snd : push_eval.
86
87 Example base10_2digit_mul (a0:Z) (a1:Z) (b0:Z) (b1:Z) :
88 {ab| eval ab = eval [(10,a1);(1,a0)] * eval [(10,b1);(1,b0)]}.
89 eexists ?[ab].
90 (* Goal: eval ?ab = eval [(10,a1);(1,a0)] * eval [(10,b1);(1,b0)] *)
91 rewrite <-eval_mul.
92 (* Goal: eval ?ab = eval (mul [(10,a1);(1,a0)] [(10,b1);(1,b0)]) *)
93 cbv -[Z.mul eval]; cbn -[eval].
94 (* Goal: eval ?ab = eval [(100,(a1*b1));(10,a1*b0);(10,a0*b1);(1,a0*b0)]%RT *)
95 trivial. Defined.
96
97 Lemma eval_partition f (p:list (Z*Z)) :
98 eval (snd (partition f p)) + eval (fst (partition f p)) = eval p.
99 Proof. induction p; cbn [partition]; eta_expand; break_match; cbn [fst snd]; push; nsatz. Qed.
100 #[global]
101 Hint Rewrite eval_partition : push_eval.
102
103 Lemma eval_partition' f (p:list (Z*Z)) :
104 eval (fst (partition f p)) + eval (snd (partition f p)) = eval p.
105 Proof. rewrite Z.add_comm, eval_partition; reflexivity. Qed.
106 #[global]
107 Hint Rewrite eval_partition' : push_eval.
108
109 Lemma eval_fst_partition f p : eval (fst (partition f p)) = eval p - eval (snd (partition f p)).
110 Proof. rewrite <- (eval_partition f p); nsatz. Qed.
111 Lemma eval_snd_partition f p : eval (snd (partition f p)) = eval p - eval (fst (partition f p)).
112 Proof. rewrite <- (eval_partition f p); nsatz. Qed.
113
114 Definition split (s:Z) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)
115 := let hi_lo := partition (fun t => fst t mod s =? 0) p in
116 (snd hi_lo, map (fun t => (fst t / s, snd t)) (fst hi_lo)).
117 Lemma eval_snd_split s p (s_nz:s<>0) :
118 s * eval (snd (split s p)) = eval (fst (partition (fun t => fst t mod s =? 0) p)).
119 Proof using Type. cbv [split Let_In]; induction p;
120 repeat match goal with
121 | |- context[?a/?b] =>
122 unique pose proof (Z_div_exact_full_2 a b ltac:(trivial) ltac:(trivial))
123 | _ => progress push
124 | _ => progress break_match
125 | _ => progress nsatz end. Qed.
126 Lemma eval_split s p (s_nz:s<>0) :
127 eval (fst (split s p)) + s * eval (snd (split s p)) = eval p.
128 Proof using Type. rewrite eval_snd_split, eval_fst_partition by assumption; cbv [split Let_In]; cbn [fst snd]; lia. Qed.
129
130 Lemma reduction_rule' b s c (modulus_nz:s-c<>0) :
131 (s * b) mod (s - c) = (c * b) mod (s - c).
132 Proof using Type. replace (s * b) with ((c*b) + b*(s-c)) by nsatz.
133 rewrite Z.add_mod,Z_mod_mult,Z.add_0_r,Z.mod_mod;trivial. Qed.
134
135 Lemma reduction_rule a b s c (modulus_nz:s-c<>0) :
136 (a + s * b) mod (s - c) = (a + c * b) mod (s - c).
137 Proof using Type. apply Z.add_mod_Proper; [ reflexivity | apply reduction_rule', modulus_nz ]. Qed.
138
139 Definition reduce (s:Z) (c:list _) (p:list _) : list (Z*Z) :=
140 let lo_hi := split s p in fst lo_hi ++ mul c (snd lo_hi).
141
142 Lemma eval_reduce s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0) :
143 eval (reduce s c p) mod (s - eval c) = eval p mod (s - eval c).
144 Proof using Type. cbv [reduce]; push.
145 rewrite <-reduction_rule, eval_split; trivial. Qed.
146 #[global]
147 Hint Rewrite eval_reduce : push_eval.
148
149 Lemma eval_reduce_adjusted s c p w c' (s_nz:s<>0) (modulus_nz:s-eval c<>0)
150 (w_mod:w mod s = 0) (w_nz:w <> 0) (Hc' : eval c' = (w / s) * eval c) :
151 eval (reduce w c' p) mod (s - eval c) = eval p mod (s - eval c).
152 Proof using Type.
153 cbv [reduce]; push.
154 rewrite Hc', <- (Z.mul_comm (eval c)), <- !Z.mul_assoc, <-reduction_rule by auto.
155 autorewrite with zsimplify_const; rewrite !Z.mul_assoc, Z.mul_div_eq_full, w_mod by auto.
156 autorewrite with zsimplify_const; rewrite eval_split; trivial.
157 Qed.
158
159 (* reduce at most [n] times, stopping early if the high list is nil at any point *)
160 Definition repeat_reduce (n : nat) (s:Z) (c:list _) (p:list _) : list (Z * Z)
161 := nat_rect
162 _
163 (fun p => p)
164 (fun n' repeat_reduce_n' p
165 => let lo_hi := split s p in
166 if (length (snd lo_hi) =? 0)%nat
167 then p
168 else let p := fst lo_hi ++ mul c (snd lo_hi) in
169 repeat_reduce_n' p)
170 n
171 p.
172
173 Lemma repeat_reduce_S_step n s c p
174 : repeat_reduce (S n) s c p
175 = if (length (snd (split s p)) =? 0)%nat
176 then p
177 else repeat_reduce n s c (reduce s c p).
178 Proof using Type. cbv [repeat_reduce]; cbn [nat_rect]; break_innermost_match; auto. Qed.
179
180 Lemma eval_repeat_reduce n s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0) :
181 eval (repeat_reduce n s c p) mod (s - eval c) = eval p mod (s - eval c).
182 Proof using Type.
183 revert p; induction n as [|n IHn]; intro p; [ reflexivity | ];
184 rewrite repeat_reduce_S_step; break_innermost_match;
185 [ reflexivity | rewrite IHn ].
186 now rewrite eval_reduce.
187 Qed.
188 #[global]
189 Hint Rewrite eval_repeat_reduce : push_eval.
190
191 Lemma eval_repeat_reduce_adjusted n s c p w c' (s_nz:s<>0) (modulus_nz:s-eval c<>0)
192 (w_mod:w mod s = 0) (w_nz:w <> 0) (Hc' : eval c' = (w / s) * eval c) :
193 eval (repeat_reduce n w c' p) mod (s - eval c) = eval p mod (s - eval c).
194 Proof using Type.
195 revert p; induction n as [|n IHn]; intro p; [ reflexivity | ];
196 rewrite repeat_reduce_S_step; break_innermost_match;
197 [ reflexivity | rewrite IHn ].
198 now rewrite eval_reduce_adjusted.
199 Qed.
200
201 Definition split_one (s:Z) (w fw : Z) (p:list (Z*Z)) :=
202 let hi_lo := partition (fun t => (fst t =? w)) p in
203 (snd hi_lo, map (fun t => (fst t / fw, snd t)) (fst hi_lo)).
204
205 Lemma eval_split_one s w fw p (s_nz:s<>0) (fw_nz:fw<>0) (w_fw : w mod fw = 0) (fw_s : fw mod s = 0):
206 Associational.eval (fst (split_one s w fw p)) + fw * Associational.eval (snd (split_one s w fw p)) = Associational.eval p.
207 Proof.
208 remember (Z_div_exact_full_2 _ _ fw_nz w_fw) as H2.
209 clear HeqH2 fw_nz w_fw.
210 induction p as [|t p' IHp'].
211 - simpl. cbv [Associational.eval]. simpl. lia.
212 - cbv [split_one]. simpl. destruct (fst t =? w) eqn:E.
213 + simpl in IHp'. remember (partition (fun t0 : Z * Z => fst t0 =? w) p') as thing.
214 destruct thing as [thing1 thing2]. simpl. simpl in IHp'. repeat rewrite Associational.eval_cons.
215 ring_simplify. simpl.
216 apply Z.eqb_eq in E. rewrite E. rewrite <- H2. rewrite <- IHp'. ring.
217 + simpl in IHp'. remember (partition (fun t0 : Z * Z => fst t0 =? w) p') as thing.
218 destruct thing as [thing1 thing2]. simpl. simpl in IHp'. repeat rewrite Associational.eval_cons.
219 rewrite <- IHp'. ring.
220 Qed.
221
222 Definition reduce_one (s:Z) (w fw : Z) (c: list (Z*Z)) (p:list _) : list (Z*Z) :=
223 let lo_hi := split_one s w fw p in
224 fst lo_hi ++ mul (snd lo_hi) (map (fun thing => (fst thing, snd thing * (fw / s))) c).
225
226 Lemma eval_map_mul_snd (x:Z) (p:list (Z*Z))
227 : Associational.eval (List.map (fun t => (fst t, snd t * x)) p) = x * Associational.eval p.
228 Proof. induction p; push; nsatz. Qed.
229
230 Lemma eval_reduce_one s w fw c p (s_nz:s<>0) (fw_nz:fw<>0) (w_fw : w mod fw = 0) (fw_s : fw mod s = 0)
231 (modulus_nz: s - Associational.eval c <> 0) :
232 Associational.eval (reduce_one s w fw c p) mod (s - Associational.eval c) =
233 Associational.eval p mod (s - Associational.eval c).
234 Proof using Type.
235 cbv [reduce_one]; push.
236 rewrite eval_map_mul_snd. rewrite Z.mul_assoc. rewrite <- Z.mul_comm.
237 rewrite <- (reduction_rule _ _ _ _ modulus_nz). rewrite (Z.mul_comm _ (fw / s)).
238 rewrite Z.mul_assoc. rewrite <- (Z_div_exact_full_2 fw s s_nz fw_s).
239 rewrite eval_split_one; trivial.
240 Qed.
241
242 (*
243 Definition splitQ (s:Q) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)
244 := let hi_lo := partition (fun t => (fst t * Zpos (Qden s)) mod (Qnum s) =? 0) p in
245 (snd hi_lo, map (fun t => ((fst t * Zpos (Qden s)) / Qnum s, snd t)) (fst hi_lo)).
246 Lemma eval_snd_splitQ s p (s_nz:Qnum s<>0) :
247 Qnum s * eval (snd (splitQ s p)) = eval (fst (partition (fun t => (fst t * Zpos (Qden s)) mod (Qnum s) =? 0) p)) * Zpos (Qden s).
248 Proof using Type.
249 (* Work around https://github.com/mit-plv/fiat-crypto/issues/381 ([nsatz] can't handle [Zpos]) *)
250 cbv [splitQ Let_In]; cbn [fst snd]; zify; generalize dependent (Zpos (Qden s)); generalize dependent (Qnum s); clear s; intros.
251 induction p;
252 repeat match goal with
253 | |- context[?a/?b] =>
254 unique pose proof (Z_div_exact_full_2 a b ltac:(trivial) ltac:(trivial))
255 | _ => progress push
256 | _ => progress break_match
257 | _ => progress nsatz end. Qed.
258 Lemma eval_splitQ s p (s_nz:Qnum s<>0) :
259 eval (fst (splitQ s p)) + (Qnum s * eval (snd (splitQ s p))) / Zpos (Qden s) = eval p.
260 Proof using Type. rewrite eval_snd_splitQ, eval_fst_partition by assumption; cbv [splitQ Let_In]; cbn [fst snd]; Z.div_mod_to_quot_rem_in_goal; nia. Qed.
261 Lemma eval_splitQ_mul s p (s_nz:Qnum s<>0) :
262 eval (fst (splitQ s p)) * Zpos (Qden s) + (Qnum s * eval (snd (splitQ s p))) = eval p * Zpos (Qden s).
263 Proof using Type. rewrite eval_snd_splitQ, eval_fst_partition by assumption; cbv [splitQ Let_In]; cbn [fst snd]; nia. Qed.
264 *)
265 Lemma eval_rev p : eval (rev p) = eval p.
266 Proof using Type. induction p; cbn [rev]; push; lia. Qed.
267 #[global]
268 Hint Rewrite eval_rev : push_eval.
269 (*
270 Lemma eval_permutation (p q : list (Z * Z)) : Permutation p q -> eval p = eval q.
271 Proof using Type. induction 1; push; nsatz. Qed.
272
273 Module RevWeightOrder <: TotalLeBool.
274 Definition t := (Z * Z)%type.
275 Definition leb (x y : t) := Z.leb (fst y) (fst x).
276 Infix "<=?" := leb.
277 Local Coercion is_true : bool >-> Sortclass.
278 Theorem leb_total : forall a1 a2, a1 <=? a2 \/ a2 <=? a1.
279 Proof using Type.
280 cbv [is_true leb]; intros x y; rewrite !Z.leb_le; pose proof (Z.le_ge_cases (fst x) (fst y)).
281 lia.
282 Qed.
283 Global Instance leb_Transitive : Transitive leb.
284 Proof using Type. repeat intro; unfold is_true, leb in *; Z.ltb_to_lt; lia. Qed.
285 End RevWeightOrder.
286
287 Module RevWeightSort := Mergesort.Sort RevWeightOrder.
288
289 Lemma eval_sort p : eval (RevWeightSort.sort p) = eval p.
290 Proof using Type. symmetry; apply eval_permutation, RevWeightSort.Permuted_sort. Qed.
291 Hint Rewrite eval_sort : push_eval.
292 *)
293 (* rough template (we actually have to do things a bit differently to account for duplicate weights):
294 [ dlet fi_c := c * fi in
295 let (fj_high, fj_low) := split fj at s/fi.weight in
296 dlet fi_2 := 2 * fi in
297 dlet fi_2_c := 2 * fi_c in
298 (if fi.weight^2 >= s then fi_c * fi else fi * fi)
299 ++ fi_2_c * fj_high
300 ++ fi_2 * fj_low
301 | fi <- f , fj := (f weight less than i) ]
302 *)
303 (** N.B. We take advantage of dead code elimination to allow us to
304 let-bind partial products that we don't end up using *)
305 (** [v] -> [(v, v*c, v*c*2, v*2)] *)
306 Definition let_bind_for_reduce_square (c:list (Z*Z)) (p:list (Z*Z)) : list ((Z*Z) * list(Z*Z) * list(Z*Z) * list(Z*Z)) :=
307 let two := [(1,2)] (* (weight, value) *) in
308 map (fun t => dlet c_t := mul [t] c in dlet two_c_t := mul c_t two in dlet two_t := mul [t] two in (t, c_t, two_c_t, two_t)) p.
309 Definition reduce_square (s:Z) (c:list (Z*Z)) (p:list (Z*Z)) : list (Z*Z) :=
310 let p := let_bind_for_reduce_square c p in
311 let div_s := map (fun t => (fst t / s, snd t)) in
312 list_rect
313 _
314 nil
315 (fun t ts acc
316 => (let '(t, c_t, two_c_t, two_t) := t in
317 (if ((fst t * fst t) mod s =? 0)
318 then div_s (mul [t] c_t)
319 else mul [t] [t])
320 ++ (flat_map
321 (fun '(t', c_t', two_c_t', two_t')
322 => if ((fst t * fst t') mod s =? 0)
323 then div_s
324 (if fst t' <=? fst t
325 then mul [t'] two_c_t
326 else mul [t] two_c_t')
327 else (if fst t' <=? fst t
328 then mul [t'] two_t
329 else mul [t] two_t'))
330 ts))
331 ++ acc)
332 p.
333 Lemma eval_map_div s p (s_nz:s <> 0) (Hmod : forall v, In v p -> fst v mod s = 0)
334 : eval (map (fun x => (fst x / s, snd x)) p) = eval p / s.
335 Proof using Type.
336 assert (Hmod' : forall v, In v p -> (fst v * snd v) mod s = 0).
337 { intros; push_Zmod; rewrite Hmod by assumption; autorewrite with zsimplify_const; reflexivity. }
338 induction p as [|p ps IHps]; push.
339 { autorewrite with zsimplify_const; reflexivity. }
340 { cbn [In] in *; rewrite Z.div_add_exact by eauto.
341 rewrite !Z.Z_divide_div_mul_exact', IHps by auto using Znumtheory.Zmod_divide.
342 nsatz. }
343 Qed.
344 Lemma eval_map_mul_div s a b c (s_nz:s <> 0) (a_mod : (a*a) mod s = 0)
345 : eval (map (fun x => ((a * (a * fst x)) / s, b * (b * snd x))) c) = ((a * a) / s) * (b * b) * eval c.
346 Proof using Type.
347 rewrite <- eval_map_mul; apply f_equal, map_ext; intro.
348 rewrite !Z.mul_assoc.
349 rewrite !Z.Z_divide_div_mul_exact' by auto using Znumtheory.Zmod_divide.
350 f_equal; nia.
351 Qed.
352 #[global]
353 Hint Rewrite eval_map_mul_div using solve [ auto ] : push_eval.
354
355 Lemma eval_map_mul_div' s a b c (s_nz:s <> 0) (a_mod : (a*a) mod s = 0)
356 : eval (map (fun x => (((a * a) * fst x) / s, (b * b) * snd x)) c) = ((a * a) / s) * (b * b) * eval c.
357 Proof using Type. rewrite <- eval_map_mul_div by assumption; f_equal; apply map_ext; intro; Z.div_mod_to_quot_rem_in_goal; f_equal; nia. Qed.
358 #[global]
359 Hint Rewrite eval_map_mul_div' using solve [ auto ] : push_eval.
360
361 Lemma eval_flat_map_if A (f : A -> bool) g h p
362 : eval (flat_map (fun x => if f x then g x else h x) p)
363 = eval (flat_map g (fst (partition f p))) + eval (flat_map h (snd (partition f p))).
364 Proof using Type.
365 induction p; cbn [flat_map partition fst snd]; eta_expand; break_match; cbn [fst snd]; push;
366 nsatz.
367 Qed.
368 (*Local Hint Rewrite eval_flat_map_if : push_eval.*) (* this should be [Local], but that doesn't work *)
369
370 Lemma eval_if (b : bool) p q : eval (if b then p else q) = if b then eval p else eval q.
371 Proof using Type. case b; reflexivity. Qed.
372 #[global]
373 Hint Rewrite eval_if : push_eval.
374
375 Lemma split_app s p q :
376 split s (p ++ q) = (fst (split s p) ++ fst (split s q), snd (split s p) ++ snd (split s q)).
377 Proof using Type.
378 cbv [split]; rewrite !partition_app; cbn [fst snd].
379 rewrite !map_app; reflexivity.
380 Qed.
381 Lemma fst_split_app s p q :
382 fst (split s (p ++ q)) = fst (split s p) ++ fst (split s q).
383 Proof using Type. rewrite split_app; reflexivity. Qed.
384 Lemma snd_split_app s p q :
385 snd (split s (p ++ q)) = snd (split s p) ++ snd (split s q).
386 Proof using Type. rewrite split_app; reflexivity. Qed.
387 #[global]
388 Hint Rewrite fst_split_app snd_split_app : push_eval.
389
390 Lemma eval_reduce_list_rect_app A s c N C p :
391 eval (reduce s c (@list_rect A _ N (fun x xs acc => C x xs ++ acc) p))
392 = eval (@list_rect A _ (reduce s c N) (fun x xs acc => reduce s c (C x xs) ++ acc) p).
393 Proof using Type.
394 cbv [reduce]; induction p as [|p ps IHps]; cbn [list_rect]; push; [ nsatz | rewrite <- IHps; clear IHps ].
395 push; nsatz.
396 Qed.
397 #[global]
398 Hint Rewrite eval_reduce_list_rect_app : push_eval.
399
400 Lemma eval_list_rect_app A N C p :
401 eval (@list_rect A _ N (fun x xs acc => C x xs ++ acc) p)
402 = @list_rect A _ (eval N) (fun x xs acc => eval (C x xs) + acc) p.
403 Proof using Type. induction p; cbn [list_rect]; push; nsatz. Qed.
404 #[global]
405 Hint Rewrite eval_list_rect_app : push_eval.
406
407 Local Existing Instances list_rect_Proper pointwise_map flat_map_Proper.
408 Local Hint Extern 0 (Proper _ _) => solve_Proper_eq : typeclass_instances.
409
410 Lemma reduce_nil s c : reduce s c nil = nil.
411 Proof using Type. cbv [reduce]; induction c; cbn; intuition auto. Qed.
412 #[global]
413 Hint Rewrite reduce_nil : push_eval.
414
415 Lemma eval_reduce_app s c p q : eval (reduce s c (p ++ q)) = eval (reduce s c p) + eval (reduce s c q).
416 Proof using Type. cbv [reduce]; push; nsatz. Qed.
417 #[global]
418 Hint Rewrite eval_reduce_app : push_eval.
419
420 Lemma eval_reduce_cons s c p q :
421 eval (reduce s c (p :: q))
422 = (if fst p mod s =? 0 then eval c * ((fst p / s) * snd p) else fst p * snd p)
423 + eval (reduce s c q).
424 Proof using Type.
425 cbv [reduce split]; cbn [partition fst snd]; eta_expand; push.
426 break_innermost_match; cbn [fst snd map]; push; nsatz.
427 Qed.
428 #[global]
429 Hint Rewrite eval_reduce_cons : push_eval.
430
431 Lemma mul_cons_l t ts p :
432 mul (t::ts) p = map (fun t' => (fst t * fst t', snd t * snd t')) p ++ mul ts p.
433 Proof using Type. reflexivity. Qed.
434 Lemma mul_nil_l p : mul nil p = nil.
435 Proof using Type. reflexivity. Qed.
436 Lemma mul_nil_r p : mul p nil = nil.
437 Proof using Type. cbv [mul]; induction p; cbn; intuition auto. Qed.
438 #[global]
439 Hint Rewrite mul_nil_l mul_nil_r : push_eval.
440 Lemma mul_app_l p p' q :
441 mul (p ++ p') q = mul p q ++ mul p' q.
442 Proof using Type. cbv [mul]; rewrite flat_map_app; reflexivity. Qed.
443 Lemma mul_singleton_l_app_r p q q' :
444 mul [p] (q ++ q') = mul [p] q ++ mul [p] q'.
445 Proof using Type. cbv [mul flat_map]; rewrite !map_app, !app_nil_r; reflexivity. Qed.
446 #[global]
447 Hint Rewrite mul_singleton_l_app_r : push_eval.
448 Lemma mul_singleton_singleton p q :
449 mul [p] [q] = [(fst p * fst q, snd p * snd q)].
450 Proof using Type. reflexivity. Qed.
451
452 Lemma eval_reduce_square_step_helper s c t' t v (s_nz:s <> 0) :
453 (fst t * fst t') mod s = 0 \/ (fst t' * fst t) mod s = 0 -> In v (mul [t'] (mul (mul [t] c) [(1, 2)])) -> fst v mod s = 0.
454 Proof using Type.
455 cbv [mul]; cbn [map flat_map fst snd].
456 rewrite !app_nil_r, flat_map_singleton, !map_map; cbn [fst snd]; rewrite in_map_iff; intros [H|H] [? [? ?] ]; subst; revert H.
457 all:cbn [fst snd]; autorewrite with zsimplify_const; intro H; rewrite Z.mul_assoc, Z.mul_mod_l.
458 all:rewrite H || rewrite (Z.mul_comm (fst t')), H; autorewrite with zsimplify_const; reflexivity.
459 Qed.
460
461 Lemma eval_reduce_square_step s c t ts (s_nz : s <> 0) :
462 eval (flat_map
463 (fun t' => if (fst t * fst t') mod s =? 0
464 then map (fun t => (fst t / s, snd t))
465 (if fst t' <=? fst t
466 then mul [t'] (mul (mul [t] c) [(1, 2)])
467 else mul [t] (mul (mul [t'] c) [(1, 2)]))
468 else (if fst t' <=? fst t
469 then mul [t'] (mul [t] [(1, 2)])
470 else mul [t] (mul [t'] [(1, 2)])))
471 ts)
472 = eval (reduce s c (mul [(1, 2)] (mul [t] ts))).
473 Proof using Type.
474 induction ts as [|t' ts IHts]; cbn [flat_map]; [ push; nsatz | rewrite eval_app, IHts; clear IHts ].
475 change (t'::ts) with ([t'] ++ ts); rewrite !mul_singleton_l_app_r, !mul_singleton_singleton; autorewrite with zsimplify_const; push.
476 break_match; Z.ltb_to_lt; push; try nsatz.
477 all:rewrite eval_map_div by eauto using eval_reduce_square_step_helper; push; autorewrite with zsimplify_const.
478 all:rewrite ?Z.mul_assoc, <- !(Z.mul_comm (fst t')), ?Z.mul_assoc.
479 all:rewrite ?Z.mul_assoc, <- !(Z.mul_comm (fst t)), ?Z.mul_assoc.
480 all:rewrite <- !Z.mul_assoc, Z.mul_assoc.
481 all:rewrite !Z.Z_divide_div_mul_exact' by auto using Znumtheory.Zmod_divide.
482 all:nsatz.
483 Qed.
484
485 Lemma eval_reduce_square_helper s c x y v (s_nz:s <> 0) :
486 (fst x * fst y) mod s = 0 \/ (fst y * fst x) mod s = 0 -> In v (mul [x] (mul [y] c)) -> fst v mod s = 0.
487 Proof using Type.
488 cbv [mul]; cbn [map flat_map fst snd].
489 rewrite !app_nil_r, ?flat_map_singleton, !map_map; cbn [fst snd]; rewrite in_map_iff; intros [H|H] [? [? ?] ]; subst; revert H.
490 all:cbn [fst snd]; autorewrite with zsimplify_const; intro H; rewrite Z.mul_assoc, Z.mul_mod_l.
491 all:rewrite H || rewrite (Z.mul_comm (fst x)), H; autorewrite with zsimplify_const; reflexivity.
492 Qed.
493
494 Lemma eval_reduce_square_exact s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0)
495 : eval (reduce_square s c p) = eval (reduce s c (square p)).
496 Proof using Type.
497 cbv [let_bind_for_reduce_square reduce_square square Let_In]; rewrite list_rect_map; push.
498 apply list_rect_Proper; [ | repeat intro; subst | reflexivity ]; cbv [split]; push; [ nsatz | ].
499 rewrite flat_map_map, eval_reduce_square_step by auto.
500 break_match; Z.ltb_to_lt; push.
501 1:rewrite eval_map_div by eauto using eval_reduce_square_helper; push.
502 all:cbv [mul]; cbn [map flat_map fst snd]; rewrite !app_nil_r, !map_map; cbn [fst snd].
503 all:autorewrite with zsimplify_const.
504 all:rewrite <- ?Z.mul_assoc, !(Z.mul_comm (fst a)), <- ?Z.mul_assoc.
505 all:rewrite ?Z.mul_assoc, <- (Z.mul_assoc _ (fst a) (fst a)), <- !(Z.mul_comm (fst a * fst a)).
506 1:rewrite !Z.Z_divide_div_mul_exact' by auto using Znumtheory.Zmod_divide.
507 all:idtac;
508 let LHS := match goal with |- ?LHS = ?RHS => LHS end in
509 let RHS := match goal with |- ?LHS = ?RHS => RHS end in
510 let f := match LHS with context[eval (reduce _ _ (map ?f _))] => f end in
511 let g := match RHS with context[eval (reduce _ _ (map ?f _))] => f end in
512 rewrite (map_ext f g) by (intros; f_equal; nsatz).
513 all:nsatz.
514 Qed.
515 Lemma eval_reduce_square s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0)
516 : eval (reduce_square s c p) mod (s - eval c)
517 = (eval p * eval p) mod (s - eval c).
518 Proof using Type. rewrite eval_reduce_square_exact by assumption; push; auto. Qed.
519 #[global]
520 Hint Rewrite eval_reduce_square : push_eval.
521
522 Definition bind_snd (p : list (Z*Z)) :=
523 map (fun t => dlet_nd t2 := snd t in (fst t, t2)) p.
524
525 Lemma bind_snd_correct p : bind_snd p = p.
526 Proof using Type.
527 cbv [bind_snd]; induction p as [| [? ?] ];
528 push; [|rewrite IHp]; reflexivity.
529 Qed.
530
531 Definition value_at_weight (a : list (Z * Z)) (d : Z) :=
532 fold_right Z.add 0 (map snd (filter (fun p => fst p =? d) a)).
533
534 Lemma value_at_weight_works a d : d * (value_at_weight a d) = Associational.eval (filter (fun p => fst p =? d) a).
535 Proof.
536 induction a as [| a0 a' IHa'].
537 - cbv [Associational.eval value_at_weight]. simpl. lia.
538 - cbv [value_at_weight]. simpl. destruct (fst a0 =? d) eqn:E.
539 + rewrite Associational.eval_cons. simpl. rewrite <- IHa'. cbv [value_at_weight]. lia.
540 + apply IHa'.
541 Qed.
542
543 Lemma not_in_value_0 a d : ~ In d (map fst a) -> value_at_weight a d = 0.
544 Proof.
545 intros H. induction a as [| x a' IHa'].
546 - reflexivity.
547 - cbv [value_at_weight]. simpl. destruct (fst x =? d) eqn:E.
548 + exfalso. apply H. simpl. lia.
549 + apply IHa'. intros H'. apply H. simpl. right. apply H'.
550 Qed.
551
552 Definition dedup_weights a :=
553 map (fun d => (d, value_at_weight a d)) (nodupb Z.eqb (map fst a)).
554
555 Lemma funs_same (l : list Z) (a0 : Z*Z) (a' : list (Z*Z)) :
556 ~ In (fst a0) l ->
557 forall d, In d l ->
558 (fun d : Z => (d, value_at_weight (a0 :: a') d)) d = (fun d => (d, value_at_weight a' d)) d.
559 Proof.
560 intros H d H'. simpl. f_equal. cbv [value_at_weight]. simpl. destruct (fst a0 =? d) eqn:E.
561 - exfalso. rewrite Z.eqb_eq in E. subst. apply (H H').
562 - reflexivity.
563 Qed.
564
565 Lemma eval_dedup_weights a : Associational.eval (dedup_weights a) = Associational.eval a.
566 Proof.
567 induction a as [| a0 a' IHa'].
568 - reflexivity.
569 - cbv [dedup_weights]. simpl. destruct (existsb (Z.eqb (fst a0)) (nodupb Z.eqb (map fst a'))) eqn:E.
570 + apply (existsb_eqb_true_iff Z.eqb Z.eqb_eq) in E. rewrite <- (nodupb_in_iff Z.eqb Z.eqb_eq) in E.
571 apply (nodupb_split Z.eqb Z.eqb_eq) in E. destruct E as [l1 [l2 [H1 [H2 H3] ] ] ]. rewrite H1.
572 repeat rewrite map_app. rewrite (map_ext_in _ _ l1 (funs_same l1 a0 a' H2)).
573 rewrite (map_ext_in _ _ l2 (funs_same l2 a0 a' H3)). repeat rewrite Associational.eval_app. simpl.
574 repeat rewrite Associational.eval_cons. simpl. rewrite <- IHa'. simpl. rewrite Associational.eval_nil.
575 cbv [dedup_weights]. rewrite H1. repeat rewrite map_app. repeat rewrite Associational.eval_app.
576 cbv [value_at_weight]. simpl. rewrite Z.eqb_refl. simpl. cbv [Associational.eval]. simpl. lia.
577 + simpl. apply (existsb_eqb_false_iff Z.eqb Z.eqb_eq) in E. rewrite (map_ext_in _ _ _ (funs_same _ _ _ E)).
578 repeat rewrite Associational.eval_cons. simpl. rewrite <- IHa'. cbv [dedup_weights]. f_equal. f_equal.
579 rewrite <- (nodupb_in_iff Z.eqb Z.eqb_eq) in E. cbv [value_at_weight]. simpl. rewrite Z.eqb_refl.
580 apply not_in_value_0 in E. cbv [value_at_weight] in E. simpl. rewrite E. lia.
581 Qed.
582
583 Section Carries.
584 Definition carryterm (w fw:Z) (t:Z * Z) :=
585 if (Z.eqb (fst t) w)
586 then dlet_nd t2 := snd t in
587 dlet_nd d2 := t2 / fw in
588 dlet_nd m2 := t2 mod fw in
589 [(w * fw, d2);(w,m2)]
590 else [t].
591
592 Lemma eval_carryterm w fw (t:Z * Z) (fw_nonzero:fw<>0):
593 eval (carryterm w fw t) = eval [t].
594 Proof using Type*.
595 cbv [carryterm Let_In]; break_match; push; [|trivial].
596 pose proof (Z.div_mod (snd t) fw fw_nonzero).
597 rewrite Z.eqb_eq in *.
598 nsatz.
599 Qed. Hint Rewrite eval_carryterm using auto : push_eval.
600
601 Definition carry (w fw:Z) (p:list (Z * Z)):=
602 flat_map (carryterm w fw) p.
603
604 Lemma eval_carry w fw p (fw_nonzero:fw<>0):
605 eval (carry w fw p) = eval p.
606 Proof using Type*. cbv [carry]; induction p; push; nsatz. Qed.
607 Hint Rewrite eval_carry using auto : push_eval.
608
609 Definition borrowterm (w fw:Z) (t:Z * Z) :=
610 let quot := w / fw in
611 if (Z.eqb (fst t) w)
612 then [(quot, snd t * fw)]
613 else [t].
614
615 Lemma eval_borrowterm w fw (t:Z * Z) (fw_nz:fw<>0) (w_fw:w mod fw = 0) :
616 Associational.eval (borrowterm w fw t) = Associational.eval [t].
617 Proof using Type*.
618 cbv [borrowterm Let_In]; break_match; push; [|trivial].
619 pose proof (Z.div_mod (snd t) fw fw_nz).
620 rewrite Z.eqb_eq in *.
621 ring_simplify. rewrite Z.mul_comm. rewrite Z.mul_assoc. rewrite <- Z_div_exact_full_2; lia.
622 Qed.
623
624 Definition borrow (w fw:Z) (p:list (Z*Z)) :=
625 flat_map (borrowterm w fw) p.
626
627 Lemma eval_borrow w fw p (fw_nz:fw<>0) (w_fw:w mod fw = 0):
628 Associational.eval (borrow w fw p) = Associational.eval p.
629 Proof using Type*.
630 cbv [borrow borrowterm]. induction p as [| a p' IHp'].
631 - trivial.
632 - push. destruct (fst a =? w) eqn:E.
633 + rewrite Z.mul_comm. rewrite <- Z.mul_assoc. rewrite <- Z_div_exact_full_2; lia.
634 + rewrite IHp'. lia.
635 Qed.
636
637 End Carries.
638 End Associational.
639
640 Module Weight.
641 Section Weight.
642 Context weight
643 (weight_0 : weight 0%nat = 1)
644 (weight_positive : forall i, 0 < weight i)
645 (weight_multiples : forall i, weight (S i) mod weight i = 0)
646 (weight_divides : forall i : nat, 0 < weight (S i) / weight i).
647
648 Lemma weight_multiples_full' j : forall i, weight (i+j) mod weight i = 0.
649 Proof using weight_positive weight_multiples.
650 induction j; intros;
651 repeat match goal with
652 | _ => rewrite Nat.add_succ_r
653 | _ => rewrite IHj
654 | |- context [weight (S ?x) mod weight _] =>
655 rewrite (Z.div_mod (weight (S x)) (weight x)), weight_multiples by auto with zarith
656 | _ => progress autorewrite with push_Zmod natsimplify zsimplify_fast
657 | _ => reflexivity
658 end.
659 Qed.
660
661 Lemma weight_multiples_full j i : (i <= j)%nat -> weight j mod weight i = 0.
662 Proof using weight_positive weight_multiples.
663 intros; replace j with (i + (j - i))%nat by lia.
664 apply weight_multiples_full'.
665 Qed.
666
667 Lemma weight_divides_full j i : (i <= j)%nat -> 0 < weight j / weight i.
668 Proof using weight_positive weight_multiples. auto using Z.gt_lt, Z.div_positive_gt_0, weight_multiples_full with zarith. Qed.
669
670 Lemma weight_div_mod j i : (i <= j)%nat -> weight j = weight i * (weight j / weight i).
671 Proof using weight_positive weight_multiples. intros. apply Z.div_exact; auto using weight_multiples_full with zarith. Qed.
672
673 Lemma weight_mod_pull_div n x :
674 x mod weight (S n) / weight n =
675 (x / weight n) mod (weight (S n) / weight n).
676 Proof using weight_positive weight_multiples weight_divides.
677 replace (weight (S n)) with (weight n * (weight (S n) / weight n));
678 repeat match goal with
679 | _ => progress autorewrite with zsimplify_fast
680 | _ => rewrite Z.mul_div_eq_full by auto with zarith
681 | _ => rewrite Z.mul_div_eq' by auto with zarith
682 | _ => rewrite Z.mod_pull_div
683 | _ => rewrite weight_multiples by auto with zarith
684 | _ => solve [auto with zarith]
685 end.
686 Qed.
687
688 Lemma weight_div_pull_div n x :
689 x / weight (S n) =
690 (x / weight n) / (weight (S n) / weight n).
691 Proof using weight_positive weight_multiples weight_divides.
692 replace (weight (S n)) with (weight n * (weight (S n) / weight n));
693 repeat match goal with
694 | _ => progress autorewrite with zdiv_to_mod zsimplify_fast
695 | _ => rewrite Z.mul_div_eq_full by auto with zarith
696 | _ => rewrite Z.mul_div_eq' by auto with zarith
697 | _ => rewrite Z.div_div by auto with zarith
698 | _ => rewrite weight_multiples by assumption
699 | _ => solve [auto with zarith]
700 end.
701 Qed.
702 End Weight.
703 End Weight.
704
705 Module Positional.
706 Import Weight.
707 Section Positional.
708 Context (weight : nat -> Z)
709 (weight_0 : weight 0%nat = 1)
710 (weight_nz : forall i, weight i <> 0).
711
712 Definition to_associational (n:nat) (xs:list Z) : list (Z*Z)
713 := combine (map weight (List.seq 0 n)) xs.
714 Definition eval n x := Associational.eval (@to_associational n x).
715 Lemma eval_to_associational n x :
716 Associational.eval (@to_associational n x) = eval n x.
717 Proof using Type. trivial. Qed.
718 Hint Rewrite @eval_to_associational : push_eval.
719 Lemma eval_nil n : eval n [] = 0.
720 Proof using Type. cbv [eval to_associational]. rewrite combine_nil_r. reflexivity. Qed.
721 Hint Rewrite eval_nil : push_eval.
722 Lemma eval0 p : eval 0 p = 0.
723 Proof using Type. cbv [eval to_associational]. reflexivity. Qed.
724 Hint Rewrite eval0 : push_eval.
725
726 Lemma eval_snoc n m x y : n = length x -> m = S n -> eval m (x ++ [y]) = eval n x + weight n * y.
727 Proof using Type.
728 cbv [eval to_associational]; intros; subst n m.
729 rewrite seq_snoc, map_app.
730 rewrite combine_app_samelength by distr_length.
731 autorewrite with push_eval. simpl.
732 autorewrite with push_eval cancel_pair; ring.
733 Qed.
734
735 Lemma eval_snoc_S n x y : n = length x -> eval (S n) (x ++ [y]) = eval n x + weight n * y.
736 Proof using Type. intros; erewrite eval_snoc; eauto. Qed.
737 Hint Rewrite eval_snoc_S using (solve [distr_length]) : push_eval.
738
739 (* SKIP over this: zeros, add_to_nth *)
740 Local Ltac push := autorewrite with push_eval push_map distr_length
741 push_flat_map push_fold_right push_nth_default cancel_pair natsimplify.
742 Definition zeros n : list Z := repeat 0 n.
743 Lemma length_zeros n : length (zeros n) = n. Proof using Type. clear; cbv [zeros]; distr_length. Qed.
744 Hint Rewrite length_zeros : distr_length.
745 Lemma eval_combine_zeros ls n : Associational.eval (List.combine ls (zeros n)) = 0.
746 Proof using Type.
747 clear; cbv [Associational.eval zeros].
748 revert n; induction ls, n; simpl; rewrite ?IHls; nsatz. Qed.
749 Lemma eval_zeros n : eval n (zeros n) = 0.
750 Proof using Type. apply eval_combine_zeros. Qed.
751 Definition add_to_nth i x (ls : list Z) : list Z
752 := ListUtil.update_nth i (fun y => x + y) ls.
753 Lemma length_add_to_nth i x ls : length (add_to_nth i x ls) = length ls.
754 Proof using Type. clear; cbv [add_to_nth]; distr_length. Qed.
755 Hint Rewrite length_add_to_nth : distr_length.
756 Lemma eval_add_to_nth (n:nat) (i:nat) (x:Z) (xs:list Z) (H:(i<length xs)%nat)
757 (Hn : length xs = n) (* N.B. We really only need [i < Nat.min n (length xs)] *) :
758 eval n (add_to_nth i x xs) = weight i * x + eval n xs.
759 Proof using Type.
760 subst n.
761 cbv [eval to_associational add_to_nth].
762 rewrite ListUtil.combine_update_nth_r at 1.
763 rewrite <-(update_nth_id i (List.combine _ _)) at 2.
764 rewrite <-!(ListUtil.splice_nth_equiv_update_nth_update _ _
765 (weight 0, 0)) by (push; lia); cbv [ListUtil.splice_nth id].
766 repeat match goal with
767 | _ => progress push
768 | _ => progress break_match
769 | _ => progress (apply Zminus_eq; ring_simplify)
770 | _ => rewrite <-ListUtil.map_nth_default_always
771 end; lia. Qed.
772 Hint Rewrite @eval_add_to_nth eval_zeros eval_combine_zeros : push_eval.
773 Lemma add_to_nth_zero i l : add_to_nth i 0 l = l.
774 Proof. cbv [add_to_nth]. apply update_nth_id_eq. reflexivity. Qed.
775
776 Lemma zeros_ext_map {A} n (p : list A) : length p = n -> zeros n = map (fun _ => 0) p.
777 Proof using Type. cbv [zeros]; intro; subst; induction p; cbn; congruence. Qed.
778
779 Lemma eval_mul_each (n:nat) (a:Z) (p:list Z)
780 (Hn : length p = n)
781 : eval n (List.map (fun x => a*x) p) = a*eval n p.
782 Proof using Type.
783 clear -Hn.
784 transitivity (Associational.eval (map (fun t => (1 * fst t, a * snd t)) (to_associational n p))).
785 { cbv [eval to_associational]; rewrite !combine_map_r.
786 f_equal; apply map_ext; intros; f_equal; nsatz. }
787 { rewrite Associational.eval_map_mul, eval_to_associational; nsatz. }
788 Qed.
789 Hint Rewrite eval_mul_each : push_eval.
790
791 Definition place (t:Z*Z) (i:nat) : nat * Z :=
792 nat_rect
793 (fun _ => unit -> (nat * Z)%type)
794 (fun _ => (O, fst t * snd t))
795 (fun i' place_i' _
796 => let i := S i' in
797 if (fst t mod weight i =? 0)
798 then (i, let c := fst t / weight i in c * snd t)
799 else place_i' tt)
800 i
801 tt.
802
803 Lemma place_in_range (t:Z*Z) (n:nat) : (fst (place t n) < S n)%nat.
804 Proof using Type. induction n; cbv [place nat_rect] in *; break_match; autorewrite with cancel_pair; try lia. Qed.
805 Lemma weight_place t i : weight (fst (place t i)) * snd (place t i) = fst t * snd t.
806 Proof using weight_nz weight_0. induction i; cbv [place nat_rect] in *; break_match; push;
807 repeat match goal with |- context[?a/?b] =>
808 unique pose proof (Z_div_exact_full_2 a b ltac:(auto) ltac:(auto))
809 end; nsatz. Qed.
810 Hint Rewrite weight_place : push_eval.
811 Lemma weight_add_mod (weight_mul : forall i, weight (S i) mod weight i = 0) i j
812 : weight (i + j) mod weight i = 0.
813 Proof using weight_nz.
814 rewrite Nat.add_comm.
815 induction j as [|[|j] IHj]; cbn [Nat.add] in *;
816 eauto using Z_mod_same_full, Z.mod_mod_trans.
817 Qed.
818 Lemma weight_mul_iff (weight_pos : forall i, 0 < weight i) (weight_mul : forall i, weight (S i) mod weight i = 0) i j
819 : weight i mod weight j = 0 <-> ((j < i)%nat \/ forall k, (i <= k <= j)%nat -> weight k = weight j).
820 Proof using weight_nz.
821 split.
822 { destruct (dec (j < i)%nat); [ left; lia | intro H; right; revert H ].
823 assert (j = (j - i) + i)%nat by lia.
824 generalize dependent (j - i)%nat; intro jmi; intros ? H0.
825 subst j.
826 destruct jmi as [|j]; [ intros k ?; assert (k = i) by lia; subst; f_equal; lia | ].
827 induction j as [|j IH]; cbn [Nat.add] in *.
828 { intros k ?; assert (k = i \/ k = S i) by lia; destruct_head'_or; subst;
829 eauto using Z.mod_mod_0_0_eq_pos. }
830 { specialize_by lia.
831 { pose proof (weight_mul (S (j + i))) as H.
832 specialize_by eauto using Z.mod_mod_trans with lia.
833 intros k H'; destruct (dec (k = S (S (j + i)))); subst;
834 try rewrite IH by eauto using Z.mod_mod_trans with lia;
835 eauto using Z.mod_mod_trans, Z.mod_mod_0_0_eq_pos with lia.
836 rewrite (IH i) in * by lia.
837 eauto using Z.mod_mod_trans, Z.mod_mod_0_0_eq_pos with lia. } } }
838 { destruct (dec (j < i)%nat) as [H|H]; [ intros _ | intros [H'|H']; try lia ].
839 { assert (i = j + (i - j))%nat by lia.
840 generalize dependent (i - j)%nat; intro imj; intros.
841 subst i.
842 apply weight_add_mod; auto. }
843 { erewrite H', Z_mod_same_full by lia; lia. } }
844 Qed.
845 Lemma weight_div_from_pos_mul (weight_pos : forall i, 0 < weight i) (weight_mul : forall i, weight (S i) mod weight i = 0)
846 : forall i, 0 < weight (S i) / weight i.
847 Proof using weight_nz.
848 intro i; generalize (weight_mul i) (weight_mul (S i)).
849 Z.div_mod_to_quot_rem; nia.
850 Qed.
851 Lemma place_weight n (weight_pos : forall i, 0 < weight i) (weight_mul : forall i, weight (S i) mod weight i = 0)
852 (weight_unique : forall i j, (i <= n)%nat -> (j <= n)%nat -> weight i = weight j -> i = j)
853 i x
854 : (place (weight i, x) n) = (Nat.min i n, (weight i / weight (Nat.min i n)) * x).
855 Proof using weight_0 weight_nz.
856 cbv [place].
857 induction n as [|n IHn]; cbn; [ destruct i; cbn; rewrite ?weight_0; autorewrite with zsimplify_const; reflexivity | ].
858 destruct (dec (i < S n)%nat);
859 break_innermost_match; cbn [fst snd] in *; Z.ltb_to_lt; [ | rewrite IHn | | rewrite IHn ];
860 break_innermost_match;
861 rewrite ?Nat.min_l in * by lia;
862 rewrite ?Nat.min_r in * by lia;
863 eauto with lia.
864 { rewrite weight_mul_iff in * by auto.
865 destruct_head'_or; try lia.
866 assert (S n = i).
867 { apply weight_unique; try lia.
868 symmetry; eauto with lia. }
869 subst; reflexivity. }
870 { rewrite weight_mul_iff in * by auto.
871 exfalso; intuition eauto with lia. }
872 Qed.
873
874 Definition from_associational n (p:list (Z*Z)) :=
875 List.fold_right (fun t ls =>
876 dlet_nd p := place t (pred n) in
877 add_to_nth (fst p) (snd p) ls ) (zeros n) p.
878 Lemma eval_from_associational n p (n_nz:n<>O \/ p = nil) :
879 eval n (from_associational n p) = Associational.eval p.
880 Proof using weight_0 weight_nz. destruct n_nz; [ induction p | subst p ];
881 cbv [from_associational Let_In] in *; push; try
882 pose proof place_in_range a (pred n); try lia; try nsatz;
883 apply fold_right_invariant; cbv [zeros add_to_nth];
884 intros; rewrite ?map_length, ?List.repeat_length, ?seq_length, ?length_update_nth;
885 destruct n; cbn [pred] in *; try lia. Qed.
886 Hint Rewrite @eval_from_associational : push_eval.
887 Lemma length_from_associational n p : length (from_associational n p) = n.
888 Proof using Type. cbv [from_associational Let_In]. apply fold_right_invariant; intros; distr_length. Qed.
889 Hint Rewrite length_from_associational : distr_length.
890
891 Definition extend_to_length (n_in n_out : nat) (p:list Z) : list Z :=
892 p ++ zeros (n_out - n_in).
893 Lemma eval_extend_to_length n_in n_out p :
894 length p = n_in -> (n_in <= n_out)%nat ->
895 eval n_out (extend_to_length n_in n_out p) = eval n_in p.
896 Proof using Type.
897 cbv [eval extend_to_length to_associational]; intros.
898 replace (seq 0 n_out) with (seq 0 (n_in + (n_out - n_in))) by (f_equal; lia).
899 rewrite seq_add, map_app, combine_app_samelength, Associational.eval_app;
900 push; lia.
901 Qed.
902 Hint Rewrite eval_extend_to_length : push_eval.
903 Lemma length_extend_to_length n_in n_out p :
904 length p = n_in -> (n_in <= n_out)%nat ->
905 length (extend_to_length n_in n_out p) = n_out.
906 Proof using Type. clear; cbv [extend_to_length]; intros; distr_length. Qed.
907 Hint Rewrite length_extend_to_length : distr_length.
908
909 Definition drop_high_to_length (n : nat) (p:list Z) : list Z :=
910 firstn n p.
911 Lemma length_drop_high_to_length n p :
912 length (drop_high_to_length n p) = Nat.min n (length p).
913 Proof using Type. clear; cbv [drop_high_to_length]; intros; distr_length. Qed.
914 Hint Rewrite length_drop_high_to_length : distr_length.
915
916 Section mulmod.
917 Context (s:Z) (s_nz:s <> 0)
918 (c:list (Z*Z))
919 (m_nz:s - Associational.eval c <> 0).
920 Definition mulmod (n:nat) (a b:list Z) : list Z
921 := let a_a := to_associational n a in
922 let b_a := to_associational n b in
923 let ab_a := Associational.mul a_a b_a in
924 let abm_a := Associational.repeat_reduce n s c ab_a in
925 from_associational n abm_a.
926 Lemma eval_mulmod n (f g:list Z)
927 (Hf : length f = n) (Hg : length g = n) :
928 eval n (mulmod n f g) mod (s - Associational.eval c)
929 = (eval n f * eval n g) mod (s - Associational.eval c).
930 Proof using m_nz s_nz weight_0 weight_nz. cbv [mulmod]; push; trivial.
931 destruct f, g; simpl in *; [ right; subst n | left; try lia.. ].
932 clear; cbv -[Associational.repeat_reduce].
933 induction c as [|?? IHc]; simpl; trivial. Qed.
934
935 Definition squaremod (n:nat) (a:list Z) : list Z
936 := let a_a := to_associational n a in
937 let aa_a := Associational.reduce_square s c a_a in
938 let aam_a := Associational.repeat_reduce (pred n) s c aa_a in
939 from_associational n aam_a.
940 Lemma eval_squaremod n (f:list Z)
941 (Hf : length f = n) :
942 eval n (squaremod n f) mod (s - Associational.eval c)
943 = (eval n f * eval n f) mod (s - Associational.eval c).
944 Proof using m_nz s_nz weight_0 weight_nz. cbv [squaremod]; push; trivial.
945 destruct f; simpl in *; [ right; subst n; reflexivity | left; try lia.. ]. Qed.
946 End mulmod.
947 Hint Rewrite @eval_mulmod @eval_squaremod : push_eval.
948
949 Definition add (n:nat) (a b:list Z) : list Z
950 := let a_a := to_associational n a in
951 let b_a := to_associational n b in
952 from_associational n (a_a ++ b_a).
953 Lemma eval_add n (f g:list Z)
954 (Hf : length f = n) (Hg : length g = n) :
955 eval n (add n f g) = (eval n f + eval n g).
956 Proof using weight_0 weight_nz. cbv [add]; push; trivial. destruct n; auto. Qed.
957 Hint Rewrite @eval_add : push_eval.
958 Lemma length_add n f g
959 (Hf : length f = n) (Hg : length g = n) :
960 length (add n f g) = n.
961 Proof using Type. clear -Hf Hf; cbv [add]; distr_length. Qed.
962 Hint Rewrite @length_add : distr_length.
963
964 Section Carries.
965 Definition carry n m (index:nat) (p:list Z) : list Z :=
966 from_associational
967 m (@Associational.carry (weight index)
968 (weight (S index) / weight index)
969 (to_associational n p)).
970
971 Lemma length_carry n m index p : length (carry n m index p) = m.
972 Proof using Type. cbv [carry]; distr_length. Qed.
973 Hint Rewrite length_carry : distr_length.
974 Lemma eval_carry n m i p: (n <> 0%nat) -> (m <> 0%nat) ->
975 weight (S i) / weight i <> 0 ->
976 eval m (carry n m i p) = eval n p.
977 Proof using weight_0 weight_nz.
978 cbv [carry]; intros; push; [|tauto].
979 rewrite @Associational.eval_carry by eauto.
980 apply eval_to_associational.
981 Qed. Hint Rewrite @eval_carry : push_eval.
982
983 Definition carry_reduce n (s:Z) (c:list (Z * Z))
984 (index:nat) (p : list Z) :=
985 from_associational
986 n (Associational.reduce
987 s c (to_associational (S n) (@carry n (S n) index p))).
988
989 Lemma eval_carry_reduce n s c index p :
990 (s <> 0) -> (s - Associational.eval c <> 0) -> (n <> 0%nat) ->
991 (weight (S index) / weight index <> 0) ->
992 eval n (carry_reduce n s c index p) mod (s - Associational.eval c)
993 = eval n p mod (s - Associational.eval c).
994 Proof using weight_0 weight_nz. cbv [carry_reduce]; intros; push; auto. Qed.
995 Hint Rewrite @eval_carry_reduce : push_eval.
996 Lemma length_carry_reduce n s c index p
997 : length p = n -> length (carry_reduce n s c index p) = n.
998 Proof using Type. cbv [carry_reduce]; distr_length. Qed.
999 Hint Rewrite @length_carry_reduce : distr_length.
1000
1001 (* N.B. It is important to reverse [idxs] here, because fold_right is
1002 written such that the first terms in the list are actually used
1003 last in the computation. For example, running:
1004
1005 `Eval cbv - [Z.add] in (fun a b c d => fold_right Z.add d [a;b;c]).`
1006
1007 will produce [fun a b c d => (a + (b + (c + d)))].*)
1008 Definition chained_carries n s c p (idxs : list nat) :=
1009 fold_right (fun a b => carry_reduce n s c a b) p (rev idxs).
1010
1011 Lemma eval_chained_carries n s c p idxs :
1012 (s <> 0) -> (s - Associational.eval c <> 0) -> (n <> 0%nat) ->
1013 (forall i, In i idxs -> weight (S i) / weight i <> 0) ->
1014 eval n (chained_carries n s c p idxs) mod (s - Associational.eval c)
1015 = eval n p mod (s - Associational.eval c).
1016 Proof using Type*.
1017 cbv [chained_carries]; intros; push.
1018 apply fold_right_invariant; [|intro; rewrite <-in_rev];
1019 destruct n; intros; push; auto.
1020 Qed. Hint Rewrite @eval_chained_carries : push_eval.
1021 Lemma length_chained_carries n s c p idxs
1022 : length p = n -> length (@chained_carries n s c p idxs) = n.
1023 Proof using Type.
1024 intros; cbv [chained_carries]; induction (rev idxs) as [|x xs IHxs];
1025 cbn [fold_right]; distr_length.
1026 Qed. Hint Rewrite @length_chained_carries : distr_length.
1027
1028 (* Reverse of [eval]; translate from Z to basesystem by putting
1029 everything in first digit and then carrying. *)
1030 Definition simple_encode n (x : Z) : list Z :=
1031 fold_right (fun a b => carry n n a b) (from_associational n [(1,x)]) (seq 0 (n - 1)).
1032 Lemma eval_simple_encode n (x : Z) :
1033 n <> 0%nat ->
1034 (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->
1035 eval n (simple_encode n x) = x.
1036 Proof using Type*.
1037 cbv [simple_encode]. intros H1 H2. apply fold_right_invariant.
1038 - push; auto; f_equal; lia.
1039 - intros y H3 l H4. rewrite eval_carry; push; auto. apply H2.
1040 rewrite Lists.List.in_seq in *. lia.
1041 Qed.
1042 Definition encode n s c (x : Z) : list Z :=
1043 chained_carries n s c (from_associational n [(1,x)]) (seq 0 n).
1044 Lemma eval_encode n s c x :
1045 (s <> 0) -> (s - Associational.eval c <> 0) -> (n <> 0%nat) ->
1046 (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->
1047 eval n (encode n s c x) mod (s - Associational.eval c)
1048 = x mod (s - Associational.eval c).
1049 Proof using Type*. cbv [encode]; intros; push; auto; f_equal; lia. Qed.
1050 Lemma length_encode n s c x
1051 : length (encode n s c x) = n.
1052 Proof using Type. cbv [encode]; repeat distr_length. Qed.
1053 End Carries.
1054 Hint Rewrite @eval_encode @eval_carry @eval_carry_reduce @eval_chained_carries : push_eval.
1055 Hint Rewrite @length_encode @length_carry @length_carry_reduce @length_chained_carries : distr_length.
1056
1057 Section sub.
1058 Context (n:nat)
1059 (s:Z) (s_nz:s <> 0)
1060 (c:list (Z * Z))
1061 (m_nz:s - Associational.eval c <> 0)
1062 (balance:list Z)
1063 (length_balance:length balance = n)
1064 (eval_balance:eval n balance mod (s - Associational.eval c) = 0).
1065
1066 Definition negate_snd (a:list Z) : list Z
1067 := let A := to_associational n a in
1068 let negA := Associational.negate_snd A in
1069 from_associational n negA.
1070
1071 Definition scmul (x:Z) (a:list Z) : list Z
1072 := let A := to_associational n a in
1073 let R := Associational.mul A [(1, x)] in
1074 from_associational n R.
1075
1076 Definition sub (a b:list Z) : list Z
1077 := let ca := add n balance a in
1078 let _b := negate_snd b in
1079 add n ca _b.
1080
1081 Lemma length_scmul x a : length (scmul x a) = n.
1082 Proof using Type. cbv [scmul]; now push. Qed.
1083 Hint Rewrite length_scmul : distr_length.
1084
1085 Lemma eval_scmul x a : eval n (scmul x a) = x * eval n a.
1086 Proof using weight_0 weight_nz.
1087 clear -weight_0 weight_nz.
1088 destruct (zerop n) as [->|]; [ cbn; lia | ].
1089 cbv [scmul]; push; try lia.
1090 Qed.
1091 Hint Rewrite eval_scmul : push_eval.
1092
1093 Hint Rewrite eval_balance : push_eval.
1094 Lemma eval_sub a b
1095 : (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->
1096 (List.length a = n) -> (List.length b = n) ->
1097 eval n (sub a b) mod (s - Associational.eval c)
1098 = (eval n a - eval n b) mod (s - Associational.eval c).
1099 Proof using s_nz m_nz weight_0 weight_nz eval_balance length_balance.
1100 destruct (zerop n) as [->|]; try reflexivity.
1101 intros; cbv [sub negate_snd]; push; repeat distr_length;
1102 eauto with lia.
1103 push_Zmod; push; pull_Zmod; push_Zmod; pull_Zmod; distr_length; eauto.
1104 Qed.
1105 Hint Rewrite eval_sub : push_eval.
1106 Lemma length_sub a b
1107 : length a = n -> length b = n ->
1108 length (sub a b) = n.
1109 Proof using length_balance. clear dependent s. intros; cbv [sub scmul negate_snd]; repeat distr_length. Qed.
1110 Hint Rewrite length_sub : distr_length.
1111 Definition opp (a:list Z) : list Z
1112 := sub (zeros n) a.
1113 Lemma eval_opp
1114 (a:list Z)
1115 : (length a = n) ->
1116 (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->
1117 eval n (opp a) mod (s - Associational.eval c)
1118 = (- eval n a) mod (s - Associational.eval c).
1119 Proof using m_nz s_nz weight_0 weight_nz eval_balance length_balance. intros; cbv [opp]; push; distr_length; auto. Qed.
1120 Lemma length_opp a
1121 : length a = n -> length (opp a) = n.
1122 Proof using length_balance. clear dependent s. cbv [opp]; intros; repeat distr_length. Qed.
1123 End sub.
1124 Hint Rewrite @eval_scmul @eval_opp @eval_sub : push_eval.
1125 Hint Rewrite @length_scmul @length_sub @length_opp : distr_length.
1126
1127 Section select.
1128 Definition zselect (mask cond:Z) (p:list Z) :=
1129 dlet t := Z.zselect cond 0 mask in List.map (Z.land t) p.
1130
1131 Definition select (cond:Z) (if_zero if_nonzero:list Z) :=
1132 List.map (fun '(p, q) => Z.zselect cond p q) (List.combine if_zero if_nonzero).
1133
1134 Lemma map_and_0 n (p:list Z) : length p = n -> map (Z.land 0) p = zeros n.
1135 Proof using Type.
1136 intro; subst; induction p as [|x xs IHxs]; [reflexivity | ].
1137 cbn; f_equal; auto.
1138 Qed.
1139 Lemma eval_zselect n mask cond p (H:List.map (Z.land mask) p = p) :
1140 length p = n
1141 -> eval n (zselect mask cond p) =
1142 if dec (cond = 0) then 0 else eval n p.
1143 Proof using Type.
1144 cbv [zselect Let_In].
1145 rewrite Z.zselect_correct; break_match.
1146 { intros; erewrite map_and_0 by eassumption. apply eval_zeros. }
1147 { rewrite H; reflexivity. }
1148 Qed.
1149 Lemma length_zselect mask cond p :
1150 length (zselect mask cond p) = length p.
1151 Proof using Type. clear dependent weight. cbv [zselect Let_In]; break_match; intros; distr_length. Qed.
1152
1153 (** We need an explicit equality proof here, because sometimes it
1154 matters that we retain the same bounds when selecting. The
1155 alternative (weaker) lemma is [eval_select], where we only
1156 talk about equality under [eval]. *)
1157 Lemma select_eq cond n : forall p q,
1158 length p = n -> length q = n ->
1159 select cond p q = if dec (cond = 0) then p else q.
1160 Proof using weight.
1161 cbv [select]; induction n; intros;
1162 destruct p; distr_length;
1163 destruct q; distr_length;
1164 repeat match goal with
1165 | _ => progress autorewrite with push_combine push_map
1166 | _ => rewrite IHn by distr_length
1167 | _ => rewrite Z.zselect_correct
1168 | _ => break_match; reflexivity
1169 end.
1170 Qed.
1171 Lemma eval_select n cond p q :
1172 length p = n -> length q = n
1173 -> eval n (select cond p q) =
1174 if dec (cond = 0) then eval n p else eval n q.
1175 Proof using weight.
1176 intros; erewrite select_eq by eauto.
1177 break_match; reflexivity.
1178 Qed.
1179 Lemma length_select_min cond p q :
1180 length (select cond p q) = Nat.min (length p) (length q).
1181 Proof using Type. clear dependent weight. cbv [select Let_In]; distr_length. Qed.
1182 Hint Rewrite length_select_min : distr_length.
1183 Lemma length_select n cond p q :
1184 length p = n -> length q = n ->
1185 length (select cond p q) = n.
1186 Proof using Type. clear dependent weight. distr_length; lia **. Qed.
1187
1188 Lemma select_push cond a b f (H : length a = length b) :
1189 f (select cond a b) = Z.zselect cond (f a) (f b).
1190 Proof using Type. unfold select, Z.zselect.
1191 destruct (Z.eqb_spec cond 0); subst; simpl.
1192 - rewrite (map_ext _ fst), ListUtil.map_fst_combine, <- H, firstn_all; reflexivity.
1193 - rewrite (map_ext _ snd), ListUtil.map_snd_combine, H, firstn_all; reflexivity. Qed.
1194 End select.
1195 End Positional.
1196 (* Hint Rewrite disappears after the end of a section *)
1197 #[global]
1198 Hint Rewrite length_zeros length_add_to_nth length_from_associational @length_add @length_carry_reduce @length_carry @length_chained_carries @length_encode @length_scmul @length_sub @length_opp @length_select @length_zselect @length_select_min @length_extend_to_length @length_drop_high_to_length : distr_length.
1199 #[global]
1200 Hint Rewrite @eval_zeros @eval_nil @eval_snoc_S @eval_select @eval_zselect @eval_extend_to_length using solve [auto; distr_length]: push_eval.
1201 Section Positional_nonuniform.
1202 Context (weight weight' : nat -> Z).
1203
1204 Lemma eval_hd_tl n (xs:list Z) :
1205 length xs = n ->
1206 eval weight n xs = weight 0%nat * hd 0 xs + eval (fun i => weight (S i)) (pred n) (tl xs).
1207 Proof using Type.
1208 intro; subst; destruct xs as [|x xs]; [ cbn; lia | ].
1209 cbv [eval to_associational Associational.eval] in *; cbn.
1210 rewrite <- map_S_seq; reflexivity.
1211 Qed.
1212
1213 Lemma eval_cons n (x:Z) (xs:list Z) :
1214 length xs = n ->
1215 eval weight (S n) (x::xs) = weight 0%nat * x + eval (fun i => weight (S i)) n xs.
1216 Proof using Type. intro; subst; apply eval_hd_tl; reflexivity. Qed.
1217
1218 Lemma eval_weight_mul n p k :
1219 (forall i, In i (seq 0 n) -> weight i = k * weight' i) ->
1220 eval weight n p = k * eval weight' n p.
1221 Proof using Type.
1222 setoid_rewrite List.in_seq.
1223 revert n weight weight'; induction p as [|x xs IHxs], n as [|n]; intros weight weight' Hwt;
1224 cbv [eval to_associational Associational.eval] in *; cbn in *; try lia.
1225 rewrite Hwt, Z.mul_add_distr_l, Z.mul_assoc by lia.
1226 erewrite <- !map_S_seq, IHxs; [ reflexivity | ]; cbn; eauto with lia.
1227 Qed.
1228 End Positional_nonuniform.
1229 #[global]
1230 Hint Rewrite @eval_cons using solve [auto; distr_length]: push_eval.
1231 End Positional.
1232
1233 Record weight_properties {weight : nat -> Z} :=
1234 {
1235 weight_0 : weight 0%nat = 1;
1236 weight_positive : forall i, 0 < weight i;
1237 weight_multiples : forall i, weight (S i) mod weight i = 0;
1238 weight_divides : forall i : nat, 0 < weight (S i) / weight i;
1239 }.
1240 Global Hint Resolve weight_0 weight_positive weight_multiples weight_divides : core.
1241 #[global]
1242 Hint Rewrite @weight_0 @weight_multiples using solve [auto]: push_eval.
1243 Lemma weight_nz {weight : nat -> Z} {wprops : @weight_properties weight}
1244 : forall i, weight i <> 0.
1245 Proof. intro i; pose proof (@weight_positive _ wprops i); lia. Qed.
1246 Global Hint Resolve weight_nz : core.