Skip to content

cems_api

NAME: cems_api.py PGRMMER: Alice Crawford ORG: ARL This code written at the NOAA air resources laboratory Python 3

The key and url for the epa api should be stored in a file called .epaapirc in the $HOME directory. The contents should be key: apikey url: https://api.epa.gov/FACT/1.0/

TO DO

Date is in local time (not daylight savings) Need to convert to UTC. This will require an extra package or api.

Classes:

EpaApiObject - Base class EmissionsCall FacilitiesData MonitoringPlan

Emissions CEMS

Functions:

addquarter get_datelist findquarter sendrequest getkey

CEMS

Class for data from continuous emission monitoring systems (CEMS). Data from power plants can be downloaded from ftp://newftp.epa.gov/DMDNLoad/emissions/

Attributes:

Name Type Description
efile type string

Description of attribute efile. url : type string Description of attribute url. info : type string Information about data. df : pandas DataFrame dataframe containing emissions data.

Methods:

Name Description
__init__

add_data(self, rdate, states=['md'], download=False, verbose=True):

Source code in monetio/obs/cems_api.py
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
class CEMS:
    """
     Class for data from continuous emission monitoring systems (CEMS).
     Data from power plants can be downloaded from
     ftp://newftp.epa.gov/DMDNLoad/emissions/

    Attributes
     ----------
     efile : type string
         Description of attribute `efile`.
     url : type string
         Description of attribute `url`.
     info : type string
         Information about data.
     df : pandas DataFrame
         dataframe containing emissions data.
    Methods
     ----------
     __init__(self)
     add_data(self, rdate, states=['md'], download=False, verbose=True):

    """

    def __init__(self):
        self.efile = None
        self.lb2kg = 0.453592  # number of kilograms per pound.
        self.info = "Data from continuous emission monitoring systems (CEMS)\n"
        self.df = pd.DataFrame()
        self.so2name = "SO2CEMReportedAdjustedSO2"
        # Each facility may have more than one unit which is specified by the
        # unit id.
        self.emit = Emissions()
        self.orislist = []

    def add_emissions(self, oris, mid, datelist, method):
        # 5. Call to the Emissions class to add each monitoring location
        #    to the dataframe for each quarter in the time period.
        statuslist = []
        for ndate in datelist:
            quarter = findquarter(ndate)
            print(str(oris) + " " + str(mid) + " Loading data for quarter " + str(quarter))
            status = self.emit.add(oris, mid, ndate.year, quarter, method)
            if status == 200:
                self.orislist.append((oris, mid))
                write_status_message(status, oris, mid, quarter, "log.txt")
            else:
                write_status_message(status, oris, "no mp " + str(mid), quarter, "log.txt")
            statuslist.append(status)
        return statuslist

    def add_data(self, rdate, alist, area=True, verbose=True):
        # CEMS class
        """
        INPUTS:
        rdate :  either datetime object or tuple of two datetime objects.
        alist  : list of 4 floats. (lat, lon, lat, lon)
                OR list of oris codes.
        area : if True then alist defines area to use.
               if False then alist is a list of oris codes.
        verbose : boolean

        RETURNS:
        emitdf : pandas DataFrame with SO2 emission information.

        # 1. get list of oris codes within the area of interest
        # 2. get list of monitoring location ids for each oris code
        # 3. each unit has a monitoring plan.
        # 4. get stack heights for each monitoring location from
        #    class MonitoringPlan
        # 5. Call to the Emissions class to add each monitoring location
        #    to the dataframe.


        TODO - MonitoringPlan contains quarterly summaries of mass and operating
               time. May be able to use those

        TODO - to generalize to emissions besides SO2. Modify get_so2 routine.

        TODO - what is the flow rate?



        """
        # 1. get list of oris codes within the area of interest
        # class FacilitiesData for this
        fac = FacilitiesData()
        if area:
            llcrnr = (alist[0], alist[1])
            urcrnr = (alist[2], alist[3])
            orislist = fac.oris_by_area(llcrnr, urcrnr)
        else:
            orislist = alist
        # date list is list of dates between r1, r2 starting each quarter.
        datelist = get_datelist(rdate)
        if verbose:
            print("ORIS to retrieve ", orislist)
        if verbose:
            print("DATES ", datelist)

        # 2. get list of monitoring location ids for each oris code
        # FacilitiesData also provides this.
        facdf = fac.df[fac.df["oris"].isin(orislist)]
        facdf = facdf.drop(["begin time", "end time"], axis=1)

        # dflist is list of tuples (oris, unit, stackht)
        dflist = []
        for oris in orislist:
            units = fac.get_units(oris)
            if verbose:
                print("Units to retrieve ", str(oris), units)
            # 3. each unit has a monitoring plan.
            for mid in units:
                # 4. get stack heights for each monitoring location from
                #    class
                # although the date is included for the monitoring plan request,
                # the information returned is the same most of the time
                # (possibly unless the monitoring plan changes during the time
                # of interest).
                # to reduce number of requests, the monitoring plan is only
                # requested for the first date which returns a valid monitoring
                # plan.

                # find first valid monitoringplan by date.
                mrequest = None
                for udate in datelist:
                    mrequest = fac.get_unit_request(oris, mid, udate)
                    if mrequest:
                        break
                # write to message file which monitoring plan was found.
                if not mrequest:
                    with open("MESSAGE.txt", "a") as fid:
                        fid.write(" No monitoring plan for ")
                        fid.write(" oris: " + str(oris))
                        fid.write(" mid: " + str(mid))
                        fid.write(" date: " + datelist[0].strftime("%y %m/%d"))
                        fid.write("\n")
                else:
                    with open("MESSAGE.txt", "a") as fid:
                        fid.write(" EXISTS  monitoring plan for ")
                        fid.write(" oris: " + str(oris))
                        fid.write(" mid: " + str(mid))
                        fid.write(" date: " + datelist[0].strftime("%y %m/%d"))
                        fid.write("\n")

                    # update dflist from the monitoring plan.
                    dflist, method = get_monitoring_plan(oris, mid, mrequest, udate, dflist)
                    if not method:
                        method = []
                    # add emissions for each quarter list.
                    for meth in method:
                        _ = self.add_emissions(oris, mid, datelist, meth)
        # print(dflist)

        # create dataframe from dflist.
        stackdf = pd.DataFrame(dflist, columns=["oris", "unit", "stackht"])
        stackdf = stackdf.drop_duplicates()
        # keep only the following columns
        # there was a problem when more than one request_string per unit
        facdf = facdf[["oris", "unit", "facility_name", "latitude", "longitude"]]
        facdf = facdf.drop_duplicates()

        # merge stackdf with facdf to get  latitude longitude facility_name
        # information
        facdf = pd.merge(
            stackdf,
            facdf,
            how="left",
            left_on=["oris", "unit"],
            right_on=["oris", "unit"],
        )
        # need to drop duplicates here or else will create duplicate rows in
        # emitdf
        facdf = facdf.drop_duplicates()

        # drop un-needed columns from the emissions DataFrame
        emitdf = get_so2(self.emit.df)

        c1 = facdf.columns.values
        c2 = emitdf.columns.values
        jlist = [x for x in c1 if x in c2]

        if emitdf.empty:
            return emitdf
        emitdf = emitdf.dropna(axis=0, subset=["so2_lbs"])

        # The LME data sometimes has duplicate rows.
        # causing emissions to be over-estimated.
        # emitdf = emitdf.drop_duplicates()
        def badrow(rrr):
            test1 = True
            test2 = True
            if rrr["so2_lbs"] == 0:
                test1 = False
            if not rrr["so2_lbs"]:
                test1 = False

            if rrr["time local"] == pd.NaT:
                test2 = False

            return test1 or test2

        # False if no so2_lbs (0 or Nan) and date is NaT.
        emitdf["goodrow"] = emitdf.apply(badrow, axis=1)
        emitdf = emitdf[emitdf["goodrow"]]

        rowsbefore = emitdf.shape[0]
        if not emitdf.empty:
            # merge data from the facilities DataFrame into the Emissions DataFrame
            emitdf = pd.merge(
                emitdf,
                facdf,
                how="left",
                # left_on=["oris", "unit"],
                # right_on=["oris", "unit"],
                left_on=jlist,
                right_on=jlist,
            )
        rowsafter = emitdf.shape[0]
        if rowsafter != rowsbefore:
            print("WARNING: merge changed number of rows")
            sys.exit()

        diag = False
        if diag:
            for ccc in emitdf.columns.values:
                try:
                    tempdf = emitdf.dropna(axis=0, subset=[ccc])
                    print(ccc + " na dropped", tempdf.shape)
                except Exception:
                    print(ccc + " cannot drop, error")
        # print('stackht is na ---------------------------------')
        # tempdf = emitdf[emitdf['stackht'].isnull()]
        # print(tempdf[['oris','so2_lbs','unit','time local','stackht']])
        # emitdf = emitdf.dropna(axis=0, subset=['so2_lbs'])
        # print('Rows after dropna', emitdf.shape)
        # tempdf = dropna(axis=0, how='any', inplace=True)
        # print('Rows after dropna 2', tempdf)
        # temp = emitdf[not emitdf['so2_lbs']]
        # print('not so2lbs', temp)
        # temp = emitdf[not emitdf['stackht']]
        # print('not stackht', temp)

        emitdf = emitdf.dropna(axis=0, subset=["so2_lbs"])

        # def remove_nans(x):
        #    if np.isnan(x):
        #        return False
        #    elif pd.isna(x):
        #        return False
        #    else:
        #        return True

        # emitdf["keep"] = emitdf.apply(lambda row: remove_nans(row["so2_lbs"]), axis=1)
        # emitdf = emitdf[emitdf["keep"] == True]
        # emitdf.drop(["keep"], axis=1, inplace=True)
        # emitdf.fillna(0, inplace=True)
        # r_duplicates = tempdf.duplicated()
        # if not np.all(r_duplicates):
        #   print('Warning: Duplicate rows in the emitdf dataframe')
        #   print(tempdf[tempdf[r_duplicates]])
        #   print('-------------HERE ')
        #   print(tempdf[tempdf['so2_lbs'].isna()])
        #   print('------------- HERE B')
        #   temp = tempdf[tempdf[r_duplicates]]
        #   temp = temp['so2_lbs']
        #   print(temp[0:10])
        #   print(temp.values)
        #   print(type(temp.values[0]))
        #   print(pd.isna(temp.values[0]))
        #   print(tempdf[tempdf['so2_lbs'].isna()])
        #   #sys.exit()
        return emitdf

add_data(rdate, alist, area=True, verbose=True)

INPUTS: rdate : either datetime object or tuple of two datetime objects. alist : list of 4 floats. (lat, lon, lat, lon) OR list of oris codes. area : if True then alist defines area to use. if False then alist is a list of oris codes. verbose : boolean

