-
Notifications
You must be signed in to change notification settings - Fork 0
/
blocks.go
1218 lines (1081 loc) · 30 KB
/
blocks.go
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 questions
import (
"errors"
"fmt"
"strings"
ex "github.com/benoitkugler/maths-online/server/src/maths/expression"
"github.com/benoitkugler/maths-online/server/src/maths/functiongrapher"
"github.com/benoitkugler/maths-online/server/src/maths/questions/client"
"github.com/benoitkugler/maths-online/server/src/maths/repere"
)
const exhaustiveTextKind = "exhaustiveTextKind"
var (
_ Block = TextBlock{}
_ Block = FormulaBlock{}
_ Block = VariationTableBlock{}
_ Block = SignTableBlock{}
_ Block = FigureBlock{}
_ Block = FunctionsGraphBlock{}
_ Block = TableBlock{}
_ Block = TreeBlock{}
)
// Block form the actual content of a question
// it is stored in a DB in generic form, but may be instantiated
// against random parameter values
type Block interface {
// ID is only used by answer fields
instantiate(params ex.Vars, ID int) (instance, error)
// setupValidator is called on teacher input
// it must :
// - performs validation not depending on instantiated parameters
// - delegates to `validator` for the other
// is is also meant to ensure that only valid content is persisted on DB
setupValidator(*ex.RandomParameters) (validator, error)
}
// ParameterEntry is either a single variable definition,
// a special function or a (possibly multiline) comment.
type ParameterEntry interface {
// Return a user friendly description
String() string
// mergeTo returns an `ErrDuplicateParameter` error if parameters are already defined
mergeTo(vars *ex.RandomParameters) error
}
func (rp Rp) String() string {
return fmt.Sprintf("%s = %s", rp.Variable, rp.Expression)
}
func (it In) String() string { return string(it) }
func (cm Co) String() string { return string(cm) }
func (rp Rp) mergeTo(vars *ex.RandomParameters) error {
return vars.ParseVariable(rp.Variable, rp.Expression)
}
func (it In) mergeTo(vars *ex.RandomParameters) error {
return vars.ParseIntrinsic(string(it))
}
// Comment are ignored
func (Co) mergeTo(vars *ex.RandomParameters) error { return nil }
func (comment Co) isTodo() bool {
return strings.Contains(strings.ToLower(string(comment)), "todo")
}
// ToMap may only be used after `Validate`
func (pr Parameters) ToMap() *ex.RandomParameters {
out := ex.NewRandomParameters()
for _, entry := range pr {
_ = entry.mergeTo(out) // error is check in Validate
}
return out
}
// HasTODO returns true if one of the comment has a TODO mention
func (pr Parameters) HasTODO() bool {
for _, entry := range pr {
if entry, ok := entry.(Co); ok && entry.isTodo() {
return true
}
}
return false
}
type Rp struct {
Expression string `json:"expression"` // as typed by the user, but validated
Variable ex.Variable `json:"variable"`
}
// String form on an intrinsic call, validated by expression.ParseIntrinsic
type In string
type Co string
// QuestionPage is the fundamental object to build exercices.
// It is mainly consituted of a list of content blocks, which
// describes the question (description, question, field answer),
// and are parametrized by random values.
type QuestionPage struct {
Enonce Enonce `json:"enonce" gomacro-opaque:"dart"`
Parameters Parameters `json:"parameters" gomacro-opaque:"dart"` // random parameters shared by the all the blocks
Correction Enonce `json:"correction" gomacro-opaque:"dart"`
}
// Instantiate returns a deep copy of `qu`, where all random parameters
// have been resolved.
// It assumes that the expressions and random parameters definitions are valid :
// if an error is encountered, it is returned as a TextInstance displaying the error.
func (qu QuestionPage) Instantiate() (out QuestionInstance, vars ex.Vars) {
out, vars, err := qu.InstantiateErr()
if err != nil {
out = QuestionInstance{Enonce: EnonceInstance{
TextInstance{
Parts: []client.TextOrMath{
{
Text: fmt.Sprintf("Erreur inattendue : %v", err),
},
},
},
}}
}
return out, vars
}
func (qu QuestionPage) InstantiateWith(params ex.Vars) (QuestionInstance, error) {
enonce, err := qu.Enonce.InstantiateWith(params)
if err != nil {
return QuestionInstance{}, err
}
correction, err := qu.Correction.InstantiateWith(params)
if err != nil {
return QuestionInstance{}, err
}
return QuestionInstance{enonce, correction}, err
}
// InstantiateErr is a shortcut to :
// - instantiate [Parameters]
// - instantiate [Enonce] with these parameters
// - instantiate [Correction] with these parameters
func (qu QuestionPage) InstantiateErr() (QuestionInstance, ex.Vars, error) {
// generate random params
rp, err := qu.Parameters.ToMap().Instantiate()
if err != nil {
return QuestionInstance{}, nil, err
}
instance, err := qu.InstantiateWith(rp)
return instance, rp, err
}
func (qu Enonce) expandText() Enonce {
out := make(Enonce, 0, len(qu))
for _, b := range qu {
if text, isText := b.(TextBlock); isText {
out = append(out, text.expandFormulas()...)
} else {
out = append(out, b)
}
}
return out
}
// InstantiateWith uses the given values to instantiate the general question
func (qu Enonce) InstantiateWith(params ex.Vars) (EnonceInstance, error) {
qu = qu.expandText()
enonce := make(EnonceInstance, len(qu))
var currentID int
for j, bl := range qu {
var err error
enonce[j], err = bl.instantiate(params, currentID)
if err != nil {
return nil, err
}
if _, isField := enonce[j].(fieldInstance); isField {
currentID++
}
}
return enonce, nil
}
// TextPart is either a plain text, a LaTeX code or an expression
type TextPart struct {
Content string
Kind TextKind
}
func NewPText(content string) TextPart {
return TextPart{Content: content, Kind: Text}
}
func NewPMath(content string) TextPart {
return TextPart{Content: content, Kind: StaticMath}
}
func NewPExpr(content string) TextPart {
return TextPart{Content: content, Kind: Expression}
}
func (tp TextPart) instantiate(params ex.Vars) (client.TextOrMath, error) {
switch tp.Kind {
case Text:
return client.TextOrMath{Text: tp.Content}, nil
case StaticMath:
return client.TextOrMath{Text: tp.Content, IsMath: true}, nil
case Expression:
expr, err := ex.ParseCompound(tp.Content)
if err != nil {
return client.TextOrMath{}, err
}
expr.Substitute(params)
return client.TextOrMath{Text: expr.AsLaTeX(), IsMath: true}, nil
default:
panic(exhaustiveTextKind)
}
}
func (tp TextPart) validate() error {
switch tp.Kind {
case Text, StaticMath:
return nil // nothing to do
case Expression:
_, err := ex.ParseCompound(tp.Content)
return err
default:
panic(exhaustiveTextKind)
}
}
type TextParts []TextPart
// instantiate merges adjacent math chunks so that latex expression are not split up
// and may be successfully parsed by the client
func (tp TextParts) instantiate(params ex.Vars) (client.TextLine, error) {
var parts client.TextLine
for _, p := range tp {
sample, err := p.instantiate(params)
if err != nil {
return nil, err
}
L := len(parts)
if L == 0 {
parts = append(parts, sample)
continue
}
// check if the previous chunk as same type
if parts[L-1].IsMath == sample.IsMath {
// simply merge the contents
parts[L-1].Text = parts[L-1].Text + sample.Text
} else { // start a new chunk
parts = append(parts, sample)
}
}
return parts, nil
}
// assume all parts are either static math or expression.
func (tp TextParts) instantiateAndMerge(params ex.Vars) (string, error) {
parts, err := tp.instantiate(params)
if err != nil {
return "", err
}
chunks := make([]string, len(parts))
for i, p := range parts {
chunks[i] = p.Text
}
return strings.Join(chunks, ""), nil
}
// TextBlock is a chunk of text
// which may contain maths
// It support basic interpolation syntax.
type TextBlock struct {
Parts Interpolated
Bold bool
Italic bool
Smaller bool
}
// return TextBlock, FormulaBlock or NumberFieldBlock
func (t TextBlock) expandFormulas() []Block {
blocks := t.Parts.parseFormula()
out := make([]Block, len(blocks))
for i, b := range blocks {
switch b.kind {
case iText:
out[i] = TextBlock{Parts: Interpolated(b.s), Bold: t.Bold, Italic: t.Italic, Smaller: t.Smaller}
case iFormula:
out[i] = FormulaBlock{Parts: Interpolated(b.s)}
case iNumberField:
out[i] = NumberFieldBlock{Expression: b.s}
}
}
return out
}
func (t TextBlock) instantiate(params ex.Vars, _ int) (instance, error) {
parts, err := t.Parts.instantiate(params)
if err != nil {
return nil, err
}
return TextInstance{
Parts: parts,
Bold: t.Bold,
Italic: t.Italic,
Smaller: t.Smaller,
}, nil
}
func (t TextBlock) setupValidator(*ex.RandomParameters) (validator, error) {
_, err := t.Parts.parse()
return noOpValidator{}, err
}
// FormulaContent is a list of chunks, either
// - static math symbols, such as f(x) =
// - valid expression, such as a*x - b, which will be instantiated
//
// when rendering the question
//
// For instance, the formula "f(x) = a*(x + 2)"
// is represented by two FormulaPart elements:
//
// { f(x) = } and { a*(x + 2) }
type FormulaContent []FormulaPart
// FormulaPart forms a logic chunk of a formula.
type FormulaPart struct {
Content string
IsExpression bool // when true, Content is interpreted as an expression.Expression
}
// FormulaBlock is a math formula, which should be display using
// a LaTeX renderer.
type FormulaBlock struct {
Parts Interpolated
}
func (f FormulaBlock) instantiate(params ex.Vars, _ int) (instance, error) {
parts, err := f.Parts.parse()
if err != nil {
return nil, err
}
partsInstance, err := parts.instantiate(params)
if err != nil {
return nil, err
}
out := make(FormulaDisplayInstance, len(partsInstance))
for i, c := range partsInstance {
out[i] = c.Text
}
return out, nil
}
func (f FormulaBlock) setupValidator(*ex.RandomParameters) (validator, error) {
_, err := f.Parts.parse()
return noOpValidator{}, err
}
func evaluateExpr(expr string, params ex.Vars) (float64, error) {
e, err := ex.Parse(expr)
if err != nil {
return 0, err
}
return e.Evaluate(params)
}
// parse, substitute and return LaTeX format
func instantiateLaTeXExpr(expr string, params ex.Vars) (string, error) {
e, err := ex.Parse(expr)
if err != nil {
return "", err
}
e.Substitute(params)
return e.AsLaTeX(), nil
}
type VariationTableBlock struct {
Label Interpolated
Xs []string // expressions
Fxs []string // expressions
}
func (vt VariationTableBlock) instantiateVT(params ex.Vars) (VariationTableInstance, error) {
out := VariationTableInstance{
Xs: make([]evaluatedExpression, len(vt.Xs)),
Fxs: make([]evaluatedExpression, len(vt.Fxs)),
}
var err error
out.Label, err = vt.Label.instantiateAndMerge(params)
if err != nil {
return out, err
}
for i, c := range vt.Xs {
out.Xs[i], err = newEvaluatedExpression(c, params)
if err != nil {
return out, err
}
}
for i, c := range vt.Fxs {
out.Fxs[i], err = newEvaluatedExpression(c, params)
if err != nil {
return out, err
}
}
return out, nil
}
func (vt VariationTableBlock) instantiate(params ex.Vars, _ int) (instance, error) {
return vt.instantiateVT(params)
}
func (vt VariationTableBlock) setupValidatorVT() (variationTableValidator, error) {
label, err := vt.Label.parse()
if err != nil {
return variationTableValidator{}, err
}
if len(vt.Xs) < 2 {
return variationTableValidator{}, errors.New("Au moins deux colonnes sont attendues.")
}
if len(vt.Xs) != len(vt.Fxs) {
return variationTableValidator{}, errors.New("internal error: expected same length for X and Fx")
}
xExprs := make([]*ex.Expr, len(vt.Xs))
fxExprs := make([]*ex.Expr, len(vt.Fxs))
for i, c := range vt.Xs {
var err error
xExprs[i], err = ex.Parse(c)
if err != nil {
return variationTableValidator{}, err
}
fxExprs[i], err = ex.Parse(vt.Fxs[i])
if err != nil {
return variationTableValidator{}, err
}
}
return variationTableValidator{label: label, xs: xExprs, fxs: fxExprs}, nil
}
func (vt VariationTableBlock) setupValidator(*ex.RandomParameters) (validator, error) {
out, err := vt.setupValidatorVT()
if err != nil {
return nil, err
}
return out, nil
}
type FunctionSign struct {
Label Interpolated
FxSymbols []client.SignSymbol
Signs []bool
}
type SignTableBlock struct {
Xs []string // valid expression
Functions []FunctionSign
}
func (st SignTableBlock) instantiate(params ex.Vars, _ int) (instance, error) {
return st.instantiateST(params)
}
func (st SignTableBlock) instantiateST(params ex.Vars) (SignTableInstance, error) {
out := SignTableInstance{
Xs: make([]*ex.Expr, len(st.Xs)),
Functions: make([]client.FunctionSign, len(st.Functions)),
}
var err error
for i, c := range st.Xs {
out.Xs[i], err = ex.Parse(c)
if err != nil {
return out, err
}
out.Xs[i].Substitute(params)
}
for i, fn := range st.Functions {
label, err := fn.Label.instantiateAndMerge(params)
if err != nil {
return out, err
}
out.Functions[i] = client.FunctionSign{
Label: label,
FxSymbols: fn.FxSymbols,
Signs: fn.Signs,
}
}
return out, nil
}
func (st SignTableBlock) setupValidator(*ex.RandomParameters) (validator, error) {
if len(st.Xs) < 2 {
return nil, errors.New("Au moins deux colonnes sont attendues.")
}
labels := make([]TextParts, len(st.Functions))
for i, function := range st.Functions {
if len(st.Xs) != len(function.FxSymbols) || len(function.Signs) != len(st.Xs)-1 {
return nil, errors.New("internal error: unexpected length for X and Fx")
}
var err error
labels[i], err = function.Label.parse()
if err != nil {
return nil, err
}
}
for _, c := range st.Xs {
_, err := ex.Parse(c)
if err != nil {
return nil, err
}
}
return signTableValidator{labels: labels}, nil
}
type FigureBlock struct {
Drawings repere.RandomDrawings
Bounds repere.RepereBounds
ShowGrid bool
ShowOrigin bool
}
func (f FigureBlock) instantiate(params ex.Vars, _ int) (instance, error) {
return f.instantiateF(params)
}
func (f FigureBlock) instantiateF(params ex.Vars) (FigureInstance, error) {
out := FigureInstance{
Figure: repere.Figure{
Drawings: repere.Drawings{
Segments: make([]repere.Segment, len(f.Drawings.Segments)),
Points: make(map[string]repere.LabeledPoint),
Lines: make([]repere.Line, len(f.Drawings.Lines)),
Circles: make([]repere.Circle, len(f.Drawings.Circles)),
Areas: make([]repere.Area, len(f.Drawings.Areas)),
},
Bounds: f.Bounds,
ShowGrid: f.ShowGrid,
ShowOrigin: f.ShowOrigin,
},
}
for _, v := range f.Drawings.Points {
name, err := instantiateLaTeXExpr(v.Name, params)
if err != nil {
return out, err
}
x, err := evaluateExpr(v.Point.Coord.X, params)
if err != nil {
return out, err
}
y, err := evaluateExpr(v.Point.Coord.Y, params)
if err != nil {
return out, err
}
out.Figure.Drawings.Points[name] = repere.LabeledPoint{
Point: repere.PosPoint{
Point: repere.Coord{
X: x,
Y: y,
},
Pos: v.Point.Pos,
},
Color: v.Point.Color,
}
}
var err error
for i, s := range f.Drawings.Segments {
instance := repere.Segment(s)
instance.LabelName, err = Interpolated(s.LabelName).instantiateAndMerge(params)
if err != nil {
return out, err
}
instance.From, err = instantiateLaTeXExpr(s.From, params)
if err != nil {
return out, err
}
instance.To, err = instantiateLaTeXExpr(s.To, params)
if err != nil {
return out, err
}
out.Figure.Drawings.Segments[i] = instance
}
for i, l := range f.Drawings.Lines {
a, err := evaluateExpr(l.A, params)
if err != nil {
return out, err
}
b, err := evaluateExpr(l.B, params)
if err != nil {
return out, err
}
out.Figure.Drawings.Lines[i] = repere.Line{
Label: l.Label,
A: a,
B: b,
Color: l.Color,
}
}
for i, circle := range f.Drawings.Circles {
legend, err := Interpolated(circle.Legend).instantiateAndMerge(params)
if err != nil {
return out, err
}
center, err := CoordExpression(circle.Center).instantiateToFloat(params)
if err != nil {
return out, err
}
radius, err := evaluateExpr(circle.Radius, params)
if err != nil {
return out, err
}
out.Figure.Drawings.Circles[i] = repere.Circle{
Radius: radius,
Center: center,
LineColor: circle.LineColor,
FillColor: circle.FillColor,
Legend: legend,
}
}
for i, area := range f.Drawings.Areas {
instance := repere.Area{
Color: area.Color,
Points: make([]repere.PointName, len(area.Points)),
}
for j, p := range area.Points {
instance.Points[j], err = instantiateLaTeXExpr(p, params)
if err != nil {
return out, err
}
}
out.Figure.Drawings.Areas[i] = instance
}
return out, nil
}
func (f FigureBlock) setupValidator(*ex.RandomParameters) (validator, error) {
var (
out figureValidator
err error
)
if f.Bounds.Height <= 0 || f.Bounds.Width <= 0 {
return nil, errors.New("Les dimensions de la figure sont invalides.")
}
out.pointNames = make([]*ex.Expr, len(f.Drawings.Points))
out.points = make([]*ex.Expr, 0, 2*len(f.Drawings.Points))
for i, v := range f.Drawings.Points {
out.pointNames[i], err = ex.Parse(v.Name)
if err != nil {
return nil, err
}
ptX, err := ex.Parse(v.Point.Coord.X)
if err != nil {
return nil, err
}
ptY, err := ex.Parse(v.Point.Coord.Y)
if err != nil {
return nil, err
}
out.points = append(out.points, ptX, ptY)
}
// ... and undefined points
out.references = make([]*ex.Expr, 0, 2*len(f.Drawings.Segments))
for _, seg := range f.Drawings.Segments {
// validate the syntax for the name, which support interpolation
_, err = Interpolated(seg.LabelName).parse()
if err != nil {
return nil, err
}
from, err := ex.Parse(seg.From)
if err != nil {
return nil, err
}
to, err := ex.Parse(seg.To)
if err != nil {
return nil, err
}
out.references = append(out.references, from, to)
}
for _, area := range f.Drawings.Areas {
if len(area.Points) < 3 {
return nil, errors.New("Une surface requiert au moins 3 points.")
}
for _, point := range area.Points {
e, err := ex.Parse(point)
if err != nil {
return nil, err
}
out.references = append(out.references, e)
}
}
for _, circle := range f.Drawings.Circles {
center, err := CoordExpression(circle.Center).parse()
if err != nil {
return nil, err
}
radius, err := ex.Parse(circle.Radius)
if err != nil {
return nil, err
}
_, err = Interpolated(circle.Legend).parse()
if err != nil {
return nil, err
}
out.circlesDims = append(out.circlesDims, center.X, center.Y, radius)
}
out.lines = make([][2]*ex.Expr, len(f.Drawings.Lines))
for i, l := range f.Drawings.Lines {
out.lines[i][0], err = ex.Parse(l.A)
if err != nil {
return nil, err
}
out.lines[i][1], err = ex.Parse(l.B)
if err != nil {
return nil, err
}
}
return out, nil
}
type FunctionDecoration struct {
Label Interpolated
Color string
}
type FunctionDefinition struct {
Function string // expression.Expression
Decoration FunctionDecoration
Variable ex.Variable // usually x
From, To string // definition domain, expression.Expression
}
func (fg FunctionDefinition) parse() (fn ex.FunctionExpr, from, to *ex.Expr, err error) {
expr, err := ex.Parse(fg.Function)
if err != nil {
return fn, from, to, err
}
from, err = ex.Parse(fg.From)
if err != nil {
return fn, from, to, err
}
to, err = ex.Parse(fg.To)
if err != nil {
return fn, from, to, err
}
return ex.FunctionExpr{
Function: expr,
Variable: fg.Variable,
}, from, to, nil
}
func (fg FunctionDefinition) instantiate(params ex.Vars) (_ ex.FunctionDefinition, _ functiongrapher.FunctionDecoration, err error) {
fnExpr, from, to, err := fg.parse()
if err != nil {
return
}
fnExpr.Function.Substitute(params)
fromV, err := from.Evaluate(params)
if err != nil {
return
}
toV, err := to.Evaluate(params)
if err != nil {
return
}
label, err := fg.Decoration.Label.instantiateAndMerge(params)
if err != nil {
return
}
return ex.FunctionDefinition{
FunctionExpr: fnExpr,
From: fromV,
To: toV,
}, functiongrapher.FunctionDecoration{
Label: label,
Color: fg.Decoration.Color,
}, nil
}
type FunctionArea struct {
// reference to function [Label]s, with empty meaning
// horizontal line
Bottom, Top Interpolated
Left, Right string // expression.Expression
Color repere.ColorHex
}
// FunctionPoint draws a point at a given
// abscice for a given function
type FunctionPoint struct {
Function Interpolated // reference to a function [Label]
X string // expression.Expression
Color repere.ColorHex
Legend Interpolated // legend
}
// FunctionsGraphBlock draws a figure with functions
// curves and colored areas
// Function are identifier by their [Label]
type FunctionsGraphBlock struct {
FunctionExprs []FunctionDefinition
FunctionVariations []VariationTableBlock
SequenceExprs []FunctionDefinition // displayed as discrete sequences
Areas []FunctionArea
Points []FunctionPoint
}
func (fg FunctionsGraphBlock) setupValidator(params *ex.RandomParameters) (validator, error) {
out := functionsGraphValidator{
functions: make([]functionValidator, len(fg.FunctionExprs)),
variationValidator: make([]variationTableValidator, len(fg.FunctionVariations)),
sequences: make([]functionValidator, len(fg.SequenceExprs)),
areas: make([]areaVData, len(fg.Areas)),
points: make([]functionPointVData, len(fg.Points)),
}
for i, f := range fg.FunctionExprs {
var err error
out.functions[i], err = newFunctionValidator(f, params)
if err != nil {
return nil, err
}
}
for i, vt := range fg.FunctionVariations {
var err error
out.variationValidator[i], err = vt.setupValidatorVT()
if err != nil {
return nil, err
}
}
for i, f := range fg.SequenceExprs {
var err error
out.sequences[i], err = newFunctionValidator(f, params)
if err != nil {
return nil, err
}
}
for i, area := range fg.Areas {
var err error
out.areas[i].top, err = area.Top.parse()
if err != nil {
return nil, err
}
out.areas[i].bottom, err = area.Bottom.parse()
if err != nil {
return nil, err
}
out.areas[i].domain.From, err = ex.Parse(area.Left)
if err != nil {
return nil, err
}
out.areas[i].domain.To, err = ex.Parse(area.Right)
if err != nil {
return nil, err
}
}
for i, point := range fg.Points {
_, err := point.Legend.parse() // check the syntax for the legend
if err != nil {
return nil, err
}
out.points[i].fnLabel, err = point.Function.parse()
if err != nil {
return nil, err
}
out.points[i].x, err = ex.Parse(point.X)
if err != nil {
return nil, err
}
}
return out, nil
}
func extractValues(vt VariationTableInstance) (xs, fxs []float64) {
xs = make([]float64, len(vt.Xs))
fxs = make([]float64, len(vt.Fxs))
for i, v := range vt.Xs {
xs[i] = v.Value
}
for i, v := range vt.Fxs {
fxs[i] = v.Value
}
return
}
type domainCurves struct {
curves []functiongrapher.BezierCurve
domain [2]float64
}
func horizontalAxis(left, right float64) domainCurves {
return domainCurves{curves: functiongrapher.HorizontalAxis(left, right, 0), domain: [2]float64{left, right}}
}
func selectByDomain(candidates []domainCurves, left, right float64) (domainCurves, error) {
for _, c := range candidates {
if c.domain[0] <= left && right <= c.domain[1] {
return c, nil
}
}
return domainCurves{}, fmt.Errorf("aucun domaine ne contient [%f, %f]", left, right)
}
func (fg FunctionsGraphBlock) instantiate(params ex.Vars, _ int) (instance, error) {
return fg.instantiateG(params)
}
func (fg FunctionsGraphBlock) instantiateG(params ex.Vars) (FunctionsGraphInstance, error) {
out := FunctionsGraphInstance{}
byNames := make(map[string][]domainCurves)
// instantiate expression
for _, f := range fg.FunctionExprs {
fd, dec, err := f.instantiate(params)
if err != nil {
return out, err
}
fg := functiongrapher.FunctionGraph{
Segments: functiongrapher.NewFunctionGraph(fd),
Decoration: dec,
}
out.Functions = append(out.Functions, fg)
byNames[fg.Decoration.Label] = append(byNames[fg.Decoration.Label], domainCurves{
curves: fg.Segments,
domain: [2]float64{fd.From, fd.To},
})
}
for _, f := range fg.SequenceExprs {
fd, dec, err := f.instantiate(params)
if err != nil {
return out, err
}
fg := functiongrapher.SequenceGraph{
Points: functiongrapher.NewSequenceGraph(fd),
Decoration: dec,
}
out.Sequences = append(out.Sequences, fg)
}
// instantiate variations
for _, f := range fg.FunctionVariations {
vt, err := f.instantiateVT(params)
if err != nil {
return out, err
}
xs, fxs := extractValues(vt)
fg := functiongrapher.FunctionGraph{
Segments: functiongrapher.NewFunctionGraphFromVariations(xs, fxs),
Decoration: functiongrapher.FunctionDecoration{Label: vt.Label},
}
out.Functions = append(out.Functions, fg)
byNames[fg.Decoration.Label] = append(byNames[fg.Decoration.Label], domainCurves{
curves: fg.Segments,
domain: [2]float64{vt.Xs[0].Value, vt.Xs[len(vt.Xs)-1].Value},
})