Source Code

Backend Class

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
#cython: linetrace=True
#distutils: define_macros=CYTHON_TRACE_NOGIL=1
#cython: language_level=3
# cython: embedsignature=True, binding=True
"""
Copyright (C) 2020 AMSIMP

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see https://www.gnu.org/licenses/.
"""

# ------------------------------------------------------------------------------#

# Importing Dependencies
import os, sys, socket
from datetime import datetime, timedelta
import numpy as np
from astropy import constants as constant
from astropy import units
from astropy.units.quantity import Quantity
cimport numpy as np
from cpython cimport bool
import matplotlib.pyplot as plt
from matplotlib import ticker
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
import iris
from iris.coords import DimCoord
from iris.cube import Cube
from iris.coord_systems import GeogCS

# ------------------------------------------------------------------------------#

cdef class Backend:
    """
    This is the base class for AMSIMP, as such, all other classes within AMSIMP
    inherit this class, either directly or indirectly.
    """

    # Meteorologically significant constants
    # Sidereal day in seconds.
    sidereal_day = (23 + (56 / 60)) * 3600 * units.s
    # Angular rotation rate of the planet.
    Upomega = ((2 * np.pi) / ((23 + (56 / 60)) * 3600))
    # Mean radius of the planet.
    a = constant.R_earth.value * constant.R_earth.unit
    # Mass of the planet.
    M = constant.M_earth.value * constant.M_earth.unit
    # The specific heat capacity on a constant pressure surface.
    c_p = 718 * (units.J / (units.kg * units.K))
    # Gravitational acceleration.
    g = 9.80665 * (units.m / (units.s ** 2))
    # Gas constant.
    R = 287.05799596 * (units.J / (units.kg * units.K))
    # Universal gravitational constant.
    G = constant.G
    G = G.value * G.unit

    def __cinit__(self, forecast_length=120, historical_data=None):
        """
        The parameter, forecast_length, defines the length of the 
        weather forecast (defined in hours). Defaults to a value of 120.
        It is currently not recommended to generate a climate forecast
        using this software, as it has not been tested for this purpose.
        This may change at some point in the future.

        The parameter, historical_data, defines the state of the atmosphere
        in the past thirty days in two-hour intervals up to the present 
        moment. The following  parameters must be defined: air
        temperature (air_temperature), zonal wind (x_wind), meridional
        wind (y_wind), geopotential, and relative 
        humidity (relative_humidity). The expected input parameter is
        an iris cube list. Each cube must have the same grid points as
        all of the other cubes. The grid must be 3 dimensional, and consist
        of: pressure, latitude, and longitude. The pressure surfaces must
        start at the lowest pressure value, and increase from that point.
        The latitude points range from -90 to 90, and the longitude points
        range from -180 to 180. The pressure grid must be named 'air_pressure',
        and the unit of pressure must be Pascal. An example dataset may be
        download using the following Google Drive link:

        https://drive.google.com/file/d/1lsZYfnqwm1hr6d7RiDHBPC9_rUx-q_FV/view?usp=sharing
        """
        # Make the aforementioned variables available else where in the class.
        self.historical_data = historical_data
        if type(forecast_length) != Quantity:
            forecast_length *= units.hr
        self.forecast_length = forecast_length

        # Ensure self.forecast_length is greater than, or equal to 1.
        if self.forecast_length.value <= 0:
            raise Exception(
                "forecast_length must be a positive number greater than, or equal to 1. "
                +  "The value of forecast_length was: {}".format(self.forecast_length)
            )

        # The date at which the initial conditions was gathered (i.e. how
        # recent the data is).
        time = self.historical_data[0][-1].coord('time')
        date = [cell.point for cell in time.cells()]
        date = date[0]
        self.date = date

        # Function to ensure that the input data is 4 dimensional and that
        # there is 30 days of atmospheric conditions in two-hour intervals.
        def dimension(input_variable):
            if np.ndim(input_variable.data) != 4:
                raise Exception(
                    "All cubes in the cube list must be a 4 dimensional."
                )
            
            if input_variable.data.shape[0] != 180:
                raise Exception(
                    "The past thirty days in two-hour intervals up to the present "
                    + "moment must be define in order to use the software."
                )

        # Check if the input is a cube list.
        if type(self.historical_data) != iris.cube.CubeList:
            raise Exception(
                "The expected input parameter is an iris cube list."
            )
        
        # Extract all of the relevant atmospheric parameters.
        try:
            # Geopotential.
            geo = self.historical_data.extract("geopotential")[0]
            dimension(geo)
            geo = geo[:, ::-1, ::-1, :]
            self.input_geo = geo
            # Air temperature.
            temp = self.historical_data.extract("air_temperature")[0]
            dimension(temp)
            temp = temp[:, ::-1, ::-1, :]
            self.input_temp = temp
            # Relative humidity.
            rh = self.historical_data.extract("relative_humidity")[0]
            dimension(rh)
            rh = rh[:, ::-1, ::-1, :]
            self.input_rh = rh
            # Zonal wind.
            u = self.historical_data.extract("x_wind")[0]
            dimension(u)
            u = u[:, ::-1, ::-1, :]
            self.input_u = u
            # Meridional wind.
            v = self.historical_data.extract("y_wind")[0]
            dimension(v)
            v = v[:, ::-1, ::-1, :]
            self.input_v = v
        except:
            raise Exception(
                "The following  parameters must be defined: air "
                + "temperature (air_temperature), zonal wind (x_wind), "
                + "meridional wind (y_wind), geopotential, and "
                + "relative humidity (relative_humidity).")
        
        # Define the grid points.
        # Pressure surfaces.
        try:
            psurfaces = geo.coords('air_pressure')[0].points
        except:
            psurfaces = geo.coords('pressure_level')[0].points
        psurfaces *= units.mbar
        self.psurfaces = psurfaces

        # Latitude.
        lat = geo.coords('latitude')[0].points
        self.lat = lat

        # Longitude.
        lon = geo.coords('longitude')[0].points
        self.lon = lon

        # Function to check for an internet connection.
        def is_connected():
            try:
                host = socket.gethostbyname("www.github.com")
                s = socket.create_connection((host, 80), 2)
                s.close()
                return True
            except OSError:
                pass
            return False

        # Check for an internet connection.
        if not is_connected():
            raise Exception(
                "You must connect to the internet in order to utilise AMSIMP."
                + " Apologies for any inconvenience caused."
            )

