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
//! Bins (building blocks) for arnalisa.

pub mod add;
pub mod blocker;
pub mod calibration;
pub mod cborsink;
pub mod channelsink;
pub mod cosinus;
pub mod cumulation;
pub mod derivation;
pub mod directsource;
pub mod divide;
pub mod fifo;
pub mod first_value;
pub mod fixedvalues;
pub mod greater_than;
pub mod invert;
pub mod jsonlsink;
pub mod jsonlsource;
pub mod last_calm_point;
pub mod linear_regression;
pub mod maximum;
pub mod mean;
pub mod minimum;
pub mod multiplex;
pub mod multiply;
pub mod not;
pub mod passthrough;
pub mod pipeline;
pub mod single_not_null;
pub mod sinus;
pub mod storage;
pub mod subtract;
pub mod verificationsink;

#[cfg(feature = "xio")]
pub mod xiosource;

use crate::{
    error, CalibrationSource, GetCalibration, Item, Proceed, Result, Scope,
};
use indexmap::IndexSet;
use snafu::{ensure, OptionExt, ResultExt};
use std::fmt::Debug;
use std::io::Write;
use std::rc::Weak;
use std::sync::RwLock;

/// A trait for a bin which provides output data.
pub trait SourceBin: Debug {
    /// Get the source data for a specific source.
    fn get_source_data(&self, source: &SourceId) -> Result<Item>;
}

impl<S: SourceBin + ?Sized> SourceBin for Box<S> {
    fn get_source_data(&self, source: &SourceId) -> Result<Item> {
        (**self).get_source_data(source)
    }
}

/// A trait for a bin which can take data through sinks.
pub trait SinkBin {}

impl<S: SinkBin + ?Sized> SinkBin for Box<S> {}

/// A trait for a bin which only has sources, but no sinks.
pub trait SourceOnlyBin: SourceBin + Debug {
    /// Fetch the next row of values.
    /// If Ok(Proceed::Continue) is returned, then more data can
    /// be fetched afterwards.
    fn fetch_next(&mut self, iteration: &Iteration) -> Result<Proceed>;
}

/// A trait for a bin which has sources and sinks.
pub trait SourceSinkBin: SinkBin + SourceBin + Calculator {}

impl<T: SinkBin + SourceBin + Calculator> SourceSinkBin for T {}

/// A trait for a bin which only has sinks, but no sources.
pub trait SinkOnlyBin: SinkBin + Calculator + Debug {}

/// A processor for a source-only bin.
#[derive(Debug)]
pub struct SourceOnlyBinProcessor {
    bin: Box<dyn SourceOnlyBin>,
    previous_iteration: Option<Iteration>,
    proceed: Proceed,
}

impl SourceOnlyBinProcessor {
    /// Create a new instance.
    pub fn new(bin: Box<dyn SourceOnlyBin>) -> Self {
        SourceOnlyBinProcessor {
            bin,
            previous_iteration: None,
            proceed: Proceed::Continue,
        }
    }
}

/// A processor for a source-sink bin.
#[derive(Debug)]
pub struct SourceSinkBinProcessor {
    bin: Box<dyn SourceSinkBin>,
    previous_iteration: Option<Iteration>,
}

impl SinkBin for SourceSinkBinProcessor {}

impl Calculator for SourceSinkBinProcessor {
    fn calculate(&mut self, iteration: &Iteration) -> Result<()> {
        if self.previous_iteration != Some(iteration.clone()) {
            self.bin.calculate(iteration)?;
        }
        self.previous_iteration = Some(iteration.clone());
        Ok(())
    }
}

impl SourceBin for SourceSinkBinProcessor {
    fn get_source_data(&self, source: &SourceId) -> Result<Item> {
        self.bin.get_source_data(source)
    }
}

/// A processor for a sink-only bin.
#[derive(Debug)]
pub struct SinkOnlyBinProcessor {
    bin: Box<dyn SinkOnlyBin>,
    previous_iteration: Option<Iteration>,
}

