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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
use super::super::pins::pins_to_backend_lookup_fields;
use super::timeset_container::{
    EventContainer, WaveContainer, WaveGroupContainer, WavetableContainer,
};
use origen::error::Error;
use origen::DUT;
use pyo3::class::mapping::PyMappingProtocol;
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyDict, PyTuple};

#[macro_export]
macro_rules! pytimeset {
    ($py:expr, $model:expr, $model_id:expr, $name:expr) => {
        if $model.contains_timeset($name) {
            Ok(Py::new(
                $py,
                crate::timesets::timeset::Timeset {
                    name: String::from($name),
                    model_id: $model_id,
                },
            )
            .unwrap()
            .to_object($py))
        } else {
            // Note: Errors here shouldn't happen. Any errors that arise are either
            // bugs or from the user meta-programming their way into the backend DB.
            Err(PyErr::from(origen::error::Error::new(&format!(
                "No timeset {} has been added on block {}",
                $name, $model.name
            ))))
        }
    };
}

// Returns a (Python) Timeset or NoneType instance.
// Note: this does NOT return a Rust Option::None, but
#[macro_export]
macro_rules! pytimeset_or_pynone {
    ($py:expr, $model:expr, $model_id:expr, $name:expr) => {
        if $model.contains_timeset($name) {
            Py::new(
                $py,
                crate::timesets::timeset::Timeset {
                    name: String::from($name),
                    model_id: $model_id,
                },
            )
            .unwrap()
            .to_object($py)
        } else {
            $py.None()
        }
    };
}

#[macro_export]
macro_rules! pywavetable {
    ($py:expr, $timeset:expr, $t_id:expr, $name:expr) => {
        if $timeset.contains_wavetable($name) {
            Ok(Py::new(
                $py,
                crate::timesets::timeset::Wavetable {
                    name: String::from($name),
                    model_id: $timeset.model_id,
                    timeset_id: $timeset.id,
                },
            )
            .unwrap()
            .to_object($py))
        } else {
            // Note: Errors here shouldn't happen. Any errors that arise are either
            // bugs or from the user meta-programming their way into the backend DB.
            Err(PyErr::from(origen::error::Error::new(&format!(
                "No wavetable {} has been added on block {}",
                $name, $timeset.name
            ))))
        }
    };
}

#[macro_export]
macro_rules! pywave_group {
    ($py:expr, $wavetable:expr, $name:expr) => {
        if $wavetable.contains_wave_group($name) {
            Ok(Py::new(
                $py,
                crate::timesets::timeset::WaveGroup {
                    name: String::from($name),
                    model_id: $wavetable.model_id,
                    timeset_id: $wavetable.timeset_id,
                    wavetable_id: $wavetable.id,
                },
            )
            .unwrap()
            .to_object($py))
        } else {
            // Note: Errors here shouldn't happen. Any errors that arise are either
            // bugs or from the user meta-programming their way into the backend DB.
            Err(PyErr::from(origen::error::Error::new(&format!(
                "No wave group {} has been added on block {}",
                $name, $wavetable.name
            ))))
        }
    };
}

#[macro_export]
macro_rules! pywave {
    ($py:expr, $wave_group:expr, $name:expr) => {
        if $wave_group.contains_wave($name) {
            Ok(Py::new(
                $py,
                crate::timesets::timeset::Wave {
                    name: String::from($name),
                    model_id: $wave_group.model_id,
                    timeset_id: $wave_group.timeset_id,
                    wavetable_id: $wave_group.wavetable_id,
                    wave_group_id: $wave_group.id,
                },
            )
            .unwrap()
            .to_object($py))
        } else {
            // Note: Errors here shouldn't happen. Any errors that arise are either
            // bugs or from the user meta-programming their way into the backend DB.
            Err(PyErr::from(origen::error::Error::new(&format!(
                "No wave {} has been added on block {}",
                $name, $wave_group.name
            ))))
        }
    };
}

