ncbi 0.2.0-beta

Rust data structures for NCBI APIs
Documentation
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
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
//! Sequence feature elements
//!
//! Adapted from ["seqfeat.asn"](https://www.ncbi.nlm.nih.gov/IEB/ToolBox/CPP_DOC/lxr/source/src/objects/seqfeat/seqfeat.asn)
//! and documented by [NCBI C++ Toolkit Book](https://ncbi.github.io/cxx-toolkit/pages/ch_datamod#ch_datamod.datamodel.seqfeat)
//!
//! A feature table is a collection of sequence features called [`SeqFeat`]s.
//! A [`SeqFeat`] serves to connect a sequence location ([`SeqLoc`]) with a
//! specific block of data known as a datablock. Datablocks are defined
//! objects on their own and are often used in other contexts, such as
//! publications ([`PubSet`]), references to organisms ([`OrgRef`]), or genes
//! ([`GeneRef`]). Some datablocks, like coding regions ([`CdRegion`]), only make
//! sense when considered within the context of a [`SeqLoc`]. However, each
//! datablock is designed to fulfill a specific purpose and is independent
//! of others. This means that changes or additions to one datablock do not
//! affect the others.
//!
//! When a pre-existing object from another context is used as a datablock,
//! any software capable of utilizing that object can also operate on the
//! feature. For example, code that displays a publication can function with a
//! publication from a bibliographic database or one used as a sequence
//! feature without any modifications.
//!
//! The [`SeqFeat`] data structure and the [`SeqLoc`] used to attach it to the
//! sequence are shared among all features. This allows for a set of operations
//! that can be performed on all features, regardless of the type of datablocks
//! attached to them. Therefore, a function designed to determine all features
//! in a specific region of a Bioseq does not need to consider the specific
//! types of features involved.
//!
//! A [`SeqFeat`] is referred to as bipolar because it can have up to two
//! [`SeqLoc`]s. The [`SeqFeat`].location indicates the "source" and represents
//! the location on the DNA sequence, similar to the single location in common
//! feature table implementations. The `product` from [`SeqFeat`] represents
//! the "sink" and is typically associated with the protein sequence produced.
//! For example, a [`CdRegion`] feature would have its [`SeqFeat`].location on
//! the DNA and its [`SeqFeat`].product on the corresponding protein sequence.
//! This usage defines the process of translating a DNA sequence into a protein
//! sequence, establishing an explicit relationship between nucleic acid and
//! protein sequence databases.
//!
//! Having two [`SeqLoc`]s allows for a more comprehensive representation of
//! data conflicts or exceptional biological circumstances. For instance,
//! if an author presents a DNA sequence and its protein product in a figure,
//! it is possible to enter the DNA and protein sequences independently and
//! then confirm through the [`CdRegion`] feature that the DNA indeed translates
//! to the provided protein sequence. In cases where the DNA and protein do
//! not match, it could indicate an error in the database or the original
//! paper. By setting a "conflict" flag in the CdRegion, the problem can be
//! identified early and addressed. Additionally, there may be situations
//! where a genomic sequence cannot be translated to a protein due to known
//! biological reasons, such as RNA editing or suppressor tRNAs. In such
//! cases, the [`SeqFeat`] can be marked with an "exception" flag to indicate
//! that the data is correct but may not behave as expected.

use crate::biblio::{PubMedId, DOI};
use crate::general::{DbTag, IntFuzz, ObjectId, UserObject};
use crate::parsing::{read_vec_node, read_int, read_node, read_string, read_vec_str_unchecked, UnexpectedTags, read_bool_attribute};
use crate::r#pub::PubSet;
use crate::seq::{Heterogen, Numbering, PubDesc, SeqLiteral};
use crate::seqloc::{GiimportId, SeqId, SeqLoc};
use crate::parsing::{XmlNode, XmlVecNode};
use bitflags::bitflags;
use enum_primitive::FromPrimitive;
use quick_xml::events::{BytesStart, Event};
use quick_xml::Reader;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
/// Feature identifiers
pub enum FeatId {
    /// GenInfo backbone
    GIBB(u64),

    /// GenInfo import
    GIIM(GiimportId),

    /// for local software use
    Local(ObjectId),

    /// for use by various databases
    General(DbTag),
}

impl XmlNode for FeatId {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Feat-id")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        // variant tags
        let gibb_tag = BytesStart::new("Feat-id_gibb");
        let giim_tag = BytesStart::new("Feat-id_giim");
        let local_tag = BytesStart::new("Feat-id_local");
        let general_tag = BytesStart::new("Feat-id_general");

        let forbidden = [
            gibb_tag,
            giim_tag
        ];
        let forbidden = UnexpectedTags(&forbidden);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == local_tag.name() {
                        return Self::Local(read_node(reader).unwrap()).into();
                    } else if name == general_tag.name() {
                        return Self::General(read_node(reader).unwrap()).into();
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return None
                    }
                }
                _ => ()
            }
        }
    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Experimental evidence for existence of feature
///
/// # Note
///
/// Original implementation lists this as `ENUMERATED`, therefore it is assumed that
/// serialized representation is an integer.
pub enum SeqFeatExpEvidence {
    /// any reasonable experiment check
    Experimental = 1,

    /// similarity, pattern, etc
    NotExperimental,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
/// Sequence feature generalization
pub struct SeqFeat {
    pub id: Option<FeatId>,

    /// the specific data
    pub data: SeqFeatData,

    /// incomplete in some way?
    pub partial: Option<bool>,

    /// something funny about this?
    pub except: Option<bool>,

    pub comment: Option<String>,

    /// product of process
    pub product: Option<SeqLoc>,

    /// feature made from
    pub location: SeqLoc,

    /// qualifiers
    pub qual: Option<Vec<GbQual>>,

    /// for user defined label
    pub title: Option<String>,

    /// user defined structure extension
    pub ext: Option<UserObject>,

    /// citations for this feature
    pub cit: Option<PubSet>,

    /// evidence for existence of feature
    pub exp_ev: Option<SeqFeatExpEvidence>,

    /// cite other relevant features
    pub xref: Option<Vec<SeqFeatXref>>,

    /// support for xref to other databases
    pub dbxref: Option<Vec<DbTag>>,

    /// annotated on pseudogene
    pub pseudo: Option<bool>,

    /// explain if `except=true`
    pub except_text: Option<String>,

    /// set of id's; will replace `id` field
    pub ids: Option<Vec<FeatId>>,

    /// set of extensions; will replace `ext` field
    pub exts: Option<Vec<UserObject>>,

    pub support: Option<SeqFeatSupport>,
}

impl SeqFeat {
    /// not originally in spec
    pub fn default() -> Self {
        Self::new(SeqFeatData::User(UserObject::default()))
    }

    pub fn new(data: SeqFeatData) -> Self {
        Self {
            id: None,
            data,
            partial: None,
            except: None,
            comment: None,
            product: None,
            location: SeqLoc::default(),
            qual: None,
            title: None,
            ext: None,
            cit: None,
            exp_ev: None,
            xref: None,
            dbxref: None,
            pseudo: None,
            except_text: None,
            ids: None,
            exts: None,
            support: None,
        }
    }
}

impl XmlNode for SeqFeat {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Seq-feat")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        let mut feat = Self::default();

        // attribute tags
        let id_tag = BytesStart::new("Seq-feat_id");
        let data_tag = BytesStart::new("Seq-feat_data");
        let partial_tag = BytesStart::new("Seq-feat_partial");
        let except_tag = BytesStart::new("Seq-feat_except");
        let comment_tag = BytesStart::new("Seq-feat_comment");
        let product_tag = BytesStart::new("Seq-feat_product");
        let location_tag = BytesStart::new("Seq-feat_location");
        let qual_tag = BytesStart::new("Seq-feat_qual");
        let title_tag = BytesStart::new("Seq-feat_title");
        let ext_tag = BytesStart::new("Seq-feat_ext");
        let cit_tag = BytesStart::new("Seq-feat_cit");
        let exp_ev_tag = BytesStart::new("Seq-feat_exp_ev");
        let xref_tag = BytesStart::new("Seq-feat_xref");
        let dbxref_tag = BytesStart::new("Seq-feat_db_xref");
        let pseudo_tag = BytesStart::new("Seq-feat_pseudo");
        let except_text_tag = BytesStart::new("Seq-feat_except_text");
        let ids_tag = BytesStart::new("Seq-feat_ids");
        let exts_tag = BytesStart::new("Seq-feat_exts");
        let support_tag = BytesStart::new("Seq-feat_support");

