
% Drought impact in the Bolivian Altiplano agriculture associated with El Niño–Southern Oscillation using satellite imagery data
% Claudia Canedo-Rosso, Stefan Hochrainer-Stigler, Georg Pflug3, Bruno Condori, and Ronny Berndtsson

% The present script was written in MATLAB R2020a and it cointains three analyses: 
% 1. Satellite data evaluation 
% 2. Drought indices: VCI,TCI,VHI 
% 3. Stepwise regression: vegetation (as dependant variable) and climate variables (preciptiation and air temperature as independent variables)

%% 1. Satellite data evaluation
% Load data 
% Precipitation 
  % CHIRPS  
load F:\IIASA\CHIRPS\precipaltlat.mat
load F:\IIASA\CHIRPS\precipaltlon.mat
%load F:\IIASA\CHIRPS\precipalt2D.mat %from Jan-1981 to May-2017 
load F:\IIASA\CHIRPS\precip2D-v2.0.mat %from Jan-1981 to Aug-2018
load F:\IIASA\CHIRPS\precipalt.mat
%  CHIRPSppt=datetime(1981,01,01):calmonths(1):datetime(2018,8,1);
   % Gauged precipitation from January 1980 to December 2016 
load F:\IIASA\gaugedpp.mat
% gaugedppt=datetime(1980,01,01):calmonths(1):datetime(2016,12,1);
% NDVI data 
load F:\IIASA\NDVI.mat % NDVI data lat and lon. And latitude and longitude of La Paz, Oruro and Potosi 

%Crop production: crop yield from INE from 1981 to 2015  
%load F:\IIASA\cropyield.mat

%Air Surface Temperature GHCN_CAMS NOAA/OAR/ESRL PSD Kelvin (0 deg C =  273.15 deg K)
load F:\IIASA\air_Temperature\TairNOAA.mat
STlon=STlon-360;

% Observed temperature (ground) January 1980 to December 2016 
% https://www.esrl.noaa.gov/psd/data/gridded/data.UDel_AirT_Precip.html
load F:\IIASA\variables\WStemperature.mat Tmax
load F:\IIASA\variables\WStemperature.mat Tmin
load F:\IIASA\variables\WStemperature.mat templat
load F:\IIASA\variables\WStemperature.mat templon
load F:\IIASA\variables\WStemperature.mat stations

% Satellite air surface temperature from 1900 to 2017 
load F:\IIASA\ASTaltiplano.mat 
load F:\IIASA\ASTlat.mat ASTlat
load F:\IIASA\ASTlon.mat ASTlon
load F:\IIASA\ASTdate.mat ASTtime
load F:\IIASA\ASTalt.mat
ASTlon=ASTlon-360;

% ENSO El Nino Southern Oscillation: Nino3.4 anomalies 
% load F:\IIASA\ONI.mat 
% nino(19)=2;
% t=datet(405:end-37, :);
% period=datetime(t(:,1),t(:,2),01);

% 1.2 Data quality 

% Select gauged precipitation datasets with only 10% of missing values from September 1981 to August 2015
rawobservedpp65=rawobservedpp65((21:end-12-4),:); % september 1981 to august 2015 (from january 1980 to december 2016)
column=sum(isnan(rawobservedpp65))<length(rawobservedpp65)*10/100;% stations that present less than 10%of missing values 

gaugedpplat=rawobservedpp65lat(column);
gaugedpplon=rawobservedpp65lon(column); 

gaugedpp = rawobservedpp65(:,column);
stationname24=stationsname(column,:);
stationname14=stationsname(column,:);


for k=1:size(gaugedpp,2)
latx=gaugedpplat(k,1);
lonx=gaugedpplon(k,1);
latndvi=abs(precipaltlat-latx);
[~,ndvi3glat]=min(latndvi);
lonndvi=abs(precipaltlon-lonx);
[~,ndvi3glon]=min(lonndvi);
CHIRPSpp(:,k)=reshape(precipalt(ndvi3glon,ndvi3glat,:),[],1);
end
CHIRPS=CHIRPSpp(9:end-21,:);% To Sep 1981 to Aug 2015 from January 1981 to May 2017

% 1.3 Evaluation of satellite precipitation: CHIRPS 
% ------------------------------------------------------------------------
month = repmat(1:12,1,34); % 
figure
scatter(gaugedpp(:),CHIRPS(:),'.k'), xlim([0 400]), ylim([0 400])
line([0 400],[0 400],'Color','black','LineStyle','-')
figure
for k=1:size(gaugedpp,2)
   a=gaugedpp(:,k);%
   b=CHIRPS(:,k);%
   for f=1:12
   x=a(month==f);
   y=b(month==f);
   
[RHO,PVAL]  = corr(x,y,'Type','Spearman','Rows','pairwise'); 
cc(f)=RHO;
pval(f)=PVAL;

ME(f)= nanmean(y-x);%  Mean error
Rbias(f) = nansum(y-x)/nansum(x); % Relative mean error RME 
RMAE (f) = nanmean(abs(y-x))/nanmean(abs(x)); % Relative mean absolute error
RRMSE(f)= sqrt(nanmean((y-x).^2))/nanmean(x); % Relative  Root Mean Square Error
N  (f) = 1-(nansum((y-x).^2)/nansum((x-nanmean(x)).^2));% Nash-Sutcliffe efficiency coefficient

t=0.4;
    H = y >= t & x >= t; %  Hits, satellite rain and gauged pp
    F = y >= t & x < t; %  False alarms  
    M = y < t & x >= t; % Missed events 
    D = y < t & x < t;
 
 POD(f)= nansum(H)/(nansum(H)+nansum(M)); 
 FAR (f)= nansum(F)/(nansum(H)+nansum(F)); 
 
   end
   
 ccm(:,k)=cc;
 pvalm(:,k)=pval;
 MEm(:,k)=ME;
 Rbiasm(:,k)=Rbias;
 RMAEm(:,k)=RMAE;
 Nm(:,k)=N;
 RRMSEm(:,k)=RRMSE;
    
PODm(:,k)=POD;
FARm(:,k)=FAR;
 
end

% Figure 3
subplot(2,2,1)
errorbar(mean(ccm'),std(ccm')./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]), ylim([0.2 0.8]), ylabel({'r  (-)'}), xticks(1:12), xticklabels([]), box off

subplot(2,2,2)
errorbar(mean(MEm'),std(MEm')./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]),ylim([-15 15]), ylabel({'ME  (mm)'}), xticks(1:12), xticklabels([]), box off
subplot(2,2,3)
errorbar(mean(Rbiasm'*100),std(Rbiasm'*100)./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]), ylim([-79.5 50]),ylabel({'Bias  (%)'}), xticks(1:12), xticklabels({'S','O','N','D','J','F','M','A','M','J','J','A'}), box off
%xtickangle(90)
subplot(2,2,4)
errorbar(mean(RMAEm'.*100),std(RMAEm'.*100)./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]), ylabel({'MAE  (%)'}), xticks(1:12), xticklabels({'S','O','N','D','J','F','M','A','M','J','J','A'}), box off
ylim([0 110])

clear a b ans i k m D f F H t k M FAR POD PVAL cc ME N Rbias rawobservedpp65 rawobservedpp65lat rawobservedpp65lon

% 1.4 Evaluation of Temperature
% ------------------------------------------------------------------------

Tmaxr=Tmax(21:end-12-4,:);% from september 1981 to august 2015 from January 1980 to december 2016
Tminr=Tmin(21:end-12-4,:);

Tmeanr=(Tmaxr+Tminr)./2;
column=sum(isnan(Tmeanr))<length(Tmeanr)/10;% stations that present less than 10%of missing values 

Tmean = Tmeanr(:,column);
Tstations=stations(column,1);
Tmeanlat=templat(column);
Tmeanlon=templon(column);

for k=1:length(Tmeanlat)
latx=Tmeanlat(k,1);
lonx=Tmeanlon(k,1);
latndvi=abs(ASTlat-latx);
[~,temp3glat]=min(latndvi);
lonndvi=abs(ASTlon-lonx);
[~,temp3glon]=min(lonndvi);

TairS(:,k)=reshape(ASTalt(temp3glon,temp3glat,:),[],1);% ASTtime==datetime(1900,01,01):calmonths(1):datetime(2017,12,01);
end
Tair=TairS(981:1388,:); % datetime(1981,09,01):calmonths(1):datetime(2015,08,01);

month = repmat(1:12,1,34);  

clear cc ME Rbias RMAE RRMSE N

for k=1:size(Tmean,2)
   a=Tmean(:,k);%g(:,k);%gaugedppD(:,k);
   b=Tair(:,k);%s(:,k);%CHIRPSD(:,k);
   for f=1:12
   x=a(month==f);
   y=b(month==f);
 [RHO,PVAL]  = corr(x,y,'Type','Spearman','Rows','pairwise'); 
cc(f)=RHO;
pval(f)=PVAL;

ME(f)= nanmean(y-x);%  mean error
%bias(f) = nanmean(y-x); % ABSOLUTE mean error RME ***
MAE (f) = nanmean(abs(y-x)); % ABSOLUTE mean absolute error ***
Rbias(f) = nansum(y-x)/nansum(x); % relative mean error RME 
RMAE (f) = nanmean(abs(y-x))/nanmean(abs(x)); % Relative mean absolute error
N  (f) = 1-(nansum((y-x).^2)/nansum((x-nanmean(x)).^2));
RRMSE(f)= sqrt(nanmean((y-x).^2))/nanmean(x); % Relative  Root Mean Square Error

     end
 ccmt(:,k)=cc;
 pvalt(:,k)=pval;
 MEt(:,k)=ME;
 %biast(:,k)=bias;
 MAEt(:,k)= MAE;
 Rbiast(:,k)=Rbias;
 RMAEt(:,k)= RMAE;
 RRMSEt(:,k)=RRMSE;
 Nt(:,k)=N;
end
% Figure 4
figure
subplot(2,2,1)
errorbar(mean(ccmt'),std(ccmt')./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]), ylabel({'r  (-)'}), xticks(1:12), xticklabels([]), box off , ylim([0 0.81])
subplot(2,2,2)
errorbar(mean(MEt'),std(MEt')./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]), ylabel({'ME  (deg C)'}), xticks(1:12), xticklabels([]), box off, ylim([-1.2 1.2])
subplot(2,2,3)
%errorbar(mean(Rbiast'),std(Rbiast')./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
errorbar(mean(Rbiast'.*100),std(Rbiast'.*100)./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]),ylabel({'Bias  (%)'}), xticks(1:12), xticklabels({'S','O','N','D','J','F','M','A','M','J','J','A'}), box off
ylim([-20 30]);
subplot(2,2,4)
errorbar(mean(MAEt'),std(MAEt')./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
%errorbar(mean(RMAEt'.*100),std(RMAEt'.*100)./sqrt(34),'-ok','MarkerSize',4,'MarkerEdgeColor','k','MarkerFaceColor','k')
xlim([0.8 12.2]),, ylabel({'MAE  (deg C)'}), xticks(1:12), xticklabels({'S','O','N','D','J','F','M','A','M','J','J','A'}), box off
%ylim([0 1.1])
%%
% Figure 1
% Select the Tmax Tmin for the coordinates of Tmean
Tmax8 = Tmaxr(:,column);
Tmin8 = Tminr(:,column);

% Select the NDVI values for the coordinates of the gauged precip
for k=1:length(gaugedpplat)
latx=gaugedpplat(k,1);
lonx=gaugedpplon(k,1);
latndvi=abs(ndvilat-latx);
[~,ndvi3glat]=min(latndvi);
lonndvi=abs(ndvilon-lonx);
[~,ndvi3glon]=min(lonndvi);
ndvicol=(length(ndvilon)*(ndvi3glat-1)+ndvi3glon);
ndvi_pp(:,k)=ndvi2Dcorr(:,ndvicol);
end
clear ndvi3glat ndvi3glon latx lonx latndvi lonndvi
% Calculate the monthy NDVI (using the bimontlhy average)
for j=1:length(gaugedpplat)%from July 1981 to december 2015
a= ndvi_pp(1:2:length(ndvi_pp),j);
b= ndvi_pp(2:2:length(ndvi_pp),j);     
ndvipp(:,j)=nanmean([a b],2);
end 
% Filling the NDVI mising values
NDVIf1 = fillmissing(ndvipp(3:end-4,:),'nearest')/1000;% less than 10% is missing 

% Montlhy mean 
for i=1:12
meanpp(i,:)=nanmean(gaugedpp(month==i,:)); 
meanNDVI(i,:)=nanmean(NDVIf1(month==i,:)); 
end 
for i=1:12
meanTmax8(i,:)=nanmean(Tmax8(month==i,:));
meanTmin8(i,:)=nanmean(Tmin8(month==i,:));
end
figure 
subplot(1,2,1)
boxplot(meanpp','Labels',{'Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug'},'color','k','OutlierSize',3,'Symbol','ko')
ylim([-18 180])
xtickangle(90)
hold on
%plot(mean(meanCHIRPSpp'),'k')
ylabel('Precipitation (mm)','FontName','Arial','FontSize',10)% mm month^-^1
text(-1.8,205,'a)','FontName','Arial','FontSize',10)
set(gca,'FontName','Arial','FontSize',10)
yyaxis right
plot(mean(meanTmax8'),'.k-'), ylim([-6.5 35])
plot(mean(meanTmin8'),'.k-')
ylabel('Temperature (deg C)')
set(gca,'yColor','k')
box off
subplot(1,2,2)
boxplot(meanNDVI','Labels',{'Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug'},'color','k','OutlierSize',3,'Symbol','ko')
ylabel('NDVI [-]','FontName','Arial','FontSize',10)
text(-1,1.06,'b)','FontName','Arial','FontSize',10)
set(gca,'FontName','Arial','FontSize',10)
xtickangle(90)
box off 

%Figure 2 
for m=1:12:size(gaugedpp,1)
for n=12:12:size(gaugedpp,1)
       ppaccum((m:n),:)= cumsum(gaugedpp((m:n),:)); 
end 
end
%% 2. Drought indices: VCI,TCI,VHI 
% from september 1981 to august 2015  
% Load data 
load  F:\IIASA\crop_coord.mat
load  F:\IIASA\NDVI.mat % Jul 1981 - dec 2015 
load F:\IIASA\NDVI\ndviallper.mat
load  F:\IIASA\cropyield.mat
load F:\IIASA\final\newfinal\LST\LST.mat % GLDAS_NOAH025
crop_lat(47)=[]; % Lake Titicaca, NaN values, water
crop_lon(47)=[]; % Lake Titicaca, NaN values, water
ndviall=double(ndviallper);
% Select the NDVI values based on the coordinates of Agricultural Land Use
for k=1:length(crop_lat)
latx=crop_lat(k,1);
lonx=crop_lon(k,1);
latndvi=abs(ndvilat-latx);
[~,ndvi3glat]=min(latndvi);
lonndvi=abs(ndvilon-lonx);
[~,ndvi3glon]=min(lonndvi);
ndvicol=(length(ndvilon)*(ndvi3glat-1)+ndvi3glon);
ndvi_crop(:,k)=ndvi2Dcorr(:,ndvicol);
end
clear ndvi3glat ndvi3glon latx lonx latndvi lonndvi
% Calculate the monthy NDVI (using the bimontlhy average)
for j=1:length(crop_lat)%from July 1981 to december 2015
a= ndvi_crop(1:2:length(ndvi_crop),j);
b= ndvi_crop(2:2:length(ndvi_crop),j);     
ndvi(:,j)=nanmean([a b],2);
end 
% Filling the NDVI mising values
NDVI = fillmissing(ndvi(3:end-4,:),'nearest')/1000;% less than 10% is missing 

% VCI 
% ---------------------------------------------------------------------
% VCI= (NDVIi - NDVImin)/(NDVImax - NDVImin)*100 
month = repmat(1:12,1,34);
x=NDVI; % from sep 1981 to aug 2015 

for f=1:size(NDVI,2)
for i=1:12
y=x(month==i,f); % from september to april (agriculture period)
VCIm(month==i,f)=(y-min(y))/(max(y)-min(y))*100;
end
end

% TCI
% --------------------------------------------------------------------------
for k=1:length(crop_lat)
latx=crop_lat(k,1);
lonx=crop_lon(k,1);
latndvi=abs(LSTlat-latx);
[~,ndvi3glat]=min(latndvi);
lonndvi=abs(LSTlon-lonx);
[~,ndvi3glon]=min(lonndvi);
LST_crop(:,k)=reshape(LST(ndvi3glon,ndvi3glat,:),[],1);
end

clear LST
LST=LST_crop(12+9:end-4,:); % September 1981 to August 2015 (from Jan 1980 to Dec 2015)
month = repmat(1:12,1,34);

for f=1:length(crop_lat)
for i=1:12
y=LST(month==i,f); % from september to april (agriculture period)
TCIm(month==i,f)=(max(y)-y)/(max(y)-min(y))*100;
end
end
clear i y absmin absmax x y 

% VHI 
% -------------------------------------------------------------------------
VHIm = (0.5 .* VCIm) +((1-0.5).*TCIm);

for f=1:12 % september to august
i=VCIm(f:12:end,:);
VCImeanm(f,:)=mean(i');
ii=TCIm(f:12:end,:);
TCImeanm(f,:)=mean(ii');
iii= VHIm(f:12:end,:);
VHImeanm(f,:)=mean(iii');
end
clear x i ii iii a b f y j k latx lonx ndvi3glon ndvi3glat ndvicol

figure
x=VCImeanm;
plot(1981:2014, min(x(3:8,:)),'k-')
hold on
Nov=plot(1981:2014, x(3,:),'ko','MarkerFaceColor','w')
Dec=plot(1981:2014, x(4,:),'ko','MarkerFaceColor','k')
Jan=plot(1981:2014, x(5,:),'ks','MarkerFaceColor','w')
Feb=plot(1981:2014, x(6,:),'ks','MarkerFaceColor','k')
Mar=plot(1981:2014, x(7,:),'k^','MarkerFaceColor','w')
Apr=plot(1981:2014, x(8,:),'k^','MarkerFaceColor','k')
line([1980 2015],[40 40],'Color','black','LineStyle','--')
xticks([1981:4:2014])
xticklabels({'1981-82','1985-86','1989-90','1993-94','1997-98','2001-02','2005-06','2009-10','2013-14'})
box off
legend([Nov Dec Jan Feb Mar Apr],'Nov','Dec','Jan','Feb','Mar','Apr','EdgeColor','none') % 'Orientation','horizontal','location','eastoutside')


figure
x=TCImeanm;
plot(1981:2014, min(x(3:8,:)),'k-')
hold on
Nov=plot(1981:2014, x(3,:),'ko','MarkerFaceColor','w')
Dec=plot(1981:2014, x(4,:),'ko','MarkerFaceColor','k')
Jan=plot(1981:2014, x(5,:),'ks','MarkerFaceColor','w')
Feb=plot(1981:2014, x(6,:),'ks','MarkerFaceColor','k')
Mar=plot(1981:2014, x(7,:),'k^','MarkerFaceColor','w')
Apr=plot(1981:2014, x(8,:),'k^','MarkerFaceColor','k')
line([1980 2015],[40 40],'Color','black','LineStyle','--')
box off
xticks([1981:4:2014])
xticklabels({'1981-82','1985-86','1989-90','1993-94','1997-98','2001-02','2005-06','2009-10','2013-14'})
legend([Nov Dec Jan Feb Mar Apr],'Nov','Dec','Jan','Feb','Mar','Apr','EdgeColor','none')

figure
x=VHImeanm;
plot(1981:2014, min(x(3:8,:)),'k-')
hold on
Nov=plot(1981:2014, x(3,:),'ko','MarkerFaceColor','w')
Dec=plot(1981:2014, x(4,:),'ko','MarkerFaceColor','k')
Jan=plot(1981:2014, x(5,:),'ks','MarkerFaceColor','w')
Feb=plot(1981:2014, x(6,:),'ks','MarkerFaceColor','k')
Mar=plot(1981:2014, x(7,:),'k^','MarkerFaceColor','w')
Apr=plot(1981:2014, x(8,:),'k^','MarkerFaceColor','k')
line([1980 2015],[40 40],'Color','black','LineStyle','--')
xticks([1981:4:2014])
xticklabels({'1981-82','1985-86','1989-90','1993-94','1997-98','2001-02','2005-06','2009-10','2013-14'})
box off
legend([Nov Dec Jan Feb Mar Apr],'Nov','Dec','Jan','Feb','Mar','Apr','EdgeColor','none')

%% 3 Stepwise regression: vegetation (dependant variable) and climate variables (preciptiation and temperature, independent variables)
% Load data: Same datasets used for step 1 and 2 

% Three months stepwise linear regression model 
% NDVI = b0 + b1 PRECIPITATION

seasonal=repmat(1:3,1,34); 
month = repmat(1:12,1,34); 
crop_lat(47)=[]; % Lake Titicaca, NaN values 
crop_lon(47)=[]; % Lake Titicaca, NaN values
crop_lat(end)=[]; 
crop_lon(end)=[];

for k=1:size(crop_lat,1)
latx=crop_lat(k,1);
lonx=crop_lon(k,1);
latndvi=abs(precipaltlat-latx);
[~,ndvi3glat]=min(latndvi);
lonndvi=abs(precipaltlon-lonx);
[~,ndvi3glon]=min(lonndvi);
CHIRPSc(:,k)=reshape(precipalt(ndvi3glon,ndvi3glat,:),[],1);

%col=(length(precipaltlon)*(ndvi3glat-1)+ndvi3glon);
%CHIRPSpp(:,k)=precip2D(:,col); 
end
CHIRPScrop=CHIRPSc(9:end-12-9,:);% Sep-1981 to Aug-2015, from Jan-1981 to May-2017
for m=1:12:size(CHIRPScrop,1)
for n=12:12:size(CHIRPScrop,1)
        CHIRPScumpp((m:n),:)= cumsum(CHIRPScrop((m:n),:));
end 
end

clear ndvi3glat ndvi3glon
% Air temperature satellite data within the land use area 
for k=1:size(crop_lat,1)
latx=crop_lat(k,1);
lonx=crop_lon(k,1);
latndvi=abs(ASTlat-latx);
[~,ndvi3glat]=min(latndvi);
lonndvi=abs(ASTlon-lonx);
[~,ndvi3glon]=min(lonndvi);
AirTcrop(:,k)=reshape(ASTalt(ndvi3glon,ndvi3glat,981:1388),[],1); % from sep 1981- aug 2015 
end

% Time series
season =repmat(1:4,3,408/12);
season=season(:);
year=repmat(1:12,1,34);
% 7 series of NDVI, 7 series precipitation, and 7 series of temperature
% 1 SON, 2 OND, 3 NDJ, 4 DJF, 5 JFM, 6 FMA, 7 MAM
for i= 1:12
NDVIy{i}= NDVI(i:12:end,:);
CHIRPSy{i} = CHIRPScumpp(i:12:end,:);
Tairy{i}=AirTcrop(i:12:end,:);
end

for i=1:7
y1(1:3:102,:) = NDVIy{1,i};
y1(2:3:102,:) = NDVIy{1,i+1};
y1(3:3:102,:) = NDVIy{1,i+2};
y{i}=y1;
end

for i=1:7
x1a(1:3:102,:) = CHIRPSy{1,i};
x1a(2:3:102,:) = CHIRPSy{1,i+1};
x1a(3:3:102,:) = CHIRPSy{1,i+2};
x1{i}=x1a;
end

for i=1:7
x2a(1:3:102,:) = Tairy{1,i};
x2a(2:3:102,:) = Tairy{1,i+1};
x2a(3:3:102,:) = Tairy{1,i+2};
x2{i}=x2a;
end
clear y1 x1a x2a 
% Standardizing time series 
%----------------------------------------------------------------	
[nt,ny] = size(y{1,1});
[nt,nx1] = size(x1{1,1});
for i=1:7 
    y1=y{1,i};
    x1a=x1{1,i};
    x2a=x2{1,i};
    for k=1:606   
        y2(:,k) = y1(:,k) - ones(nt,1)*mean(y1(:,k));% extract mean on y
        y2(:,k) = y2(:,k) ./(ones(nt,1)*std(y2(:,k)));% divide by std
        
        x1b(:,k) = x1a(:,k) - ones(nt,1)*mean(x1a(:,k));% extract mean on z
        x1b(:,k) = x1b(:,k) ./(ones(nt,1)*std(x1b(:,k)));% divide by std
        
        x2b(:,k) = x2a(:,k) - ones(nt,1)*mean(x2a(:,k));% extract mean on z
        x2b(:,k) = x2b(:,k) ./(ones(nt,1)*std(x2b(:,k)));% divide by std
    end 
    yS{1,i}=y2;
    x1S{1,i}=x1b;
    x2S{1,i}=x2b;
end
clear y1 y2 x1a x1b y1a y1b x2a x2b

% Regression 3 months period 
%--------------------------------------------------------------------------

% NDVI = Precip
% yS is the standardize NDVI for: 1 SON 2 OND 3 NDJ 4 DJF 5 JFM 6 FMA 7 MAM
% x1S is the standardize CHIRPS for the same three months period
% x2S is the stardardize air Temperature for the same three months period
z=7; % for z=1:7; % change  from 1 to 7 
    for b=z:7
    yR=yS{1,b}; % NDVI (1 SON 2 OND 3 NDJ 4 DJF 5 JFM 6 FMA 7 MAM)
    x1R=x1S{1,z}; % CHIRPS 
    % x2R=x2S{1,1}; % Tair  
for i=1:606      
mdl3m1{1,i} = stepwiselm(x1R(:,i),yR(:,i),'PEnter',0.06);
mdl{1,b}= mdl3m1;
xvar3m1{1,i}=mdl3m1{1,i}.Coefficients.Properties.RowNames{end};
xvar{1,b}=xvar3m1;
end
    end  

for b=z:7
    for i=1:606  
if size(mdl{1,b}{1,i}.Coefficients.SE,1)==2;
    %xvar(i,b)=mdl{1,b}{1,i}.Coefficients.Properties.RowNames{end};
    xR2(i,b)=mdl{1,b}{1,i}.Rsquared.Ordinary;
    xpval(i,b) = mdl{1,b}{1,i}.Coefficients.pValue(2);
    xSE(i,b) =mdl{1,b}{1,i}.Coefficients.SE(2);
    xcoeff(i,b)=mdl{1,b}{1,i}.Coefficients.Estimate(2);
else             
    xR2(i,b)=NaN; 
    xpval(i,b)=NaN; 
    xSE(i,b)=NaN;
    xcoeff(i,b)=NaN;
    
end    
end
    end

    
% save regressionmonths.mat mdl xvar xR2 xpal xSE

% Regression NDVI = Precip + Tair
% -------------------------------------------------------------------------

z=6; % from z=1:7;% change from 1 to 7 
    for b=z:7
    yR=yS{1,b}; % NDVI (1 SON 2 OND 3 NDJ 4 DJF 5 JFM 6 FMA 7 MAM)
    x1R=x1S{1,z}; % CHIRPS 
    x2R=x2S{1,z}; % Tair  
for i=1:606      
mdl3m1{1,i} = stepwiselm([x1R(:,i), x2R(:,i)],yR(:,i),'PEnter',0.06);
mdl{1,b}= mdl3m1;
xvar3m1{1,i}=mdl3m1{1,i}.Coefficients.Properties.RowNames{end};
xvar{1,b}=xvar3m1;
end
    end  
%
% mdl=mdlOND
% z=2
for b=z:7
    for i=1:606  
if size(mdl{1,b}{1,i}.Coefficients.SE,1)>=3; % x1 (CHIRPS) and x2 (Tair)
    %xvar(i,b)=mdl{1,b}{1,i}.Coefficients.Properties.RowNames{end};
    xR2(i,b)=mdl{1,b}{1,i}.Rsquared.Ordinary;
    xSE(i,b) =mdl{1,b}{1,i}.Coefficients.SE(3);
    xcoeffpp(i,b)=mdl{1,b}{1,i}.Coefficients.Estimate(2);
    xcoeffTair(i,b)=mdl{1,b}{1,i}.Coefficients.Estimate(3);
    xpvalpp(i,b) = mdl{1,b}{1,i}.Coefficients.pValue(2);
    xpvalTair(i,b) = mdl{1,b}{1,i}.Coefficients.pValue(3);
elseif  sum(mdl{1,b}{1,i}.CoefficientNames{end}=='1')==1% x1 (CHIRPS) 
    %xvar(i,b)=mdl{1,b}{1,i}.Coefficients.Properties.RowNames{end};
    xR2(i,b)=mdl{1,b}{1,i}.Rsquared.Ordinary;
    xSE(i,b) =mdl{1,b}{1,i}.Coefficients.SE(2);
    xcoeffpp(i,b)=mdl{1,b}{1,i}.Coefficients.Estimate(2);
    xpvalpp(i,b) = mdl{1,b}{1,i}.Coefficients.pValue(2);
    xcoeffTair(i,b)=NaN;
    xpvalTair(i,b) = NaN;
elseif    sum(mdl{1,b}{1,i}.CoefficientNames{end}=='2')==1 % x2 (Tair)
    xR2(i,b)=mdl{1,b}{1,i}.Rsquared.Ordinary;
    xSE(i,b) =mdl{1,b}{1,i}.Coefficients.SE(2);
    xcoeffTair(i,b)=mdl{1,b}{1,i}.Coefficients.Estimate(2);
    xpvalTair(i,b) = mdl{1,b}{1,i}.Coefficients.pValue(2);
    xcoeffpp(i,b)=NaN;
    xpvalpp(i,b) = NaN;
else
    xR2(i,b)=NaN; 
    xSE(i,b)=NaN;
    xcoeffpp(i,b)=NaN;
    xpvalpp(i,b)=NaN; 
    xcoeffTair(i,b)=NaN;
    xpvalTair(i,b)=NaN;
end    
    end
end