#[macro_export]
macro_rules! pyevent {
    ($py:expr, $wave:expr, $event_index:expr) => {
        if $wave.events.len() > $event_index {
            Ok(Py::new(
                $py,
                crate::timesets::timeset::Event {
                    model_id: $wave.model_id,
                    timeset_id: $wave.timeset_id,
                    wavetable_id: $wave.wavetable_id,
                    wave_group_id: $wave.wave_group_id,
                    wave_id: $wave.wave_id,
                    wave_indicator: $wave.indicator.clone(),
                    index: $event_index,
                },
            )
            .unwrap()
            .to_object($py))
        } else {
            // Note: Errors here shouldn't happen. Any errors that arise are either
            // bugs or from the user meta-programming their way into the backend DB.
            Err(PyErr::from(origen::error::Error::new(&format!(
                "No event at {} has been added on wave {}",
                $event_index, $wave.indicator
            ))))
        }
    };
}

#[pyclass]
pub struct Timeset {
    pub name: String,
    pub model_id: usize,
}

#[pymethods]
impl Timeset {
    #[getter]
    fn get_name(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let timeset = dut.get_timeset(self.model_id, &self.name);
        Ok(timeset.unwrap().name.clone())
    }

    #[allow(non_snake_case)]
    #[getter]
    fn get___origen__model_id__(&self) -> PyResult<usize> {
        Ok(self.model_id)
    }

    #[getter]
    fn get_period(&self) -> PyResult<f64> {
        let dut = DUT.lock().unwrap();
        let timeset = dut._get_timeset(self.model_id, &self.name)?;
        Ok(timeset.eval(Option::None)?)
    }

    #[getter]
    fn get_default_period(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let timeset = dut._get_timeset(self.model_id, &self.name)?;

        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(match timeset.default_period {
            Some(p) => p.to_object(py),
            None => py.None(),
        })
    }

    #[allow(non_snake_case)]
    #[getter]
    fn get___eval_str__(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let timeset = dut._get_timeset(self.model_id, &self.name)?;
        Ok(timeset.eval_str().clone())
    }

    #[allow(non_snake_case)]
    #[getter]
    fn get___period__(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let timeset = dut._get_timeset(self.model_id, &self.name)?;
        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(match &timeset.period_as_string {
            Some(p) => p.clone().to_object(py),
            None => py.None(),
        })
    }

    #[getter]
    fn wavetables(&self) -> PyResult<Py<WavetableContainer>> {
        let t_id;
        {
            t_id = self.get_origen_id()?;
        }
        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(pywavetable_container!(py, self.model_id, t_id, &self.name))
    }

    #[args(_kwargs = "**")]
    fn add_wavetable(&self, name: &str, _kwargs: Option<&PyDict>) -> PyResult<PyObject> {
        let mut dut = DUT.lock().unwrap();
        let t_id;
        {
            t_id = dut._get_timeset(self.model_id, &self.name).unwrap().id;
        }
        dut.create_wavetable(t_id, name)?;

        let gil = Python::acquire_gil();
        let py = gil.python();
        let tset = dut._get_timeset(self.model_id, &self.name).unwrap();
        Ok(pywavetable!(py, tset, t_id, name)?)
    }

    #[getter]
    fn symbol_map(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let t_id;
        {
            t_id = dut._get_timeset(self.model_id, &self.name).unwrap().id;
        }
        let tester = origen::tester();

        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(Py::new(
            py,
            crate::timesets::timeset::SymbolMap {
                timeset_id: t_id,
                target_name: {
                    match tester.focused_tester_name() {
                        Some(n) => n,
                        None => return Ok(py.None()),
                    }
                },
            },
        )
        .unwrap()
        .to_object(py))
    }

    #[getter]
    fn symbol_maps(&self) -> PyResult<Vec<PyObject>> {
        let dut = DUT.lock().unwrap();
        let t = dut._get_timeset(self.model_id, &self.name).unwrap();
        let t_id;
        {
            t_id = t.id;
        }

        let gil = Python::acquire_gil();
        let py = gil.python();
        let retn = t
            .pin_action_resolvers
            .keys()
            .map({
                |target| {
                    Py::new(
                        py,
                        crate::timesets::timeset::SymbolMap {
                            timeset_id: t_id,
                            target_name: target.to_string(),
                        },
                    )
                    .unwrap()
                    .to_object(py)
                }
            })
            .collect::<Vec<PyObject>>();
        Ok(retn)
    }
}

