Skip to content

API Reference

A universal cycling protocol which can be converted to different formats.

Create a Protocol object directly, or create from a dict or JSON file.

Convert to different formats e.g. .to_neware_xml() or to_biologic_mps().

ConstantCurrent

Bases: Step

Constant current step.

At least one of rate_C or current_mA must be set. If rate_C is used, a sample capacity must be set in the Protocol, and it will take priority over current_mA.

The termination ('until') conditions are OR conditions, the step will end when any one of these is met.

Attributes:

Name Type Description
rate_C float | None

(optional) The current applied in C-rate units (i.e. mA per mAh).

current_mA float | None

(optional) The current applied in mA.

until_time_s float | None

Duration of step in seconds.

until_voltage_V float | None

End step when this voltage in V is reached.

Source code in aurora_unicycler\unicycler.py
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
class ConstantCurrent(Step):
    """Constant current step.

    At least one of `rate_C` or `current_mA` must be set. If `rate_C` is used, a
    sample capacity must be set in the Protocol, and it will take priority over
    `current_mA`.

    The termination ('until') conditions are OR conditions, the step will end
    when any one of these is met.

    Attributes:
        rate_C: (optional) The current applied in C-rate units (i.e. mA per mAh).
        current_mA: (optional) The current applied in mA.
        until_time_s: Duration of step in seconds.
        until_voltage_V: End step when this voltage in V is reached.

    """

    step: Literal["constant_current"] = Field(default="constant_current", frozen=True)
    rate_C: float | None = None
    current_mA: float | None = None
    until_time_s: float | None = None
    until_voltage_V: float | None = None

    @field_validator("rate_C", mode="before")
    @classmethod
    def _parse_c_rate(cls, v: float | str) -> float | None:
        """C-rate can be a string e.g. "C/2"."""
        return _coerce_c_rate(v)

    @field_validator("current_mA", "until_time_s", "until_voltage_V", mode="before")
    @classmethod
    def _allow_empty_string(cls, v: float | str) -> float | None:
        """Empty string is interpreted as None."""
        return _empty_string_is_none(v)

    @model_validator(mode="after")
    def _ensure_rate_or_current(self) -> Self:
        """Ensure at least one of rate_C or current_mA is set."""
        has_rate_C = self.rate_C is not None and self.rate_C != 0
        has_current_mA = self.current_mA is not None and self.current_mA != 0
        if not (has_rate_C or has_current_mA):
            msg = "Either rate_C or current_mA must be set and non-zero."
            raise ValueError(msg)
        return self

    @model_validator(mode="after")
    def _ensure_stop_condition(self) -> Self:
        """Ensure at least one stop condition is set."""
        has_time_s = self.until_time_s is not None and self.until_time_s != 0
        has_voltage_V = self.until_voltage_V is not None and self.until_voltage_V != 0
        if not (has_time_s or has_voltage_V):
            msg = "Either until_time_s or until_voltage_V must be set and non-zero."
            raise ValueError(msg)
        return self

ConstantVoltage

Bases: Step

Constant voltage step.

The termination ('until') conditions are OR conditions, the step will end when any one of these is met. If both until_rate_C and until_current_mA are set, C-rate will take priority.

Note that in most cyclers, a voltage is not applied directly, instead the current is adjusted to achieve a certain voltage.

Attributes:

Name Type Description
voltage_V float

The voltage applied in V.

until_time_s float | None

Duration of step in seconds.

until_rate_C float | None

End step when this C-rate (i.e. mA per mAh) is reached.

until_current_mA float | None

End step when this current in mA is reached.

Source code in aurora_unicycler\unicycler.py
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
class ConstantVoltage(Step):
    """Constant voltage step.

    The termination ('until') conditions are OR conditions, the step will end
    when any one of these is met. If both `until_rate_C` and `until_current_mA`
    are set, C-rate will take priority.

    Note that in most cyclers, a voltage is not applied directly, instead the
    current is adjusted to achieve a certain voltage.

    Attributes:
        voltage_V: The voltage applied in V.
        until_time_s: Duration of step in seconds.
        until_rate_C: End step when this C-rate (i.e. mA per mAh) is reached.
        until_current_mA: End step when this current in mA is reached.

    """

    step: Literal["constant_voltage"] = Field(default="constant_voltage", frozen=True)
    voltage_V: float
    until_time_s: float | None = None
    until_rate_C: float | None = None
    until_current_mA: float | None = None

    @field_validator("until_rate_C", mode="before")
    @classmethod
    def _parse_c_rate(cls, v: float | str) -> float | None:
        """C-rate can be a string e.g. "C/2"."""
        return _coerce_c_rate(v)

    @field_validator("voltage_V", "until_time_s", "until_current_mA", mode="before")
    @classmethod
    def _allow_empty_string(cls, v: float | str) -> float | None:
        """Empty string is interpreted as None."""
        return _empty_string_is_none(v)

    @model_validator(mode="after")
    def _check_stop_condition(self) -> Self:
        """Ensure at least one of until_rate_C or until_current_mA is set."""
        has_time_s = self.until_time_s is not None and self.until_time_s != 0
        has_rate_C = self.until_rate_C is not None and self.until_rate_C != 0
        has_current_mA = self.until_current_mA is not None and self.until_current_mA != 0
        if not (has_time_s or has_rate_C or has_current_mA):
            msg = "Either until_time_s, until_rate_C, or until_current_mA must be set and non-zero."
            raise ValueError(msg)
        return self

ImpedanceSpectroscopy

Bases: Step

Electrochemical Impedance Spectroscopy (EIS) step.

Only one of amplitude_V (PEIS) or amplitude_mA (GEIS) can be set.

Attributes:

Name Type Description
amplitude_V float | None

(optional) Oscillation amplitude in V.

amplitude_mA float | None

(optional) Oscillation amplitude in mA.

start_frequency_Hz float

Beginning frequency in Hz.

end_frequency_Hz float

End frequency in Hz.

points_per_decade int

How many points to measure per decade, i.e. power of 10.

measures_per_point int

How many measurements to average per point.

drift_correction bool | None

Corrects for drift in the system - requires twice as many measurements. Compensates measured current/voltage at frequency f_m with pointsf_m-1 and f_m+1 using the formula for PEIS ∆I(f_m) = I(f_m) + (I(f_m+1) - I(f_m-1))/2, (and similar for V in GEIS). Operates on both real and imaginary parts.

Source code in aurora_unicycler\unicycler.py
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
class ImpedanceSpectroscopy(Step):
    """Electrochemical Impedance Spectroscopy (EIS) step.

    Only one of `amplitude_V` (PEIS) or `amplitude_mA` (GEIS) can be set.

    Attributes:
        amplitude_V: (optional) Oscillation amplitude in V.
        amplitude_mA: (optional) Oscillation amplitude in mA.
        start_frequency_Hz: Beginning frequency in Hz.
        end_frequency_Hz: End frequency in Hz.
        points_per_decade: How many points to measure per decade, i.e. power of 10.
        measures_per_point: How many measurements to average per point.
        drift_correction: Corrects for drift in the system - requires twice as
            many measurements. Compensates measured current/voltage at frequency
            `f_m` with points`f_m-1` and `f_m+1` using the formula for PEIS
            `∆I(f_m) = I(f_m) + (I(f_m+1) - I(f_m-1))/2`, (and similar for V in
            GEIS). Operates on both real and imaginary parts.

    """

    step: Literal["impedance_spectroscopy"] = Field(default="impedance_spectroscopy", frozen=True)
    amplitude_V: float | None = None
    amplitude_mA: float | None = None
    start_frequency_Hz: float = Field(ge=1e-5, le=1e5, description="Start frequency in Hz")
    end_frequency_Hz: float = Field(ge=1e-5, le=1e5, description="End frequency in Hz")
    points_per_decade: int = Field(gt=0, default=10)
    measures_per_point: int = Field(gt=0, default=1)
    drift_correction: bool | None = Field(default=False, description="Apply drift correction")
    model_config = ConfigDict(extra="forbid")

    @field_validator("amplitude_V", "amplitude_mA", mode="before")
    @classmethod
    def _allow_empty_string(cls, v: float | str) -> float | None:
        """Empty string is interpreted as None."""
        return _empty_string_is_none(v)

    @model_validator(mode="after")
    def _validate_amplitude(self) -> Self:
        """Cannot set both amplitude_V and amplitude_mA."""
        if self.amplitude_V is not None and self.amplitude_mA is not None:
            msg = "Cannot set both amplitude_V and amplitude_mA."
            raise ValueError(msg)
        if self.amplitude_V is None and self.amplitude_mA is None:
            msg = "Either amplitude_V or amplitude_mA must be set."
            raise ValueError(msg)
        return self

Loop

Bases: Step

Loop step.

Supports both looping to a tag or the step number (1-indexed). It is recommened to use tags to avoid potential errors with indexing or when adding/removing steps.

Internally, tags are converted to indexes with the correct indexing when sending to cyclers.

Attributes:

Name Type Description
loop_to Annotated[int | str, Field()]

The tag or step number (1-indexed) to loop back to.

cycle_count int

How many times to loop. This is the TOTAL number of cycles. Different cyclers define this differently. Here, a cycle_count of 3 means 3 cycles in total will be performed.

Source code in aurora_unicycler\unicycler.py
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
class Loop(Step):
    """Loop step.

    Supports both looping to a tag or the step number (1-indexed). It is
    recommened to use tags to avoid potential errors with indexing or when
    adding/removing steps.

    Internally, tags are converted to indexes with the correct indexing when
    sending to cyclers.

    Attributes:
        loop_to: The tag or step number (1-indexed) to loop back to.
        cycle_count: How many times to loop. This is the TOTAL number of cycles.
            Different cyclers define this differently. Here, a cycle_count of 3
            means 3 cycles in total will be performed.

    """

    step: Literal["loop"] = Field(default="loop", frozen=True)
    loop_to: Annotated[int | str, Field()] = Field(default=1)
    cycle_count: int = Field(gt=0)
    model_config = ConfigDict(extra="forbid")

    @field_validator("loop_to")
    @classmethod
    def _validate_loop_to(cls, v: int | str) -> int | str:
        """Ensure loop_to is a positive integer or a string."""
        if isinstance(v, int) and v <= 0:
            msg = "Start step must be positive integer or a string"
            raise ValueError(msg)
        if isinstance(v, str) and v.strip() == "":
            msg = "Start step cannot be empty"
            raise ValueError(msg)
        return v

OpenCircuitVoltage

Bases: Step

Open circuit voltage step.

Attributes:

Name Type Description
until_time_s float

Duration of step in seconds.

Source code in aurora_unicycler\unicycler.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class OpenCircuitVoltage(Step):
    """Open circuit voltage step.

    Attributes:
        until_time_s: Duration of step in seconds.

    """

    step: Literal["open_circuit_voltage"] = Field(default="open_circuit_voltage", frozen=True)
    until_time_s: float = Field(gt=0)

    @field_validator("until_time_s", mode="before")
    @classmethod
    def _allow_empty_string(cls, v: float | str) -> float | None:
        """Empty string is interpreted as None."""
        return _empty_string_is_none(v)

Protocol

Bases: BaseModel

Protocol model which can be converted to various formats.

Source code in aurora_unicycler\unicycler.py
 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