# ------------------------------------------------------------------------------#

    cpdef np.ndarray latitude_lines(self):
        r"""Generates an array of latitude lines.

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Latitude lines

        See Also
        --------
        longitude_lines, pressure_surfaces
        """
        latitude_lines = self.lat * units.deg

        return latitude_lines
    
    cpdef np.ndarray longitude_lines(self):
        r"""Generates an array of longitude lines.

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Longitude lines

        See Also
        --------
        latitude_lines, pressure_surfaces
        """
        longitude_lines = self.lon * units.deg

        return longitude_lines

    cpdef np.ndarray pressure_surfaces(self, dim_3d=False):
        r"""Generates an array of constant pressure surfaces. 

        Parameters
        ----------
        dim_3d: `bool`
            If true, this will generate a 3-dimensional array
        
        Returns
        -------
        `astropy.units.quantity.Quantity`
            Constant pressure surfaces

        Notes
        -----
        This is the isobaric coordinate system.

        See Also
        --------
        latitude_lines, longitude_lines
        """
        pressure_surfaces = self.psurfaces
        
        return pressure_surfaces

# ------------------------------------------------------------------------------#

    cpdef np.ndarray gradient_longitude(self, parameter=None):
        r"""Calculate the gradient of a grid of values with respect to longitude.

        Parameters
        ----------
        parameter: `astropy.units.quantity.Quantity`
            Array of values of which to calculate the gradient

        Returns
        -------
        `astropy.units.quantity.Quantity`
            The gradient calculated with respect to longitude of the original array

        Notes
        -----
        The gradient is computed using second order accurate central differences
        in the interior points. The boundaries are joined together for the purposes
        of this compuation, allowing for the use of second order accurate central 
        differences at the boundaries.

        See Also
        --------
        gradient_latitude, gradient_pressure
        """
        # Determine gradient with respect to longitude.
        cdef np.ndarray longitude = np.radians(self.longitude_lines().value)

        # Define variable types.
        cdef np.ndarray parameter_central, parameter_boundaries
        cdef np.ndarray parameter_lgmt, parameter_rgmt
        cdef np.ndarray lon_lgmt, lon_rgmt, lon_boundaries

        # Compute gradient.
        # Central points.
        parameter_central = np.gradient(
            parameter, longitude, axis=2
        )

        # Boundaries.
        # Define atmospheric parameter boundaries.
        parameter_lgmt = parameter[:, :, -3:].value
        parameter_rgmt = parameter[:, :, :3].value
        # Define longitude boundaries.
        lon_lgmt = longitude[-3:]
        lon_rgmt = longitude[:3]
        # Concatenate atmospheric parameter boundaries.
        parameter_boundaries = np.concatenate(
            (parameter_lgmt, parameter_rgmt), axis=2
        ) * parameter.unit
        # Concatenate longitude boundaries.
        lon_boundaries = np.concatenate((lon_lgmt, lon_rgmt))
        # Compute gradient at boundaries.
        parameter_boundaries = np.gradient(
            parameter_boundaries, lon_boundaries, axis=2
        )
        # Redefine parameter as computed gradient.
        parameter = parameter_central
        parameter[:, :, -1] = parameter_boundaries[:, :, 2]
        parameter[:, :, 0] = parameter_boundaries[:, :, 3]

        # Make 1d latitude array into a 3d latitude array.
        cdef np.ndarray latitude = np.radians(self.latitude_lines())
        latitude = self.make_3dimensional_array(
            parameter=latitude, axis=1
        )

        # Handle longitudinal variation with respect to latitude.
        gradient_longitude = (
            (1 / (self.a * np.cos(latitude.value))) * parameter
        )

        return gradient_longitude

    cpdef np.ndarray gradient_latitude(self, parameter=None):
        r"""Calculate the gradient of a grid of values with respect to latitude.

        Parameters
        ----------
        parameter: `astropy.units.quantity.Quantity`
            Array of values of which to calculate the gradient

        Returns
        -------
        `astropy.units.quantity.Quantity`
            The gradient calculated with respect to latitude of the original array

        Notes
        -----
        The gradient is computed using second order accurate central differences
        in the interior points and either first or second order accurate 
        one-sides (forward or backwards) differences at the boundaries.
        The returned gradient hence has the same shape as the input array.

        See Also
        --------
        gradient_longitude, gradient_pressure
        """
        # Define variable.
        cdef np.ndarray latitude = np.radians(self.latitude_lines().value)

        # Determine gradient with respect to latitude.
        gradient_latitude = np.gradient(
            parameter.value, self.a.value * latitude, axis=1
        ) * (parameter.unit / units.m)

        return gradient_latitude
    
    cpdef np.ndarray gradient_pressure(self, parameter=None):
        r"""Calculate the gradient of a grid of values with respect to pressure.

        Parameters
        ----------
        parameter: `astropy.units.quantity.Quantity`
            Array of values of which to calculate the gradient

        Returns
        -------
        `astropy.units.quantity.Quantity`
            The gradient calculated with respect to pressure of the original array

        Notes
        -----
        The gradient is computed using second order accurate central differences
        in the interior points and either first or second order accurate 
        one-sides (forward or backwards) differences at the boundaries.
        The returned gradient hence has the same shape as the input array.

        See Also
        --------
        gradient_longitude, gradient_latitude
        """
        # Define variable.
        cdef np.ndarray pressure = self.pressure_surfaces()

         # Determine gradient with respect to pressure.
        gradient_pressure = np.gradient(
            parameter.value, pressure.value, axis=0
        ) * (parameter.unit / units.hPa)

        return gradient_pressure

    cpdef np.ndarray make_3dimensional_array(self, parameter=None, axis=1):
        r"""Convert 1-dimensional array to array with three dimensions.

        Parameters
        ----------
        parameter: `astropy.units.quantity.Quantity`
            Input array to be converted 
        axis: `int`
            Defines the variable over which the given parameter varies

        Returns
        -------
        `astropy.units.quantity.Quantity`
            3-dimensional version of input array
        
        Notes
        -----
        If axis is set to 0, this variable is constant pressure surfaces. 
        If axis is set to 1, this variable is latitude.  If axis is set to
        2, this variable is longitude.
        """
        if axis == 0:
            a = self.latitude_lines().value
            b = self.longitude_lines().value
        elif axis == 1:
            a = self.pressure_surfaces().value
            b = self.longitude_lines().value
        elif axis == 2:
            a = self.pressure_surfaces().value
            b = self.latitude_lines().value

        list_parameter = []
        for param in parameter:
            unit = param.unit
            param = param.value + np.zeros((len(a), len(b)))
            param = param.tolist()
            list_parameter.append(param)
        parameter = np.asarray(list_parameter) * unit

        if axis == 1:
            parameter = np.transpose(parameter, (1, 0, 2))
        elif axis == 2:
            parameter = np.transpose(parameter, (1, 2, 0))
        
        return parameter