impl Timeset {
    pub fn new(name: &str, model_id: usize) -> Self {
        Self {
            name: String::from(name),
            model_id: model_id,
        }
    }

    pub fn get_origen_id(&self) -> Result<usize, Error> {
        let dut = DUT.lock().unwrap();
        let timeset = dut._get_timeset(self.model_id, &self.name)?;
        Ok(timeset.id)
    }
}

#[pyclass]
pub struct Wavetable {
    pub timeset_id: usize,
    pub name: String,
    pub model_id: usize,
}

#[pymethods]
impl Wavetable {
    #[args(_kwargs = "**")]
    fn add_waves(&self, name: &str, _kwargs: Option<&PyDict>) -> PyResult<PyObject> {
        let mut dut = DUT.lock().unwrap();
        let w_id;
        {
            w_id = dut.get_wavetable(self.timeset_id, &self.name).unwrap().id;
        }
        dut.create_wave_group(w_id, name, Option::None)?;

        let gil = Python::acquire_gil();
        let py = gil.python();
        let wt = dut.get_wavetable(self.timeset_id, &self.name).unwrap();
        Ok(pywave_group!(py, wt, name)?)
    }

    #[args(_kwargs = "**")]
    fn add_wave(&self, name: &str, _kwargs: Option<&PyDict>) -> PyResult<PyObject> {
        self.add_waves(name, _kwargs)
    }

    #[getter]
    fn get_waves(&self) -> PyResult<Py<WaveGroupContainer>> {
        let w_id;
        {
            w_id = self.get_origen_id()?;
        }
        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(pywave_group_container!(
            py,
            self.model_id,
            self.timeset_id,
            w_id,
            &self.name
        ))
    }

    /// Retrieves all applied waves as a dictionary whose keys are the physical pins which has a corresponding
    /// wave. The values are another dictionary whose key-value pair is the indicator finally pointing to the wave
    /// which defines the wave.
    ///
    /// .. code: python
    ///     {
    ///         porta1: {
    ///             "0": <Wave>,
    ///             "1": <Wave>,
    ///             "h": <Wave>,
    ///             "l": <Wave>,
    ///         },
    ///         porta0: {
    ///             "0": <Wave>,
    ///             "1": <Wave>,
    ///             "h": <Wave>,
    ///             "l": <Wave>,
    ///         },
    ///         clk: {
    ///             "0": <Wave>,
    ///             "1": <Wave>,
    ///         }
    ///     }
    ///
    fn applied_waves(&self) -> PyResult<PyObject> {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let empty: [PyObject; 0] = [];
        let t = PyTuple::new(py, &empty);
        self.applied_waves_for(t, None)
    }

    /// Same as :meth:`applied_waves` but supports internal filtering of the return values.
    #[args(pins = "*")]
    fn applied_waves_for(
        &self,
        pins: &PyTuple,
        indicators: Option<Vec<String>>,
    ) -> PyResult<PyObject> {
        let gil = Python::acquire_gil();
        let py = gil.python();

        let dut = DUT.lock().unwrap();
        let wt = dut._get_wavetable(self.timeset_id, &self.name)?;
        let waves = wt.applied_waves(
            &dut,
            &pins_to_backend_lookup_fields(py, &pins)?,
            &indicators.unwrap_or(vec![]),
        )?;
        Ok(waves.to_object(py))
    }

    #[getter]
    fn get_symbol_map(&self) -> PyResult<PyObject> {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let tester = origen::tester();
        match tester.focused_tester_name() {
            Some(name) => Ok(Py::new(py, SymbolMap::new(self.timeset_id, name))
                .unwrap()
                .to_object(py)),
            None => Ok(py.None()),
        }
    }