RETURNS: emitdf : pandas DataFrame with SO2 emission information.

1. get list of oris codes within the area of interest

2. get list of monitoring location ids for each oris code

3. each unit has a monitoring plan.

4. get stack heights for each monitoring location from

class MonitoringPlan

5. Call to the Emissions class to add each monitoring location

to the dataframe.

TODO - MonitoringPlan contains quarterly summaries of mass and operating time. May be able to use those

TODO - to generalize to emissions besides SO2. Modify get_so2 routine.

TODO - what is the flow rate?

Source code in monetio/obs/cems_api.py
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
def add_data(self, rdate, alist, area=True, verbose=True):
    # CEMS class
    """
    INPUTS:
    rdate :  either datetime object or tuple of two datetime objects.
    alist  : list of 4 floats. (lat, lon, lat, lon)
            OR list of oris codes.
    area : if True then alist defines area to use.
           if False then alist is a list of oris codes.
    verbose : boolean

    RETURNS:
    emitdf : pandas DataFrame with SO2 emission information.

    # 1. get list of oris codes within the area of interest
    # 2. get list of monitoring location ids for each oris code
    # 3. each unit has a monitoring plan.
    # 4. get stack heights for each monitoring location from
    #    class MonitoringPlan
    # 5. Call to the Emissions class to add each monitoring location
    #    to the dataframe.


    TODO - MonitoringPlan contains quarterly summaries of mass and operating
           time. May be able to use those

    TODO - to generalize to emissions besides SO2. Modify get_so2 routine.

    TODO - what is the flow rate?



    """
    # 1. get list of oris codes within the area of interest
    # class FacilitiesData for this
    fac = FacilitiesData()
    if area:
        llcrnr = (alist[0], alist[1])
        urcrnr = (alist[2], alist[3])
        orislist = fac.oris_by_area(llcrnr, urcrnr)
    else:
        orislist = alist
    # date list is list of dates between r1, r2 starting each quarter.
    datelist = get_datelist(rdate)
    if verbose:
        print("ORIS to retrieve ", orislist)
    if verbose:
        print("DATES ", datelist)

    # 2. get list of monitoring location ids for each oris code
    # FacilitiesData also provides this.
    facdf = fac.df[fac.df["oris"].isin(orislist)]
    facdf = facdf.drop(["begin time", "end time"], axis=1)

    # dflist is list of tuples (oris, unit, stackht)
    dflist = []
    for oris in orislist:
        units = fac.get_units(oris)
        if verbose:
            print("Units to retrieve ", str(oris), units)
        # 3. each unit has a monitoring plan.
        for mid in units:
            # 4. get stack heights for each monitoring location from
            #    class
            # although the date is included for the monitoring plan request,
            # the information returned is the same most of the time
            # (possibly unless the monitoring plan changes during the time
            # of interest).
            # to reduce number of requests, the monitoring plan is only
            # requested for the first date which returns a valid monitoring
            # plan.

            # find first valid monitoringplan by date.
            mrequest = None
            for udate in datelist:
                mrequest = fac.get_unit_request(oris, mid, udate)
                if mrequest:
                    break
            # write to message file which monitoring plan was found.
            if not mrequest:
                with open("MESSAGE.txt", "a") as fid:
                    fid.write(" No monitoring plan for ")
                    fid.write(" oris: " + str(oris))
                    fid.write(" mid: " + str(mid))
                    fid.write(" date: " + datelist[0].strftime("%y %m/%d"))
                    fid.write("\n")
            else:
                with open("MESSAGE.txt", "a") as fid:
                    fid.write(" EXISTS  monitoring plan for ")
                    fid.write(" oris: " + str(oris))
                    fid.write(" mid: " + str(mid))
                    fid.write(" date: " + datelist[0].strftime("%y %m/%d"))
                    fid.write("\n")

                # update dflist from the monitoring plan.
                dflist, method = get_monitoring_plan(oris, mid, mrequest, udate, dflist)
                if not method:
                    method = []
                # add emissions for each quarter list.
                for meth in method:
                    _ = self.add_emissions(oris, mid, datelist, meth)
    # print(dflist)

    # create dataframe from dflist.
    stackdf = pd.DataFrame(dflist, columns=["oris", "unit", "stackht"])
    stackdf = stackdf.drop_duplicates()
    # keep only the following columns
    # there was a problem when more than one request_string per unit
    facdf = facdf[["oris", "unit", "facility_name", "latitude", "longitude"]]
    facdf = facdf.drop_duplicates()

    # merge stackdf with facdf to get  latitude longitude facility_name
    # information
    facdf = pd.merge(
        stackdf,
        facdf,
        how="left",
        left_on=["oris", "unit"],
        right_on=["oris", "unit"],
    )
    # need to drop duplicates here or else will create duplicate rows in
    # emitdf
    facdf = facdf.drop_duplicates()

    # drop un-needed columns from the emissions DataFrame
    emitdf = get_so2(self.emit.df)

    c1 = facdf.columns.values
    c2 = emitdf.columns.values
    jlist = [x for x in c1 if x in c2]

    if emitdf.empty:
        return emitdf
    emitdf = emitdf.dropna(axis=0, subset=["so2_lbs"])

    # The LME data sometimes has duplicate rows.
    # causing emissions to be over-estimated.
    # emitdf = emitdf.drop_duplicates()
    def badrow(rrr):
        test1 = True
        test2 = True
        if rrr["so2_lbs"] == 0:
            test1 = False
        if not rrr["so2_lbs"]:
            test1 = False

        if rrr["time local"] == pd.NaT:
            test2 = False

        return test1 or test2

    # False if no so2_lbs (0 or Nan) and date is NaT.
    emitdf["goodrow"] = emitdf.apply(badrow, axis=1)
    emitdf = emitdf[emitdf["goodrow"]]

    rowsbefore = emitdf.shape[0]
    if not emitdf.empty:
        # merge data from the facilities DataFrame into the Emissions DataFrame
        emitdf = pd.merge(
            emitdf,
            facdf,
            how="left",
            # left_on=["oris", "unit"],
            # right_on=["oris", "unit"],
            left_on=jlist,
            right_on=jlist,
        )
    rowsafter = emitdf.shape[0]
    if rowsafter != rowsbefore:
        print("WARNING: merge changed number of rows")
        sys.exit()

    diag = False
    if diag:
        for ccc in emitdf.columns.values:
            try:
                tempdf = emitdf.dropna(axis=0, subset=[ccc])
                print(ccc + " na dropped", tempdf.shape)
            except Exception:
                print(ccc + " cannot drop, error")
    # print('stackht is na ---------------------------------')
    # tempdf = emitdf[emitdf['stackht'].isnull()]
    # print(tempdf[['oris','so2_lbs','unit','time local','stackht']])
    # emitdf = emitdf.dropna(axis=0, subset=['so2_lbs'])
    # print('Rows after dropna', emitdf.shape)
    # tempdf = dropna(axis=0, how='any', inplace=True)
    # print('Rows after dropna 2', tempdf)
    # temp = emitdf[not emitdf['so2_lbs']]
    # print('not so2lbs', temp)
    # temp = emitdf[not emitdf['stackht']]
    # print('not stackht', temp)

    emitdf = emitdf.dropna(axis=0, subset=["so2_lbs"])

    # def remove_nans(x):
    #    if np.isnan(x):
    #        return False
    #    elif pd.isna(x):
    #        return False
    #    else:
    #        return True

    # emitdf["keep"] = emitdf.apply(lambda row: remove_nans(row["so2_lbs"]), axis=1)
    # emitdf = emitdf[emitdf["keep"] == True]
    # emitdf.drop(["keep"], axis=1, inplace=True)
    # emitdf.fillna(0, inplace=True)
    # r_duplicates = tempdf.duplicated()
    # if not np.all(r_duplicates):
    #   print('Warning: Duplicate rows in the emitdf dataframe')
    #   print(tempdf[tempdf[r_duplicates]])
    #   print('-------------HERE ')
    #   print(tempdf[tempdf['so2_lbs'].isna()])
    #   print('------------- HERE B')
    #   temp = tempdf[tempdf[r_duplicates]]
    #   temp = temp['so2_lbs']
    #   print(temp[0:10])
    #   print(temp.values)
    #   print(type(temp.values[0]))
    #   print(pd.isna(temp.values[0]))
    #   print(tempdf[tempdf['so2_lbs'].isna()])
    #   #sys.exit()
    return emitdf

Emissions

class that represents data returned by emissions/hourlydata call to the restapi. Attributes self.df : DataFrame

Methods init add

see https://www.epa.gov/airmarkets/field-audit-checklist-tool-fact-field-references#EMISSION

class that represents data returned by facilities call to the restapi.

NOTES

BAF - bias adjustment factor

MEC - maximum expected concentraiton

MPF - maximum potential stack gas flow rate

monitoring plan specified monitor range.

FlowPMA % of time flow monitoring system available.

SO2CEMReportedAdjustedSO2 - average adjusted so2 concentration

SO2CEMReportedSO2MassRate - average adjusted so2 rate (lbs/hr)

AdjustedFlow - average volumetric flow rate for the hour. adjusted for

bias.

It looks like MassRate is calculated from concentration of SO2 and flow

rate. So flow rate should be rate of all gasses coming out of stack.

