Skip to content

Array Class#

The ArrayGlyph class provides functionality for visualizing and manipulating arrays, including plotting, animating, and saving animations.

Class Documentation#

cleopatra.array_glyph.ArrayGlyph #

A class to handle arrays and perform various visualization operations on them.

The ArrayGlyph class provides functionality for visualizing 2D and 3D arrays with various customization options. It supports plotting single arrays, RGB arrays, and creating animations from 3D arrays.

Attributes:

Name Type Description
fig Figure

The matplotlib figure object.

ax Axes

The matplotlib axes object.

extent List

The extent of the array [xmin, xmax, ymin, ymax].

rgb bool

Whether the array is an RGB array.

no_elem int

The number of elements in the array.

anim FuncAnimation

The animation object if created.

Notes

This class provides methods for: - Plotting arrays with customizable color scales, color bars, and annotations - Creating animations from 3D arrays - Displaying point values on arrays - Customizing plot appearance

Examples:

  • Create a simple array plot:
    >>> import numpy as np
    >>> from cleopatra.array_glyph import ArrayGlyph
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array_glyph = ArrayGlyph(arr)
    >>> fig, ax = array_glyph.plot()
    
  • Create an RGB plot from a 3D array:
    >>> rgb_array = np.random.randint(0, 255, size=(3, 10, 10))
    >>> rgb_glyph = ArrayGlyph(rgb_array, rgb=[0, 1, 2])
    >>> fig, ax = rgb_glyph.plot()
    
  • Create an animated plot from a 3D array:
    >>> time_series = np.random.randint(1, 10, size=(5, 10, 10))
    >>> time_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
    >>> animated_glyph = ArrayGlyph(time_series)
    >>> anim = animated_glyph.animate(time_labels)
    