class Protocol(BaseModel):
    """Protocol model which can be converted to various formats."""

    unicycler: UnicyclerParams = Field(default_factory=UnicyclerParams)
    sample: SampleParams = Field(default_factory=SampleParams)
    record: RecordParams
    safety: SafetyParams = Field(default_factory=SafetyParams)
    method: Sequence[AnyTechnique] = Field(min_length=1)  # Ensure at least one step

    model_config = ConfigDict(extra="forbid")

    # Only checked when outputting
    def _validate_capacity_c_rates(self) -> None:
        """Ensure if using C-rate steps, a capacity is set."""
        if not self.sample.capacity_mAh and any(
            getattr(s, "rate_C", None) or getattr(s, "until_rate_C", None) for s in self.method
        ):
            msg = "Sample capacity must be set if using C-rate steps."
            raise ValueError(msg)

    @model_validator(mode="before")
    @classmethod
    def _check_no_blank_steps(cls, values: dict[str, Any]) -> dict[str, Any]:
        """Check if any 'blank' steps are in the method before trying to parse them."""
        steps = values.get("method", [])
        for i, step in enumerate(steps):
            if (isinstance(step, Step) and not hasattr(step, "step")) or (
                isinstance(step, dict) and ("step" not in step or not step["step"])
            ):
                msg = f"Step at index {i} is incomplete, needs a 'step' type."
                raise ValueError(msg)
        return values

    @model_validator(mode="after")
    def _validate_loops_and_tags(self) -> Self:
        """Ensure that if a loop uses a string, it is a valid tag."""
        loop_tags = {
            i: step.loop_to
            for i, step in enumerate(self.method)
            if isinstance(step, Loop) and isinstance(step.loop_to, str)
        }
        loop_idx = {
            i: step.loop_to
            for i, step in enumerate(self.method)
            if isinstance(step, Loop) and isinstance(step.loop_to, int)
        }
        tags = {i: step.tag for i, step in enumerate(self.method) if isinstance(step, Tag)}

        # Cannot have duplicate tags
        tag_list = list(tags.values())
        if len(tag_list) != len(set(tag_list)):
            duplicate_tags = {"'" + tag + "'" for tag in tag_list if tag_list.count(tag) > 1}
            msg = "Duplicate tags: " + ", ".join(duplicate_tags)
            raise ValueError(msg)

        tags_rev = {v: k for k, v in tags.items()}  # to map from tag to index

        # indexed loops cannot go on itself or forwards
        for i, loop_start in loop_idx.items():
            if loop_start >= i:
                msg = f"Loop start index {loop_start} cannot be on or after the loop index {i}."
                raise ValueError(msg)

        # Loops cannot go forwards to tags, or back one index to a tag
        for i, loop_tag in loop_tags.items():
            if loop_tag not in tags_rev:
                msg = f"Tag '{loop_tag}' is missing."
                raise ValueError(msg)
            # loop_tag is in tags, ensure i is larger than the tag index
            tag_i = tags_rev[loop_tag]
            if i <= tag_i:
                msg = f"Loops must go backwards, '{loop_tag}' goes forwards ({i}->{tag_i})."
                raise ValueError(msg)
            if i == tag_i + 1:
                msg = f"Loop '{loop_tag}' cannot start immediately after its tag."
                raise ValueError(msg)
        return self

    def _tag_to_indices(self) -> None:
        """Convert tag steps into indices to be processed later."""
        # In a protocol the steps are 1-indexed and tags should be ignored
        # The loop function should point to the index of the step AFTER the corresponding tag
        indices = [0] * len(self.method)
        tags = {}
        methods_to_remove = []
        j = 0
        for i, step in enumerate(self.method):
            if isinstance(step, Tag):
                indices[i] = j + 1
                tags[step.tag] = j + 1
                # drop this step from the list
                methods_to_remove.append(i)
            elif isinstance(step, Step):
                j += 1
                indices[i] = j
                if isinstance(step, Loop):
                    if isinstance(step.loop_to, str):
                        # If the start step is a string, it should be a tag, go to the tag index
                        try:
                            step.loop_to = tags[step.loop_to]
                        except KeyError as e:
                            msg = (
                                f"Loop step with tag {step.loop_to} "
                                "does not have a corresponding tag step."
                            )
                            raise ValueError(msg) from e
                    else:
                        # If the start step is an int, it should be the NEW index of the step
                        step.loop_to = indices[step.loop_to - 1]
            else:
                methods_to_remove.append(i)
        # Remove tags and other invalid steps
        self.method = [step for i, step in enumerate(self.method) if i not in methods_to_remove]

    def _check_for_intersecting_loops(self) -> None:
        """Check if a method has intersecting loops. Cannot contain Tags."""
        loops = []
        for i, step in enumerate(self.method):
            if isinstance(step, Loop):
                loops.append((int(step.loop_to), i + 1))
        loops.sort()

        for i in range(len(loops)):
            for j in range(i + 1, len(loops)):
                i_start, i_end = loops[i]
                j_start, j_end = loops[j]

                # If loop j starts after loop i ends, stop checking i
                if j_start > i_end:
                    break

                # Otherwise check if they intersect, completely nested is okay
                if (i_start < j_start and i_end < j_end) or (i_start > j_start and i_end > j_end):
                    msg = "Protocol has intersecting loops."
                    raise ValueError(msg)

    def to_neware_xml(
        self,
        save_path: Path | str | None = None,
        sample_name: str | None = None,
        capacity_mAh: float | None = None,
    ) -> str:
        """Convert the protocol to Neware XML format.

        Args:
            save_path: (optional) File path of where to save the xml file.
            sample_name: (optional) Override the protocol sample name. A sample
                name must be provided in this function. It is stored as the
                'barcode' of the Neware protocol.
            capacity_mAh: (optional) Override the protocol sample capacity.

        Returns:
            xml string representation of the protocol.

        """
        # Create and operate on a copy of the original object
        protocol = self.model_copy()

        # Allow overwriting name and capacity
        if sample_name:
            protocol.sample.name = sample_name
        if capacity_mAh:
            protocol.sample.capacity_mAh = capacity_mAh

        # Make sure sample name is set
        if not protocol.sample.name or protocol.sample.name == "$NAME":
            msg = (
                "If using blank sample name or $NAME placeholder, "
                "a sample name must be provided in this function."
            )
            raise ValueError(msg)

        # Make sure capacity is set if using C-rate steps
        protocol._validate_capacity_c_rates()

        # Remove tags and convert to indices
        protocol._tag_to_indices()
        protocol._check_for_intersecting_loops()

        # Create XML structure
        root = ET.Element("root")
        config = ET.SubElement(
            root,
            "config",
            type="Step File",
            version="17",
            client_version="BTS Client 8.0.0.478(2024.06.24)(R3)",
            date=datetime.now().strftime("%Y%m%d%H%M%S"),
            Guid=str(uuid.uuid4()),
        )
        head_info = ET.SubElement(config, "Head_Info")
        ET.SubElement(head_info, "Operate", Value="66")
        ET.SubElement(head_info, "Scale", Value="1")
        ET.SubElement(head_info, "Start_Step", Value="1", Hide_Ctrl_Step="0")
        ET.SubElement(head_info, "Creator", Value="aurora-unicycler")
        ET.SubElement(head_info, "Remark", Value=protocol.sample.name)
        # 103, non C-rate mode, seems to give more precise values vs 105
        ET.SubElement(head_info, "RateType", Value="103")
        if protocol.sample.capacity_mAh:
            ET.SubElement(head_info, "MultCap", Value=f"{protocol.sample.capacity_mAh * 3600:f}")

        whole_prt = ET.SubElement(config, "Whole_Prt")
        protect = ET.SubElement(whole_prt, "Protect")
        main_protect = ET.SubElement(protect, "Main")
        volt = ET.SubElement(main_protect, "Volt")
        if protocol.safety.max_voltage_V:
            ET.SubElement(volt, "Upper", Value=f"{protocol.safety.max_voltage_V * 10000:f}")
        if protocol.safety.min_voltage_V:
            ET.SubElement(volt, "Lower", Value=f"{protocol.safety.min_voltage_V * 10000:f}")
        curr = ET.SubElement(main_protect, "Curr")
        if protocol.safety.max_current_mA:
            ET.SubElement(curr, "Upper", Value=f"{protocol.safety.max_current_mA:f}")
        if protocol.safety.min_current_mA:
            ET.SubElement(curr, "Lower", Value=f"{protocol.safety.min_current_mA:f}")
        if protocol.safety.delay_s:
            ET.SubElement(main_protect, "Delay_Time", Value=f"{protocol.safety.delay_s * 1000:f}")
        cap = ET.SubElement(main_protect, "Cap")
        if protocol.safety.max_capacity_mAh:
            ET.SubElement(cap, "Upper", Value=f"{protocol.safety.max_capacity_mAh * 3600:f}")

        record = ET.SubElement(whole_prt, "Record")
        main_record = ET.SubElement(record, "Main")
        if protocol.record.time_s:
            ET.SubElement(main_record, "Time", Value=f"{protocol.record.time_s * 1000:f}")
        if protocol.record.voltage_V:
            ET.SubElement(main_record, "Volt", Value=f"{protocol.record.voltage_V * 10000:f}")
        if protocol.record.current_mA:
            ET.SubElement(main_record, "Curr", Value=f"{protocol.record.current_mA:f}")

        step_info = ET.SubElement(
            config, "Step_Info", Num=str(len(protocol.method) + 1)
        )  # +1 for end step

        def _step_to_element(
            step: AnyTechnique,
            step_num: int,
            parent: ET.Element,
            prev_step: AnyTechnique | None = None,
        ) -> None:
            """Create XML subelement from protocol technique."""
            match step:
                case ConstantCurrent():
                    if step.rate_C is not None and step.rate_C != 0:
                        step_type = "1" if step.rate_C > 0 else "2"
                    elif step.current_mA is not None and step.current_mA != 0:
                        step_type = "1" if step.current_mA > 0 else "2"
                    else:
                        msg = "Must have a current or C-rate"
                        raise ValueError(msg)

                    step_element = ET.SubElement(
                        parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type=step_type
                    )
                    limit = ET.SubElement(step_element, "Limit")
                    main = ET.SubElement(limit, "Main")
                    if step.rate_C is not None:
                        assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                        ET.SubElement(main, "Rate", Value=f"{abs(step.rate_C):f}")
                        ET.SubElement(
                            main,
                            "Curr",
                            Value=f"{abs(step.rate_C) * protocol.sample.capacity_mAh:f}",
                        )
                    elif step.current_mA is not None:
                        ET.SubElement(main, "Curr", Value=f"{abs(step.current_mA):f}")
                    if step.until_time_s is not None:
                        ET.SubElement(main, "Time", Value=f"{step.until_time_s * 1000:f}")
                    if step.until_voltage_V is not None:
                        ET.SubElement(main, "Stop_Volt", Value=f"{step.until_voltage_V * 10000:f}")

                case ConstantVoltage():
                    # Check if CV follows CC and has the same voltage cutoff
                    prev_rate_C = None
                    prev_current_mA = None
                    if (
                        isinstance(prev_step, ConstantCurrent)
                        and prev_step.until_voltage_V == step.voltage_V
                    ):
                        if prev_step.rate_C is not None:
                            assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                            prev_rate_C = abs(prev_step.rate_C)
                            prev_current_mA = abs(prev_step.rate_C) * protocol.sample.capacity_mAh
                        elif prev_step.current_mA is not None:
                            prev_current_mA = abs(prev_step.current_mA)
                    if step.until_rate_C is not None and step.until_rate_C != 0:
                        step_type = "3" if step.until_rate_C > 0 else "19"
                    elif step.until_current_mA is not None and step.until_current_mA != 0:
                        step_type = "3" if step.until_current_mA > 0 else "19"
                    else:
                        step_type = "3"  # If it can't be figured out, default to charge
                    step_element = ET.SubElement(
                        parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type=step_type
                    )
                    limit = ET.SubElement(step_element, "Limit")
                    main = ET.SubElement(limit, "Main")
                    ET.SubElement(main, "Volt", Value=f"{step.voltage_V * 10000:f}")
                    if step.until_time_s is not None:
                        ET.SubElement(main, "Time", Value=f"{step.until_time_s * 1000:f}")
                    if step.until_rate_C is not None:
                        assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                        ET.SubElement(main, "Stop_Rate", Value=f"{abs(step.until_rate_C):f}")
                        ET.SubElement(
                            main,
                            "Stop_Curr",
                            Value=f"{abs(step.until_rate_C) * protocol.sample.capacity_mAh:f}",
                        )
                    elif step.until_current_mA is not None:
                        ET.SubElement(main, "Stop_Curr", Value=f"{abs(step.until_current_mA):f}")
                    if prev_rate_C is not None:
                        assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                        ET.SubElement(main, "Rate", Value=f"{abs(prev_rate_C):f}")
                        ET.SubElement(
                            main,
                            "Curr",
                            Value=f"{abs(prev_rate_C) * protocol.sample.capacity_mAh:f}",
                        )
                    elif prev_current_mA is not None:
                        ET.SubElement(main, "Curr", Value=f"{abs(prev_current_mA):f}")

                case OpenCircuitVoltage():
                    step_element = ET.SubElement(
                        parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type="4"
                    )
                    limit = ET.SubElement(step_element, "Limit")
                    main = ET.SubElement(limit, "Main")
                    ET.SubElement(main, "Time", Value=f"{step.until_time_s * 1000:f}")

                case Loop():
                    step_element = ET.SubElement(
                        parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type="5"
                    )
                    limit = ET.SubElement(step_element, "Limit")
                    other = ET.SubElement(limit, "Other")
                    ET.SubElement(other, "Start_Step", Value=str(step.loop_to))
                    ET.SubElement(other, "Cycle_Count", Value=str(step.cycle_count))

                case _:
                    msg = f"to_neware_xml does not support step type: {step.step}"
                    raise TypeError(msg)

        for i, technique in enumerate(protocol.method):
            step_num = i + 1
            prev_step = protocol.method[i - 1] if i >= 1 else None
            _step_to_element(technique, step_num, step_info, prev_step)

        # Add an end step
        step_num = len(protocol.method) + 1
        ET.SubElement(step_info, f"Step{step_num}", Step_ID=str(step_num), Step_Type="6")

        smbus = ET.SubElement(config, "SMBUS")
        ET.SubElement(smbus, "SMBUS_Info", Num="0", AdjacentInterval="0")

        # Convert to string and prettify it
        pretty_xml_string = minidom.parseString(ET.tostring(root)).toprettyxml(indent="  ")  # noqa: S318
        if save_path:
            save_path = Path(save_path)
            save_path.parent.mkdir(parents=True, exist_ok=True)
            with save_path.open("w", encoding="utf-8") as f:
                f.write(pretty_xml_string)
        return pretty_xml_string

    def to_tomato_mpg2(
        self,
        save_path: Path | str | None = None,
        tomato_output: Path = Path("C:/tomato_data/"),
        sample_name: str | None = None,
        capacity_mAh: float | None = None,
    ) -> str:
        """Convert protocol to tomato 0.2.3 + MPG2 compatible JSON format.

        Args:
            save_path: (optional) File path of where to save the json file.
            tomato_output: (optional) Where to save the data from tomato.
            sample_name: (optional) Override the protocol sample name.
            capacity_mAh: (optional) Override the protocol sample capacity.

        Returns:
            json string representation of the protocol.

        """
        # Create and operate on a copy of the original object
        protocol = self.model_copy()

        # Allow overwriting name and capacity
        if sample_name:
            protocol.sample.name = sample_name
        if capacity_mAh:
            protocol.sample.capacity_mAh = capacity_mAh

        # Make sure sample name is set
        if not protocol.sample.name or protocol.sample.name == "$NAME":
            msg = (
                "If using blank sample name or $NAME placeholder, "
                "a sample name must be provided in this function."
            )
            raise ValueError(msg)

        # Make sure capacity is set if using C-rate steps
        protocol._validate_capacity_c_rates()

        # Remove tags and convert to indices
        protocol._tag_to_indices()
        protocol._check_for_intersecting_loops()

        # Create JSON structure
        tomato_dict: dict = {
            "version": "0.1",
            "sample": {},
            "method": [],
            "tomato": {
                "unlock_when_done": True,
                "verbosity": "DEBUG",
                "output": {
                    "path": str(tomato_output),
                    "prefix": protocol.sample.name,
                },
            },
        }
        # tomato -> MPG2 does not support safety parameters, they are set in the instrument
        tomato_dict["sample"]["name"] = protocol.sample.name
        tomato_dict["sample"]["capacity_mAh"] = protocol.sample.capacity_mAh
        for step in protocol.method:
            tomato_step: dict = {}
            tomato_step["device"] = "MPG2"
            tomato_step["technique"] = step.step
            if isinstance(step, (ConstantCurrent, ConstantVoltage, OpenCircuitVoltage)):
                if protocol.record.time_s:
                    tomato_step["measure_every_dt"] = protocol.record.time_s
                if protocol.record.current_mA:
                    tomato_step["measure_every_dI"] = protocol.record.current_mA
                if protocol.record.voltage_V:
                    tomato_step["measure_every_dE"] = protocol.record.voltage_V
                tomato_step["I_range"] = "10 mA"
                tomato_step["E_range"] = "+-5.0 V"

            match step:
                case OpenCircuitVoltage():
                    tomato_step["time"] = step.until_time_s

                case ConstantCurrent():
                    if step.rate_C:
                        if step.rate_C > 0:
                            charging = True
                            tomato_step["current"] = str(step.rate_C) + "C"
                        else:
                            charging = False
                            tomato_step["current"] = str(abs(step.rate_C)) + "D"
                    elif step.current_mA:
                        if step.current_mA > 0:
                            charging = True
                            tomato_step["current"] = step.current_mA / 1000
                        else:
                            charging = False
                            tomato_step["current"] = step.current_mA / 1000
                    else:
                        msg = "Must have a current or C-rate"
                        raise ValueError(msg)
                    if step.until_time_s:
                        tomato_step["time"] = step.until_time_s
                    if step.until_voltage_V:
                        if charging:
                            tomato_step["limit_voltage_max"] = step.until_voltage_V
                        else:
                            tomato_step["limit_voltage_min"] = step.until_voltage_V

                case ConstantVoltage():
                    tomato_step["voltage"] = step.voltage_V
                    if step.until_time_s:
                        tomato_step["time"] = step.until_time_s
                    if step.until_rate_C:
                        if step.until_rate_C > 0:
                            tomato_step["limit_current_min"] = str(step.until_rate_C) + "C"
                        else:
                            tomato_step["limit_current_max"] = str(abs(step.until_rate_C)) + "D"

                case Loop():
                    assert isinstance(step.loop_to, int)  # noqa: S101, from _tag_to_indices()
                    tomato_step["goto"] = step.loop_to - 1  # 0-indexed in mpr
                    tomato_step["n_gotos"] = step.cycle_count - 1  # gotos is one less than cycles

                case _:
                    msg = f"to_tomato_mpg2 does not support step type: {step.step}"
                    raise TypeError(msg)

            tomato_dict["method"].append(tomato_step)

        if save_path:
            save_path = Path(save_path)
            save_path.parent.mkdir(parents=True, exist_ok=True)
            with save_path.open("w", encoding="utf-8") as f:
                json.dump(tomato_dict, f, indent=4)
        return json.dumps(tomato_dict, indent=4)

    def to_pybamm_experiment(self) -> list[str]:
        """Convert protocol to PyBaMM experiment format.

        A PyBaMM experiment does not need capacity or sample name.

        Returns:
            list of strings representing the PyBaMM experiment.

        """
        # Don't need to validate capacity if using C-rate steps
        # Create and operate on a copy of the original object
        protocol = self.model_copy()

        # Remove tags and convert to indices
        protocol._tag_to_indices()
        protocol._check_for_intersecting_loops()

        pybamm_experiment: list[str] = []
        loops: dict[int, dict] = {}
        for i, step in enumerate(protocol.method):
            step_str = ""
            match step:
                case ConstantCurrent():
                    if step.rate_C:
                        if step.rate_C > 0:
                            step_str += f"Charge at {step.rate_C}C"
                        else:
                            step_str += f"Discharge at {abs(step.rate_C)}C"
                    elif step.current_mA:
                        if step.current_mA > 0:
                            step_str += f"Charge at {step.current_mA} mA"
                        else:
                            step_str += f"Discharge at {abs(step.current_mA)} mA"
                    if step.until_time_s:
                        if step.until_time_s % 3600 == 0:
                            step_str += f" for {int(step.until_time_s / 3600)} hours"
                        elif step.until_time_s % 60 == 0:
                            step_str += f" for {int(step.until_time_s / 60)} minutes"
                        else:
                            step_str += f" for {step.until_time_s} seconds"
                    if step.until_voltage_V:
                        step_str += f" until {step.until_voltage_V} V"

                case ConstantVoltage():
                    step_str += f"Hold at {step.voltage_V} V"
                    conditions = []
                    if step.until_time_s:
                        if step.until_time_s % 3600 == 0:
                            step_str += f" for {int(step.until_time_s / 3600)} hours"
                        elif step.until_time_s % 60 == 0:
                            step_str += f" for {int(step.until_time_s / 60)} minutes"
                        else:
                            conditions.append(f"for {step.until_time_s} seconds")
                    if step.until_rate_C:
                        conditions.append(f"until {step.until_rate_C}C")
                    if step.until_current_mA:
                        conditions.append(f" until {step.until_current_mA} mA")
                    if conditions:
                        step_str += " " + " or ".join(conditions)

                case OpenCircuitVoltage():
                    step_str += f"Rest for {step.until_time_s} seconds"

                case Loop():
                    # The string from this will get dropped later
                    assert isinstance(step.loop_to, int)  # noqa: S101, from _tag_to_indices()
                    loops[i] = {"goto": step.loop_to - 1, "n": step.cycle_count, "n_done": 0}

                case _:
                    msg = f"to_pybamm_experiment does not support step type: {step.step}"
                    raise TypeError(msg)

            pybamm_experiment.append(step_str)

        exploded_steps = []
        i = 0
        total_itr = 0
        while i < len(pybamm_experiment):
            exploded_steps.append(i)
            if i in loops and loops[i]["n_done"] < loops[i]["n"]:
                # check if it passes over a different loop, if so reset its count
                for j in loops:  # noqa: PLC0206
                    if j < i and j >= loops[i]["goto"]:
                        loops[j]["n_done"] = 0
                loops[i]["n_done"] += 1
                i = loops[i]["goto"]
            else:
                i += 1
            total_itr += 1
            if total_itr > 10000:
                msg = (
                    "Over 10000 steps in protocol to_pybamm_experiment(), "
                    "likely a loop definition error."
                )
                raise RuntimeError(msg)

        # remove all loop steps from the list
        cleaned_exploded_steps = [i for i in exploded_steps if i not in loops]
        # change from list of indices to list of strings
        return [pybamm_experiment[i] for i in cleaned_exploded_steps]

    def to_biologic_mps(
        self,
        save_path: Path | str | None = None,
        sample_name: str | None = None,
        capacity_mAh: float | None = None,
    ) -> str:
        """Convert protocol to a Biologic Settings file (.mps).

        Uses the ModuloBatt technique.

        Note that you must add OCV steps inbetween CC/CV steps if you want the
        current range to be able to change.

        Args:
            save_path: (optional) File path of where to save the mps file.
            sample_name: (optional) Override the protocol sample name.
            capacity_mAh: (optional) Override the protocol sample capacity.

        Returns:
            mps string representation of the protocol.

        """
        # Create and operate on a copy of the original object
        protocol = self.model_copy()

        # Allow overwriting name and capacity
        if sample_name:
            protocol.sample.name = sample_name
        if capacity_mAh:
            protocol.sample.capacity_mAh = capacity_mAh

        # Make sure sample name is set
        if not protocol.sample.name or protocol.sample.name == "$NAME":
            msg = (
                "If using blank sample name or $NAME placeholder, "
                "a sample name must be provided in this function."
            )
            raise ValueError(msg)

        # Make sure capacity is set if using C-rate steps
        protocol._validate_capacity_c_rates()

        # Remove tags and convert to indices
        protocol._tag_to_indices()
        protocol._check_for_intersecting_loops()

        header = [
            "EC-LAB SETTING FILE",
            "",
            "Number of linked techniques : 1",
            "Device : MPG-2",
            "CE vs. WE compliance from -10 V to 10 V",
            "Electrode connection : standard",
            "Potential control : Ewe",
            "Ewe ctrl range : min = 0.00 V, max = 5.00 V",
            "Safety Limits :",
            "	Do not start on E overload",
            f"Comments : {protocol.sample.name}",
            "Cycle Definition : Charge/Discharge alternance",
            "Do not turn to OCV between techniques",
            "",
            "Technique : 1",
            "Modulo Bat",
        ]

        default_step = {
            "Ns": "",
            "ctrl_type": "",
            "Apply I/C": "I",
            "current/potential": "current",
            "ctrl1_val": "",
            "ctrl1_val_unit": "",
            "ctrl1_val_vs": "",
            "ctrl2_val": "",
            "ctrl2_val_unit": "",
            "ctrl2_val_vs": "",
            "ctrl3_val": "",
            "ctrl3_val_unit": "",
            "ctrl3_val_vs": "",
            "N": "0.00",
            "charge/discharge": "Charge",
            "charge/discharge_1": "Charge",
            "Apply I/C_1": "I",
            "N1": "0.00",
            "ctrl4_val": "",
            "ctrl4_val_unit": "",
            "ctrl5_val": "",
            "ctrl5_val_unit": "",
            "ctrl_tM": "0",
            "ctrl_seq": "0",
            "ctrl_repeat": "0",
            "ctrl_trigger": "Falling Edge",
            "ctrl_TO_t": "0.000",
            "ctrl_TO_t_unit": "d",
            "ctrl_Nd": "6",
            "ctrl_Na": "2",
            "ctrl_corr": "0",
            "lim_nb": "0",
            "lim1_type": "Time",
            "lim1_comp": ">",
            "lim1_Q": "",
            "lim1_value": "0.000",
            "lim1_value_unit": "s",
            "lim1_action": "Next sequence",
            "lim1_seq": "",
            "lim2_type": "",
            "lim2_comp": "",
            "lim2_Q": "",
            "lim2_value": "",
            "lim2_value_unit": "",
            "lim2_action": "Next sequence",
            "lim2_seq": "",
            "rec_nb": "0",
            "rec1_type": "",
            "rec1_value": "",
            "rec1_value_unit": "",
            "rec2_type": "",
            "rec2_value": "",
            "rec2_value_unit": "",
            "E range min (V)": "0.000",
            "E range max (V)": "5.000",
            "I Range": "Auto",
            "I Range min": "Unset",
            "I Range max": "Unset",
            "I Range init": "Unset",
            "auto rest": "1",
            "Bandwidth": "5",
        }

        # Use fixed I range for CC and GEIS steps, Auto otherwise
        # There is no Auto option for CC or GEIS
        I_ranges_mA = {
            0.01: "10 µA",
            0.1: "100 µA",
            1: "1 mA",
            10: "10 mA",
            100: "100 mA",
        }

        # Make a list of dicts, one for each step
        step_dicts = []
        for i, step in enumerate(protocol.method):
            step_dict = default_step.copy()
            step_dict.update(
                {
                    "Ns": str(i),
                    "lim1_seq": str(i + 1),
                    "lim2_seq": str(i + 1),
                },
            )
            match step:
                case OpenCircuitVoltage():
                    step_dict.update(
                        {
                            "ctrl_type": "Rest",
                            "lim_nb": "1",
                            "lim1_type": "Time",
                            "lim1_comp": ">",
                            "lim1_value": f"{step.until_time_s:.3f}",
                            "lim1_value_unit": "s",
                            "rec_nb": "1",
                            "rec1_type": "Time",
                            "rec1_value": f"{protocol.record.time_s or 0:.3f}",
                            "rec1_value_unit": "s",
                        },
                    )

                case ConstantCurrent():
                    if step.rate_C and protocol.sample.capacity_mAh:
                        current_mA = step.rate_C * protocol.sample.capacity_mAh
                    elif step.current_mA:
                        current_mA = step.current_mA
                    else:
                        msg = "Either rate_C or current_mA must be set for ConstantCurrent step."
                        raise ValueError(msg)

                    if abs(current_mA) < 1:
                        step_dict.update(
                            {
                                "ctrl_type": "CC",
                                "ctrl1_val": f"{current_mA * 1e3:.3f}",
                                "ctrl1_val_unit": "uA",
                                "ctrl1_val_vs": "<None>",
                            },
                        )
                    else:
                        step_dict.update(
                            {
                                "ctrl_type": "CC",
                                "ctrl1_val": f"{current_mA:.3f}",
                                "ctrl1_val_unit": "mA",
                                "ctrl1_val_vs": "<None>",
                            },
                        )
                    for val, range_str in I_ranges_mA.items():
                        if abs(current_mA) <= val:
                            step_dict.update({"I Range": range_str})
                            break
                    else:
                        msg = f"I range not supported for {current_mA} mA"
                        raise ValueError(msg)

                    # Add limit details
                    lim_num = 0
                    if step.until_time_s:
                        lim_num += 1
                        step_dict.update(
                            {
                                f"lim{lim_num}_type": "Time",
                                f"lim{lim_num}_comp": ">",
                                f"lim{lim_num}_value": f"{step.until_time_s:.3f}",
                                f"lim{lim_num}_value_unit": "s",
                            },
                        )
                    if step.until_voltage_V:
                        lim_num += 1
                        comp = ">" if current_mA > 0 else "<"
                        step_dict.update(
                            {
                                f"lim{lim_num}_type": "Ewe",
                                f"lim{lim_num}_comp": comp,
                                f"lim{lim_num}_value": f"{step.until_voltage_V:.3f}",
                                f"lim{lim_num}_value_unit": "V",
                            },
                        )
                    step_dict.update(
                        {
                            "lim_nb": str(lim_num),
                        },
                    )

                    # Add record details
                    rec_num = 0
                    if protocol.record.time_s:
                        rec_num += 1
                        step_dict.update(
                            {
                                f"rec{rec_num}_type": "Time",
                                f"rec{rec_num}_value": f"{protocol.record.time_s:.3f}",
                                f"rec{rec_num}_value_unit": "s",
                            },
                        )
                    if protocol.record.voltage_V:
                        rec_num += 1
                        step_dict.update(
                            {
                                f"rec{rec_num}_type": "Ewe",
                                f"rec{rec_num}_value": f"{protocol.record.voltage_V:.3f}",
                                f"rec{rec_num}_value_unit": "V",
                            },
                        )
                    step_dict.update(
                        {
                            "rec_nb": str(rec_num),
                        },
                    )

                case ConstantVoltage():
                    step_dict.update(
                        {
                            "ctrl_type": "CV",
                            "ctrl1_val": f"{step.voltage_V:.3f}",
                            "ctrl1_val_unit": "V",
                            "ctrl1_val_vs": "Ref",
                        },
                    )

                    # Add limit details
                    lim_num = 0
                    if step.until_time_s:
                        lim_num += 1
                        step_dict.update(
                            {
                                f"lim{lim_num}_type": "Time",
                                f"lim{lim_num}_comp": ">",
                                f"lim{lim_num}_value": f"{step.until_time_s:.3f}",
                                f"lim{lim_num}_value_unit": "s",
                            },
                        )
                    if step.until_rate_C and protocol.sample.capacity_mAh:
                        until_mA = step.until_rate_C * protocol.sample.capacity_mAh
                    elif step.until_current_mA:
                        until_mA = step.until_current_mA
                    else:
                        until_mA = None
                    if until_mA:
                        lim_num += 1
                        step_dict.update(
                            {
                                f"lim{lim_num}_type": "|I|",
                                f"lim{lim_num}_comp": "<",
                                f"lim{lim_num}_value": f"{abs(until_mA):.3f}",
                                f"lim{lim_num}_value_unit": "mA",
                            },
                        )
                    step_dict.update(
                        {
                            "lim_nb": str(lim_num),
                        },
                    )
                    if i > 0:
                        prev_mA = None
                        prev_step = protocol.method[i - 1]
                        if isinstance(prev_step, ConstantCurrent):
                            prev_mA = None
                            if prev_step.rate_C and protocol.sample.capacity_mAh:
                                prev_mA = prev_step.rate_C * protocol.sample.capacity_mAh
                            elif prev_step.current_mA:
                                prev_mA = prev_step.current_mA
                            if prev_mA and prev_step.until_voltage_V == step.voltage_V:
                                for val, range_str in I_ranges_mA.items():
                                    if abs(prev_mA) <= val:
                                        step_dict.update({"I Range": range_str})
                                        break

                    # Add record details
                    rec_num = 0
                    if protocol.record.time_s:
                        rec_num += 1
                        step_dict.update(
                            {
                                f"rec{rec_num}_type": "Time",
                                f"rec{rec_num}_value": f"{protocol.record.time_s:.3f}",
                                f"rec{rec_num}_value_unit": "s",
                            },
                        )
                    if protocol.record.current_mA:
                        rec_num += 1
                        step_dict.update(
                            {
                                f"rec{rec_num}_type": "I",
                                f"rec{rec_num}_value": f"{protocol.record.current_mA:.3f}",
                                f"rec{rec_num}_value_unit": "mA",
                            },
                        )
                    step_dict.update(
                        {
                            "rec_nb": str(rec_num),
                        },
                    )

                case ImpedanceSpectroscopy():
                    if step.amplitude_V:
                        step_dict.update({"ctrl_type": "PEIS"})
                        if step.amplitude_V >= 0.1:
                            step_dict.update({"ctrl1_val": f"{step.amplitude_V:.3f}"})
                            step_dict.update({"ctrl1_val_unit": "V"})
                        elif step.amplitude_V >= 0.001:
                            step_dict.update({"ctrl1_val": f"{step.amplitude_V * 1e3:.3f}"})
                            step_dict.update({"ctrl1_val_unit": "mV"})
                        else:
                            step_dict.update({"ctrl1_val": f"{step.amplitude_V * 1e6:.3f}"})
                            step_dict.update({"ctrl1_val_unit": "uV"})

                    elif step.amplitude_mA:
                        step_dict.update({"ctrl_type": "GEIS"})
                        if step.amplitude_mA >= 1000:
                            step_dict.update({"ctrl1_val": f"{step.amplitude_mA / 1000:.3f}"})
                            step_dict.update({"ctrl1_val_unit": "A"})
                        elif step.amplitude_mA >= 1:
                            step_dict.update({"ctrl1_val": f"{step.amplitude_mA:.3f}"})
                            step_dict.update({"ctrl1_val_unit": "mA"})
                        else:
                            step_dict.update({"ctrl1_val": f"{step.amplitude_mA * 1000:.3f}"})
                            step_dict.update({"ctrl1_val_unit": "uA"})

                        for val, range_str in I_ranges_mA.items():
                            # GEIS I range behaves differently to CC
                            # 1 mA range means 0.5 mA max amplitude
                            if abs(step.amplitude_mA) * 2 <= val:
                                step_dict.update({"I Range": range_str})
                                break
                        else:
                            msg = f"I range not supported for {step.amplitude_mA} mA"
                            raise ValueError(msg)

                    else:
                        msg = "Either amplitude_V or amplitude_mA must be set."
                        raise ValueError(msg)

                    for freq, ctrl in ((step.start_frequency_Hz, 2), (step.end_frequency_Hz, 3)):
                        if freq >= 1e3:
                            step_dict.update({f"ctrl{ctrl}_val": f"{freq / 1e3:.3f}"})
                            step_dict.update({f"ctrl{ctrl}_val_unit": "kHz"})
                        elif freq >= 1:
                            step_dict.update({f"ctrl{ctrl}_val": f"{freq:.3f}"})
                            step_dict.update({f"ctrl{ctrl}_val_unit": "Hz"})
                        elif freq >= 1e-3:
                            step_dict.update({f"ctrl{ctrl}_val": f"{freq * 1e3:.3f}"})
                            step_dict.update({f"ctrl{ctrl}_val_unit": "mHz"})
                    step_dict.update(
                        {
                            "ctrl_Nd": f"{step.points_per_decade}",
                            "ctrl_Na": f"{step.measures_per_point}",
                            "ctrl_corr": f"{1 if step.drift_correction is True else 0}",
                        }
                    )

                case Loop():
                    assert isinstance(step.loop_to, int)  # noqa: S101, from _tag_to_indices()
                    step_dict.update(
                        {
                            "ctrl_type": "Loop",
                            "ctrl_seq": str(step.loop_to - 1),  # 0-indexed here
                            "ctrl_repeat": str(
                                step.cycle_count - 1
                            ),  # cycles is one less than n_gotos
                        },
                    )

                case _:
                    msg = f"to_biologic_mps() does not support step type: {step.step}"
                    raise NotImplementedError(msg)

            step_dicts.append(step_dict)

        # Transform list of dicts into list of strings
        # Each row is one key and all values of each step
        # All elements must be 20 characters wide
        rows = []
        for row_header in default_step:
            row_data = [step[row_header] for step in step_dicts]
            rows.append(row_header.ljust(20) + "".join(d.ljust(20) for d in row_data))

        settings_string = "\n".join([*header, *rows, ""])

        if save_path:
            save_path = Path(save_path)
            save_path.parent.mkdir(parents=True, exist_ok=True)
            with save_path.open("w", encoding="cp1252") as f:
                f.write(settings_string)

        return settings_string

    def to_battinfo_jsonld(
        self,
        save_path: Path | str | None = None,
        capacity_mAh: float | None = None,
        *,
        include_context: bool = False,
    ) -> dict:
        """Convert protocol to BattInfo JSON-LD format.

        This generates the 'hasTask' key in BattINFO, and does not include the
        creator, lab, instrument etc.

        Args:
            save_path: (optional) File path of where to save the JSON-LD file.
            capacity_mAh: (optional) Override the protocol sample capacity.
            include_context: (optional) Add a `@context` key to the root of the
                JSON-LD.

        Returns:
            Dictionary representation of the JSON-LD.

        """

        def group_iterative_tasks(
            step_numbers: list[int], method: Sequence[AnyTechnique]
        ) -> list[int | tuple[int, list]]:
            """Take a list of techniques, find the iterative loops.

            Returns a list containing ints (a task) or a tuple of an int and
            list (an iterative workflow).

            E.g. [0,1,2,(1000, [4,5,6])]
            Means do tasks 0, 1, 2, then loop over 4, 5, 6 1000 times.
            """
            # Either this is surprisingly complex, or I am just stupid
            # Assume there are no intersecting loops and tags are removed
            # Must iterate BACKWARDS over techniques and treat loops recursively

            tasks: list[int | tuple[int, list]] = []
            skip_above: int | None = None

            list_indices = list(range(len(method)))

            for i, step_number in zip(reversed(list_indices), reversed(step_numbers), strict=True):
                # If the techniques are already included in a loop at a higher depth, skip
                if skip_above and step_numbers[i] >= skip_above:
                    continue

                # If the technique is a loop, the whole loop goes inside a tuple
                if isinstance(method[i], Loop):
                    loop_object = method[i]
                    assert isinstance(loop_object, Loop)  # noqa: S101
                    assert isinstance(loop_object.loop_to, int)  # noqa: S101
                    cycle_count = loop_object.cycle_count
                    start_step: int = loop_object.loop_to - 1  # because loop_to is 1-indexed

                    # Find the subsection that the loop belongs to
                    start_i = next(j for j, n in enumerate(step_numbers) if n == start_step)
                    end_i = i

                    # Add this element, recursively run this function on the loops subsection
                    tasks.append(
                        (
                            cycle_count,
                            group_iterative_tasks(
                                step_numbers[start_i:end_i], method[start_i:end_i]
                            ),
                        ),
                    )

                    # Skip the rest of the loop at this depth
                    skip_above = start_step
                else:
                    # Just add the technique
                    tasks.append(step_number)
            return tasks[::-1]

        def battinfoify_technique(step: AnyTechnique, capacity_mAh: float | None) -> dict:
            """Create a single BattINFO dict from a technique."""
            match step:
                case OpenCircuitVoltage():
                    tech_dict = {
                        "@type": "Resting",
                        "hasInput": [
                            {
                                "@type": "Duration",
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": step.until_time_s,
                                },
                                "hasMeasurementUnit": "Second",
                            }
                        ],
                    }
                case ConstantCurrent():
                    inputs = []
                    current_mA: float | None = None
                    if step.rate_C and capacity_mAh:
                        current_mA = step.rate_C * capacity_mAh
                    elif step.current_mA:
                        current_mA = step.current_mA
                    charging = (current_mA and current_mA > 0) or (step.rate_C and step.rate_C > 0)
                    if current_mA:
                        inputs.append(
                            {
                                "@type": "ElectricCurrent",
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": abs(current_mA),
                                },
                                "hasMeasurementUnit": "MilliAmpere",
                            },
                        )
                    if step.rate_C:
                        inputs.append(
                            {
                                "@type": "CRate",
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": abs(step.rate_C),
                                },
                                "hasMeasurementUnit": "CRateUnit",
                            },
                        )
                    if step.until_voltage_V:
                        inputs.append(
                            {
                                "@type": [
                                    "UpperVoltageLimit" if charging else "LowerVoltageLimit",
                                    "TerminationQuantity",
                                ],
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": step.until_voltage_V,
                                },
                                "hasMeasurementUnit": "Volt",
                            }
                        )
                    if step.until_time_s:
                        inputs.append(
                            {
                                "@type": "Duration",
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": step.until_time_s,
                                },
                                "hasMeasurementUnit": "Second",
                            }
                        )
                    tech_dict = {
                        "@type": "Charging" if charging else "Discharging",
                        "hasInput": inputs,
                    }
                case ConstantVoltage():
                    inputs = [
                        {
                            "@type": "Voltage",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": step.voltage_V,
                            },
                            "hasMeasurementUnit": "Volt",
                        }
                    ]
                    until_current_mA: None | float = None
                    if step.until_rate_C and capacity_mAh:
                        until_current_mA = step.until_rate_C * capacity_mAh
                    elif step.until_current_mA:
                        until_current_mA = step.until_current_mA
                    if until_current_mA is not None:
                        inputs.append(
                            {
                                "@type": ["LowerCurrentLimit", "TerminationQuantity"],
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": abs(until_current_mA),
                                },
                                "hasMeasurementUnit": "MilliAmpere",
                            }
                        )
                    if step.until_rate_C:
                        inputs.append(
                            {
                                "@type": ["LowerCRateLimit", "TerminationQuantity"],
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": abs(step.until_rate_C),
                                },
                                "hasMeasurementUnit": "CRateUnit",
                            },
                        )
                    if step.until_time_s:
                        inputs.append(
                            {
                                "@type": "Duration",
                                "hasNumericalPart": {
                                    "@type": "RealData",
                                    "hasNumberValue": step.until_time_s,
                                },
                                "hasMeasurementUnit": "Second",
                            }
                        )
                    tech_dict = {
                        "@type": "Hold",
                        "hasInput": inputs,
                    }
                case _:
                    msg = f"Technique {step.step} not supported by to_battinfo_jsonld()"
                    raise NotImplementedError(msg)
            return tech_dict

        def recursive_battinfo_build(
            order: list[int | tuple[int, list]],
            methods: Sequence[AnyTechnique],
            capacity_mAh: float | None,
        ) -> dict:
            """Recursively build the a BattINFO JSON-LD from a method."""
            if isinstance(order[0], int):
                # It is just a normal techqniue
                this_tech = battinfoify_technique(methods[order[0]], capacity_mAh)
            else:
                # It is an iterative workflow
                assert isinstance(order[0], tuple)  # noqa: S101
                this_tech = {
                    "@type": "IterativeWorkflow",
                    "hasInput": [
                        {
                            "@type": "NumberOfIterations",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": order[0][0],
                            },
                            "hasMeasurementUnit": "UnitOne",
                        }
                    ],
                    "hasTask": recursive_battinfo_build(order[0][1], methods, capacity_mAh),
                }

            # If there is another technique, keep going
            if len(order) > 1:
                this_tech["hasNext"] = recursive_battinfo_build(order[1:], methods, capacity_mAh)
            return this_tech

        # Create and operate on a copy of the original object
        protocol = self.model_copy()

        # Allow overwriting capacity
        if capacity_mAh:
            protocol.sample.capacity_mAh = capacity_mAh

        # Make sure there are no tags or interecting loops
        protocol._tag_to_indices()
        protocol._check_for_intersecting_loops()

        # Get the order of techniques with nested loops
        battinfo_order = group_iterative_tasks(list(range(len(protocol.method))), protocol.method)

        # Build the battinfo JSON-LD
        battinfo_dict = recursive_battinfo_build(
            battinfo_order, protocol.method, protocol.sample.capacity_mAh
        )

        # Include context at this level, if requested
        if include_context:
            battinfo_dict["@context"] = [
                "https://w3id.org/emmo/domain/battery/context",
            ]

        # Optionally save
        if save_path:
            save_path = Path(save_path)
            save_path.parent.mkdir(parents=True, exist_ok=True)
            with save_path.open("w", encoding="utf-8") as f:
                json.dump(battinfo_dict, f, indent=4)

        return battinfo_dict

    @classmethod
    def from_dict(
        cls,
        data: dict,
        sample_name: str | None = None,
        sample_capacity_mAh: float | None = None,
    ) -> "Protocol":
        """Create a Protocol instance from a dictionary."""
        # If values given then overwrite
        data.setdefault("sample", {})
        if sample_name:
            data["sample"]["name"] = sample_name
        if sample_capacity_mAh:
            data["sample"]["capacity_mAh"] = sample_capacity_mAh
        return Protocol(**data)

    @classmethod
    def from_json(
        cls,
        json_file: str | Path,
        sample_name: str | None = None,
        sample_capacity_mAh: float | None = None,
    ) -> "Protocol":
        """Create a Protocol instance from a JSON file."""
        json_file = Path(json_file)
        with json_file.open("r", encoding="utf-8") as f:
            data = json.load(f)
        return cls.from_dict(data, sample_name, sample_capacity_mAh)

    def to_dict(self) -> dict:
        """Convert a Protocol instance to a dictionary."""
        return self.model_dump()

    def to_json(self, json_file: str | Path | None = None, indent: int = 4) -> str:
        """Dump model as JSON string, optionally save as a JSON file."""
        json_string = self.model_dump_json(indent=indent)
        if json_file:
            json_file = Path(json_file)
            json_file.parent.mkdir(parents=True, exist_ok=True)
            with json_file.open("w", encoding="utf-8") as f:
                f.write(json_string)
        return json_string