        // list of XML elements that have not been implemented yet
        let forbidden = [
            partial_tag,
            except_tag,
            title_tag,
            cit_tag,
            exp_ev_tag,
            dbxref_tag,
            except_text_tag,
            ids_tag,
            exts_tag,
            support_tag
        ];
        let forbidden = UnexpectedTags(&forbidden);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();
                    if name == id_tag.name() {
                        feat.id = read_node(reader);
                    } else if name == ext_tag.name() {
                        feat.ext = read_node(reader);
                    } else if name == product_tag.name() {
                        feat.product = read_node(reader);
                    } else if name == qual_tag.name() {
                        feat.qual = Some(read_vec_node(reader, qual_tag.to_end()));
                    } else if name == data_tag.name() {
                        feat.data = read_node(reader).unwrap();
                    } else if name == location_tag.name() {
                        feat.location = read_node(reader).unwrap();
                    } else if name == comment_tag.name() {
                        feat.comment = read_string(reader);
                    } else if name == xref_tag.name() {
                        feat.xref = Some(read_vec_node(reader, xref_tag.to_end()));
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::Empty(e) => {
                    if e.name() == pseudo_tag.name() {
                        feat.pseudo = read_bool_attribute(&e);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return feat.into()
                    }
                }
                _ => ()
            }
        }
    }
}
impl XmlVecNode for SeqFeat {}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Internal representation of chemical bond for [`SeqFeatData`]
///
/// # Note
///
/// Original implementation lists this as `ENUMERATED`, therefore it is assumed that
/// serialized representation is an integer.
pub enum SeqFeatBond {
    Disulfide = 1,
    Thiolester,
    XLink,
    Thioether,
    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Internal representation of site biochemical modification for [`SeqFeatData`]
///
/// # Note
///
/// Original implementation lists this as `ENUMERATED`, therefore it is assumed that
/// serialized representation is an integer.
pub enum SeqFeatSite {
    Active = 1,
    Binding,
    Cleavage,
    Inhibit,
    Modified,
    Clycosylation,
    Myristoylation,
    Mutagenized,
    MetalBinding,
    Phosphorylation,
    Acetylation,
    Amidation,
    Methylation,
    Hydroxylation,
    Sulfatation,
    OxidativeDeamination,
    PyrrolidoneCarboxylicAcid,
    GammaCarboxylglutamicAcid,
    Blocked,
    LipidBinding,
    NpBinding,
    DnaBinding,
    SignalPeptide,
    TransitPeptide,
    TransmembraneRegion,
    Nitrosylation,
    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Internal representation of protein secondary structure for [`SeqFeatData`]
///
/// # Note
///
/// Original implementation lists this as `ENUMERATED`, therefore it is assumed that
/// serialized representation is an integer.
pub enum PSecStr {
    /// any helix
    Helix = 1,

    /// beta sheet
    Sheet,

    /// beta or gamma turn
    Turn,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum SeqFeatData {
    Gene(GeneRef),
    Org(OrgRef),
    CdRegion(CdRegion),
    Prot(ProtRef),
    RNA(RnaRef),

    /// publication applies to this seq
    Pub(PubDesc),

    /// to annotate origin from another seq
    Seq(SeqLoc),

    Imp(ImpFeat),

    /// named region (ie: "globin locus")
    Region(String),
    Bond(SeqFeatBond),

    Site(SeqFeatSite),

    /// restriction site (for maps really)
    RSite(RSiteRef),

    /// user defined structure
    User(UserObject),

    /// transcription initiation
    TxInit(TxInit),

    /// a numbering system
    Num(Numbering),

    #[serde(rename = "psec-str")]
    /// protein secondary structure
    PSecStr(PSecStr),

    #[serde(rename = "non-std-residue")]
    /// non-standard residue here in seq
    NonStdResidue(String),

    /// cofactor, prosthetic group, etc, bound to seq
    Het(Heterogen),

    BioSrc(BioSource),
    Clone(CloneRef),
    Variation(VariationRef),
}

impl XmlNode for SeqFeatData {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("SeqFeatData")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        // variant tags
        let gene_tag = BytesStart::new("SeqFeatData_gene");
        let org_tag = BytesStart::new("SeqFeatData_org");
        let cdregion_tag = BytesStart::new("SeqFeatData_cdregion");
        let prot_tag = BytesStart::new("SeqFeatData_prot");
        let rna_tag = BytesStart::new("SeqFeatData_rna");
        let pub_tag = BytesStart::new("SeqFeatData_pub");
        let seq_tag = BytesStart::new("SeqFeatData_seq");
        let imp_tag = BytesStart::new("SeqFeatData_imp");
        let region_tag = BytesStart::new("SeqFeatData_region");
        let bond_tag = BytesStart::new("SeqFeatData_bond");
        let site_tag = BytesStart::new("SeqFeatData_site");
        let rsite_tag = BytesStart::new("SeqFeatData_rsite");
        let user_tag = BytesStart::new("SeqFeatData_user");
        let txinit_tag = BytesStart::new("SeqFeatData_txinit");
        let num_tag = BytesStart::new("SeqFeatData_num");
        let psec_str_tag = BytesStart::new("SeqFeatData_psec-str");
        let non_std_residue_tag = BytesStart::new("SeqFeatData_non-std-residue");
        let het_tag = BytesStart::new("SeqFeatData_het");
        let biosrc_tag = BytesStart::new("SeqFeatData_biosrc");
        let clone_tag = BytesStart::new("SeqFeatData_clone");
        let variation_tag = BytesStart::new("SeqFeatData_variation");

        let forbidden = [
            org_tag,
            rna_tag,
            pub_tag,
            seq_tag,
            imp_tag,
            region_tag,
            bond_tag,
            site_tag,
            rsite_tag,
            user_tag,
            txinit_tag,
            num_tag,
            psec_str_tag,
            non_std_residue_tag,
            het_tag,
            biosrc_tag,
            clone_tag,
            variation_tag
        ];
        let forbidden = UnexpectedTags(&forbidden);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == gene_tag.name() {
                        return Self::Gene(read_node(reader).unwrap()).into()
                    }
                    else if name == cdregion_tag.name() {
                        return Self::CdRegion(read_node(reader).unwrap()).into()
                    }
                    else if name == prot_tag.name() {
                        return Self::Prot(read_node(reader).unwrap()).into();
                    }
                    else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return None
                    }
                }
                _ => ()
            }
        }
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct SeqFeatXref {
    pub id: Option<FeatId>,
    pub data: Option<SeqFeatData>,
}

impl XmlNode for SeqFeatXref {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("SeqFeatXref")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        let mut xref = Self::default();