Source code in cleopatra/array_glyph.py
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
class ArrayGlyph:
    """A class to handle arrays and perform various visualization operations on them.

    The ArrayGlyph class provides functionality for visualizing 2D and 3D arrays with
    various customization options. It supports plotting single arrays, RGB arrays,
    and creating animations from 3D arrays.

    Attributes
    ----------
    fig : matplotlib.figure.Figure
        The matplotlib figure object.
    ax : matplotlib.axes.Axes
        The matplotlib axes object.
    extent : List
        The extent of the array [xmin, xmax, ymin, ymax].
    rgb : bool
        Whether the array is an RGB array.
    no_elem : int
        The number of elements in the array.
    anim : matplotlib.animation.FuncAnimation
        The animation object if created.

    Notes
    -----
    This class provides methods for:
    - Plotting arrays with customizable color scales, color bars, and annotations
    - Creating animations from 3D arrays
    - Displaying point values on arrays
    - Customizing plot appearance

    Examples
    --------
    - Create a simple array plot:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> array_glyph = ArrayGlyph(arr)
        >>> fig, ax = array_glyph.plot()

        ```
    - Create an RGB plot from a 3D array:
    ```python
    >>> rgb_array = np.random.randint(0, 255, size=(3, 10, 10))
    >>> rgb_glyph = ArrayGlyph(rgb_array, rgb=[0, 1, 2])
    >>> fig, ax = rgb_glyph.plot()

    ```
    - Create an animated plot from a 3D array:
    ```python
    >>> time_series = np.random.randint(1, 10, size=(5, 10, 10))
    >>> time_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
    >>> animated_glyph = ArrayGlyph(time_series)
    >>> anim = animated_glyph.animate(time_labels)

    ```
    """

    def __init__(
        self,
        array: np.ndarray,
        exclude_value: List = np.nan,
        extent: List = None,
        rgb: List[int] = None,
        surface_reflectance: int = None,
        cutoff: List = None,
        ax: Axes = None,
        fig: Figure = None,
        percentile: int = None,
        **kwargs,
    ):
        """Initialize the ArrayGlyph object with an array and optional parameters.

        Parameters
        ----------
        array : np.ndarray
            The array to be visualized. Can be a 2D array for single plots or a 3D array for RGB plots or animations.
        exclude_value : List or numeric, optional
            Value(s) used to mask cells out of the domain, by default np.nan.
            Can be a single value or a list of values to exclude.
        extent : List, optional
            The extent of the array in the format [xmin, ymin, xmax, ymax], by default None.
            If provided, the array will be plotted with these spatial boundaries.
        rgb : List[int], optional
            The indices of the red, green, and blue bands in the given array, by default None.
            If provided, the array will be treated as an RGB image.
            Can be a list of three values [r, g, b], or four values if alpha band is included [r, g, b, a].
        surface_reflectance : int, optional
            Surface reflectance value for normalizing satellite data, by default None.
            Typically 10000 for Sentinel-2 data.
        cutoff : List, optional
            Clip the range of pixel values for each band, by default None.
            Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1.
            Should be a list with one value per band.
        ax : matplotlib.axes.Axes, optional
            A pre-existing axes to plot on, by default None.
            If None, a new axes will be created.
        fig : matplotlib.figure.Figure, optional
            A pre-existing figure to plot on, by default None.
            If None, a new figure will be created.
        percentile : int, optional
            The percentile value to be used for scaling the array values, by default None.
            Used to enhance contrast by stretching the histogram.
        **kwargs : dict
            Additional keyword arguments for customizing the plot.
            Supported arguments include:
                figsize : tuple, optional
                    Figure size, by default (8, 8).
                vmin : float, optional
                    Minimum value for color scaling, by default min(array).
                vmax : float, optional
                    Maximum value for color scaling, by default max(array).
                title : str, optional
                    Title of the plot, by default 'Array Plot'.
                title_size : int, optional
                    Title font size, by default 15.
                cmap : str, optional
                    Colormap name, by default 'coolwarm_r'.

        Raises
        ------
        ValueError
            If an invalid keyword argument is provided.
        ValueError
            If rgb is provided but the array doesn't have enough dimensions.

        Examples
        --------
        Basic initialization with a 2D array:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> array_glyph = ArrayGlyph(arr)
        >>> fig, ax = array_glyph.plot()

        ```
        Initialization with custom figure size and title:
        ```python
        >>> array_glyph = ArrayGlyph(arr, figsize=(10, 8), title="Custom Array Plot")
        >>> fig, ax = array_glyph.plot()

        ```
        Initialization with RGB bands from a 3D array:
        ```python
        >>> rgb_array = np.random.randint(0, 255, size=(3, 10, 10))
        >>> rgb_glyph = ArrayGlyph(rgb_array, rgb=[0, 1, 2], surface_reflectance=255)
        >>> fig, ax = rgb_glyph.plot()

        ```
        Initialization with custom extent:
        ```python
        >>> array_glyph = ArrayGlyph(arr, extent=[0, 0, 10, 10])
        >>> fig, ax = array_glyph.plot()

        ```
        """
        self._default_options = DEFAULT_OPTIONS.copy()

        for key, val in kwargs.items():
            if key not in self.default_options.keys():
                raise ValueError(
                    f"The given keyword argument:{key} is not correct, possible parameters are,"
                    f" {DEFAULT_OPTIONS}"
                )
            else:
                self.default_options[key] = val
        # first replace the no_data_value by nan
        # convert the array to float32 to be able to replace the no data value with nan
        if exclude_value is not np.nan:
            if len(exclude_value) > 1:
                mask = np.logical_or(
                    np.isclose(array, exclude_value[0], rtol=0.001),
                    np.isclose(array, exclude_value[1], rtol=0.001),
                )
            else:
                mask = np.isclose(array, exclude_value[0], rtol=0.0000001)
            array = ma.array(array, mask=mask, dtype=array.dtype)
        else:
            array = ma.array(array)

        # convert the extent from [xmin, ymin, xmax, ymax] to [xmin, xmax, ymin, ymax] as required by matplotlib.
        if extent is not None:
            extent = [extent[0], extent[2], extent[1], extent[3]]
        self.extent = extent

        if rgb is not None:
            self.rgb = True
            # prepare to plot rgb plot only if there are three arrays
            if array.shape[0] < 3:
                raise ValueError(
                    f"To plot RGB plot the given array should have only 3 arrays, given array have "
                    f"{array.shape[0]}"
                )
            else:
                array = self.prepare_array(
                    array,
                    rgb=rgb,
                    surface_reflectance=surface_reflectance,
                    cutoff=cutoff,
                    percentile=percentile,
                )
        else:
            self.rgb = False

        self._exclude_value = exclude_value

        self._vmax = (
            np.nanmax(array) if kwargs.get("vmax") is None else kwargs.get("vmax")
        )
        self._vmin = (
            np.nanmin(array) if kwargs.get("vmin") is None else kwargs.get("vmin")
        )

        self._arr = array
        # get the tick spacing that has 10 ticks only
        self.ticks_spacing = (self._vmax - self._vmin) / 10
        shape = array.shape
        if len(shape) == 3:
            no_elem = array[0, :, :].count()
        else:
            no_elem = array.count()

        self.no_elem = no_elem

        if fig is not None:
            self.fig, self.ax = fig, ax
        else:
            self.fig = None

    @property
    def arr(self):
        """array"""
        return self._arr

    @arr.setter
    def arr(self, value):
        self._arr = value

    def prepare_array(
        self,
        array: np.ndarray,
        rgb: List[int] = None,
        surface_reflectance: int = None,
        cutoff: List = None,
        percentile: int = None,
    ) -> np.ndarray:
        """Prepare an array for RGB visualization.

        This method processes a multi-band array to create an RGB image suitable for visualization.
        It can normalize the data using either percentile-based scaling or surface reflectance values.

        Parameters
        ----------
        array : np.ndarray
            The input array containing multiple bands. For RGB visualization,
            this should be a 3D array where the first dimension represents the bands.
        rgb : List[int], optional
            The indices of the red, green, and blue bands in the given array, by default None.
            If None, assumes the order is [3, 2, 1] (common for Sentinel-2 data).
        surface_reflectance : int, optional
            Surface reflectance value for normalizing satellite data, by default None.
            Typically 10000 for Sentinel-2 data or 255 for 8-bit imagery.
            Used to scale values to the range [0, 1].
        cutoff : List, optional
            Clip the range of pixel values for each band, by default None.
            Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1.
            Should be a list with one value per band.
        percentile : int, optional
            The percentile value to be used for scaling the array values, by default None.
            Used to enhance contrast by stretching the histogram.
            If provided, this takes precedence over surface_reflectance.

        Returns
        -------
        np.ndarray
            The prepared array with shape (height, width, 3) suitable for RGB visualization.
            Values are normalized to the range [0, 1].
            the rgb 3d array is converted into 2d array to be plotted using the plt.imshow function.
            a float32 array normalized between 0 and 1 using the `percentile` values or the `surface_reflectance`.
            if the `percentile` or `surface_reflectance` values are not given, the function just reorders the values
            to have the red-green-blue order.

        Raises
        ------
        ValueError
            If the array shape is incompatible with the provided RGB indices.

        Notes
        -----
            - The `prepare_array` function is called in the constructor of the `ArrayGlyph` class to prepare the array,
              so you can provide the same parameters of the `prepare_array` function to the `ArrayGlyph constructor`.
            - The prepare function moves the first axes (the channel axis) to the last axes, and then scales the array
              using the percentile values. If the percentile is not given, the function scales the array using the
              surface reflectance values. If the surface reflectance is not given, the function scales the array using
              the cutoff values. If the cutoff is not given, the function scales the array using the sentinel data

        Examples
        --------
        Prepare an array using percentile-based scaling:
            ```python
            >>> import numpy as np
            >>> from cleopatra.array_glyph import ArrayGlyph
            >>> # Create a 3-band array (e.g., satellite image)
            >>> bands = np.random.randint(0, 10000, size=(3, 100, 100))
            >>> glyph = ArrayGlyph(np.zeros((1, 1)))  # Dummy initialization
            >>> rgb_array = glyph.prepare_array(bands, rgb=[0, 1, 2], percentile=2)
            >>> rgb_array.shape
            (100, 100, 3)
            >>> np.all((0 <= rgb_array) & (rgb_array <= 1))
            np.True_

            ```
        Prepare an array using surface reflectance normalization:
            ```python
            >>> rgb_array = glyph.prepare_array(bands, rgb=[0, 1, 2], surface_reflectance=10000)
            >>> rgb_array.shape
            (100, 100, 3)
            >>> np.all((0 <= rgb_array) & (rgb_array <= 1))
            np.True_

            ```
        Prepare an array with cutoff values:
            ```python
            >>> rgb_array = glyph.prepare_array(
            ...     bands, rgb=[0, 1, 2], surface_reflectance=10000, cutoff=[5000, 5000, 5000]
            ... )
            >>> rgb_array.shape
            (100, 100, 3)
            >>> np.all((0 <= rgb_array) & (rgb_array <= 1))
            np.True_

            ```

        - Create an array and instantiate the `ArrayGlyph` class.
            ```python
            >>> import numpy as np
            >>> arr = np.random.randint(0, 255, size=(3, 5, 5)).astype(np.float32)
            >>> array_glyph = ArrayGlyph(arr)
            >>> print(array_glyph.arr.shape)
            (3, 5, 5)

            ```
        `rgb` channels:
            - Now let's use the `prepare_array` function with `rgb` channels as [0, 1, 2]. so the finction does not to
                reorder the chennels. but it just needs to move the first axis to the last axis.
                ```python
                >>> rgb_array = array_glyph.prepare_array(arr, rgb=[0, 1, 2])
                >>> print(rgb_array.shape)
                (5, 5, 3)

                ```
            - If we compare the values of the first channel in the original array with the first array in the rgb array it
                should be the same.
                ```python
                >>> np.testing.assert_equal(arr[0, :, :],rgb_array[:, :, 0])

                ```
        surface_reflectance:
            - if you provide the surface reflectance value, the function will scale the array using the surface reflectance
                value to a normalized rgb values.
                ```python
                >>> array_glyph = ArrayGlyph(arr)
                >>> rgb_array = array_glyph.prepare_array(arr, surface_reflectance=10000, rgb=[0, 1, 2])
                >>> print(rgb_array.shape)
                (5, 5, 3)

                ```
            - if you print the values of the first channel, you will find all the values are between 0 and 1.
                ```python
                >>> print(rgb_array[:, :, 0]) # doctest: +SKIP
                [[0.0195 0.02   0.0109 0.0211 0.0087]
                 [0.0112 0.0221 0.0035 0.0234 0.0141]
                 [0.0116 0.0188 0.0001 0.0176 0.    ]
                 [0.0014 0.0147 0.0043 0.0167 0.0117]
                 [0.0083 0.0139 0.0186 0.02   0.0058]]

                ```
            - With the `surface_reflectance` parameter, you can also use the `cutoff` parameter to affect values that
                are above it, by rescaling them.
                ```python
                >>> rgb_array = array_glyph.prepare_array(
                ...     arr, surface_reflectance=10000, rgb=[0, 1, 2], cutoff=[0.8, 0.8, 0.8]
                ... )
                >>> print(rgb_array[:, :, 0]) # doctest: +SKIP
                [[0.     0.     0.     0.     0.    ]
                 [1.     1.     1.     1.     1.    ]
                 [1.     1.     1.     1.     1.    ]
                 [0.0014 0.0147 0.0043 0.0167 0.0117]
                 [0.0083 0.0139 0.0186 0.02   0.0058]]

                ```
        """
        # take the rgb arrays and reorder them to have the red-green-blue, if the order is not given, assume the
        # order as sentinel data. [3, 2, 1]
        array = array[rgb].transpose(1, 2, 0)

        if percentile is not None:
            array = self.scale_percentile(array, percentile=percentile)
        elif surface_reflectance is not None:
            array = self._prepare_sentinel_rgb(
                array,
                rgb=rgb,
                surface_reflectance=surface_reflectance,
                cutoff=cutoff,
            )
        return array

    def _prepare_sentinel_rgb(
        self,
        array: np.ndarray,
        rgb: List[int] = None,
        surface_reflectance: int = 10000,
        cutoff: List = None,
    ) -> np.ndarray:
        """Prepare Sentinel satellite data for RGB visualization.

        This method specifically handles Sentinel satellite imagery by normalizing the data
        using the provided surface reflectance value and optional cutoff values.

        Parameters
        ----------
        array : np.ndarray
            The input array with shape (height, width, 3) containing RGB bands.
            This array should already be transposed from the original band-first format.
        rgb : List[int], optional
            The indices of the red, green, and blue bands in the original array, by default None.
            Used only for cutoff application.
        surface_reflectance : int, optional
            Surface reflectance value for normalizing satellite data, by default 10000.
            Sentinel-2 data typically uses 10000 as the maximum reflectance value.
            Used to scale values to the range [0, 1].
        cutoff : List, optional
            Clip the range of pixel values for each band, by default None.
            Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1.
            Should be a list with one value per band.

        Returns
        -------
        np.ndarray
            The prepared array with shape (height, width, 3) suitable for RGB visualization.
            Values are normalized to the range [0, 1].

        Examples
        --------
        Prepare Sentinel-2 data with default surface reflectance:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> # Create a simulated Sentinel-2 RGB array
        >>> rgb_data = np.random.randint(0, 10000, size=(100, 100, 3))
        >>> glyph = ArrayGlyph(np.zeros((1, 1)))  # Dummy initialization
        >>> normalized = glyph._prepare_sentinel_rgb(rgb_data)
        >>> np.all((0 <= normalized) & (normalized <= 1))
        np.True_

        ```
        Prepare Sentinel-2 data with custom cutoff values:
        ```python
        >>> cutoffs = [8000, 7000, 9000]
        >>> normalized = glyph._prepare_sentinel_rgb(rgb_data, rgb=[0, 1, 2], cutoff=cutoffs)
        >>> np.all((0 <= normalized) & (normalized <= 1))
        np.True_

        ```
        """
        array = np.clip(array / surface_reflectance, 0, 1)
        if cutoff is not None:
            array[0] = np.clip(rgb[0], 0, cutoff[0]) / cutoff[0]
            array[1] = np.clip(rgb[1], 0, cutoff[1]) / cutoff[1]
            array[2] = np.clip(rgb[2], 0, cutoff[2]) / cutoff[2]

        return array

    @staticmethod
    def scale_percentile(arr: np.ndarray, percentile: int = 1) -> np.ndarray:
        """Scale an array using percentile-based contrast stretching.

        This method enhances the contrast of an image by stretching the histogram
        based on percentile values. It calculates the lower and upper percentile values
        for each band and normalizes the data to the range [0, 1].

        Parameters
        ----------
        arr : np.ndarray
            The array to be scaled, with shape (height, width, bands).
            Typically an RGB image with 3 bands.
        percentile : int, optional
            The percentile value to be used for scaling, by default 1.
            This value determines how much of the histogram tails to exclude.
            Higher values result in more contrast stretching.
            Typical values range from 1 to 5.

        Returns
        -------
        np.ndarray
            The scaled array, normalized between 0 and 1, with the same shape as input.
            Data type is float32.

        Notes
        -----
        The method works by:
        1. Computing the lower percentile value for each band
        2. Computing the upper percentile value (100 - percentile) for each band
        3. Normalizing each band using these percentile values
        4. Clipping values to the range [0, 1]

        This is particularly useful for visualizing satellite imagery with high dynamic range.

        Examples
        --------
        Scale a single-band array:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> # Create a test array with values between 0 and 10000
        >>> test_array = np.random.randint(0, 10000, size=(100, 100, 1))
        >>> scaled = ArrayGlyph.scale_percentile(test_array, percentile=2)
        >>> scaled.shape
        (100, 100, 1)
        >>> np.all((0 <= scaled) & (scaled <= 1))
        np.True_

        ```
        Scale an RGB array:
        ```python
        >>> rgb_array = np.random.randint(0, 10000, size=(100, 100, 3))
        >>> scaled = ArrayGlyph.scale_percentile(rgb_array, percentile=2)
        >>> scaled.shape
        (100, 100, 3)
        >>> np.all((0 <= scaled) & (scaled <= 1))
        np.True_

        ```
        Using different percentile values affects contrast:
        ```python
        >>> low_contrast = ArrayGlyph.scale_percentile(rgb_array, percentile=1)
        >>> high_contrast = ArrayGlyph.scale_percentile(rgb_array, percentile=5)
        >>> # Higher percentile typically results in higher contrast

        ```
        """
        rows, columns, bands = arr.shape
        # flatten image.
        arr = np.reshape(arr, [rows * columns, bands]).astype(np.float32)
        # lower percentile values (one value for each band).
        lower_percent = np.percentile(arr, percentile, axis=0)
        # 98 percentile values.
        upper_percent = np.percentile(arr, 100 - percentile, axis=0) - lower_percent
        # normalize the 3 bands using the percentile values for each band.
        arr = (arr - lower_percent[None, :]) / upper_percent[None, :]
        arr = np.reshape(arr, [rows, columns, bands])
        # discard outliers.
        arr = arr.clip(0, 1)

        return arr

    def __str__(self):
        """String representation of the Array object."""
        message = f"""
                    Min: {self.vmin}
                    Max: {self.vmax}
                    Exclude values: {self.exclude_value}
                    RGB: {self.rgb}
                """
        return message

    @property
    def vmin(self):
        """min value in the array"""
        return self._vmin

    @property
    def vmax(self):
        """max value in the array"""
        return self._vmax

    @property
    def exclude_value(self):
        """exclude_value"""
        return self._exclude_value

    @exclude_value.setter
    def exclude_value(self, value):
        self._exclude_value = value

    @property
    def default_options(self):
        """Default plot options"""
        return self._default_options

    @property
    def anim(self):
        """Animation function"""
        if hasattr(self, "_anim"):
            val = self._anim
        else:
            raise ValueError(
                "Please first use the function animate to create the animation object"
            )
        return val

    def create_figure_axes(self) -> Tuple[Figure, Axes]:
        """Create the figure and the axes.

        Returns
        -------
        fig: matplotlib.figure.Figure
            the created figure.
        ax: matplotlib.axes.Axes
            the created axes.
        """
        fig, ax = plt.subplots(figsize=self.default_options["figsize"])

        return fig, ax

    def get_ticks(self) -> np.ndarray:
        """get a list of ticks for the color bar"""
        ticks_spacing = self.default_options["ticks_spacing"]
        vmax = self.default_options["vmax"]
        vmin = self.default_options["vmin"]
        remainder = np.round(math.remainder(vmax, ticks_spacing), 3)
        # np.mod(vmax, ticks_spacing) gives float point error, so we use the round function.
        if remainder == 0:
            ticks = np.arange(vmin, vmax + ticks_spacing, ticks_spacing)
        else:
            try:
                ticks = np.arange(vmin, vmax + ticks_spacing, ticks_spacing)
            except ValueError:
                raise ValueError(
                    "The number of ticks exceeded the max allowed size, possible errors"
                    f" is the value of the NodataValue you entered-{self.exclude_value}"
                )
            ticks = np.append(
                ticks,
                [int(vmax / ticks_spacing) * ticks_spacing + ticks_spacing],
            )
        return ticks

    def _plot_im_get_cbar_kw(
        self, ax: Axes, arr: np.ndarray, ticks: np.ndarray
    ) -> Tuple[AxesImage, Dict[str, str]]:
        """Plot a single image and get color bar keyword arguments.

        Parameters
        ----------
        ax: [axes]
            matplotlib figure axes.
        arr: [array]
            numpy array.
        ticks: [list]
            color bar ticks.

        Returns
        -------
        im: AxesImage
            image axes.
        cbar: Dict[str,str]
            color bar keyword arguments.
        """
        color_scale = self.default_options["color_scale"]
        cmap = self.default_options["cmap"]
        # get the vmin and vmax from the tick instead of the default values.
        vmin: float = ticks[0]  # self.default_options["vmin"]
        vmax: float = ticks[-1]  # self.default_options["vmax"]

        if color_scale.lower() == "linear":
            im = ax.matshow(arr, cmap=cmap, vmin=vmin, vmax=vmax, extent=self.extent)
            cbar_kw = {"ticks": ticks}
        elif color_scale.lower() == "power":
            im = ax.matshow(
                arr,
                cmap=cmap,
                norm=colors.PowerNorm(
                    gamma=self.default_options["gamma"], vmin=vmin, vmax=vmax
                ),
                extent=self.extent,
            )
            cbar_kw = {"ticks": ticks}
        elif color_scale.lower() == "sym-lognorm":
            im = ax.matshow(
                arr,
                cmap=cmap,
                norm=colors.SymLogNorm(
                    linthresh=self.default_options["line_threshold"],
                    linscale=self.default_options["line_scale"],
                    base=np.e,
                    vmin=vmin,
                    vmax=vmax,
                ),
                extent=self.extent,
            )
            formatter = LogFormatter(10, labelOnlyBase=False)
            cbar_kw = {"ticks": ticks, "format": formatter}
        elif color_scale.lower() == "boundary-norm":
            if not self.default_options["bounds"]:
                bounds = ticks
                cbar_kw = {"ticks": ticks}
            else:
                bounds = self.default_options["bounds"]
                cbar_kw = {"ticks": self.default_options["bounds"]}
            norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
            im = ax.matshow(arr, cmap=cmap, norm=norm, extent=self.extent)
        elif color_scale.lower() == "midpoint":
            arr = arr.filled(np.nan)
            im = ax.matshow(
                arr,
                cmap=cmap,
                norm=MidpointNormalize(
                    midpoint=self.default_options["midpoint"],
                    vmin=vmin,
                    vmax=vmax,
                ),
                extent=self.extent,
            )
            cbar_kw = {"ticks": ticks}
        else:
            raise ValueError(
                f"Invalid color scale option: {color_scale}. Use 'linear', 'power', 'power-norm',"
                "'sym-lognorm', 'boundary-norm'"
            )

        return im, cbar_kw

    def apply_colormap(self, cmap: Union[Colormap, str]) -> np.ndarray:
        """Apply a matplotlib colormap to an array.

            Create an RGB channel from the given array using the given colormap.

        Parameters
        ----------
        cmap: Colormap/str
            colormap.

        Returns
        -------
        np.ndarray: 8-bit array
            the array with the colormap applied.

        Examples
        --------
        - Create an array and instantiate the `Array` object:
        ```python
        >>> import numpy as np
        >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> array = ArrayGlyph(arr)
        >>> rgb_array = array.apply_colormap("coolwarm_r")
        >>> print(rgb_array) # doctest: +SKIP
        [[[179   3  38]
          [221  96  76]
          [244 154 123]]
         [[244 196 173]
          [220 220 221]
          [183 207 249]]
         [[139 174 253]
          [ 96 128 232]
          [ 58  76 192]]]

        >>> print(rgb_array.dtype)
        uint8

        ```
        """
        colormap = plt.get_cmap(cmap) if isinstance(cmap, str) else cmap
        normed_data = (self.arr - self.arr.min()) / (self.arr.max() - self.arr.min())
        colored = colormap(normed_data)
        return (colored[:, :, :3] * 255).astype("uint8")

    def to_image(self, arr: np.ndarray = None) -> Image.Image:
        """Create an RGB image from an array.

            convert the array to an image.

        Parameters
        ----------
        arr: np.ndarray, default is None.
            array. if None, the array in the object will be used.

        Examples
        --------
        ```python
        >>> import numpy as np
        >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> array = ArrayGlyph(arr)
        >>> image = array.to_image()
        >>> print(image) # doctest: +SKIP
        <PIL.Image.Image image mode=RGB size=3x3 at 0x7F5E0D2F4C40>

        ```
        """
        if arr is None:
            arr = self.arr
        # This is done to scale the values between 0 and 255
        arr = arr if arr.dtype == "uint8" else self.scale_to_rgb()
        return Image.fromarray(arr).convert("RGB")

    def scale_to_rgb(self, arr: np.ndarray = None) -> np.ndarray:
        """Create an RGB image.

        Parameters
        ----------
        arr: np.ndarray, default is None.
            array. if None, the array in the object will be used.

        Examples
        --------
        ```python
        >>> import numpy as np
        >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> array = ArrayGlyph(arr)
        >>> rgb_array = array.scale_to_rgb()
        >>> print(rgb_array)
        [[28 56 85]
         [113 141 170]
         [198 226 255]]
        >>> print(rgb_array.dtype)
        uint8

        ```
        """
        if arr is None:
            arr = self.arr
        # This is done to scale the values between 0 and 255
        return (arr * 255 / arr.max()).astype("uint8")

    @staticmethod
    def _plot_text(
        ax: Axes, arr: np.ndarray, indices, default_options_dict: dict
    ) -> list:
        """plot values as a text in each cell.

        Parameters
        ----------
        ax:[matplotlib ax]
            matplotlib axes
        indices: [array]
            array with columns, (row, col)
        default_options_dict: Dict
            default options dictionary after updating the options.

        Returns
        -------
        list:
            list of the text object
        """
        # https://github.com/Serapieum-of-alex/cleopatra/issues/75
        # add text for the cell values
        add_text = lambda elem: ax.text(
            elem[1],
            elem[0],
            np.round(arr[elem[0], elem[1]], 2),
            ha="center",
            va="center",
            color="w",
            fontsize=default_options_dict["num_size"],
        )
        return list(map(add_text, indices))

    @staticmethod
    def _plot_point_values(ax, point_table: np.ndarray, pid_color, pid_size):
        write_points = lambda x: ax.text(
            x[2],
            x[1],
            x[0],
            ha="center",
            va="center",
            color=pid_color,
            fontsize=pid_size,
        )
        return list(map(write_points, point_table))

    def create_color_bar(self, ax: Axes, im: AxesImage, cbar_kw: dict) -> Colorbar:
        """Create Color bar.

        Parameters
        ----------
        ax: Axes
            matplotlib axes.
        im: AxesImage
            Image axes.
        cbar_kw: dict
            color bar keyword arguments.

        Returns
        -------
        Colorbar:
            colorbar object.
        """
        # im or cax is the last image added to the axes
        # im = ax.images[-1]
        cbar = ax.figure.colorbar(
            im,
            ax=ax,
            shrink=self.default_options["cbar_length"],
            orientation=self.default_options["cbar_orientation"],
            **cbar_kw,
        )
        # cbar.ax.set_ylabel(
        #     self.default_options["cbar_label"],
        #     rotation=self.default_options["cbar_label_rotation"],
        #     va=self.default_options["cbar_label_location"],
        #     fontsize=self.default_options["cbar_label_size"],
        # )
        cbar.ax.tick_params(labelsize=10)
        cbar.set_label(
            self.default_options["cbar_label"],
            fontsize=self.default_options["cbar_label_size"],
            loc=self.default_options["cbar_label_location"],
        )

        return cbar

    def plot(
        self,
        points: np.ndarray = None,
        point_color: str = "red",
        point_size: Union[int, float] = 100,
        pid_color="blue",
        pid_size: Union[int, float] = 10,
        **kwargs,
    ) -> Tuple[Figure, Axes]:
        """Plot the array with customizable visualization options.

        This method creates a visualization of the array with various customization options
        including color scales, color bars, cell value display, and point annotations.
        It supports both regular arrays and RGB arrays.

        Parameters
        ----------
        points : np.ndarray, optional
            Points to display on the array, by default None.
            Should be a 3-column array where:
            - First column: values to display for each point
            - Second column: row indices of the points in the array
            - Third column: column indices of the points in the array
        point_color : str, optional
            Color of the points, by default "red".
            Any valid matplotlib color string.
        point_size : Union[int, float], optional
            Size of the points, by default 100.
            Controls the marker size.
        pid_color : str, optional
            Color of the point value annotations, by default "blue".
            Any valid matplotlib color string.
        pid_size : Union[int, float], optional
            Size of the point value annotations, by default 10.
            Controls the font size of the annotations.
        **kwargs : dict
            Additional keyword arguments for customizing the plot.

            Plot appearance:
            ---------------
            title : str, optional
                Title of the plot, by default 'Array Plot'.
            title_size : int, optional
                Title font size, by default 15.
            cmap : str, optional
                Colormap name, by default 'coolwarm_r'.
            vmin : float, optional
                Minimum value for color scaling, by default min(array).
            vmax : float, optional
                Maximum value for color scaling, by default max(array).

            Color bar options:
            ----------------
            cbar_orientation : str, optional
                Orientation of the color bar, by default 'vertical'.
                Can be 'horizontal' or 'vertical'.
            cbar_label_rotation : float, optional
                Rotation angle of the color bar label, by default -90.
            cbar_label_location : str, optional
                Location of the color bar label, by default 'bottom'.
                Options: 'top', 'bottom', 'center', 'baseline', 'center_baseline'.
            cbar_length : float, optional
                Ratio to control the height/width of the color bar, by default 0.75.
            ticks_spacing : int, optional
                Spacing between ticks on the color bar, by default 2.
            cbar_label_size : int, optional
                Font size of the color bar label, by default 12.
            cbar_label : str, optional
                Label text for the color bar, by default 'Value'.

            Color scale options:
            ------------------
            color_scale : str, optional
                Type of color scaling to use, by default 'linear'.
                Options:
                - 'linear': Linear scale
                - 'power': Power-law normalization
                - 'sym-lognorm': Symmetrical logarithmic scale
                - 'boundary-norm': Discrete intervals based on boundaries
                - 'midpoint': Scale split at a specified midpoint
            gamma : float, optional
                Exponent for 'power' color scale, by default 0.5.
                Values < 1 emphasize lower values, values > 1 emphasize higher values.
            line_threshold : float, optional
                Threshold for 'sym-lognorm' color scale, by default 0.0001.
            line_scale : float, optional
                Scale factor for 'sym-lognorm' color scale, by default 0.001.
            bounds : List, optional
                Boundaries for 'boundary-norm' color scale, by default None.
                Defines the discrete intervals for color mapping.
            midpoint : float, optional
                Midpoint value for 'midpoint' color scale, by default 0.

            Cell value display options:
            -------------------------
            display_cell_value : bool, optional
                Whether to display the values of cells as text, by default False.
            num_size : int, optional
                Font size of the cell value text, by default 8.
            background_color_threshold : float, optional
                Threshold for cell value text color, by default None.
                If cell value > threshold, text is black; otherwise, text is white.
                If None, uses max(array)/2 as the threshold.

        Returns
        -------
        Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
            A tuple containing:
            - fig: The matplotlib Figure object
            - ax: The matplotlib Axes object

        Raises
        ------
        ValueError
            If an invalid keyword argument is provided.

        Examples
        --------
        - Basic array plot:

            ```python
            >>> import numpy as np
            >>> from cleopatra.array_glyph import ArrayGlyph
            >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
            >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Customized Plot", title_size=18)
            >>> fig, ax = array.plot()

            ```
        ![array-plot](./../_images/array_glyph/array-plot.png)

        - Color bar customization:

            - Create an array and instantiate the `Array` object with custom options.
                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Customized color bar", title_size=18)
                >>> fig, ax = array.plot(
                ...     cbar_orientation="horizontal",
                ...     cbar_label_rotation=-90,
                ...     cbar_label_location="center",
                ...     cbar_length=0.7,
                ...     cbar_label_size=12,
                ...     cbar_label="Discharge m3/s",
                ...     ticks_spacing=5,
                ...     color_scale="linear",
                ...     cmap="coolwarm_r",
                ... )

                ```
                ![color-bar-customization](./../_images/array_glyph/color-bar-customization.png)

        - Display values for each cell:

            - you can display the values for each cell by using thr parameter `display_cell_value`, and customize how
                the values are displayed using the parameter `background_color_threshold` and `num_size`.

                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Display array values", title_size=18)
                >>> fig, ax = array.plot(
                ...     display_cell_value=True,
                ...     num_size=12
                ... )

                ```
                ![display-cell-values](./../_images/array_glyph/display-cell-values.png)

        - Plot points at specific locations in the array:

            - you can display points in specific cells in the array and also display a value for each of these points.
                The point parameter takes an array with the first column as the values to be displayed on top of the
                points, the second and third columns are the row and column index of the point in the array.
            - The `point_color` and `point_size` parameters are used to customize the appearance of the points,
                while the `pid_color` and `pid_size` parameters are used to customize the appearance of the point
                IDs/text.

                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Display Points", title_size=14)
                >>> points = np.array([[1, 0, 0], [2, 1, 1], [3, 2, 2]])
                >>> fig, ax = array.plot(
                ...     points=points,
                ...     point_color="black",
                ...     point_size=100,
                ...     pid_color="orange",
                ...     pid_size=30,
                ... )

                ```
                ![display-points](./../_images/array_glyph/display-points.png)

        - Color scale customization:

            - Power scale (with different gamma values).

                - The default power scale uses a gamma value of 0.5.

                    ```python
                    >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale", title_size=18)
                    >>> fig, ax = array.plot(
                    ...     cbar_label="Discharge m3/s",
                    ...     color_scale="power",
                    ...     cmap="coolwarm_r",
                    ...     cbar_label_rotation=-90,
                    ... )

                    ```
                    ![power-scale](./../_images/array_glyph/power-scale.png)

                - change the gamma of 0.8 (emphasizes higher values less).

                    ```python
                    >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale - gamma=0.8", title_size=18)
                    >>> fig, ax = array.plot(
                    ...     color_scale="power",
                    ...     gamma=0.8,
                    ...     cmap="coolwarm_r",
                    ...     cbar_label_rotation=-90,
                    ...     cbar_label="Discharge m3/s",
                    ... )

                    ```
                    ![power-scale-gamma-0.8](./../_images/array_glyph/power-scale-gamma-0.8.png)

                - change the gamma of 0.1 (emphasizes higher values more).

                    ```python
                    >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale - gamma=0.1", title_size=18)
                    >>> fig, ax = array.plot(
                    ...     color_scale="power",
                    ...     gamma=0.1,
                    ...     cmap="coolwarm_r",
                    ...     cbar_label_rotation=-90,
                    ...     cbar_label="Discharge m3/s",
                    ... )

                    ```
                    ![power-scale-gamma-0.1](./../_images/array_glyph/power-scale-gamma-0.1.png)

            - Logarithmic scale.

                - the logarithmic scale uses to parameters `line_threshold` and `line_scale` with a default
                value if 0.0001, and 0.001 respectively.
                    ```python
                    >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Logarithmic scale", title_size=18)
                    >>> fig, ax = array.plot(
                    ...     cbar_label="Discharge m3/s",
                    ...     color_scale="sym-lognorm",
                    ...     cmap="coolwarm_r",
                    ...     cbar_label_rotation=-90,
                    ... )

                    ```
                    ![log-scale](./../_images/array_glyph/log-scale.png)

                - you can change the `line_threshold` and `line_scale` values.
                    ```python
                    >>> array = ArrayGlyph(
                    ...     arr, figsize=(6, 6), title="Logarithmic scale: Customized Parameter", title_size=12
                    ... )
                    >>> fig, ax = array.plot(
                    ...     cbar_label_rotation=-90,
                    ...     cbar_label="Discharge m3/s",
                    ...     color_scale="sym-lognorm",
                    ...     cmap="coolwarm_r",
                    ...     line_threshold=0.015,
                    ...     line_scale=0.1,
                    ... )

                    ```
                    ![log-scale](./../_images/array_glyph/log-scale-custom-parameters.png)

            - Defined boundary scale.
                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Defined boundary scale", title_size=18)
                >>> fig, ax = array.plot(
                ...     cbar_label_rotation=-90,
                ...     cbar_label="Discharge m3/s",
                ...     color_scale="boundary-norm",
                ...     cmap="coolwarm_r",
                ... )

                ```
                ![boundary-scale](./../_images/array_glyph/boundary-scale.png)

                - You can also define the boundaries.
                    ```python
                    >>> array = ArrayGlyph(
                    ...     arr, figsize=(6, 6), title="Defined boundary scale: defined bounds", title_size=18
                    ... )
                    >>> bounds = [0, 5, 10]
                    >>> fig, ax = array.plot(
                    ...     cbar_label_rotation=-90,
                    ...     cbar_label="Discharge m3/s",
                    ...     color_scale="boundary-norm",
                    ...     bounds=bounds,
                    ...     cmap="coolwarm_r",
                    ... )

                    ```
                    ![boundary-scale-defined-bounds](./../_images/array_glyph/boundary-scale-defined-bounds.png)

            - Midpoint scale.

                in the midpoint scale you can define a value that splits the scale into half.
                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Midpoint scale", title_size=18)
                >>> fig, ax = array.plot(
                ...     cbar_label_rotation=-90,
                ...     cbar_label="Discharge m3/s",
                ...     color_scale="midpoint",
                ...     cmap="coolwarm_r",
                ...     midpoint=2,
                ... )

                ```
                ![midpoint-scale-costom-parameters](./../_images/array_glyph/midpoint-scale-costom-parameters.png)
        """
        for key, val in kwargs.items():
            if key not in self.default_options.keys():
                raise ValueError(
                    f"The given keyword argument:{key} is not correct, possible parameters are,"
                    f" {DEFAULT_OPTIONS}"
                )
            else:
                self.default_options[key] = val

        if self.fig is None:
            self.fig, self.ax = self.create_figure_axes()

        arr = self.arr
        fig, ax = self.fig, self.ax

        if self.rgb:
            ax.imshow(arr, extent=self.extent)
        else:
            # if user did not input ticks spacing use the calculated one.
            if "ticks_spacing" in kwargs.keys():
                self.default_options["ticks_spacing"] = kwargs["ticks_spacing"]
            else:
                self.default_options["ticks_spacing"] = self.ticks_spacing

            if "vmin" in kwargs.keys():
                self.default_options["vmin"] = kwargs["vmin"]
            else:
                self.default_options["vmin"] = self.vmin

            if "vmax" in kwargs.keys():
                self.default_options["vmax"] = kwargs["vmax"]
            else:
                self.default_options["vmax"] = self.vmax

            # creating the ticks/bounds
            ticks = self.get_ticks()
            im, cbar_kw = self._plot_im_get_cbar_kw(ax, arr, ticks)

            # Create colorbar
            self.create_color_bar(ax, im, cbar_kw)

        ax.set_title(
            self.default_options["title"], fontsize=self.default_options["title_size"]
        )

        if self.extent is None:
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.set_xticks([])
            ax.set_yticks([])

        optional_display = {}
        if self.default_options["display_cell_value"]:
            indices = get_indices2(arr, [np.nan])
            optional_display["cell_text_value"] = self._plot_text(
                ax, arr, indices, self.default_options
            )

        if points is not None:
            row = points[:, 1]
            col = points[:, 2]
            optional_display["points_scatter"] = ax.scatter(
                col, row, color=point_color, s=point_size
            )
            optional_display["points_id"] = self._plot_point_values(
                ax, points, pid_color, pid_size
            )

        # # Normalize the threshold to the image color range.
        # if self.default_options["background_color_threshold"] is not None:
        #     im.norm(self.default_options["background_color_threshold"])
        # else:
        #     im.norm(self.vmax) / 2.0
        plt.show()
        return fig, ax

    def adjust_ticks(
        self,
        axis: str,
        multiply_value: Union[float, int] = 1,
        add_value: Union[float, int] = 0,
        fmt: str = "{0:g}",
        visible: bool = True,
    ):
        """Adjust the ticks of the axes.

        Parameters
        ----------
        axis: str
            x or y.
        multiply_value: Union[float, int]
            value to be multiplied.
        add_value: Union[float, int]
            value to be added.
        fmt: str, default is "{0:g}".
            format of the ticks.
            - 123.456 with the format "{0:f}" will give '123.456000'.
            - 123.456 with the format "{0:.2f}" will give '123.46'.
            - 123456.789 with the format "{0:e}" will give '1.234568e+05'.
            - 123456.789 with the format "{0:.2e}" will give '1.23e+05'.
            - 123456.789 with the format "{0:g}" will give '123457'.
            - 123456.789 with the format "{0:.2g}" will give '1.2e+05'.
            - 123 with the format "{0:d}" will give '123'.
         visible: bool, optional, default is True.
            Whether the ticks are visible or not.

        Returns
        -------
        None

        Examples
        --------
        - Create an array and instantiate the `ArrayGlyph` object:
            ```python
            >>> import numpy as np
            >>> arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
            >>> extent = [34.62, 34.65, 31.82, 31.85]
            >>> my_glyph = ArrayGlyph(arr, extent=extent)
            >>> fig, ax = my_glyph.plot()

            ```
            ![adjust_tick](./../_images/array_glyph/adjust_tick.png)

        - Adjust the ticks of the x-axis:
            ```python
            >>> my_glyph.adjust_ticks(axis='x', multiply_value=0.01, add_value=34.62, fmt="{0:.2f}")

            ```
            ![adjust_tick](./../_images/array_glyph/adjust_tick-x.png)

        - Adjust the ticks of the y-axis:
            ```python
            >>> my_glyph.adjust_ticks(axis='y', multiply_value=0.01, add_value=31.82, fmt="{0:.2e}")

            ```
            ![adjust_tick-y](./../_images/array_glyph/adjust_tick-y.png)
        """
        if axis == "x":
            ticks_x = ticker.FuncFormatter(
                lambda x, pos: fmt.format(x * multiply_value + add_value)
            )
            self.ax.xaxis.set_major_formatter(ticks_x)
        else:
            ticks_y = ticker.FuncFormatter(
                lambda y, pos: fmt.format(y * multiply_value + add_value)
            )
            self.ax.yaxis.set_major_formatter(ticks_y)

        if not visible:
            if axis == "x":
                self.ax.get_xaxis().set_visible(visible)
            else:
                self.ax.get_yaxis().set_visible(visible)

        plt.show()

    def animate(
        self,
        time: List[Any],
        points: np.ndarray = None,
        text_colors=("white", "black"),
        interval=200,
        text_loc: list[Any, Any] = None,
        point_color="red",
        point_size=100,
        pid_color="blue",
        pid_size=10,
        **kwargs,
    ):
        """Create an animation from a 3D array.

        This method creates an animation by iterating through the first dimension of a 3D array.
        Each slice of the array becomes a frame in the animation, with optional time labels,
        point annotations, and cell value displays.

        Parameters
        ----------
        time : List[Any]
            A list containing labels for each frame in the animation.
            These could be timestamps, frame numbers, or any other identifiers.
            The length of this list should match the first dimension of the array.
        points : np.ndarray, optional
            Points to display on the array, by default None.
            Should be a 3-column array where:
            - First column: values to display for each point
            - Second column: row indices of the points in the array
            - Third column: column indices of the points in the array
        text_colors : Tuple[str, str], optional
            Two colors to be used for cell value text, by default ("white", "black").
            The first color is used when the cell value is below the background_color_threshold,
            and the second color is used when the cell value is above the threshold.
        interval : int, optional
            Delay between frames in milliseconds, by default 200.
            Controls the speed of the animation (smaller values = faster animation).
        text_loc : list[Any, Any], optional
            Location of the time label text as [x, y] coordinates, by default None.
            If None, defaults to [0.1, 0.2].
        point_color : str, optional
            Color of the points, by default "red".
            Any valid matplotlib color string.
        point_size : int, optional
            Size of the points, by default 100.
            Controls the marker size.
        pid_color : str, optional
            Color of the point value annotations, by default "blue".
            Any valid matplotlib color string.
        pid_size : int, optional
            Size of the point value annotations, by default 10.
            Controls the font size of the annotations.
        **kwargs : dict
            Additional keyword arguments for customizing the animation.

            Plot appearance:
            ---------------
            title : str, optional
                Title of the plot, by default 'Array Plot'.
            title_size : int, optional
                Title font size, by default 15.
            cmap : str, optional
                Colormap name, by default 'coolwarm_r'.
            vmin : float, optional
                Minimum value for color scaling, by default min(array).
            vmax : float, optional
                Maximum value for color scaling, by default max(array).

            Color bar options:
            ----------------
            cbar_orientation : str, optional
                Orientation of the color bar, by default 'vertical'.
                Can be 'horizontal' or 'vertical'.
            cbar_label_rotation : float, optional
                Rotation angle of the color bar label, by default -90.
            cbar_label_location : str, optional
                Location of the color bar label, by default 'bottom'.
                Options: 'top', 'bottom', 'center', 'baseline', 'center_baseline'.
            cbar_length : float, optional
                Ratio to control the height/width of the color bar, by default 0.75.
            ticks_spacing : int, optional
                Spacing between ticks on the color bar, by default 2.
            cbar_label_size : int, optional
                Font size of the color bar label, by default 12.
            cbar_label : str, optional
                Label text for the color bar, by default 'Value'.

            Color scale options:
            ------------------
            color_scale : str, optional
                Type of color scaling to use, by default 'linear'.
                Options:
                - 'linear': Linear scale
                - 'power': Power-law normalization
                - 'sym-lognorm': Symmetrical logarithmic scale
                - 'boundary-norm': Discrete intervals based on boundaries
                - 'midpoint': Scale split at a specified midpoint
            gamma : float, optional
                Exponent for 'power' color scale, by default 0.5.
                Values < 1 emphasize lower values, values > 1 emphasize higher values.
            line_threshold : float, optional
                Threshold for 'sym-lognorm' color scale, by default 0.0001.
            line_scale : float, optional
                Scale factor for 'sym-lognorm' color scale, by default 0.001.
            bounds : List, optional
                Boundaries for 'boundary-norm' color scale, by default None.
                Defines the discrete intervals for color mapping.
            midpoint : float, optional
                Midpoint value for 'midpoint' color scale, by default 0.

            Cell value display options:
            -------------------------
            display_cell_value : bool, optional
                Whether to display the values of cells as text, by default False.
            num_size : int, optional
                Font size of the cell value text, by default 8.
            background_color_threshold : float, optional
                Threshold for cell value text color, by default None.
                If cell value > threshold, text is black; otherwise, text is white.
                If None, uses max(array)/2 as the threshold.

        Returns
        -------
        matplotlib.animation.FuncAnimation
            The animation object that can be displayed in a notebook or saved to a file.

        Raises
        ------
        ValueError
            If an invalid keyword argument is provided.
        ValueError
            If the length of the time list doesn't match the first dimension of the array.

        Notes
        -----
        The animation is created by iterating through the first dimension of the array.
        For example, if the array has shape (10, 20, 30), the animation will have 10 frames,
        each showing a 20x30 slice of the array.

        To display the animation in a Jupyter notebook, you may need to use:
        ```python
        from IPython.display import HTML
        HTML(anim_obj.to_jshtml())
        ```

        To save the animation to a file, use the `save_animation` method after creating
        the animation.

        Examples
        --------
        Basic animation from a 3D array:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> # Create a 3D array with 5 frames, each 10x10
        >>> arr = np.random.randint(1, 10, size=(5, 10, 10))
        >>> # Create labels for each frame
        >>> frame_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
        >>> # Create the ArrayGlyph object
        >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
        >>> # Create the animation
        >>> anim_obj = animated_array.animate(frame_labels)

        ```
        Animation with custom interval (speed):
        ```python
        >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
        >>> # Slower animation (500ms between frames)
        >>> anim_obj = animated_array.animate(frame_labels, interval=500)
        >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
        >>> # Faster animation (100ms between frames)
        >>> anim_obj = animated_array.animate(frame_labels, interval=100)

        ```
        Animation with points:
        ```python
        >>> # Create points to display on the animation
        >>> points = np.array([[1, 2, 3], [2, 5, 5], [3, 8, 8]])
        >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
        >>> anim_obj = animated_array.animate(
        ...     frame_labels,
        ...     points=points,
        ...     point_color="black",
        ...     point_size=150,
        ...     pid_color="white",
        ...     pid_size=12
        ... )

        ```
        Animation with cell values displayed:
        ```python
        >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
        >>> anim_obj = animated_array.animate(
        ...     frame_labels,
        ...     display_cell_value=True,
        ...     num_size=10,
        ...     text_colors=("yellow", "blue")
        ... )

        ```
        ![animated_array](./../_images/array_glyph/animated_array.gif)

        Saving the animation to a file:
        ```python
        >>> # Create the animation first
        >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
        >>> anim_obj = animated_array.animate(frame_labels)
        >>> # Then save it to a file
        >>> animated_array.save_animation("animation.gif", fps=2)

        ```
        """
        if text_loc is None:
            text_loc = [0.1, 0.2]

        for key, val in kwargs.items():
            if key not in self.default_options.keys():
                raise ValueError(
                    f"The given keyword argument:{key} is not correct, possible parameters are,"
                    f" {DEFAULT_OPTIONS}"
                )
            else:
                self.default_options[key] = val

        # if user did not input ticks spacing use the calculated one.
        if "ticks_spacing" in kwargs.keys():
            self.default_options["ticks_spacing"] = kwargs["ticks_spacing"]
        else:
            self.default_options["ticks_spacing"] = self.ticks_spacing

        if "vmin" in kwargs.keys():
            self.default_options["vmin"] = kwargs["vmin"]
        else:
            self.default_options["vmin"] = self.vmin

        if "vmax" in kwargs.keys():
            self.default_options["vmax"] = kwargs["vmax"]
        else:
            self.default_options["vmax"] = self.vmax

        # if optional_display
        precision = self.default_options["precision"]
        array = self.arr

        if self.fig is None:
            self.fig, self.ax = self.create_figure_axes()

        fig, ax = self.fig, self.ax

        ticks = self.get_ticks()
        im, cbar_kw = self._plot_im_get_cbar_kw(ax, array[0, :, :], ticks)

        # Create colorbar
        cbar = ax.figure.colorbar(
            im,
            ax=ax,
            shrink=self.default_options["cbar_length"],
            orientation=self.default_options["cbar_orientation"],
            **cbar_kw,
        )
        cbar.ax.set_ylabel(
            self.default_options["cbar_label"],
            rotation=self.default_options["cbar_label_rotation"],
            va=self.default_options["cbar_label_location"],
            fontsize=self.default_options["cbar_label_size"],
        )
        cbar.ax.tick_params(labelsize=10)

        ax.set_title(
            self.default_options["title"], fontsize=self.default_options["title_size"]
        )
        ax.set_xticklabels([])
        ax.set_yticklabels([])

        ax.set_xticks([])
        ax.set_yticks([])

        if self.default_options["display_cell_value"]:
            indices = get_indices2(array[0, :, :], [np.nan])
            cell_text_value = self._plot_text(
                ax, array[0, :, :], indices, self.default_options
            )
            indices = np.array(indices)

        if points is not None:
            row = points[:, 1]
            col = points[:, 2]
            points_scatter = ax.scatter(col, row, color=point_color, s=point_size)
            points_id = self._plot_point_values(ax, points, pid_color, pid_size)

        # Normalize the threshold to the image color range.
        if self.default_options["background_color_threshold"] is not None:
            background_color_threshold = im.norm(
                self.default_options["background_color_threshold"]
            )
        else:
            background_color_threshold = im.norm(np.nanmax(array)) / 2.0

        day_text = ax.text(
            text_loc[0],
            text_loc[1],
            " ",
            fontsize=self.default_options["cbar_label_size"],
        )

        def init():
            """initialize the plot with the first array"""
            im.set_data(array[0, :, :])
            day_text.set_text("")
            output = [im, day_text]

            if points is not None:
                points_scatter.set_offsets(np.c_[col, row])
                output.append(points_scatter)
                update_points = lambda x: points_id[x].set_text(points[x, 0])
                list(map(update_points, range(len(col))))

                output += points_id

            if self.default_options["display_cell_value"]:
                vals = array[0, indices[:, 0], indices[:, 1]]
                update_cell_value = lambda x: cell_text_value[x].set_text(vals[x])
                list(map(update_cell_value, range(self.no_elem)))
                output += cell_text_value

            return output

        def animate_a(i):
            """plot for each element in the iterable."""
            im.set_data(array[i, :, :])
            day_text.set_text("Date = " + str(time[i])[0:10])
            output = [im, day_text]

            if points is not None:
                points_scatter.set_offsets(np.c_[col, row])
                output.append(points_scatter)

                for x in range(len(col)):
                    points_id[x].set_text(points[x, 0])

                output += points_id

            if self.default_options["display_cell_value"]:
                vals = array[i, indices[:, 0], indices[:, 1]]

                def update_cell_value(x):
                    """Update cell value"""
                    val = round(vals[x], precision)
                    kw = {
                        "color": text_colors[
                            int(im.norm(vals[x]) > background_color_threshold)
                        ]
                    }
                    cell_text_value[x].update(kw)
                    cell_text_value[x].set_text(val)

                list(map(update_cell_value, range(self.no_elem)))

                output += cell_text_value

            return output

        plt.tight_layout()
        anim = FuncAnimation(
            fig,
            animate_a,
            init_func=init,
            frames=np.shape(array)[0],
            interval=interval,
            blit=True,
        )
        self._anim = anim
        plt.show()
        return anim

    def save_animation(self, path: str, fps: int = 2):
        """Save the animation to a file.

        This method saves the animation created by the `animate` method to a file.
        The format of the output file is determined by the file extension in the path.

        Parameters
        ----------
        path : str
            The file path where the animation will be saved.
            The file extension determines the output format.
            Supported formats: gif, mov, avi, mp4.
        fps : int, optional
            Frames per second for the saved animation, by default 2.
            Higher values create faster animations, lower values create slower animations.

        Raises
        ------
        ValueError
            If the file extension is not one of the supported formats.
        FileNotFoundError
            If FFmpeg is not installed (required for mov, avi, and mp4 formats).

        Notes
        -----
        - For GIF format, the PillowWriter is used.
        - For MOV, AVI, and MP4 formats, FFMpegWriter is used, which requires FFmpeg to be installed.
        - You can download FFmpeg from https://ffmpeg.org/

        Examples
        --------
        Save an animation as a GIF file:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> # Create a 3D array with 5 frames, each 10x10
        >>> arr = np.random.randint(1, 10, size=(5, 10, 10))
        >>> frame_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
        >>> animated_array = ArrayGlyph(arr)
        >>> anim_obj = animated_array.animate(frame_labels)
        >>> animated_array.save_animation("animation.gif") # doctest: +SKIP

        ```
        Save with a higher frame rate for a faster animation:
        ```python
        >>> animated_array.save_animation("animation.gif", fps=5) # doctest: +SKIP

        ```
        Save in MP4 format (requires FFmpeg):
        ```python
        >>> animated_array.save_animation("animation.mp4", fps=10) # doctest: +SKIP

        ```
        """
        video_format = path.split(".")[-1]
        if video_format not in SUPPORTED_VIDEO_FORMAT:
            raise ValueError(
                f"The given extension {video_format} implies a format that is not supported, "
                f"only {SUPPORTED_VIDEO_FORMAT} are supported"
            )

        if video_format == "gif":
            writer_gif = animation.PillowWriter(fps=fps)
            self.anim.save(path, writer=writer_gif)
        else:
            try:
                if video_format == "avi" or video_format == "mov":
                    writer_video = animation.FFMpegWriter(fps=fps, bitrate=1800)
                    self.anim.save(path, writer=writer_video)
                elif video_format == "mp4":
                    writer_mp4 = animation.FFMpegWriter(fps=fps, bitrate=1800)
                    self.anim.save(path, writer=writer_mp4)
            except FileNotFoundError:
                print(
                    "Please visit https://ffmpeg.org/ and download a version of ffmpeg compatible with your operating"
                    "system, for more details please check the method definition"
                )