# ------------------------------------------------------------------------------#

    cpdef np.ndarray coriolis_parameter(self):
        r"""Generates an arrray of the Coriolis parameter at various latitudes.

        .. math:: f = 2 \Omega \sin{\phi}

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Coriolis parameter

        Notes
        -----      
        The Coriolis parameter is defined as two times the angular rotation of
        the Earth by the sin of the latitude you are interested in.
        """
        coriolis_parameter = (
            2 * self.Upomega * np.sin(np.radians(self.latitude_lines()))
        )

        return coriolis_parameter

# ------------------------------------------------------------------------------#

    cpdef geopotential_height(self, bool cube=False):
        r"""Generates an arrray of geopotential height.
        
        Returns
        -------
        `astropy.units.quantity.Quantity`
            Geopotential height

        Notes
        -----
        If the user did not define initial conditions on initialisation
        of the class, this data is retrieved from the AMSIMP Initial
        Conditions Data Repository on GitHub. Geopotential Height is the
        height above sea level of a pressure level. For example, if a 
        station reports that the 500 hPa height at its location is 5600 m,
        it means that the level of the atmosphere over that station at which
        the atmospheric pressure is 500 hPa is 5600 meters above sea level.

        See Also
        --------
        relative_humidity, temperature
        """
        geopotential_height = self.input_geo / self.g
        geopotential_height = np.asarray(
            geopotential_height[-1].data
        ) * units.m
        
        return geopotential_height

    cpdef relative_humidity(self, bool cube=False):
        r"""Generates an arrray of relative humidity.
        
        Returns
        -------
        `astropy.units.quantity.Quantity`
            Relative humidity

        Notes
        -----
        If the user did not define initial conditions on initialisation
        of the class, this data is retrieved from the AMSIMP Initial
        Conditions Data Repository on GitHub. Relative Humidity is the amount
        of water vapour present in air expressed as a percentage of the amount
        needed for saturation at the same temperature.

        See Also
        --------
        geopotential_height, temperature
        """
        relative_humidity = self.input_rh[-1].data
        relative_humidity = np.asarray(relative_humidity) * units.percent
        
        return relative_humidity

    cpdef temperature(self, bool cube=False):
        r"""Generates an arrray of temperature.
        
        Returns
        -------
        `astropy.units.quantity.Quantity`
            Temperature

        Notes
        -----
        If the user did not define initial conditions on initialisation
        of the class, this data is retrieved from the AMSIMP Initial
        Conditions Data Repository on GitHub. Temperature is defined as
        the mean kinetic energy density of molecular motion.

        See Also
        --------
        geopotential_height, relative_humidity
        """
        temperature = self.input_temp[-1].data
        temperature = np.asarray(temperature) * units.K
        
        return temperature

    cpdef exit(self):
        r"""This method deletes any file created by the software.

        Notes
        -----
        This command will also cause the Python interpreter to close
        and exit. It does not delete any forecast generated and saved
        by the software.

        See Also
        --------
        geopotential_height, relative_humidity, temperature
        """
        # Initial atmospheric conditions file.
        try:
            os.remove("initial_conditions.nc")
        except OSError:
            pass
        
        # Close Python.
        sys.exit()

# ------------------------------------------------------------------------------#

    cpdef np.ndarray pressure_thickness(self, p1=1000, p2=500):
        r"""Generates an array of the thickness of a layer.

        .. math:: h = z_2 - z_1

        Parameters
        ----------
        p1: `int`
            Bottom of the layer.
        p2: `int`
            Top of the layer.

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Pressure thickness        
        
        Notes
        -----
        Pressure thickness is defined as the distance between two
        pressure surfaces. Pressure thickness is determined through the
        hypsometric equation.
        """
        # Ensure p1 is greater than p2.
        if p1 < p2:
            raise Exception("Please note that p1 must be greater than p2.")

        # Find the nearest constant pressure surface to p1 and p2 in pressure.
        cdef int indx_p1 = (np.abs(self.pressure_surfaces().value - p1)).argmin()
        cdef int indx_p2 = (np.abs(self.pressure_surfaces().value - p2)).argmin()

        pressure_thickness = (
            self.geopotential_height()[indx_p2] - self.geopotential_height()[indx_p1]
        )

        return pressure_thickness

    cpdef np.ndarray troposphere_boundaryline(self):
        r"""Generates an array of the troposphere - stratosphere boundary line.

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Troposphere - stratosphere boundary line

        Notes
        -----
        The atmosphere is divided into four distinct layers: the troposphere,
        the stratosphere, the mesosphere, and the thermosphere. These layers
        are defined and  characterised by their vertical temperature profile.
        In the troposphere, temperature decreases with altitude; while in the
        stratosphere, temperature increases with altitude. This method
        determines the point at which temperature starts to increase with
        altitude (the boundary line between these two layers).

        See Also
        --------
        temperature
        """
        cdef np.ndarray temperature = self.temperature().value
        grad_temperature = np.gradient(temperature)
        cdef np.ndarray gradient_temperature = grad_temperature[0]
        gradient_temperature = np.transpose(gradient_temperature, (2, 1, 0))

        cdef np.ndarray psurface = self.pressure_surfaces().value

        cdef list trop_strat_line = []
        cdef list lat_trop_strat_line
        cdef np.ndarray temp, t
        cdef int n
        cdef float t_n, p
        for temp in gradient_temperature:
            lat_trop_strat_line = []
            for t in temp:
                n = 0
                while n < len(t):
                    t_n = t[n]
                    if t[n] >= 0:
                        p = psurface[n]
                        if p < 400:
                            lat_trop_strat_line.append(p)
                            n = len(t)
                    n += 1
            trop_strat_line.append(lat_trop_strat_line)

        troposphere_boundaryline = np.asarray(trop_strat_line)
        troposphere_boundaryline = np.transpose(troposphere_boundaryline, (1, 0)) 
        troposphere_boundaryline *= units.hPa
        return troposphere_boundaryline

# ------------------------------------------------------------------------------#

    def longitude_contourf(self, which="air_temperature", psurface=1000):
        r"""Plots a desired atmospheric parameter on a contour plot.

        Parameters
        ----------
        which: `str`
            Desired atmospheric parameter
        psurface: `int`
            Pressure at which the contour plot is generated

        Notes
        -----
        For the raw data, please see the other methods found in this class.
        This plot is layed on top of a EckertIII global projection. The
        axes are latitude and longitude. If you would like a particular
        atmospheric parameter to be added to this method, either create 
        an issue on GitHub or send an email to support@amsimp.com.

        See Also
        --------
        psurface_contourf, thickness_contourf
        """        
        # Ensure, which, is a string.
        if not isinstance(which, str):
            raise Exception(
                "which must be a string of the name of the"
                + "atmospheric parameter of interest."
            )

        # Index of the nearest pressure surface in 
        # amsimp.Backend.pressure_surfaces()
        indx_psurface = (
            np.abs(self.pressure_surfaces().value - psurface)
        ).argmin()
        
        # Defines the axes, and the data.
        latitude, longitude = np.meshgrid(
            self.latitude_lines().value,
            self.longitude_lines().value
        )

        if which == "temperature" or which == "air_temperature":
            data = self.temperature()[indx_psurface, :, :]
            data_type = "Air Temperature"
            unit = " (K)"
        elif which == "geopotential_height" or which == "height":
            data = self.geopotential_height()[indx_psurface, :, :]
            data_type = "Geopotential Height"
            unit = " (m)"
        elif which == "density" or which == "atmospheric_density":
            data = self.density()[indx_psurface, :, :]
            data_type = "Atmospheric Density"
            unit = " ($\\frac{kg}{m^3}$)"
        elif which == "humidity" or which == "relative_humidity":
            data = self.relative_humidity()[indx_psurface, :, :]
            data_type = "Relative Humidity"
            unit = " (%)"
        elif which == "virtual_temperature":
            data = self.virtual_temperature()[indx_psurface, :, :]
            data_type = "Virtual Temperature"
            unit = " (K)"
        elif which == "vapor_pressure":
            data = self.vapor_pressure()[indx_psurface, :, :]
            data_type = "Vapor Pressure"
            unit = " (hPa)"
        elif which == "potential_temperature":
            data = self.potential_temperature()[indx_psurface, :, :]
            data_type = "Potential Temperature"
            unit = " (K)"
        elif which == "precipitable_water" or which == "precipitable_water_vapor":
            data = self.precipitable_water()
            data_type = "Precipitable Water Vapor"
            unit = " (mm)"
        elif which == "zonal_wind":
            data = self.wind()[0][indx_psurface, :, :]
            data_type = "Zonal Wind"
            unit = " ($\\frac{m}{s}$)"
        elif which == "meridional_wind":
            data = self.wind()[1][indx_psurface, :, :]
            data_type = "Meridional Wind"
            unit = " ($\\frac{m}{s}$)"
        elif which == "wind":
            data = self.wind()
            data = np.sqrt(data[0]**2 + data[1]**2)[indx_psurface, :, :]
            data_type = "Wind"
            unit = " ($\\frac{m}{s}$)"
        elif which == "mixing_ratio":
            data = self.mixing_ratio()[indx_psurface, :, :]
            data_type = "Mixing Ratio"
            unit = " (Dimensionless)"
        else:
            raise Exception(
                "Invalid keyword. which must be a string of an atmospheric "
                + "parameter included with AMSIMP."
            )

        psurfaces = self.pressure_surfaces().value
        if psurface < psurfaces[-1] or psurface > psurfaces[0]:
            raise Exception(
                "psurface must be a real number within the isobaric boundaries."
                + " The value of psurface was: {}".format(
                    psurface
                )
            )

        # EckertIII projection details.
        ax = plt.axes(projection=ccrs.EckertIII())
        ax.set_global()
        ax.coastlines()
        ax.gridlines()

        # Contourf plotting.
        minimum = data.min()
        maximum = data.max()
        levels = np.linspace(minimum, maximum, 21)
        data, lon = add_cyclic_point(data, coord=self.longitude_lines().value)
        data, lat = add_cyclic_point(
            np.transpose(data), coord=self.latitude_lines().value
        )
        data = np.transpose(data)
        contour = plt.contourf(
            lon,
            lat,
            data,
            transform=ccrs.PlateCarree(),
            levels=levels,
        )

        # Add SALT.
        plt.xlabel("Latitude ($\phi$)")
        plt.ylabel("Longitude ($\lambda$)")
        title = (
            data_type + " ("
            + str(self.date.year) + '-' + str(self.date.month) + '-'
            + str(self.date.day) + " " + str(self.date.hour)
            + ":00 h)"
        )
    
        if which != "precipitable_water" and which != "precipitable_water_vapor":
            title = (
                title + " (" + "Pressure Surface = " + str(
                    self.pressure_surfaces()[indx_psurface]
                ) + ")"
            )

        plt.title(title)

        # Colorbar creation.
        colorbar = plt.colorbar()
        tick_locator = ticker.MaxNLocator(nbins=15)
        colorbar.locator = tick_locator
        colorbar.update_ticks()
        colorbar.set_label(
            data_type + unit
        )

        plt.show()
        plt.close()
    
    def psurface_contourf(self, which="air_temperature", central_long=352.3079):
        r"""Plots a desired atmospheric parameter on a contour plot, with the axes
        being latitude, and pressure surfaces. 
        
        Parameters
        ----------
        which: `str`
            Desired atmospheric parameter
        central_long: `int`
            Line of longitude at which the contour plot is generated

        Notes
        -----
        For the raw data, please see the other methods found in this class.
        This plot is layed on top of a EckertIII global projection. The
        axes are pressure and latitude. If you would like a particular
        atmospheric parameter to be added to this method, either create 
        an issue on GitHub or send an email to support@amsimp.com.

        See Also
        --------
        longitude_contourf, thickness_contourf
        """
        # Ensure, which, is a string.
        if not isinstance(which, str):
            raise Exception(
                "which must be a string of the name of the atmospheric parameter"
                + " of interest."
            )
        
        # Ensure central_long is between 0 and 359.
        if central_long < 0 or central_long > 359:
            raise Exception(
                "central_long must be a real number between 0 and 359. The value"
                + " of central_long was: {}".format(
                    central_long
                )
            )
        
        # Index of the nearest central_long in amsimp.Backend.longtitude_lines()
        indx_long = (np.abs(self.longitude_lines().value - central_long)).argmin()

        # Defines the axes, and the data.
        latitude, pressure_surfaces = np.meshgrid(
            self.latitude_lines().value, self.pressure_surfaces()
        )
        
        if which == "temperature" or which == "air_temperature":
            data = self.temperature()[:, :, indx_long]
            data_type = "Air Temperature"
            unit = " (K)"
        elif which == "density" or which == "atmospheric_density":
            data = self.density()[:, :, indx_long]
            data_type = "Atmospheric Density"
            unit = " ($\\frac{kg}{m^3}$)"
        elif which == "humidity" or which == "relative_humidity":
            data = self.relative_humidity()[:, :, indx_long]
            data_type = "Relative Humidity"
            unit = " (%)"
        elif which == "virtual_temperature":
            data = self.virtual_temperature()[:, :, indx_long]
            data_type = "Virtual Temperature"
            unit = " (K)"
        elif which == "vapor_pressure":
            data = self.vapor_pressure()[:, :, indx_long]
            data_type = "Vapor Pressure"
            unit = " (hPa)"
        elif which == "potential_temperature":
            data = self.potential_temperature()[:, :, indx_long]
            data_type = "Potential Temperature"
            unit = " (K)"
        elif which == "zonal_wind":
            data = self.wind()[0][:, :, indx_long]
            data_type = "Zonal Wind"
            unit = " ($\\frac{m}{s}$)"
        elif which == "meridional_wind":
            data = self.wind()[1][:, :, indx_long]
            data_type = "Meridional Wind"
            unit = " ($\\frac{m}{s}$)"
        elif which == "mixing_ratio":
            data = self.mixing_ratio()[:, :, indx_long]
            data_type = "Mixing Ratio"
            unit = " (Dimensionless)"
        else:
            raise Exception(
                "Invalid keyword. which must be a string of an atmospheric parameter"
                + " included with AMSIMP."
            )

        # Contourf plotting.
        minimum = data.min()
        maximum = data.max()
        levels = np.linspace(minimum, maximum, 21)
        plt.contourf(
            latitude,
            pressure_surfaces,
            data,
            levels=levels,
        )

        # Add SALT.
        plt.xlabel("Latitude ($\phi$)")
        plt.ylabel("Pressure (hPa)")
        plt.yscale('log')
        plt.gca().invert_yaxis()
        plt.title(
            data_type + " ("
            + str(self.date.year) + '-' + str(self.date.month) + '-'
            + str(self.date.day) + " " + str(self.date.hour)
            + ":00 h, Longitude = "
            + str(np.round(self.longitude_lines()[indx_long], 2)) + ")"
        )

        # Colorbar creation.
        colorbar = plt.colorbar()
        tick_locator = ticker.MaxNLocator(nbins=15)
        colorbar.locator = tick_locator
        colorbar.update_ticks()
        colorbar.set_label(
            data_type + unit
        )

        # Average boundary line between the troposphere and the stratosphere.
        troposphere_boundaryline = self.troposphere_boundaryline()
        avg_tropstratline = np.mean(troposphere_boundaryline) + np.zeros(
            len(troposphere_boundaryline)
        )

        # Plot average boundary line on the contour plot.
        plt.plot(
            latitude[1],
            avg_tropstratline,
            color="black",
            linestyle="dashed",
            label="Troposphere - Stratosphere Boundary Line",
        )
        plt.legend(loc=0)

        plt.show()
        plt.close()
    
    def thickness_contourf(self, p1=1000, p2=500):
        r"""Plots the thickness of a layer on a contour plot.

        Parameters
        ----------
        p1: `int`
            Bottom of the layer
        p2: `int`
            Top of the layer

        Notes
        -----
        This plot is layed on top of a EckertIII global projection. If you
        would like a particular atmospheric parameter to be added to 
        this method, either create an issue on GitHub or send an email
        to support@amsimp.com.

        See Also
        --------
        pressure_thickness, longitude_contourf, psurface_contourf
        """
        # Defines the axes, and the data.
        latitude, longitude = (
            self.latitude_lines().value, self.longitude_lines().value
        )

        pressure_thickness = self.pressure_thickness(p1=p1, p2=p2)

        # EckertIII projection details.
        ax = plt.axes(projection=ccrs.EckertIII())
        ax.set_global()
        ax.coastlines()
        ax.gridlines()

        # Contourf plotting.
        minimum = pressure_thickness.min()
        maximum = pressure_thickness.max()
        levels = np.linspace(minimum, maximum, 21)
        pressure_thickness, longitude = add_cyclic_point(
            pressure_thickness, coord=longitude
        )
        pressure_thickness, latitude = add_cyclic_point(
            np.transpose(pressure_thickness), coord=latitude
        )
        pressure_thickness = np.transpose(pressure_thickness)
        contour = plt.contourf(
            longitude,
            latitude,
            pressure_thickness,
            transform=ccrs.PlateCarree(),
            levels=levels,
        )

        # Index of the rain / snow line
        indx_snowline = (np.abs(levels.value - 5400)).argmin()
        contour.collections[indx_snowline].set_color('black')
        contour.collections[indx_snowline].set_linewidth(1) 

        # Add SALT.
        plt.xlabel("Latitude ($\phi$)")
        plt.ylabel("Longitude ($\lambda$)")
        plt.title("Pressure Thickness ("
            + str(self.date.year) + '-' + str(self.date.month) + '-'
            + str(self.date.day) + " " + str(self.date.hour) + ":00 h"
            + ")"
        )

        # Colorbar creation.
        colorbar = plt.colorbar()
        tick_locator = ticker.MaxNLocator(nbins=15)
        colorbar.locator = tick_locator
        colorbar.update_ticks()
        colorbar.set_label(
            "Pressure Thickness (" + str(p1) + " hPa - " + str(p2) + " hPa) (m)"
        )

        # Footnote
        if p1 == 1000 and p2 == 500:
            plt.figtext(
                0.99,
                0.01,
                "Rain / Snow Line is marked by the black line (5,400 m).",
                horizontalalignment="right",
            )

        plt.show()
        plt.close()

Wind Class

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#cython: linetrace=True
#distutils: define_macros=CYTHON_TRACE_NOGIL=1
#cython: language_level=3
# cython: embedsignature=True, binding=True
"""
Copyright (C) 2020 AMSIMP

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see https://www.gnu.org/licenses/.
"""

# ------------------------------------------------------------------------------#

# Importing Dependencies
import os
import iris
from astropy import units
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib.widgets import Slider, Button
import numpy as np
from amsimp.moist cimport Moist
from amsimp.moist import Moist
cimport numpy as np
from cpython cimport bool

# ------------------------------------------------------------------------------#

cdef class Wind(Moist):
    """
    This class is concerned with calculating numerical values for wind.
    """

    cpdef np.ndarray static_stability(self):
        r"""Generates an array of the the static stability.

        .. math:: \sigma = - \frac{R T}{p \theta} \frac{\partial \theta}{\partial p}

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Static stability

        Notes
        -----
        Static stability is defined as the stability of the
        atmosphere in hydrostatic equilibrium with respect to vertical
        displacements.
        """
        cdef np.ndarray theta = self.potential_temperature(moist=False)
        cdef np.ndarray temperature = self.temperature()
        cdef np.ndarray pressure = self.pressure_surfaces(dim_3d=True)

        static_stability = - self.R * (
                temperature / (pressure * theta)
            ) * self.gradient_p(
                parameter=theta
        )
        return static_stability

    cpdef tuple wind(self, bool cube=False):
        r"""Generates an arrray of wind.
        
        Returns
        -------
        `tuple`
            Wind (zonal and meridional components)

        Notes
        -----
        If the user did not define initial conditions on initialisation
        of the class, this data is retrieved from the AMSIMP Initial
        Conditions Data Repository on GitHub. Wind is the flow of gases
        on a large scale. Wind consists of the bulk movement of air.

        See Also
        --------
        vertical_motion
        """
        # Zonal.
        u = self.input_u.data
        u = np.asarray(u) * (units.m / units.s)
        # Meridional.
        v = self.input_v.data
        v = np.asarray(v) * (units.m / units.s)

        return u, v

    cpdef np.ndarray vertical_motion(self):
        r"""Generates an array of the vertical motion.
        
        .. math:: \frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} \
            = - \frac{\partial \omega}{\partial p}
        
        Returns
        -------
        `astropy.units.quantity.Quantity`
            Vertical motion

        Notes
        -----
        Typical large-scale vertical motions in the atmosphere
        are of the order of 0.01 – 0.1 :math:`\frac{m}{s}`.

        See Also
        --------
        wind
        """
        # Define variables.
        cdef np.ndarray latitude = np.radians(self.latitude_lines()).value
        cdef np.ndarray longitude = np.radians(self.longitude_lines()).value
        cdef np.ndarray pressure = self.pressure_surfaces(dim_3d=True)
        cdef np.ndarray u, v
        u, v = self.wind()
        
        # Determine the LHS pf the equation by calculating the derivatives.
        # Change in meridional wind with respect to latitude.
        v_dy = self.gradient_latitude(parameter=v)

        # Change in zonal wind with respect to longitude.
        u_dx = self.gradient_longitude(parameter=u)

        LHS = u_dx + v_dy
        LHS *= -1

        # Integrate the continunity equation.
        cdef list vertical_motion_list = []
        cdef int n = 0
        cdef int len_pressure = len(pressure)
        cdef omega, omega_unit
        while n < len_pressure:
            p1 = n
            p2 = n+2
            y = LHS[p1:p2, :, :]
            p = pressure[p1:p2, :, :]
            omega = np.trapz(
                y=y, x=p, axis=0
            )
            omega_unit = omega.unit
            vertical_motion_list.append(omega.value)

            n += 1

        # Convert list to NumPy array.
        vertical_motion = np.asarray(vertical_motion_list)

        # Add units.
        vertical_motion *= omega_unit

        # Ensure the shape is correct.
        if np.shape(vertical_motion) != np.shape(u):
            raise Exception("Unable to determine vertical motion"
                + " at this time. Please contact the developer for futher"
                + " assistance.")

        return vertical_motion

# ------------------------------------------------------------------------------#

    def globe(
            self,
            which="air_temperature",
            central_latitude = 53.1424, 
            central_longitude = 352.3079, 
            psurface=1000
        ):
        r"""Generates a wind vector plot over a contour plot.

        Parameters
        ----------
        which: `str`
            Desired atmospheric parameter
        central_latitude: `float`
            The line of latitude at which the view is looking directly down at
        central_longitude: `float`
            The line of longitude at which the view is looking directly down at
        psurface: `int`
            Pressure at which the contour plot is generated
        
        Notes
        -----
        It overlays both of these elements onto a Nearside Perspective projection
        of the Earth. By default, the perspective view is looking directly 
        down at the city of Dublin in the country of Ireland. If you would 
        like a particular atmospheric parameter to be added to this method, 
        either create an issue on GitHub or send an email to support@amsimp.com.

        See Also
        --------
        wind
        """
        if self.planet == "Earth":
            # Ensure psurface is between 1000 and 1 hPa above sea level.
            if psurface < 1 or psurface > 1000:
                raise Exception(
                    "psurface must be a real number between 1 and 1,000."
                    + " The value of psurface was: {}".format(
                        psurface
                    )
                )
            
            # Index of the nearest alt in amsimp.Backend.altitude_level()
            indx_psurface = (
                np.abs(self.pressure_surfaces().value - psurface)
            ).argmin()

            # Define latitude and longitude variables.
            latitude = self.latitude_lines().value
            longitude = self.longitude_lines().value

            # Remove NumPy runtime warning.
            np.seterr(all='ignore')

            # Vector plot.
            # Define zonal and meridional wind.
            wind = self.wind()
            u = wind[0][indx_psurface, :, :]
            v = wind[1][indx_psurface, :, :]

            # Reduce density of wind vectors.
            skip_lat = latitude.shape[0] / 23
            skip_lat = int(np.round(skip_lat))
            skip_lon = longitude.shape[0] / 23
            skip_lon = int(np.round(skip_lat))

            # Contour plotting.
            # Define atmospheric parameter of interest.
            if which == "temperature" or which == "air_temperature":
                data = self.temperature()[indx_psurface, :, :]
                data_type = "Air Temperature"
                unit = " (K)"
            elif which == "geopotential_height" or which == "height":
                data = self.geopotential_height()[indx_psurface, :, :]
                data_type = "Geopotential Height"
                unit = " (m)"
            elif which == "density" or which == "atmospheric_density":
                data = self.density()[indx_psurface, :, :]
                data_type = "Atmospheric Density"
                unit = " ($\\frac{kg}{m^3}$)"
            elif which == "humidity" or which == "relative_humidity":
                data = self.relative_humidity()[indx_psurface, :, :]
                data_type = "Relative Humidity"
                unit = " (%)"
            elif which == "virtual_temperature":
                data = self.virtual_temperature()[indx_psurface, :, :]
                data_type = "Virtual Temperature"
                unit = " (K)"
            elif which == "vapor_pressure":
                data = self.vapor_pressure()[indx_psurface, :, :]
                data_type = "Vapor Pressure"
                unit = " (hPa)"
            elif which == "potential_temperature":
                data = self.potential_temperature()[indx_psurface, :, :]
                data_type = "Potential Temperature"
                unit = " (K)"
            elif which == "precipitable_water" or which == "precipitable_water_vapor":
                data = self.precipitable_water()
                data_type = "Precipitable Water Vapor"
                unit = " (mm)"
            elif which == "zonal_wind":
                data = self.wind()[0][indx_psurface, :, :]
                data_type = "Zonal Wind"
                unit = " ($\\frac{m}{s}$)"
            elif which == "meridional_wind":
                data = self.wind()[1][indx_psurface, :, :]
                data_type = "Meridional Wind"
                unit = " ($\\frac{m}{s}$)"
            elif which == "wind":
                data = self.wind()
                data = np.sqrt(data[0]**2 + data[1]**2)[indx_psurface, :, :]
                data_type = "Wind"
                unit = " ($\\frac{m}{s}$)"
            elif which == "mixing_ratio":
                data = self.mixing_ratio()[indx_psurface, :, :]
                data_type = "Mixing Ratio"
                unit = " (Dimensionless)"
            else:
                raise Exception(
                    "Invalid keyword. which must be a string of an atmospheric "
                    + "parameter included with AMSIMP."
                )

            # Define graphing parameters.
            minimum_val = data.min().value
            maximum_val = data.max().value
            levels = np.linspace(minimum_val, maximum_val, 21)
            data, lon = add_cyclic_point(data, coord=longitude)
            data, lat = add_cyclic_point(np.transpose(data), coord=latitude)
            data = np.transpose(data)

            def update(val):
                try:
                    central_lon = slon.val
                    central_lat = slat.val
                except:
                    central_lat = central_latitude
                    central_lon = central_longitude

                # Define the axes.
                crs = ccrs.NearsidePerspective(
                    central_longitude=central_lon, 
                    central_latitude=central_lat
                )
                ax = plt.axes(
                    projection=crs
                )
                plt.subplots_adjust(left=0.25, bottom=0.25)
                
                # Add latitudinal and longitudinal grid lines, as well as, 
                # coastlines to the globe.
                ax.set_global()
                ax.coastlines()
                ax.gridlines()

                # Contour plot.
                contourf = plt.contourf(
                    lon,
                    lat,
                    data,
                    transform=ccrs.PlateCarree(),
                    levels=levels,
                )

                # Add wind vectors.
                plt.quiver(
                    longitude[::skip_lon],
                    latitude[::skip_lat],
                    u.value[::skip_lat, ::skip_lon],
                    v.value[::skip_lat, ::skip_lon],
                    transform=ccrs.PlateCarree(),   
                )

                # Colorbar creation.
                colorbar = plt.colorbar(contourf)
                tick_locator = ticker.MaxNLocator(nbins=15)
                colorbar.locator = tick_locator
                colorbar.update_ticks()
                colorbar.set_label(
                    data_type + unit
                )

                # Add SALT.
                title = (
                    data_type + " ("
                    + str(self.date.year) + '-' + str(self.date.month) + '-'
                    + str(self.date.day) + " " + str(self.date.hour)
                    + ":00 h)"
                )
            
                if which != "precipitable_water" and which != "precipitable_water_vapor":
                    title = (
                        title + " (" + "Pressure Surface = " + str(
                            self.pressure_surfaces()[indx_psurface]
                        ) + ")"
                    )

                plt.title(title)
            
            # First plot.
            update(None)

            # Sliders.
            axcolor = 'lightgoldenrodyellow'
            axlon = plt.axes(
                [0.25, 0.15, 0.65, 0.03],
                facecolor=axcolor, 
                projection=ccrs.PlateCarree()
            )
            axlat = plt.axes(
                [0.25, 0.2, 0.65, 0.03],
                facecolor=axcolor, 
                projection=ccrs.PlateCarree()
            )

            slon = Slider(
                axlon, 'Longitude', 0, 359, valinit=central_longitude
            )
            slat = Slider(
                axlat, 'Latitude', -89, 89, valinit=central_latitude
            )

            slon.on_changed(update)
            slat.on_changed(update)

            resetax = plt.axes(
                [0.8, 0.025, 0.1, 0.04], projection=ccrs.PlateCarree()
            )
            button = Button(
                resetax, 
                'Reset', 
                color=axcolor, 
                hovercolor='0.975'
            )

            def reset(event):
                slon.reset()
                slat.reset()
            button.on_clicked(reset)

            # Show plot.
            plt.show()
        else:
            raise NotImplementedError(
                "Visualisations for planetary bodies other than Earth"
                + " is not currently implemented."
            )

Moist Class

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#cython: linetrace=True
#distutils: define_macros=CYTHON_TRACE_NOGIL=1
#cython: language_level=3
# cython: embedsignature=True, binding=True
"""
Copyright (C) 2020 AMSIMP

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see https://www.gnu.org/licenses/.
"""

# ------------------------------------------------------------------------------#

# Importing Dependencies
import numpy as np
from astropy import units
from scipy.integrate import quad
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
import matplotlib.pyplot as plt
from matplotlib import ticker
from amsimp.backend cimport Backend
from amsimp.backend import Backend
cimport numpy as np
from cpython cimport bool

# ------------------------------------------------------------------------------#

cdef class Moist(Backend):
    """
    This class is concerned with incorpating moisture into the atmospheric model.
    """

    cpdef np.ndarray vapor_pressure(self):
        r"""Generates an array of vapor pressure. 

        .. math:: e_s = 6.112 \exp{\frac{17.67 T}{T + 243.15}}

        .. math:: e = \frac{r_h e_s}{100}

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Vapor pressure
        
        Notes
        -----
        Vapor pressure, in meteorology, is the partial pressure of water vapor.
        The partial pressure of water vapor is the pressure that water vapor
        contributes to the total atmospheric pressure.
        """
        # Convert temperature in Kelvin to degrees centigrade.
        cdef np.ndarray temperature = self.temperature().value - 273.15

        # Saturated water vapor pressure
        sat_vapor_pressure = 0.61121 * np.exp(
            (
                18.678 - (temperature / 234.5)
            ) * (temperature / (257.14 + temperature)
            )
        )

        # Add units of measurement.
        sat_vapor_pressure *= units.kPa
        sat_vapor_pressure = sat_vapor_pressure.to(units.hPa)

        # Vapor pressure, accounting for relative humidity.
        vapor_pressure = self.relative_humidity().value * sat_vapor_pressure
        vapor_pressure /= 100

        return vapor_pressure

    cpdef np.ndarray virtual_temperature(self):
        r"""Generates an array of the virtual temperature.

        .. math:: T_v = \frac{T}{1 - \frac{0.378 e}{p}}

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Virtual temperature
        
        Notes
        -----
        The virtual temperature is the temperature at which dry air
        would have the same density as the moist air, at a given
        pressure. In other words, two air samples with the same
        virtual temperature have the same density, regardless
        of their actual temperature or relative humidity.

        See Also
        --------
        vapor_pressure
        """
        virtual_temperature = self.temperature() / (
            1 - (
            self.vapor_pressure() / self.pressure_surfaces(dim_3d=True)
            ) * (1 - 0.622)
        )

        return virtual_temperature

# ------------------------------------------------------------------------------#

    cpdef np.ndarray density(self):
        r"""Generates an array of atmospheric density.

        .. math:: \rho = \frac{p}{R T_v}

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Atmospheric density
        
        Notes
        -----
        The atmospheric density is the mass of the atmosphere per unit
        volume. The ideal gas equation is the equation of state for the
        atmosphere, and is defined as an equation relating temperature,
        pressure, and specific volume of a system in theromodynamic
        equilibrium.

        See Also
        --------
        virtual_temperature
        """
        cdef np.ndarray pressure_surfaces = self.pressure_surfaces(dim_3d=True)

        density = pressure_surfaces / (self.virtual_temperature() * self.R)

        # Switch to the appropriate SI units.
        density = density.si
        return density

    cpdef np.ndarray mixing_ratio(self):
        r""""Generates an array of the mixing ratio.
        
        .. math:: r = \frac{0.622 e}{p - e}

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Mixing ratio

        Notes
        -----
        The mixing ratio is the ratio of the mass of a variable atmospheric
        constituent to the mass of dry air. In this particular case, it refers
        to water vapor.

        See Also
        --------
        vapor_pressure
        """
        mixing_ratio = (
            0.622 * self.vapor_pressure()
        ) / (
                self.pressure_surfaces(dim_3d=True) - self.vapor_pressure()
        )

        return mixing_ratio

    cpdef np.ndarray potential_temperature(self, moist=False):
        r"""Generates an array of potential temperature.

        .. math:: \theta = T (\frac{p}{p_0})^{-R / c_p}

        Parameters
        ----------
        moist: `bool`
            If true, returns virtual potential temperature
        
        Returns
        -------
        `astropy.units.quantity.Quantity`
            Potential temperature

        Notes
        -----
        The potential temperature of a parcel of fluid at pressure P is the
        temperature that the parcel would attain if adiabatically brought
        to a standard reference pressure.
        
        See Also
        --------
        virtual_temperature
        """
        # Ensure moist is a boolean value.
        if not isinstance(moist, bool):
            raise Exception(
                "moist must be a boolean value. The value of moist was: {}".format(
                    moist
                )
            )

        # Determine whether to calculate wet-bulb potential temperature, or
        # potential temperature.
        cdef np.ndarray temperature
        if moist:
            temperature = self.virtual_temperature().value
        else:
            temperature = self.temperature().value

        cdef np.ndarray pressure_surfaces = self.pressure_surfaces(dim_3d=True).value
        cdef float R = self.R.value
        cdef float c_p = self.c_p.value

        cdef list list_potentialtemperature = []
        cdef int n = 0
        cdef int len_psurfaces = len(pressure_surfaces)
        while n < len_psurfaces:
            theta = temperature[n] * (
                (pressure_surfaces[n] / pressure_surfaces[0]) ** (-R / c_p)
            )
            
            list_potentialtemperature.append(theta)
            
            n += 1

        potential_temperature = np.asarray(list_potentialtemperature)
        potential_temperature *= units.K
        return potential_temperature

# ------------------------------------------------------------------------------#

    def __mixing_ratio(self, pressure, vapor_pressure):
        """
        This method is solely utilised for integration in the
        amsimp.Water.precipitable_water method.
        """
        y = (0.622 * vapor_pressure) / (pressure - vapor_pressure)

        return y

    cpdef np.ndarray precipitable_water(self, sum_pwv=True):
        r"""Generates an array of precipitable water vapor.

        .. math:: W = \frac{1}{\rho g} \int r dp

        Parameters
        ----------
        sum_pwv: `bool`
            If true, returns 3-dimensional precipitable water vapor array.

        Returns
        -------
        `astropy.units.quantity.Quantity`
            Precipitable water vapor
        
        Notes
        -----
        Precipitable water is the total atmospheric water vapor contained in a
        vertical column of unit cross-sectional area extending between any two
        specified levels.

        See Also
        --------
        vapor_pressure, mixing_ratio
        """
        # Defining some variables.
        cdef np.ndarray pressure = self.pressure_surfaces(dim_3d=True).to(units.Pa).value
        pressure = np.transpose(pressure, (2, 1, 0))
        cdef np.ndarray vapor_pressure = self.vapor_pressure().to(units.Pa)
        vapor_pressure = np.transpose(vapor_pressure.value, (2, 1, 0))
        cdef g = self.g
        cdef rho_w = 997 * (units.kg / units.m ** 3)

        # Integrate the mixing ratio with respect to pressure between the
        # pressure boundaries of p1, and p2.
        cdef list list_precipitablewater = []
        cdef list pwv_lat, pwv_alt
        cdef tuple integration_term
        cdef float p1, p2, e, Pwv_intergrationterm
        cdef P_wv
        cdef int len_pressurelong = len(pressure)
        cdef int len_pressurelat = len(pressure[0])
        cdef int len_pressurealt = len(pressure[0][0]) - 1
        cdef int i, n, k
        i = 0
        while i < len_pressurelong:
            pwv_lat = []

            n = 0
            while n < len_pressurelat:
                pwv_alt = []

                k = 0
                while k < len_pressurealt:
                    p1 = pressure[i][n][k]
                    p2 = pressure[i][n][k + 1]
                    e = (vapor_pressure[i][n][k] + vapor_pressure[i][n][k + 1]) / 2

                    integration_term = quad(self.__mixing_ratio, p1, p2, args=(e,))
                    Pwv_intergrationterm = integration_term[0]
                    pwv_alt.append(Pwv_intergrationterm)

                    k += 1

                if sum_pwv: 
                    P_wv = np.sum(pwv_alt)
                else:
                    P_wv = pwv_alt
                
                pwv_lat.append(P_wv)                   

                n += 1
            
            list_precipitablewater.append(pwv_lat)
            i += 1

        precipitable_water = np.asarray(list_precipitablewater) * units.Pa

        if np.shape(precipitable_water) == (len_pressurelong, len_pressurelat):
            precipitable_water = np.transpose(precipitable_water)
        else:
            precipitable_water = np.transpose(precipitable_water, (2, 1, 0))

        # Multiplication term by integration.
        precipitable_water *= -1 / (rho_w * g)

        precipitable_water = precipitable_water.to(units.mm)
        return precipitable_water

Weather Class

To be added.