    #[getter]
    fn get_name(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let wt = dut.get_wavetable(self.timeset_id, &self.name);
        Ok(wt.unwrap().name.clone())
    }

    // Evaluates and returns the period.
    // Returns None if no period was specified or an error if it could not be evaluated.
    #[getter]
    pub fn get_period(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let wt = dut.get_wavetable(self.timeset_id, &self.name);
        let p = wt.unwrap().eval(Option::None)?;

        let gil = Python::acquire_gil();
        let py = gil.python();
        match p {
            Some(_p) => Ok(_p.to_object(py)),
            None => Ok(py.None()),
        }
    }

    // From the Python side, want to support receiving input as either an expression (String)
    // or as hard coded integer/float values..
    #[setter]
    pub fn set_period(&self, period: &PyAny) -> PyResult<()> {
        let mut dut = DUT.lock().unwrap();
        let wt = dut.get_mut_wavetable(self.timeset_id, &self.name).unwrap();
        if let Ok(p) = period.extract::<String>() {
            wt.set_period(Some(Box::new(p)))?;
        } else if let Ok(p) = period.extract::<f64>() {
            wt.set_period(Some(Box::new(p)))?;
        } else if period.get_type().name() == "NoneType" {
            wt.set_period(Option::None)?;
        } else {
            return super::super::type_error!(format!("Could not interpret 'period' argument as Numeric, String, or NoneType! (class '{}')", period.get_type().name()));
        };
        Ok(())
    }

    // Returns the period as a string before evaluation.
    #[allow(non_snake_case)]
    #[getter]
    pub fn get___period__(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let wt = dut.get_wavetable(self.timeset_id, &self.name);
        let p = &wt.unwrap().period;

        let gil = Python::acquire_gil();
        let py = gil.python();
        match p {
            Some(_p) => Ok(_p.to_object(py)),
            None => Ok(py.None()),
        }
    }
}

impl Wavetable {
    pub fn new(model_id: usize, timeset_id: usize, name: &str) -> Self {
        Self {
            timeset_id: timeset_id,
            name: String::from(name),
            model_id: model_id,
        }
    }

    pub fn get_origen_id(&self) -> Result<usize, Error> {
        let dut = DUT.lock().unwrap();
        let timeset = &dut.timesets[self.timeset_id];
        let w_id = timeset.get_wavetable_id(&self.name).unwrap();
        Ok(w_id)
    }
}

#[pyclass]
pub struct WaveGroup {
    pub model_id: usize,
    pub timeset_id: usize,
    pub wavetable_id: usize,
    pub name: String,
}

#[pymethods]
impl WaveGroup {
    #[args(_kwargs = "**")]
    fn add_wave(&self, name: &str, _kwargs: Option<&PyDict>) -> PyResult<PyObject> {
        let mut dut = DUT.lock().unwrap();
        let wgrp_id;
        {
            wgrp_id = dut
                .get_wave_group(self.wavetable_id, &self.name)
                .unwrap()
                .id;
        }
        let mut derived_from = Option::None;
        if let Some(args) = _kwargs {
            if let Some(_derived_from) = args.get_item("derived_from") {
                if let Ok(_waves) = _derived_from.extract::<String>() {
                    derived_from = Some(vec![_waves]);
                } else if let Ok(_waves) = _derived_from.extract::<Vec<String>>() {
                    derived_from = Some(_waves);
                } else {
                    return type_error!("Could not interpret 'derived_From' argument as a string or as a list of strings!");
                }
            }
        }
        dut.create_wave(wgrp_id, name, derived_from)?;

        let gil = Python::acquire_gil();
        let py = gil.python();
        let wgrp = dut.get_wave_group(self.wavetable_id, &self.name).unwrap();
        Ok(pywave!(py, wgrp, name)?)
    }