        // field tags
        let data_tag = BytesStart::new("SeqFeatXref_data");
        let id_tag = BytesStart::new("SeqFeatXref_id");

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == data_tag.name() {
                        xref.data = read_node(reader);
                    } else if name == id_tag.name() {
                        xref.id = read_node(reader);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return xref.into()
                    }
                }
                _ => ()
            }
        }
    }
}
impl XmlVecNode for SeqFeatXref {}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct SeqFeatSupport {
    pub experiment: Option<Vec<ExperimentSupport>>,
    pub inference: Option<Vec<InferenceSupport>>,
    pub model_evidence: Option<Vec<ModelEvidenceSupport>>,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Discrete types for types of experimental evidence
///
/// # Note
///
/// Original implementation lists this as `INTEGER`, therefore it is assumed that
/// serialized representation is an integer.
pub enum EvidenceCategory {
    NotSet,
    Coordinates,
    Description,
    Existence,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct ExperimentSupport {
    pub category: Option<EvidenceCategory>,
    pub explanation: String,
    pub pmids: Option<Vec<PubMedId>>,
    pub dois: Option<Vec<DOI>>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct ProgramId {
    pub name: String,
    pub version: Option<String>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct EvidenceBasis {
    pub programs: Option<Vec<ProgramId>>,
    pub accessions: Option<Vec<SeqId>>,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
#[repr(u8)]
/// Internal representation of inference support type for [`InferenceSupport`]
///
/// # Note
///
/// Original implementation lists this as `INTEGER`, therefore it is assumed that
/// serialized representation is an integer.
pub enum InferenceSupportType {
    #[default]
    NotSet,
    SimilarToSequence,
    SimilarToAA,
    SimilarToDNA,
    SimilarToRNA,
    SimilarTomRNA,
    SimilarToEst,
    SimilarToOtherRNA,
    Profile,
    NucleotideMotif,
    ProteinMotif,
    AbInitioPrediction,
    Alignment,
    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct InferenceSupport {
    pub category: Option<EvidenceCategory>,
    #[serde(rename = "type")]
    pub r#type: InferenceSupportType,
    pub other_type: Option<String>,
    // TODO: default to false
    pub same_species: bool,
    pub basis: EvidenceBasis,
    pub pmids: Option<Vec<PubMedId>>,
    pub dois: Option<Vec<DOI>>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct ModelEvidenceItem {
    pub id: SeqId,
    pub exon_count: Option<u64>,
    pub exon_length: Option<u64>,
    // TODO: default to false
    pub full_length: bool,
    // TODO: default to false
    pub supports_all_exon_combo: bool,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct ModelEvidenceSupport {
    pub method: Option<String>,
    pub mrna: Option<Vec<ModelEvidenceItem>>,
    pub est: Option<Vec<ModelEvidenceItem>>,
    pub protein: Option<Vec<ModelEvidenceItem>>,
    pub identification: Option<SeqId>,
    pub dbxref: Option<Vec<DbTag>>,
    pub exon_count: Option<u64>,
    pub exon_length: Option<u64>,
    pub full_length: bool,             // TODO: default false
    pub supports_all_exon_combo: bool, // TODO: default false
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
#[repr(u8)]
/// Internal representation of reading frame for [`CdRegion`]
///
/// # Note
///
/// Original implementation lists this as `ENUMERATED`, therefore it is assumed that
/// serialized representation is an integer.
pub enum CdRegionFrame {
    #[default]
    /// not set, code uses one
    NotSet,
    One,
    Two,
    /// reading frame
    Three,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
#[serde(rename_all = "kebab-case")]
/// Instructions to translate from a nucleic acid to a peptide
pub struct CdRegion {
    /// just an ORF ?
    pub orf: Option<bool>,

    pub frame: CdRegionFrame,

    /// supposed to translate, but doesn't
    pub conflict: Option<bool>,

    /// number of gaps on conflict/except
    pub gaps: Option<u64>,

    /// number of mismatches on above
    pub mismatch: Option<u64>,

    /// genetic code used
    pub code: Option<GeneticCode>,

    /// individual exceptions
    pub code_break: Option<Vec<CodeBreak>>,

    /// number of stop codons on above
    ///
    /// ### Original Comment:
    ///     each code is 64 cells long, in the order where:
    ///     `T=0, C=1, A=2, G=3, TTT=0, TTC=1, CTA=4, ...`
    ///
    ///     NOTE: this order does NOT correspond to a [`SeqData`] encoding.
    ///     It is "natural" to codon usage instead. The value in each cell is
    ///     the AA coded for start=AA coded only if first in peptide in start
    ///     array, if codon is not a legitimate start codon, that cell will
    ///     have the "gap" symbol for that alphabet. Otherwise it will have the
    ///     AA encoded when that codon is used at the start.
    pub stops: Option<u64>,
}

impl XmlNode for CdRegion {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Cdregion")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        let mut cdregion = Self::default();

        // field tags
        let _orf_tag = BytesStart::new("Cdregion_orf");
        let _frame_tag = BytesStart::new("Cdregion_frame");
        let _conflict_tag = BytesStart::new("Cdregion_conflict");
        let gaps_tag = BytesStart::new("Cdregion_gaps");
        let mismatch_tag = BytesStart::new("Cdregion_mismatch");
        let code_tag = BytesStart::new("Cdregion_code");
        let _code_break_tag = BytesStart::new("Cdregion_code-break");
        let stops_tag = BytesStart::new("Cdregion_stops");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == code_tag.name() {
                        cdregion.code = Some(read_vec_node(reader, code_tag.to_end()))
                    } else if name == gaps_tag.name() {
                        cdregion.gaps = read_int(reader);
                    } else if name == mismatch_tag.name() {
                        cdregion.mismatch = read_int(reader);
                    } else if name == stops_tag.name() {
                        cdregion.stops = read_int(reader);
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name)
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return cdregion.into()
                    }
                }
                _ => ()
            }
        }
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
/// Storage type for genetic code data
///
/// I do not know what purpose the "start" variants [`Self::SNcbiStdAa`],
/// [`Self::SNcbi8aa`], [`Self::SNcbiEaa`] serve.
pub enum GeneticCodeOpt {
    /// name of a code
    Name(String),

    /// id in dbase
    Id(u64),

    /// indexed to [`crate::asn::NCBIEaa`]
    NcbiEaa(String),

    /// indexed to [`crate::asn::NCBI8aa`]
    NCBI8aa(Vec<u8>),

    /// indexed to [`crate::asn::NCBIStdAa`]
    NCBIStdAa(Vec<u8>),

    /// start, indexed to [`crate::asn::NCBIEaa`]
    SNcbiEaa(String),

    /// start, indexed to [`crate::asn::NCBI8aa`]
    SNcbi8aa(Vec<u8>),

    /// start, indexed to [`crate::asn::NCBIStdAa`]
    SNcbiStdAa(Vec<u8>),
}

impl XmlNode for GeneticCodeOpt {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Genetic-code_E")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        // variant tags
        let id_tag = BytesStart::new("Genetic-code_E_id");
        let name_tag = BytesStart::new("Genetic-code_E_name");
        let ncbieaa_tag = BytesStart::new("Genetic-code_E_ncbieaa");
        let ncbi8aa_tag = BytesStart::new("Genetic-code_E_ncbi8aa");
        let ncbistdaa_tag = BytesStart::new("Genetic-code_E_ncbistdaa");
        let sncbieaa_tag = BytesStart::new("Genetic-code_E_sncbieaa");
        let sncbi8aa_tag = BytesStart::new("Genetic-code_E_sncbi8aa");
        let sncbistdaa_tag = BytesStart::new("Genetic-code_E_sncbistdaa");

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == id_tag.name() {
                        return Self::Id(read_int(reader).unwrap()).into()
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return None
                    }
                }
                _ => ()
            }
        }
    }
}
impl XmlVecNode for GeneticCodeOpt {}

pub type GeneticCode = Vec<GeneticCodeOpt>;

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
/// the amino acid that is the exception
pub enum CodeBreakAA {
    /// ASCII value of [`crate::asn::NCBIEaa`] code
    NcbiAa(u64),

    /// [`crate::asn::NCBI8aa`] code
    Ncbi8aa(u64),

    /// [`crate::asn::NCBIStdAa`] code
    NcbiStdAa(u64),
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
/// specific codon exceptions
pub struct CodeBreak {
    /// location of exception
    pub loc: SeqLoc,

    /// the amino acid that is the exception
    pub aa: CodeBreakAA,
}

/// table of genetic codes
pub type GeneticCodeTable = Vec<GeneticCode>;

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
/// Features imported from other databases
pub struct ImpFeat {
    pub key: String,

    /// original location string
    pub loc: Option<String>,

    /// text description
    pub descr: Option<String>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct GbQual {
    pub qual: String,
    pub val: String,
}

impl XmlNode for GbQual {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Gb-qual")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        let mut qual = Self::default();

        // field tags
        let qual_tag = BytesStart::new("Gb-qual_qual");
        let val_tag = BytesStart::new("Gb-qual_val");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == qual_tag.name() {
                        qual.qual = read_string(reader).unwrap();
                    } else if name == val_tag.name() {
                        qual.val = read_string(reader).unwrap();
                    } else {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return qual.into()
                    }
                }
                _ => ()
            }
        }
    }
}
impl XmlVecNode for GbQual {}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Internal representation of placement method for [`CloneRef`]
///
/// # Note
///
/// Original implementation lists this as `INTEGER`, therefore it is assumed that
/// serialized representation is an integer.
pub enum CloneRefPlacementMethod {
    /// clone placed by end sequence
    EndSeq,