Source code in monetio/obs/cems_api.py
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
class Emissions:
    """
    class that represents data returned by emissions/hourlydata call to the restapi.
    Attributes
    self.df : DataFrame

    Methods
    __init__
    add

    see
    https://www.epa.gov/airmarkets/field-audit-checklist-tool-fact-field-references#EMISSION

    class that represents data returned by facilities call to the restapi.
    # NOTES
    # BAF - bias adjustment factor
    # MEC - maximum expected concentraiton
    # MPF - maximum potential stack gas flow rate
    # monitoring plan specified monitor range.
    # FlowPMA % of time flow monitoring system available.

    # SO2CEMReportedAdjustedSO2 - average adjusted so2 concentration
    # SO2CEMReportedSO2MassRate - average adjusted so2 rate (lbs/hr)

    # AdjustedFlow - average volumetric flow rate for the hour. adjusted for
    # bias.

    # It looks like MassRate is calculated from concentration of SO2 and flow
    # rate. So flow rate should be rate of all gasses coming out of stack.

    """

    def __init__(self):
        self.df = pd.DataFrame()
        self.orislist = []
        self.unithash = {}
        # self.so2name = "SO2CEMReportedAdjustedSO2"
        self.so2name = "SO2CEMReportedSO2MassRate"
        self.so2nameB = "UnadjustedSO2"

    def add(
        self,
        oris,
        locationID,
        year,
        quarter,
        method,
        logfile="warnings.emit.txt",
    ):
        """
        oris : int
        locationID : str
        year : int
        quarter : int
        ifile : str
        data2add : list of tuples (str, value)
                   str is name of column. value to add to column.

        """

        if oris not in self.orislist:
            self.orislist.append(oris)
        if oris not in self.unithash.keys():
            self.unithash[oris] = []
        self.unithash[oris].append(locationID)
        with open(logfile, "w") as fid:
            dnow = datetime.datetime.now()
            fid.write(dnow.strftime("%Y %m %d %H:%M/n"))
        # if locationID == None:
        #   unitra = self.get_units(oris)
        # else:
        #   unitra = [locationID]
        if int(quarter) > 4:
            print("Warning: quarter greater than 4")
            sys.exit()

        # for locationID in unitra:
        locationID = str(locationID)
        # print('call type :', method)
        ec = EmissionsCall(oris, locationID, year, quarter, calltype=method)
        df = ec.df
        # print('EMISSIONS CALL to DF', year, quarter, locationID)
        # print(df[0:10])
        if self.df.empty:
            self.df = df
        elif not df.empty:
            self.df = pd.concat([self.df, df], ignore_index=True)
        # self.df.to_csv(efile)
        return ec.status_code

    def save(self):
        efile = "efile.txt"
        self.df.to_csv(efile)

    def merge_facilities(self, dfac):
        dfnew = pd.merge(
            self.df,
            dfac,
            how="left",
            left_on=["oris", "unit"],
            right_on=["oris", "unit"],
        )
        return dfnew

    def plot(self):
        import matplotlib.pyplot as plt

        df = self.df.copy()
        temp1 = df[df["date"].dt.year != 1700]
        sns.set()
        for unit in df["unit"].unique():
            temp = temp1[temp1["unit"] == unit]
            temp = temp[temp["SO2MODC"].isin(["01", "02", "03", "04"])]
            plt.plot(temp["date"], temp["so2_lbs"], label=str(unit))
            print("UNIT", str(unit))
            print(temp["SO2MODC"].unique())
        # for unit in df["unit"].unique():
        #    temp = temp1[temp1["unit"] == unit]
        #    temp = temp[temp["SO2MODC"].isin(
        #        ["01", "02", "03", "04"]) == False]
        #    plt.plot(temp["date"], temp["so2_lbs"], label="bad " + str(unit))
        #    print("UNIT", str(unit))
        #    print(temp["SO2MODC"].unique())
        ax = plt.gca()
        handles, labels = ax.get_legend_handles_labels()
        ax.legend(handles, labels)
        plt.show()
        for unit in df["unit"].unique():
            temp = temp1[temp1["unit"] == unit]
            print("BAF", temp["FlowBAF"].unique())
            print("MODC", temp["FlowMODC"].unique())
            print("PMA", temp["FlowPMA"].unique())
            # plt.plot(temp["date"], temp["AdjustedFlow"], label=str(unit))
        plt.show()

add(oris, locationID, year, quarter, method, logfile='warnings.emit.txt')

oris : int locationID : str year : int quarter : int ifile : str data2add : list of tuples (str, value) str is name of column. value to add to column.

Source code in monetio/obs/cems_api.py
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
def add(
    self,
    oris,
    locationID,
    year,
    quarter,
    method,
    logfile="warnings.emit.txt",
):
    """
    oris : int
    locationID : str
    year : int
    quarter : int
    ifile : str
    data2add : list of tuples (str, value)
               str is name of column. value to add to column.

    """

    if oris not in self.orislist:
        self.orislist.append(oris)
    if oris not in self.unithash.keys():
        self.unithash[oris] = []
    self.unithash[oris].append(locationID)
    with open(logfile, "w") as fid:
        dnow = datetime.datetime.now()
        fid.write(dnow.strftime("%Y %m %d %H:%M/n"))
    # if locationID == None:
    #   unitra = self.get_units(oris)
    # else:
    #   unitra = [locationID]
    if int(quarter) > 4:
        print("Warning: quarter greater than 4")
        sys.exit()

    # for locationID in unitra:
    locationID = str(locationID)
    # print('call type :', method)
    ec = EmissionsCall(oris, locationID, year, quarter, calltype=method)
    df = ec.df
    # print('EMISSIONS CALL to DF', year, quarter, locationID)
    # print(df[0:10])
    if self.df.empty:
        self.df = df
    elif not df.empty:
        self.df = pd.concat([self.df, df], ignore_index=True)
    # self.df.to_csv(efile)
    return ec.status_code

EmissionsCall

Bases: EpaApiObject

class that represents data returned by one emissions/hourlydata call to the restapi. Attributes

Source code in monetio/obs/cems_api.py
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
class EmissionsCall(EpaApiObject):
    """
    class that represents data returned by one emissions/hourlydata call to the restapi.
    Attributes
    """

    def __init__(
        self,
        oris,
        mid,
        year,
        quarter,
        fname=None,
        calltype="CEM",
        save=True,
        prompt=False,
    ):
        self.oris = oris  # oris code of facility
        self.mid = mid  # monitoring location id.
        self.year = str(year)
        self.quarter = str(quarter)
        calltype = calltype.upper().strip()
        if calltype == "F23":
            calltype = "AD"
        if not fname:
            fname = "Emissions." + self.year + ".q" + self.quarter
            if calltype == "AD":
                fname += ".AD"
            fname += "." + str(self.mid) + "." + str(oris) + ".csv"
        self.dfall = pd.DataFrame()

        self.calltype = calltype
        if calltype.upper().strip() == "AD":
            self.so2name = "SO2ADReportedSO2MassRate"
        elif calltype.upper().strip() == "CEM":
            self.so2name = "SO2CEMReportedSO2MassRate"
        elif calltype.upper().strip() == "LME":
            # this should probably be so2mass??? TO DO.
            self.so2name = "LMEReportedSO2Mass"
        else:
            self.so2name = "SO2CEMReportedSO2MassRate"

        self.so2nameB = "UnadjustedSO2"
        super().__init__(fname, save, prompt)
        # if 'DateHour' in df.columns:
        #    df = df.drop(['DateHour'], axis=1)

    def create_getstr(self):
        # for locationID in unitra:
        # efile = "efile.txt"

        if self.calltype.upper().strip() == "AD":
            estr = "emissions/hourlyFuelData/csv"
        elif self.calltype.upper().strip() == "LME":
            estr = "emissions/hourlyData/csv"
        else:
            estr = "emissions/hourlyData/csv"
        getstr = quote("/".join([estr, str(self.oris), str(self.mid), self.year, self.quarter]))
        return getstr

    def load(self):
        # Emissions call
        # datefmt = "%Y %m %d %H:%M"
        datefmt = self.datefmt
        datefmt2 = "%Y %m %d %H:%M:%S"
        chash = {"mid": str, "oris": str, "unit": str}
        df = pd.read_csv(self.fname, index_col=[0], converters=chash, parse_dates=False)
        # if not df.empty:
        if not df.empty:
            self.status_code = 200
            print("SO2 DATA EXISTS")
            temp = df[df["so2_lbs"] > 0]
            if temp.empty:
                print("SO2 lbs all zero")
            # check for  two date formats.

            # -----------------------------------------
            def newdate(x):
                rval = x["time local"]
                if isinstance(rval, float):
                    if np.isnan(rval):
                        return pd.NaT

                rval = rval.replace("-", " ")
                rval = rval.strip()
                fail = 0
                try:
                    rval = datetime.datetime.strptime(rval, datefmt)
                except ValueError:
                    fail = 1
                if fail == 1:
                    try:
                        rval = datetime.datetime.strptime(rval, datefmt2)
                    except ValueError:
                        fail = 2
                        print(self.fname)
                        print("WARNING: Could not parse date " + rval)
                return rval

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

            df["time local"] = df.apply(newdate, axis=1)
            # if 'DateHour' in df.columns:
            #    df = df.drop(['DateHour'], axis=1)
        # df = pd.read_csv(self.fname, index_col=[0])
        else:
            print("NO SO2 DATA in FILE")
        return df, False

    def return_empty(self):
        return None

    def get(self):
        data = self.get_raw_data()
        try:
            self.status_code = data.status_code
        except AttributeError:
            self.status_code = None
        if data:
            df = self.unpack(data)
        else:
            df = pd.DataFrame()
        return df

    def unpack(self, data):
        logfile = "warnings.emit.txt"
        iii = 0
        cols = []
        tra = []
        print("----UNPACK-----------------")
        for line in data.iter_lines(decode_unicode=True):
            # if iii < 5:
            # print('LINE')
            # print(line)
            # 1. Process First line
            temp = line.split(",")
            if temp[-1] and self.calltype == "LME":
                print(line)

            if iii == 0:
                tcols = line.split(",")
                # add columns for unit id and oris code
                tcols.append("unit")
                tcols.append("oris")
                # add columns for other info (stack height, latitude etc).
                # for edata in data2add:
                #    tcols.append(edata[0])
                # 1a write column headers to a file.
                verbose = True
                if verbose:
                    with open("headers.txt", "w") as fid:
                        for val in tcols:
                            fid.write(val + "\n")
                    # print('press a key to continue ')
                    # input()
                # 1b check to see if desired emission variable is in the file.
                if self.so2name not in tcols:
                    with open(logfile, "a") as fid:
                        rstr = "ORIS " + str(self.oris)
                        rstr += " mid " + str(self.mid) + "\n"
                        rstr += "NO adjusted SO2 data \n"
                        if self.so2name not in tcols:
                            rstr += "NO SO2 data \n"
                        rstr += "------------------------\n"
                        fid.write(rstr)
                    print("--------------------------------------")
                    print("ORIS " + str(self.oris))
                    print("UNIT " + str(self.mid) + " no SO2 data")
                    print(self.fname)
                    print("--------------------------------------")
                    # return empty dataframe
                    return pd.DataFrame()
                else:
                    cols = tcols
                    print("--------------------------------------")
                    print("ORIS " + str(self.oris))
                    print("UNIT " + str(self.mid) + " YES SO2 data")
                    print(self.fname)
                    print("--------------------------------------")
            # 2. Process rest of lines
            else:
                lt = line.split(",")
                # add input info to line.
                lt.append(str(self.mid))
                lt.append(str(self.oris))
                # for edata in data2add:
                #    lt.append(edata[1])
                tra.append(lt)
            iii += 1
            # with open(efile, "a") as fid:
            #    fid.write(line)
        # ----------------------------------------------------
        df = pd.DataFrame(tra, columns=cols)
        for c in df.columns:
            try:
                df[c] = pd.to_numeric(df[c])
            except Exception:
                pass
        df = self.manage_date(df)
        if self.calltype == "AD":
            df["SO2MODC"] = -8
        if self.calltype == "LME":
            df["SO2MODC"] = -9
        df = self.convert_cols(df)
        df = self.manage_so2modc(df)
        df = get_so2(df)
        # the LME data sometimes has duplicate rows.
        # causing emissions to be over-estimated.
        if self.calltype == "LME":
            df = df.drop_duplicates()
        return df

    # ----------------------------------------------------------------------------------------------
    def manage_date(self, df):
        """DateHour field is originally in string form 4/1/2016 02:00:00 PM
        Here, change to a datetime object.

        # also need to change to UTC.

        # time is local standard time (never daylight savings)
        """

        # Using the %I for the hour field and %p for AM/Pm converts time
        # correctly.
        def newdate(xxx):
            fmt = "%m/%d/%Y %I:%M:%S %p"
            try:
                rdt = datetime.datetime.strptime(xxx["DateHour"], fmt)
            except BaseException:
                # print("LINE WITH NO DATE :", xxx["DateHour"], ":")
                rdt = pd.NaT
            return rdt

        df["time local"] = df.apply(newdate, axis=1)
        df = df.drop(["DateHour"], axis=1)
        return df

    def manage_so2modc(self, df):
        if "SO2CEMSO2FormulaCode" not in df.columns.values:
            return df

        def checkmodc(formula, so2modc, so2_lbs):
            # if F-23 is the formula code and
            # so2modc is Nan then change so2modc to -7.
            if not so2_lbs or so2_lbs == 0:
                return so2modc
            if so2modc != 0 or not formula:
                return so2modc
            else:
                if "F-23" in str(formula):
                    return -7
                else:
                    return -10

        df["SO2MODC"] = df.apply(
            lambda row: checkmodc(row["SO2CEMSO2FormulaCode"], row["SO2MODC"], row["so2_lbs"]),
            axis=1,
        )
        return df

    def convert_cols(self, df):
        """
        All columns are read in as strings and must be converted to the
        appropriate units. NaNs or empty values may be present in the columns.

        OperatingTime : fraction of the clock hour during which the unit
                        combusted any fuel. If unit, stack or pipe did not
                        operate report 0.00.
        """

        # three different ways to convert columns
        # def toint(xxx):
        #    try:
        #        rt = int(xxx)
        #    except BaseException:
        #        rt = -99
        #    return rt

        def tostr(xxx):
            try:
                rt = str(xxx)
            except BaseException:
                rt = "none"
            return rt

        def simpletofloat(xxx):
            try:
                rt = float(xxx)
            except BaseException:
                rt = 0
            return rt

        # calculate lbs of so2 by multiplying rate by operating time.
        # checked this with FACTS
        def getmass(optime, cname):
            # if operating time is zero then emissions are zero.
            if float(optime) < 0.0001:
                rval = 0
            else:
                try:
                    rval = float(cname) * float(optime)
                except BaseException:
                    rval = np.nan
            return rval

        def lme_getmass(cname):
            try:
                rval = float(cname)
            except BaseException:
                rval = np.nan
            return rval

        df["SO2MODC"] = df["SO2MODC"].map(simpletofloat)
        # map OperatingTime to a float
        df["OperatingTime"] = df["OperatingTime"].map(simpletofloat)
        # map Adjusted Flow to a float
        # df["AdjustedFlow"] = df["AdjustedFlow"].map(simpletofloat)
        # df["oris"] = df["oris"].map(toint)
        df["oris"] = df.apply(lambda row: tostr(row["oris"]), axis=1)
        # map SO2 data to a float
        # if operating time is zero then map to 0 (it is '' in file)
        optime = "OperatingTime"
        cname = self.so2name
        if self.calltype == "LME":
            df["so2_lbs"] = df.apply(lambda row: lme_getmass(row[cname]), axis=1)
        else:
            df["so2_lbs"] = df.apply(lambda row: getmass(row[optime], row[cname]), axis=1)
        temp = df[["time local", "so2_lbs", cname, optime]]
        temp = df[df["OperatingTime"] > 1.0]
        if not temp.empty:
            print("Operating Time greater than 1 ")
            print(
                temp[
                    [
                        "oris",
                        "unit",
                        "OperatingTime",
                        "time local",
                        "so2_lbs",
                        self.so2name,
                    ]
                ]
            )
        # -------------------------------------------------------------
        # these were checks to see what values the fields were holding.
        # temp is values that are not valid
        # temp = temp[temp["OperatingTime"] > 0]
        # print("Values that cannot be converted to float")
        # print(temp[cname].unique())
        # print("MODC ", temp["SO2MODC"].unique())
        # ky = "MATSSstartupshutdownflat"
        # if ky in temp.keys():
        #    print("MATSSstartupshutdownflat", temp["MATSStartupShutdownFlag"].unique())
        # print(temp['date'].unique())

        # ky = "Operating Time"
        # if ky in temp.keys():
        #    print("Operating Time", temp["OperatingTime"].unique())
        # if ky in df.keys():
        #    print("All op times", df["OperatingTime"].unique())
        # for line in temp.iterrows():
        #    print(line)
        # -------------------------------------------------------------
        return df