    #[getter]
    fn get_waves(&self) -> PyResult<Py<WaveContainer>> {
        let wgrp_id;
        {
            wgrp_id = self.get_origen_id()?;
        }
        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(pywave_container!(
            py,
            self.model_id,
            self.timeset_id,
            self.wavetable_id,
            wgrp_id,
            &self.name
        ))
    }

    #[getter]
    fn get_name(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let wt = dut.get_wavetable(self.timeset_id, &self.name);
        Ok(wt.unwrap().name.clone())
    }
}

impl WaveGroup {
    pub fn new(model_id: usize, timeset_id: usize, wavetable_id: usize, name: &str) -> Self {
        Self {
            model_id: model_id,
            timeset_id: timeset_id,
            wavetable_id: wavetable_id,
            name: String::from(name),
        }
    }

    pub fn get_origen_id(&self) -> Result<usize, Error> {
        let dut = DUT.lock().unwrap();
        let wavetable = &dut.wavetables[self.wavetable_id];
        let wgrp_id = wavetable.get_wave_group_id(&self.name).unwrap();
        Ok(wgrp_id)
    }
}

#[pyclass]
pub struct Wave {
    pub model_id: usize,
    pub timeset_id: usize,
    pub wavetable_id: usize,
    pub wave_group_id: usize,
    pub name: String,
}

#[pymethods]
impl Wave {
    #[getter]
    fn get_events(&self) -> PyResult<Py<EventContainer>> {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let wave_id;
        {
            wave_id = self.get_origen_id()?;
        }
        Ok(pyevent_container!(
            py,
            self.model_id,
            self.timeset_id,
            self.wavetable_id,
            self.wave_group_id,
            wave_id,
            &self.name
        ))
    }

    #[args(event = "**")]
    fn push_event(&self, event: Option<&PyDict>) -> PyResult<PyObject> {
        let mut dut = DUT.lock().unwrap();
        let (w_id, e_index);
        {
            w_id = dut
                .get_wave(self.wave_group_id, &self.name)
                .unwrap()
                .wave_id;
        }

        if event.is_none() {
            return type_error!("Keywords 'at' and 'action' are required to push a new event!");
        }

        let (at, unit, action) = (
            event.unwrap().get_item("at"),
            event.unwrap().get_item("unit"),
            event.unwrap().get_item("action"),
        );
        {
            // Resolve the 'action' keyword first because rust is a pain in the butt.
            // This is required and can only be a String.
            let temp: String;
            match action {
                Some(_action) => {
                    if let Ok(val) = _action.extract::<String>() {
                        temp = val;
                    } else if _action.is_none() {
                        return type_error!("'action' keyword is required (found None)!");
                    } else {
                        return type_error!("Could not interpret 'action' argument as String!");
                    }
                }
                None => return type_error!("'action' keyword is required!"),
            }
            let e = dut.create_event(
                w_id,
                // Resolve the 'at' keyword. This is required and can be either a String or a numeric.
                match at {
                    Some(_at) => {
                        if let Ok(val) = _at.extract::<String>() {
                            Box::new(val)
                        } else if let Ok(val) = _at.extract::<f64>() {
                            Box::new(val)
                        } else if _at.is_none() {
                            return type_error!("'at' keyword is required (found None)!");
                        } else {
                            return type_error!(
                                "Could not interpret 'at' argument as String or Numeric!"
                            );
                        }
                    }
                    None => return type_error!("'at' keyword is required!"),
                },
                // Resolve the 'unit' keyword. This is optional and can only be a string.
                match unit {
                    Some(_unit) => {
                        if let Ok(val) = _unit.extract::<String>() {
                            Some(val)
                        } else if _unit.is_none() {
                            Option::None
                        } else {
                            return type_error!(
                                "Could not interpret 'unit' argument as String or NoneType!"
                            );
                        }
                    }
                    None => Option::None,
                },
                &temp,
            )?;
            e_index = e.event_index;
        }

        // Return the newly created event
        let gil = Python::acquire_gil();
        let py = gil.python();

        let w = dut.get_wave(self.wave_group_id, &self.name).unwrap();
        Ok(pyevent!(py, w, e_index)?)
    }