from_dict(data, sample_name=None, sample_capacity_mAh=None) classmethod

Create a Protocol instance from a dictionary.

Source code in aurora_unicycler\unicycler.py
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
@classmethod
def from_dict(
    cls,
    data: dict,
    sample_name: str | None = None,
    sample_capacity_mAh: float | None = None,
) -> "Protocol":
    """Create a Protocol instance from a dictionary."""
    # If values given then overwrite
    data.setdefault("sample", {})
    if sample_name:
        data["sample"]["name"] = sample_name
    if sample_capacity_mAh:
        data["sample"]["capacity_mAh"] = sample_capacity_mAh
    return Protocol(**data)

from_json(json_file, sample_name=None, sample_capacity_mAh=None) classmethod

Create a Protocol instance from a JSON file.

Source code in aurora_unicycler\unicycler.py
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
@classmethod
def from_json(
    cls,
    json_file: str | Path,
    sample_name: str | None = None,
    sample_capacity_mAh: float | None = None,
) -> "Protocol":
    """Create a Protocol instance from a JSON file."""
    json_file = Path(json_file)
    with json_file.open("r", encoding="utf-8") as f:
        data = json.load(f)
    return cls.from_dict(data, sample_name, sample_capacity_mAh)

to_battinfo_jsonld(save_path=None, capacity_mAh=None, *, include_context=False)

