]> git.donarmstrong.com Git - lilypond.git/blob - lily/constrained-breaking.cc
Merge branch 'master' of ssh+git://hanwen@git.sv.gnu.org/srv/git/lilypond
[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--2007 Joe Neeman <joeneeman@gmail.com>
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 indices "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   Matrix<Constrained_break_node> &st = state_[start];
78   vsize max_index = brk - start_col;
79   for (vsize j=max_index; j-- > sys;)
80     {
81       if (0 == sys && j > 0)
82         continue; /* the first line cannot have its first break after the beginning */
83
84       Line_details const &cur = lines_.at (brk, j + start_col);
85       if (isinf (cur.force_))
86         break;
87
88       Real prev_f = 0;
89       Real prev_dem = 0;
90
91       if (sys > 0)
92         {
93           prev_f = st.at (j, sys-1).details_.force_;
94           prev_dem = st.at (j, sys-1).demerits_;
95         }
96       if (isinf (prev_dem))
97         continue;
98
99       Real dem = combine_demerits (cur.force_, prev_f) + prev_dem + cur.break_penalty_;
100       Constrained_break_node &n = st.at (max_index, sys);
101       if (dem < n.demerits_)
102         {
103           found_something = true;
104           n.demerits_ = dem;
105           n.details_ = cur;
106           n.prev_ = j;
107         }
108     }
109   return found_something;
110 }
111
112
113 Column_x_positions
114 Constrained_breaking::space_line (vsize i, vsize j)
115 {
116   bool ragged_right = to_boolean (pscore_->layout ()->c_variable ("ragged-right"));
117   bool ragged_last = to_boolean (pscore_->layout ()->c_variable ("ragged-last"));
118   Column_x_positions col;
119
120   vector<Grob*> line (all_.begin () + breaks_[i],
121                       all_.begin () + breaks_[j] + 1);
122   Interval line_dims = line_dimensions_int (pscore_->layout (), i);
123   bool last = j == breaks_.size () - 1;
124   bool ragged = ragged_right || (last && ragged_last);
125
126   return get_line_configuration (line, line_dims[RIGHT] - line_dims[LEFT], line_dims[LEFT], ragged);
127 }
128
129 void
130 Constrained_breaking::resize (vsize systems)
131 {
132   systems_ = systems;
133
134   if (pscore_ && systems_ > valid_systems_)
135     {
136       for (vsize i = 0; i < state_.size (); i++)
137         state_[i].resize (breaks_.size () - starting_breakpoints_[i], systems_, Constrained_break_node ());
138
139       /* fill out the matrices */
140       for (vsize i = 0; i < state_.size (); i++)
141         for (vsize j = valid_systems_; j < systems_; j++)
142           for (vsize k = starting_breakpoints_[i] + j + 1; k < breaks_.size (); k++)
143             if (!calc_subproblem (i, j, k))
144               break; /* if we couldn't break this, it is too cramped already */
145       valid_systems_ = systems_;
146     }
147 }
148
149 vector<Column_x_positions>
150 Constrained_breaking::solve (vsize start, vsize end, vsize sys_count)
151 {
152   vsize start_brk = starting_breakpoints_[start];
153   vsize end_brk = prepare_solution (start, end, sys_count);
154
155   Matrix<Constrained_break_node> const &st = state_[start];
156   vector<Column_x_positions> ret;
157
158   /* find the first solution that satisfies constraints */
159   for (vsize sys = sys_count-1; sys != VPOS; sys--)
160     {
161       for (vsize brk = end_brk; brk != VPOS; brk--)
162         {
163           if (!isinf (st.at (brk, sys).details_.force_))
164             {
165               if (brk != end_brk)
166                 {
167                   warning (_ ("cannot find line breaking that satisfies constraints" ));
168                   ret.push_back (space_line (brk, end_brk));
169                 }
170               /* build up the good solution */
171               for (vsize cur_sys = sys; cur_sys != VPOS; cur_sys--)
172                 {
173                   vsize prev_brk = st.at (brk, cur_sys).prev_;
174                   assert (brk != VPOS);
175                   ret.push_back (space_line (prev_brk + start_brk, brk + start_brk));
176                   brk = prev_brk;
177                 }
178               reverse (ret);
179               return ret;
180             }
181         }
182     }
183   /* if we get to here, just put everything on one line */
184   warning (_ ("cannot find line breaking that satisfies constraints"));
185   ret.push_back (space_line (0, end_brk));
186   return ret;
187 }
188
189 vector<Column_x_positions>
190 Constrained_breaking::best_solution (vsize start, vsize end)
191 {
192   vsize min_systems =  min_system_count (start, end);
193   vsize max_systems = max_system_count (start, end);
194   Real best_demerits = infinity_f;
195   vector<Column_x_positions> best_so_far;
196
197   for (vsize i = min_systems; i <= max_systems; i++)
198     {
199       vsize brk = prepare_solution (start, end, i);
200       Real dem = state_[start].at (brk, i-1).demerits_;
201
202       if (dem < best_demerits)
203         {
204           best_demerits = dem;
205           best_so_far = solve (start, end, i);
206         }
207       else
208         {
209           vector<Column_x_positions> cur = solve (start, end, i);
210           bool too_many_lines = true;
211           
212           for (vsize j = 0; j < cur.size (); j++)
213             if (cur[j].force_ < 0)
214               {
215                 too_many_lines = false;
216                 break;
217               }
218           if (too_many_lines)
219             return best_so_far;
220         }
221     }
222   if (best_so_far.size ())
223     return best_so_far;
224   return solve (start, end, max_systems);
225 }
226
227 std::vector<Line_details>
228 Constrained_breaking::line_details (vsize start, vsize end, vsize sys_count)
229 {
230   vsize brk = prepare_solution (start, end, sys_count);
231   Matrix<Constrained_break_node> const &st = state_[start];
232   vector<Line_details> ret;
233
234   for (int sys = sys_count-1; sys >= 0 && brk != VPOS; sys--)
235     {
236       ret.push_back (st.at (brk, sys).details_);
237       brk = st.at (brk, sys).prev_;
238     }
239   reverse (ret);
240   return ret;
241 }
242
243 int
244 Constrained_breaking::min_system_count (vsize start, vsize end)
245 {
246   vsize sys_count;
247   vsize brk = prepare_solution (start, end, 1);
248   vsize rank = breaks_.size () - starting_breakpoints_[start];
249   Matrix<Constrained_break_node> const &st = state_[start];
250
251   /* sys_count < rank : rank is the # of breakpoints, we can't have more systems */
252   for (sys_count = 0; sys_count < rank; sys_count++)
253     {
254       if (sys_count >= valid_systems_)
255         {
256           resize (sys_count + 3);
257         }
258       if (!isinf (st.at (brk, sys_count).details_.force_))
259         return sys_count + 1;
260     }
261   /* no possible breaks satisfy constraints */
262   return 1;
263 }
264
265 int
266 Constrained_breaking::max_system_count (vsize start, vsize end)
267 {
268   vsize brk = (end >= start_.size ()) ? breaks_.size () : starting_breakpoints_[end];
269   return brk - starting_breakpoints_[start];
270 }
271
272 vsize
273 Constrained_breaking::prepare_solution (vsize start, vsize end, vsize sys_count)
274 {
275   assert (start < start_.size () && (end == VPOS || end <= start_.size ()));
276   assert (start < end);
277
278   resize (sys_count);
279   if (end == start_.size ())
280     end = VPOS;
281
282   vsize brk;
283   brk = end == VPOS ? breaks_.size () - 1 : starting_breakpoints_[end];
284   brk -= starting_breakpoints_[start];
285   return brk;
286 }
287
288 Constrained_breaking::Constrained_breaking (Paper_score *ps)
289 {
290   valid_systems_ = systems_ = 0;
291   start_.push_back (0);
292   pscore_ = ps;
293   initialize ();
294 }
295
296 Constrained_breaking::Constrained_breaking (Paper_score *ps, vector<vsize> const &start)
297   : start_ (start)
298 {
299   valid_systems_ = systems_ = 0;
300   pscore_ = ps;
301   initialize ();
302 }
303
304 /* find the forces for all possible lines and cache ragged_ and ragged_right_ */
305 void
306 Constrained_breaking::initialize ()
307 {
308   if (!pscore_)
309     return;
310
311   ragged_right_ = to_boolean (pscore_->layout ()->c_variable ("ragged-right"));
312   ragged_last_ = to_boolean (pscore_->layout ()->c_variable ("ragged-last"));
313       
314   Output_def *l = pscore_->layout ();
315   System *sys = pscore_->root_system ();
316   Real space = robust_scm2double (l->c_variable ("ideal-system-space"), 0);
317   SCM padding_scm = l->c_variable ("page-breaking-between-system-padding");
318   if (!scm_is_number (padding_scm))
319     padding_scm = l->c_variable ("between-system-padding");
320   Real padding = robust_scm2double (padding_scm, 0.0);
321
322   Interval first_line = line_dimensions_int (pscore_->layout (), 0);
323   Interval other_lines = line_dimensions_int (pscore_->layout (), 1);
324   /* do all the rod/spring problems */
325   breaks_ = pscore_->find_break_indices ();
326   all_ = pscore_->root_system ()->used_columns ();
327   lines_.resize (breaks_.size (), breaks_.size (), Line_details ());
328   vector<Real> forces = get_line_forces (all_,
329                                          other_lines.length (),
330                                          other_lines.length () - first_line.length (),
331                                          ragged_right_);
332   for (vsize i = 0; i + 1 < breaks_.size (); i++)
333     {
334       Real max_ext = 0;
335       for (vsize j = i + 1; j < breaks_.size (); j++)
336         {
337           int start = Paper_column::get_rank (all_[breaks_[i]]);
338           int end = Paper_column::get_rank (all_[breaks_[j]]);
339           Interval extent = sys->pure_height (sys, start, end);
340           bool last = j == breaks_.size () - 1;
341           bool ragged = ragged_right_ || (last && ragged_last_);
342           Line_details &line = lines_.at (j, i);
343
344           line.force_ = forces[i*breaks_.size () + j];
345           if (ragged && last && !isinf (line.force_))
346             line.force_ = (line.force_ < 0) ? infinity_f : 0;
347           if (isinf (line.force_))
348             break;
349
350           Grob *c = all_[breaks_[j]];
351           line.break_penalty_ = robust_scm2double (c->get_property ("line-break-penalty"), 0);
352           line.page_penalty_ = robust_scm2double (c->get_property ("page-break-penalty"), 0);
353           line.turn_penalty_ = robust_scm2double (c->get_property ("page-turn-penalty"), 0);
354           line.break_permission_ = c->get_property ("line-break-permission");
355           line.page_permission_ = c->get_property ("page-break-permission");
356           line.turn_permission_ = c->get_property ("page-turn-permission");
357
358           max_ext = max (max_ext, extent.length ());
359           line.extent_ = extent;
360           line.padding_ = padding;
361           line.space_ = space;
362           line.inverse_hooke_ = extent.length () + space;
363         }
364     }
365
366   /* work out all the starting indices */
367   for (vsize i = 0; i < start_.size (); i++)
368     {
369       vsize j;
370       for (j = 0; j + 1 < breaks_.size () && breaks_[j] < start_[i]; j++)
371         ;
372       starting_breakpoints_.push_back (j);
373       start_[i] = breaks_[j];
374     }
375   state_.resize (start_.size ());
376 }
377
378 Real
379 Constrained_breaking::combine_demerits (Real force, Real prev_force)
380 {
381   if (ragged_right_)
382     return force * force;
383
384   return force * force + (prev_force - force) * (prev_force - force);
385 }
386