/
Breather.java
1216 lines (1194 loc) · 54.8 KB
/
Breather.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package net.cscott.sdr.calls;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.cscott.jdoctest.JDoctestRunner;
import net.cscott.sdr.util.Box;
import net.cscott.sdr.util.Fraction;
import net.cscott.sdr.util.Point;
import net.cscott.sdr.util.SdrToString;
import net.cscott.sdr.util.Tools.ListMultiMap;
import net.cscott.sdr.util.Tools.F; // list comprehension helper
import static net.cscott.sdr.util.Tools.foreach; // list comprehension
import static net.cscott.sdr.util.Tools.l;//list constructor
import static net.cscott.sdr.util.Tools.m;//map constructor
import static net.cscott.sdr.util.Tools.mml;//listmultimap constructor
import static net.cscott.sdr.util.Tools.p;//pair constructor
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.junit.runner.RunWith;
import EDU.Washington.grad.gjb.cassowary.CL;
import EDU.Washington.grad.gjb.cassowary.ClBooleanVariable;
import EDU.Washington.grad.gjb.cassowary.ClBranchAndBound;
import EDU.Washington.grad.gjb.cassowary.ClConstraint;
import EDU.Washington.grad.gjb.cassowary.ClLinearEquation;
import EDU.Washington.grad.gjb.cassowary.ClLinearExpression;
import EDU.Washington.grad.gjb.cassowary.ClLinearInequality;
import EDU.Washington.grad.gjb.cassowary.ClSimplexSolver;
import EDU.Washington.grad.gjb.cassowary.ClStrength;
import EDU.Washington.grad.gjb.cassowary.ClVariable;
import EDU.Washington.grad.gjb.cassowary.ExCLError;
import EDU.Washington.grad.gjb.cassowary.ExCLInternalError;
import EDU.Washington.grad.gjb.cassowary.ExCLNonlinearExpression;
import EDU.Washington.grad.gjb.cassowary.ExCLRequiredFailure;
/**
* The {@link Breather} class contains methods to reassemble and
* breathe formations.
*
* <p>The {@link #insert(Formation,Map) insert()} method pushes
* sub-formations into a meta-formation after performing (say) a four
* person call — ie, starting with a tidal wave, {@link
* Matcher} will pull out two four-person waves as a mini-wave as the
* meta-formation. We do a crossfire (say) from the mini-waves to get
* boxes. Now {@link #insert(Formation,Map)} will shove the boxes
* into the mini-wave meta-formation to get parallel ocean waves.</p>
*
* <p>The {@link #breathe(List) breathe()} method is a part of {@link
* #insert(Formation,Map) insert()} which is useful in its own right:
* it takes a {@link Formation} (or a list of {@link FormationPiece}s)
* and breathes it in or out to normalize the spacing between dancers.
* For example, after "trailers extend" from boxes, we need to make
* room for the resulting mini-wave in the center. If the ends then
* u-turn back and everyone extends again, the formation has to
* squeeze in again to erase the space.</p>
*
* <h3>Theory of breathing</h3>
* <p>First: identify collisions. Collided dancers are
* inserted into a miniwave which replaces them in the remainder of the
* algorithm. Second: resolve overlaps. Dancers which overlap have their
* boundaries adjusted so that they share a boundary, ideally at the midpoint
* of the overlap. We now use a mixed integer programming solver to perform
* an optimal adjustment, keeping handholds and making stars when possible.
* Third: Sort and order the boundary coordinates, and then allocate space
* between boundaries so that it is "just enough" to fit the dancers between
* them. If a dancer spans multiple boundary points, their allocation is
* divided equally between them. We use linear programming here to find
* an optimal expansion. Finally, the output formations are
* relocated so that they are centered between their new boundaries.
*
* @author C. Scott Ananian
* @version $Id: Breather.java,v 1.10 2006-10-30 22:09:29 cananian Exp $
*/
@RunWith(value=JDoctestRunner.class)
public class Breather {
private Breather() { }
/**
* Insert formations into a meta-formation. This reassembles the
* formation after we've decomposed it into (say) boxes to do a
* four-person call.
*
* @doc.test Insert COUPLEs, then TANDEMs into a RH_OCEAN_WAVE. Then, for
* a challenge, insert TANDEMs into a DIAMOND to give a t-bone column:
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> function xofy(meta, f) {
* > var i=0
* > var m=new java.util.LinkedHashMap()
* > for (d in Iterator(meta.sortedDancers())) {
* > var mm=new java.util.LinkedHashMap()
* > for (dd in Iterator(f.sortedDancers())) {
* > mm.put(dd, StandardDancer.values()[i++])
* > }
* > m.put(d, f.map(mm))
* > print(m.get(d).toStringDiagram())
* > }
* > return m
* > }
* js> meta = FormationList.RH_OCEAN_WAVE ; meta.toStringDiagram()
* ^ v ^ v
* js> m = xofy(meta, FormationList.COUPLE); undefined
* 1B^ 1G^
* 2B^ 2G^
* 3B^ 3G^
* 4B^ 4G^
* js> Breather.insert(meta, m).toStringDiagram()
* 1B^ 1G^ 2Gv 2Bv 3B^ 3G^ 4Gv 4Bv
* js> m = xofy(meta, FormationList.TANDEM); undefined
* 1B^
*
* 1G^
* 2B^
*
* 2G^
* 3B^
*
* 3G^
* 4B^
*
* 4G^
* js> Breather.insert(meta, m).toStringDiagram()
* 1B^ 2Gv 3B^ 4Gv
*
* 1G^ 2Bv 3G^ 4Bv
* js> meta = FormationList.RH_DIAMOND ; meta.toStringDiagram("|", Formation.dancerNames)
* | >
* |
* |^ v
* |
* | <
* js> m = xofy(meta, FormationList.TANDEM); undefined
* 1B^
*
* 1G^
* 2B^
*
* 2G^
* 3B^
*
* 3G^
* 4B^
*
* 4G^
* js> Breather.insert(meta, m).toStringDiagram()
* 1G> 1B>
*
* 2B^ 3Gv
*
* 2G^ 3Bv
*
* 4B< 4G<
*/
public static Formation insert(final Formation meta,
final Map<Dancer,Formation> components) {
List<FormationPiece> l =
new ArrayList<FormationPiece>(meta.dancers().size());
for (Dancer d : meta.dancers()) {
assert meta.location(d).facing.isExact();
l.add(new FormationPiece(meta.select(d).onlySelected(),
components.get(d),
(ExactRotation) meta.location(d).facing));
}
return breathe(l);
}
/*-----------------------------------------------------------------------*/
/** A component to be breathed into a complete formation. Each
* {@link FormationPiece} contains a position and a formation to be
* inserted at that position. */
public static class FormationPiece {
/** Input formation piece. The original formation is a simple
* superposition of these. */
public final Formation input;
/** The formation which will correspond to {@link #input} in the output
* (meta) formation. This might be a formation of a single
* {@link PhantomDancer Phantom}, for example.
* @see FormationList#SINGLE_DANCER
*/
public final Formation output;
/**
* Prepare an argument to the {@link #breathe} method.
* @param input Input formation piece.
* @param output Output formation piece.
* @param r
* The rotation to use for the output formation in the eventual
* result. Typically this is the rotation of formation {@link #input}
* from whatever the 'canonical' orientation of {@link #output} is.
* For example, if we are mapping single dancers to single dancers,
* then {@link #input} is the rotated offset result of
* {@link Formation#onlySelected()}, {@link #output} is
* {@link FormationList#SINGLE_DANCER} (which is facing north), and
* the rotation {@code imr} matches the rotation of the dancer in
* {@link #input}.
*/
public FormationPiece(Formation input, Formation output, ExactRotation r) {
this(input, output.rotate(r));
}
public FormationPiece(Formation input, Formation output) {
this.input = input;
this.output = output;
}
@Override
public String toString() {
return new ToStringBuilder(this, SdrToString.STYLE)
.append("input", input)
.append("output", output)
.toString();
}
}
/**
* Create a canonical formation by compressing the given one. This
* is just an invokation of {@link #breathe(List)} with
* trivial {@link FormationPiece}s consisting of a single dancer each.
*
* @doc.test From couples back to back, step out; then breathe in:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.BACK_TO_BACK_COUPLES ; f.toStringDiagram()
* ^ ^
*
* v v
* js> for (d in Iterator(f.dancers())) {
* > f=f.move(d,f.location(d).forwardStep(Fraction.ONE, false));
* > }; f.toStringDiagram()
* ^ ^
*
*
*
* v v
* js> Breather.breathe(f).toStringDiagram()
* ^ ^
*
* v v
* @doc.test From facing couples, take half a step in; breathe out:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.FACING_COUPLES ; f.toStringDiagram()
* v v
*
* ^ ^
* js> for (d in Iterator(f.dancers())) {
* > f=f.move(d,f.location(d).forwardStep(Fraction.ONE_HALF, false));
* > }; f.toStringDiagram()
* v v
* ^ ^
* js> Breather.breathe(f).toStringDiagram()
* v v
*
* ^ ^
* @doc.test From single three quarter tag, step out; then breathe in:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.RH_SINGLE_THREE_QUARTER_TAG ; f.toStringDiagram()
* ^
*
* ^ v
*
* v
* js> for (d in Iterator(f.tagged(TaggedFormation.Tag.END))) {
* > f=f.move(d,f.location(d).forwardStep(Fraction.ONE, false));
* > }; f.toStringDiagram()
* ^
*
*
* ^ v
*
*
* v
* js> Breather.breathe(f).toStringDiagram()
* ^
*
* ^ v
*
* v
* @doc.test From single quarter tag, take half a step in; breathe out:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.RH_SINGLE_QUARTER_TAG ; f.toStringDiagram()
* v
*
* ^ v
*
* ^
* js> for (d in Iterator(f.tagged(TaggedFormation.Tag.END))) {
* > f=f.move(d,f.location(d).forwardStep(Fraction.ONE, false));
* > }; f.toStringDiagram()
* v
* ^ v
* ^
* js> Breather.breathe(f).toStringDiagram()
* v
*
* ^ v
*
* ^
* @doc.test From right-hand diamond, take half a step in; breathe out:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.RH_DIAMOND ; f.toStringDiagram("|", Formation.dancerNames)
* | >
* |
* |^ v
* |
* | <
* js> for (d in Iterator(f.tagged(TaggedFormation.Tag.POINT))) {
* > f=f.move(d,f.location(d).sideStep(Fraction.valueOf(1,2), true));
* > }; f.toStringDiagram("|", Formation.dancerNames)
* | >
* |
* |^ v
* | <
* js> Breather.breathe(f).toStringDiagram("|", Formation.dancerNames)
* | >
* |
* |^ v
* |
* | <
* @doc.test From right-hand diamond, take 1 1/2 steps in; breathe out to stars:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.RH_DIAMOND ; f.toStringDiagram("|", Formation.dancerNames)
* | >
* |
* |^ v
* |
* | <
* js> for (d in Iterator(f.tagged(TaggedFormation.Tag.POINT))) {
* > f=f.move(d,f.location(d).sideStep(Fraction.valueOf(3,2), true));
* > }; f.toStringDiagram("|", Formation.dancerNames)
* | >
* |^ < v
* js> Breather.breathe(f).toStringDiagram("|", Formation.dancerNames)
* | >
* |^ v
* | <
* @doc.test Facing dancers step forward; resolve collision.
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.FACING_DANCERS ; f.toStringDiagram()
* v
*
* ^
* js> for (d in Iterator(f.dancers())) {
* > f=f.move(d,f.location(d).forwardStep(Fraction.ONE, false));
* > }; f
* net.cscott.sdr.calls.TaggedFormation[
* location={<phantom@7f>=0,0,n, <phantom@7e>=0,0,s}
* selected=[<phantom@7f>, <phantom@7e>]
* tags={<phantom@7f>=TRAILER, <phantom@7e>=TRAILER}
* ]
* js> Breather.breathe(f).toStringDiagram()
* ^ v
* @doc.test Facing couples step forward with a left-shoulder pass;
* resolve collision and breathe.
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = FormationList.FACING_COUPLES ; f.toStringDiagram()
* v v
*
* ^ ^
* js> for (d in Iterator(f.dancers())) {
* > f=f.move(d,f.location(d).forwardStep(Fraction.ONE, false).addFlags(Position.Flag.PASS_LEFT));
* > }; undefined
* js> Breather.breathe(f).toStringDiagram()
* v ^ v ^
* @doc.test From EvalPrim test:
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> m = new java.util.HashMap(); undefined
* js> function di(p) { m.put(new PhantomDancer(), p); }
* js> di(new Position(Fraction.mONE, Fraction.ONE, ExactRotation.NORTH));
* js> di(new Position(Fraction.mONE, Fraction.ZERO, ExactRotation.NORTH));
* js> di(new Position(Fraction.ONE, Fraction.ZERO, ExactRotation.SOUTH));
* js> di(new Position(Fraction.ONE, Fraction.mONE, ExactRotation.SOUTH));
* js> f = new Formation(m); f.toStringDiagram();
* ^
* ^ v
* v
* js> [f.location(d) for (d in Iterator(f.sortedDancers()))].join(' ')
* -1,1,n -1,0,n 1,0,s 1,-1,s
* js> ff = Breather.breathe(f); ff.toStringDiagram()
* ^
*
* ^ v
*
* v
* js> [ff.location(d) for (d in Iterator(ff.sortedDancers()))].join(' ')
* -1,2,n -1,0,n 1,0,s 1,-2,s
* @doc.test From 'do half of an ends cross run':
* js> importPackage(net.cscott.sdr.util) // for Fraction
* js> m = new java.util.HashMap(); undefined
* js> SD = StandardDancer; undefined
* js> m.put(SD.COUPLE_4_GIRL, new Position(Fraction.valueOf(-5,2), Fraction.ONE, ExactRotation.WEST)); undefined
* js> m.put(SD.COUPLE_1_GIRL, new Position(Fraction.valueOf(3,2), Fraction.ONE, ExactRotation.WEST)); undefined
* js> m.put(SD.COUPLE_4_BOY, new Position(Fraction.valueOf(-3), Fraction.ZERO, ExactRotation.NORTH, Position.Flag.ROLL_RIGHT)); undefined
* js> m.put(SD.COUPLE_3_BOY, new Position(Fraction.mONE, Fraction.ZERO, ExactRotation.SOUTH, Position.Flag.ROLL_RIGHT)); undefined
* js> m.put(SD.COUPLE_1_BOY, new Position(Fraction.ONE, Fraction.ZERO, ExactRotation.NORTH, Position.Flag.ROLL_RIGHT)); undefined
* js> m.put(SD.COUPLE_2_BOY, new Position(Fraction.valueOf(3), Fraction.ZERO, ExactRotation.SOUTH, Position.Flag.ROLL_RIGHT)); undefined
* js> m.put(SD.COUPLE_3_GIRL, new Position(Fraction.valueOf(-3,2), Fraction.mONE, ExactRotation.EAST)); undefined
* js> m.put(SD.COUPLE_2_GIRL, new Position(Fraction.valueOf(5,2), Fraction.mONE, ExactRotation.EAST)); undefined
* js> f = new Formation(m); f.toStringDiagram();
* 4G< 1G<
* 4B^ 3Bv 1B^ 2Bv
* 3G> 2G>
* js> [f.location(d) for (d in Iterator(f.sortedDancers()))].join(' ')
* -2 1/2,1,w 1 1/2,1,w -3,0,n,[ROLL_RIGHT] -1,0,s,[ROLL_RIGHT] 1,0,n,[ROLL_RIGHT] 3,0,s,[ROLL_RIGHT] -1 1/2,-1,e 2 1/2,-1,e
* js> ff = Breather.breathe(f); ff.toStringDiagram()
* 4G< 1G<
*
* 4B^ 3Bv 1B^ 2Bv
*
* 3G> 2G>
* js> [ff.location(d) for (d in Iterator(ff.sortedDancers()))].join(' ')
* -2 1/3,2,w 1 2/3,2,w -3,0,n,[ROLL_RIGHT] -1,0,s,[ROLL_RIGHT] 1,0,n,[ROLL_RIGHT] 3,0,s,[ROLL_RIGHT] -1 2/3,-2,e 2 1/3,-2,e
*/
public static Formation breathe(Formation f) {
// special case for 1/8-off formations
if (isOneEighthRotated(f)) {
Formation ff = breathe(f.rotate(ExactRotation.ONE_EIGHTH));
return ff.rotate(ExactRotation.ONE_EIGHTH.negate());
}
List<FormationPiece> fpl = new ArrayList<FormationPiece>
(f.dancers().size());
for (Dancer d: f.dancers()) {
Formation in = f.select(Collections.singleton(d)).onlySelected();
Position p = in.location(d);
p = p.relocate(Fraction.ZERO, Fraction.ZERO, p.facing);
Formation out = new Formation(m(p(d, p)));
fpl.add(new FormationPiece(in, out));
}
return breathe(fpl);
}
private static boolean isOneEighthRotated(Formation f) {
Rotation E = Rotation.fromAbsoluteString("x");
for (Dancer d : f.dancers())
if (!E.includes(f.location(d).facing))
return false;
return true;
}
/**
* Take a set of input formation pieces and substitute the
* given output formation pieces for them, breathing the result
* together so that the formation is compact. (The map giving the
* correspondence between dancers in
* the new formation and the input formations is given by the
* individual {@link FormationPiece} objects.) We also resolve
* collisions to right or left hands, depending on whether the
* pass-left flag is set for the {@link Position}s involved.
* @doc.test Triangle point breathes to center of the base:
* js> importPackage(net.cscott.sdr.util)
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f2 = new Formation(Tools.m(
* > Tools.p(StandardDancer.COUPLE_2_BOY, Position.getGrid(1,-1,"n")),
* > Tools.p(StandardDancer.COUPLE_2_GIRL, Position.getGrid(3,-1,"n"))))
* net.cscott.sdr.calls.Formation[
* location={COUPLE 2 BOY=1,-1,n, COUPLE 2 GIRL=3,-1,n}
* selected=[COUPLE 2 BOY, COUPLE 2 GIRL]
* ]
* js> f2.toStringDiagram()
* 2B^ 2G^
* js> fp2 = new Breather.FormationPiece(f2, FormationList.RH_MINIWAVE); undefined
* js> // point on far side
* js> f1 = new Formation(Tools.m(
* > Tools.p(StandardDancer.COUPLE_1_BOY, Position.getGrid(3,1,"e"))))
* net.cscott.sdr.calls.Formation[
* location={COUPLE 1 BOY=3,1,e}
* selected=[COUPLE 1 BOY]
* ]
* js> fp1 = new Breather.FormationPiece(f1, FormationList.SINGLE_DANCER); undefined
* js> Breather.breathe(Tools.l(fp1, fp2)).toStringDiagram()
* ^
*
* ^ v
* js> // now just slightly off-center
* js> f1 = new Formation(Tools.m(
* > Tools.p(StandardDancer.COUPLE_1_BOY, Position.getGrid(1,1,"e")
* > .forwardStep(Fraction.ONE_HALF, false))))
* net.cscott.sdr.calls.Formation[
* location={COUPLE 1 BOY=1 1/2,1,e}
* selected=[COUPLE 1 BOY]
* ]
* js> fp1 = new Breather.FormationPiece(f1, FormationList.SINGLE_DANCER); undefined
* js> Breather.breathe(Tools.l(fp1, fp2)).toStringDiagram()
* ^
*
* ^ v
* js> // point butting up against centerline
* js> // NOTE doesn't float to center. Is this correct?
* js> f1 = new Formation(Tools.m(
* > Tools.p(StandardDancer.COUPLE_1_BOY, Position.getGrid(1,1,"e"))))
* net.cscott.sdr.calls.Formation[
* location={COUPLE 1 BOY=1,1,e}
* selected=[COUPLE 1 BOY]
* ]
* js> fp1 = new Breather.FormationPiece(f1, FormationList.SINGLE_DANCER); undefined
* js> Breather.breathe(Tools.l(fp1, fp2)).toStringDiagram()
* ^
*
* ^ v
* @doc.test Middle of a run, runner breathes out slightly to make room:
* js> importPackage(net.cscott.sdr.util)
* js> f = new Formation(Tools.m(
* > Tools.p(StandardDancer.COUPLE_2_BOY, Position.getGrid(0,0,"n")),
* > Tools.p(StandardDancer.COUPLE_2_GIRL, Position.getGrid(0,1,"e"))))
* net.cscott.sdr.calls.Formation[
* location={COUPLE 2 GIRL=0,1,e, COUPLE 2 BOY=0,0,n}
* selected=[COUPLE 2 GIRL, COUPLE 2 BOY]
* ]
* js> f.toStringDiagram()
* 2G>
* 2B^
* js> f = Breather.breathe(f)
* net.cscott.sdr.calls.Formation[
* location={COUPLE 2 GIRL=0,2,e, COUPLE 2 BOY=0,0,n}
* selected=[COUPLE 2 GIRL, COUPLE 2 BOY]
* ]
* js> f.toStringDiagram()
* 2G>
*
* 2B^
* @doc.test Same thing with more dancers:
* js> importPackage(net.cscott.sdr.util)
* js> f = new Formation(Tools.m(
* > Tools.p(StandardDancer.COUPLE_3_BOY, Position.getGrid(-3,1,"n")),
* > Tools.p(StandardDancer.COUPLE_4_GIRL,Position.getGrid(-3,0,"w")),
* > Tools.p(StandardDancer.COUPLE_3_GIRL,Position.getGrid(-1,1,"e")),
* > Tools.p(StandardDancer.COUPLE_4_BOY, Position.getGrid(-1,0,"s")),
* > Tools.p(StandardDancer.COUPLE_2_BOY, Position.getGrid(1,1,"n")),
* > Tools.p(StandardDancer.COUPLE_1_GIRL,Position.getGrid(1,0,"w")),
* > Tools.p(StandardDancer.COUPLE_2_GIRL,Position.getGrid(3,1,"e")),
* > Tools.p(StandardDancer.COUPLE_1_BOY, Position.getGrid(3,0,"s")))
* > ).recenter();
* net.cscott.sdr.calls.Formation[
* location={COUPLE 3 BOY=-3,1/2,n, COUPLE 3 GIRL=-1,1/2,e, COUPLE 2 BOY=1,1/2,n, COUPLE 2 GIRL=3,1/2,e, COUPLE 4 GIRL=-3,-1/2,w, COUPLE 4 BOY=-1,-1/2,s, COUPLE 1 GIRL=1,-1/2,w, COUPLE 1 BOY=3,-1/2,s}
* selected=[COUPLE 3 BOY, COUPLE 3 GIRL, COUPLE 2 BOY, COUPLE 2 GIRL, COUPLE 4 GIRL, COUPLE 4 BOY, COUPLE 1 GIRL, COUPLE 1 BOY]
* ]
* js> f.toStringDiagram()
* 3B^ 3G> 2B^ 2G>
* 4G< 4Bv 1G< 1Bv
* js> f = Breather.breathe(f)
* net.cscott.sdr.calls.Formation[
* location={COUPLE 3 BOY=-3,1,n, COUPLE 3 GIRL=-1,1,e, COUPLE 2 BOY=1,1,n, COUPLE 2 GIRL=3,1,e, COUPLE 4 GIRL=-3,-1,w, COUPLE 4 BOY=-1,-1,s, COUPLE 1 GIRL=1,-1,w, COUPLE 1 BOY=3,-1,s}
* selected=[COUPLE 3 BOY, COUPLE 3 GIRL, COUPLE 2 BOY, COUPLE 2 GIRL, COUPLE 4 GIRL, COUPLE 4 BOY, COUPLE 1 GIRL, COUPLE 1 BOY]
* ]
* js> f.toStringDiagram()
* 3B^ 3G> 2B^ 2G>
*
* 4G< 4Bv 1G< 1Bv
*/
// note that we resolve collisions in input formation, but ignore any
// present in output formation. That ensures that we don't unnecessarily
// breathe space-invader calls, esp if the input formation is a single
// dancer giving the orientation only (or the match was used solely
// to assign tags).
public static Formation breathe(List<FormationPiece> pieces) {
try {
return _breathe(pieces);
} catch (ExCLError e) {
throw new BadCallException("Can't breathe");
}
}
private static Formation _breathe(List<FormationPiece> pieces) throws ExCLError {
// Locate collisions and resolve them to miniwaves.
pieces = resolveCollisions(pieces);
// center all output formations
pieces = centerOutputPieces(pieces);
// Trim boundaries to resolve overlaps
List<Box> inputBounds = trimOverlap(pieces);
// Find and sort boundaries of component formations.
Axis x = new Axis(), y = new Axis();
for (int i=0; i<pieces.size(); i++) {
FormationPiece fp = pieces.get(i);
Box inBound = inputBounds.get(i);
Box outBound = fp.output.bounds();
x.bounds.put(inBound.ll.x, Fraction.ZERO);
x.bounds.put(inBound.ur.x, Fraction.ZERO);
y.bounds.put(inBound.ll.y, Fraction.ZERO);
y.bounds.put(inBound.ur.y, Fraction.ZERO);
x.addBit(inBound.ll.x, inBound.ur.x, outBound.width());
y.addBit(inBound.ll.y, inBound.ur.y, outBound.height());
}
// make sure there's an entry for the centerline, even if no dancer
// is adjacent.
x.bounds.put(Fraction.ZERO, Fraction.ZERO);
y.bounds.put(Fraction.ZERO, Fraction.ZERO);
// okay, now expand our formations, until all our constraints are met
for (Axis axis: l(x, y)) {
// use Cassowary constraint solver (basic linear programming)
// to expand formation.
// solver setup: create variables for each boundary point;
// objective function minimizes all boundaries
ClSimplexSolver solver = new ClSimplexSolver();
Map<Fraction, ClVariable> vars =
new LinkedHashMap<Fraction, ClVariable>();
for (Fraction f: axis.bounds.keySet()) {
ClVariable v = new ClVariable(Fraction.ZERO);
ClStrength s = f.equals(Fraction.ZERO) ?
ClStrength.required : ClStrength.weak;
solver.addConstraint(new ClLinearEquation(v, Fraction.ZERO, s));
vars.put(f, v);
}
assert vars.containsKey(Fraction.ZERO);
// Constraint 1: Boundaries need to be strictly increasing
// (required constraint)
Fraction last = null;
for (Fraction f : axis.bounds.keySet()) {
if (last!=null)
solver.addConstraint(new ClLinearInequality
(vars.get(f), CL.Op.GEQ, vars.get(last)));
last = f;
}
// Constraint 2: Must fit formation (outer-inner >= size)
// (required constraint)
for (Bit b : axis.bits) {
ClVariable lo = vars.get(b.start), hi = vars.get(b.end);
solver.addConstraint(new ClLinearInequality
(CL.Plus(lo, b.size), CL.Op.LEQ, hi));
}
// Symmetry constraint: moving from edges in, gaps should
// be equal. (strong constraint, not required)
for (Bit b : axis.bits) {
// (inner and outer are actually reversed for negative coords,
// but it doesn't matter)
Fraction lastInner = b.start, lastOuter = b.end;
while(true) {
Fraction inner = axis.bounds.higherKey(lastInner);
Fraction outer = axis.bounds.lowerKey(lastOuter);
if (inner.compareTo(outer) >= 0) break; // done.
// okay, compare size of inner gap (inner-lastInner)
// to outer gap (lastOuter-outer).
ClLinearExpression innerSize =
CL.Minus(vars.get(inner), vars.get(lastInner));
ClLinearExpression outerSize =
CL.Minus(vars.get(lastOuter), vars.get(outer));
solver.addConstraintNoException(new ClLinearEquation
(innerSize, outerSize, ClStrength.strong));
lastInner = inner; lastOuter = outer;
}
}
// okay, read out the results.
for (Fraction f : axis.bounds.keySet()) {
axis.bounds.put(f, vars.get(f).value());
}
}
// assemble meta formation.
Map<Dancer,Position> nf = new LinkedHashMap<Dancer,Position>();
for (int i=0; i<pieces.size(); i++) {
FormationPiece fp = pieces.get(i);
Box origBounds = inputBounds.get(i);
Box newBounds = new Box(new Point(x.bounds.get(origBounds.ll.x),
y.bounds.get(origBounds.ll.y)),
new Point(x.bounds.get(origBounds.ur.x),
y.bounds.get(origBounds.ur.y)));
Point newCenter = newBounds.center();
// translate the output formation to this center.
for (Dancer d: fp.output.dancers()) {
Position oldPos = fp.output.location(d);
nf.put(d, oldPos.relocate(oldPos.x.add(newCenter.x),
oldPos.y.add(newCenter.y),
oldPos.facing));
}
}
return new Formation(nf);
}
/** Abstract representation of one dimension of a formation, used
* for the expansion algorithm. */
private static class Bit {
/** Original boundary corresponding to the inner border of the
* formation. */
final Fraction start;
/** Original boundary corresponding to the outer border of the
* formation. */
final Fraction end;
/** Minimum size needed for this formation piece. */
final Fraction size;
public Bit(Fraction start, Fraction end, Fraction size) {
this.start = start;
this.end = end;
this.size = size;
}
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("start", start.toProperString())
.append("end", end.toProperString())
.append("size", size.toProperString())
.toString();
}
}
/** State associated with the x or y axis; since we expand each axis
* separately, it's nice to abstract away exactly which one we're dealing
* with. */
private static class Axis {
final TreeMap<Fraction,Fraction> bounds =
new TreeMap<Fraction,Fraction>();
final List<Bit> bits =
new ArrayList<Bit>();
public Axis() {}
void addBit(Fraction start, Fraction end, Fraction size) {
// if this bit straddles zero, add two bits of half the size
if ((start.compareTo(Fraction.ZERO) >= 0) !=
(end.compareTo(Fraction.ZERO) > 0) ) {
addBit(start, Fraction.ZERO, size.divide(Fraction.TWO));
addBit(Fraction.ZERO, end, size.divide(Fraction.TWO));
} else {
// otherwise, just add the bit
bits.add(new Bit(start, end, size));
}
}
public String toString() {
return new ToStringBuilder(this, SdrToString.STYLE)
.append("bounds", bounds)
.append("bits", bits)
.toString();
}
}
/** Locate collisions and resolve them to miniwaves. */
private static List<FormationPiece> resolveCollisions(List<FormationPiece>
pieces) {
// hash to collect pieces with the same center
ListMultiMap<Point,FormationPiece> mm = mml();
for (FormationPiece fp : pieces)
mm.add(fp.input.bounds().center(), fp);
// now assemble result list of FormationPieces, merging collisions as
// we find them.
List<FormationPiece> result =
new ArrayList<FormationPiece>(pieces.size());
for (Point center: mm.keySet()) {
List<FormationPiece> l= mm.getValues(center);
switch(l.size()) {
case 1:
// no collision
result.add(l.get(0));
break;
case 2:
// collision!
result.add(collide(l.get(0), l.get(1)));
break;
default:
// illegal if more then 2 dancers collide on a spot
throw new BadCallException("more than two dancers colliding");
}
}
return result;
}
/* Ensure that fp.output is centered, for every formation pieces. */
private static List<FormationPiece> centerOutputPieces(List<FormationPiece>
pieces) {
return foreach(pieces, new F<FormationPiece,FormationPiece>() {
@Override
public FormationPiece map(FormationPiece fp) {
return new FormationPiece(fp.input, fp.output.recenter());
}
});
}
/** Collide two formation pieces, creating a new FormationPiece
* with the resulting miniwave of pieces. */
private static FormationPiece collide(FormationPiece a, FormationPiece b) {
boolean passLeft = isLeft(a.input);
if (passLeft != isLeft(b.input))
throw new BadCallException("inconsistent passing shoulder");
Formation meta = passLeft ?
FormationList.LH_MINIWAVE : FormationList.RH_MINIWAVE ;
Dancer[] dd = meta.sortedDancers().toArray(new Dancer[2]);
// use rotation of a.input and b.input to determine
// how to rotate meta formation, such that 'a' maps to dd[0]
// and 'b' maps to dd[1]
ExactRotation[] rr = new ExactRotation[] {
(ExactRotation) formationFacing(a.input, Fraction.ONE),
(ExactRotation) formationFacing(b.input, Fraction.ONE)
};
if (rr[0]==null || rr[1]==null)
throw new BadCallException("inconsistent facing direction");
if (!rr[0].add(Fraction.ONE_HALF).equals(rr[1]))
throw new BadCallException("collision but not facing opposite");
meta = meta.rotate(rr[0].subtract(meta.location(dd[0]).facing.amount));
// this is a little odd; insert wants to rotate the output formations
// to match the facing directions in the meta formation. But our
// output formations are already facing the right way, so force all
// the facing directions in the meta to 'north'
for (Dancer d : meta.dancers()) {
Position p = meta.location(d);
meta = meta.move(d, p.relocate(p.x, p.y, ExactRotation.ZERO));
}
// okay, put the pieces together!
Formation f = insert(meta, m(p(dd[0],a.output),p(dd[1],b.output)));
return new FormationPiece(a/*pick one arbitrarily*/.input, f);
}
/** Check that the {@link Position.Flag#PASS_LEFT} flag is consistent
* on all dancers in {@code fp.input}, and return true if it is
* present.
*/
private static boolean isLeft(Formation f) {
boolean sawRight = false, sawLeft = false;
for (Dancer d : f.dancers()) {
if (f.location(d).flags.contains(Position.Flag.PASS_LEFT))
sawLeft = true;
else
sawRight = true;
}
assert sawLeft || sawRight : "what, no dancers?";
if (sawLeft && sawRight)
throw new BadCallException("inconsistent passing shoulder");
return sawLeft;
}
/** Return a consistent facing direction (modulo the modulus) if the
* formation f has one, or else return null. */
private static Rotation formationFacing(Formation f, Fraction modulus){
Rotation r = null;
// find "most exact" facing direction (largest modulus)
for (Dancer d : f.dancers()) {
Rotation rr = f.location(d).facing;
if (r==null || r.modulus.compareTo(rr.modulus) < 0)
r = rr;
}
assert r!=null : "what, no dancers?";
// normalize to the desired level of (in)exactness.
if (r.modulus.compareTo(modulus) < 0)
return null; // formation direction is vague
r = Rotation.create(r.amount, modulus);
// ensure all dancers are consistent with this.
for (Dancer d : f.dancers()) {
Rotation rr = f.location(d).facing;
if (!r.includes(rr))
return null; // inconsistent facing direction
}
return r;
}
/**
* Create a list of trimmed bounding boxes <i>which do not overlap</i>
* from the given list of potentially-overlapping {@link FormationPiece}s.
* We are only concerned with the {@link FormationPiece#input} formations
* in the {@link FormationPiece}s. This is a mess of heuristics and
* hacks. Currently: we prefer to trim boundaries which are not shared
* (ie, don't break existing proper handholds), and then order by the
* size of the overlap, trimming smallest to largest overlap. We also
* have a special "star" recognition algorithm, and don't attempt to
* trim edges involved in a star. The goal is to ensure that as you move
* the points of a diamond inward, you never force the centers apart, until
* you get to the point where the points and centers are equidistant --
* at that point you have a star. If you continue bringing the points
* in, you should really breathe out to a star (ie, still avoid breaking
* the centers' existing handhold), but at the moment we'll breathe out
* to a diamond instead: we only preserve stars if they already exist,
* we never make stars.
*/
// test cases are contained within doctests for public breathe()
private static List<Box> trimOverlap(List<FormationPiece> pieces) {
try {
return _trimOverlap(pieces);
} catch (ExCLInternalError e) {
assert false; // should never happen
} catch (ExCLRequiredFailure e) {
// fall through
}
throw new BadCallException("can't trim");
}
private static boolean hasAnyOverlaps(List<FormationPiece> pieces) {
for (int i=0; i<pieces.size(); i++) {
Box iBounds = pieces.get(i).input.bounds();
for (int j=i+1; j<pieces.size(); j++) {
Box jBounds = pieces.get(j).input.bounds();
if (iBounds.overlaps(jBounds))
return true;
}
}
return false;
}
private static List<Box> _trimOverlap(List<FormationPiece> pieces)
throws ExCLRequiredFailure, ExCLInternalError {
// quick out if no overlaps
if (!hasAnyOverlaps(pieces)) {
List<Box> bounds = new ArrayList<Box>(pieces.size());
for (FormationPiece fp : pieces)
bounds.add(fp.input.bounds());
return bounds;
}
List<VariableBox> vars = new ArrayList<VariableBox>(pieces.size());
// create variables and basic constraints
ClBranchAndBound solver = new ClBranchAndBound();
for (FormationPiece fp : pieces)
vars.add(new VariableBox(solver, fp.input));
// add pairwise constraints
for (int i=0; i<pieces.size(); i++) {
for (int j=i+1; j<pieces.size(); j++) {
VariableBox va = vars.get(i), vb = vars.get(j);
// no X overlap | some X overlap | total X overlap
// no Y overlap skip skip skip
// some Y overlap skip resolve X or Y resolve Y
// total Y overlap skip resolve X error
if (va.toBox().overlaps(vb.toBox())) {
PairedConstraint<ClLinearInequality> xOverlap =
va.overlapConstraint(vb,true);
PairedConstraint<ClLinearInequality> yOverlap =
va.overlapConstraint(vb,false);
List<PairedConstraint<ClLinearEquation>> star =
va.starConstraints(vb);
List<ClBooleanVariable> options =
new ArrayList<ClBooleanVariable>(3);
if (star!=null) {
// option 1: could make a star
ClBooleanVariable sw = new ClBooleanVariable(solver);
for (PairedConstraint<ClLinearEquation> pc : star) {
solver.addConstraintIf(sw, pc.required);
if (pc.symmetry != null)
solver.addConstraintIf(sw, pc.symmetry);
}
options.add(sw);
}
if (xOverlap!=null) {
// option 2: could resolve the x overlap
ClBooleanVariable sw = new ClBooleanVariable(solver);
solver.addConstraintIf(sw, xOverlap.required);
solver.addConstraintIf(sw, xOverlap.symmetry);
options.add(sw);
}
if (yOverlap!=null) {
// option 3: could resolve the y overlap
ClBooleanVariable sw = new ClBooleanVariable(solver);
solver.addConstraintIf(sw, yOverlap.required);
solver.addConstraintIf(sw, yOverlap.symmetry);
options.add(sw);
}
// we can only take one of these options.
if (!options.isEmpty()) {
ClLinearExpression sum =
new ClLinearExpression(Fraction.mONE);
for (ClBooleanVariable v : options)
sum = sum.addVariable(v);
solver.addConstraint(new ClLinearEquation(sum));
}
}
// try to keep handholds (optional constraints)
List<PairedConstraint<ClLinearEquation>> handConstraints =
va.handConstraints(vb);
if (handConstraints!=null) {
ClBooleanVariable sw = new ClBooleanVariable(solver);
for (PairedConstraint<ClLinearEquation> pc:handConstraints){
solver.addConstraintIf(sw, pc.required);
if (pc.symmetry != null)
solver.addConstraintIf(sw, pc.symmetry);
}
// w/ medium strength, request sw to be 1
solver.addConstraint
(new ClLinearEquation(sw, Fraction.ONE, ClStrength.medium));
}
}
}
// sanity check: verify that var values haven't changed before solving
for (int i=0; i<pieces.size(); i++)
assert pieces.get(i).input.bounds().equals(vars.get(i).toBox());
// solve constraints, return list of new boundaries.
solver.solve();
List<Box> bounds = new ArrayList<Box>(pieces.size());
for (VariableBox v : vars)
bounds.add(v.toBox());
return bounds;
}
/** A {@link Box}, except using {@link ClVariable}s to represent the
* left/right/bottom/top coordinates.
*/
private static class VariableBox {
final ClVariable left, bottom;
final ClVariable right, top;
/**
* Formation "handhold" direction modulo 1/2, or {@code} null if it does
* not have a consistent handhold direction. For a dancer facing
* north or south, the hand hold direction is "east and west"; for
* dancers facing east or west, the hand hold direction is "north and
* south", etc.
*/
final Rotation handholdDir;
/** Create a new {@link VariableBox} corresponding to the bounds of
* the specified input {@link Formation}.
*/
public VariableBox(ClBranchAndBound s, Formation input)
throws ExCLRequiredFailure, ExCLInternalError {
Box b = input.bounds();
this.left = new ClVariable(b.ll.x);
this.bottom = new ClVariable(b.ll.y);
this.right = new ClVariable(b.ur.x);
this.top = new ClVariable(b.ur.y);
Rotation hhD = formationFacing(input, Fraction.ONE_HALF);
this.handholdDir = (hhD==null)?null:hhD.add(Fraction.ONE_QUARTER);
// stays: try to keep the bounds in the same place if possible
for (ClVariable v : l(left, bottom, right, top))