Convert protocol to BattInfo JSON-LD format.

This generates the 'hasTask' key in BattINFO, and does not include the creator, lab, instrument etc.

Parameters:

Name Type Description Default
save_path Path | str | None

(optional) File path of where to save the JSON-LD file.

None
capacity_mAh float | None

(optional) Override the protocol sample capacity.

None
include_context bool

(optional) Add a @context key to the root of the JSON-LD.

False

Returns:

Type Description
dict

Dictionary representation of the JSON-LD.

Source code in aurora_unicycler\unicycler.py
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
def to_battinfo_jsonld(
    self,
    save_path: Path | str | None = None,
    capacity_mAh: float | None = None,
    *,
    include_context: bool = False,
) -> dict:
    """Convert protocol to BattInfo JSON-LD format.

    This generates the 'hasTask' key in BattINFO, and does not include the
    creator, lab, instrument etc.

    Args:
        save_path: (optional) File path of where to save the JSON-LD file.
        capacity_mAh: (optional) Override the protocol sample capacity.
        include_context: (optional) Add a `@context` key to the root of the
            JSON-LD.

    Returns:
        Dictionary representation of the JSON-LD.

    """

    def group_iterative_tasks(
        step_numbers: list[int], method: Sequence[AnyTechnique]
    ) -> list[int | tuple[int, list]]:
        """Take a list of techniques, find the iterative loops.

        Returns a list containing ints (a task) or a tuple of an int and
        list (an iterative workflow).

        E.g. [0,1,2,(1000, [4,5,6])]
        Means do tasks 0, 1, 2, then loop over 4, 5, 6 1000 times.
        """
        # Either this is surprisingly complex, or I am just stupid
        # Assume there are no intersecting loops and tags are removed
        # Must iterate BACKWARDS over techniques and treat loops recursively

        tasks: list[int | tuple[int, list]] = []
        skip_above: int | None = None

        list_indices = list(range(len(method)))

        for i, step_number in zip(reversed(list_indices), reversed(step_numbers), strict=True):
            # If the techniques are already included in a loop at a higher depth, skip
            if skip_above and step_numbers[i] >= skip_above:
                continue

            # If the technique is a loop, the whole loop goes inside a tuple
            if isinstance(method[i], Loop):
                loop_object = method[i]
                assert isinstance(loop_object, Loop)  # noqa: S101
                assert isinstance(loop_object.loop_to, int)  # noqa: S101
                cycle_count = loop_object.cycle_count
                start_step: int = loop_object.loop_to - 1  # because loop_to is 1-indexed

                # Find the subsection that the loop belongs to
                start_i = next(j for j, n in enumerate(step_numbers) if n == start_step)
                end_i = i

                # Add this element, recursively run this function on the loops subsection
                tasks.append(
                    (
                        cycle_count,
                        group_iterative_tasks(
                            step_numbers[start_i:end_i], method[start_i:end_i]
                        ),
                    ),
                )

                # Skip the rest of the loop at this depth
                skip_above = start_step
            else:
                # Just add the technique
                tasks.append(step_number)
        return tasks[::-1]

    def battinfoify_technique(step: AnyTechnique, capacity_mAh: float | None) -> dict:
        """Create a single BattINFO dict from a technique."""
        match step:
            case OpenCircuitVoltage():
                tech_dict = {
                    "@type": "Resting",
                    "hasInput": [
                        {
                            "@type": "Duration",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": step.until_time_s,
                            },
                            "hasMeasurementUnit": "Second",
                        }
                    ],
                }
            case ConstantCurrent():
                inputs = []
                current_mA: float | None = None
                if step.rate_C and capacity_mAh:
                    current_mA = step.rate_C * capacity_mAh
                elif step.current_mA:
                    current_mA = step.current_mA
                charging = (current_mA and current_mA > 0) or (step.rate_C and step.rate_C > 0)
                if current_mA:
                    inputs.append(
                        {
                            "@type": "ElectricCurrent",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": abs(current_mA),
                            },
                            "hasMeasurementUnit": "MilliAmpere",
                        },
                    )
                if step.rate_C:
                    inputs.append(
                        {
                            "@type": "CRate",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": abs(step.rate_C),
                            },
                            "hasMeasurementUnit": "CRateUnit",
                        },
                    )
                if step.until_voltage_V:
                    inputs.append(
                        {
                            "@type": [
                                "UpperVoltageLimit" if charging else "LowerVoltageLimit",
                                "TerminationQuantity",
                            ],
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": step.until_voltage_V,
                            },
                            "hasMeasurementUnit": "Volt",
                        }
                    )
                if step.until_time_s:
                    inputs.append(
                        {
                            "@type": "Duration",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": step.until_time_s,
                            },
                            "hasMeasurementUnit": "Second",
                        }
                    )
                tech_dict = {
                    "@type": "Charging" if charging else "Discharging",
                    "hasInput": inputs,
                }
            case ConstantVoltage():
                inputs = [
                    {
                        "@type": "Voltage",
                        "hasNumericalPart": {
                            "@type": "RealData",
                            "hasNumberValue": step.voltage_V,
                        },
                        "hasMeasurementUnit": "Volt",
                    }
                ]
                until_current_mA: None | float = None
                if step.until_rate_C and capacity_mAh:
                    until_current_mA = step.until_rate_C * capacity_mAh
                elif step.until_current_mA:
                    until_current_mA = step.until_current_mA
                if until_current_mA is not None:
                    inputs.append(
                        {
                            "@type": ["LowerCurrentLimit", "TerminationQuantity"],
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": abs(until_current_mA),
                            },
                            "hasMeasurementUnit": "MilliAmpere",
                        }
                    )
                if step.until_rate_C:
                    inputs.append(
                        {
                            "@type": ["LowerCRateLimit", "TerminationQuantity"],
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": abs(step.until_rate_C),
                            },
                            "hasMeasurementUnit": "CRateUnit",
                        },
                    )
                if step.until_time_s:
                    inputs.append(
                        {
                            "@type": "Duration",
                            "hasNumericalPart": {
                                "@type": "RealData",
                                "hasNumberValue": step.until_time_s,
                            },
                            "hasMeasurementUnit": "Second",
                        }
                    )
                tech_dict = {
                    "@type": "Hold",
                    "hasInput": inputs,
                }
            case _:
                msg = f"Technique {step.step} not supported by to_battinfo_jsonld()"
                raise NotImplementedError(msg)
        return tech_dict

    def recursive_battinfo_build(
        order: list[int | tuple[int, list]],
        methods: Sequence[AnyTechnique],
        capacity_mAh: float | None,
    ) -> dict:
        """Recursively build the a BattINFO JSON-LD from a method."""
        if isinstance(order[0], int):
            # It is just a normal techqniue
            this_tech = battinfoify_technique(methods[order[0]], capacity_mAh)
        else:
            # It is an iterative workflow
            assert isinstance(order[0], tuple)  # noqa: S101
            this_tech = {
                "@type": "IterativeWorkflow",
                "hasInput": [
                    {
                        "@type": "NumberOfIterations",
                        "hasNumericalPart": {
                            "@type": "RealData",
                            "hasNumberValue": order[0][0],
                        },
                        "hasMeasurementUnit": "UnitOne",
                    }
                ],
                "hasTask": recursive_battinfo_build(order[0][1], methods, capacity_mAh),
            }

        # If there is another technique, keep going
        if len(order) > 1:
            this_tech["hasNext"] = recursive_battinfo_build(order[1:], methods, capacity_mAh)
        return this_tech

    # Create and operate on a copy of the original object
    protocol = self.model_copy()

    # Allow overwriting capacity
    if capacity_mAh:
        protocol.sample.capacity_mAh = capacity_mAh

    # Make sure there are no tags or interecting loops
    protocol._tag_to_indices()
    protocol._check_for_intersecting_loops()

    # Get the order of techniques with nested loops
    battinfo_order = group_iterative_tasks(list(range(len(protocol.method))), protocol.method)

    # Build the battinfo JSON-LD
    battinfo_dict = recursive_battinfo_build(
        battinfo_order, protocol.method, protocol.sample.capacity_mAh
    )

    # Include context at this level, if requested
    if include_context:
        battinfo_dict["@context"] = [
            "https://w3id.org/emmo/domain/battery/context",
        ]

    # Optionally save
    if save_path:
        save_path = Path(save_path)
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with save_path.open("w", encoding="utf-8") as f:
            json.dump(battinfo_dict, f, indent=4)

    return battinfo_dict

