From 03dbe317c5d6ec1464b900c325907d0820985696 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9l=C3=A8ne=20Corbineau?= Date: Wed, 10 Jun 2026 09:15:08 +0200 Subject: [PATCH] Begin implementation of better partition strategy Uneven folios are awkward, and folios of many different sizes are hard to bind correctly. Therefore, try to partition the sheets as folios of max_folio_size and max_folio_size - k, where k is minimal. --- foliator.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/foliator.py b/foliator.py index 17e0132..eca5949 100755 --- a/foliator.py +++ b/foliator.py @@ -34,6 +34,30 @@ def append_folio_A6(input_pdf, offset, size, append_to): dpage.merge_page(ipage) return writer +# Tries to find a partition as +# num_sheets = max_folio_size * a + (max_folio_size - k) * b +# where k is minimal. We let n = max_folio_size and L = num_sheets. +# Note that when L > n^2, then k = 1 must succeed. +def find_partition(num_sheets, max_folio_size): + max_a = num_sheets // max_folio_size + for k in range(1, max_folio_size): + # We want to solve a*k = L (mod n-k). This happens iff + # a*k' = L' (mod m') where k,L,m are divided by their gcd. + # Then, if k' and m' have a common factor, L' doesn't have it and there + # are no solutions. Otherwise, there's one solution mod m'. + g = math.gcd(max_folio_size - k, k, num_sheets) + mprime = (max_folio_size - k)//g + kprime = k//g + Lprime = num_sheets//g + if (math.gcd(kprime, mprime) > 1): + continue + a_mod_mprime = (pow(kprime, -1, mprime) * Lprime) % mprime + tosub = (max_a - a_mod_mprime + mprime) % mprime + # If we're a bit above, substract only a little. But a bit below implies + # substracting almost mprime. + candidate = max_a - tosub + if (candidate >= 0): + return (candidate, k) # Interprets input_pdf as a list of A6 pages, and appends to append_to with # A5 pages using the following rules: