size = 10000

tco2_store = np.empty(size)
talk_store = np.empty(size)
ph_store = np.empty(size)
co3_store = np.empty(size)
co2_store = np.empty(size)

for i in range(size):
	tmp_tco2 = random.randint(1600,2300)/1.0e6
	tmp_alk = random.randint(1800,2500)/1.0e6
	tco2_store[i] = tmp_tco2
	talk_store[i] = tmp_alk
	TCO2.fill(tmp_tco2)
	TALK.fill(tmp_alk)
	ph_store[i] =  carbchem.carbchem(2,mdi,T,S,TCO2,TALK)[0]
	co3_store[i] =  carbchem.carbchem(5,mdi,T,S,TCO2,TALK)[0]
	co2_store[i] = carbchem.carbchem(1,mdi,T,S,TCO2,TALK)[0]



x = ph_store
y = co3_store
z = co2_store
# define grid.
xi = np.linspace(np.min(x),np.max(x),100)
yi = np.linspace(np.min(y),np.max(y),100)
# grid the data.
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
# contour the gridded data, plotting dots at the randomly spaced data points.
#CS = plt.contour(xi,yi,zi,51,linewidths=0.5,colors='k')
import carbchem
import numpy as np
import matplotlib.pyplot as plt

mdi=-999.0
sizing=(100)
T = np.empty(sizing)
S = np.empty(sizing)
TCO2 = np.empty(sizing)
TALK = np.empty(sizing)
T.fill(15.0)
S.fill(32.0)

tco2_tmp = 0.005
talk_tmp = 0.005

for i in np.arange(100):
	TCO2[i] = tco2_tmp
	TALK[i] = talk_tmp
	tco2_tmp = tco2_tmp*0.99
	talk_tmp = talk_tmp*0.99

plt.plot(TALK,carbchem.carbchem(1,mdi,T,S,TCO2,TALK))
plt.show()
    # plt.show()

mlr_tco2.data = mlr_tco2_tmp
mlr_alk.data = mlr_alk_tmp

import carbchem


pco2_tmp = pco2.data
pH_tmp = pco2.data
for i in np.arange(pco2_tmp.shape[0]):
    tco2_in2 = tco2_in[i]
    tco2_in2.transpose()
    alk_in2 = alk_in[i]
    alk_in2.transpose()
    pco2_tmp[i,:,:] = carbchem.carbchem(1,0.0,sst_in[0][i].data,sss_in[0][i].data,mlr_tco2_tmp[i,:,:]/(1026.*1000.),mlr_alk_tmp[i,:,:]/(1026.*1000.))
    pH_tmp[i,:,:] = carbchem.carbchem(2,0.0,sst_in[0][i].data,sss_in[0][i].data,mlr_tco2_tmp[i,:,:]/(1026.*1000.),mlr_alk_tmp[i,:,:]/(1026.*1000.))

    #CARBCHEM.carbchem(1,0.0,sst_in[0][i].data,sss_in[0][i].data,tco2_in2.data/(1000.*1000.),alk_in2.data/(1000.*1000.))

#note that his is only applicable near the surface because I've not introducsed the pressure term...

#note that the pCO2 we calculate using glodap and woa is high when before I start MLRing. Why is this? Glodap is paracticle alkalinity, as the carbem script uses.

pco2.data = pco2_tmp
pH = pco2
pH.data = pH_tmp

qplt.contourf(pco2[0])
plt.show()
        s_temp=s[(years == yr_temp) & (months == month_temp) & (tco2 != mdi) & (t != mdi) & (s != mdi) & (talk != mdi) & (depth <= 20.0)]
        tco2_temp=tco2[(years == yr_temp) & (months == month_temp) & (tco2 != mdi) & (t != mdi) & (s != mdi) & (talk != mdi) & (depth <= 20.0)]
        talk_temp=talk[(years == yr_temp) & (months == month_temp) & (tco2 != mdi) & (t != mdi) & (s != mdi) & (talk != mdi) & (depth <= 20.0)]
        #pulls out only those lats and longs corresponding to the subpolar gyre
        test1=np.in1d(lats_temp,spg_lats)
        test2=np.in1d(lons_temp,spg_lons)
 
        #note - I can't find a simple way of combining the two masks - this is the best I can manage!
        combined_mask=np.copy(test1)
        combined_mask.fill(False)
        loc=[i for i,x in enumerate(test1) if (test1[i] == True) & (test2[i] == True)]
        combined_mask[loc]=True
  
        #calculate the mean pco2 for the spg in that year and month
        if t_temp[combined_mask].size > 1:
            temp_co2_data = carbchem.carbchem(1,mdi,t_temp[combined_mask],s_temp[combined_mask],tco2_temp[combined_mask],talk_temp[combined_mask])
            # print 'lats: '+str(lats_temp[combined_mask[0:10]])
            # print 'lons: '+str(lons_temp[combined_mask[0:10]])
            # print 'T: '+str(t_temp[combined_mask[0:10]])
            # print 'S: '+str(s_temp[combined_mask[0:10]])
            # print 'TALK: '+str(tco2_temp[combined_mask[0:10]])
            # print 'TCO2: '+str(talk_temp[combined_mask[0:10]])
            # print np.mean(temp_co2_data)
            # print 'year: '+str(yr_temp)
            # print 'month: '+str(month_temp)
            # print '\n'
            co2_obs.append(np.mean(temp_co2_data))
            year_co2.append(yr_temp)
            month_co2.append(month_temp)
            lats_obs.append(lats_temp[combined_mask])
            lons_obs.append(lons_temp[combined_mask])