convert_cols(df)

All columns are read in as strings and must be converted to the appropriate units. NaNs or empty values may be present in the columns.

OperatingTime : fraction of the clock hour during which the unit combusted any fuel. If unit, stack or pipe did not operate report 0.00.

Source code in monetio/obs/cems_api.py
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
def convert_cols(self, df):
    """
    All columns are read in as strings and must be converted to the
    appropriate units. NaNs or empty values may be present in the columns.

    OperatingTime : fraction of the clock hour during which the unit
                    combusted any fuel. If unit, stack or pipe did not
                    operate report 0.00.
    """

    # three different ways to convert columns
    # def toint(xxx):
    #    try:
    #        rt = int(xxx)
    #    except BaseException:
    #        rt = -99
    #    return rt

    def tostr(xxx):
        try:
            rt = str(xxx)
        except BaseException:
            rt = "none"
        return rt

    def simpletofloat(xxx):
        try:
            rt = float(xxx)
        except BaseException:
            rt = 0
        return rt

    # calculate lbs of so2 by multiplying rate by operating time.
    # checked this with FACTS
    def getmass(optime, cname):
        # if operating time is zero then emissions are zero.
        if float(optime) < 0.0001:
            rval = 0
        else:
            try:
                rval = float(cname) * float(optime)
            except BaseException:
                rval = np.nan
        return rval

    def lme_getmass(cname):
        try:
            rval = float(cname)
        except BaseException:
            rval = np.nan
        return rval

    df["SO2MODC"] = df["SO2MODC"].map(simpletofloat)
    # map OperatingTime to a float
    df["OperatingTime"] = df["OperatingTime"].map(simpletofloat)
    # map Adjusted Flow to a float
    # df["AdjustedFlow"] = df["AdjustedFlow"].map(simpletofloat)
    # df["oris"] = df["oris"].map(toint)
    df["oris"] = df.apply(lambda row: tostr(row["oris"]), axis=1)
    # map SO2 data to a float
    # if operating time is zero then map to 0 (it is '' in file)
    optime = "OperatingTime"
    cname = self.so2name
    if self.calltype == "LME":
        df["so2_lbs"] = df.apply(lambda row: lme_getmass(row[cname]), axis=1)
    else:
        df["so2_lbs"] = df.apply(lambda row: getmass(row[optime], row[cname]), axis=1)
    temp = df[["time local", "so2_lbs", cname, optime]]
    temp = df[df["OperatingTime"] > 1.0]
    if not temp.empty:
        print("Operating Time greater than 1 ")
        print(
            temp[
                [
                    "oris",
                    "unit",
                    "OperatingTime",
                    "time local",
                    "so2_lbs",
                    self.so2name,
                ]
            ]
        )
    # -------------------------------------------------------------
    # these were checks to see what values the fields were holding.
    # temp is values that are not valid
    # temp = temp[temp["OperatingTime"] > 0]
    # print("Values that cannot be converted to float")
    # print(temp[cname].unique())
    # print("MODC ", temp["SO2MODC"].unique())
    # ky = "MATSSstartupshutdownflat"
    # if ky in temp.keys():
    #    print("MATSSstartupshutdownflat", temp["MATSStartupShutdownFlag"].unique())
    # print(temp['date'].unique())

    # ky = "Operating Time"
    # if ky in temp.keys():
    #    print("Operating Time", temp["OperatingTime"].unique())
    # if ky in df.keys():
    #    print("All op times", df["OperatingTime"].unique())
    # for line in temp.iterrows():
    #    print(line)
    # -------------------------------------------------------------
    return df

manage_date(df)

DateHour field is originally in string form 4/1/2016 02:00:00 PM Here, change to a datetime object.

also need to change to UTC.

time is local standard time (never daylight savings)

Source code in monetio/obs/cems_api.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def manage_date(self, df):
    """DateHour field is originally in string form 4/1/2016 02:00:00 PM
    Here, change to a datetime object.

    # also need to change to UTC.

    # time is local standard time (never daylight savings)
    """

    # Using the %I for the hour field and %p for AM/Pm converts time
    # correctly.
    def newdate(xxx):
        fmt = "%m/%d/%Y %I:%M:%S %p"
        try:
            rdt = datetime.datetime.strptime(xxx["DateHour"], fmt)
        except BaseException:
            # print("LINE WITH NO DATE :", xxx["DateHour"], ":")
            rdt = pd.NaT
        return rdt

    df["time local"] = df.apply(newdate, axis=1)
    df = df.drop(["DateHour"], axis=1)
    return df

EpaApiObject

Source code in monetio/obs/cems_api.py
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
class EpaApiObject:
    def __init__(self, fname=None, save=True, prompt=False, fdir=None):
        """
        Base class for all classes that send request to EpaApi.
        to avoid sending repeat requests to the api, the default option
        is to save the data in a file - specified by fname.

        fname : str
        fdir : str
        save : boolean
        prompt : boolean

        """

        # fname is name of file that data would be saved to.
        self.status_code = None
        self.df = pd.DataFrame()
        self.fname = fname
        self.datefmt = "%Y %m %d %H:%M"
        if fdir:
            self.fdir = fdir
        else:
            self.fdir = "./apifiles/"
        if self.fdir[-1] != "/":
            self.fdir += "/"
        # returns None if filename does not exist.
        # if prompt True then will ask for new filename if does not exist.
        fname2 = get_filename(self.fdir + fname, prompt)
        self.getstr = self.create_getstr()
        # if the file exists load data from it.
        getboolean = True
        if fname2:
            print("Loading from file ", self.fdir + self.fname)
            self.fname = fname2
            self.df, getboolean = self.load()
        elif fname:
            self.fname = self.fdir + fname
        # if it doesn't load then get it from the api.
        # if save is True then save.
        if self.df.empty and getboolean:
            # get sends request to api and processes data received.
            self.df = self.get()
            if save:
                self.save()

    def set_filename(self, fname):
        self.fname = fname

    def load(self):
        chash = {"mid": str, "oris": str}
        df = pd.read_csv(self.fname, index_col=[0], converters=chash, parse_dates=True)
        # df = pd.read_csv(self.fname, index_col=[0])
        return df, True

    def save(self):
        """
        save to a csv file.
        """
        print("saving here", self.fname)
        if not self.df.empty:
            self.df.to_csv(self.fname, date_format=self.datefmt)
        else:
            with open(self.fname, "w") as fid:
                fid.write("no data")

    def create_getstr(self):
        # each derived class should have
        # its own create_getstr method.
        return "placeholder" + self.fname

    def printall(self):
        data = sendrequest(self.getstr)
        jobject = data.json()
        rstr = self.getstr + "\n"
        rstr += unpack_response(jobject)
        return rstr

    def return_empty(self):
        return pd.DataFrame()

    def get_raw_data(self):
        data = sendrequest(self.getstr)
        if data.status_code != 200:
            return self.return_empty()
        else:
            return data

    def get(self):
        data = self.get_raw_data()
        try:
            self.status_code = data.status_code
        except AttributeError:
            self.status_code = "None"
        try:
            jobject = data.json()
        except Exception:
            return data
        df = self.unpack(jobject)
        return df

    def unpack(self, data):
        # each derived class should have
        # its own unpack method.
        return pd.DataFrame()