impl Calculator for SinkOnlyBinProcessor {
    fn calculate(&mut self, iteration: &Iteration) -> Result<()> {
        if self.previous_iteration != Some(iteration.clone()) {
            self.bin.calculate(iteration)?;
        }
        self.previous_iteration = Some(iteration.clone());
        Ok(())
    }
}

impl SinkOnlyBinProcessor {
    /// Create a new instance.
    pub fn new(bin: Box<dyn SinkOnlyBin>) -> Self {
        SinkOnlyBinProcessor {
            bin,
            previous_iteration: None,
        }
    }
}

impl SourceBin for SourceOnlyBinProcessor {
    fn get_source_data(&self, source: &SourceId) -> Result<Item> {
        self.bin.get_source_data(source)
    }
}

impl SourceSinkBinProcessor {
    /// Create a new instance.
    pub fn new(bin: Box<dyn SourceSinkBin>) -> Self {
        SourceSinkBinProcessor {
            bin,
            previous_iteration: None,
        }
    }
}

impl SourceOnlyBin for SourceOnlyBinProcessor {
    fn fetch_next(&mut self, iteration: &Iteration) -> Result<Proceed> {
        if self.proceed == Proceed::Stop {
            Ok(Proceed::Stop)
        } else {
            self.previous_iteration = match self.previous_iteration {
                None => {
                    self.proceed = self.bin.fetch_next(iteration)?;
                    Some(iteration.clone())
                }
                Some(ref it) if it == iteration => {
                    self.previous_iteration.clone()
                }
                Some(_) => {
                    self.proceed = self.bin.fetch_next(iteration)?;
                    Some(iteration.clone())
                }
            };
            Ok(self.proceed.clone())
        }
    }
}

/// A calculator trait for bins.
pub trait Calculator {
    /// Calculate a single iteration.
    fn calculate(&mut self, iteration: &Iteration) -> Result<()>;

    /// Initialize the bin.
    fn initialize(&mut self) -> Result<()> {
        Ok(())
    }
}

impl<T: Calculator + ?Sized> Calculator for Box<T> {
    fn calculate(&mut self, iteration: &Iteration) -> Result<()> {
        (**self).calculate(iteration)
    }

    fn initialize(&mut self) -> Result<()> {
        (**self).initialize()
    }
}

/// Description of a source-only bin.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum SourceOnlyDescription {
    /// A jsonlsource bin description.
    JsonLSource(jsonlsource::Description),
    /// A directsource bin description.
    DirectSource(directsource::Description),
}

/// Description of a source-sink bin.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum SourceSinkDescription {
    /// A add bin description.
    Add(add::Description),
    /// A blocker bin description.
    Blocker(blocker::Description),
    /// A calibration bin description.
    Calibration(calibration::Description),
    /// A cosinus bin description.
    Cosinus(cosinus::Description),
    /// A cumulation bin description.
    Cumulation(cumulation::Description),
    /// A derivation bin description.
    Derivation(derivation::Description),
    /// A divide bin description.
    Divide(divide::Description),
    /// A fifo bin description.
    Fifo(fifo::Description),
    /// A first_value bin description.
    FirstValue(first_value::Description),
    /// A fixedvalues bin description.
    FixedValues(fixedvalues::Description),
    /// A greater_than bin description.
    GreaterThan(greater_than::Description),
    /// A invert bin description.
    Invert(invert::Description),
    /// A last_calm_point bin description.
    LastCalmPoint(last_calm_point::Description),
    /// A linear_regression bin description.
    LinearRegression(linear_regression::Description),
    /// A maximum bin description.
    Maximum(maximum::Description),
    /// A mean bin description.
    Mean(mean::Description),
    /// A minimum bin description.
    Minimum(minimum::Description),
    /// A multiplex bin description.
    Multiplex(multiplex::Description),
    /// A multiply bin description.
    Multiply(multiply::Description),
    /// A not bin description.
    Not(not::Description),
    /// A pipeline bin description.
    Pipeline(pipeline::Description),
    /// A single_not_null bin description.
    SingleNotNull(single_not_null::Description),
    /// A sinus bin description.
    Sinus(sinus::Description),
    /// A subtract bin description.
    Subtract(subtract::Description),
    /// A storage bin description.
    Storage(storage::Description),
}

/// Description of a sink-only bin.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum SinkOnlyDescription {
    /// A jsonlsink bin description.
    JsonLSink(jsonlsink::Description),
    /// A cborsink bin description.
    CborSink(cborsink::Description),
    /// A verificationsink bin description.
    VerificationSink(verificationsink::Description),
}

impl BinDescription for SinkOnlyDescription {
    type Bin = Box<dyn SinkOnlyBin>;

    fn check_validity(
        &self,
        scope: &Scope,
        getcal: &mut dyn GetCalibration,
    ) -> Result<()> {
        use self::SinkOnlyDescription::*;
        match *self {
            JsonLSink(ref d) => d.check_validity(scope, getcal),
            CborSink(ref d) => d.check_validity(scope, getcal),
            VerificationSink(ref d) => d.check_validity(scope, getcal),
        }
    }

    fn bin_type(&self) -> &'static str {
        use self::SinkOnlyDescription::*;
        match *self {
            JsonLSink(ref d) => d.bin_type(),
            CborSink(ref d) => d.bin_type(),
            VerificationSink(ref d) => d.bin_type(),
        }
    }
}

impl SinkNames for SinkOnlyDescription {
    fn sink_names(&self) -> IndexSet<String> {
        use self::SinkOnlyDescription::*;
        match *self {
            JsonLSink(ref d) => d.sink_names(),
            CborSink(ref d) => d.sink_names(),
            VerificationSink(ref d) => d.sink_names(),
        }
    }
}

impl SinkOnlyBinDescription for SinkOnlyDescription {
    fn build_bin(
        &self,
        scope: &Scope,
        env: &mut dyn BinBuildEnvironment,
    ) -> Result<Self::Bin> {
        use self::SinkOnlyDescription::*;
        let b: Box<dyn SinkOnlyBin> = match *self {
            JsonLSink(ref d) => Box::new(d.build_bin(scope, env)?),
            CborSink(ref d) => Box::new(d.build_bin(scope, env)?),
            VerificationSink(ref d) => Box::new(d.build_bin(scope, env)?),
        };
        Ok(b)
    }
}

/// A description of any bin.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", untagged)]
pub enum Description {
    /// A source-only bin description.
    SourceOnly(SourceOnlyDescription),
    /// A source-sink bin description.
    SourceSink(SourceSinkDescription),
    /// A sink-only bin description.
    SinkOnly(SinkOnlyDescription),
}

/// A reference to a source.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SourceReference {
    /// The bin. If none, the source is taken from from a pipeline input.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bin: Option<String>,
    /// The source id.
    pub source: String,
}

impl BinDescription for SourceSinkDescription {
    type Bin = Box<dyn SourceSinkBin>;

    fn check_validity(
        &self,
        scope: &Scope,
        getcal: &mut dyn GetCalibration,
    ) -> Result<()> {
        use self::SourceSinkDescription::*;
        match *self {
            Add(ref d) => d.check_validity(scope, getcal),
            Blocker(ref d) => d.check_validity(scope, getcal),
            Calibration(ref d) => d.check_validity(scope, getcal),
            Cosinus(ref d) => d.check_validity(scope, getcal),
            Cumulation(ref d) => d.check_validity(scope, getcal),
            Derivation(ref d) => d.check_validity(scope, getcal),
            Divide(ref d) => d.check_validity(scope, getcal),
            Fifo(ref d) => d.check_validity(scope, getcal),
            FirstValue(ref d) => d.check_validity(scope, getcal),
            FixedValues(ref d) => d.check_validity(scope, getcal),
            GreaterThan(ref d) => d.check_validity(scope, getcal),
            Invert(ref d) => d.check_validity(scope, getcal),
            LastCalmPoint(ref d) => d.check_validity(scope, getcal),
            LinearRegression(ref d) => d.check_validity(scope, getcal),
            Maximum(ref d) => d.check_validity(scope, getcal),
            Mean(ref d) => d.check_validity(scope, getcal),
            Minimum(ref d) => d.check_validity(scope, getcal),
            Multiplex(ref d) => d.check_validity(scope, getcal),
            Multiply(ref d) => d.check_validity(scope, getcal),
            Not(ref d) => d.check_validity(scope, getcal),
            Pipeline(ref d) => d.check_validity(scope, getcal),
            SingleNotNull(ref d) => d.check_validity(scope, getcal),
            Sinus(ref d) => d.check_validity(scope, getcal),
            Subtract(ref d) => d.check_validity(scope, getcal),
            Storage(ref d) => d.check_validity(scope, getcal),
        }
    }

    fn bin_type(&self) -> &'static str {
        use self::SourceSinkDescription::*;
        match *self {
            Add(ref d) => d.bin_type(),
            Blocker(ref d) => d.bin_type(),
            Calibration(ref d) => d.bin_type(),
            Cosinus(ref d) => d.bin_type(),
            Cumulation(ref d) => d.bin_type(),
            Derivation(ref d) => d.bin_type(),
            Divide(ref d) => d.bin_type(),
            Fifo(ref d) => d.bin_type(),
            FirstValue(ref d) => d.bin_type(),
            FixedValues(ref d) => d.bin_type(),
            GreaterThan(ref d) => d.bin_type(),
            Invert(ref d) => d.bin_type(),
            LastCalmPoint(ref d) => d.bin_type(),
            LinearRegression(ref d) => d.bin_type(),
            Maximum(ref d) => d.bin_type(),
            Mean(ref d) => d.bin_type(),
            Minimum(ref d) => d.bin_type(),
            Multiplex(ref d) => d.bin_type(),
            Multiply(ref d) => d.bin_type(),
            Not(ref d) => d.bin_type(),
            Pipeline(ref d) => d.bin_type(),
            SingleNotNull(ref d) => d.bin_type(),
            Sinus(ref d) => d.bin_type(),
            Subtract(ref d) => d.bin_type(),
            Storage(ref d) => d.bin_type(),
        }
    }
}

impl WriteDot for SourceSinkDescription {
    fn write_dot<W: Write>(&self, w: &mut W, name: &str) -> Result<()> {
        use self::SourceSinkDescription::*;
        match *self {
            Add(ref d) => d.write_dot(w, name),
            Blocker(ref d) => d.write_dot(w, name),
            Calibration(ref d) => d.write_dot(w, name),
            Cosinus(ref d) => d.write_dot(w, name),
            Cumulation(ref d) => d.write_dot(w, name),
            Derivation(ref d) => d.write_dot(w, name),
            Divide(ref d) => d.write_dot(w, name),
            Fifo(ref d) => d.write_dot(w, name),
            FirstValue(ref d) => d.write_dot(w, name),
            FixedValues(ref d) => d.write_dot(w, name),
            GreaterThan(ref d) => d.write_dot(w, name),
            Invert(ref d) => d.write_dot(w, name),
            LastCalmPoint(ref d) => d.write_dot(w, name),
            LinearRegression(ref d) => d.write_dot(w, name),
            Maximum(ref d) => d.write_dot(w, name),
            Mean(ref d) => d.write_dot(w, name),
            Minimum(ref d) => d.write_dot(w, name),
            Multiplex(ref d) => d.write_dot(w, name),
            Multiply(ref d) => d.write_dot(w, name),
            Not(ref d) => d.write_dot(w, name),
            Pipeline(ref d) => d.write_dot(w, name),
            SingleNotNull(ref d) => d.write_dot(w, name),
            Sinus(ref d) => d.write_dot(w, name),
            Subtract(ref d) => d.write_dot(w, name),
            Storage(ref d) => d.write_dot(w, name),
        }
    }
}

impl SourceSinkBinDescription for SourceSinkDescription {
    fn build_bin(
        &self,
        s: &Scope,
        e: &mut dyn BinBuildEnvironment,
    ) -> Result<Self::Bin> {
        use self::SourceSinkDescription::*;
        Ok(match *self {
            Add(ref d) => Box::new(d.build_bin(s, e)?),
            Blocker(ref d) => Box::new(d.build_bin(s, e)?),
            Calibration(ref d) => Box::new(d.build_bin(s, e)?),
            Cosinus(ref d) => Box::new(d.build_bin(s, e)?),
            Cumulation(ref d) => Box::new(d.build_bin(s, e)?),
            Derivation(ref d) => Box::new(d.build_bin(s, e)?),
            Divide(ref d) => Box::new(d.build_bin(s, e)?),
            Fifo(ref d) => Box::new(d.build_bin(s, e)?),
            FirstValue(ref d) => Box::new(d.build_bin(s, e)?),
            FixedValues(ref d) => Box::new(d.build_bin(s, e)?),
            GreaterThan(ref d) => Box::new(d.build_bin(s, e)?),
            Invert(ref d) => Box::new(d.build_bin(s, e)?),
            LastCalmPoint(ref d) => Box::new(d.build_bin(s, e)?),
            LinearRegression(ref d) => Box::new(d.build_bin(s, e)?),
            Maximum(ref d) => Box::new(d.build_bin(s, e)?),
            Mean(ref d) => Box::new(d.build_bin(s, e)?),
            Minimum(ref d) => Box::new(d.build_bin(s, e)?),
            Multiplex(ref d) => Box::new(d.build_bin(s, e)?),
            Multiply(ref d) => Box::new(d.build_bin(s, e)?),
            Not(ref d) => Box::new(d.build_bin(s, e)?),
            Pipeline(ref d) => Box::new(d.build_bin(s, e)?),
            SingleNotNull(ref d) => Box::new(d.build_bin(s, e)?),
            Sinus(ref d) => Box::new(d.build_bin(s, e)?),
            Subtract(ref d) => Box::new(d.build_bin(s, e)?),
            Storage(ref d) => Box::new(d.build_bin(s, e)?),
        })
    }
}

impl SinkNames for SourceSinkDescription {
    fn sink_names(&self) -> IndexSet<String> {
        use self::SourceSinkDescription::*;
        match *self {
            Add(ref d) => d.sink_names(),
            Blocker(ref d) => d.sink_names(),
            Calibration(ref d) => d.sink_names(),
            Cosinus(ref d) => d.sink_names(),
            Cumulation(ref d) => d.sink_names(),
            Derivation(ref d) => d.sink_names(),
            Divide(ref d) => d.sink_names(),
            Fifo(ref d) => d.sink_names(),
            FirstValue(ref d) => d.sink_names(),
            FixedValues(ref d) => d.sink_names(),
            GreaterThan(ref d) => d.sink_names(),
            Invert(ref d) => d.sink_names(),
            LastCalmPoint(ref d) => d.sink_names(),
            LinearRegression(ref d) => d.sink_names(),
            Maximum(ref d) => d.sink_names(),
            Mean(ref d) => d.sink_names(),
            Minimum(ref d) => d.sink_names(),
            Multiplex(ref d) => d.sink_names(),
            Multiply(ref d) => d.sink_names(),
            Not(ref d) => d.sink_names(),
            Pipeline(ref d) => d.sink_names(),
            SingleNotNull(ref d) => d.sink_names(),
            Sinus(ref d) => d.sink_names(),
            Subtract(ref d) => d.sink_names(),
            Storage(ref d) => d.sink_names(),
        }
    }
}

impl SourceNames for SourceSinkDescription {
    fn source_names(&self) -> Result<IndexSet<String>> {
        use self::SourceSinkDescription::*;
        match *self {
            Add(ref d) => d.source_names(),
            Blocker(ref d) => d.source_names(),
            Calibration(ref d) => d.source_names(),
            Cosinus(ref d) => d.source_names(),
            Cumulation(ref d) => d.source_names(),
            Derivation(ref d) => d.source_names(),
            Divide(ref d) => d.source_names(),
            Fifo(ref d) => d.source_names(),
            FirstValue(ref d) => d.source_names(),
            FixedValues(ref d) => d.source_names(),
            GreaterThan(ref d) => d.source_names(),
            Invert(ref d) => d.source_names(),
            LastCalmPoint(ref d) => d.source_names(),
            LinearRegression(ref d) => d.source_names(),
            Maximum(ref d) => d.source_names(),
            Mean(ref d) => d.source_names(),
            Minimum(ref d) => d.source_names(),
            Multiplex(ref d) => d.source_names(),
            Multiply(ref d) => d.source_names(),
            Not(ref d) => d.source_names(),
            Pipeline(ref d) => d.source_names(),
            SingleNotNull(ref d) => d.source_names(),
            Sinus(ref d) => d.source_names(),
            Subtract(ref d) => d.source_names(),
            Storage(ref d) => d.source_names(),
        }
    }
}

/// A trait for descriptions of source-only bins.
pub trait SourceOnlyBinDescription: SourceNames + BinDescription {
    /// Build the bin.
    fn build_bin(&self, scope: &Scope) -> Result<Self::Bin>;
}

impl BinDescription for SourceOnlyDescription {
    type Bin = Box<dyn SourceOnlyBin>;

    fn check_validity(
        &self,
        scope: &Scope,
        getcal: &mut dyn GetCalibration,
    ) -> Result<()> {
        use self::SourceOnlyDescription::*;
        match *self {
            JsonLSource(ref d) => d.check_validity(scope, getcal),
            DirectSource(ref d) => d.check_validity(scope, getcal),
        }
    }

    fn bin_type(&self) -> &'static str {
        use self::SourceOnlyDescription::*;
        match *self {
            JsonLSource(ref d) => d.bin_type(),
            DirectSource(ref d) => d.bin_type(),
        }
    }
}

impl SourceNames for SourceOnlyDescription {
    fn source_names(&self) -> Result<IndexSet<String>> {
        use self::SourceOnlyDescription::*;
        match *self {
            JsonLSource(ref d) => d.source_names(),
            DirectSource(ref d) => d.source_names(),
        }
    }
}

impl SourceOnlyBinDescription for SourceOnlyDescription {
    fn build_bin(&self, scope: &Scope) -> Result<Self::Bin> {
        use self::SourceOnlyDescription::*;
        let b: Box<dyn SourceOnlyBin> = match *self {
            JsonLSource(ref d) => Box::new(d.build_bin(scope)?),
            DirectSource(ref d) => Box::new(d.build_bin(scope)?),
        };
        Ok(b)
    }
}

/// A trait for descriptions of source-sink bins.
pub trait SourceSinkBinDescription:
    SourceNames + SinkNames + BinDescription
{
    /// Build the bin.
    fn build_bin(
        &self,
        scope: &Scope,
        env: &mut dyn BinBuildEnvironment,
    ) -> Result<Self::Bin>;
}

/// A trait for descriptions of sink-only bins.
pub trait SinkOnlyBinDescription: SinkNames + BinDescription {
    /// Build the bin.
    fn build_bin(
        &self,
        scope: &Scope,
        env: &mut dyn BinBuildEnvironment,
    ) -> Result<Self::Bin>;
}

/// A trait providing sink names as an index set.
pub trait SinkNames {
    /// Get the sink names.
    fn sink_names(&self) -> IndexSet<String>;

    /// Check that all incoming sinks will be fed by a source.
    /// The sink_names parameter mast match *exactly* the set
    /// of sinks which will be found in the bin.
    fn check_sink_names(
        &self,
        scope: &Scope,
        sink_names: &IndexSet<String>,
    ) -> Result<()> {
        ensure!(
            sink_names == &self.sink_names(),
            error::InvalidSinkNames {
                scope: scope.clone(),
                expected: self.sink_names().clone(),
                received: sink_names.clone(),
            }
        );
        Ok(())
    }
}

/// A trait for descriptions of sink bins.
pub trait SinkBinDescription: BinDescription + SinkNames {}

impl<T: BinDescription + SinkNames> SinkBinDescription for T {}

/// A trait for descriptions of source bins.
pub trait SourceBinDescription: BinDescription + SourceNames {}

impl<T: BinDescription + SourceNames> SourceBinDescription for T {}

/// A trait providing source names as an index set.
pub trait SourceNames {
    /// Get the source names.
    fn source_names(&self) -> Result<IndexSet<String>>;
}

/// A trait for descriptions of bins.
pub trait BinDescription {
    /// The associated bin type.
    type Bin;

    /// Check the validity of the description.
    fn check_validity(
        &self,
        scope: &Scope,
        get_calibration: &mut dyn GetCalibration,
    ) -> Result<()>;

    /// Get the bin type string.
    fn bin_type(&self) -> &'static str;
}

/// A trait for writing dot (graphviz) description of a bin.
pub trait WriteDot {
    /// Write the description.
    fn write_dot<W: Write>(&self, w: &mut W, name: &str) -> Result<()>;
}

/// A trait for writing a simple dot (graphviz) description of a bin.
pub trait WriteDotSimple {}

impl<T: SourceNames + SinkNames + BinDescription + WriteDotSimple> WriteDot
    for T
{
    fn write_dot<W: Write>(&self, w: &mut W, name: &str) -> Result<()> {
        write_dot_bin(
            w,
            name,
            self.bin_type(),
            &self.sink_names(),
            &self.source_names()?,
        )
    }
}

/// An iteration in a calculation series.
#[derive(Debug, PartialEq, Clone, Default)]
pub struct Iteration {
    /// The index of the iteration.
    pub index: usize,
}

impl Iteration {
    /// Move on to the next iteration.
    pub fn iterate(&mut self) {
        self.index = self.index.checked_add(1usize).unwrap();
    }
}

/// The identifier of a source.
#[derive(Debug, PartialEq)]
pub struct SourceId {
    /// The id string of the source.
    pub id: String,
}

impl SourceId {
    /// Create a new instance.
    pub fn new(id: &str) -> Self {
        SourceId { id: id.to_string() }
    }
}

/// A trait for fetching an item from a scope.
pub trait FetchItem: Debug {
    /// Fetch the item.
    fn fetch_item(&self, scope: &Scope) -> Result<Item>;
}

/// A source for data items.
#[derive(Debug)]
pub struct DataSource<T: SourceBin> {
    /// The provider of the data.
    pub data_provider: Weak<RwLock<T>>,
    /// The id of the data source.
    pub source: SourceId,
}

impl<T: SourceBin> FetchItem for DataSource<T> {
    fn fetch_item(&self, scope: &Scope) -> Result<Item> {
        let provider_mut = self.data_provider.upgrade().context(
            error::DataProviderGone {
                scope: scope.clone(),
            },
        )?;
        let provider = provider_mut.write().unwrap();
        provider.get_source_data(&self.source)
    }
}

trait CheckContains {
    fn check_contains(
        &self,
        scope: &Scope,
        bin_type: &str,
        value: &str,
    ) -> Result<()>;
}

impl CheckContains for IndexSet<String> {
    fn check_contains(
        &self,
        scope: &Scope,
        bin_type: &str,
        value: &str,
    ) -> Result<()> {
        ensure!(
            self.contains(&value.to_string()),
            error::InvalidSourceName {
                bin_type: bin_type.to_string(),
                name: format!("{:?}", value),
                scope: scope.clone(),
            }
        );
        Ok(())
    }
}

fn write_dot_bin<W: Write>(
    w: &mut W,
    name: &str,
    bin_type: &str,
    sinks: &IndexSet<String>,
    sources: &IndexSet<String>,
) -> Result<()> {
    writeln!(w, "{} [label=<", name).context(error::Io)?;
    write_dot_bin_table(w, name, bin_type, sinks, sources)?;
    writeln!(w, ">];").context(error::Io)?;
    Ok(())
}

fn write_dot_bin_table<W: Write>(
    w: &mut W,
    name: &str,
    bin_type: &str,
    sinks: &IndexSet<String>,
    sources: &IndexSet<String>,
) -> Result<()> {
    let cols = match (sinks.is_empty(), sources.is_empty()) {
        (false, false) => 2,
        (true, false) | (false, true) => 1,
        (true, true) => 0,
    };

    writeln!(w, "<table border=\"0\" cellborder=\"1\" cellspacing=\"0\">")
        .context(error::Io)?;

    writeln!(w, "<tr>").context(error::Io)?;
    writeln!(w, "<td colspan=\"{}\">", cols).context(error::Io)?;
    writeln!(
        w,
        "<font point-size=\"12\">{}</font><br/>{}",
        name, bin_type
    )
    .context(error::Io)?;
    writeln!(w, "</td>").context(error::Io)?;
    writeln!(w, "</tr>").context(error::Io)?;

    if cols > 0 {
        writeln!(w, "<tr>").context(error::Io)?;
        if !sinks.is_empty() {
            writeln!(w, "<td>").context(error::Io)?;
            write_dot_socket_table(w, sinks, "_sink")?;
            writeln!(w, "</td>").context(error::Io)?;
        }
        if !sources.is_empty() {
            writeln!(w, "<td>").context(error::Io)?;
            write_dot_socket_table(w, sources, "_source")?;
            writeln!(w, "</td>").context(error::Io)?;
        }
        writeln!(w, "</tr>").context(error::Io)?;
    }

    writeln!(w, "</table>").context(error::Io)?;

    Ok(())
}

fn write_dot_socket_table<W: Write>(
    w: &mut W,
    items: &IndexSet<String>,
    suffix: &str,
) -> Result<()> {
    writeln!(w, "<table border=\"0\" cellborder=\"0\" cellspacing=\"0\">")
        .context(error::Io)?;
    for item in items {
        writeln!(w, "<tr>").context(error::Io)?;
        writeln!(w, "<td port=\"{}{}\">{}</td>", item, suffix, item)
            .context(error::Io)?;
        writeln!(w, "</tr>").context(error::Io)?;
    }

    writeln!(w, "</table>").context(error::Io)?;

    Ok(())
}

/// An environment for resolving data sources and calibration.
pub trait BinBuildEnvironment: GetCalibration {
    /// Resolve a data source by id.
    fn resolve(&mut self, id: &str) -> Result<Box<dyn FetchItem>>;
}

static SINK_A: &str = "a";
static SINK_B: &str = "b";
static SINK_INPUT: &str = "input";
static SINK_SELECT: &str = "select";
static SINK_TRIGGER: &str = "trigger";
static SINK_X: &str = "x";
static SINK_Y: &str = "y";

static SOURCE_OUTPUT: &str = "output";
static SOURCE_CHANGED: &str = "changed";

fn build_names<S: ToString>(names: &[S]) -> IndexSet<String> {
    names.iter().map(S::to_string).collect()
}

fn sink_names_a_b() -> IndexSet<String> {
    build_names(&[SINK_A, SINK_B])
}

fn sink_names_input_trigger() -> IndexSet<String> {
    build_names(&[SINK_INPUT, SINK_TRIGGER])
}

fn sink_names_trigger() -> IndexSet<String> {
    build_names(&[SINK_TRIGGER])
}

fn sink_names_input_select() -> IndexSet<String> {
    build_names(&[SINK_INPUT, SINK_SELECT])
}

fn sink_names_input() -> IndexSet<String> {
    build_names(&[SINK_INPUT])
}

fn source_names_output() -> IndexSet<String> {
    build_names(&[SOURCE_OUTPUT])
}

fn source_names_output_changed() -> IndexSet<String> {
    build_names(&[SOURCE_OUTPUT, &SOURCE_CHANGED])
}