Search code examples
pythonnumpytypeerrorcartopypython-iris

What am I doing wrong? TypeError: unsupported operand type(s) for -: 'str' and 'Cube'


I am having some problems with my code for my MSc thesis. I am following https://github.com/ErikaWarnatzsch/Malawi-Future-Climate-Modelling-Assessment/edit/master/Histogram_TasMAX.py model to be able to build a Histogram for future RCP scenarios (4.5 and 8.5) while using historical and observed data.

The region I am looking at lies along the Central belt of Colombia.

The code that I fed in goes as follows:

import numpy as np
import iris
import iris.coord_categorisation as iriscc
import iris.analysis.cartography

def main():
    
    Current45_b = r'C:\Users\issaa\OneDrive\Desktop\Thesis\Coding\EW_Method\Air Temperature\Tasmax\PastModel\tasmax_historicalcombined.nc'

    Current45_b = iris.load_cube(Current45_b, 'air_temperature')

    lats = iris.coords.DimCoord(Current45_b.coord('latitude').points[:,0], standard_name='latitude', units='degrees')
    lons = Current45_b.coord('longitude').points[0]
    for i in range(len(lons)):
        if 100. < lons[i]:
            lons[i] -= 360.
    lons = iris.coords.DimCoord(lons, standard_name='longitude', units='degrees')
                              
    Current45_b.remove_coord('latitude')
    Current45_b.remove_coord('longitude')
    Current45_b.remove_coord('grid_latitude')
    Current45_b.remove_coord('grid_longitude')
    Current45_b.add_dim_coord(lats, 1)
    Current45_b.add_dim_coord(lons, 2)

    Current45_b.coord('latitude').guess_bounds()
    Current45_b.coord('longitude').guess_bounds()

    Current45 =  r'C:\Users\issaa\OneDrive\Desktop\Thesis\Coding\EW_Method\Air Temperature\Tasmax\RCP4.5\tasmax_rcp45combined.nc'
    Current85 =  r'C:\Users\issaa\OneDrive\Desktop\Thesis\Coding\EW_Method\Air Temperature\Tasmax\RCP_8.5_Future\tasmax_rcp8.5combined.nc'
    
    Current45 = iris.load_cube(Current45, 'air_temperature')
    Current85 = iris.load_cube(Current85, 'air_temperature')
    
    lats = iris.coords.DimCoord(Current45.coord('latitude').points[:,0], standard_name='latitude', units='degrees')
    lons = Current45.coord('longitude').points[0]
    for i in range(len(lons)):
        if 100. < lons[i]:
            lons[i] -= 360.
    lons = iris.coords.DimCoord(lons, standard_name='longitude', units='degrees')
                              
    Current45.remove_coord('latitude')
    Current45.remove_coord('longitude')
    Current45.remove_coord('grid_latitude')
    Current45.remove_coord('grid_longitude')
    Current45.add_dim_coord(lats, 1)
    Current45.add_dim_coord(lons, 2)

    Current45.coord('latitude').guess_bounds()
    Current45.coord('longitude').guess_bounds()
   
    lats = iris.coords.DimCoord(
     Current85.coord('latitude').points[:,0], 
    standard_name='latitude', 
    units='degrees'
    )
    lats = iris.coords.DimCoord(Current85.coord('latitude').points[:,0], standard_name='latitude', units='degrees')
    lons = Current85.coord('longitude').points[0]
    for i in range(len(lons)):
        if lons[i]>100.:
            lons[i] = lons[i]-360.
    lons = iris.coords.DimCoord(lons, standard_name='longitude', units='degrees')
                              
    Current85.remove_coord('latitude')
    Current85.remove_coord('longitude')
    Current85.remove_coord('grid_latitude')
    Current85.remove_coord('grid_longitude')
    Current85.add_dim_coord(lats, 1)
    Current85.add_dim_coord(lons, 2)

    Current85.coord('latitude').guess_bounds()
    Current85.coord('longitude').guess_bounds()

    CRU = r'C:\Users\issaa\OneDrive\Desktop\Thesis\Coding\EW_Method\Air Temperature\Tasmax\Observed Data\cru_ts4.04.1901.2019.tmx.dat.nc'
     #good up until line 77 -  TypeError : unsupported operand type(s) for -: 'str' and 'cube'
    CRU - iris.load_cube(CRU, 'near-surface temperature maximum')

    CRU.coord('latitude').guess_bounds()

    iris.FUTURE.cell_datetime_objects = True
    t_constraint_obs = iris.Constraint(time=lambda cell: 1951 <= cell.point.year <= 2006)
    CRU = CRU.extract(t_constraint_obs)


    Central_Colombia = iris.Constraint(longitude=lambda v: -76.2 <= v <= -74.73, \
                            latitude=lambda v: 4.43 <= v <= 5.3)

    Current45_b = Current45_b.extract(Central_Colombia)
    Current45 = Current45.extract(Central_Colombia)
    Current85 = Current85.extract(Central_Colombia)

    CRU = CRU.extract(Central_Colombia)

    Current45_b.convert_units('Celsius')
    Current45.convert_units('Celsius')
    Current85.convert_units('Celsius')



    iriscc.add_day_of_year(Current45_b, 'time')
    iriscc.add_day_of_year(Current45, 'time')
    iriscc.add_day_of_year(Current85, 'time')

    iriscc.add_day_of_year(CRU, 'time')

    iriscc.add_year(Current45_b, 'time')
    iriscc.add_year(Current45, 'time')
    iriscc.add_year(Current85, 'time')


    Current45_b = Current45_b.aggregated_by('year', iris.analysis.MEAN)
    
    CRU = CRU.aggregated_by('year', iris.analysis.MEAN)

    Current45_b_grid_areas = iris.analysis.cartography.area_weights(Current45_b)

    CRU_grid_areas = iris.analysis.cartography.area_weights(CRU)

    Current45_b_mean = Current45_b.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=Current45_b_grid_areas)

    CRU_mean = CRU.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=CRU_grid_areas)

    Current45_b_mean = Current45_b_mean.collapsed(['time'], iris.analysis.MEAN)

    CRU_mean = CRU_mean.collapsed(['time'], iris.analysis.MEAN)

    Obs = CRU_mean

    iris.FUTURE.cell_datetime_objects = True

    t_constraint_30 = iris.Constraint(time=lambda cell: 2020 <= cell.point.year <= 2049)

    Current45_30 = Current45.extract(t_constraint_30)
    Current85_30 = Current85.extract(t_constraint_30)

    Current45_30 = Current45_30.aggregated_by('day_of_year', iris.analysis.MEAN)
    Current85_30 = Current85_30.aggregated_by('day of year', iris.analysis.MEAN)

    Current45_30_grid_areas = iris.analysis.cartography.area_weights(Current45_30)
    Current85_30_grid_areas = iris.analysis.cartography.area_weights(Current85_30)

    Current45_30_mean = Current45_30.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=Current45_30_grid_areas)
    Current85_30_mean = Current85_30.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=Current85_30_grid_areas)
    
    Current45_30_mean = (Current_45_30_mean.data - Current45_b_mean.data + Obs.data)

    Current85_30_mean = (Current_85_30_mean.data - Current85_b_mean.data + Obs.data)

    import csv
    with open('output_TasMAXdata.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')

        writer.writerow(['Parameter', 'Means'])

        writer.writerow(["Current45_30_mean"] + Current45_30_mean.data.flatten().astype(np.str).tolist())

        writer.writerow(["Current85_30_mean"] + Current85_30_mean.data.flatten().astype(np.str).tolist())