__init__(fname=None, save=True, prompt=False, fdir=None)

Base class for all classes that send request to EpaApi. to avoid sending repeat requests to the api, the default option is to save the data in a file - specified by fname.

fname : str fdir : str save : boolean prompt : boolean

Source code in monetio/obs/cems_api.py
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
def __init__(self, fname=None, save=True, prompt=False, fdir=None):
    """
    Base class for all classes that send request to EpaApi.
    to avoid sending repeat requests to the api, the default option
    is to save the data in a file - specified by fname.

    fname : str
    fdir : str
    save : boolean
    prompt : boolean

    """

    # fname is name of file that data would be saved to.
    self.status_code = None
    self.df = pd.DataFrame()
    self.fname = fname
    self.datefmt = "%Y %m %d %H:%M"
    if fdir:
        self.fdir = fdir
    else:
        self.fdir = "./apifiles/"
    if self.fdir[-1] != "/":
        self.fdir += "/"
    # returns None if filename does not exist.
    # if prompt True then will ask for new filename if does not exist.
    fname2 = get_filename(self.fdir + fname, prompt)
    self.getstr = self.create_getstr()
    # if the file exists load data from it.
    getboolean = True
    if fname2:
        print("Loading from file ", self.fdir + self.fname)
        self.fname = fname2
        self.df, getboolean = self.load()
    elif fname:
        self.fname = self.fdir + fname
    # if it doesn't load then get it from the api.
    # if save is True then save.
    if self.df.empty and getboolean:
        # get sends request to api and processes data received.
        self.df = self.get()
        if save:
            self.save()

save()

save to a csv file.

Source code in monetio/obs/cems_api.py
403
404
405
406
407
408
409
410
411
412
def save(self):
    """
    save to a csv file.
    """
    print("saving here", self.fname)
    if not self.df.empty:
        self.df.to_csv(self.fname, date_format=self.datefmt)
    else:
        with open(self.fname, "w") as fid:
            fid.write("no data")

FacilitiesData

Bases: EpaApiObject

class that represents data returned by facilities call to the restapi.

Attributes: self.fname : filename for reading and writing df to csv file. self.df : dataframe columns are begin time, end time, isunit (boolean), latitude, longitude, facility_name, oris, unit

Methods: init printall : returns a string with the unpacked data. get : sends request to the restapi and calls unpack. oris_by_area : returns list of oris codes in an area get_units : returns a list of units for an oris code

set_filename : set filename to save and load from.
load : load datafraem from csv file
save : save dateframe to csv file
get  : request facilities information from api
unpack : process the data sent back from the api
         and put relevant info in a dataframe.
Source code in monetio/obs/cems_api.py
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
class FacilitiesData(EpaApiObject):
    """
    class that represents data returned by facilities call to the restapi.

    Attributes:
        self.fname : filename for reading and writing df to csv file.
        self.df  : dataframe
         columns are
         begin time,
         end time,
         isunit (boolean),
         latitude,
         longitude,
         facility_name,
         oris,
         unit

    Methods:
        __init__
        printall : returns a string with the unpacked data.
        get : sends request to the restapi and calls unpack.
        oris_by_area : returns list of oris codes in an area
        get_units : returns a list of units for an oris code

        set_filename : set filename to save and load from.
        load : load datafraem from csv file
        save : save dateframe to csv file
        get  : request facilities information from api
        unpack : process the data sent back from the api
                 and put relevant info in a dataframe.

    """

    def __init__(self, fname="Fac.csv", prompt=False, save=True):
        self.plan_hash = {}
        super().__init__(fname, save, prompt)

    def process_time_fields(self, df):
        """
        time fields give year and quarter.
        This converts them to a datetime object with
        date at beginning of quarter.
        """

        def process_unit_time(instr):
            instr = str(instr)
            # there are many None in end time field.
            try:
                year = int(instr[0:4])
            except ValueError:
                return None
            quarter = int(instr[4])
            if quarter == 1:
                dt = datetime.datetime(year, 1, 1)
            elif quarter == 2:
                dt = datetime.datetime(year, 4, 1)
            elif quarter == 3:
                dt = datetime.datetime(year, 7, 1)
            elif quarter == 4:
                dt = datetime.datetime(year, 10, 1)
            return dt

        df["begin time"] = df.apply(lambda row: process_unit_time(row["begin time"]), axis=1)
        df["end time"] = df.apply(lambda row: process_unit_time(row["end time"]), axis=1)
        return df

    def __str__(self):
        cols = self.df.columns
        rstr = ", ".join(cols)
        return rstr

    def create_getstr(self):
        """
        used to send the request.
        """
        return "facilities"

    def oris_by_area(self, llcrnr, urcrnr):
        """
        llcrnr : tuple (float,float)
        urcrnr : tuple (float,float)
        returns list of oris codes in box defined by
        llcrnr and urcrnr
        """
        dftemp = obs_util.latlonfilter(self.df, llcrnr, urcrnr)
        orislist = dftemp["oris"].unique()
        return orislist

    def state_from_oris(self, orislist):
        """
        orislist : list of oris codes
        Returns
        list of state abbreviations
        """
        # statelist = []
        temp = self.df[self.df["oris"].isin(orislist)]
        return temp["state"].unique()

    def get_units(self, oris):
        """
        oris : int
        Returns list of monitoring location ids
        for a particular oris code.
        """
        oris = str(oris)
        # if self.df.empty:
        #    self.facdata()
        temp = self.df[self.df["oris"] == oris]
        units = temp["unit"].unique()
        return units

    def process_unit_time(self, instr):
        instr = str(instr)
        year = int(instr[0:4])
        quarter = int(instr[4])
        if quarter == 1:
            dt = datetime.datetime(year, 1, 1)
        elif quarter == 2:
            dt = datetime.datetime(year, 4, 1)
        elif quarter == 3:
            dt = datetime.datetime(year, 7, 1)
        elif quarter == 4:
            dt = datetime.datetime(year, 10, 1)
        return dt

    def get_unit_start(self, oris, unit):
        oris = str(oris)
        temp = self.df[self.df["oris"] == oris]
        temp = temp[temp["unit"] == unit]

        start = temp["begin time"].unique()
        # end = temp["end time"].unique()
        sdate = []
        for sss in start:
            sdate.append(self.process_unit_time(sss))
        return sdate

    def get_unit_request(self, oris, unit, sdate):
        oris = str(oris)
        temp = self.df[self.df["oris"] == oris]
        temp = temp[temp["unit"] == unit]
        temp = self.process_time_fields(temp)
        temp = temp[temp["begin time"] <= sdate]
        if temp.empty:
            return None
        temp["testdate"] = temp.apply(lambda row: test_end(row["end time"], sdate), axis=1)
        print("--------------------------------------------")
        print("Monitoring Plans available")
        klist = ["testdate", "begin time", "end time", "unit", "oris", "request_string"]
        print(temp[klist])
        print("--------------------------------------------")
        temp = temp[temp["testdate"]]
        rstr = temp["request_string"].unique()
        return rstr

    def unpack(self, data):
        """
        iterates through a response which contains nested dictionaries and lists.
        # facilities 'data' is a list of dictionaries.
        # there is one dictionary for each oris code.
        # Each dictionary has a list under the key monitoringLocations.
        # each monitoryLocation has a name which is what is needed
        # for the locationID input into the get_emissions.

        return is a dataframe with following fields.

        oris
        facility name
        latitude
        longitude
        status
        begin time
        end time
        unit id
        isunit

        """
        # dlist is a list of dictionaries.
        dlist = []

        # originally just used one dictionary but if doing
        # a['dog'] = 1
        # dlist.append(a)
        # a['dog'] = 2
        # dlist.append(a)
        # for some reason dlist will then update the dictionary and will get
        # dlist = [{'dog': 2}, {'dog':2}] instead of
        # dlist = [{'dog': 1}, {'dog':2}]

        slist = []
        for val in data["data"]:
            ahash = {}
            ahash["oris"] = str(val["orisCode"])
            ahash["facility_name"] = val["name"]
            ahash["latitude"] = val["geographicLocation"]["latitude"]
            ahash["longitude"] = val["geographicLocation"]["longitude"]
            state1 = val["state"]
            ahash["state"] = state1["abbrev"]
            # ahash['time_offset'] = get_timezone_offset(ahash['latitude'],
            #                       ahash['longitude'])
            # keep track of which locations belong to a plan
            plan_number = 1
            # list 2
            for sid in val["units"]:
                unithash = {}
                unitid = sid["unitId"]
                unithash["unit"] = unitid
                unithash["oris"] = ahash["oris"]
                for gid in sid["generators"]:
                    capacity = gid["nameplateCapacity"]
                    # capacity_hash['unitid'] = capacity
                    unithash["capacity"] = capacity
                for gid in sid["fuels"]:
                    if gid["indicatorDescription"].strip() == "Primary":
                        fuel = gid["fuelCode"]
                        # fuel_hash['unitid'] = fuel
                        unithash["primary_fuel"] = fuel
                    else:
                        unithash["primary_fuel"] = np.nan
                for gid in sid["controls"]:
                    if gid["parameterCode"].strip() == "SO2":
                        control = gid["controlCode"]
                        # control_hash['unitid'] = control
                        unithash["so2_contro"] = control
                    else:
                        unithash["so2_contro"] = np.nan
                slist.append(unithash)
            unitdf = pd.DataFrame(slist)

            for sid in val["monitoringPlans"]:
                bhash = {}

                # if sid["status"] == "Active":
                bhash["plan number"] = plan_number
                bhash["status"] = sid["status"]
                bhash["begin time"] = str(sid["beginYearQuarter"])
                bhash["end time"] = str(sid["endYearQuarter"])
                # bhash["state"] = str(sid["abbrev"])
                plan_name = []
                blist = []
                for unit in sid["monitoringLocations"]:
                    chash = {}
                    chash["unit"] = unit["name"]
                    chash["isunit"] = unit["isUnit"]
                    chash.update(ahash)
                    chash.update(bhash)
                    blist.append(chash)
                    # dlist.append(chash)
                    plan_name.append(chash["unit"])
                plan_name.sort()
                request_string = quote(str.join(",", plan_name))
                self.plan_hash[plan_number] = request_string
                for hhh in blist:
                    hhh["request_string"] = request_string
                plan_number += 1
                dlist.extend(blist)

        df = pd.DataFrame(dlist)
        df = pd.merge(df, unitdf, how="left", left_on=["unit", "oris"], right_on=["unit", "oris"])
        return df

create_getstr()

used to send the request.

Source code in monetio/obs/cems_api.py
1385
1386
1387
1388
1389
def create_getstr(self):
    """
    used to send the request.
    """
    return "facilities"

get_units(oris)

oris : int Returns list of monitoring location ids for a particular oris code.

Source code in monetio/obs/cems_api.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
def get_units(self, oris):
    """
    oris : int
    Returns list of monitoring location ids
    for a particular oris code.
    """
    oris = str(oris)
    # if self.df.empty:
    #    self.facdata()
    temp = self.df[self.df["oris"] == oris]
    units = temp["unit"].unique()
    return units

oris_by_area(llcrnr, urcrnr)

llcrnr : tuple (float,float) urcrnr : tuple (float,float) returns list of oris codes in box defined by llcrnr and urcrnr

Source code in monetio/obs/cems_api.py
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
def oris_by_area(self, llcrnr, urcrnr):
    """
    llcrnr : tuple (float,float)
    urcrnr : tuple (float,float)
    returns list of oris codes in box defined by
    llcrnr and urcrnr
    """
    dftemp = obs_util.latlonfilter(self.df, llcrnr, urcrnr)
    orislist = dftemp["oris"].unique()
    return orislist

process_time_fields(df)

time fields give year and quarter. This converts them to a datetime object with date at beginning of quarter.

Source code in monetio/obs/cems_api.py
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
def process_time_fields(self, df):
    """
    time fields give year and quarter.
    This converts them to a datetime object with
    date at beginning of quarter.
    """

    def process_unit_time(instr):
        instr = str(instr)
        # there are many None in end time field.
        try:
            year = int(instr[0:4])
        except ValueError:
            return None
        quarter = int(instr[4])
        if quarter == 1:
            dt = datetime.datetime(year, 1, 1)
        elif quarter == 2:
            dt = datetime.datetime(year, 4, 1)
        elif quarter == 3:
            dt = datetime.datetime(year, 7, 1)
        elif quarter == 4:
            dt = datetime.datetime(year, 10, 1)
        return dt

    df["begin time"] = df.apply(lambda row: process_unit_time(row["begin time"]), axis=1)
    df["end time"] = df.apply(lambda row: process_unit_time(row["end time"]), axis=1)
    return df

state_from_oris(orislist)

orislist : list of oris codes Returns list of state abbreviations

Source code in monetio/obs/cems_api.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
def state_from_oris(self, orislist):
    """
    orislist : list of oris codes
    Returns
    list of state abbreviations
    """
    # statelist = []
    temp = self.df[self.df["oris"].isin(orislist)]
    return temp["state"].unique()

unpack(data)

iterates through a response which contains nested dictionaries and lists.

facilities 'data' is a list of dictionaries.

there is one dictionary for each oris code.

Each dictionary has a list under the key monitoringLocations.

each monitoryLocation has a name which is what is needed

for the locationID input into the get_emissions.

return is a dataframe with following fields.

oris facility name latitude longitude status begin time end time unit id isunit

Source code in monetio/obs/cems_api.py
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
def unpack(self, data):
    """
    iterates through a response which contains nested dictionaries and lists.
    # facilities 'data' is a list of dictionaries.
    # there is one dictionary for each oris code.
    # Each dictionary has a list under the key monitoringLocations.
    # each monitoryLocation has a name which is what is needed
    # for the locationID input into the get_emissions.

    return is a dataframe with following fields.

    oris
    facility name
    latitude
    longitude
    status
    begin time
    end time
    unit id
    isunit

    """
    # dlist is a list of dictionaries.
    dlist = []

    # originally just used one dictionary but if doing
    # a['dog'] = 1
    # dlist.append(a)
    # a['dog'] = 2
    # dlist.append(a)
    # for some reason dlist will then update the dictionary and will get
    # dlist = [{'dog': 2}, {'dog':2}] instead of
    # dlist = [{'dog': 1}, {'dog':2}]

    slist = []
    for val in data["data"]:
        ahash = {}
        ahash["oris"] = str(val["orisCode"])
        ahash["facility_name"] = val["name"]
        ahash["latitude"] = val["geographicLocation"]["latitude"]
        ahash["longitude"] = val["geographicLocation"]["longitude"]
        state1 = val["state"]
        ahash["state"] = state1["abbrev"]
        # ahash['time_offset'] = get_timezone_offset(ahash['latitude'],
        #                       ahash['longitude'])
        # keep track of which locations belong to a plan
        plan_number = 1
        # list 2
        for sid in val["units"]:
            unithash = {}
            unitid = sid["unitId"]
            unithash["unit"] = unitid
            unithash["oris"] = ahash["oris"]
            for gid in sid["generators"]:
                capacity = gid["nameplateCapacity"]
                # capacity_hash['unitid'] = capacity
                unithash["capacity"] = capacity
            for gid in sid["fuels"]:
                if gid["indicatorDescription"].strip() == "Primary":
                    fuel = gid["fuelCode"]
                    # fuel_hash['unitid'] = fuel
                    unithash["primary_fuel"] = fuel
                else:
                    unithash["primary_fuel"] = np.nan
            for gid in sid["controls"]:
                if gid["parameterCode"].strip() == "SO2":
                    control = gid["controlCode"]
                    # control_hash['unitid'] = control
                    unithash["so2_contro"] = control
                else:
                    unithash["so2_contro"] = np.nan
            slist.append(unithash)
        unitdf = pd.DataFrame(slist)

        for sid in val["monitoringPlans"]:
            bhash = {}

            # if sid["status"] == "Active":
            bhash["plan number"] = plan_number
            bhash["status"] = sid["status"]
            bhash["begin time"] = str(sid["beginYearQuarter"])
            bhash["end time"] = str(sid["endYearQuarter"])
            # bhash["state"] = str(sid["abbrev"])
            plan_name = []
            blist = []
            for unit in sid["monitoringLocations"]:
                chash = {}
                chash["unit"] = unit["name"]
                chash["isunit"] = unit["isUnit"]
                chash.update(ahash)
                chash.update(bhash)
                blist.append(chash)
                # dlist.append(chash)
                plan_name.append(chash["unit"])
            plan_name.sort()
            request_string = quote(str.join(",", plan_name))
            self.plan_hash[plan_number] = request_string
            for hhh in blist:
                hhh["request_string"] = request_string
            plan_number += 1
            dlist.extend(blist)

    df = pd.DataFrame(dlist)
    df = pd.merge(df, unitdf, how="left", left_on=["unit", "oris"], right_on=["unit", "oris"])
    return df

MonitoringPlan

Bases: EpaApiObject

Stack height is converted to meters. Request to get monitoring plans for oris code and locationID. locationIDs for an oris code can be found in

The monitoring plan has locationAttributes which include the stackHeight, crossAreaExit, crossAreaFlow.

It also includes monitoringSystems which includes ststeymTypeDescription (such as So2 Concentration)

QuarterlySummaries gives so2Mass each quarter.

currently stack height is the only information

we want to get from monitoring plan

request string

date which indicates quarter of request

oris

mid

stack height

6.0 Monitoring Method Data March 11, 2015 Environmental Protection Agency Monitoring Plan Reporting Instructions -- Page 37

If a location which has an SO2 monitor combusts both high sulfur fuel (e.g., coal or oil) and a low sulfur fuel, and uses a default SO2 emission rate in conjunction with Equation F-23 for hours in which very low sulfur fuel is combusted (see ?75.11(e)(1)), report one monitor method record for parameter SO2 with a monitoring methodology code CEMF23. If only low-sulfur fuel is combusted and the F-23 calculation is used for every

hour, report the SO2 monitoring method as F23
Source code in monetio/obs/cems_api.py
 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
class MonitoringPlan(EpaApiObject):
    """
    Stack height is converted to meters.
    Request to get monitoring plans for oris code and locationID.
    locationIDs for an oris code can be found in

    The monitoring plan has locationAttributes which
    include the stackHeight, crossAreaExit, crossAreaFlow.

    It also includes monitoringSystems which includes
    ststeymTypeDescription (such as So2 Concentration)

    QuarterlySummaries gives so2Mass each quarter.

    # currently stack height is the only information
    # we want to get from monitoring plan

    # request string
    # date which indicates quarter of request
    # oris
    # mid
    # stack height
    ------------------------------------------------------------------------------
    6.0 Monitoring Method Data March 11, 2015
    Environmental Protection Agency Monitoring Plan Reporting Instructions -- Page
    37

    If a location which has an SO2 monitor combusts both high sulfur fuel (e.g., coal
    or oil)
    and a low sulfur fuel, and uses a default SO2 emission rate in conjunction with
    Equation
    F-23 for hours in which very low sulfur fuel is combusted (see ?75.11(e)(1)),
    report one
    monitor method record for parameter SO2 with a monitoring methodology code
    CEMF23. If only low-sulfur fuel is combusted and the F-23 calculation is used
    for every
    hour, report the SO2 monitoring method as F23
    ------------------------------------------------------------------------------

    """

    def __init__(self, oris, mid, date, fname="Mplans.csv", save=True, prompt=False):
        self.oris = oris  # oris code of facility
        self.mid = mid  # monitoring location id.
        self.date = date  # date
        self.dfall = pd.DataFrame()
        self.dfmt = "%Y-%m-%dT%H:%M:%S"
        super().__init__(fname, save, prompt)

    def to_dict(self, unit=None):
        if self.df.empty:
            return None

        if unit:
            df = self.df[self.df["name"] == unit]
        else:
            df = self.df.copy()

        try:
            mhash = df.reset_index().to_dict("records")
        except Exception:
            mhash = None
        return mhash

    def get_stackht(self, unit):
        # print(self.df)
        df = self.df[self.df["name"] == unit]
        # print(df)
        stackhts = df["stackht"].unique()
        # print('get stackht', stackhts)
        return stackhts

    def get_method(self, unit, daterange):
        # TO DO. pick method code based on dates.
        temp = self.df[self.df["name"] == unit]
        sdate = daterange[0]
        edate = daterange[1]

        temp = temp[temp["beginDateHour"] <= sdate]
        if temp.empty:
            return None

        temp["testdate"] = temp.apply(lambda row: test_end(row["endDateHour"], edate), axis=1)
        temp = temp[temp["testdate"]]
        method = temp["methodCode"].unique()

        return method

    def load(self):
        # Multiple mplans may be saved to the same csv file.
        # so this may return an emptly dataframe

        # returns empty dataframe and flag to send request.
        # return pd.DataFrame(), True
        # df = super().load()
        chash = {"mid": str, "oris": str, "name": str}

        def parsedate(x, sfmt):
            if not x:
                return pd.NaT
            elif x == "None":
                return pd.NaT
            else:
                try:
                    return pd.to_datetime(x, format=sfmt)
                except Exception:
                    print("time value", x)
                    return pd.NaT

        df = pd.read_csv(
            self.fname,
            index_col=[0],
            converters=chash,
            parse_dates=["beginDateHour", "endDateHour"],
            date_format=self.dfmt,
        )

        self.dfall = df.copy()
        df = df[df["oris"] == self.oris]
        df = df[df["mid"] == self.mid]
        if not df.empty:
            self.status_code = 200
        return df, True

    def save(self):
        # do not want to overwrite other mplans in the file.
        df = pd.DataFrame()
        subset = [
            "oris",
            "name",
            "request_date",
            "methodCode",
            "beginDateHour",
            "endDateHour",
        ]
        try:
            df, bval = self.load()
        except BaseException:
            pass
        if not self.dfall.empty:
            df = pd.concat([self.dfall, self.df], sort=True)
            df = df.drop_duplicates(subset=subset)
            df.to_csv(self.fname)
        elif not self.df.empty:
            self.df.to_csv(self.fname)

    def create_getstr(self):
        oris = self.oris
        mid = self.mid
        dstr = self.date.strftime("%Y-%m-%d")
        mstr = "monitoringplan"
        getstr = quote("/".join([mstr, str(oris), str(mid), dstr]))
        return getstr

    def unpack(self, data):
        """
        Returns:

        Information for one oris code and monitoring location.
        columns
        stackname, unit, stackheight, crossAreaExit,
        crossAreaFlow, locID, isunit

        Example ORIS 1571 unit 2 has no stack height.
        """
        ihash = data["data"]
        ft2m = 0.3048
        dlist = []

        # The stackname may contain multiple 'units'
        stackname = ihash["unitStackName"]
        # stackhash = {}
        shash = {}

        # first go through the unitStackConfigurations
        # sometimes a unit can have more than one unitStack.
        # TODO - not sure how to handle this.
        # y2009 3788 oris has this issue but both unit stacks have
        # the same stack height so it is not an issue.

        # the api seems to do emissions by the stack and not by
        # the unit. so this may be a non-issue for api data.

        # oris 1305 y2017 has unitStack CP001 and unitID GT1 and GT3.
        # height is given for GT1 and GT3 and NOT CP001.

        for stackconfig in ihash["unitStackConfigurations"]:
            # this maps the unitid to the stack id.
            # after reading in the data, go back and assign
            # stack height to the unit based on the stackconfig.
            if "unitId" in stackconfig.keys():
                name = stackconfig["unitId"]
                if name in shash.keys():
                    wstr = "-----------------------------\n"
                    wstr += "WARNING: unit " + name + "\n"
                    wstr += " oris; " + self.oris + "\n"
                    wstr += "has multiple unitStacks \n"
                    wstr += shash[name] + " " + stackconfig["unitStack"]
                    wstr += "-----------------------------\n"
                    print(wstr)
                shash[name] = stackconfig["unitStack"]
            else:
                print("STACKconfig")
                print(stackconfig)

        # next through the monitoringLocations
        for unithash in ihash["monitoringLocations"]:
            dhash = {}

            name = unithash["name"]
            print("NAME ", name)
            dhash["name"] = name
            if name in shash.keys():
                dhash["stackunit"] = shash[name]
            else:
                dhash["stackunit"] = name

            dhash["isunit"] = unithash["isUnit"]
            dhash["stackname"] = stackname
            for att in unithash["locationAttributes"]:
                if "stackHeight" in att.keys():
                    print("stackheight " + name)
                    print(att["stackHeight"])

                    try:
                        dhash["stackht"] = float(att["stackHeight"]) * ft2m
                    except ValueError:
                        dhash["stackht"] = np.nan
                else:
                    dhash["stackht"] = np.nan

                # dhash["crossAreaExit"] = att["crossAreaExit"]
                # dhash["crossAreaFlow"] = att["crossAreaFlow"]
                # dhash["locID"] = att["locId"]
                # dhash["isunit"] = att["isUnit"]
                # dlist.append(dhash)

            # each monitoringLocation has list of monitoringMethods
            iii = 0
            for method in unithash["monitoringMethods"]:
                # print('METHOD LIST', method)
                if "SO2" in method["parameterCode"]:
                    print("SO2 data")
                    dhash["parameterCode"] = method["parameterCode"]
                    dhash["methodCode"] = method["methodCode"]
                    dhash["beginDateHour"] = pd.to_datetime(
                        method["beginDateHour"], format=self.dfmt
                    )
                    dhash["endDateHour"] = pd.to_datetime(method["endDateHour"], format=self.dfmt)
                    dhash["oris"] = self.oris
                    dhash["mid"] = self.mid
                    dhash["request_date"] = self.date
                    print("Monitoring Location ------------------")
                    print(dhash)
                    print("------------------")
                    dlist.append(copy.deepcopy(dhash))
                    iii += 1
            # if there is no monitoring method for SO2
            if iii == 0:
                dhash["parameterCode"] = "None"
                dhash["methodCode"] = "None"
                dhash["beginDateHour"] = pd.NaT
                dhash["endDateHour"] = pd.NaT
                dhash["oris"] = self.oris
                dhash["mid"] = self.mid
                dhash["request_date"] = self.date
                print("Monitoring Location ------------------")
                print(dhash)
                print("------------------")
                dlist.append(copy.deepcopy(dhash))

        # print(dlist)
        df = pd.DataFrame(dlist)
        # print('DF1 ------------------')
        # print(df[['oris','name','methodCode','beginDateHour']])
        nseries = df.set_index("name")
        nseries = nseries["stackht"]
        nhash = nseries.to_dict()

        def find_stackht(name, stackht, shash, nhash):
            if pd.isna(stackht):
                # this handles case when height is specified for the stackId
                # and not the unitId
                if name in shash.keys():
                    sid = shash[name]
                    stackht = nhash[sid]
                # this handles case when height is specified for the unitId
                # and not the stackId
                else:
                    ahash = {y: x for x, y in shash.items()}
                    if name in ahash.keys():
                        sid = ahash[name]
                        stackht = nhash[sid]
            return stackht

        df["stackht"] = df.apply(
            lambda row: find_stackht(row["name"], row["stackht"], shash, nhash), axis=1
        )
        df["stackht_unit"] = "m"
        print("DF2 ------------------")
        print(df)
        return df

unpack(data)

Returns:

Information for one oris code and monitoring location. columns stackname, unit, stackheight, crossAreaExit, crossAreaFlow, locID, isunit

Example ORIS 1571 unit 2 has no stack height.

Source code in monetio/obs/cems_api.py
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
def unpack(self, data):
    """
    Returns:

    Information for one oris code and monitoring location.
    columns
    stackname, unit, stackheight, crossAreaExit,
    crossAreaFlow, locID, isunit

    Example ORIS 1571 unit 2 has no stack height.
    """
    ihash = data["data"]
    ft2m = 0.3048
    dlist = []

    # The stackname may contain multiple 'units'
    stackname = ihash["unitStackName"]
    # stackhash = {}
    shash = {}

    # first go through the unitStackConfigurations
    # sometimes a unit can have more than one unitStack.
    # TODO - not sure how to handle this.
    # y2009 3788 oris has this issue but both unit stacks have
    # the same stack height so it is not an issue.

    # the api seems to do emissions by the stack and not by
    # the unit. so this may be a non-issue for api data.

    # oris 1305 y2017 has unitStack CP001 and unitID GT1 and GT3.
    # height is given for GT1 and GT3 and NOT CP001.

    for stackconfig in ihash["unitStackConfigurations"]:
        # this maps the unitid to the stack id.
        # after reading in the data, go back and assign
        # stack height to the unit based on the stackconfig.
        if "unitId" in stackconfig.keys():
            name = stackconfig["unitId"]
            if name in shash.keys():
                wstr = "-----------------------------\n"
                wstr += "WARNING: unit " + name + "\n"
                wstr += " oris; " + self.oris + "\n"
                wstr += "has multiple unitStacks \n"
                wstr += shash[name] + " " + stackconfig["unitStack"]
                wstr += "-----------------------------\n"
                print(wstr)
            shash[name] = stackconfig["unitStack"]
        else:
            print("STACKconfig")
            print(stackconfig)

    # next through the monitoringLocations
    for unithash in ihash["monitoringLocations"]:
        dhash = {}

        name = unithash["name"]
        print("NAME ", name)
        dhash["name"] = name
        if name in shash.keys():
            dhash["stackunit"] = shash[name]
        else:
            dhash["stackunit"] = name

        dhash["isunit"] = unithash["isUnit"]
        dhash["stackname"] = stackname
        for att in unithash["locationAttributes"]:
            if "stackHeight" in att.keys():
                print("stackheight " + name)
                print(att["stackHeight"])

                try:
                    dhash["stackht"] = float(att["stackHeight"]) * ft2m
                except ValueError:
                    dhash["stackht"] = np.nan
            else:
                dhash["stackht"] = np.nan

            # dhash["crossAreaExit"] = att["crossAreaExit"]
            # dhash["crossAreaFlow"] = att["crossAreaFlow"]
            # dhash["locID"] = att["locId"]
            # dhash["isunit"] = att["isUnit"]
            # dlist.append(dhash)

        # each monitoringLocation has list of monitoringMethods
        iii = 0
        for method in unithash["monitoringMethods"]:
            # print('METHOD LIST', method)
            if "SO2" in method["parameterCode"]:
                print("SO2 data")
                dhash["parameterCode"] = method["parameterCode"]
                dhash["methodCode"] = method["methodCode"]
                dhash["beginDateHour"] = pd.to_datetime(
                    method["beginDateHour"], format=self.dfmt
                )
                dhash["endDateHour"] = pd.to_datetime(method["endDateHour"], format=self.dfmt)
                dhash["oris"] = self.oris
                dhash["mid"] = self.mid
                dhash["request_date"] = self.date
                print("Monitoring Location ------------------")
                print(dhash)
                print("------------------")
                dlist.append(copy.deepcopy(dhash))
                iii += 1
        # if there is no monitoring method for SO2
        if iii == 0:
            dhash["parameterCode"] = "None"
            dhash["methodCode"] = "None"
            dhash["beginDateHour"] = pd.NaT
            dhash["endDateHour"] = pd.NaT
            dhash["oris"] = self.oris
            dhash["mid"] = self.mid
            dhash["request_date"] = self.date
            print("Monitoring Location ------------------")
            print(dhash)
            print("------------------")
            dlist.append(copy.deepcopy(dhash))

    # print(dlist)
    df = pd.DataFrame(dlist)
    # print('DF1 ------------------')
    # print(df[['oris','name','methodCode','beginDateHour']])
    nseries = df.set_index("name")
    nseries = nseries["stackht"]
    nhash = nseries.to_dict()

    def find_stackht(name, stackht, shash, nhash):
        if pd.isna(stackht):
            # this handles case when height is specified for the stackId
            # and not the unitId
            if name in shash.keys():
                sid = shash[name]
                stackht = nhash[sid]
            # this handles case when height is specified for the unitId
            # and not the stackId
            else:
                ahash = {y: x for x, y in shash.items()}
                if name in ahash.keys():
                    sid = ahash[name]
                    stackht = nhash[sid]
        return stackht

    df["stackht"] = df.apply(
        lambda row: find_stackht(row["name"], row["stackht"], shash, nhash), axis=1
    )
    df["stackht_unit"] = "m"
    print("DF2 ------------------")
    print(df)
    return df

addquarter(rdate)

INPUT rdate : datetime object RETURNS newdate : datetime object requests for emissions are made per quarter. Returns first date in the next quarter from the input date.

Source code in monetio/obs/cems_api.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def addquarter(rdate):
    """
    INPUT
    rdate : datetime object
    RETURNS
    newdate : datetime object
    requests for emissions are made per quarter.
    Returns first date in the next quarter from the input date.
    """
    quarter = findquarter(rdate)
    quarter += 1
    year = rdate.year
    if quarter > 4:
        quarter = 1
        year += 1
    month = 3 * quarter - 2
    newdate = datetime.datetime(year, month, 1, 0)
    return newdate

get_datelist(rdate)

INPUT rdate : tuple of datetime objects (start date, end date) RETURNS: rdatelist : list of datetimes covering range specified by rdate by quarter.

Return list of first date in each quarter from startdate to end date.

Source code in monetio/obs/cems_api.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def get_datelist(rdate):
    """
    INPUT
    rdate : tuple of datetime objects
    (start date, end date)
    RETURNS:
    rdatelist : list of datetimes covering range specified by rdate by quarter.

    Return list of first date in each quarter from
    startdate to end date.
    """
    if isinstance(rdate, list):
        rdatelist = get_datelist_sub(rdate[0], rdate[1])
    else:
        rdatelist = [rdate]
    return rdatelist

get_filename(fname, prompt)

determines if file exists. If prompt is True then will prompt for new filename if file does not exist.

Source code in monetio/obs/cems_api.py
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
def get_filename(fname, prompt):
    """
    determines if file exists. If prompt is True then will prompt for
    new filename if file does not exist.
    """
    if fname:
        done = False
        iii = 0
        while not done:
            if iii > 2:
                done = True
            iii += 1
            if os.path.isfile(fname):
                done = True
            elif prompt:
                istr = "\n" + fname + " is not a valid name for Facilities Data \n"
                istr += "Please enter a new filename \n"
                istr += "enter None to load from the api \n"
                istr += "enter x to exit program \n"
                fname = input(istr)
                # print('checking ' + fname)
                if fname == "x":
                    sys.exit()
                if fname.lower() == "none":
                    fname = None
                    done = True
            else:
                fname = None
                done = True
    return fname

get_lookups()

Request to get lookups - descriptions of various codes.

Source code in monetio/obs/cems_api.py
189
190
191
192
193
194
195
196
197
198
199
def get_lookups():
    """
    Request to get lookups - descriptions of various codes.
    """
    getstr = "emissions/lookUps"
    # rqq = self.apiurl + "emissions/" + getstr
    # rqq += "?api_key=" + self.key
    data = sendrequest(getstr)
    jobject = data.json()
    dstr = unpack_response(jobject)
    return dstr

get_monitoring_plan(oris, mid, mrequest, date1, dflist)

oris : oris code mid : unit id mrequest : list of strings: request to send date1 : date to request dflist : in/out list of tuples [(oris, mid, stackht)]

Source code in monetio/obs/cems_api.py
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
def get_monitoring_plan(oris, mid, mrequest, date1, dflist):
    """
    oris : oris code
    mid  : unit id
    mrequest : list of strings: request to send
    date1 : date to request
    dflist : in/out  list of tuples [(oris, mid, stackht)]
    """
    # adds to list of oris, mid, stackht which will later be turned into
    # a dataframe with that information.
    status_code = 204
    # mhash = None
    for mr in mrequest:
        print("Get Monitoring Plan " + mr)
        plan = MonitoringPlan(str(oris), mr, date1)
        status_code = plan.status_code  # noqa: F841
        stackht = plan.get_stackht(mid)
    if len(stackht) == 1:
        print(len(stackht))
        stackht = stackht[0]
        print(stackht)
    #    mhash = plan.to_dict(mid)
    # if mhash:
    #    if len(mhash) > 1:
    #        print(
    #            "CEMS class WARNING: more than one \
    #              Monitoring location for this unit\n"
    #        )
    #        print(str(oris) + " " + str(mid) + "---")
    #        for val in mhash.keys():
    #            print(val, mhash[val])
    #        sys.exit()
    #    else:
    #        mhash = mhash[0]
    #        stackht = float(mhash["stackht"])
    else:
        print("Stack height not determined ", stackht)
        stackht = None
        istr = "\n" + "Could not retrieve stack height from monitoring plan \n"
        istr += "Please enter stack height (in meters) \n"
        istr += "for oris " + str(oris) + " and unit" + str(mid) + " \n"
        test = input(istr)
        try:
            stackht = float(test)
        except ValueError:
            stackht = None
    method = plan.get_method(mid, [date1, date1])
    print("METHODS returned", method, mid, str(oris))
    # catchall so do not double count.
    # currently CEM and CEMF23 result in same EmissionCall request string.
    if method:
        if "CEM" in method and "CEMF23" in method:
            method = "CEM"
    dflist.append((str(oris), mid, stackht))

    return dflist, method

get_so2(df)

drop columns that are not in keep.

Source code in monetio/obs/cems_api.py
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
def get_so2(df):
    """
    drop columns that are not in keep.
    """
    keep = [
        # "DateHour",
        "time local",
        # "time",
        "OperatingTime",
        # "HourLoad",
        # "u so2_lbs",
        "so2_lbs",
        # "AdjustedFlow",
        # "UnadjustedFlow",
        # "FlowMODC",
        "SO2MODC",
        "unit",
        "stackht",
        "oris",
        "latitude",
        "longitude",
    ]
    df = keepcols(df, keep)
    if not df.empty:
        df = df[df["oris"] != "None"]
    return df

getkey()

key and url should be stored in $HOME/.epaapirc

Source code in monetio/obs/cems_api.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def getkey():
    """
    key and url should be stored in $HOME/.epaapirc
    """
    dhash = {}
    homedir = os.environ["HOME"]
    fname = "/.epaapirc"
    if os.path.isfile(homedir + fname):
        with open(homedir + fname) as fid:
            lines = fid.readlines()
        for temp in lines:
            temp = temp.split(" ")
            dhash[temp[0].strip().replace(":", "")] = temp[1].strip()
    else:
        dhash["key"] = None
        dhash["url"] = None
        dhash["geousername"] = None
    return dhash

match_column(df, varname)

varname is list of strings. returns column name which contains all the strings.

Source code in monetio/obs/cems_api.py
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
def match_column(df, varname):
    """varname is list of strings.
    returns column name which contains all the strings.
    """
    columns = list(df.columns.values)
    cmatch = None
    for ccc in columns:
        match = 0
        for vstr in varname:
            if vstr.lower() in ccc.lower():
                match += 1
        if match == len(varname):
            cmatch = ccc
    return cmatch

sendrequest(rqq, key=None, url=None)

Method for sending requests to the EPA API

Inputs :

rqq : string request string.

Returns:

data : response object

Source code in monetio/obs/cems_api.py
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
def sendrequest(rqq, key=None, url=None):
    """
    Method for sending requests to the EPA API
    Inputs :
    --------
    rqq : string
          request string.
    Returns:
    --------
    data : response object
    """
    if not key or not url:
        keyhash = getkey()
        apiurl = keyhash["url"]
        key = keyhash["key"]
    if key:
        # apiurl = "https://api.epa.gov/FACT/1.0/"
        rqq = apiurl + rqq + "?api_key=" + key
        print("Request: ", rqq)
        data = requests.get(rqq)
        print("Status Code", data.status_code)
        if data.status_code == 429:
            print("Too many requests Please Wait before trying again.")
            sys.exit()
    else:
        print("WARNING: your api key for EPA data was not found")
        print("Please obtain a key from")
        print("https://www.epa.gov/airmarkets/field-audit-checklist_tool-fact-api")
        print("The key should be placed in $HOME/.epaapirc")
        print("Contents of the file should be as follows")
        print("key: apikey")
        print("url: https://api.epa.gov/FACT/1.0/")
        sys.exit()
    return data

unpack_response(dhash, deep=100, pid=0)

iterates through a response which contains nested dictionaries and lists. dhash: dictionary which may be nested. deep: int indicated how deep to print out nested levels. pid : int

Source code in monetio/obs/cems_api.py
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
def unpack_response(dhash, deep=100, pid=0):
    """
    iterates through a response which contains nested dictionaries and lists.
    dhash: dictionary which may be nested.
    deep: int
        indicated how deep to print out nested levels.
    pid : int

    """
    rstr = ""
    for k2 in dhash.keys():
        iii = pid
        spc = " " * iii
        rstr += spc + str(k2) + " " + str(type(dhash[k2])) + " : "
        # UNPACK DICTIONARY
        if iii < deep and isinstance(dhash[k2], dict):
            rstr += "\n"
            iii += 1
            rstr += spc
            rstr += unpack_response(dhash[k2], pid=iii)
            rstr += "\n"
        # UNPACK LIST
        elif isinstance(dhash[k2], list):
            iii += 1
            rstr += "\n---BEGIN LIST---" + str(iii) + "\n"
            for val in dhash[k2]:
                if isinstance(val, dict):
                    rstr += unpack_response(val, deep=deep, pid=iii)
                    rstr += "\n"
                else:
                    rstr += spc + "listval " + str(val) + str(type(val)) + "\n"
            rstr += "---END LIST---" + str(iii) + "\n"
        elif isinstance(dhash[k2], str):
            rstr += spc + dhash[k2] + "\n"
        elif isinstance(dhash[k2], int):
            rstr += spc + str(dhash[k2]) + "\n"
        elif isinstance(dhash[k2], float):
            rstr += spc + str(dhash[k2]) + "\n"
        else:
            rstr += "\n"
    return rstr