anim property #

Animation function

default_options property #

Default plot options

vmax property #

max value in the array

vmin property #

min value in the array

__init__(array, exclude_value=np.nan, extent=None, rgb=None, surface_reflectance=None, cutoff=None, ax=None, fig=None, percentile=None, **kwargs) #

Initialize the ArrayGlyph object with an array and optional parameters.

Parameters:

Name Type Description Default
array ndarray

The array to be visualized. Can be a 2D array for single plots or a 3D array for RGB plots or animations.

required
exclude_value List or numeric

Value(s) used to mask cells out of the domain, by default np.nan. Can be a single value or a list of values to exclude.

nan
extent List

The extent of the array in the format [xmin, ymin, xmax, ymax], by default None. If provided, the array will be plotted with these spatial boundaries.

None
rgb List[int]

The indices of the red, green, and blue bands in the given array, by default None. If provided, the array will be treated as an RGB image. Can be a list of three values [r, g, b], or four values if alpha band is included [r, g, b, a].

None
surface_reflectance int

Surface reflectance value for normalizing satellite data, by default None. Typically 10000 for Sentinel-2 data.

None
cutoff List

Clip the range of pixel values for each band, by default None. Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1. Should be a list with one value per band.

None
ax Axes

A pre-existing axes to plot on, by default None. If None, a new axes will be created.