if __name__ == '__main__':
    main()

However I am receiving the error message:


(env) C:\Users\issaa\Desktop\190720>python  testewhistogram_tasmax.py
C:\Users\issaa\Anaconda3\envs\env\lib\site-packages\iris\fileformats\cf.py:1038: UserWarning: Ignoring variable 'rotated
_pole' referenced by variable 'tasmax': Dimensions ('time', 'string1') do not span ('time', 'rlat', 'rlon')
  warnings.warn(msg)
C:\Users\issaa\Anaconda3\envs\env\lib\site-packages\iris\fileformats\cf.py:1038: UserWarning: Ignoring variable 'rotated
_pole' referenced by variable 'tasmax': Dimensions ('time', 'string1') do not span ('time', 'rlat', 'rlon')
  warnings.warn(msg)
C:\Users\issaa\Anaconda3\envs\env\lib\site-packages\iris\fileformats\cf.py:1038: UserWarning: Ignoring variable 'rotated
_pole' referenced by variable 'tasmax': Dimensions ('time', 'string1') do not span ('time', 'rlat', 'rlon')
  warnings.warn(msg)
Traceback (most recent call last):
  File "testewhistogram_tasmax.py", line 161, in <module>
    main()
  File "testewhistogram_tasmax.py", line 77, in main
    CRU - iris.load_cube(CRU, 'near-surface temperature maximum')
TypeError: unsupported operand type(s) for -: 'str' and 'Cube'

I saw some stuff on the internet about it being a Python 2/Python 3 typing error - however I am still a bit confused where to go from here.

Many thanks for any help :)


Solution

  • I think it's just a typo!

        CRU - iris.load_cube(CRU, 'near-surface temperature maximum')
    

    that line has a "-" where it should have "=".

    The "-" in the type error didn't really register for me when I looked at it, but that line is clearly not what you want to do!