to_biologic_mps(save_path=None, sample_name=None, capacity_mAh=None)

Convert protocol to a Biologic Settings file (.mps).

Uses the ModuloBatt technique.

Note that you must add OCV steps inbetween CC/CV steps if you want the current range to be able to change.

Parameters:

Name Type Description Default
save_path Path | str | None

(optional) File path of where to save the mps file.

None
sample_name str | None

(optional) Override the protocol sample name.

None
capacity_mAh float | None

(optional) Override the protocol sample capacity.

None

Returns:

Type Description
str

mps string representation of the protocol.

Source code in aurora_unicycler\unicycler.py
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
def to_biologic_mps(
    self,
    save_path: Path | str | None = None,
    sample_name: str | None = None,
    capacity_mAh: float | None = None,
) -> str:
    """Convert protocol to a Biologic Settings file (.mps).

    Uses the ModuloBatt technique.

    Note that you must add OCV steps inbetween CC/CV steps if you want the
    current range to be able to change.

    Args:
        save_path: (optional) File path of where to save the mps file.
        sample_name: (optional) Override the protocol sample name.
        capacity_mAh: (optional) Override the protocol sample capacity.

    Returns:
        mps string representation of the protocol.

    """
    # Create and operate on a copy of the original object
    protocol = self.model_copy()

    # Allow overwriting name and capacity
    if sample_name:
        protocol.sample.name = sample_name
    if capacity_mAh:
        protocol.sample.capacity_mAh = capacity_mAh

    # Make sure sample name is set
    if not protocol.sample.name or protocol.sample.name == "$NAME":
        msg = (
            "If using blank sample name or $NAME placeholder, "
            "a sample name must be provided in this function."
        )
        raise ValueError(msg)

    # Make sure capacity is set if using C-rate steps
    protocol._validate_capacity_c_rates()

    # Remove tags and convert to indices
    protocol._tag_to_indices()
    protocol._check_for_intersecting_loops()

    header = [
        "EC-LAB SETTING FILE",
        "",
        "Number of linked techniques : 1",
        "Device : MPG-2",
        "CE vs. WE compliance from -10 V to 10 V",
        "Electrode connection : standard",
        "Potential control : Ewe",
        "Ewe ctrl range : min = 0.00 V, max = 5.00 V",
        "Safety Limits :",
        "	Do not start on E overload",
        f"Comments : {protocol.sample.name}",
        "Cycle Definition : Charge/Discharge alternance",
        "Do not turn to OCV between techniques",
        "",
        "Technique : 1",
        "Modulo Bat",
    ]

    default_step = {
        "Ns": "",
        "ctrl_type": "",
        "Apply I/C": "I",
        "current/potential": "current",
        "ctrl1_val": "",
        "ctrl1_val_unit": "",
        "ctrl1_val_vs": "",
        "ctrl2_val": "",
        "ctrl2_val_unit": "",
        "ctrl2_val_vs": "",
        "ctrl3_val": "",
        "ctrl3_val_unit": "",
        "ctrl3_val_vs": "",
        "N": "0.00",
        "charge/discharge": "Charge",
        "charge/discharge_1": "Charge",
        "Apply I/C_1": "I",
        "N1": "0.00",
        "ctrl4_val": "",
        "ctrl4_val_unit": "",
        "ctrl5_val": "",
        "ctrl5_val_unit": "",
        "ctrl_tM": "0",
        "ctrl_seq": "0",
        "ctrl_repeat": "0",
        "ctrl_trigger": "Falling Edge",
        "ctrl_TO_t": "0.000",
        "ctrl_TO_t_unit": "d",
        "ctrl_Nd": "6",
        "ctrl_Na": "2",
        "ctrl_corr": "0",
        "lim_nb": "0",
        "lim1_type": "Time",
        "lim1_comp": ">",
        "lim1_Q": "",
        "lim1_value": "0.000",
        "lim1_value_unit": "s",
        "lim1_action": "Next sequence",
        "lim1_seq": "",
        "lim2_type": "",
        "lim2_comp": "",
        "lim2_Q": "",
        "lim2_value": "",
        "lim2_value_unit": "",
        "lim2_action": "Next sequence",
        "lim2_seq": "",
        "rec_nb": "0",
        "rec1_type": "",
        "rec1_value": "",
        "rec1_value_unit": "",
        "rec2_type": "",
        "rec2_value": "",
        "rec2_value_unit": "",
        "E range min (V)": "0.000",
        "E range max (V)": "5.000",
        "I Range": "Auto",
        "I Range min": "Unset",
        "I Range max": "Unset",
        "I Range init": "Unset",
        "auto rest": "1",
        "Bandwidth": "5",
    }

    # Use fixed I range for CC and GEIS steps, Auto otherwise
    # There is no Auto option for CC or GEIS
    I_ranges_mA = {
        0.01: "10 µA",
        0.1: "100 µA",
        1: "1 mA",
        10: "10 mA",
        100: "100 mA",
    }

    # Make a list of dicts, one for each step
    step_dicts = []
    for i, step in enumerate(protocol.method):
        step_dict = default_step.copy()
        step_dict.update(
            {
                "Ns": str(i),
                "lim1_seq": str(i + 1),
                "lim2_seq": str(i + 1),
            },
        )
        match step:
            case OpenCircuitVoltage():
                step_dict.update(
                    {
                        "ctrl_type": "Rest",
                        "lim_nb": "1",
                        "lim1_type": "Time",
                        "lim1_comp": ">",
                        "lim1_value": f"{step.until_time_s:.3f}",
                        "lim1_value_unit": "s",
                        "rec_nb": "1",
                        "rec1_type": "Time",
                        "rec1_value": f"{protocol.record.time_s or 0:.3f}",
                        "rec1_value_unit": "s",
                    },
                )

            case ConstantCurrent():
                if step.rate_C and protocol.sample.capacity_mAh:
                    current_mA = step.rate_C * protocol.sample.capacity_mAh
                elif step.current_mA:
                    current_mA = step.current_mA
                else:
                    msg = "Either rate_C or current_mA must be set for ConstantCurrent step."
                    raise ValueError(msg)

                if abs(current_mA) < 1:
                    step_dict.update(
                        {
                            "ctrl_type": "CC",
                            "ctrl1_val": f"{current_mA * 1e3:.3f}",
                            "ctrl1_val_unit": "uA",
                            "ctrl1_val_vs": "<None>",
                        },
                    )
                else:
                    step_dict.update(
                        {
                            "ctrl_type": "CC",
                            "ctrl1_val": f"{current_mA:.3f}",
                            "ctrl1_val_unit": "mA",
                            "ctrl1_val_vs": "<None>",
                        },
                    )
                for val, range_str in I_ranges_mA.items():
                    if abs(current_mA) <= val:
                        step_dict.update({"I Range": range_str})
                        break
                else:
                    msg = f"I range not supported for {current_mA} mA"
                    raise ValueError(msg)

                # Add limit details
                lim_num = 0
                if step.until_time_s:
                    lim_num += 1
                    step_dict.update(
                        {
                            f"lim{lim_num}_type": "Time",
                            f"lim{lim_num}_comp": ">",
                            f"lim{lim_num}_value": f"{step.until_time_s:.3f}",
                            f"lim{lim_num}_value_unit": "s",
                        },
                    )
                if step.until_voltage_V:
                    lim_num += 1
                    comp = ">" if current_mA > 0 else "<"
                    step_dict.update(
                        {
                            f"lim{lim_num}_type": "Ewe",
                            f"lim{lim_num}_comp": comp,
                            f"lim{lim_num}_value": f"{step.until_voltage_V:.3f}",
                            f"lim{lim_num}_value_unit": "V",
                        },
                    )
                step_dict.update(
                    {
                        "lim_nb": str(lim_num),
                    },
                )

                # Add record details
                rec_num = 0
                if protocol.record.time_s:
                    rec_num += 1
                    step_dict.update(
                        {
                            f"rec{rec_num}_type": "Time",
                            f"rec{rec_num}_value": f"{protocol.record.time_s:.3f}",
                            f"rec{rec_num}_value_unit": "s",
                        },
                    )
                if protocol.record.voltage_V:
                    rec_num += 1
                    step_dict.update(
                        {
                            f"rec{rec_num}_type": "Ewe",
                            f"rec{rec_num}_value": f"{protocol.record.voltage_V:.3f}",
                            f"rec{rec_num}_value_unit": "V",
                        },
                    )
                step_dict.update(
                    {
                        "rec_nb": str(rec_num),
                    },
                )

            case ConstantVoltage():
                step_dict.update(
                    {
                        "ctrl_type": "CV",
                        "ctrl1_val": f"{step.voltage_V:.3f}",
                        "ctrl1_val_unit": "V",
                        "ctrl1_val_vs": "Ref",
                    },
                )

                # Add limit details
                lim_num = 0
                if step.until_time_s:
                    lim_num += 1
                    step_dict.update(
                        {
                            f"lim{lim_num}_type": "Time",
                            f"lim{lim_num}_comp": ">",
                            f"lim{lim_num}_value": f"{step.until_time_s:.3f}",
                            f"lim{lim_num}_value_unit": "s",
                        },
                    )
                if step.until_rate_C and protocol.sample.capacity_mAh:
                    until_mA = step.until_rate_C * protocol.sample.capacity_mAh
                elif step.until_current_mA:
                    until_mA = step.until_current_mA
                else:
                    until_mA = None
                if until_mA:
                    lim_num += 1
                    step_dict.update(
                        {
                            f"lim{lim_num}_type": "|I|",
                            f"lim{lim_num}_comp": "<",
                            f"lim{lim_num}_value": f"{abs(until_mA):.3f}",
                            f"lim{lim_num}_value_unit": "mA",
                        },
                    )
                step_dict.update(
                    {
                        "lim_nb": str(lim_num),
                    },
                )
                if i > 0:
                    prev_mA = None
                    prev_step = protocol.method[i - 1]
                    if isinstance(prev_step, ConstantCurrent):
                        prev_mA = None
                        if prev_step.rate_C and protocol.sample.capacity_mAh:
                            prev_mA = prev_step.rate_C * protocol.sample.capacity_mAh
                        elif prev_step.current_mA:
                            prev_mA = prev_step.current_mA
                        if prev_mA and prev_step.until_voltage_V == step.voltage_V:
                            for val, range_str in I_ranges_mA.items():
                                if abs(prev_mA) <= val:
                                    step_dict.update({"I Range": range_str})
                                    break

                # Add record details
                rec_num = 0
                if protocol.record.time_s:
                    rec_num += 1
                    step_dict.update(
                        {
                            f"rec{rec_num}_type": "Time",
                            f"rec{rec_num}_value": f"{protocol.record.time_s:.3f}",
                            f"rec{rec_num}_value_unit": "s",
                        },
                    )
                if protocol.record.current_mA:
                    rec_num += 1
                    step_dict.update(
                        {
                            f"rec{rec_num}_type": "I",
                            f"rec{rec_num}_value": f"{protocol.record.current_mA:.3f}",
                            f"rec{rec_num}_value_unit": "mA",
                        },
                    )
                step_dict.update(
                    {
                        "rec_nb": str(rec_num),
                    },
                )

            case ImpedanceSpectroscopy():
                if step.amplitude_V:
                    step_dict.update({"ctrl_type": "PEIS"})
                    if step.amplitude_V >= 0.1:
                        step_dict.update({"ctrl1_val": f"{step.amplitude_V:.3f}"})
                        step_dict.update({"ctrl1_val_unit": "V"})
                    elif step.amplitude_V >= 0.001:
                        step_dict.update({"ctrl1_val": f"{step.amplitude_V * 1e3:.3f}"})
                        step_dict.update({"ctrl1_val_unit": "mV"})
                    else:
                        step_dict.update({"ctrl1_val": f"{step.amplitude_V * 1e6:.3f}"})
                        step_dict.update({"ctrl1_val_unit": "uV"})

                elif step.amplitude_mA:
                    step_dict.update({"ctrl_type": "GEIS"})
                    if step.amplitude_mA >= 1000:
                        step_dict.update({"ctrl1_val": f"{step.amplitude_mA / 1000:.3f}"})
                        step_dict.update({"ctrl1_val_unit": "A"})
                    elif step.amplitude_mA >= 1:
                        step_dict.update({"ctrl1_val": f"{step.amplitude_mA:.3f}"})
                        step_dict.update({"ctrl1_val_unit": "mA"})
                    else:
                        step_dict.update({"ctrl1_val": f"{step.amplitude_mA * 1000:.3f}"})
                        step_dict.update({"ctrl1_val_unit": "uA"})

                    for val, range_str in I_ranges_mA.items():
                        # GEIS I range behaves differently to CC
                        # 1 mA range means 0.5 mA max amplitude
                        if abs(step.amplitude_mA) * 2 <= val:
                            step_dict.update({"I Range": range_str})
                            break
                    else:
                        msg = f"I range not supported for {step.amplitude_mA} mA"
                        raise ValueError(msg)

                else:
                    msg = "Either amplitude_V or amplitude_mA must be set."
                    raise ValueError(msg)

                for freq, ctrl in ((step.start_frequency_Hz, 2), (step.end_frequency_Hz, 3)):
                    if freq >= 1e3:
                        step_dict.update({f"ctrl{ctrl}_val": f"{freq / 1e3:.3f}"})
                        step_dict.update({f"ctrl{ctrl}_val_unit": "kHz"})
                    elif freq >= 1:
                        step_dict.update({f"ctrl{ctrl}_val": f"{freq:.3f}"})
                        step_dict.update({f"ctrl{ctrl}_val_unit": "Hz"})
                    elif freq >= 1e-3:
                        step_dict.update({f"ctrl{ctrl}_val": f"{freq * 1e3:.3f}"})
                        step_dict.update({f"ctrl{ctrl}_val_unit": "mHz"})
                step_dict.update(
                    {
                        "ctrl_Nd": f"{step.points_per_decade}",
                        "ctrl_Na": f"{step.measures_per_point}",
                        "ctrl_corr": f"{1 if step.drift_correction is True else 0}",
                    }
                )

            case Loop():
                assert isinstance(step.loop_to, int)  # noqa: S101, from _tag_to_indices()
                step_dict.update(
                    {
                        "ctrl_type": "Loop",
                        "ctrl_seq": str(step.loop_to - 1),  # 0-indexed here
                        "ctrl_repeat": str(
                            step.cycle_count - 1
                        ),  # cycles is one less than n_gotos
                    },
                )

            case _:
                msg = f"to_biologic_mps() does not support step type: {step.step}"
                raise NotImplementedError(msg)

        step_dicts.append(step_dict)

    # Transform list of dicts into list of strings
    # Each row is one key and all values of each step
    # All elements must be 20 characters wide
    rows = []
    for row_header in default_step:
        row_data = [step[row_header] for step in step_dicts]
        rows.append(row_header.ljust(20) + "".join(d.ljust(20) for d in row_data))

    settings_string = "\n".join([*header, *rows, ""])

    if save_path:
        save_path = Path(save_path)
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with save_path.open("w", encoding="cp1252") as f:
            f.write(settings_string)

    return settings_string

to_dict()

Convert a Protocol instance to a dictionary.

Source code in aurora_unicycler\unicycler.py
1763
1764
1765
def to_dict(self) -> dict:
    """Convert a Protocol instance to a dictionary."""
    return self.model_dump()

to_json(json_file=None, indent=4)

Dump model as JSON string, optionally save as a JSON file.

Source code in aurora_unicycler\unicycler.py
1767
1768
1769
1770
1771
1772
1773
1774
1775
def to_json(self, json_file: str | Path | None = None, indent: int = 4) -> str:
    """Dump model as JSON string, optionally save as a JSON file."""
    json_string = self.model_dump_json(indent=indent)
    if json_file:
        json_file = Path(json_file)
        json_file.parent.mkdir(parents=True, exist_ok=True)
        with json_file.open("w", encoding="utf-8") as f:
            f.write(json_string)
    return json_string

to_neware_xml(save_path=None, sample_name=None, capacity_mAh=None)

Convert the protocol to Neware XML format.

Parameters:

Name Type Description Default
save_path Path | str | None

(optional) File path of where to save the xml file.

None
sample_name str | None

(optional) Override the protocol sample name. A sample name must be provided in this function. It is stored as the 'barcode' of the Neware protocol.

None
capacity_mAh float | None

(optional) Override the protocol sample capacity.

None

Returns:

Type Description
str

xml string representation of the protocol.

Source code in aurora_unicycler\unicycler.py
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
def to_neware_xml(
    self,
    save_path: Path | str | None = None,
    sample_name: str | None = None,
    capacity_mAh: float | None = None,
) -> str:
    """Convert the protocol to Neware XML format.

    Args:
        save_path: (optional) File path of where to save the xml file.
        sample_name: (optional) Override the protocol sample name. A sample
            name must be provided in this function. It is stored as the
            'barcode' of the Neware protocol.
        capacity_mAh: (optional) Override the protocol sample capacity.

    Returns:
        xml string representation of the protocol.

    """
    # Create and operate on a copy of the original object
    protocol = self.model_copy()

    # Allow overwriting name and capacity
    if sample_name:
        protocol.sample.name = sample_name
    if capacity_mAh:
        protocol.sample.capacity_mAh = capacity_mAh

    # Make sure sample name is set
    if not protocol.sample.name or protocol.sample.name == "$NAME":
        msg = (
            "If using blank sample name or $NAME placeholder, "
            "a sample name must be provided in this function."
        )
        raise ValueError(msg)

    # Make sure capacity is set if using C-rate steps
    protocol._validate_capacity_c_rates()

    # Remove tags and convert to indices
    protocol._tag_to_indices()
    protocol._check_for_intersecting_loops()

    # Create XML structure
    root = ET.Element("root")
    config = ET.SubElement(
        root,
        "config",
        type="Step File",
        version="17",
        client_version="BTS Client 8.0.0.478(2024.06.24)(R3)",
        date=datetime.now().strftime("%Y%m%d%H%M%S"),
        Guid=str(uuid.uuid4()),
    )
    head_info = ET.SubElement(config, "Head_Info")
    ET.SubElement(head_info, "Operate", Value="66")
    ET.SubElement(head_info, "Scale", Value="1")
    ET.SubElement(head_info, "Start_Step", Value="1", Hide_Ctrl_Step="0")
    ET.SubElement(head_info, "Creator", Value="aurora-unicycler")
    ET.SubElement(head_info, "Remark", Value=protocol.sample.name)
    # 103, non C-rate mode, seems to give more precise values vs 105
    ET.SubElement(head_info, "RateType", Value="103")
    if protocol.sample.capacity_mAh:
        ET.SubElement(head_info, "MultCap", Value=f"{protocol.sample.capacity_mAh * 3600:f}")

    whole_prt = ET.SubElement(config, "Whole_Prt")
    protect = ET.SubElement(whole_prt, "Protect")
    main_protect = ET.SubElement(protect, "Main")
    volt = ET.SubElement(main_protect, "Volt")
    if protocol.safety.max_voltage_V:
        ET.SubElement(volt, "Upper", Value=f"{protocol.safety.max_voltage_V * 10000:f}")
    if protocol.safety.min_voltage_V:
        ET.SubElement(volt, "Lower", Value=f"{protocol.safety.min_voltage_V * 10000:f}")
    curr = ET.SubElement(main_protect, "Curr")
    if protocol.safety.max_current_mA:
        ET.SubElement(curr, "Upper", Value=f"{protocol.safety.max_current_mA:f}")
    if protocol.safety.min_current_mA:
        ET.SubElement(curr, "Lower", Value=f"{protocol.safety.min_current_mA:f}")
    if protocol.safety.delay_s:
        ET.SubElement(main_protect, "Delay_Time", Value=f"{protocol.safety.delay_s * 1000:f}")
    cap = ET.SubElement(main_protect, "Cap")
    if protocol.safety.max_capacity_mAh:
        ET.SubElement(cap, "Upper", Value=f"{protocol.safety.max_capacity_mAh * 3600:f}")

    record = ET.SubElement(whole_prt, "Record")
    main_record = ET.SubElement(record, "Main")
    if protocol.record.time_s:
        ET.SubElement(main_record, "Time", Value=f"{protocol.record.time_s * 1000:f}")
    if protocol.record.voltage_V:
        ET.SubElement(main_record, "Volt", Value=f"{protocol.record.voltage_V * 10000:f}")
    if protocol.record.current_mA:
        ET.SubElement(main_record, "Curr", Value=f"{protocol.record.current_mA:f}")

    step_info = ET.SubElement(
        config, "Step_Info", Num=str(len(protocol.method) + 1)
    )  # +1 for end step

    def _step_to_element(
        step: AnyTechnique,
        step_num: int,
        parent: ET.Element,
        prev_step: AnyTechnique | None = None,
    ) -> None:
        """Create XML subelement from protocol technique."""
        match step:
            case ConstantCurrent():
                if step.rate_C is not None and step.rate_C != 0:
                    step_type = "1" if step.rate_C > 0 else "2"
                elif step.current_mA is not None and step.current_mA != 0:
                    step_type = "1" if step.current_mA > 0 else "2"
                else:
                    msg = "Must have a current or C-rate"
                    raise ValueError(msg)

                step_element = ET.SubElement(
                    parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type=step_type
                )
                limit = ET.SubElement(step_element, "Limit")
                main = ET.SubElement(limit, "Main")
                if step.rate_C is not None:
                    assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                    ET.SubElement(main, "Rate", Value=f"{abs(step.rate_C):f}")
                    ET.SubElement(
                        main,
                        "Curr",
                        Value=f"{abs(step.rate_C) * protocol.sample.capacity_mAh:f}",
                    )
                elif step.current_mA is not None:
                    ET.SubElement(main, "Curr", Value=f"{abs(step.current_mA):f}")
                if step.until_time_s is not None:
                    ET.SubElement(main, "Time", Value=f"{step.until_time_s * 1000:f}")
                if step.until_voltage_V is not None:
                    ET.SubElement(main, "Stop_Volt", Value=f"{step.until_voltage_V * 10000:f}")

            case ConstantVoltage():
                # Check if CV follows CC and has the same voltage cutoff
                prev_rate_C = None
                prev_current_mA = None
                if (
                    isinstance(prev_step, ConstantCurrent)
                    and prev_step.until_voltage_V == step.voltage_V
                ):
                    if prev_step.rate_C is not None:
                        assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                        prev_rate_C = abs(prev_step.rate_C)
                        prev_current_mA = abs(prev_step.rate_C) * protocol.sample.capacity_mAh
                    elif prev_step.current_mA is not None:
                        prev_current_mA = abs(prev_step.current_mA)
                if step.until_rate_C is not None and step.until_rate_C != 0:
                    step_type = "3" if step.until_rate_C > 0 else "19"
                elif step.until_current_mA is not None and step.until_current_mA != 0:
                    step_type = "3" if step.until_current_mA > 0 else "19"
                else:
                    step_type = "3"  # If it can't be figured out, default to charge
                step_element = ET.SubElement(
                    parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type=step_type
                )
                limit = ET.SubElement(step_element, "Limit")
                main = ET.SubElement(limit, "Main")
                ET.SubElement(main, "Volt", Value=f"{step.voltage_V * 10000:f}")
                if step.until_time_s is not None:
                    ET.SubElement(main, "Time", Value=f"{step.until_time_s * 1000:f}")
                if step.until_rate_C is not None:
                    assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                    ET.SubElement(main, "Stop_Rate", Value=f"{abs(step.until_rate_C):f}")
                    ET.SubElement(
                        main,
                        "Stop_Curr",
                        Value=f"{abs(step.until_rate_C) * protocol.sample.capacity_mAh:f}",
                    )
                elif step.until_current_mA is not None:
                    ET.SubElement(main, "Stop_Curr", Value=f"{abs(step.until_current_mA):f}")
                if prev_rate_C is not None:
                    assert protocol.sample.capacity_mAh is not None  # noqa: S101, from _validate_capacity_c_rates()
                    ET.SubElement(main, "Rate", Value=f"{abs(prev_rate_C):f}")
                    ET.SubElement(
                        main,
                        "Curr",
                        Value=f"{abs(prev_rate_C) * protocol.sample.capacity_mAh:f}",
                    )
                elif prev_current_mA is not None:
                    ET.SubElement(main, "Curr", Value=f"{abs(prev_current_mA):f}")

            case OpenCircuitVoltage():
                step_element = ET.SubElement(
                    parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type="4"
                )
                limit = ET.SubElement(step_element, "Limit")
                main = ET.SubElement(limit, "Main")
                ET.SubElement(main, "Time", Value=f"{step.until_time_s * 1000:f}")

            case Loop():
                step_element = ET.SubElement(
                    parent, f"Step{step_num}", Step_ID=str(step_num), Step_Type="5"
                )
                limit = ET.SubElement(step_element, "Limit")
                other = ET.SubElement(limit, "Other")
                ET.SubElement(other, "Start_Step", Value=str(step.loop_to))
                ET.SubElement(other, "Cycle_Count", Value=str(step.cycle_count))

            case _:
                msg = f"to_neware_xml does not support step type: {step.step}"
                raise TypeError(msg)

    for i, technique in enumerate(protocol.method):
        step_num = i + 1
        prev_step = protocol.method[i - 1] if i >= 1 else None
        _step_to_element(technique, step_num, step_info, prev_step)

    # Add an end step
    step_num = len(protocol.method) + 1
    ET.SubElement(step_info, f"Step{step_num}", Step_ID=str(step_num), Step_Type="6")

    smbus = ET.SubElement(config, "SMBUS")
    ET.SubElement(smbus, "SMBUS_Info", Num="0", AdjacentInterval="0")

    # Convert to string and prettify it
    pretty_xml_string = minidom.parseString(ET.tostring(root)).toprettyxml(indent="  ")  # noqa: S318
    if save_path:
        save_path = Path(save_path)
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with save_path.open("w", encoding="utf-8") as f:
            f.write(pretty_xml_string)
    return pretty_xml_string