plt.figure()
plt.pcolor(alk_field2,cmap='jet',vmin = vmin,vmax = vmax)
plt.colorbar()
plt.title('mean alkalinity = '+np.str(np.mean(alk_field1))+' (mol kg$^{-1}$)')
#plt.show(block = False)
plt.savefig('/home/ph290/Documents/figures/alkalinity_nonlinearity/alk_2.pdf',transparent = True)

plt.figure()
plt.pcolor(alk_field3,cmap='jet',vmin = vmin,vmax = vmax)
plt.colorbar()
plt.title('mean alkalinity = '+np.str(np.mean(alk_field1))+' (mol kg$^{-1}$)')
#plt.show(block = False)
plt.savefig('/home/ph290/Documents/figures/alkalinity_nonlinearity/alk_3.pdf',transparent = True)


co2_1 = carbchem.carbchem(1,-99.9,t,s,dic,alk_field1)
co2_2 = carbchem.carbchem(1,-99.9,t,s,dic,alk_field2)
co2_3 = carbchem.carbchem(1,-99.9,t,s,dic,alk_field3)


vmin1 = 100
vmax1 = 3000

plt.figure()
plt.pcolor(co2_1,cmap='jet',vmin = vmin1,vmax = vmax1)
plt.colorbar()
plt.title('mean pCO$_2$ = '+np.str(np.mean(co2_1))+' (uatm.)')
#plt.show(block = False)
plt.savefig('/home/ph290/Documents/figures/alkalinity_nonlinearity/co2_1.pdf',transparent = True)

plt.figure()
rcp85=['ajnji', 'kaadf', 'kaaef', 'kaaff']
co2_stab=['alytb']
geo_e=['amreb','amrec']

#runs=[rcp26,rcp45,rcp60,rcp85,co2_stab,geo_e]
runs=[g3,g4]

for i,dummy in enumerate(runs):
    size=np.size(dummy)
    for j in range(size):
        print 'processing '+runs[i][j]

        cube=iris.load(dir+runs[i][j]+'/*.pp')

        s101 = cube.extract(c_stash_101)
        s101=s101[0]
        s102 = cube.extract(c_stash_102)
        s102=s102[0]
        s103 = cube.extract(c_stash_103)
        s103=s103[0]
        s104 = cube.extract(c_stash_104)
        s104=s104[0]

        arag_ss_data = carbchem.carbchem(9,s101.data.fill_value,s101.data,s102.data*1000.0+35.0,s103.data/(1026.0*1000.0),s104.data/(1026.0*1000.0))

        arag_ss=s101.copy(data=arag_ss_data)
        arag_ss.long_name='aragnoite_saturation_state'

        iris.fileformats.netcdf.save(arag_ss, '/data/local/hador/arag_ss/'+runs[i][j]+'.nc', netcdf_format='NETCDF3_CLASSIC')

def answer(TALK,TCO2,t,s):
    H2CO3 = cc.carbchem(3,-99.0,np.array([t,t]),np.array([s,s]),np.array([TCO2,TCO2]),np.array([TALK,TALK]))[0]
    HCO3 = cc.carbchem(4,-99.0,np.array([t,t]),np.array([s,s]),np.array([TCO2,TCO2]),np.array([TALK,TALK]))[0]
    CO3 = cc.carbchem(5,-99.0,np.array([t,t]),np.array([s,s]),np.array([TCO2,TCO2]),np.array([TALK,TALK]))[0]
    return H2CO3*10000.0,HCO3*10000.0,CO3*10000.0
import carbchem
import matplotlib.pyplot as plt
import numpy as np

sizing = 1000
mdi=-999.0
T = np.empty(sizing)
S = np.empty(sizing)
TCO2 = np.empty(sizing)
TALK = np.empty(sizing)
T.fill(15.0)
S.fill(32.0)
TCO2 = np.linspace(0.0016,0.0023,1000)
TALK.fill(0.0024)

co2 = carbchem.carbchem(1,mdi,T,S,TCO2,TALK)

plt.plot(co2,TCO2,'r')

TALK.fill(0.0020)

co2 = carbchem.carbchem(1,mdi,T,S,TCO2,TALK)

plt.plot(co2,TCO2,'b')
plt.xlim([200,1000])
#plt.show(block = True)
plt.savefig('/home/ph290/Documents/figures/co2_dic.pdf')



import iris
import carbchem
import iris.quickplot as qplt
import matplotlib.pyplot as plt

directory = '/home/ph290/data0/lester_geoeng/'

files = ['anfea.pp','anfeb.pp','anfec.pp','anfed.pp']

for i,file in enumerate(files):
	cube = iris.load(directory+files[i])

	aragonite_sat_state = cube[2].copy()
	aragonite_sat_state.data = carbchem.carbchem(9,cube[0].data.fill_value,cube[2].data,cube[3].data*1000+35.0,cube[0].data/(1026.*1000.),cube[1].data/(1026.*1000.))

	iris.fileformats.netcdf.save(aragonite_sat_state, directory+files[i][0:5]+'_aragonite_sat_state.nc', netcdf_format='NETCDF3_CLASSIC')
	iris.fileformats.netcdf.save(cube[2], directory+files[i][0:5]+'_sst.nc', netcdf_format='NETCDF3_CLASSIC')