None
fig Figure

A pre-existing figure to plot on, by default None. If None, a new figure will be created.

None
percentile int

The percentile value to be used for scaling the array values, by default None. Used to enhance contrast by stretching the histogram.

None
**kwargs dict

Additional keyword arguments for customizing the plot. Supported arguments include: figsize : tuple, optional Figure size, by default (8, 8). vmin : float, optional Minimum value for color scaling, by default min(array). vmax : float, optional Maximum value for color scaling, by default max(array). title : str, optional Title of the plot, by default 'Array Plot'. title_size : int, optional Title font size, by default 15. cmap : str, optional Colormap name, by default 'coolwarm_r'.

{}

Raises:

Type Description
ValueError

If an invalid keyword argument is provided.

ValueError

If rgb is provided but the array doesn't have enough dimensions.

Examples:

Basic initialization with a 2D array:

>>> import numpy as np
>>> from cleopatra.array_glyph import ArrayGlyph
>>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> array_glyph = ArrayGlyph(arr)
>>> fig, ax = array_glyph.plot()
Initialization with custom figure size and title:
>>> array_glyph = ArrayGlyph(arr, figsize=(10, 8), title="Custom Array Plot")
>>> fig, ax = array_glyph.plot()
Initialization with RGB bands from a 3D array:
>>> rgb_array = np.random.randint(0, 255, size=(3, 10, 10))
>>> rgb_glyph = ArrayGlyph(rgb_array, rgb=[0, 1, 2], surface_reflectance=255)
>>> fig, ax = rgb_glyph.plot()
Initialization with custom extent:
>>> array_glyph = ArrayGlyph(arr, extent=[0, 0, 10, 10])
>>> fig, ax = array_glyph.plot()

Source code in cleopatra/array_glyph.py
def __init__(
    self,
    array: np.ndarray,
    exclude_value: List = np.nan,
    extent: List = None,
    rgb: List[int] = None,
    surface_reflectance: int = None,
    cutoff: List = None,
    ax: Axes = None,
    fig: Figure = None,
    percentile: int = None,
    **kwargs,
):
    """Initialize the ArrayGlyph object with an array and optional parameters.

    Parameters
    ----------
    array : np.ndarray
        The array to be visualized. Can be a 2D array for single plots or a 3D array for RGB plots or animations.
    exclude_value : List or numeric, optional
        Value(s) used to mask cells out of the domain, by default np.nan.
        Can be a single value or a list of values to exclude.
    extent : List, optional
        The extent of the array in the format [xmin, ymin, xmax, ymax], by default None.
        If provided, the array will be plotted with these spatial boundaries.
    rgb : List[int], optional
        The indices of the red, green, and blue bands in the given array, by default None.
        If provided, the array will be treated as an RGB image.
        Can be a list of three values [r, g, b], or four values if alpha band is included [r, g, b, a].
    surface_reflectance : int, optional
        Surface reflectance value for normalizing satellite data, by default None.
        Typically 10000 for Sentinel-2 data.
    cutoff : List, optional
        Clip the range of pixel values for each band, by default None.
        Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1.
        Should be a list with one value per band.
    ax : matplotlib.axes.Axes, optional
        A pre-existing axes to plot on, by default None.
        If None, a new axes will be created.
    fig : matplotlib.figure.Figure, optional
        A pre-existing figure to plot on, by default None.
        If None, a new figure will be created.
    percentile : int, optional
        The percentile value to be used for scaling the array values, by default None.
        Used to enhance contrast by stretching the histogram.
    **kwargs : dict
        Additional keyword arguments for customizing the plot.
        Supported arguments include:
            figsize : tuple, optional
                Figure size, by default (8, 8).
            vmin : float, optional
                Minimum value for color scaling, by default min(array).
            vmax : float, optional
                Maximum value for color scaling, by default max(array).
            title : str, optional
                Title of the plot, by default 'Array Plot'.
            title_size : int, optional
                Title font size, by default 15.
            cmap : str, optional
                Colormap name, by default 'coolwarm_r'.

    Raises
    ------
    ValueError
        If an invalid keyword argument is provided.
    ValueError
        If rgb is provided but the array doesn't have enough dimensions.

    Examples
    --------
    Basic initialization with a 2D array:
    ```python
    >>> import numpy as np
    >>> from cleopatra.array_glyph import ArrayGlyph
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array_glyph = ArrayGlyph(arr)
    >>> fig, ax = array_glyph.plot()

    ```
    Initialization with custom figure size and title:
    ```python
    >>> array_glyph = ArrayGlyph(arr, figsize=(10, 8), title="Custom Array Plot")
    >>> fig, ax = array_glyph.plot()

    ```
    Initialization with RGB bands from a 3D array:
    ```python
    >>> rgb_array = np.random.randint(0, 255, size=(3, 10, 10))
    >>> rgb_glyph = ArrayGlyph(rgb_array, rgb=[0, 1, 2], surface_reflectance=255)
    >>> fig, ax = rgb_glyph.plot()

    ```
    Initialization with custom extent:
    ```python
    >>> array_glyph = ArrayGlyph(arr, extent=[0, 0, 10, 10])
    >>> fig, ax = array_glyph.plot()

    ```
    """
    self._default_options = DEFAULT_OPTIONS.copy()

    for key, val in kwargs.items():
        if key not in self.default_options.keys():
            raise ValueError(
                f"The given keyword argument:{key} is not correct, possible parameters are,"
                f" {DEFAULT_OPTIONS}"
            )
        else:
            self.default_options[key] = val
    # first replace the no_data_value by nan
    # convert the array to float32 to be able to replace the no data value with nan
    if exclude_value is not np.nan:
        if len(exclude_value) > 1:
            mask = np.logical_or(
                np.isclose(array, exclude_value[0], rtol=0.001),
                np.isclose(array, exclude_value[1], rtol=0.001),
            )
        else:
            mask = np.isclose(array, exclude_value[0], rtol=0.0000001)
        array = ma.array(array, mask=mask, dtype=array.dtype)
    else:
        array = ma.array(array)

    # convert the extent from [xmin, ymin, xmax, ymax] to [xmin, xmax, ymin, ymax] as required by matplotlib.
    if extent is not None:
        extent = [extent[0], extent[2], extent[1], extent[3]]
    self.extent = extent

    if rgb is not None:
        self.rgb = True
        # prepare to plot rgb plot only if there are three arrays
        if array.shape[0] < 3:
            raise ValueError(
                f"To plot RGB plot the given array should have only 3 arrays, given array have "
                f"{array.shape[0]}"
            )
        else:
            array = self.prepare_array(
                array,
                rgb=rgb,
                surface_reflectance=surface_reflectance,
                cutoff=cutoff,
                percentile=percentile,
            )
    else:
        self.rgb = False

    self._exclude_value = exclude_value

    self._vmax = (
        np.nanmax(array) if kwargs.get("vmax") is None else kwargs.get("vmax")
    )
    self._vmin = (
        np.nanmin(array) if kwargs.get("vmin") is None else kwargs.get("vmin")
    )

    self._arr = array
    # get the tick spacing that has 10 ticks only
    self.ticks_spacing = (self._vmax - self._vmin) / 10
    shape = array.shape
    if len(shape) == 3:
        no_elem = array[0, :, :].count()
    else:
        no_elem = array.count()

    self.no_elem = no_elem

    if fig is not None:
        self.fig, self.ax = fig, ax
    else:
        self.fig = None

__str__() #

String representation of the Array object.

Source code in cleopatra/array_glyph.py
def __str__(self):
    """String representation of the Array object."""
    message = f"""
                Min: {self.vmin}
                Max: {self.vmax}
                Exclude values: {self.exclude_value}
                RGB: {self.rgb}
            """
    return message

adjust_ticks(axis, multiply_value=1, add_value=0, fmt='{0:g}', visible=True) #

Adjust the ticks of the axes.

Parameters:

Name Type Description Default
axis str

x or y.

required
multiply_value Union[float, int]

value to be multiplied.

1
add_value Union[float, int]

value to be added.

0
fmt str

format of the ticks. - 123.456 with the format "{0:f}" will give '123.456000'. - 123.456 with the format "{0:.2f}" will give '123.46'. - 123456.789 with the format "{0:e}" will give '1.234568e+05'. - 123456.789 with the format "{0:.2e}" will give '1.23e+05'. - 123456.789 with the format "{0:g}" will give '123457'. - 123456.789 with the format "{0:.2g}" will give '1.2e+05'. - 123 with the format "{0:d}" will give '123'. visible: bool, optional, default is True. Whether the ticks are visible or not.

'{0:g}'

Returns:

Type Description
None

Examples:

  • Create an array and instantiate the ArrayGlyph object:

    >>> import numpy as np
    >>> arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
    >>> extent = [34.62, 34.65, 31.82, 31.85]
    >>> my_glyph = ArrayGlyph(arr, extent=extent)
    >>> fig, ax = my_glyph.plot()
    
    adjust_tick

  • Adjust the ticks of the x-axis:

    >>> my_glyph.adjust_ticks(axis='x', multiply_value=0.01, add_value=34.62, fmt="{0:.2f}")
    
    adjust_tick

  • Adjust the ticks of the y-axis:

    >>> my_glyph.adjust_ticks(axis='y', multiply_value=0.01, add_value=31.82, fmt="{0:.2e}")
    
    adjust_tick-y