to_pybamm_experiment()

Convert protocol to PyBaMM experiment format.

A PyBaMM experiment does not need capacity or sample name.

Returns:

Type Description
list[str]

list of strings representing the PyBaMM experiment.

Source code in aurora_unicycler\unicycler.py
 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
def to_pybamm_experiment(self) -> list[str]:
    """Convert protocol to PyBaMM experiment format.

    A PyBaMM experiment does not need capacity or sample name.

    Returns:
        list of strings representing the PyBaMM experiment.

    """
    # Don't need to validate capacity if using C-rate steps
    # Create and operate on a copy of the original object
    protocol = self.model_copy()

    # Remove tags and convert to indices
    protocol._tag_to_indices()
    protocol._check_for_intersecting_loops()

    pybamm_experiment: list[str] = []
    loops: dict[int, dict] = {}
    for i, step in enumerate(protocol.method):
        step_str = ""
        match step:
            case ConstantCurrent():
                if step.rate_C:
                    if step.rate_C > 0:
                        step_str += f"Charge at {step.rate_C}C"
                    else:
                        step_str += f"Discharge at {abs(step.rate_C)}C"
                elif step.current_mA:
                    if step.current_mA > 0:
                        step_str += f"Charge at {step.current_mA} mA"
                    else:
                        step_str += f"Discharge at {abs(step.current_mA)} mA"
                if step.until_time_s:
                    if step.until_time_s % 3600 == 0:
                        step_str += f" for {int(step.until_time_s / 3600)} hours"
                    elif step.until_time_s % 60 == 0:
                        step_str += f" for {int(step.until_time_s / 60)} minutes"
                    else:
                        step_str += f" for {step.until_time_s} seconds"
                if step.until_voltage_V:
                    step_str += f" until {step.until_voltage_V} V"

            case ConstantVoltage():
                step_str += f"Hold at {step.voltage_V} V"
                conditions = []
                if step.until_time_s:
                    if step.until_time_s % 3600 == 0:
                        step_str += f" for {int(step.until_time_s / 3600)} hours"
                    elif step.until_time_s % 60 == 0:
                        step_str += f" for {int(step.until_time_s / 60)} minutes"
                    else:
                        conditions.append(f"for {step.until_time_s} seconds")
                if step.until_rate_C:
                    conditions.append(f"until {step.until_rate_C}C")
                if step.until_current_mA:
                    conditions.append(f" until {step.until_current_mA} mA")
                if conditions:
                    step_str += " " + " or ".join(conditions)

            case OpenCircuitVoltage():
                step_str += f"Rest for {step.until_time_s} seconds"

            case Loop():
                # The string from this will get dropped later
                assert isinstance(step.loop_to, int)  # noqa: S101, from _tag_to_indices()
                loops[i] = {"goto": step.loop_to - 1, "n": step.cycle_count, "n_done": 0}

            case _:
                msg = f"to_pybamm_experiment does not support step type: {step.step}"
                raise TypeError(msg)

        pybamm_experiment.append(step_str)

    exploded_steps = []
    i = 0
    total_itr = 0
    while i < len(pybamm_experiment):
        exploded_steps.append(i)
        if i in loops and loops[i]["n_done"] < loops[i]["n"]:
            # check if it passes over a different loop, if so reset its count
            for j in loops:  # noqa: PLC0206
                if j < i and j >= loops[i]["goto"]:
                    loops[j]["n_done"] = 0
            loops[i]["n_done"] += 1
            i = loops[i]["goto"]
        else:
            i += 1
        total_itr += 1
        if total_itr > 10000:
            msg = (
                "Over 10000 steps in protocol to_pybamm_experiment(), "
                "likely a loop definition error."
            )
            raise RuntimeError(msg)

    # remove all loop steps from the list
    cleaned_exploded_steps = [i for i in exploded_steps if i not in loops]
    # change from list of indices to list of strings
    return [pybamm_experiment[i] for i in cleaned_exploded_steps]

to_tomato_mpg2(save_path=None, tomato_output=Path('C:/tomato_data/'), sample_name=None, capacity_mAh=None)

Convert protocol to tomato 0.2.3 + MPG2 compatible JSON format.

Parameters:

Name Type Description Default
save_path Path | str | None

(optional) File path of where to save the json file.

None
tomato_output Path

(optional) Where to save the data from tomato.

Path('C:/tomato_data/')
sample_name str | None

(optional) Override the protocol sample name.

None
capacity_mAh float | None

(optional) Override the protocol sample capacity.

None

Returns:

Type Description
str

json string representation of the protocol.

Source code in aurora_unicycler\unicycler.py
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
def to_tomato_mpg2(
    self,
    save_path: Path | str | None = None,
    tomato_output: Path = Path("C:/tomato_data/"),
    sample_name: str | None = None,
    capacity_mAh: float | None = None,
) -> str:
    """Convert protocol to tomato 0.2.3 + MPG2 compatible JSON format.

    Args:
        save_path: (optional) File path of where to save the json file.
        tomato_output: (optional) Where to save the data from tomato.
        sample_name: (optional) Override the protocol sample name.
        capacity_mAh: (optional) Override the protocol sample capacity.

    Returns:
        json string representation of the protocol.

    """
    # Create and operate on a copy of the original object
    protocol = self.model_copy()

    # Allow overwriting name and capacity
    if sample_name:
        protocol.sample.name = sample_name
    if capacity_mAh:
        protocol.sample.capacity_mAh = capacity_mAh

    # Make sure sample name is set
    if not protocol.sample.name or protocol.sample.name == "$NAME":
        msg = (
            "If using blank sample name or $NAME placeholder, "
            "a sample name must be provided in this function."
        )
        raise ValueError(msg)

    # Make sure capacity is set if using C-rate steps
    protocol._validate_capacity_c_rates()

    # Remove tags and convert to indices
    protocol._tag_to_indices()
    protocol._check_for_intersecting_loops()

    # Create JSON structure
    tomato_dict: dict = {
        "version": "0.1",
        "sample": {},
        "method": [],
        "tomato": {
            "unlock_when_done": True,
            "verbosity": "DEBUG",
            "output": {
                "path": str(tomato_output),
                "prefix": protocol.sample.name,
            },
        },
    }
    # tomato -> MPG2 does not support safety parameters, they are set in the instrument
    tomato_dict["sample"]["name"] = protocol.sample.name
    tomato_dict["sample"]["capacity_mAh"] = protocol.sample.capacity_mAh
    for step in protocol.method:
        tomato_step: dict = {}
        tomato_step["device"] = "MPG2"
        tomato_step["technique"] = step.step
        if isinstance(step, (ConstantCurrent, ConstantVoltage, OpenCircuitVoltage)):
            if protocol.record.time_s:
                tomato_step["measure_every_dt"] = protocol.record.time_s
            if protocol.record.current_mA:
                tomato_step["measure_every_dI"] = protocol.record.current_mA
            if protocol.record.voltage_V:
                tomato_step["measure_every_dE"] = protocol.record.voltage_V
            tomato_step["I_range"] = "10 mA"
            tomato_step["E_range"] = "+-5.0 V"

        match step:
            case OpenCircuitVoltage():
                tomato_step["time"] = step.until_time_s

            case ConstantCurrent():
                if step.rate_C:
                    if step.rate_C > 0:
                        charging = True
                        tomato_step["current"] = str(step.rate_C) + "C"
                    else:
                        charging = False
                        tomato_step["current"] = str(abs(step.rate_C)) + "D"
                elif step.current_mA:
                    if step.current_mA > 0:
                        charging = True
                        tomato_step["current"] = step.current_mA / 1000
                    else:
                        charging = False
                        tomato_step["current"] = step.current_mA / 1000
                else:
                    msg = "Must have a current or C-rate"
                    raise ValueError(msg)
                if step.until_time_s:
                    tomato_step["time"] = step.until_time_s
                if step.until_voltage_V:
                    if charging:
                        tomato_step["limit_voltage_max"] = step.until_voltage_V
                    else:
                        tomato_step["limit_voltage_min"] = step.until_voltage_V

            case ConstantVoltage():
                tomato_step["voltage"] = step.voltage_V
                if step.until_time_s:
                    tomato_step["time"] = step.until_time_s
                if step.until_rate_C:
                    if step.until_rate_C > 0:
                        tomato_step["limit_current_min"] = str(step.until_rate_C) + "C"
                    else:
                        tomato_step["limit_current_max"] = str(abs(step.until_rate_C)) + "D"

            case Loop():
                assert isinstance(step.loop_to, int)  # noqa: S101, from _tag_to_indices()
                tomato_step["goto"] = step.loop_to - 1  # 0-indexed in mpr
                tomato_step["n_gotos"] = step.cycle_count - 1  # gotos is one less than cycles

            case _:
                msg = f"to_tomato_mpg2 does not support step type: {step.step}"
                raise TypeError(msg)

        tomato_dict["method"].append(tomato_step)

    if save_path:
        save_path = Path(save_path)
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with save_path.open("w", encoding="utf-8") as f:
            json.dump(tomato_dict, f, indent=4)
    return json.dumps(tomato_dict, indent=4)

RecordParams

Bases: BaseModel

Recording parameters.

Attributes:

Name Type Description
current_mA float | None

Current change in mA which triggers recording data.

voltage_V float | None

Voltage change in V which triggers recording data.

time_s float

Time in seconds between recording data.

Source code in aurora_unicycler\unicycler.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class RecordParams(BaseModel):
    """Recording parameters.

    Attributes:
        current_mA: Current change in mA which triggers recording data.
        voltage_V: Voltage change in V which triggers recording data.
        time_s: Time in seconds between recording data.

    """

    current_mA: float | None = None
    voltage_V: float | None = None
    time_s: float = Field(gt=0)

    model_config = ConfigDict(extra="forbid")

SafetyParams

Bases: BaseModel

Safety parameters, i.e. limits before cancelling the entire experiment.

Attributes:

Name Type Description
max_voltage_V float | None

Maximum voltage in V.

min_voltage_V float | None

Minimum voltage in V.

max_current_mA float | None

Maximum current in mA.

min_current_mA float | None

Minimum current in mA (can be negative).

delay_s float | None

How long in seconds limits must be exceeded before cancelling.

Source code in aurora_unicycler\unicycler.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
class SafetyParams(BaseModel):
    """Safety parameters, i.e. limits before cancelling the entire experiment.

    Attributes:
        max_voltage_V: Maximum voltage in V.
        min_voltage_V: Minimum voltage in V.
        max_current_mA: Maximum current in mA.
        min_current_mA: Minimum current in mA (can be negative).
        delay_s: How long in seconds limits must be exceeded before cancelling.

    """

    max_voltage_V: float | None = None
    min_voltage_V: float | None = None
    max_current_mA: float | None = None
    min_current_mA: float | None = None
    max_capacity_mAh: float | None = Field(ge=0, default=None)
    delay_s: float | None = Field(ge=0, default=None)

    model_config = ConfigDict(extra="forbid")

SampleParams

Bases: BaseModel

Sample parameters.

Attributes:

Name Type Description
name str

Sample name.

capacity_mAh float | None

Sample capacity in mAh, used to calculate current from C-rates.

Source code in aurora_unicycler\unicycler.py
123
124
125
126
127
128
129
130
131
132
133
134
135
class SampleParams(BaseModel):
    """Sample parameters.

    Attributes:
        name: Sample name.
        capacity_mAh: Sample capacity in mAh, used to calculate current from C-rates.

    """

    name: str = Field(default="$NAME")
    capacity_mAh: float | None = Field(gt=0, default=None)

    model_config = ConfigDict(extra="forbid")

Step

Bases: BaseModel

Base class for all steps.

Source code in aurora_unicycler\unicycler.py
177
178
179
180
181
182
class Step(BaseModel):
    """Base class for all steps."""

    # optional id field
    id: str | None = Field(default=None, description="Optional ID for the technique step")
    model_config = ConfigDict(extra="forbid")

Tag

Bases: Step

Tag step.

Used in combination with the Loop step, e.g.

[
    Tag(tag="formation")
    # Your cycling steps here
    Loop(loop_to="formation", cycle_count=3)
]

This will loop over the cycling steps 3 times. Put the tag before the step you want to loop to.

Can also be used for comments or organisation, but note that it will only be stored in unicycler, when sending to e.g. Biologic or Neware, loops/tags are converted to indices and the tag steps are removed.

Attributes:

Name Type Description
tag str

The tag name.

Source code in aurora_unicycler\unicycler.py
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
class Tag(Step):
    """Tag step.

    Used in combination with the Loop step, e.g.
    ```
    [
        Tag(tag="formation")
        # Your cycling steps here
        Loop(loop_to="formation", cycle_count=3)
    ]
    ```

    This will loop over the cycling steps 3 times. Put the tag before the step
    you want to loop to.

    Can also be used for comments or organisation, but note that it will only be
    stored in unicycler, when sending to e.g. Biologic or Neware, loops/tags are
    converted to indices and the tag steps are removed.

    Attributes:
        tag: The tag name.

    """

    step: Literal["tag"] = Field(default="tag", frozen=True)
    tag: str = Field(default="")

    model_config = ConfigDict(extra="forbid")