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.
This commit is contained in:
Sélène Corbineau 2026-06-10 09:15:08 +02:00
parent 7fab01aeca
commit 03dbe317c5

View file

@ -34,6 +34,30 @@ def append_folio_A6(input_pdf, offset, size, append_to):
dpage.merge_page(ipage) dpage.merge_page(ipage)
return writer 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 # Interprets input_pdf as a list of A6 pages, and appends to append_to with
# A5 pages using the following rules: # A5 pages using the following rules: