]> git.donarmstrong.com Git - lilypond.git/blob - lily/constrained-breaking.cc
*** empty log message ***
[lilypond.git] / lily / constrained-breaking.cc
1 /*
2   constrained-breaking.cc -- implement a line breaker that
3   support limits on the number of systems
4
5   source file of the GNU LilyPond music typesetter
6
7   (c) 2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
8 */
9
10 #include "constrained-breaking.hh"
11
12 #include "international.hh"
13 #include "main.hh"
14 #include "output-def.hh"
15 #include "paper-column.hh"
16 #include "paper-score.hh"
17 #include "simple-spacer.hh"
18 #include "system.hh"
19 #include "warn.hh"
20
21 /*
22   We use the following optimal substructure. Let W(A) be our weight function.
23
24   Let A_{k,n} = (a_{k,n,1}, ... a_{k,n,k}) be the optimal set of line breaks
25   for k systems and n potential breakpoints. a_{k,n,k} = n (it is the end of
26   the piece)
27
28   Then A_{k+1, m} is contructed from
29   min_ {k < j < m} ( W(A_{k,j} :: m) )
30   where by A::m we denote appending m to the list A
31
32   Indices in the code:
33
34   The above algorithm makes it easy to end at a point before the end of the
35   score (just find A_{k,m} for some m < breaks_.size () - 1). However, we must
36   add information for starting at a point after the beginning. One constructor
37   allows the specification of a list of starting columns, start_. We then have
38   start_.size () different solution arrays. state_[i] is the array for the
39   solution starting at column number start_[i].
40
41   The indicies "start" and "end" refer to the index in the start_ array of the
42   desired starting and ending columns.
43
44   each solution array looks like
45    a_{1,1,1} a_{2,1,2} a_{3,1,3} . . .
46        X     a_{2,2,2} a_{3,2,3} . . .
47        X         X     a_{3,3,3} . . .
48        .         .         .     .
49        .         .         .       .
50   where the X's mark invalid solutions (can't have more systems than
51   breakpoints). Note that each value is of the form a_{x,n,x}. This is because
52   a breakpoint of the form a_{x,n,x-1} will also be called a_{x-1,m,x-1} for
53   some m < n. Each cell in the array stores the value of its m (ie. the
54   ending breakpoint of the previous line) as "prev_".
55
56   For finding A_{sys, brk}, let "me" be the (sys_count,brk) cell in our
57   solution array (state_[start][sys * rank + brk]).
58
59   Then A_{sys, brk} = A_{sys - 1, me.prev_} :: me
60 */
61
62 /*
63   start and sys here are indexed from 0.
64   brk is indexed from starting_breakpoints_[start]
65   (for brk, starting_breakpoints_[start] is the beginning
66   of the piece; the smallest value we should ever see here is
67   starting_breakpoints_[start] + 1) */
68 bool
69 Constrained_breaking::calc_subproblem (vsize start, vsize sys, vsize brk)
70 {
71   assert (sys < systems_);
72   assert (start < start_.size ());
73   assert (brk < breaks_.size ());
74
75   bool found_something = false;
76   vsize start_col = starting_breakpoints_[start];
77   vector<Constrained_break_node> &st = state_[start];
78   vsize rank = breaks_.size () - start_col;
79   vsize max_index = brk - start_col;
80   for (vsize j=sys; j < max_index; j++)
81     {
82       if (0 == sys && j > 0)
83         break; /* the first line cannot have its first break after the beginning */
84
85       Column_x_positions const *cur = &cols_[(j + start_col)*cols_rank_ + brk];
86       Column_x_positions const *prev = NULL;
87       Real prev_dem = 0;
88
89       if (sys > 0)
90         {
91           prev = st[(sys-1) * rank + j].line_config_;
92           prev_dem = st[(sys-1) * rank + j].demerits_;
93         }
94       if (isinf (prev_dem))
95         break;
96
97       Real dem;
98       Real force;
99       Real pen;
100       combine_demerits (prev, cur, &force, &pen, &dem);
101       dem += prev_dem;
102       if (isinf (dem))
103         continue;
104
105       int k = sys*rank + max_index;
106       if (isinf (st[k].demerits_) || dem < st[k].demerits_)
107         {
108           found_something = true;
109           st[k].demerits_ = dem;
110           st[k].force_ = force;
111           st[k].penalty_ = pen;
112           st[k].prev_ = j;
113           st[k].line_config_ = cur;
114         }
115     }
116   return found_something;
117 }
118
119 vector<Column_x_positions>
120 Constrained_breaking::solve ()
121 {
122   if (!systems_)
123     {
124       programming_error (_f ("no system number set in constrained-breaking"));
125       systems_ = breaks_.size () / 4;
126     }
127
128   resize (systems_);
129   return get_solution(0, VPOS, systems_);
130 }
131
132 Column_x_positions
133 Constrained_breaking::space_line (vsize i, vsize j)
134 {
135   bool ragged_right = to_boolean (pscore_->layout ()->c_variable ("ragged-right"));
136   bool ragged_last = to_boolean (pscore_->layout ()->c_variable ("ragged-last"));
137   Column_x_positions col;
138
139   vector<Grob*> line (all_.begin () + breaks_[i],
140                       all_.begin() + breaks_[j] + 1);
141
142   line[0] = dynamic_cast<Item *> (line[0])->find_prebroken_piece (RIGHT);
143   line.back () = dynamic_cast<Item *> (line.back ())->find_prebroken_piece (LEFT);
144
145   col.cols_ = line;
146
147   /* we have no idea what line this will be -- only whether it is the first */
148   Interval line_dims = line_dimensions_int (pscore_->layout (), i);
149   Simple_spacer_wrapper *sp = generate_spacing_problem (line, line_dims);
150
151   bool last = j == breaks_.size () - 1;
152   bool ragged = ragged_right || (last && ragged_last);
153   sp->solve (&col, ragged);
154
155   delete sp;
156   return col;
157 }
158
159 void
160 Constrained_breaking::resize (vsize systems)
161 {
162   systems_ = systems;
163
164   if (!breaks_.size () && pscore_)
165     {
166       /* do all the rod/spring problems */
167       breaks_ = pscore_->find_break_indices ();
168       cols_rank_ = breaks_.size ();
169       all_ = pscore_->root_system ()->columns ();
170       cols_.resize (breaks_.size () * breaks_.size ());
171       for (vsize i = 0; i < breaks_.size () - 1; i++)
172           for (vsize j = i + 1; j < breaks_.size (); j++)
173             {
174               cols_[i*cols_rank_ + j] = space_line (i, j);
175               if (!cols_[i*cols_rank_ + j].satisfies_constraints_)
176                 break;
177             }
178
179       /* work out all the starting indices */
180       for (vsize i = 0; i < start_.size (); i++)
181         {
182           vsize j;
183           for (j = 0; j < breaks_.size () - 1 && breaks_[j] < start_[i]; j++)
184             ;
185           starting_breakpoints_.push_back (j);
186           start_[i] = breaks_[j];
187         }
188       state_.resize (start_.size ());
189     }
190
191   if (pscore_ && systems_ > valid_systems_)
192     {
193       for (vsize i = 0; i < state_.size (); i++)
194         state_[i].resize((breaks_.size () - starting_breakpoints_[i]) * systems_);
195
196       /* fill out the matrices */
197       for (vsize i = 0; i < state_.size (); i++)
198         for (vsize j = valid_systems_; j < systems_; j++)
199           for (vsize k = starting_breakpoints_[i] + j + 1; k < breaks_.size (); k++)
200             if (!calc_subproblem (i, j, k))
201               break; /* if we couldn't break this, it is too cramped already */
202       valid_systems_ = systems_;
203     }
204 }
205
206 vector<Column_x_positions>
207 Constrained_breaking::get_solution (vsize start, vsize end, vsize sys_count)
208 {
209   vsize rank;
210   vsize end_brk;
211   prepare_solution (start, end, sys_count, &rank, &end_brk);
212
213   vector<Constrained_break_node> const &st = state_[start];
214   vector<Column_x_positions> ret;
215
216   /* find the first solution that satisfies constraints */
217   for (vsize sys = sys_count-1; sys != VPOS; sys--)
218     {
219       for (vsize brk = end_brk; brk != VPOS; brk--)
220         {
221           if (!isinf (st[sys*rank + brk].force_))
222             {
223               if (brk != end_brk)
224                 {
225                   warning ( _("couldn't find line breaking that satisfies constraints" ));
226                   ret.push_back (space_line (brk, end_brk));
227                 }
228               /* build up the good solution */
229               for (vsize cur_sys = sys; cur_sys != VPOS; cur_sys--)
230                 {
231                   assert (brk != VPOS);
232                   ret.push_back( *st[cur_sys*rank + brk].line_config_ );
233                   brk = st[cur_sys*rank + brk].prev_;
234                 }
235               reverse (ret);
236               return ret;
237             }
238         }
239     }
240   /* if we get to here, just put everything on one line */
241   warning ( _("couldn't find line breaking that satisfies constraints" ));
242   ret.push_back (space_line (0, end_brk));
243   return ret;
244 }
245
246 Real
247 Constrained_breaking::get_demerits (vsize start, vsize end, vsize sys_count)
248 {
249   vsize rank;
250   vsize brk;
251   prepare_solution (start, end, sys_count, &rank, &brk);
252
253   return state_[start][(sys_count-1)*rank + brk].demerits_;
254 }
255
256 Real
257 Constrained_breaking::get_force (vsize start, vsize end, vsize sys_count)
258 {
259   vsize rank;
260   vsize brk;
261   prepare_solution (start, end, sys_count, &rank, &brk);
262   vector<Constrained_break_node> const &st = state_[start];
263   Real f = 0;
264
265   for (int sys = sys_count-1; sys >= 0 && brk != VPOS; sys--)
266     {
267       f += fabs (st[sys*rank + brk].force_);
268       brk = st[sys*rank + brk].prev_;
269     }
270   if (brk == VPOS)
271     f = infinity_f;
272
273   return f;
274 }
275
276 Real
277 Constrained_breaking::get_penalty (vsize start, vsize end, vsize sys_count)
278 {
279   vsize rank;
280   vsize brk;
281   prepare_solution (start, end, sys_count, &rank, &brk);
282
283   return state_[start][(sys_count-1)*rank + brk].penalty_;
284 }
285
286 Real
287 Constrained_breaking::get_page_penalty (vsize start, vsize end, vsize sys_count, vsize sys_num, bool turn)
288 {
289   vsize rank;
290   vsize brk;
291   prepare_solution (start, end, sys_count, &rank, &brk);
292
293   vsize sys;
294   for (sys = sys_count-1; sys > sys_num; sys--)
295       brk = state_[start][sys*rank + brk].prev_;
296
297   if (brk == VPOS) /* we didn't satisfy constraints */
298     return 0;
299   vector<Grob*> const &cols = state_[start][sys*rank + brk].line_config_->cols_;
300   if (cols.empty ())
301     return 0;
302
303   Grob const *pc = cols.back ();
304   if (pc->original ())
305     {
306       SCM pen = pc->get_property ("page-penalty");
307       SCM turn_pen = pc->get_property ("page-turn-penalty");
308       Real ret = 0;
309       if (!turn && scm_is_number (pen) && fabs (scm_to_double (pen)) < 10000)
310         ret = scm_to_double (pen);
311       if (turn && scm_is_number (turn_pen) && fabs (scm_to_double (turn_pen)) < 10000)
312         ret = scm_to_double (turn_pen);
313       return ret;
314     }
315   return 0;
316 }
317
318 int
319 Constrained_breaking::get_min_systems (vsize start, vsize end)
320 {
321   vsize rank;
322   vsize brk;
323   vsize sys_count;
324
325   prepare_solution (start, end, 1, &rank, &brk);
326   vector<Constrained_break_node> const &st = state_[start];
327
328   /* sys_count < rank : rank is the # of breakpoints, we can't have more systems */
329   for (sys_count = 0; sys_count < rank; sys_count++)
330     {
331       if (sys_count >= valid_systems_)
332         {
333           resize (sys_count + 3);
334         }
335       if (!isinf (st[sys_count*rank + brk].force_))
336         return sys_count + 1;
337     }
338   /* no possible breaks satisfy constraints */
339   return 1;
340 }
341
342 int
343 Constrained_breaking::get_max_systems (vsize start, vsize end)
344 {
345   vsize brk = (end >= start_.size ()) ? breaks_.size () - 1 : starting_breakpoints_[end];
346   return brk - starting_breakpoints_[start];
347 }
348
349 void
350 Constrained_breaking::prepare_solution (vsize start, vsize end, vsize sys_count, vsize *rank, vsize *brk)
351 {
352   assert (start < start_.size () && (end == VPOS || end <= start_.size ()));
353   assert (start < end);
354
355   resize (sys_count);
356   if (end == start_.size ())
357     end = VPOS;
358
359   *rank = breaks_.size () - starting_breakpoints_[start];
360   *brk = end == VPOS ? breaks_.size () - 1 : starting_breakpoints_[end];
361   *brk -= starting_breakpoints_[start];
362 }
363
364 Constrained_breaking::Constrained_breaking ()
365 {
366   valid_systems_ = systems_ = 0;
367   start_.push_back (0);
368 }
369
370 Constrained_breaking::Constrained_breaking (vector<int> const &start)
371   : start_ (start)
372 {
373   valid_systems_ = systems_ = 0;
374 }
375
376 void
377 Constrained_breaking::combine_demerits (Column_x_positions const *prev,
378                                         Column_x_positions const *col,
379                                         Real *force,
380                                         Real *penalty,
381                                         Real *demerits) const
382 {
383   Real prev_f = prev ? prev->force_ : 0;
384
385   *penalty = 0;
386   if (col->cols_.empty () || !col->satisfies_constraints_)
387     *force = infinity_f;
388   else
389     {
390       *force = col->force_;
391
392       Grob *pc = col->cols_.back ();
393       if (pc->original ())
394         {
395           SCM pen = pc->get_property ("penalty");
396           if (scm_is_number (pen) && fabs (scm_to_double (pen)) < 10000)
397             *penalty += scm_to_double (pen);
398         }
399     }
400
401   *demerits = (*force) * (*force) + abs (prev_f - *force) + *penalty;
402 }
403