Source code in cleopatra/array_glyph.py
def adjust_ticks(
    self,
    axis: str,
    multiply_value: Union[float, int] = 1,
    add_value: Union[float, int] = 0,
    fmt: str = "{0:g}",
    visible: bool = True,
):
    """Adjust the ticks of the axes.

    Parameters
    ----------
    axis: str
        x or y.
    multiply_value: Union[float, int]
        value to be multiplied.
    add_value: Union[float, int]
        value to be added.
    fmt: str, default is "{0:g}".
        format of the ticks.
        - 123.456 with the format "{0:f}" will give '123.456000'.
        - 123.456 with the format "{0:.2f}" will give '123.46'.
        - 123456.789 with the format "{0:e}" will give '1.234568e+05'.
        - 123456.789 with the format "{0:.2e}" will give '1.23e+05'.
        - 123456.789 with the format "{0:g}" will give '123457'.
        - 123456.789 with the format "{0:.2g}" will give '1.2e+05'.
        - 123 with the format "{0:d}" will give '123'.
     visible: bool, optional, default is True.
        Whether the ticks are visible or not.

    Returns
    -------
    None

    Examples
    --------
    - Create an array and instantiate the `ArrayGlyph` object:
        ```python
        >>> import numpy as np
        >>> arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
        >>> extent = [34.62, 34.65, 31.82, 31.85]
        >>> my_glyph = ArrayGlyph(arr, extent=extent)
        >>> fig, ax = my_glyph.plot()

        ```
        ![adjust_tick](./../_images/array_glyph/adjust_tick.png)

    - Adjust the ticks of the x-axis:
        ```python
        >>> my_glyph.adjust_ticks(axis='x', multiply_value=0.01, add_value=34.62, fmt="{0:.2f}")

        ```
        ![adjust_tick](./../_images/array_glyph/adjust_tick-x.png)

    - Adjust the ticks of the y-axis:
        ```python
        >>> my_glyph.adjust_ticks(axis='y', multiply_value=0.01, add_value=31.82, fmt="{0:.2e}")

        ```
        ![adjust_tick-y](./../_images/array_glyph/adjust_tick-y.png)
    """
    if axis == "x":
        ticks_x = ticker.FuncFormatter(
            lambda x, pos: fmt.format(x * multiply_value + add_value)
        )
        self.ax.xaxis.set_major_formatter(ticks_x)
    else:
        ticks_y = ticker.FuncFormatter(
            lambda y, pos: fmt.format(y * multiply_value + add_value)
        )
        self.ax.yaxis.set_major_formatter(ticks_y)

    if not visible:
        if axis == "x":
            self.ax.get_xaxis().set_visible(visible)
        else:
            self.ax.get_yaxis().set_visible(visible)

    plt.show()

animate(time, points=None, text_colors=('white', 'black'), interval=200, text_loc=None, point_color='red', point_size=100, pid_color='blue', pid_size=10, **kwargs) #

Create an animation from a 3D array.

This method creates an animation by iterating through the first dimension of a 3D array. Each slice of the array becomes a frame in the animation, with optional time labels, point annotations, and cell value displays.

Parameters:

Name Type Description Default
time List[Any]

A list containing labels for each frame in the animation. These could be timestamps, frame numbers, or any other identifiers. The length of this list should match the first dimension of the array.

required
points ndarray

Points to display on the array, by default None. Should be a 3-column array where: - First column: values to display for each point - Second column: row indices of the points in the array - Third column: column indices of the points in the array

None
text_colors Tuple[str, str]

Two colors to be used for cell value text, by default ("white", "black"). The first color is used when the cell value is below the background_color_threshold, and the second color is used when the cell value is above the threshold.

('white', 'black')
interval int

Delay between frames in milliseconds, by default 200. Controls the speed of the animation (smaller values = faster animation).

200
text_loc list[Any, Any]

Location of the time label text as [x, y] coordinates, by default None. If None, defaults to [0.1, 0.2].

None
point_color str

Color of the points, by default "red". Any valid matplotlib color string.

'red'
point_size int

Size of the points, by default 100. Controls the marker size.

100
pid_color str

Color of the point value annotations, by default "blue". Any valid matplotlib color string.

'blue'
pid_size int

Size of the point value annotations, by default 10. Controls the font size of the annotations.

10
**kwargs dict

Additional keyword arguments for customizing the animation.

Plot appearance:#

title : str, optional Title of the plot, by default 'Array Plot'. title_size : int, optional Title font size, by default 15. cmap : str, optional Colormap name, by default 'coolwarm_r'. vmin : float, optional Minimum value for color scaling, by default min(array). vmax : float, optional Maximum value for color scaling, by default max(array).

Color bar options:#

cbar_orientation : str, optional Orientation of the color bar, by default 'vertical'. Can be 'horizontal' or 'vertical'. cbar_label_rotation : float, optional Rotation angle of the color bar label, by default -90. cbar_label_location : str, optional Location of the color bar label, by default 'bottom'. Options: 'top', 'bottom', 'center', 'baseline', 'center_baseline'. cbar_length : float, optional Ratio to control the height/width of the color bar, by default 0.75. ticks_spacing : int, optional Spacing between ticks on the color bar, by default 2. cbar_label_size : int, optional Font size of the color bar label, by default 12. cbar_label : str, optional Label text for the color bar, by default 'Value'.

Color scale options:#

color_scale : str, optional Type of color scaling to use, by default 'linear'. Options: - 'linear': Linear scale - 'power': Power-law normalization - 'sym-lognorm': Symmetrical logarithmic scale - 'boundary-norm': Discrete intervals based on boundaries - 'midpoint': Scale split at a specified midpoint gamma : float, optional Exponent for 'power' color scale, by default 0.5. Values < 1 emphasize lower values, values > 1 emphasize higher values. line_threshold : float, optional Threshold for 'sym-lognorm' color scale, by default 0.0001. line_scale : float, optional Scale factor for 'sym-lognorm' color scale, by default 0.001. bounds : List, optional Boundaries for 'boundary-norm' color scale, by default None. Defines the discrete intervals for color mapping. midpoint : float, optional Midpoint value for 'midpoint' color scale, by default 0.

Cell value display options:#

display_cell_value : bool, optional Whether to display the values of cells as text, by default False. num_size : int, optional Font size of the cell value text, by default 8. background_color_threshold : float, optional Threshold for cell value text color, by default None. If cell value > threshold, text is black; otherwise, text is white. If None, uses max(array)/2 as the threshold.

{}

Returns:

Type Description
FuncAnimation

The animation object that can be displayed in a notebook or saved to a file.

Raises:

Type Description
ValueError

If an invalid keyword argument is provided.

ValueError

If the length of the time list doesn't match the first dimension of the array.

Notes

The animation is created by iterating through the first dimension of the array. For example, if the array has shape (10, 20, 30), the animation will have 10 frames, each showing a 20x30 slice of the array.

To display the animation in a Jupyter notebook, you may need to use:

from IPython.display import HTML
HTML(anim_obj.to_jshtml())

To save the animation to a file, use the save_animation method after creating the animation.

Examples:

Basic animation from a 3D array:

>>> import numpy as np
>>> from cleopatra.array_glyph import ArrayGlyph
>>> # Create a 3D array with 5 frames, each 10x10
>>> arr = np.random.randint(1, 10, size=(5, 10, 10))
>>> # Create labels for each frame
>>> frame_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
>>> # Create the ArrayGlyph object
>>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
>>> # Create the animation
>>> anim_obj = animated_array.animate(frame_labels)
Animation with custom interval (speed):
>>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
>>> # Slower animation (500ms between frames)
>>> anim_obj = animated_array.animate(frame_labels, interval=500)
>>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
>>> # Faster animation (100ms between frames)
>>> anim_obj = animated_array.animate(frame_labels, interval=100)
Animation with points:
>>> # Create points to display on the animation
>>> points = np.array([[1, 2, 3], [2, 5, 5], [3, 8, 8]])
>>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
>>> anim_obj = animated_array.animate(
...     frame_labels,
...     points=points,
...     point_color="black",
...     point_size=150,
...     pid_color="white",
...     pid_size=12
... )
Animation with cell values displayed:
>>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
>>> anim_obj = animated_array.animate(
...     frame_labels,
...     display_cell_value=True,
...     num_size=10,
...     text_colors=("yellow", "blue")
... )
animated_array

Saving the animation to a file:

>>> # Create the animation first
>>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
>>> anim_obj = animated_array.animate(frame_labels)
>>> # Then save it to a file
>>> animated_array.save_animation("animation.gif", fps=2)

Source code in cleopatra/array_glyph.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
def animate(
    self,
    time: List[Any],
    points: np.ndarray = None,
    text_colors=("white", "black"),
    interval=200,
    text_loc: list[Any, Any] = None,
    point_color="red",
    point_size=100,
    pid_color="blue",
    pid_size=10,
    **kwargs,
):
    """Create an animation from a 3D array.

    This method creates an animation by iterating through the first dimension of a 3D array.
    Each slice of the array becomes a frame in the animation, with optional time labels,
    point annotations, and cell value displays.

    Parameters
    ----------
    time : List[Any]
        A list containing labels for each frame in the animation.
        These could be timestamps, frame numbers, or any other identifiers.
        The length of this list should match the first dimension of the array.
    points : np.ndarray, optional
        Points to display on the array, by default None.
        Should be a 3-column array where:
        - First column: values to display for each point
        - Second column: row indices of the points in the array
        - Third column: column indices of the points in the array
    text_colors : Tuple[str, str], optional
        Two colors to be used for cell value text, by default ("white", "black").
        The first color is used when the cell value is below the background_color_threshold,
        and the second color is used when the cell value is above the threshold.
    interval : int, optional
        Delay between frames in milliseconds, by default 200.
        Controls the speed of the animation (smaller values = faster animation).
    text_loc : list[Any, Any], optional
        Location of the time label text as [x, y] coordinates, by default None.
        If None, defaults to [0.1, 0.2].
    point_color : str, optional
        Color of the points, by default "red".
        Any valid matplotlib color string.
    point_size : int, optional
        Size of the points, by default 100.
        Controls the marker size.
    pid_color : str, optional
        Color of the point value annotations, by default "blue".
        Any valid matplotlib color string.
    pid_size : int, optional
        Size of the point value annotations, by default 10.
        Controls the font size of the annotations.
    **kwargs : dict
        Additional keyword arguments for customizing the animation.

        Plot appearance:
        ---------------
        title : str, optional
            Title of the plot, by default 'Array Plot'.
        title_size : int, optional
            Title font size, by default 15.
        cmap : str, optional
            Colormap name, by default 'coolwarm_r'.
        vmin : float, optional
            Minimum value for color scaling, by default min(array).
        vmax : float, optional
            Maximum value for color scaling, by default max(array).

        Color bar options:
        ----------------
        cbar_orientation : str, optional
            Orientation of the color bar, by default 'vertical'.
            Can be 'horizontal' or 'vertical'.
        cbar_label_rotation : float, optional
            Rotation angle of the color bar label, by default -90.
        cbar_label_location : str, optional
            Location of the color bar label, by default 'bottom'.
            Options: 'top', 'bottom', 'center', 'baseline', 'center_baseline'.
        cbar_length : float, optional
            Ratio to control the height/width of the color bar, by default 0.75.
        ticks_spacing : int, optional
            Spacing between ticks on the color bar, by default 2.
        cbar_label_size : int, optional
            Font size of the color bar label, by default 12.
        cbar_label : str, optional
            Label text for the color bar, by default 'Value'.

        Color scale options:
        ------------------
        color_scale : str, optional
            Type of color scaling to use, by default 'linear'.
            Options:
            - 'linear': Linear scale
            - 'power': Power-law normalization
            - 'sym-lognorm': Symmetrical logarithmic scale
            - 'boundary-norm': Discrete intervals based on boundaries
            - 'midpoint': Scale split at a specified midpoint
        gamma : float, optional
            Exponent for 'power' color scale, by default 0.5.
            Values < 1 emphasize lower values, values > 1 emphasize higher values.
        line_threshold : float, optional
            Threshold for 'sym-lognorm' color scale, by default 0.0001.
        line_scale : float, optional
            Scale factor for 'sym-lognorm' color scale, by default 0.001.
        bounds : List, optional
            Boundaries for 'boundary-norm' color scale, by default None.
            Defines the discrete intervals for color mapping.
        midpoint : float, optional
            Midpoint value for 'midpoint' color scale, by default 0.

        Cell value display options:
        -------------------------
        display_cell_value : bool, optional
            Whether to display the values of cells as text, by default False.
        num_size : int, optional
            Font size of the cell value text, by default 8.
        background_color_threshold : float, optional
            Threshold for cell value text color, by default None.
            If cell value > threshold, text is black; otherwise, text is white.
            If None, uses max(array)/2 as the threshold.

    Returns
    -------
    matplotlib.animation.FuncAnimation
        The animation object that can be displayed in a notebook or saved to a file.

    Raises
    ------
    ValueError
        If an invalid keyword argument is provided.
    ValueError
        If the length of the time list doesn't match the first dimension of the array.

    Notes
    -----
    The animation is created by iterating through the first dimension of the array.
    For example, if the array has shape (10, 20, 30), the animation will have 10 frames,
    each showing a 20x30 slice of the array.

    To display the animation in a Jupyter notebook, you may need to use:
    ```python
    from IPython.display import HTML
    HTML(anim_obj.to_jshtml())
    ```

    To save the animation to a file, use the `save_animation` method after creating
    the animation.

    Examples
    --------
    Basic animation from a 3D array:
    ```python
    >>> import numpy as np
    >>> from cleopatra.array_glyph import ArrayGlyph
    >>> # Create a 3D array with 5 frames, each 10x10
    >>> arr = np.random.randint(1, 10, size=(5, 10, 10))
    >>> # Create labels for each frame
    >>> frame_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
    >>> # Create the ArrayGlyph object
    >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
    >>> # Create the animation
    >>> anim_obj = animated_array.animate(frame_labels)

    ```
    Animation with custom interval (speed):
    ```python
    >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
    >>> # Slower animation (500ms between frames)
    >>> anim_obj = animated_array.animate(frame_labels, interval=500)
    >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
    >>> # Faster animation (100ms between frames)
    >>> anim_obj = animated_array.animate(frame_labels, interval=100)

    ```
    Animation with points:
    ```python
    >>> # Create points to display on the animation
    >>> points = np.array([[1, 2, 3], [2, 5, 5], [3, 8, 8]])
    >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
    >>> anim_obj = animated_array.animate(
    ...     frame_labels,
    ...     points=points,
    ...     point_color="black",
    ...     point_size=150,
    ...     pid_color="white",
    ...     pid_size=12
    ... )

    ```
    Animation with cell values displayed:
    ```python
    >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
    >>> anim_obj = animated_array.animate(
    ...     frame_labels,
    ...     display_cell_value=True,
    ...     num_size=10,
    ...     text_colors=("yellow", "blue")
    ... )

    ```
    ![animated_array](./../_images/array_glyph/animated_array.gif)

    Saving the animation to a file:
    ```python
    >>> # Create the animation first
    >>> animated_array = ArrayGlyph(arr, figsize=(8, 8), title="Animated Array")
    >>> anim_obj = animated_array.animate(frame_labels)
    >>> # Then save it to a file
    >>> animated_array.save_animation("animation.gif", fps=2)

    ```
    """
    if text_loc is None:
        text_loc = [0.1, 0.2]

    for key, val in kwargs.items():
        if key not in self.default_options.keys():
            raise ValueError(
                f"The given keyword argument:{key} is not correct, possible parameters are,"
                f" {DEFAULT_OPTIONS}"
            )
        else:
            self.default_options[key] = val

    # if user did not input ticks spacing use the calculated one.
    if "ticks_spacing" in kwargs.keys():
        self.default_options["ticks_spacing"] = kwargs["ticks_spacing"]
    else:
        self.default_options["ticks_spacing"] = self.ticks_spacing

    if "vmin" in kwargs.keys():
        self.default_options["vmin"] = kwargs["vmin"]
    else:
        self.default_options["vmin"] = self.vmin

    if "vmax" in kwargs.keys():
        self.default_options["vmax"] = kwargs["vmax"]
    else:
        self.default_options["vmax"] = self.vmax

    # if optional_display
    precision = self.default_options["precision"]
    array = self.arr

    if self.fig is None:
        self.fig, self.ax = self.create_figure_axes()

    fig, ax = self.fig, self.ax

    ticks = self.get_ticks()
    im, cbar_kw = self._plot_im_get_cbar_kw(ax, array[0, :, :], ticks)

    # Create colorbar
    cbar = ax.figure.colorbar(
        im,
        ax=ax,
        shrink=self.default_options["cbar_length"],
        orientation=self.default_options["cbar_orientation"],
        **cbar_kw,
    )
    cbar.ax.set_ylabel(
        self.default_options["cbar_label"],
        rotation=self.default_options["cbar_label_rotation"],
        va=self.default_options["cbar_label_location"],
        fontsize=self.default_options["cbar_label_size"],
    )
    cbar.ax.tick_params(labelsize=10)

    ax.set_title(
        self.default_options["title"], fontsize=self.default_options["title_size"]
    )
    ax.set_xticklabels([])
    ax.set_yticklabels([])

    ax.set_xticks([])
    ax.set_yticks([])

    if self.default_options["display_cell_value"]:
        indices = get_indices2(array[0, :, :], [np.nan])
        cell_text_value = self._plot_text(
            ax, array[0, :, :], indices, self.default_options
        )
        indices = np.array(indices)

    if points is not None:
        row = points[:, 1]
        col = points[:, 2]
        points_scatter = ax.scatter(col, row, color=point_color, s=point_size)
        points_id = self._plot_point_values(ax, points, pid_color, pid_size)

    # Normalize the threshold to the image color range.
    if self.default_options["background_color_threshold"] is not None:
        background_color_threshold = im.norm(
            self.default_options["background_color_threshold"]
        )
    else:
        background_color_threshold = im.norm(np.nanmax(array)) / 2.0

    day_text = ax.text(
        text_loc[0],
        text_loc[1],
        " ",
        fontsize=self.default_options["cbar_label_size"],
    )

    def init():
        """initialize the plot with the first array"""
        im.set_data(array[0, :, :])
        day_text.set_text("")
        output = [im, day_text]

        if points is not None:
            points_scatter.set_offsets(np.c_[col, row])
            output.append(points_scatter)
            update_points = lambda x: points_id[x].set_text(points[x, 0])
            list(map(update_points, range(len(col))))

            output += points_id

        if self.default_options["display_cell_value"]:
            vals = array[0, indices[:, 0], indices[:, 1]]
            update_cell_value = lambda x: cell_text_value[x].set_text(vals[x])
            list(map(update_cell_value, range(self.no_elem)))
            output += cell_text_value

        return output

    def animate_a(i):
        """plot for each element in the iterable."""
        im.set_data(array[i, :, :])
        day_text.set_text("Date = " + str(time[i])[0:10])
        output = [im, day_text]

        if points is not None:
            points_scatter.set_offsets(np.c_[col, row])
            output.append(points_scatter)

            for x in range(len(col)):
                points_id[x].set_text(points[x, 0])

            output += points_id

        if self.default_options["display_cell_value"]:
            vals = array[i, indices[:, 0], indices[:, 1]]

            def update_cell_value(x):
                """Update cell value"""
                val = round(vals[x], precision)
                kw = {
                    "color": text_colors[
                        int(im.norm(vals[x]) > background_color_threshold)
                    ]
                }
                cell_text_value[x].update(kw)
                cell_text_value[x].set_text(val)

            list(map(update_cell_value, range(self.no_elem)))

            output += cell_text_value

        return output

    plt.tight_layout()
    anim = FuncAnimation(
        fig,
        animate_a,
        init_func=init,
        frames=np.shape(array)[0],
        interval=interval,
        blit=True,
    )
    self._anim = anim
    plt.show()
    return anim