    /// clone placed by insert alignment
    InsertAlignment,

    /// clone placed by STS
    STS,

    Fish,
    Fingerprint,

    /// combined end-seq and insert align
    EndSeqInsertAlignment,

    /// placement provided externally
    External = 253,

    /// human placed or approved
    Curated = 254,

    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
/// Specification of clone features
pub struct CloneRef {
    /// official clone symbol
    pub name: String,

    /// library name
    pub library: Option<String>,

    pub concordant: bool, // TODO: default to false
    pub unique: bool,     // TODO: default to false
    pub placement_method: Option<CloneRefPlacementMethod>,
    pub clone_seq: Option<CloneSeqSet>,
}

pub type CloneSeqSet = Vec<CloneSeq>;

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Internal representation of clone sequence type for [`CloneSeq`]
///
/// # Note
///
/// Original implementation lists this as `INTEGER`, therefore it is assumed that
/// serialized representation is an integer.
pub enum CloneSeqType {
    Insert,
    End,
    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Internal representation of clone confidence for [`CloneSeq`]
///
/// # Note
///
/// Original implementation lists this as `INTEGER`, therefore it is assumed that
/// serialized representation is an integer.
pub enum CloneSeqConfidence {
    /// multiple hits
    Multiple,

    /// unspecified
    Na,

    /// no hits, end flagged repetitive
    NoHitRep,

    /// no hits, end not flagged repetitive
    NoHitNoRep,

    /// hit on different chromosome
    OtherChrm,

    Unique,

    /// virtual (hasn't been sequenced)
    Virtual,

    /// multiple hits, end flagged repetitive
    MultipleRep,

    /// multiple hits, end not flagged repetitive
    MultipleNoRep,

    /// no hits
    NoHit,

    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
///
/// # Note
///
/// Original implementation lists this as `INTEGER`, therefore it is assumed that
/// serialized representation is an integer.
pub enum CloneSeqSupport {
    /// sequence used to place clone
    Prototype,

    /// sequence supports placement
    Supporting,

    /// supports a different placement
    SupportsOther,

    /// dose not support any placement
    NonSupporting,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct CloneSeq {
    #[serde(rename = "type")]
    pub r#type: CloneSeqType,
    pub confidence: Option<CloneSeqConfidence>,

    /// location on sequence
    pub location: SeqLoc,

    /// clone sequence location
    pub seq: Option<SeqLoc>,

    /// internal alignment identifier
    pub align_id: Option<DbTag>,
    pub support: Option<CloneSeqSupport>,
}

bitflags! {
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct VariantResourceLink: u8 {
    /// Clinical, Pubmed, Cited
    const Preserved = 1;

    /// Provisional third party annotations
    const Provisional = 2;

    /// has 3D structure in SNP3D table
    const Has3D = 4;

    /// SNP -> SubSNP -> Batch link_out
    const SubmitterLinkout = 8;

    /// Clinical if LSDB, OMIM, TPA, Diagnostic
    const Clinical = 16;

    /// Marker exists on high density genotyping kit
    const GenotypeKit = 32;
}}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    pub struct VariantGeneLocation: u32 {
        /// sequence intervals covered by a gene ID but not
        /// having an aligned transcript
        const InGene = 1;

        /// within 2kb of the 5' end of a gene feature
        const NearGene5 = 2;

        /// within 0.5kb of the 3' end of a gene feature
        const NearGene3 = 4;

        /// in intron
        const Intron = 8;

        /// in donor splice-site
        const Donor = 16;

        /// in acceptor splice-site
        const Acceptor = 32;

        /// in 5' UTR
        const UTR5 = 64;

        /// in 3' UTR
        const UTR3 = 128;

        /// the variant is observed in a start codon
        const InStartCodon = 256;

        /// the variant is observed in a stop codon
        const InStopCodon = 512;

        /// variant located between genes
        const Intergenic = 1024;

        /// variant is located in a conserved non-coding region
        const ConservedNoncoding = 2048;
    }
}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    pub struct VariantEffect: u16 {
        /// known to cause no functional changes.
        /// since value is 0, it does not combine with any other bit, explicitly
        /// implying there are no consequences from SNP
        const NoChange = 0;

        /// one allele in the set does not change the encoded amino aced
        const Synonymous = 1;

        /// one allele in the set changes to STOP codon
        const Nonsense = 2;

        /// one allele in the set changes protein peptide
        const Missense = 4;

        /// one allele in the set changes all downstream amino acids
        const Frameshift = 8;

        /// the variant causes increased transcription
        const UpRegulator = 16;

        /// the variant causes decreased transcription
        const DownRegulator = 32;

        const Methylation = 64;

        /// reference codon is not stop codon, but the SNP variant allele changes
        /// the codon to a termination codon
        const StopGain = 128;

        /// reverse of [`Self::StopGain`]: reference codon is a stop codon, but
        /// a SNP variant allele changes the codon to a non-termination codon.
        const StopLoss = 256;
    }
}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    pub struct VariantMapping: u8 {
        /// another SNP has the same mapped positions on reference assembly
        const HasOtherSnp = 1;

        /// weight 1 or 2 SNPs that map to different chromosomes on
        /// different assemblies
        const HasAssemblyConflict = 2;

        /// Only maps to 1 assembly
        const IsAssemblySpecific = 4;
    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// captures specificity of placement
///
/// # Note
///
/// This is *NOT* a bitfield
pub enum VariantMapWeight {
    IsUniquelyPlaced = 1,
    PlacedTwiceOnSameChrom = 2,
    PlacedTypeOnDiffChrom = 3,
    ManyPlacements = 10,
}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    pub struct FrequencyBasedValidation: u8 {
        /// low frequency variation that is cited in journal or other reputable
        /// source.
        const IsMutation = 1;

        /// >5% minor allele freq in each and all populations
        const Above5pctAll = 2;

        /// >5% minor allele freq in 1+ populations
        const Above5pct1plus = 4;

        /// bit is set if the variant has a minor allele observed in two or
        /// more separate chromosomes.
        const Validated = 8;

        /// >1% minor allele frequency in each and all populations
        const Above1pctAll = 16;

        /// >1% minor allele frequency in 1+ populations
        const Above1pct1plus = 32;
    }

}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum VariantGenotype {
    /// exists in a haplotype tagging set
    InHaplotypeSet,

    /// SNP has individual genotype
    HasGenotypes,
}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    pub struct VariantQualityCheck: u8 {
        /// reference sequence allele at the mapped position is not present in
        /// the SNP allele list, adjust for orientation
        const ContigAlleleMissing = 1;

        /// one member SS is withdrawn by submitter
        const WithdrawnBySubmitter = 2;

        /// RS set has 2+ alleles from different submissions and these sets
        /// share no alleles in common
        const NonOverlappingAlleles = 4;

        /// strain specific fixed difference
        const StrainSpecific = 8;

        /// has genotype conflict
        const GenotypeConflict = 16;
    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum VariantConfidence {
    Unknown,
    LikelyArtifact,
    Other = 255,
}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    /// origin of this allele, if known
    ///
    /// # See also
    /// - [`bitflags`](https://docs.rs/bitflags/latest/bitflags/macro.bitflags.html)
    ///   to view how multiple values may be held by this object
    pub struct VariantAlleleOrigin: u32 {
        const Unknown = 0;
        const Germline = 1;
        const Somatic = 2;
        const Inherited = 4;
        const Paternal = 8;
        const Maternal = 16;
        const DeNovo = 32;
        const Biparental = 64;
        const Uniparental = 128;
        const NotTested = 256;
        const TestedInconclusive = 512;
        const NotReported = 1024;

        /// stopper - 2^31
        const Other = 1073741824;
    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// observed allele state, if known
///
/// NOTE this field is not a bitflag
pub enum VariantAlleleState {
    Unknown,
    Homosygous,
    Heterozygous,
    Hemizygous,
    Nullizygous,
    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
/// Specification of variation features
///
/// The intention is to provide information to clients that reflect internal
/// information produced during the mapping of SNPs.
///
/// # Note
/// The most of these values are bitflags, an integer that represents
/// a bitwise OR (simple sum) of the possible values, unless otherwise stated
///
/// # Original comment
///
/// This comment comes from deprecated values from [`VariationRef`]
/// for fields that were moved here, specifically `allele_frequency`, and
/// `quality_codes`:
///
///     The case of multiple alleles for a SNP would be described by
///     parent-features of type `VariationSet.diff_alleles`, where the child
///     features of type `VariationINst`, all at the same location, would
///     describe individual alleles.
///
pub struct VariantProperties {
    pub version: u64,
    pub resource_link: Option<VariantResourceLink>,
    pub gene_location: Option<VariantGeneLocation>,
    pub effect: Option<VariantEffect>,
    pub mapping: Option<VariantMapping>,

    /// specificity of placement
    pub map_weight: Option<VariantMapWeight>,

    pub frequency_based_validation: Option<FrequencyBasedValidation>,
    pub genotype: Option<VariantGenotype>,
    pub quality_check: Option<VariantQualityCheck>,
    pub confidence: VariantConfidence,

    /// has this variant been validated?
    ///
    /// While a boolean flag offers no subtle distinctions of validation
    /// methods, occasionally it is only known as a single bool value.
    ///
    /// ### Note
    /// This flag is redundant and should be omitted if more comprehensive
    /// validation information is present
    pub other_validation: Option<bool>,

    /// origin of allele, if known
    pub allele_origin: Option<VariantAlleleOrigin>,

    /// observed allele state, if known
    pub allele_state: Option<VariantAlleleState>,

    /// minor allele frequency of the default population
    pub allele_frequency: Option<f64>,

    /// is this variant the ancestral allele
    pub is_ancestral_allele: Option<bool>,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// does this variant have known clinical significance?
pub enum PhenotypeClinicalSignificance {
    Unknown,
    Untested,
    NonPathogenic,
    ProbableNonPathogenic,
    ProbablePathogenic,
    Pathogenic,
    DrugResponse,
    Histocompatibility,
    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Phenotype {
    pub source: Option<String>,
    pub term: Option<String>,
    pub xref: Option<Vec<DbTag>>,

    /// does this variant have known clinical significance?
    pub clinical_significance: Option<PhenotypeClinicalSignificance>,
}

bitflags! {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    /// This field is an explicit bitflag
    pub struct PopulationDataFlags: u8 {
        const IsDefaultPopulation = 1;
        const IsMinorAllele = 2;
        const IsRareAllele = 4;
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct PopulationData {
    /// assayed population (eg: HAPMAP-CEU)
    pub population: String,
    pub genotype_frequency: Option<f64>,
    pub chromosomes_tested: Option<u64>,
    pub sample_ids: Option<Vec<ObjectId>>,
    pub allele_frequency: Option<f64>,
    pub flags: Option<PopulationDataFlags>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct ExtLoc {
    pub id: ObjectId,
    pub location: SeqLoc,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum VariantRefMethod {
    Unknown,
    BacAcgh,
    Computational,
    Curated,
    DigitalArray,
    ExpressionArray,
    Fish,
    FlankingSequence,
    Maph,
    McdAnalysis,
    Mlpa,
    OeaAssembly,
    OligoAcgh,
    PairedEnd,
    Pcr,
    Qpcr,
    ReadDepth,
    Roma,
    RtPcr,
    Sage,
    SequenceAlignment,
    Sequencing,
    SnpArray,
    Southern,
    Western,
    OpticalMapping,
    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum VariationRefDataSetType {
    Unknown,
    Compound,
    Products,
    Haplotype,
    Genotype,
    Mosaic,
    Individual,
    Population,
    Alleles,
    Package,
    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct VariationRefDataSet {
    #[serde(rename = "type")]
    pub r#type: VariationRefDataSetType,
    pub variations: Vec<VariationRef>,
    pub name: Option<String>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum VariationRefData {
    Unknown,

    /// free-form
    Note(String),

    UniparentalDisomy,

    /// actual sequence-edit at feat.location
    Instance(VariationInst),

    /// set of related variations
    ///
    /// location of the set equals to the union of member locations
    Set(Vec<VariationRefDataSet>),

    Variations(Vec<VariationRef>),

    /// variant is a complex and un-described change at the location
    ///
    /// This type of variant is known to occur in dbVar submissions
    Complex,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
/// see http://www.hgvs.org/mutnomen/recs-prot.html
pub struct VariationFrameshift {
    pub phase: Option<i64>,
    pub x_length: Option<i64>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct VariationLossOfHeterozygosity {
    /// in germline comparison, it will be reference genome assembly
    /// (default) or referenece/normal population. In somatic mutation,
    /// it will be a name of the normal tissue
    pub reference: Option<String>,

    /// name of the testing subject type or the testing issue
    pub test: Option<String>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum VariationConsequence {
    Unknown,

    /// some effect on splicing
    Splicing,

    /// free-form
    Note(String),

    /// describe resulting variation in the product, eg: missense,
    /// nonsense, silent, neutral, etc in a protein that arises from
    /// THIS variation.
    Variation(VariationRef),

    /// see http://www.hgvs.org/mutnomen/recs-prot.html
    Frameshift(VariationFrameshift),
    LossOfHeterozygosity(VariationLossOfHeterozygosity),
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct SomaticOriginCondition {
    pub description: Option<String>,

    /// reference to BioTerm / other descriptive database
    pub object_id: Option<Vec<DbTag>>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct VariationSomaticOrigin {
    /// description of the somatic origin itself
    pub source: Option<SubSource>,

    /// condition related to this origin's type
    pub condition: Option<SomaticOriginCondition>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
/// reference to SNP
///
/// This object relates three IDs:
/// - our current object's ID
/// - the ID of this object's parent, if it exists
/// - the sample ID that this item originates from
pub struct VariationRef {
    /// ID's (ie: SN rsid / ssid, dbVar nsv/nssv)
    ///
    /// expected values include:
    /// - 'dbSNP|rs12334'
    /// - 'dbSNP|ss12345'
    /// - 'dbVar|nsv1'
    pub id: Option<DbTag>,
    pub parent_id: Option<DbTag>,
    pub sample_id: Option<ObjectId>,
    pub other_ids: Option<Vec<DbTag>>,

    /// names and synonyms
    /// some variants have well-known canonical names and possible
    /// accepted synonyms
    pub name: Option<String>,
    pub synonyms: Option<Vec<String>>,

    /// tag for comment and descriptions
    pub description: Option<String>,

    /// phenotype
    pub phenotype: Option<Vec<Phenotype>>,

    /// sequencing / acquisition method
    pub method: Option<Vec<VariantRefMethod>>,

    /// variant properties bitflags
    pub variant_prop: Option<VariantProperties>,

    pub data: VariationRefData,
    pub consequence: Option<Vec<VariationConsequence>>,
    pub somatic_origin: Option<Vec<VariationSomaticOrigin>>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum DeltaSeq {
    Literal(SeqLiteral),
    Loc(SeqLoc),

    /// same location as [`VariationRef`] itself
    This,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
#[repr(u8)]
pub enum DeltaAction {
    #[default]
    /// replace len(seq) positions starting with location.start with seq
    Morph,

    /// go downstream by distance specified by multiplier (upstream if < 0)
    /// in genomic context
    Offset,

    /// excise sequence at location
    ///
    /// if multiplier is specified, delete len(location)*multiplier
    /// positions downstream
    DelAt,

    ///  insert seq before the location.start
    InsBefore,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct DeltaItem {
    pub seq: Option<DeltaSeq>,

    /// multiplier allows representing a tandem, eg: ATATAT as AT*3
    ///
    /// This allows describing CNV/SSR where delta=self  with a
    /// multiplier which specifies the count of the repeat unit.
    pub multiplier: Option<i64>, // assumed 1 if not specified
    pub multiplier_fuzz: Option<IntFuzz>,

    pub action: DeltaAction,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum VariationInstType {
    /// `delta=None`
    Unknown,

    /// `delta=None`
    Identity,

    /// `delta=[del, ins.seq=RevComp(variation-location)]`
    Inv,

    /// `delta=[morph of length 1]`
    ///
    /// NOTE: this is snV not snP; the latter requires frequency-based
    /// validation to be established in [`VariantProperties`]. The strict
    /// definition of SNP is an SNV with an established population frequency
    /// of at least 1% in at least 1 population.
    Snv,

    /// `delta=[morph of length >1]`
    Mnp,

    #[serde(rename = "delins")]
    /// `delta=[del, ins]`
    DelIns,

    /// `delta=[del]`
    Del,

    /// `delta=[ins]`
    Ins,

    /// `delta=[del, ins.seq=repeat-unit with fuzzy multiplier]`
    ///
    /// `variation_location` is the microsat expansion on the sequence
    Microsatellite,

    /// `delta=[del, ins.seq= known donor or 'this']`
    ///
    /// `variation_location` is equiv of transposon locations
    Transposon,

    /// `delta=[del, ins= 'this' with fuzzy multiplier]`
    Cnv,

    /// `delta=[ins.seq= upstream location on the same strand]`
    DirectCopy,

    /// `delta=[ins.seq= downstream location on the same strand]`
    RevDirectCopy,

    /// `delta=[ins.seq= upstream location on the same opposite strand]`
    InvertedCopy,

    /// `delta=[ins.seq= downstream location on the same opposite strand]`
    EvertedCopy,

    /// delta = like [`Self::DelIns`]
    Translocation,

    /// `delta=[morph of length 1]`
    ProtMissense,

    /// `delta=[del]`
    ///
    /// `variation_location` is the tail of the protein being truncated
    ProtNonsense,

    /// `delta=[morph of length 1]`
    ProtNeutral,

    /// `delta=[morph of length 1, same AA as at variation-location]`
    ProtSilent,

    /// delta=any
    ProtOther,

    /// delta=any
    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Used to label items in a [`VariationRef`] package
pub enum VariationInstObservation {
    /// represents the asserted base at a position
    Asserted = 1,

    /// represents the reference base at the position
    Reference = 2,

    /// represent the observed variant at a given position
    Variant = 4,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct VariationInst {
    #[serde(rename = "type")]
    pub r#type: VariationInstType,

    /// sequence that replaces the location, in biological order
    pub delta: Vec<DeltaItem>,

    /// used to label items in a [`VariationRef`] package
    ///
    /// This field is explicitly a bitflag
    pub observation: Option<VariationInstObservation>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum RSiteRef {
    /// may be unparsable
    Str(String),

    /// pointer to a restriction site database
    DB(DbTag),
}

#[allow(non_camel_case_types)]
#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Represents RNA feature types
pub enum RnaRefType {
    Unknown,
    PreMsg,
    mRNA,
    tRNA,
    rRNA,

    /// ### Original Comment:
    ///     will become ncRNA, with RNAGen.class = snRNA
    snRNA,

    /// ### Original Comment:
    ///     will become ncRNA, with RNAGen.class = snRNA
    scRNA,

    /// ### Original Comment:
    ///     will become ncRNA, with RNAGen.class = snRNA
    snoRNA,

    /// non-coding RNA; subsumes `snRNA`, `scRNA` and `snoRNA`
    ncRNA,
    tmRNA,
    MiscRNA,
    Other = 255,
}

#[allow(non_camel_case_types)]
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum RnaRefExt {
    /// for naming "other" type
    Name(String),

    /// for tRNA's
    tRNA(TRnaExt),

    /// generic fields for `ncRNA`, `tmRNA` and `miscRNA`
    Gen(RnaGen),
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct RnaRef {
    #[serde(rename = "type")]
    pub r#type: RnaRefType,
    pub pseudo: Option<bool>,
    pub ext: Option<RnaRefExt>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum TRnaExtAa {
    IUPACAa(u64),
    NCBIEaa(u64),
    NCBI8aa(u64),
    NCBIStdAa(u64),
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
/// tRNA feature extensions
pub struct TRnaExt {
    /// transported amino acid
    pub aa: TRnaExtAa,

    /// codon(s) as in [`GeneticCode`]
    pub codon: Option<Vec<u64>>,

    /// location of anticodon
    pub anticodon: Option<SeqLoc>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct RnaGen {
    /// for ncRNA's, the class of non-coding RNA
    ///
    /// examples: antisense RNA, guide RNA, snRNA
    pub class: Option<String>,

    pub product: Option<String>,

    /// eg: `tag_peptide` qualifier for tmRNA's
    pub quals: Option<RnaQualSet>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct RnaQual {
    pub qual: String,
    pub val: String,
}

pub type RnaQualSet = Vec<RnaQual>;

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
#[serde(rename_all = "kebab-case")]
pub struct GeneRef {
    /// official gene symbol
    pub locus: Option<String>,

    /// official allele designation
    pub allele: Option<String>,

    /// descriptive name
    pub desc: Option<String>,

    /// descriptive map location
    pub maploc: Option<String>,

    /// pseudogene
    pub pseudo: bool,

    /// ids in other dbases
    pub db: Option<Vec<DbTag>>,

    /// synonyms for locus
    pub syn: Option<Vec<String>>,

    /// systematic gene name (eg: MI0001, ORF0069)
    pub locus_tag: Option<String>,

    pub formal_name: Option<GeneNomenclature>,
}

impl XmlNode for GeneRef {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Gene-ref")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        let mut gene = Self::default();

        // field tags
        let locus_tag = BytesStart::new("Gene-ref_locus");
        let allele_tag = BytesStart::new("Gene-ref_allele");
        let desc_tag = BytesStart::new("Gene-ref_desc");
        let maploc_tag = BytesStart::new("Gene-ref_maploc");
        let pseudo_tag = BytesStart::new("Gene-ref_pseudo");
        let db_tag = BytesStart::new("Gene-ref_db");
        let syn_tag = BytesStart::new("Gene-ref_syn");
        let locus_tag_tag = BytesStart::new("Gene-ref_locus-tag");
        let form_name_tag = BytesStart::new("Gene-ref_formal-name");

        let forbidden = [
            pseudo_tag,
            syn_tag,
            form_name_tag,
        ];
        let forbidden = UnexpectedTags(&forbidden);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == locus_tag.name() {
                        gene.locus = read_string(reader);
                    } else if name == allele_tag.name() {
                        gene.allele = read_string(reader);
                    } else if name == desc_tag.name() {
                        gene.desc = read_string(reader);
                    } else if name == maploc_tag.name() {
                        gene.maploc = read_string(reader);
                    } else if name == db_tag.name() {
                        gene.db = Some(read_vec_node(reader, db_tag.to_end()));
                    } else if name == locus_tag_tag.name() {
                        gene.locus_tag = read_string(reader);
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return gene.into()
                    }
                }
                _ => ()
            }
        }
    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum GeneNomenclatureStatus {
    Unknown,
    Official,
    Interim,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct GeneNomenclature {
    pub status: GeneNomenclatureStatus,
    pub symbol: Option<String>,
    pub name: Option<String>,
    pub source: Option<DbTag>,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
/// Reference to an organism
///
/// Defines only the organism. Lower levels of detail for biological molecules
/// are provided by [`BioSource`]
pub struct OrgRef {
    /// preferred formal name
    pub taxname: Option<String>,

    /// common name
    pub common: Option<String>,

    /// unstructured modifiers
    pub r#mod: Option<Vec<String>>,

    /// ids in taxonomic or culture databases
    pub db: Option<Vec<DbTag>>,

    /// synonyms for `taxname` or common
    pub syn: Option<Vec<String>>,

    pub orgname: Option<OrgName>,
}

impl XmlNode for OrgRef {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Org-ref")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> {
        let mut org_ref = OrgRef::default();

        let taxname_element = BytesStart::new("Org-ref_taxname");
        let db_element = BytesStart::new("Org-ref_db");
        let orgname_element = BytesStart::new("Org-ref_orgname");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == taxname_element.name() {
                        org_ref.taxname = read_string(reader);
                    } else if name == orgname_element.name() {
                        org_ref.orgname = read_node(reader);
                    } else if name == db_element.name() {
                        org_ref.db = Some(read_vec_node(reader, db_element.to_end()))
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return org_ref.into();
                    }
                }
                _ => (),
            }
        }
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum OrgNameChoice {
    /// genus/species type name
    Binomial(BinomialOrgName),

    /// virus names are different
    Virus(String),

    /// hybrid between organisms
    Hybrid(MultiOrgName),

    /// some hybrids have genus x species name
    NamedHybrid(BinomialOrgName),

    /// when genus not known
    Partial(PartialOrgName),
}

impl XmlNode for OrgNameChoice {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("OrgName_name")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self>
    where
        Self: Sized,
    {
        // variants
        let binomial_element = BytesStart::new("OrgName_name_binomial");

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == binomial_element.name() {
                        return Self::Binomial(read_node(reader).unwrap()).into();
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return None;
                    }
                }
                _ => (),
            }
        }
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct OrgName {
    pub name: Option<OrgNameChoice>,

    /// attribution of name
    pub attrib: Option<String>,

    #[serde(rename = "mod")]
    pub r#mod: Option<Vec<OrgMod>>,

    /// lineage with semicolon separators
    pub lineage: Option<String>,

    /// genetic code
    ///
    /// See Also:
    /// - [`CdRegion`]
    pub gcode: Option<u64>,

    /// mitochondrial genetic code
    pub mgcode: Option<u64>,

    /// GenBank division code
    pub div: Option<String>,

    /// plastid genetic code
    pub pgcode: Option<u64>,
}

impl XmlNode for OrgName {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("OrgName")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self>
    where
        Self: Sized,
    {
        let mut org_name = OrgName::default();

        let name_element = BytesStart::new("OrgName_name");
        let attrib_element = BytesStart::new("OrgName_attrib");
        let mod_element = BytesStart::new("OrgName_mod");
        let lineage_element = BytesStart::new("OrgName_lineage");
        let gcode_element = BytesStart::new("OrgName_gcode");
        let div_element = BytesStart::new("OrgName_div");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == div_element.name() {
                        org_name.div = read_string(reader);
                    } else if name == attrib_element.name() {
                        org_name.attrib = read_string(reader);
                    } else if name == lineage_element.name() {
                        org_name.lineage = read_string(reader);
                    } else if name == gcode_element.name() {
                        org_name.gcode = read_int(reader);
                    } else if name == name_element.name() {
                        org_name.name = read_node(reader);
                    } else if name == mod_element.name() {
                        org_name.r#mod = Some(read_vec_node(reader, mod_element.to_end()));
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return org_name.into();
                    }
                }
                _ => (),
            }
        }
    }
}

enum_from_primitive! {
    #[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
    #[repr(u8)]
    pub enum OrgModSubType {
        Strain = 2,

        SubStrain,

        Type,

        SubType,

        Variety,
        Serotype,
        Serogroup,
        Serovar,
        Cultivar,
        Pathovar,
        Chemovar,
        Biovar,
        Biotype,
        Group,
        SubGroup,
        Isolate,
        Common,
        Acronym,

        /// chromosome dosage of hybrid
        Dosage,

        /// natural host of this specimen
        NatHost,

        SubSpecies,
        SpecimenVoucher,
        Authority,
        Forma,
        FormaSpecialis,
        Ecotype,
        Synonym,
        Anamorph,
        Breed,

        /// used by taxonomy database
        GbAcronym,

        /// used by taxonomy database
        GbAnamorph,

        /// used by taxonomy database
        GbSynonym,

        CultureCollection,
        BioMaterial,
        MetagenomeSource,
        TypeMaterial,

        /// code of nomenclature in subname (B,P,V,Z or combination)
        Nomenclature,

        OldLineage = 253,
        OldName = 254,
        Other = 255,
    }
}

/// default not defined in original spec
impl Default for OrgModSubType {
    fn default() -> Self {
        Self::Other
    }
}

impl XmlNode for OrgModSubType {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("OrgMod_subtype")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self>
    where
        Self: Sized,
    {
        Self::from_u8(read_int(reader).unwrap())
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct OrgMod {
    pub subtype: OrgModSubType,
    pub subname: String,

    /// attribution/source of name
    pub attrib: Option<String>,
}

impl XmlNode for OrgMod {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("OrgMod")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self>
    where
        Self: Sized,
    {
        let mut r#mod = Self::default();

        let subtype_element = BytesStart::new("OrgMod_subtype");
        let subname_element = BytesStart::new("OrgMod_subname");
        let attrib_element = BytesStart::new("OrgMod_attrib");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == subtype_element.name() {
                        r#mod.subtype = read_node(reader).unwrap();
                    } else if name == subname_element.name() {
                        r#mod.subname = read_string(reader).unwrap();
                    } else if name == attrib_element.name() {
                        r#mod.attrib = read_string(reader);
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return r#mod.into();
                    }
                }
                _ => (),
            }
        }
    }
}
impl XmlVecNode for OrgMod {}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct BinomialOrgName {
    /// required
    pub genus: String,

    /// species required if subspecies used
    pub species: Option<String>,
    pub subspecies: Option<String>,
}

impl XmlNode for BinomialOrgName {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("BinomialOrgName")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self>
    where
        Self: Sized,
    {
        let mut binomial = BinomialOrgName::default();

        let genus_element = BytesStart::new("BinomialOrgName_genus");
        let species_element = BytesStart::new("BinomialOrgName_species");
        let subspecies_element = BytesStart::new("BinomialOrgName_subspecies");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == genus_element.name() {
                        binomial.genus = read_string(reader).unwrap();
                    } else if name == species_element.name() {
                        binomial.species = read_string(reader);
                    } else if name == subspecies_element.name() {
                        binomial.subspecies = read_string(reader);
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return binomial.into();
                    }
                }
                _ => (),
            }
        }
    }
}

/// the first value will be used to assign division
pub type MultiOrgName = Vec<OrgName>;

/// used when genus not known
pub type PartialOrgName = Vec<TaxElement>;

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum TaxElementFixedLevel {
    /// level must be set in string
    Other,

    Family,
    Order,
    Class,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct TaxElement {
    pub fixed_level: TaxElementFixedLevel,
    pub level: Option<String>,
    pub name: String,
}

enum_from_primitive! {
    #[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
    #[repr(u8)]
    /// biological context from which a molecule came from
    pub enum BioSourceGenome {
        #[default]
        Unknown,
        Genomic,
        Chloroplast,
        Chromoplast,
        Kinetoplast,
        Mitochondrion,
        Plastid,
        Macronuclear,
        Extrachrom,
        Plasmid,
        Transposon,
        InsertionSeq,
        Cyanelle,
        Proviral,
        Virion,
        Nucleomorph,
        Apicoplast,
        Leucoplast,
        Proplastid,
        EndogenousVirus,
        Hydrogenosome,
        Chromosome,
        PlasmidInMitochondrion,
        PlasmidInPlastid,
    }
}

impl XmlNode for BioSourceGenome {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("BioSource_genome")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> {
        Self::from_u8(read_int(reader).unwrap())
    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
#[repr(u8)]
pub enum BioSourceOrigin {
    #[default]
    Unknown,

    /// normal biological entity
    Natural,

    /// naturally occurring mutant
    NatMut,

    /// artificially mutagenized
    Mut,

    /// artificially engineered
    Artificial,

    /// purely synthetic
    Synthetic,

    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
#[serde(rename_all = "kebab-case")]
pub struct BioSource {
    /// biological context
    pub genome: BioSourceGenome,

    pub origin: BioSourceOrigin,
    pub org: OrgRef,
    pub subtype: Option<Vec<SubSource>>,

    /// to distinguish biological focus
    ///
    /// # Implementation Notes
    ///
    /// `Option<()>` has been chosen to conform to ASN.1 spec
    pub is_focus: Option<()>,
    pub pcr_primers: Option<PCRReationSet>,
}

impl XmlNode for BioSource {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("BioSource")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> {
        let mut source = Self::default();

        let genome_element = BytesStart::new("BioSource_genome");
        let _origin_element = BytesStart::new("BioSource_origin");
        let org_element = BytesStart::new("BioSource_org");
        let subtype_element = BytesStart::new("BioSource_subtype");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == genome_element.name() {
                        source.genome = read_node(reader).unwrap();
                    } else if name == org_element.name() {
                        source.org = read_node(reader).unwrap();
                    } else if name == subtype_element.name() {
                        source.subtype = Some(read_vec_node(reader, subtype_element.to_end()))
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if e.name() == Self::start_bytes().to_end().name() {
                        return source.into();
                    }
                }
                _ => (),
            }
        }
    }
}

pub type PCRReationSet = Vec<PCRReaction>;
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct PCRReaction {
    pub forward: Option<PCRPrimerSet>,
    pub reverse: Option<PCRPrimerSet>,
}

pub type PCRPrimerSet = Vec<PCRPrimer>;
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct PCRPrimer {
    pub seq: Option<PCRPrimerSeq>,
    pub name: Option<PCRPrimerName>,
}
pub type PCRPrimerSeq = String;
pub type PCRPrimerName = String;

enum_from_primitive! {
    #[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
    #[repr(u8)]
    pub enum SubSourceSubType {
        Chromosome = 1,
        Map,
        Clone,
        Subclone,
        Haplotype,
        Genotype,
        Sex,
        CellLine,
        CellType,
        TissueType,
        CloneLib,
        DevStage,
        Frequency,
        Germline,
        Rearranged,
        LabHost,
        PopVariant,
        TissueLib,
        PlasmidName,
        TransposonName,
        InsertionSeqName,
        PlastidName,
        Country,
        Segment,
        EndogenousVirusName,
        Transgenic,
        EnvironmentalSample,
        IsolationSource,

        /// +/- decimal degrees
        LatLon,

        /// DD-MMM-YYYY format
        CollectionDate,

        /// name of person who collected sample
        CollectedBy,

        /// name of person who identified sample
        IdentifiedBy,

        /// sequence (possibly more than one; semicolon-separated)
        FwdPrimerSeq,

        /// sequence (possibly more than one; semicolon-separated)
        RevPrimerSeq,

        FwdPrimerName,
        RevPrimerName,
        Metagenomic,
        MatingType,
        LinkageGroup,
        Haplogroup,
        WholeReplicon,
        Phenotype,
        Altitude,
        Other = 255,
    }
}

/// default not in original spec
impl Default for SubSourceSubType {
    fn default() -> Self {
        Self::Other
    }
}

impl XmlNode for SubSourceSubType {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("SubSource_subtype")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> {
        Self::from_u8(read_int(reader).unwrap())
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct SubSource {
    pub subtype: SubSourceSubType,
    pub name: String,

    /// attribution/source of this name
    pub attrib: Option<String>,
}

impl XmlNode for SubSource {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("SubSource")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> {
        let mut source = Self::default();

        let subtype_element = BytesStart::new("SubSource_subtype");
        let name_element = BytesStart::new("SubSource_name");
        let attrib_element = BytesStart::new("SubSource_attrib");

        let forbidden = UnexpectedTags(&[]);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let qname = e.name();

                    if qname == subtype_element.name() {
                        source.subtype = read_node(reader).unwrap();
                    } else if qname == name_element.name() {
                        source.name = read_string(reader).unwrap();
                    } else if qname == attrib_element.name() {
                        source.attrib = read_string(reader);
                    } else if qname != Self::start_bytes().name() {
                        forbidden.check(&qname);
                    }
                }
                Event::End(e) => {
                    if e.name() == Self::start_bytes().to_end().name() {
                        return source.into();
                    }
                }
                _ => (),
            }
        }
    }
}
impl XmlVecNode for SubSource {}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
#[repr(u8)]
pub enum ProtRefProcessingStatus {
    #[default]
    NotSet,

    PreProtein,
    Mature,
    SignalPeptide,
    TransitPeptide,
    ProPeptide,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
#[serde(rename_all = "kebab-case")]
/// Reference to a protein name
pub struct ProtRef {
    /// protein name
    pub name: Option<Vec<String>>,

    /// description (instead of name)
    pub desc: Option<String>,

    /// E.C. number(s)
    pub ec: Option<Vec<String>>,

    /// activities
    pub activity: Option<Vec<String>>,

    /// id's in other dbases
    pub db: Option<Vec<DbTag>>,

    /// processing status
    pub processed: ProtRefProcessingStatus,
}

impl XmlNode for ProtRef {
    fn start_bytes() -> BytesStart<'static> {
        BytesStart::new("Prot-ref")
    }

    fn from_reader(reader: &mut Reader<&[u8]>) -> Option<Self> where Self: Sized {
        let mut prot = Self::default();

        // field tags
        let name_tag = BytesStart::new("Prot-ref_name");
        let desc_tag = BytesStart::new("Prot-ref_desc");
        let ec_tag = BytesStart::new("Prot-ref_ec");
        let activity_tag = BytesStart::new("Prot-ref_activity");
        let db_tag = BytesStart::new("Prot-ref_db");
        let processed_tag = BytesStart::new("Prot-ref_processed");

        // attributes that have not been implemented yet
        let forbidden = [processed_tag];
        let forbidden = UnexpectedTags(&forbidden);

        loop {
            match reader.read_event().unwrap() {
                Event::Start(e) => {
                    let name = e.name();

                    if name == name_tag.name() {
                        prot.name = read_vec_str_unchecked(reader, &name_tag.to_end()).into();
                    } else if name == desc_tag.name() {
                        prot.desc = read_string(reader);
                    } else if name == ec_tag.name() {
                        prot.ec = read_vec_str_unchecked(reader, &ec_tag.to_end()).into();
                    } else if name == activity_tag.name() {
                        prot.activity = read_vec_str_unchecked(reader, &activity_tag.to_end()).into();
                    } else if name == db_tag.name() {
                        prot.db = read_vec_node(reader, db_tag.to_end()).into();
                    } else if name != Self::start_bytes().name() {
                        forbidden.check(&name);
                    }
                }
                Event::End(e) => {
                    if Self::is_end(&e) {
                        return prot.into()
                    }
                }
                _ => {}
            }
        }

    }
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum TxSystem {
    Unknown,

    /// eukaryotic Pol I
    Pol1,

    /// eukaryotic Pol II
    Pol2,

    /// eukaryotic Pol III
    Pol3,

    Bacterial,
    Viral,

    /// RNA replicase
    Rna,

    Organelle,
    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
/// Represents type of transcription initiation site (TIS)
pub enum InitType {
    Unknown,

    /// transcript initiated from a single sites
    Single,

    /// transcript initiated from multiple sites
    Multiple,

    /// transcript is initiated from a specific region
    Region,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
/// Transcription Initiation Site feature data block
pub struct TxInit {
    /// descriptive name of initiation site
    pub name: String,

    /// synonyms
    pub syn: Option<Vec<String>>,

    /// gene(s) transcribed
    pub gene: Option<Vec<GeneRef>>,

    /// protein(s) produced
    pub protein: Option<Vec<ProtRef>>,

    /// rna(s) produced
    pub rna: Option<Vec<String>>,

    /// tissue/time of expression
    pub expression: Option<String>,

    /// transcription apparatus used at this site
    pub txsystem: TxSystem,

    /// modifiers to [`TxSystem`]
    pub txdescr: Option<String>,

    /// organism supplying transcription apparatus
    pub txorg: Option<OrgRef>,

    /// mapping precise or approx
    pub mapping_precise: bool, // TODO: default false

    /// does [`SeqLoc`] reflect mapping
    pub location_accurate: bool, // TODO: default false

    pub inittype: InitType,
    pub evidence: Option<Vec<TxEvidence>>,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum TxEvidenceExpCode {
    Unknown,

    /// direct RNA sequencing
    RnaSeq,

    /// RNA length measurement
    RnaSize,

    /// nuclease protection mapping with homologous sequence ladder
    NpMap,

    /// nuclease protected fragment length measurement
    NpSize,

    /// di-deoxy RNA sequencing
    PeSeq,

    /// full-length cDNA sequencing
    CDnaSeq,

    /// primer extension mapping with homologous sequence ladder
    PeMap,

    /// primer extension product length measurement
    PeSize,

    /// full-length processed pseudogene sequencing
    PseudoSeq,

    /// length measurement of a reverse direction primer-extension product
    /// (blocked by RNA 5' end) by comparison with homologous sequence
    /// ladder (J. Mol. Biol. 199, 587)
    RevPeMap,

    Other = 255,
}

#[derive(Clone, Serialize_repr, Deserialize_repr, PartialEq, Debug, Default)]
#[repr(u8)]
pub enum TxEvidenceExpressionSystem {
    Unknown,
    #[default]
    Physiological,
    InVitro,
    Oocyte,
    Transfection,
    Transgenic,
    Other = 255,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct TxEvidence {
    pub exp_code: TxEvidenceExpCode,
    pub expression_system: TxEvidenceExpressionSystem,
    pub low_prec_data: bool, // TODO: default false
    pub from_homolog: bool,  // TODO: default false
}