    #[getter]
    fn get_indicator(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let w = dut.get_wave(self.wave_group_id, &self.name).unwrap();
        Ok(w.indicator.clone())
    }

    #[setter]
    fn set_indicator(&self, indicator: &str) -> PyResult<()> {
        let mut dut = DUT.lock().unwrap();
        let w = dut.get_mut_wave(self.wave_group_id, &self.name).unwrap();
        w.set_indicator(&indicator)?;
        Ok(())
    }

    #[getter]
    fn get_applied_to(&self) -> PyResult<Vec<PyObject>> {
        let dut = DUT.lock().unwrap();
        let w = dut.get_wave(self.wave_group_id, &self.name).unwrap();
        let gil = Python::acquire_gil();
        let py = gil.python();

        let mut pins: Vec<PyObject> = vec![];
        for p in w.applied_pin_ids.iter() {
            let ppin = &dut.pins[*p];
            pins.push(
                super::super::pins::pin::Pin {
                    name: ppin.name.clone(),
                    model_id: ppin.model_id,
                }
                .into_py(py),
            );
        }
        Ok(pins)
    }

    #[args(pins = "*")]
    fn apply_to(&self, pins: Vec<String>) -> PyResult<PyObject> {
        let mut dut = DUT.lock().unwrap();
        let wid;
        {
            wid = dut
                .get_wave(self.wave_group_id, &self.name)
                .unwrap()
                .wave_id;
        }
        let pins_with_model_id: Vec<(usize, String)> =
            pins.iter().map(|pin| (0, pin.clone())).collect();
        dut.apply_wave_id_to_pins(wid, &pins_with_model_id)?;

        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(Py::new(
            py,
            crate::timesets::timeset::Wave {
                name: self.name.clone(),
                model_id: self.model_id,
                timeset_id: self.timeset_id,
                wavetable_id: self.wavetable_id,
                wave_group_id: self.wave_group_id,
            },
        )
        .unwrap()
        .to_object(py))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_name(&self) -> PyResult<String> {
        Ok(self.name.clone())
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_DriveHigh(&self) -> PyResult<String> {
        Ok(String::from("DriveHigh"))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_DriveLow(&self) -> PyResult<String> {
        Ok(String::from("DriveLow"))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_HighZ(&self) -> PyResult<String> {
        Ok(String::from("HighZ"))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_VerifyHigh(&self) -> PyResult<String> {
        Ok(String::from("VerifyHigh"))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_VerifyLow(&self) -> PyResult<String> {
        Ok(String::from("VerifyLow"))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_VerifyZ(&self) -> PyResult<String> {
        Ok(String::from("VerifyZ"))
    }

    #[allow(non_snake_case)]
    #[getter]
    pub fn get_Capture(&self) -> PyResult<String> {
        Ok(String::from("Capture"))
    }
}

impl Wave {
    pub fn new(
        model_id: usize,
        timeset_id: usize,
        wavetable_id: usize,
        wave_group_id: usize,
        name: &str,
    ) -> Self {
        Self {
            model_id: model_id,
            timeset_id: timeset_id,
            wavetable_id: wavetable_id,
            wave_group_id: wave_group_id,
            name: String::from(name),
        }
    }

    pub fn get_origen_id(&self) -> Result<usize, Error> {
        let dut = DUT.lock().unwrap();
        let wgrp = &dut.wave_groups[self.wave_group_id];
        let w_id = wgrp.get_wave_id(&self.name).unwrap();
        Ok(w_id)
    }
}

#[pyclass]
pub struct Event {
    pub model_id: usize,
    pub timeset_id: usize,
    pub wavetable_id: usize,
    pub wave_group_id: usize,
    pub wave_id: usize,
    pub wave_indicator: String,
    pub index: usize,
}

#[pymethods]
impl Event {
    #[getter]
    pub fn get_action(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let e = dut.get_event(self.wave_id, self.index).unwrap();
        Ok(e.action.clone())
    }

    #[setter]
    pub fn action(&self, action: &str) -> PyResult<()> {
        let mut dut = DUT.lock().unwrap();
        let e = dut.get_mut_event(self.wave_id, self.index).unwrap();
        e.set_action(action)?;
        Ok(())
    }

    #[getter]
    pub fn unit(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let e = dut.get_event(self.wave_id, self.index).unwrap();

        let gil = Python::acquire_gil();
        let py = gil.python();
        match &e.unit {
            Some(unit) => Ok(unit.clone().to_object(py)),
            None => Ok(py.None()),
        }
    }

    #[getter]
    pub fn at(&self) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        let e = dut.get_event(self.wave_id, self.index).unwrap();

        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(e.eval(&dut, Option::None)?.to_object(py))
    }

    #[getter]
    pub fn __at__(&self) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let e = dut.get_event(self.wave_id, self.index).unwrap();
        Ok(e.at.clone())
    }
}

impl Event {
    pub fn new(
        model_id: usize,
        timeset_id: usize,
        wavetable_id: usize,
        wave_group_id: usize,
        wave_id: usize,
        wave_indicator: &str,
        id: usize,
    ) -> Self {
        Self {
            model_id: model_id,
            timeset_id: timeset_id,
            wavetable_id: wavetable_id,
            wave_group_id: wave_group_id,
            wave_id: wave_id,
            wave_indicator: String::from(wave_indicator),
            index: id,
        }
    }
}

fn action_from_pyany(action: &PyAny) -> PyResult<origen::core::model::pins::pin::PinAction> {
    Ok(
        origen::core::model::pins::pin::PinAction::from_delimiter_optional(
            {
                let t;
                if let Ok(a) = action.extract::<String>() {
                    t = a.clone();
                } else if action.get_type().name() == "PinActions" {
                    let pin_actions = action
                        .extract::<PyRef<super::super::pins::pin_actions::PinActions>>()
                        .unwrap();
                    if pin_actions.actions.len() == 1 {
                        t = pin_actions.actions.first().unwrap().to_string();
                    } else {
                        return Err(pyo3::exceptions::ValueError::py_err(
                            "SymbolMap lookups can only retrieve single symbols at a time",
                        ));
                    }
                } else {
                    return super::super::type_error!(&format!(
                        "Cannot cast type {} to a valid PinAction",
                        action.get_type().name()
                    ));
                }
                t
            }
            .as_str(),
        )?,
    )
}

#[pyclass]
pub struct SymbolMap {
    timeset_id: usize,
    target_name: String,
}

impl SymbolMap {
    pub fn new(timeset_id: usize, target_name: String) -> Self {
        Self {
            timeset_id: timeset_id,
            target_name: target_name,
        }
    }
}

#[pymethods]
impl SymbolMap {
    fn keys(&self) -> PyResult<Vec<String>> {
        let dut = DUT.lock().unwrap();
        let resolver = &dut.timesets[self.timeset_id].pin_action_resolvers[&self.target_name];
        Ok(resolver
            .mapping()
            .iter()
            .map(|(k, _)| k.to_string())
            .collect())
    }

    fn values(&self) -> PyResult<Vec<String>> {
        let dut = DUT.lock().unwrap();
        let resolver = &dut.timesets[self.timeset_id].pin_action_resolvers[&self.target_name];
        Ok(resolver
            .mapping()
            .iter()
            .map(|(_, v)| v.to_string())
            .collect::<Vec<String>>())
    }

    fn items(&self) -> PyResult<Vec<(String, String)>> {
        let dut = DUT.lock().unwrap();
        let resolver = &dut.timesets[self.timeset_id].pin_action_resolvers[&self.target_name];

        Ok(resolver
            .mapping()
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect::<Vec<(String, String)>>())
    }

    fn get(&self, action: &PyAny) -> PyResult<PyObject> {
        let gil = Python::acquire_gil();
        let py = gil.python();
        match self.__getitem__(action) {
            Ok(a) => Ok(a.into_py(py)),
            Err(_) => Ok(py.None()),
        }
    }

    fn set_symbol(
        &mut self,
        action: &PyAny,
        new_resolution: String,
        target: Option<String>,
    ) -> PyResult<()> {
        if let Some(t) = target {
            let mut dut = DUT.lock().unwrap();
            let tset = &mut dut.timesets[self.timeset_id];
            if let Some(resolver) = tset.pin_action_resolvers.get_mut(&t) {
                resolver.update_mapping(action_from_pyany(action)?, new_resolution.clone());
                Ok(())
            } else {
                Err(pyo3::exceptions::KeyError::py_err(format!(
                    "Timeset '{}' does not have a symbol map targeting '{}' (The target must be set prior to timeset creation)",
                    tset.name,
                    t
                )))
            }
        } else {
            self.__setitem__(action, new_resolution)
        }
    }

    fn for_target(&self, target: String) -> PyResult<PyObject> {
        let dut = DUT.lock().unwrap();
        {
            let t = &dut.timesets[self.timeset_id];
            if !t.pin_action_resolvers.contains_key(&target) {
                return Err(pyo3::exceptions::KeyError::py_err(format!(
                    "Timeset '{}' does not have a symbol map targeting '{}' (The target must be set prior to timeset creation)",
                    t.name,
                    target
                )));
            }
        }

        let gil = Python::acquire_gil();
        let py = gil.python();
        Ok(Py::new(
            py,
            crate::timesets::timeset::SymbolMap {
                timeset_id: self.timeset_id,
                target_name: target,
            },
        )
        .unwrap()
        .to_object(py))
    }
}

#[pyproto]
impl PyMappingProtocol for SymbolMap {
    fn __getitem__(&self, action: &PyAny) -> PyResult<String> {
        let dut = DUT.lock().unwrap();
        let resolver = &dut.timesets[self.timeset_id].pin_action_resolvers[&self.target_name];

        if let Some(r) = resolver.resolve(&action_from_pyany(action)?) {
            Ok(r)
        } else {
            Err(pyo3::exceptions::KeyError::py_err(format!(
                "No symbol found for {}",
                action
            )))
        }
    }

    fn __setitem__(&mut self, action: &PyAny, new_resolution: String) -> PyResult<()> {
        let mut dut = DUT.lock().unwrap();
        let tester = origen::tester();
        for target in tester.targets_as_strs().iter() {
            // let resolver = &mut dut.timesets[self.timeset_id].pin_action_resolvers[&self.target_name];
            let resolver = &mut dut.timesets[self.timeset_id].pin_action_resolvers[target];
            resolver.update_mapping(action_from_pyany(action)?, new_resolution.clone())
        }
        Ok(())
    }

    fn __len__(&self) -> PyResult<usize> {
        let dut = DUT.lock().unwrap();
        let resolver = &dut.timesets[self.timeset_id].pin_action_resolvers[&self.target_name];
        Ok(resolver.mapping().len())
    }
}

#[pyproto]
impl pyo3::class::sequence::PySequenceProtocol for SymbolMap {
    fn __contains__(&self, item: &PyAny) -> PyResult<bool> {
        match pyo3::PyMappingProtocol::__getitem__(self, &item) {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }
}

#[pyclass]
pub struct SymbolMapIter {
    pub keys: Vec<String>,
    pub i: usize,
}

#[pyproto]
impl pyo3::class::iter::PyIterProtocol for SymbolMapIter {
    fn __iter__(slf: PyRefMut<Self>) -> PyResult<Py<Self>> {
        Ok(slf.into())
    }

    fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<String>> {
        if slf.i >= slf.keys.len() {
            return Ok(None);
        }
        let name = slf.keys[slf.i].clone();
        slf.i += 1;
        Ok(Some(name))
    }
}

#[pyproto]
impl pyo3::class::iter::PyIterProtocol for SymbolMap {
    fn __iter__(slf: PyRefMut<Self>) -> PyResult<SymbolMapIter> {
        Ok(SymbolMapIter {
            keys: slf.keys().unwrap(),
            i: 0,
        })
    }
}