]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam-quanting.cc
Adds a Flag grob to LilyPond.
[lilypond.git] / lily / beam-quanting.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1997--2011 Han-Wen Nienhuys <hanwen@xs4all.nl>
5   Jan Nieuwenhuizen <janneke@gnu.org>
6
7   LilyPond is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   LilyPond is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "beam-scoring-problem.hh"
22
23 #include <algorithm>
24 #include <queue>
25 #include <set>
26 using namespace std;
27
28 #include "align-interface.hh"
29 #include "beam.hh"
30 #include "direction.hh"
31 #include "directional-element-interface.hh"
32 #include "grob.hh"
33 #include "international.hh"
34 #include "libc-extension.hh"
35 #include "main.hh"
36 #include "output-def.hh"
37 #include "pointer-group-interface.hh"
38 #include "staff-symbol-referencer.hh"
39 #include "stencil.hh"
40 #include "stem.hh"
41 #include "warn.hh"
42
43 Real
44 get_detail (SCM alist, SCM sym, Real def)
45 {
46   SCM entry = scm_assq (sym, alist);
47
48   if (scm_is_pair (entry))
49     return robust_scm2double (scm_cdr (entry), def);
50   return def;
51 }
52
53 void
54 Beam_quant_parameters::fill (Grob *him)
55 {
56   SCM details = him->get_property ("details");
57
58   // General
59   BEAM_EPS = get_detail (details, ly_symbol2scm ("beam-eps"), 1e-3);
60   REGION_SIZE = get_detail (details, ly_symbol2scm ("region-size"), 2);
61
62   // forbidden quants
63   SECONDARY_BEAM_DEMERIT = get_detail (details, ly_symbol2scm ("secondary-beam-demerit"), 10.0);
64   STEM_LENGTH_DEMERIT_FACTOR = get_detail (details, ly_symbol2scm ("stem-length-demerit-factor"), 5);
65   HORIZONTAL_INTER_QUANT_PENALTY = get_detail (details, ly_symbol2scm ("horizontal-inter-quant"), 500);
66
67   STEM_LENGTH_LIMIT_PENALTY = get_detail (details, ly_symbol2scm ("stem-length-limit-penalty"), 5000);
68   DAMPING_DIRECTION_PENALTY = get_detail (details, ly_symbol2scm ("damping-direction-penalty"), 800);
69   HINT_DIRECTION_PENALTY = get_detail (details, ly_symbol2scm ("hint-direction-penalty"), 20);
70   MUSICAL_DIRECTION_FACTOR = get_detail (details, ly_symbol2scm ("musical-direction-factor"), 400);
71   IDEAL_SLOPE_FACTOR = get_detail (details, ly_symbol2scm ("ideal-slope-factor"), 10);
72   ROUND_TO_ZERO_SLOPE = get_detail (details, ly_symbol2scm ("round-to-zero-slope"), 0.02);
73
74   // Collisions
75   COLLISION_PENALTY = get_detail (details, ly_symbol2scm ("collision-penalty"), 500);
76   COLLISION_PADDING = get_detail (details, ly_symbol2scm ("collision-padding"), 0.5);
77   STEM_COLLISION_FACTOR = get_detail (details, ly_symbol2scm ("stem-collision-factor"), 0.1);
78 }
79
80 // Add x if x is positive, add |x|*fac if x is negative.
81 static Real
82 shrink_extra_weight (Real x, Real fac)
83 {
84   return fabs (x) * ((x < 0) ? fac : 1.0);
85 }
86
87 /****************************************************************/
88
89 Beam_configuration::Beam_configuration ()
90 {
91   y = Interval (0.0, 0.0);
92   demerits = 0.0;
93   next_scorer_todo = ORIGINAL_DISTANCE;
94 }
95
96 bool Beam_configuration::done () const
97 {
98   return next_scorer_todo >= NUM_SCORERS;
99 }
100
101 void Beam_configuration::add (Real demerit, const string &reason)
102 {
103   demerits += demerit;
104
105 #if DEBUG_BEAM_SCORING
106   if (demerit)
107     score_card_ += to_string (" %s %.2f", reason.c_str (), demerit);
108 #endif
109 }
110
111 Beam_configuration *Beam_configuration::new_config (Interval start,
112                                                     Interval offset)
113 {
114   Beam_configuration *qs = new Beam_configuration;
115   qs->y = Interval (int (start[LEFT]) + offset[LEFT],
116                     int (start[RIGHT]) + offset[RIGHT]);
117
118   // This orders the sequence so we try combinations closest to the
119   // the ideal offset first.
120   Real start_score = abs (offset[RIGHT]) + abs (offset[LEFT]);
121   qs->demerits = start_score / 1000.0;
122   qs->next_scorer_todo = ORIGINAL_DISTANCE + 1;
123
124   return qs;
125 }
126
127 Real
128 Beam_scoring_problem::y_at (Real x, Beam_configuration const *p) const
129 {
130   return p->y[LEFT] + (x - x_span[LEFT]) * p->y.delta () / x_span.delta ();
131 }
132
133 /****************************************************************/
134
135 /*
136   TODO:
137
138   - Make all demerits customisable
139
140   - Add demerits for quants per se, as to forbid a specific quant
141   entirely
142 */
143
144 // This is a temporary hack to see how much we can gain by using a
145 // priority queue on the beams to score.
146 static int score_count = 0;
147 LY_DEFINE (ly_beam_score_count, "ly:beam-score-count", 0, 0, 0,
148            (),
149            "count number of beam scores.")
150 {
151   return scm_from_int (score_count);
152 }
153
154 void Beam_scoring_problem::add_collision (Real x, Interval y,
155                                           Real score_factor)
156 {
157   if (edge_dirs[LEFT] == edge_dirs[RIGHT])
158     {
159       Direction d = edge_dirs[LEFT];
160
161       Real quant_range_y = quant_range[LEFT][-d]
162                            + (x - x_span[LEFT]) * (quant_range[RIGHT][-d] - quant_range[LEFT][-d]) / x_span.delta ();
163
164       if (d * (quant_range_y - minmax (d, y[UP], y[DOWN])) > 0)
165         {
166           return;
167         }
168     }
169
170   Beam_collision c;
171   c.beam_y_.set_empty ();
172
173   for (vsize j = 0; j < segments_.size (); j++)
174     {
175       if (segments_[j].horizontal_.contains (x))
176         c.beam_y_.add_point (segments_[j].vertical_count_ * beam_translation);
177       if (segments_[j].horizontal_[LEFT] > x)
178         break;
179     }
180   c.beam_y_.widen (0.5 * beam_thickness);
181
182   c.x_ = x;
183
184   y *= 1 / staff_space;
185   c.y_ = y;
186   c.base_penalty_ = score_factor;
187   collisions_.push_back (c);
188 }
189
190 void Beam_scoring_problem::init_collisions (vector<Grob *> grobs)
191 {
192   Grob *common_x = NULL;
193   segments_ = Beam::get_beam_segments (beam, &common_x);
194   vector_sort (segments_, beam_segment_less);
195   if (common[X_AXIS] != common_x)
196     {
197       programming_error ("Disagree on common x. Skipping collisions in beam scoring.");
198       return;
199     }
200
201   set<Grob *> stems;
202   for (vsize i = 0; i < grobs.size (); i++)
203     {
204       Box b;
205       for (Axis a = X_AXIS; a < NO_AXES; incr (a))
206         b[a] = grobs[i]->extent (common[a], a);
207
208       Real width = b[X_AXIS].length ();
209       Real width_factor = sqrt (width / staff_space);
210
211       Direction d = LEFT;
212       do
213         add_collision (b[X_AXIS][d], b[Y_AXIS], width_factor);
214       while (flip (&d) != LEFT);
215
216       Grob *stem = unsmob_grob (grobs[i]->get_object ("stem"));
217       if (stem && Stem::has_interface (stem) && Stem::is_normal_stem (stem))
218         {
219           stems.insert (stem);
220         }
221     }
222
223   for (set<Grob *>::const_iterator it (stems.begin ()); it != stems.end (); it++)
224     {
225       Grob *s = *it;
226       Real x = s->extent (common[X_AXIS], X_AXIS).center ();
227
228       Direction stem_dir = get_grob_direction (*it);
229       Interval y;
230       y.set_full ();
231       y[-stem_dir] = Stem::chord_start_y (*it) + (*it)->relative_coordinate (common[Y_AXIS], Y_AXIS)
232                      - beam->relative_coordinate (common[Y_AXIS], Y_AXIS);
233
234       Real factor = parameters.STEM_COLLISION_FACTOR;
235       if (!unsmob_grob (s->get_object ("beam")))
236         factor = 1.0;
237       add_collision (x, y, factor);
238     }
239 }
240
241 void Beam_scoring_problem::init_stems ()
242 {
243   extract_grob_set (beam, "covered-grobs", collisions);
244   extract_grob_set (beam, "stems", stems);
245   for (int a = 2; a--;)
246     {
247       common[a] = common_refpoint_of_array (stems, beam, Axis (a));
248       common[a] = common_refpoint_of_array (collisions, common[a], Axis (a));
249     }
250
251   Drul_array<Grob *> edge_stems (Beam::first_normal_stem (beam),
252                                  Beam::last_normal_stem (beam));
253   Direction d = LEFT;
254   do
255     x_span[d] = edge_stems[d] ? edge_stems[d]->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
256   while (flip (&d) != LEFT);
257
258   Drul_array<bool> dirs_found (0, 0);
259   for (vsize i = 0; i < stems.size (); i++)
260     {
261       Grob *s = stems[i];
262       if (!Stem::is_normal_stem (s))
263         continue;
264
265       Stem_info si (Stem::get_stem_info (s));
266       si.scale (1 / staff_space);
267       stem_infos.push_back (si);
268       dirs_found[si.dir_] = true;
269
270       bool f = to_boolean (s->get_property ("french-beaming"))
271                && s != edge_stems[LEFT] && s != edge_stems[RIGHT];
272
273       Real y = Beam::calc_stem_y (beam, s, common, x_span[LEFT], x_span[RIGHT], CENTER,
274                                   Interval (0, 0), f);
275       base_lengths.push_back (y / staff_space);
276       stem_xpositions.push_back (s->relative_coordinate (common[X_AXIS], X_AXIS));
277     }
278
279   edge_dirs = Drul_array<Direction> (CENTER, CENTER);
280   if (stem_infos.size ())
281     {
282       edge_dirs = Drul_array<Direction> (stem_infos[0].dir_,
283                                          stem_infos.back ().dir_);
284     }
285
286   is_xstaff = Align_interface::has_interface (common[Y_AXIS]);
287   is_knee = dirs_found[LEFT] && dirs_found[RIGHT];
288
289   staff_radius = Staff_symbol_referencer::staff_radius (beam);
290   edge_beam_counts = Drul_array<int>
291                      (Stem::beam_multiplicity (stems[0]).length () + 1,
292                       Stem::beam_multiplicity (stems.back ()).length () + 1);
293
294   // TODO - why are we dividing by staff_space?
295   beam_translation = Beam::get_beam_translation (beam) / staff_space;
296
297   d = LEFT;
298   do
299     {
300       quant_range[d].set_full ();
301       if (!edge_stems[d])
302         continue;
303
304       Real stem_offset = edge_stems[d]->relative_coordinate (common[Y_AXIS], Y_AXIS)
305                          - beam->relative_coordinate (common[Y_AXIS], Y_AXIS);
306       Interval heads = Stem::head_positions (edge_stems[d]) * 0.5 * staff_space;
307
308       Direction ed = edge_dirs[d];
309       heads.widen (0.5 * staff_space
310                    + (edge_beam_counts[d] - 1) * beam_translation + beam_thickness * .5);
311       quant_range[d][-ed] = heads[ed] + stem_offset;
312     }
313   while (flip (&d) != LEFT);
314
315   init_collisions (collisions);
316 }
317
318 Beam_scoring_problem::Beam_scoring_problem (Grob *me, Drul_array<Real> ys)
319 {
320   beam = me;
321   unquanted_y = ys;
322
323   /*
324     Calculations are relative to a unit-scaled staff, i.e. the quants are
325     divided by the current staff_space.
326   */
327   staff_space = Staff_symbol_referencer::staff_space (me);
328   beam_thickness = Beam::get_beam_thickness (me) / staff_space;
329   line_thickness = Staff_symbol_referencer::line_thickness (me) / staff_space;
330
331   // This is the least-squares DY, corrected for concave beams.
332   musical_dy = robust_scm2double (me->get_property ("least-squares-dy"), 0);
333
334   parameters.fill (me);
335   init_stems ();
336 }
337
338 void
339 Beam_scoring_problem::generate_quants (vector<Beam_configuration *> *scores) const
340 {
341   int region_size = (int) parameters.REGION_SIZE;
342
343   // Knees and collisions are harder, lets try some more possibilities
344   if (is_knee)
345     region_size += 2;
346   if (collisions_.size ())
347     region_size += 2;
348
349   Real straddle = 0.0;
350   Real sit = (beam_thickness - line_thickness) / 2;
351   Real inter = 0.5;
352   Real hang = 1.0 - (beam_thickness - line_thickness) / 2;
353   Real base_quants [] = {straddle, sit, inter, hang};
354   int num_base_quants = int (sizeof (base_quants) / sizeof (Real));
355
356   /*
357     Asymetry ? should run to <= region_size ?
358   */
359   vector<Real> unshifted_quants;
360   for (int i = -region_size; i < region_size; i++)
361     for (int j = 0; j < num_base_quants; j++)
362       {
363         unshifted_quants.push_back (i + base_quants[j]);
364       }
365
366   for (vsize i = 0; i < unshifted_quants.size (); i++)
367     for (vsize j = 0; j < unshifted_quants.size (); j++)
368       {
369         Beam_configuration *c
370           = Beam_configuration::new_config (unquanted_y,
371                                             Interval (unshifted_quants[i],
372                                                       unshifted_quants[j]));
373
374         Direction d = LEFT;
375         do
376           {
377             if (!quant_range[d].contains (c->y[d]))
378               {
379                 delete c;
380                 c = NULL;
381                 break;
382               }
383           }
384         while (flip (&d) != LEFT);
385         if (c)
386           scores->push_back (c);
387       }
388
389 }
390
391 void Beam_scoring_problem::one_scorer (Beam_configuration *config) const
392 {
393   score_count++;
394   switch (config->next_scorer_todo)
395     {
396     case SLOPE_IDEAL:
397       score_slope_ideal (config);
398       break;
399     case SLOPE_DIRECTION:
400       score_slope_direction (config);
401       break;
402     case SLOPE_MUSICAL:
403       score_slope_musical (config);
404       break;
405     case FORBIDDEN:
406       score_forbidden_quants (config);
407       break;
408     case STEM_LENGTHS:
409       score_stem_lengths (config);
410       break;
411     case COLLISIONS:
412       score_collisions (config);
413       break;
414     case HORIZONTAL_INTER:
415       score_horizontal_inter_quants (config);
416       break;
417
418     case NUM_SCORERS:
419     case ORIGINAL_DISTANCE:
420     default:
421       assert (false);
422     }
423   config->next_scorer_todo++;
424 }
425
426 Beam_configuration *
427 Beam_scoring_problem::force_score (SCM inspect_quants, const vector<Beam_configuration *> &configs) const
428 {
429   Drul_array<Real> ins = ly_scm2interval (inspect_quants);
430   Real mindist = 1e6;
431   Beam_configuration *best = NULL;
432   for (vsize i = 0; i < configs.size (); i++)
433     {
434       Real d = fabs (configs[i]->y[LEFT] - ins[LEFT]) + fabs (configs[i]->y[RIGHT] - ins[RIGHT]);
435       if (d < mindist)
436         {
437           best = configs[i];
438           mindist = d;
439         }
440     }
441   if (mindist > 1e5)
442     programming_error ("cannot find quant");
443
444   while (!best->done ())
445     one_scorer (best);
446
447   return best;
448 }
449
450 Drul_array<Real>
451 Beam_scoring_problem::solve () const
452 {
453   vector<Beam_configuration *> configs;
454   generate_quants (&configs);
455
456   if (configs.empty ())
457     {
458       programming_error ("No viable beam quanting found.  Using unquanted y value.");
459       return unquanted_y;
460     }
461
462   Beam_configuration *best = NULL;
463
464   bool debug
465     = to_boolean (beam->layout ()->lookup_variable (ly_symbol2scm ("debug-beam-scoring")));
466   SCM inspect_quants = beam->get_property ("inspect-quants");
467   if (scm_is_pair (inspect_quants))
468     {
469       debug = true;
470       best = force_score (inspect_quants, configs);
471     }
472   else
473     {
474       std::priority_queue < Beam_configuration *, std::vector<Beam_configuration *>,
475           Beam_configuration_less > queue;
476       for (vsize i = 0; i < configs.size (); i++)
477         queue.push (configs[i]);
478
479       /*
480         TODO
481
482         It would be neat if we generated new configurations on the
483         fly, depending on the best complete score so far, eg.
484
485         if (best->done()) {
486           if (best->demerits < sqrt(queue.size())
487             break;
488           while (best->demerits > sqrt(queue.size()) {
489             generate and insert new configuration
490           }
491         }
492
493         that would allow us to do away with region_size altogether.
494       */
495       while (true)
496         {
497           best = queue.top ();
498           if (best->done ())
499             break;
500
501           queue.pop ();
502           one_scorer (best);
503           queue.push (best);
504         }
505     }
506
507   Interval final_positions = best->y;
508
509 #if DEBUG_BEAM_SCORING
510   if (debug)
511     {
512       // debug quanting
513       int completed = 0;
514       for (vsize i = 0; i < configs.size (); i++)
515         {
516           if (configs[i]->done ())
517             completed++;
518         }
519
520       string card = best->score_card_ + to_string (" c%d/%d", completed, configs.size ());
521       beam->set_property ("annotation", ly_string2scm (card));
522     }
523 #endif
524
525   junk_pointers (configs);
526   return final_positions;
527 }
528
529 void
530 Beam_scoring_problem::score_stem_lengths (Beam_configuration *config) const
531 {
532   Real limit_penalty = parameters.STEM_LENGTH_LIMIT_PENALTY;
533   Drul_array<Real> score (0, 0);
534   Drul_array<int> count (0, 0);
535
536   for (vsize i = 0; i < stem_xpositions.size (); i++)
537     {
538       Real x = stem_xpositions[i];
539       Real dx = x_span.delta ();
540       Real beam_y = dx
541                     ? config->y[RIGHT] * (x - x_span[LEFT]) / dx + config->y[LEFT] * (x_span[RIGHT] - x) / dx
542                     : (config->y[RIGHT] + config->y[LEFT]) / 2;
543       Real current_y = beam_y + base_lengths[i];
544       Real length_pen = parameters.STEM_LENGTH_DEMERIT_FACTOR;
545
546       Stem_info info = stem_infos[i];
547       Direction d = info.dir_;
548
549       score[d] += limit_penalty * max (0.0, (d * (info.shortest_y_ - current_y)));
550
551       Real ideal_diff = d * (current_y - info.ideal_y_);
552       Real ideal_score = shrink_extra_weight (ideal_diff, 1.5);
553
554       /* We introduce a power, to make the scoring strictly
555          convex. Otherwise a symmetric knee beam (up/down/up/down)
556          does not have an optimum in the middle. */
557       if (is_knee)
558         ideal_score = pow (ideal_score, 1.1);
559
560       score[d] += length_pen * ideal_score;
561       count[d]++;
562     }
563
564   /* Divide by number of stems, to make the measure scale-free. */
565   Direction d = DOWN;
566   do
567     score[d] /= max (count[d], 1);
568   while (flip (&d) != DOWN);
569
570   config->add (score[LEFT] + score[RIGHT], "L");
571 }
572
573 void
574 Beam_scoring_problem::score_slope_direction (Beam_configuration *config) const
575 {
576   Real dy = config->y.delta ();
577   Real damped_dy = unquanted_y.delta ();
578   Real dem = 0.0;
579   /*
580     DAMPING_DIRECTION_PENALTY is a very harsh measure, while for
581     complex beaming patterns, horizontal is often a good choice.
582
583     TODO: find a way to incorporate the complexity of the beam in this
584     penalty.
585   */
586   if (sign (damped_dy) != sign (dy))
587     {
588       if (!dy)
589         {
590           if (fabs (damped_dy / x_span.delta ()) > parameters.ROUND_TO_ZERO_SLOPE)
591             dem += parameters.DAMPING_DIRECTION_PENALTY;
592           else
593             dem += parameters.HINT_DIRECTION_PENALTY;
594         }
595       else
596         dem += parameters.DAMPING_DIRECTION_PENALTY;
597     }
598
599   config->add (dem, "Sd");
600 }
601
602 // Score for going against the direction of the musical pattern
603 void
604 Beam_scoring_problem::score_slope_musical (Beam_configuration *config) const
605 {
606   Real dy = config->y.delta ();
607   Real dem = parameters.MUSICAL_DIRECTION_FACTOR
608              * max (0.0, (fabs (dy) - fabs (musical_dy)));
609   config->add (dem, "Sm");
610 }
611
612 // Score deviation from calculated ideal slope.
613 void
614 Beam_scoring_problem::score_slope_ideal (Beam_configuration *config) const
615 {
616   Real dy = config->y.delta ();
617   Real damped_dy = unquanted_y.delta ();
618   Real dem = 0.0;
619
620   Real slope_penalty = parameters.IDEAL_SLOPE_FACTOR;
621
622   /* Xstaff beams tend to use extreme slopes to get short stems. We
623      put in a penalty here. */
624   if (is_xstaff)
625     slope_penalty *= 10;
626
627   /* Huh, why would a too steep beam be better than a too flat one ? */
628   dem += shrink_extra_weight (fabs (damped_dy) - fabs (dy), 1.5)
629          * slope_penalty;
630
631   config->add (dem, "Si");
632 }
633
634 static Real
635 my_modf (Real x)
636 {
637   return x - floor (x);
638 }
639
640 // TODO - there is some overlap with forbidden quants, but for
641 // horizontal beams, it is much more serious to have stafflines
642 // appearing in the wrong place, so we have a separate scorer.
643 void
644 Beam_scoring_problem::score_horizontal_inter_quants (Beam_configuration *config) const
645 {
646   if (config->y.delta () == 0.0
647       && abs (config->y[LEFT]) < staff_radius * staff_space)
648     {
649       Real yshift = config->y[LEFT] - 0.5 * staff_space;
650       if (fabs (my_round (yshift) - yshift) < 0.01 * staff_space)
651         config->add (parameters.HORIZONTAL_INTER_QUANT_PENALTY, "H");
652     }
653 }
654
655 /*
656   TODO: The fixed value SECONDARY_BEAM_DEMERIT is probably flawed:
657   because for 32nd and 64th beams the forbidden quants are relatively
658   more important than stem lengths.
659 */
660 void
661 Beam_scoring_problem::score_forbidden_quants (Beam_configuration *config) const
662 {
663   Real dy = config->y.delta ();
664
665   Real extra_demerit = parameters.SECONDARY_BEAM_DEMERIT
666                        / max (edge_beam_counts[LEFT], edge_beam_counts[RIGHT]);
667
668   Direction d = LEFT;
669   Real dem = 0.0;
670   Real eps = parameters.BEAM_EPS;
671
672   do
673     {
674       for (int j = 1; j <= edge_beam_counts[d]; j++)
675         {
676           Direction stem_dir = edge_dirs[d];
677
678           /*
679             The 2.2 factor is to provide a little leniency for
680             borderline cases. If we do 2.0, then the upper outer line
681             will be in the gap of the (2, sit) quant, leading to a
682             false demerit.
683           */
684           Real gap1 = config->y[d] - stem_dir * ((j - 1) * beam_translation + beam_thickness / 2 - line_thickness / 2.2);
685           Real gap2 = config->y[d] - stem_dir * (j * beam_translation - beam_thickness / 2 + line_thickness / 2.2);
686
687           Interval gap;
688           gap.add_point (gap1);
689           gap.add_point (gap2);
690
691           for (Real k = -staff_radius;
692                k <= staff_radius + eps; k += 1.0)
693             if (gap.contains (k))
694               {
695                 Real dist = min (fabs (gap[UP] - k), fabs (gap[DOWN] - k));
696
697                 /*
698                   this parameter is tuned to grace-stem-length.ly
699                 */
700                 Real fixed_demerit = 0.4;
701
702                 dem += extra_demerit
703                        * (fixed_demerit
704                           + (1 - fixed_demerit) * (dist / gap.length ()) * 2);
705               }
706         }
707     }
708   while ((flip (&d)) != LEFT);
709
710   if (max (edge_beam_counts[LEFT], edge_beam_counts[RIGHT]) >= 2)
711     {
712       Real straddle = 0.0;
713       Real sit = (beam_thickness - line_thickness) / 2;
714       Real inter = 0.5;
715       Real hang = 1.0 - (beam_thickness - line_thickness) / 2;
716
717       Direction d = LEFT;
718       do
719         {
720           if (edge_beam_counts[d] >= 2
721               && fabs (config->y[d] - edge_dirs[d] * beam_translation) < staff_radius + inter)
722             {
723               // TODO up/down symmetry.
724               if (edge_dirs[d] == UP && dy <= eps
725                   && fabs (my_modf (config->y[d]) - sit) < eps)
726                 dem += extra_demerit;
727
728               if (edge_dirs[d] == DOWN && dy >= eps
729                   && fabs (my_modf (config->y[d]) - hang) < eps)
730                 dem += extra_demerit;
731             }
732
733           if (edge_beam_counts[d] >= 3
734               && fabs (config->y[d] - 2 * edge_dirs[d] * beam_translation) < staff_radius + inter)
735             {
736               // TODO up/down symmetry.
737               if (edge_dirs[d] == UP && dy <= eps
738                   && fabs (my_modf (config->y[d]) - straddle) < eps)
739                 dem += extra_demerit;
740
741               if (edge_dirs[d] == DOWN && dy >= eps
742                   && fabs (my_modf (config->y[d]) - straddle) < eps)
743                 dem += extra_demerit;
744             }
745         }
746       while (flip (&d) != LEFT);
747     }
748
749   config->add (dem, "F");
750 }
751
752 void
753 Beam_scoring_problem::score_collisions (Beam_configuration *config) const
754 {
755   Real demerits = 0.0;
756   for (vsize i = 0; i < collisions_.size (); i++)
757     {
758       Interval collision_y = collisions_[i].y_;
759       Real x = collisions_[i].x_;
760
761       Real center_beam_y = y_at (x, config);
762       Interval beam_y = center_beam_y + collisions_[i].beam_y_;
763
764       Real dist = infinity_f;
765       if (!intersection (beam_y, collision_y).is_empty ())
766         dist = 0.0;
767       else
768         dist = min (beam_y.distance (collision_y[DOWN]),
769                     beam_y.distance (collision_y[UP]));
770
771       Real scale_free
772         = max (parameters.COLLISION_PADDING - dist, 0.0) /
773           parameters.COLLISION_PADDING;
774       demerits
775       += collisions_[i].base_penalty_ *
776          pow (scale_free, 3) * parameters.COLLISION_PENALTY;
777     }
778
779   config->add (demerits, "C");
780 }