apply_colormap(cmap) #

Apply a matplotlib colormap to an array.

Create an RGB channel from the given array using the given colormap.

Parameters:

Name Type Description Default
cmap Union[Colormap, str]

colormap.

required

Returns:

Type Description
np.ndarray: 8-bit array

the array with the colormap applied.

Examples:

  • Create an array and instantiate the Array object:
    >>> import numpy as np
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array = ArrayGlyph(arr)
    >>> rgb_array = array.apply_colormap("coolwarm_r")
    >>> print(rgb_array) # doctest: +SKIP
    [[[179   3  38]
      [221  96  76]
      [244 154 123]]
     [[244 196 173]
      [220 220 221]
      [183 207 249]]
     [[139 174 253]
      [ 96 128 232]
      [ 58  76 192]]]
    
    >>> print(rgb_array.dtype)
    uint8
    
Source code in cleopatra/array_glyph.py
def apply_colormap(self, cmap: Union[Colormap, str]) -> np.ndarray:
    """Apply a matplotlib colormap to an array.

        Create an RGB channel from the given array using the given colormap.

    Parameters
    ----------
    cmap: Colormap/str
        colormap.

    Returns
    -------
    np.ndarray: 8-bit array
        the array with the colormap applied.

    Examples
    --------
    - Create an array and instantiate the `Array` object:
    ```python
    >>> import numpy as np
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array = ArrayGlyph(arr)
    >>> rgb_array = array.apply_colormap("coolwarm_r")
    >>> print(rgb_array) # doctest: +SKIP
    [[[179   3  38]
      [221  96  76]
      [244 154 123]]
     [[244 196 173]
      [220 220 221]
      [183 207 249]]
     [[139 174 253]
      [ 96 128 232]
      [ 58  76 192]]]

    >>> print(rgb_array.dtype)
    uint8

    ```
    """
    colormap = plt.get_cmap(cmap) if isinstance(cmap, str) else cmap
    normed_data = (self.arr - self.arr.min()) / (self.arr.max() - self.arr.min())
    colored = colormap(normed_data)
    return (colored[:, :, :3] * 255).astype("uint8")

create_color_bar(ax, im, cbar_kw) #

Create Color bar.

Parameters:

Name Type Description Default
ax Axes

matplotlib axes.

required
im AxesImage

Image axes.

required
cbar_kw dict

color bar keyword arguments.

required

Returns:

Name Type Description
Colorbar Colorbar

colorbar object.

Source code in cleopatra/array_glyph.py
def create_color_bar(self, ax: Axes, im: AxesImage, cbar_kw: dict) -> Colorbar:
    """Create Color bar.

    Parameters
    ----------
    ax: Axes
        matplotlib axes.
    im: AxesImage
        Image axes.
    cbar_kw: dict
        color bar keyword arguments.

    Returns
    -------
    Colorbar:
        colorbar object.
    """
    # im or cax is the last image added to the axes
    # im = ax.images[-1]
    cbar = ax.figure.colorbar(
        im,
        ax=ax,
        shrink=self.default_options["cbar_length"],
        orientation=self.default_options["cbar_orientation"],
        **cbar_kw,
    )
    # cbar.ax.set_ylabel(
    #     self.default_options["cbar_label"],
    #     rotation=self.default_options["cbar_label_rotation"],
    #     va=self.default_options["cbar_label_location"],
    #     fontsize=self.default_options["cbar_label_size"],
    # )
    cbar.ax.tick_params(labelsize=10)
    cbar.set_label(
        self.default_options["cbar_label"],
        fontsize=self.default_options["cbar_label_size"],
        loc=self.default_options["cbar_label_location"],
    )

    return cbar

create_figure_axes() #

Create the figure and the axes.

Returns:

Name Type Description
fig Figure

the created figure.

ax Axes

the created axes.

Source code in cleopatra/array_glyph.py
def create_figure_axes(self) -> Tuple[Figure, Axes]:
    """Create the figure and the axes.

    Returns
    -------
    fig: matplotlib.figure.Figure
        the created figure.
    ax: matplotlib.axes.Axes
        the created axes.
    """
    fig, ax = plt.subplots(figsize=self.default_options["figsize"])

    return fig, ax

get_ticks() #

get a list of ticks for the color bar

Source code in cleopatra/array_glyph.py
def get_ticks(self) -> np.ndarray:
    """get a list of ticks for the color bar"""
    ticks_spacing = self.default_options["ticks_spacing"]
    vmax = self.default_options["vmax"]
    vmin = self.default_options["vmin"]
    remainder = np.round(math.remainder(vmax, ticks_spacing), 3)
    # np.mod(vmax, ticks_spacing) gives float point error, so we use the round function.
    if remainder == 0:
        ticks = np.arange(vmin, vmax + ticks_spacing, ticks_spacing)
    else:
        try:
            ticks = np.arange(vmin, vmax + ticks_spacing, ticks_spacing)
        except ValueError:
            raise ValueError(
                "The number of ticks exceeded the max allowed size, possible errors"
                f" is the value of the NodataValue you entered-{self.exclude_value}"
            )
        ticks = np.append(
            ticks,
            [int(vmax / ticks_spacing) * ticks_spacing + ticks_spacing],
        )
    return ticks

plot(points=None, point_color='red', point_size=100, pid_color='blue', pid_size=10, **kwargs) #

Plot the array with customizable visualization options.

This method creates a visualization of the array with various customization options including color scales, color bars, cell value display, and point annotations. It supports both regular arrays and RGB arrays.

Parameters:

Name Type Description Default
points ndarray

Points to display on the array, by default None. Should be a 3-column array where: - First column: values to display for each point - Second column: row indices of the points in the array - Third column: column indices of the points in the array

None
point_color str

Color of the points, by default "red". Any valid matplotlib color string.

'red'
point_size Union[int, float]

Size of the points, by default 100. Controls the marker size.

100
pid_color str

Color of the point value annotations, by default "blue". Any valid matplotlib color string.

'blue'
pid_size Union[int, float]

Size of the point value annotations, by default 10. Controls the font size of the annotations.

10
**kwargs dict

Additional keyword arguments for customizing the plot.

Plot appearance:#

title : str, optional Title of the plot, by default 'Array Plot'. title_size : int, optional Title font size, by default 15. cmap : str, optional Colormap name, by default 'coolwarm_r'. vmin : float, optional Minimum value for color scaling, by default min(array). vmax : float, optional Maximum value for color scaling, by default max(array).

Color bar options:#

cbar_orientation : str, optional Orientation of the color bar, by default 'vertical'. Can be 'horizontal' or 'vertical'. cbar_label_rotation : float, optional Rotation angle of the color bar label, by default -90. cbar_label_location : str, optional Location of the color bar label, by default 'bottom'. Options: 'top', 'bottom', 'center', 'baseline', 'center_baseline'. cbar_length : float, optional Ratio to control the height/width of the color bar, by default 0.75. ticks_spacing : int, optional Spacing between ticks on the color bar, by default 2. cbar_label_size : int, optional Font size of the color bar label, by default 12. cbar_label : str, optional Label text for the color bar, by default 'Value'.

Color scale options:#

color_scale : str, optional Type of color scaling to use, by default 'linear'. Options: - 'linear': Linear scale - 'power': Power-law normalization - 'sym-lognorm': Symmetrical logarithmic scale - 'boundary-norm': Discrete intervals based on boundaries - 'midpoint': Scale split at a specified midpoint gamma : float, optional Exponent for 'power' color scale, by default 0.5. Values < 1 emphasize lower values, values > 1 emphasize higher values. line_threshold : float, optional Threshold for 'sym-lognorm' color scale, by default 0.0001. line_scale : float, optional Scale factor for 'sym-lognorm' color scale, by default 0.001. bounds : List, optional Boundaries for 'boundary-norm' color scale, by default None. Defines the discrete intervals for color mapping. midpoint : float, optional Midpoint value for 'midpoint' color scale, by default 0.

Cell value display options:#

display_cell_value : bool, optional Whether to display the values of cells as text, by default False. num_size : int, optional Font size of the cell value text, by default 8. background_color_threshold : float, optional Threshold for cell value text color, by default None. If cell value > threshold, text is black; otherwise, text is white. If None, uses max(array)/2 as the threshold.

{}

Returns:

Type Description
Tuple[Figure, Axes]

A tuple containing: - fig: The matplotlib Figure object - ax: The matplotlib Axes object

Raises:

Type Description
ValueError

If an invalid keyword argument is provided.

Examples:

  • Basic array plot:

    >>> import numpy as np
    >>> from cleopatra.array_glyph import ArrayGlyph
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Customized Plot", title_size=18)
    >>> fig, ax = array.plot()
    
    array-plot

  • Color bar customization:

    • Create an array and instantiate the Array object with custom options.
      >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Customized color bar", title_size=18)
      >>> fig, ax = array.plot(
      ...     cbar_orientation="horizontal",
      ...     cbar_label_rotation=-90,
      ...     cbar_label_location="center",
      ...     cbar_length=0.7,
      ...     cbar_label_size=12,
      ...     cbar_label="Discharge m3/s",
      ...     ticks_spacing=5,
      ...     color_scale="linear",
      ...     cmap="coolwarm_r",
      ... )
      
      color-bar-customization
  • Display values for each cell:

    • you can display the values for each cell by using thr parameter display_cell_value, and customize how the values are displayed using the parameter background_color_threshold and num_size.

      >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Display array values", title_size=18)
      >>> fig, ax = array.plot(
      ...     display_cell_value=True,
      ...     num_size=12
      ... )
      
      display-cell-values

  • Plot points at specific locations in the array:

    • you can display points in specific cells in the array and also display a value for each of these points. The point parameter takes an array with the first column as the values to be displayed on top of the points, the second and third columns are the row and column index of the point in the array.
    • The point_color and point_size parameters are used to customize the appearance of the points, while the pid_color and pid_size parameters are used to customize the appearance of the point IDs/text.

      >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Display Points", title_size=14)
      >>> points = np.array([[1, 0, 0], [2, 1, 1], [3, 2, 2]])
      >>> fig, ax = array.plot(
      ...     points=points,
      ...     point_color="black",
      ...     point_size=100,
      ...     pid_color="orange",
      ...     pid_size=30,
      ... )
      
      display-points

  • Color scale customization:

    • Power scale (with different gamma values).

      • The default power scale uses a gamma value of 0.5.

        >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale", title_size=18)
        >>> fig, ax = array.plot(
        ...     cbar_label="Discharge m3/s",
        ...     color_scale="power",
        ...     cmap="coolwarm_r",
        ...     cbar_label_rotation=-90,
        ... )
        
        power-scale

      • change the gamma of 0.8 (emphasizes higher values less).

        >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale - gamma=0.8", title_size=18)
        >>> fig, ax = array.plot(
        ...     color_scale="power",
        ...     gamma=0.8,
        ...     cmap="coolwarm_r",
        ...     cbar_label_rotation=-90,
        ...     cbar_label="Discharge m3/s",
        ... )
        
        power-scale-gamma-0.8

      • change the gamma of 0.1 (emphasizes higher values more).

        >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale - gamma=0.1", title_size=18)
        >>> fig, ax = array.plot(
        ...     color_scale="power",
        ...     gamma=0.1,
        ...     cmap="coolwarm_r",
        ...     cbar_label_rotation=-90,
        ...     cbar_label="Discharge m3/s",
        ... )
        
        power-scale-gamma-0.1

    • Logarithmic scale.

      • the logarithmic scale uses to parameters line_threshold and line_scale with a default value if 0.0001, and 0.001 respectively.

        >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Logarithmic scale", title_size=18)
        >>> fig, ax = array.plot(
        ...     cbar_label="Discharge m3/s",
        ...     color_scale="sym-lognorm",
        ...     cmap="coolwarm_r",
        ...     cbar_label_rotation=-90,
        ... )
        
        log-scale

      • you can change the line_threshold and line_scale values.

        >>> array = ArrayGlyph(
        ...     arr, figsize=(6, 6), title="Logarithmic scale: Customized Parameter", title_size=12
        ... )
        >>> fig, ax = array.plot(
        ...     cbar_label_rotation=-90,
        ...     cbar_label="Discharge m3/s",
        ...     color_scale="sym-lognorm",
        ...     cmap="coolwarm_r",
        ...     line_threshold=0.015,
        ...     line_scale=0.1,
        ... )
        
        log-scale

    • Defined boundary scale.

      >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Defined boundary scale", title_size=18)
      >>> fig, ax = array.plot(
      ...     cbar_label_rotation=-90,
      ...     cbar_label="Discharge m3/s",
      ...     color_scale="boundary-norm",
      ...     cmap="coolwarm_r",
      ... )
      
      boundary-scale

      • You can also define the boundaries.
        >>> array = ArrayGlyph(
        ...     arr, figsize=(6, 6), title="Defined boundary scale: defined bounds", title_size=18
        ... )
        >>> bounds = [0, 5, 10]
        >>> fig, ax = array.plot(
        ...     cbar_label_rotation=-90,
        ...     cbar_label="Discharge m3/s",
        ...     color_scale="boundary-norm",
        ...     bounds=bounds,
        ...     cmap="coolwarm_r",
        ... )
        
        boundary-scale-defined-bounds
    • Midpoint scale.

      in the midpoint scale you can define a value that splits the scale into half.

      >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Midpoint scale", title_size=18)
      >>> fig, ax = array.plot(
      ...     cbar_label_rotation=-90,
      ...     cbar_label="Discharge m3/s",
      ...     color_scale="midpoint",
      ...     cmap="coolwarm_r",
      ...     midpoint=2,
      ... )
      
      midpoint-scale-costom-parameters

Source code in cleopatra/array_glyph.py
 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
def plot(
    self,
    points: np.ndarray = None,
    point_color: str = "red",
    point_size: Union[int, float] = 100,
    pid_color="blue",
    pid_size: Union[int, float] = 10,
    **kwargs,
) -> Tuple[Figure, Axes]:
    """Plot the array with customizable visualization options.

    This method creates a visualization of the array with various customization options
    including color scales, color bars, cell value display, and point annotations.
    It supports both regular arrays and RGB arrays.

    Parameters
    ----------
    points : np.ndarray, optional
        Points to display on the array, by default None.
        Should be a 3-column array where:
        - First column: values to display for each point
        - Second column: row indices of the points in the array
        - Third column: column indices of the points in the array
    point_color : str, optional
        Color of the points, by default "red".
        Any valid matplotlib color string.
    point_size : Union[int, float], optional
        Size of the points, by default 100.
        Controls the marker size.
    pid_color : str, optional
        Color of the point value annotations, by default "blue".
        Any valid matplotlib color string.
    pid_size : Union[int, float], optional
        Size of the point value annotations, by default 10.
        Controls the font size of the annotations.
    **kwargs : dict
        Additional keyword arguments for customizing the plot.

        Plot appearance:
        ---------------
        title : str, optional
            Title of the plot, by default 'Array Plot'.
        title_size : int, optional
            Title font size, by default 15.
        cmap : str, optional
            Colormap name, by default 'coolwarm_r'.
        vmin : float, optional
            Minimum value for color scaling, by default min(array).
        vmax : float, optional
            Maximum value for color scaling, by default max(array).

        Color bar options:
        ----------------
        cbar_orientation : str, optional
            Orientation of the color bar, by default 'vertical'.
            Can be 'horizontal' or 'vertical'.
        cbar_label_rotation : float, optional
            Rotation angle of the color bar label, by default -90.
        cbar_label_location : str, optional
            Location of the color bar label, by default 'bottom'.
            Options: 'top', 'bottom', 'center', 'baseline', 'center_baseline'.
        cbar_length : float, optional
            Ratio to control the height/width of the color bar, by default 0.75.
        ticks_spacing : int, optional
            Spacing between ticks on the color bar, by default 2.
        cbar_label_size : int, optional
            Font size of the color bar label, by default 12.
        cbar_label : str, optional
            Label text for the color bar, by default 'Value'.

        Color scale options:
        ------------------
        color_scale : str, optional
            Type of color scaling to use, by default 'linear'.
            Options:
            - 'linear': Linear scale
            - 'power': Power-law normalization
            - 'sym-lognorm': Symmetrical logarithmic scale
            - 'boundary-norm': Discrete intervals based on boundaries
            - 'midpoint': Scale split at a specified midpoint
        gamma : float, optional
            Exponent for 'power' color scale, by default 0.5.
            Values < 1 emphasize lower values, values > 1 emphasize higher values.
        line_threshold : float, optional
            Threshold for 'sym-lognorm' color scale, by default 0.0001.
        line_scale : float, optional
            Scale factor for 'sym-lognorm' color scale, by default 0.001.
        bounds : List, optional
            Boundaries for 'boundary-norm' color scale, by default None.
            Defines the discrete intervals for color mapping.
        midpoint : float, optional
            Midpoint value for 'midpoint' color scale, by default 0.

        Cell value display options:
        -------------------------
        display_cell_value : bool, optional
            Whether to display the values of cells as text, by default False.
        num_size : int, optional
            Font size of the cell value text, by default 8.
        background_color_threshold : float, optional
            Threshold for cell value text color, by default None.
            If cell value > threshold, text is black; otherwise, text is white.
            If None, uses max(array)/2 as the threshold.

    Returns
    -------
    Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        A tuple containing:
        - fig: The matplotlib Figure object
        - ax: The matplotlib Axes object

    Raises
    ------
    ValueError
        If an invalid keyword argument is provided.

    Examples
    --------
    - Basic array plot:

        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Customized Plot", title_size=18)
        >>> fig, ax = array.plot()

        ```
    ![array-plot](./../_images/array_glyph/array-plot.png)

    - Color bar customization:

        - Create an array and instantiate the `Array` object with custom options.
            ```python
            >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Customized color bar", title_size=18)
            >>> fig, ax = array.plot(
            ...     cbar_orientation="horizontal",
            ...     cbar_label_rotation=-90,
            ...     cbar_label_location="center",
            ...     cbar_length=0.7,
            ...     cbar_label_size=12,
            ...     cbar_label="Discharge m3/s",
            ...     ticks_spacing=5,
            ...     color_scale="linear",
            ...     cmap="coolwarm_r",
            ... )

            ```
            ![color-bar-customization](./../_images/array_glyph/color-bar-customization.png)

    - Display values for each cell:

        - you can display the values for each cell by using thr parameter `display_cell_value`, and customize how
            the values are displayed using the parameter `background_color_threshold` and `num_size`.

            ```python
            >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Display array values", title_size=18)
            >>> fig, ax = array.plot(
            ...     display_cell_value=True,
            ...     num_size=12
            ... )

            ```
            ![display-cell-values](./../_images/array_glyph/display-cell-values.png)

    - Plot points at specific locations in the array:

        - you can display points in specific cells in the array and also display a value for each of these points.
            The point parameter takes an array with the first column as the values to be displayed on top of the
            points, the second and third columns are the row and column index of the point in the array.
        - The `point_color` and `point_size` parameters are used to customize the appearance of the points,
            while the `pid_color` and `pid_size` parameters are used to customize the appearance of the point
            IDs/text.

            ```python
            >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Display Points", title_size=14)
            >>> points = np.array([[1, 0, 0], [2, 1, 1], [3, 2, 2]])
            >>> fig, ax = array.plot(
            ...     points=points,
            ...     point_color="black",
            ...     point_size=100,
            ...     pid_color="orange",
            ...     pid_size=30,
            ... )

            ```
            ![display-points](./../_images/array_glyph/display-points.png)

    - Color scale customization:

        - Power scale (with different gamma values).

            - The default power scale uses a gamma value of 0.5.

                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale", title_size=18)
                >>> fig, ax = array.plot(
                ...     cbar_label="Discharge m3/s",
                ...     color_scale="power",
                ...     cmap="coolwarm_r",
                ...     cbar_label_rotation=-90,
                ... )

                ```
                ![power-scale](./../_images/array_glyph/power-scale.png)

            - change the gamma of 0.8 (emphasizes higher values less).

                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale - gamma=0.8", title_size=18)
                >>> fig, ax = array.plot(
                ...     color_scale="power",
                ...     gamma=0.8,
                ...     cmap="coolwarm_r",
                ...     cbar_label_rotation=-90,
                ...     cbar_label="Discharge m3/s",
                ... )

                ```
                ![power-scale-gamma-0.8](./../_images/array_glyph/power-scale-gamma-0.8.png)

            - change the gamma of 0.1 (emphasizes higher values more).

                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Power scale - gamma=0.1", title_size=18)
                >>> fig, ax = array.plot(
                ...     color_scale="power",
                ...     gamma=0.1,
                ...     cmap="coolwarm_r",
                ...     cbar_label_rotation=-90,
                ...     cbar_label="Discharge m3/s",
                ... )

                ```
                ![power-scale-gamma-0.1](./../_images/array_glyph/power-scale-gamma-0.1.png)

        - Logarithmic scale.

            - the logarithmic scale uses to parameters `line_threshold` and `line_scale` with a default
            value if 0.0001, and 0.001 respectively.
                ```python
                >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Logarithmic scale", title_size=18)
                >>> fig, ax = array.plot(
                ...     cbar_label="Discharge m3/s",
                ...     color_scale="sym-lognorm",
                ...     cmap="coolwarm_r",
                ...     cbar_label_rotation=-90,
                ... )

                ```
                ![log-scale](./../_images/array_glyph/log-scale.png)

            - you can change the `line_threshold` and `line_scale` values.
                ```python
                >>> array = ArrayGlyph(
                ...     arr, figsize=(6, 6), title="Logarithmic scale: Customized Parameter", title_size=12
                ... )
                >>> fig, ax = array.plot(
                ...     cbar_label_rotation=-90,
                ...     cbar_label="Discharge m3/s",
                ...     color_scale="sym-lognorm",
                ...     cmap="coolwarm_r",
                ...     line_threshold=0.015,
                ...     line_scale=0.1,
                ... )

                ```
                ![log-scale](./../_images/array_glyph/log-scale-custom-parameters.png)

        - Defined boundary scale.
            ```python
            >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Defined boundary scale", title_size=18)
            >>> fig, ax = array.plot(
            ...     cbar_label_rotation=-90,
            ...     cbar_label="Discharge m3/s",
            ...     color_scale="boundary-norm",
            ...     cmap="coolwarm_r",
            ... )

            ```
            ![boundary-scale](./../_images/array_glyph/boundary-scale.png)

            - You can also define the boundaries.
                ```python
                >>> array = ArrayGlyph(
                ...     arr, figsize=(6, 6), title="Defined boundary scale: defined bounds", title_size=18
                ... )
                >>> bounds = [0, 5, 10]
                >>> fig, ax = array.plot(
                ...     cbar_label_rotation=-90,
                ...     cbar_label="Discharge m3/s",
                ...     color_scale="boundary-norm",
                ...     bounds=bounds,
                ...     cmap="coolwarm_r",
                ... )

                ```
                ![boundary-scale-defined-bounds](./../_images/array_glyph/boundary-scale-defined-bounds.png)

        - Midpoint scale.

            in the midpoint scale you can define a value that splits the scale into half.
            ```python
            >>> array = ArrayGlyph(arr, figsize=(6, 6), title="Midpoint scale", title_size=18)
            >>> fig, ax = array.plot(
            ...     cbar_label_rotation=-90,
            ...     cbar_label="Discharge m3/s",
            ...     color_scale="midpoint",
            ...     cmap="coolwarm_r",
            ...     midpoint=2,
            ... )

            ```
            ![midpoint-scale-costom-parameters](./../_images/array_glyph/midpoint-scale-costom-parameters.png)
    """
    for key, val in kwargs.items():
        if key not in self.default_options.keys():
            raise ValueError(
                f"The given keyword argument:{key} is not correct, possible parameters are,"
                f" {DEFAULT_OPTIONS}"
            )
        else:
            self.default_options[key] = val

    if self.fig is None:
        self.fig, self.ax = self.create_figure_axes()

    arr = self.arr
    fig, ax = self.fig, self.ax

    if self.rgb:
        ax.imshow(arr, extent=self.extent)
    else:
        # if user did not input ticks spacing use the calculated one.
        if "ticks_spacing" in kwargs.keys():
            self.default_options["ticks_spacing"] = kwargs["ticks_spacing"]
        else:
            self.default_options["ticks_spacing"] = self.ticks_spacing

        if "vmin" in kwargs.keys():
            self.default_options["vmin"] = kwargs["vmin"]
        else:
            self.default_options["vmin"] = self.vmin

        if "vmax" in kwargs.keys():
            self.default_options["vmax"] = kwargs["vmax"]
        else:
            self.default_options["vmax"] = self.vmax

        # creating the ticks/bounds
        ticks = self.get_ticks()
        im, cbar_kw = self._plot_im_get_cbar_kw(ax, arr, ticks)

        # Create colorbar
        self.create_color_bar(ax, im, cbar_kw)

    ax.set_title(
        self.default_options["title"], fontsize=self.default_options["title_size"]
    )

    if self.extent is None:
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_xticks([])
        ax.set_yticks([])

    optional_display = {}
    if self.default_options["display_cell_value"]:
        indices = get_indices2(arr, [np.nan])
        optional_display["cell_text_value"] = self._plot_text(
            ax, arr, indices, self.default_options
        )

    if points is not None:
        row = points[:, 1]
        col = points[:, 2]
        optional_display["points_scatter"] = ax.scatter(
            col, row, color=point_color, s=point_size
        )
        optional_display["points_id"] = self._plot_point_values(
            ax, points, pid_color, pid_size
        )

    # # Normalize the threshold to the image color range.
    # if self.default_options["background_color_threshold"] is not None:
    #     im.norm(self.default_options["background_color_threshold"])
    # else:
    #     im.norm(self.vmax) / 2.0
    plt.show()
    return fig, ax

prepare_array(array, rgb=None, surface_reflectance=None, cutoff=None, percentile=None) #

Prepare an array for RGB visualization.

This method processes a multi-band array to create an RGB image suitable for visualization. It can normalize the data using either percentile-based scaling or surface reflectance values.

Parameters:

Name Type Description Default
array ndarray

The input array containing multiple bands. For RGB visualization, this should be a 3D array where the first dimension represents the bands.

required
rgb List[int]

The indices of the red, green, and blue bands in the given array, by default None. If None, assumes the order is [3, 2, 1] (common for Sentinel-2 data).

None
surface_reflectance int

Surface reflectance value for normalizing satellite data, by default None. Typically 10000 for Sentinel-2 data or 255 for 8-bit imagery. Used to scale values to the range [0, 1].

None
cutoff List

Clip the range of pixel values for each band, by default None. Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1. Should be a list with one value per band.

None
percentile int

The percentile value to be used for scaling the array values, by default None. Used to enhance contrast by stretching the histogram. If provided, this takes precedence over surface_reflectance.

None

Returns:

Type Description
ndarray

The prepared array with shape (height, width, 3) suitable for RGB visualization. Values are normalized to the range [0, 1]. the rgb 3d array is converted into 2d array to be plotted using the plt.imshow function. a float32 array normalized between 0 and 1 using the percentile values or the surface_reflectance. if the percentile or surface_reflectance values are not given, the function just reorders the values to have the red-green-blue order.

Raises:

Type Description
ValueError

If the array shape is incompatible with the provided RGB indices.

Notes
- The `prepare_array` function is called in the constructor of the `ArrayGlyph` class to prepare the array,
  so you can provide the same parameters of the `prepare_array` function to the `ArrayGlyph constructor`.
- The prepare function moves the first axes (the channel axis) to the last axes, and then scales the array
  using the percentile values. If the percentile is not given, the function scales the array using the
  surface reflectance values. If the surface reflectance is not given, the function scales the array using
  the cutoff values. If the cutoff is not given, the function scales the array using the sentinel data

Examples:

Prepare an array using percentile-based scaling:

>>> import numpy as np
>>> from cleopatra.array_glyph import ArrayGlyph
>>> # Create a 3-band array (e.g., satellite image)
>>> bands = np.random.randint(0, 10000, size=(3, 100, 100))
>>> glyph = ArrayGlyph(np.zeros((1, 1)))  # Dummy initialization
>>> rgb_array = glyph.prepare_array(bands, rgb=[0, 1, 2], percentile=2)
>>> rgb_array.shape
(100, 100, 3)
>>> np.all((0 <= rgb_array) & (rgb_array <= 1))
np.True_
Prepare an array using surface reflectance normalization:
>>> rgb_array = glyph.prepare_array(bands, rgb=[0, 1, 2], surface_reflectance=10000)
>>> rgb_array.shape
(100, 100, 3)
>>> np.all((0 <= rgb_array) & (rgb_array <= 1))
np.True_
Prepare an array with cutoff values:
>>> rgb_array = glyph.prepare_array(
...     bands, rgb=[0, 1, 2], surface_reflectance=10000, cutoff=[5000, 5000, 5000]
... )
>>> rgb_array.shape
(100, 100, 3)
>>> np.all((0 <= rgb_array) & (rgb_array <= 1))
np.True_

  • Create an array and instantiate the ArrayGlyph class.
    >>> import numpy as np
    >>> arr = np.random.randint(0, 255, size=(3, 5, 5)).astype(np.float32)
    >>> array_glyph = ArrayGlyph(arr)
    >>> print(array_glyph.arr.shape)
    (3, 5, 5)
    
    rgb channels:
    • Now let's use the prepare_array function with rgb channels as [0, 1, 2]. so the finction does not to reorder the chennels. but it just needs to move the first axis to the last axis.
      >>> rgb_array = array_glyph.prepare_array(arr, rgb=[0, 1, 2])
      >>> print(rgb_array.shape)
      (5, 5, 3)
      
    • If we compare the values of the first channel in the original array with the first array in the rgb array it should be the same.
      >>> np.testing.assert_equal(arr[0, :, :],rgb_array[:, :, 0])
      
      surface_reflectance:
    • if you provide the surface reflectance value, the function will scale the array using the surface reflectance value to a normalized rgb values.
      >>> array_glyph = ArrayGlyph(arr)
      >>> rgb_array = array_glyph.prepare_array(arr, surface_reflectance=10000, rgb=[0, 1, 2])
      >>> print(rgb_array.shape)
      (5, 5, 3)
      
    • if you print the values of the first channel, you will find all the values are between 0 and 1.
      >>> print(rgb_array[:, :, 0]) # doctest: +SKIP
      [[0.0195 0.02   0.0109 0.0211 0.0087]
       [0.0112 0.0221 0.0035 0.0234 0.0141]
       [0.0116 0.0188 0.0001 0.0176 0.    ]
       [0.0014 0.0147 0.0043 0.0167 0.0117]
       [0.0083 0.0139 0.0186 0.02   0.0058]]
      
    • With the surface_reflectance parameter, you can also use the cutoff parameter to affect values that are above it, by rescaling them.
      >>> rgb_array = array_glyph.prepare_array(
      ...     arr, surface_reflectance=10000, rgb=[0, 1, 2], cutoff=[0.8, 0.8, 0.8]
      ... )
      >>> print(rgb_array[:, :, 0]) # doctest: +SKIP
      [[0.     0.     0.     0.     0.    ]
       [1.     1.     1.     1.     1.    ]
       [1.     1.     1.     1.     1.    ]
       [0.0014 0.0147 0.0043 0.0167 0.0117]
       [0.0083 0.0139 0.0186 0.02   0.0058]]
      
Source code in cleopatra/array_glyph.py
def prepare_array(
    self,
    array: np.ndarray,
    rgb: List[int] = None,
    surface_reflectance: int = None,
    cutoff: List = None,
    percentile: int = None,
) -> np.ndarray:
    """Prepare an array for RGB visualization.

    This method processes a multi-band array to create an RGB image suitable for visualization.
    It can normalize the data using either percentile-based scaling or surface reflectance values.

    Parameters
    ----------
    array : np.ndarray
        The input array containing multiple bands. For RGB visualization,
        this should be a 3D array where the first dimension represents the bands.
    rgb : List[int], optional
        The indices of the red, green, and blue bands in the given array, by default None.
        If None, assumes the order is [3, 2, 1] (common for Sentinel-2 data).
    surface_reflectance : int, optional
        Surface reflectance value for normalizing satellite data, by default None.
        Typically 10000 for Sentinel-2 data or 255 for 8-bit imagery.
        Used to scale values to the range [0, 1].
    cutoff : List, optional
        Clip the range of pixel values for each band, by default None.
        Takes only pixel values from 0 to the value of the cutoff and scales them back to between 0 and 1.
        Should be a list with one value per band.
    percentile : int, optional
        The percentile value to be used for scaling the array values, by default None.
        Used to enhance contrast by stretching the histogram.
        If provided, this takes precedence over surface_reflectance.

    Returns
    -------
    np.ndarray
        The prepared array with shape (height, width, 3) suitable for RGB visualization.
        Values are normalized to the range [0, 1].
        the rgb 3d array is converted into 2d array to be plotted using the plt.imshow function.
        a float32 array normalized between 0 and 1 using the `percentile` values or the `surface_reflectance`.
        if the `percentile` or `surface_reflectance` values are not given, the function just reorders the values
        to have the red-green-blue order.

    Raises
    ------
    ValueError
        If the array shape is incompatible with the provided RGB indices.

    Notes
    -----
        - The `prepare_array` function is called in the constructor of the `ArrayGlyph` class to prepare the array,
          so you can provide the same parameters of the `prepare_array` function to the `ArrayGlyph constructor`.
        - The prepare function moves the first axes (the channel axis) to the last axes, and then scales the array
          using the percentile values. If the percentile is not given, the function scales the array using the
          surface reflectance values. If the surface reflectance is not given, the function scales the array using
          the cutoff values. If the cutoff is not given, the function scales the array using the sentinel data

    Examples
    --------
    Prepare an array using percentile-based scaling:
        ```python
        >>> import numpy as np
        >>> from cleopatra.array_glyph import ArrayGlyph
        >>> # Create a 3-band array (e.g., satellite image)
        >>> bands = np.random.randint(0, 10000, size=(3, 100, 100))
        >>> glyph = ArrayGlyph(np.zeros((1, 1)))  # Dummy initialization
        >>> rgb_array = glyph.prepare_array(bands, rgb=[0, 1, 2], percentile=2)
        >>> rgb_array.shape
        (100, 100, 3)
        >>> np.all((0 <= rgb_array) & (rgb_array <= 1))
        np.True_

        ```
    Prepare an array using surface reflectance normalization:
        ```python
        >>> rgb_array = glyph.prepare_array(bands, rgb=[0, 1, 2], surface_reflectance=10000)
        >>> rgb_array.shape
        (100, 100, 3)
        >>> np.all((0 <= rgb_array) & (rgb_array <= 1))
        np.True_

        ```
    Prepare an array with cutoff values:
        ```python
        >>> rgb_array = glyph.prepare_array(
        ...     bands, rgb=[0, 1, 2], surface_reflectance=10000, cutoff=[5000, 5000, 5000]
        ... )
        >>> rgb_array.shape
        (100, 100, 3)
        >>> np.all((0 <= rgb_array) & (rgb_array <= 1))
        np.True_

        ```

    - Create an array and instantiate the `ArrayGlyph` class.
        ```python
        >>> import numpy as np
        >>> arr = np.random.randint(0, 255, size=(3, 5, 5)).astype(np.float32)
        >>> array_glyph = ArrayGlyph(arr)
        >>> print(array_glyph.arr.shape)
        (3, 5, 5)

        ```
    `rgb` channels:
        - Now let's use the `prepare_array` function with `rgb` channels as [0, 1, 2]. so the finction does not to
            reorder the chennels. but it just needs to move the first axis to the last axis.
            ```python
            >>> rgb_array = array_glyph.prepare_array(arr, rgb=[0, 1, 2])
            >>> print(rgb_array.shape)
            (5, 5, 3)

            ```
        - If we compare the values of the first channel in the original array with the first array in the rgb array it
            should be the same.
            ```python
            >>> np.testing.assert_equal(arr[0, :, :],rgb_array[:, :, 0])

            ```
    surface_reflectance:
        - if you provide the surface reflectance value, the function will scale the array using the surface reflectance
            value to a normalized rgb values.
            ```python
            >>> array_glyph = ArrayGlyph(arr)
            >>> rgb_array = array_glyph.prepare_array(arr, surface_reflectance=10000, rgb=[0, 1, 2])
            >>> print(rgb_array.shape)
            (5, 5, 3)

            ```
        - if you print the values of the first channel, you will find all the values are between 0 and 1.
            ```python
            >>> print(rgb_array[:, :, 0]) # doctest: +SKIP
            [[0.0195 0.02   0.0109 0.0211 0.0087]
             [0.0112 0.0221 0.0035 0.0234 0.0141]
             [0.0116 0.0188 0.0001 0.0176 0.    ]
             [0.0014 0.0147 0.0043 0.0167 0.0117]
             [0.0083 0.0139 0.0186 0.02   0.0058]]

            ```
        - With the `surface_reflectance` parameter, you can also use the `cutoff` parameter to affect values that
            are above it, by rescaling them.
            ```python
            >>> rgb_array = array_glyph.prepare_array(
            ...     arr, surface_reflectance=10000, rgb=[0, 1, 2], cutoff=[0.8, 0.8, 0.8]
            ... )
            >>> print(rgb_array[:, :, 0]) # doctest: +SKIP
            [[0.     0.     0.     0.     0.    ]
             [1.     1.     1.     1.     1.    ]
             [1.     1.     1.     1.     1.    ]
             [0.0014 0.0147 0.0043 0.0167 0.0117]
             [0.0083 0.0139 0.0186 0.02   0.0058]]

            ```
    """
    # take the rgb arrays and reorder them to have the red-green-blue, if the order is not given, assume the
    # order as sentinel data. [3, 2, 1]
    array = array[rgb].transpose(1, 2, 0)

    if percentile is not None:
        array = self.scale_percentile(array, percentile=percentile)
    elif surface_reflectance is not None:
        array = self._prepare_sentinel_rgb(
            array,
            rgb=rgb,
            surface_reflectance=surface_reflectance,
            cutoff=cutoff,
        )
    return array

save_animation(path, fps=2) #

Save the animation to a file.

This method saves the animation created by the animate method to a file. The format of the output file is determined by the file extension in the path.

Parameters:

Name Type Description Default
path str

The file path where the animation will be saved. The file extension determines the output format. Supported formats: gif, mov, avi, mp4.

required
fps int

Frames per second for the saved animation, by default 2. Higher values create faster animations, lower values create slower animations.

2

Raises:

Type Description
ValueError

If the file extension is not one of the supported formats.

FileNotFoundError

If FFmpeg is not installed (required for mov, avi, and mp4 formats).

Notes
  • For GIF format, the PillowWriter is used.
  • For MOV, AVI, and MP4 formats, FFMpegWriter is used, which requires FFmpeg to be installed.
  • You can download FFmpeg from https://ffmpeg.org/

Examples:

Save an animation as a GIF file:

>>> import numpy as np
>>> from cleopatra.array_glyph import ArrayGlyph
>>> # Create a 3D array with 5 frames, each 10x10
>>> arr = np.random.randint(1, 10, size=(5, 10, 10))
>>> frame_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
>>> animated_array = ArrayGlyph(arr)
>>> anim_obj = animated_array.animate(frame_labels)
>>> animated_array.save_animation("animation.gif") # doctest: +SKIP
Save with a higher frame rate for a faster animation:
>>> animated_array.save_animation("animation.gif", fps=5) # doctest: +SKIP
Save in MP4 format (requires FFmpeg):
>>> animated_array.save_animation("animation.mp4", fps=10) # doctest: +SKIP

Source code in cleopatra/array_glyph.py
def save_animation(self, path: str, fps: int = 2):
    """Save the animation to a file.

    This method saves the animation created by the `animate` method to a file.
    The format of the output file is determined by the file extension in the path.

    Parameters
    ----------
    path : str
        The file path where the animation will be saved.
        The file extension determines the output format.
        Supported formats: gif, mov, avi, mp4.
    fps : int, optional
        Frames per second for the saved animation, by default 2.
        Higher values create faster animations, lower values create slower animations.

    Raises
    ------
    ValueError
        If the file extension is not one of the supported formats.
    FileNotFoundError
        If FFmpeg is not installed (required for mov, avi, and mp4 formats).

    Notes
    -----
    - For GIF format, the PillowWriter is used.
    - For MOV, AVI, and MP4 formats, FFMpegWriter is used, which requires FFmpeg to be installed.
    - You can download FFmpeg from https://ffmpeg.org/

    Examples
    --------
    Save an animation as a GIF file:
    ```python
    >>> import numpy as np
    >>> from cleopatra.array_glyph import ArrayGlyph
    >>> # Create a 3D array with 5 frames, each 10x10
    >>> arr = np.random.randint(1, 10, size=(5, 10, 10))
    >>> frame_labels = ["Frame 1", "Frame 2", "Frame 3", "Frame 4", "Frame 5"]
    >>> animated_array = ArrayGlyph(arr)
    >>> anim_obj = animated_array.animate(frame_labels)
    >>> animated_array.save_animation("animation.gif") # doctest: +SKIP

    ```
    Save with a higher frame rate for a faster animation:
    ```python
    >>> animated_array.save_animation("animation.gif", fps=5) # doctest: +SKIP

    ```
    Save in MP4 format (requires FFmpeg):
    ```python
    >>> animated_array.save_animation("animation.mp4", fps=10) # doctest: +SKIP

    ```
    """
    video_format = path.split(".")[-1]
    if video_format not in SUPPORTED_VIDEO_FORMAT:
        raise ValueError(
            f"The given extension {video_format} implies a format that is not supported, "
            f"only {SUPPORTED_VIDEO_FORMAT} are supported"
        )

    if video_format == "gif":
        writer_gif = animation.PillowWriter(fps=fps)
        self.anim.save(path, writer=writer_gif)
    else:
        try:
            if video_format == "avi" or video_format == "mov":
                writer_video = animation.FFMpegWriter(fps=fps, bitrate=1800)
                self.anim.save(path, writer=writer_video)
            elif video_format == "mp4":
                writer_mp4 = animation.FFMpegWriter(fps=fps, bitrate=1800)
                self.anim.save(path, writer=writer_mp4)
        except FileNotFoundError:
            print(
                "Please visit https://ffmpeg.org/ and download a version of ffmpeg compatible with your operating"
                "system, for more details please check the method definition"
            )

scale_percentile(arr, percentile=1) staticmethod #

Scale an array using percentile-based contrast stretching.

This method enhances the contrast of an image by stretching the histogram based on percentile values. It calculates the lower and upper percentile values for each band and normalizes the data to the range [0, 1].

Parameters:

Name Type Description Default
arr ndarray

The array to be scaled, with shape (height, width, bands). Typically an RGB image with 3 bands.

required
percentile int

The percentile value to be used for scaling, by default 1. This value determines how much of the histogram tails to exclude. Higher values result in more contrast stretching. Typical values range from 1 to 5.

1

Returns:

Type Description
ndarray

The scaled array, normalized between 0 and 1, with the same shape as input. Data type is float32.

Notes

The method works by: 1. Computing the lower percentile value for each band 2. Computing the upper percentile value (100 - percentile) for each band 3. Normalizing each band using these percentile values 4. Clipping values to the range [0, 1]

This is particularly useful for visualizing satellite imagery with high dynamic range.

Examples:

Scale a single-band array:

>>> import numpy as np
>>> from cleopatra.array_glyph import ArrayGlyph
>>> # Create a test array with values between 0 and 10000
>>> test_array = np.random.randint(0, 10000, size=(100, 100, 1))
>>> scaled = ArrayGlyph.scale_percentile(test_array, percentile=2)
>>> scaled.shape
(100, 100, 1)
>>> np.all((0 <= scaled) & (scaled <= 1))
np.True_
Scale an RGB array:
>>> rgb_array = np.random.randint(0, 10000, size=(100, 100, 3))
>>> scaled = ArrayGlyph.scale_percentile(rgb_array, percentile=2)
>>> scaled.shape
(100, 100, 3)
>>> np.all((0 <= scaled) & (scaled <= 1))
np.True_
Using different percentile values affects contrast:
>>> low_contrast = ArrayGlyph.scale_percentile(rgb_array, percentile=1)
>>> high_contrast = ArrayGlyph.scale_percentile(rgb_array, percentile=5)
>>> # Higher percentile typically results in higher contrast

Source code in cleopatra/array_glyph.py
@staticmethod
def scale_percentile(arr: np.ndarray, percentile: int = 1) -> np.ndarray:
    """Scale an array using percentile-based contrast stretching.

    This method enhances the contrast of an image by stretching the histogram
    based on percentile values. It calculates the lower and upper percentile values
    for each band and normalizes the data to the range [0, 1].

    Parameters
    ----------
    arr : np.ndarray
        The array to be scaled, with shape (height, width, bands).
        Typically an RGB image with 3 bands.
    percentile : int, optional
        The percentile value to be used for scaling, by default 1.
        This value determines how much of the histogram tails to exclude.
        Higher values result in more contrast stretching.
        Typical values range from 1 to 5.

    Returns
    -------
    np.ndarray
        The scaled array, normalized between 0 and 1, with the same shape as input.
        Data type is float32.

    Notes
    -----
    The method works by:
    1. Computing the lower percentile value for each band
    2. Computing the upper percentile value (100 - percentile) for each band
    3. Normalizing each band using these percentile values
    4. Clipping values to the range [0, 1]

    This is particularly useful for visualizing satellite imagery with high dynamic range.

    Examples
    --------
    Scale a single-band array:
    ```python
    >>> import numpy as np
    >>> from cleopatra.array_glyph import ArrayGlyph
    >>> # Create a test array with values between 0 and 10000
    >>> test_array = np.random.randint(0, 10000, size=(100, 100, 1))
    >>> scaled = ArrayGlyph.scale_percentile(test_array, percentile=2)
    >>> scaled.shape
    (100, 100, 1)
    >>> np.all((0 <= scaled) & (scaled <= 1))
    np.True_

    ```
    Scale an RGB array:
    ```python
    >>> rgb_array = np.random.randint(0, 10000, size=(100, 100, 3))
    >>> scaled = ArrayGlyph.scale_percentile(rgb_array, percentile=2)
    >>> scaled.shape
    (100, 100, 3)
    >>> np.all((0 <= scaled) & (scaled <= 1))
    np.True_

    ```
    Using different percentile values affects contrast:
    ```python
    >>> low_contrast = ArrayGlyph.scale_percentile(rgb_array, percentile=1)
    >>> high_contrast = ArrayGlyph.scale_percentile(rgb_array, percentile=5)
    >>> # Higher percentile typically results in higher contrast

    ```
    """
    rows, columns, bands = arr.shape
    # flatten image.
    arr = np.reshape(arr, [rows * columns, bands]).astype(np.float32)
    # lower percentile values (one value for each band).
    lower_percent = np.percentile(arr, percentile, axis=0)
    # 98 percentile values.
    upper_percent = np.percentile(arr, 100 - percentile, axis=0) - lower_percent
    # normalize the 3 bands using the percentile values for each band.
    arr = (arr - lower_percent[None, :]) / upper_percent[None, :]
    arr = np.reshape(arr, [rows, columns, bands])
    # discard outliers.
    arr = arr.clip(0, 1)

    return arr

scale_to_rgb(arr=None) #

Create an RGB image.

Parameters:

Name Type Description Default
arr ndarray

array. if None, the array in the object will be used.

None

Examples:

>>> import numpy as np
>>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> array = ArrayGlyph(arr)
>>> rgb_array = array.scale_to_rgb()
>>> print(rgb_array)
[[28 56 85]
 [113 141 170]
 [198 226 255]]
>>> print(rgb_array.dtype)
uint8
Source code in cleopatra/array_glyph.py
def scale_to_rgb(self, arr: np.ndarray = None) -> np.ndarray:
    """Create an RGB image.

    Parameters
    ----------
    arr: np.ndarray, default is None.
        array. if None, the array in the object will be used.

    Examples
    --------
    ```python
    >>> import numpy as np
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array = ArrayGlyph(arr)
    >>> rgb_array = array.scale_to_rgb()
    >>> print(rgb_array)
    [[28 56 85]
     [113 141 170]
     [198 226 255]]
    >>> print(rgb_array.dtype)
    uint8

    ```
    """
    if arr is None:
        arr = self.arr
    # This is done to scale the values between 0 and 255
    return (arr * 255 / arr.max()).astype("uint8")

to_image(arr=None) #

Create an RGB image from an array.

convert the array to an image.

Parameters:

Name Type Description Default
arr ndarray

array. if None, the array in the object will be used.

None

Examples:

>>> import numpy as np
>>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> array = ArrayGlyph(arr)
>>> image = array.to_image()
>>> print(image) # doctest: +SKIP
<PIL.Image.Image image mode=RGB size=3x3 at 0x7F5E0D2F4C40>
Source code in cleopatra/array_glyph.py
def to_image(self, arr: np.ndarray = None) -> Image.Image:
    """Create an RGB image from an array.

        convert the array to an image.

    Parameters
    ----------
    arr: np.ndarray, default is None.
        array. if None, the array in the object will be used.

    Examples
    --------
    ```python
    >>> import numpy as np
    >>> arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> array = ArrayGlyph(arr)
    >>> image = array.to_image()
    >>> print(image) # doctest: +SKIP
    <PIL.Image.Image image mode=RGB size=3x3 at 0x7F5E0D2F4C40>

    ```
    """
    if arr is None:
        arr = self.arr
    # This is done to scale the values between 0 and 255
    arr = arr if arr.dtype == "uint8" else self.scale_to_rgb()
    return Image.fromarray(arr).convert("RGB")

Examples#

Basic Array Plot#

import numpy as np
from cleopatra.array_glyph import ArrayGlyph

# Create a sample array
array = np.random.rand(10, 10)

# Create an ArrayGlyph object
array_glyph = ArrayGlyph(array)

# Plot the array
fig, ax, im, cbar = array_glyph.plot()

Array Plot Example

Display Cell Values#

# Plot the array with cell values displayed
fig, ax, im, cbar = array_glyph.plot(display_cell_values=True)

Display Cell Values Example

Display Points#

# Create some points to display on the array
points = np.array([[2, 3, 1], [5, 7, 2], [8, 1, 3]])

# Plot the array with points
fig, ax, im, cbar = array_glyph.plot(points=points)

Display Points Example

Animation#

import numpy as np
from cleopatra.array_glyph import ArrayGlyph

# Create a time series of arrays
time_series = [np.random.rand(10, 10) for _ in range(5)]
time_labels = ["t1", "t2", "t3", "t4", "t5"]

# Create an ArrayGlyph object with the first array
array_glyph = ArrayGlyph(time_series[0])

# Animate the array over time
anim = array_glyph.animate(time=time_labels, points=points)

# Save the animation
array_glyph.save_animation("animation.gif", fps=2)

Animation Example