
% Different options when computing SOMs

% TROPICAL OCEAN ONLY
%fln='output_phyda_djf_tropical_som8_yrs10001925_31-Dec-2019_13:57:39.mat';
%fln='output_phyda_djf_tropical_som16_yrs10001925_31-Dec-2019_13:57:00.mat';
%fln='output_phyda_djf_tropical_som12_yrs10001925_31-Dec-2019_14:10:00.mat';
%fln='output_phyda_djf_tropical_som6_yrs10001925_31-Dec-2019_14:09:07.mat';


%fln='output_phyda_djf_tropicalPlus_som9_yrs10001925_03-Jan-2020_11:20:52.mat';
%fln='output_phyda_djf_tropicalPlus_som8_yrs10001925_03-Jan-2020_11:38:24.mat';
fln='output_phyda_djf_tropicalPlus_som12_yrs10001925_06-Jan-2020_16:46:20.mat';
%fln='output_phyda_djf_tropicalPlus_som6_yrs10001925_06-Jan-2020_16:45:25.mat';


fln0=fln;
%load(['./output_som/' fln])
load([fln])

%---------------------------
%      PLOT PATTERNS
%---------------------------

%inputf='cesm_latlon.nc';

% define the output variable
outputf=['soms_tropicalPlus_sst_' fln0(1:end-13) '.nc'];
%outputf=['soms_sst_pdsi_' fln0(1:end-13) '_matlabtest.nc'];
%outputf='test_output.nc';inputf='ccsm4_latlon.nc';
% grab lat/lon from model, put it into the output file
%eval(['!ncks -A -v lat,lon ',inputf,' ',outputf]);

% Add time dimension
nccreate(outputf,'time','Dimensions',{'time',length(analyrs0)});
ncwrite(outputf,'time',analyrs0);
ncwriteatt(outputf,'time','units','Annual mean starting from April to the next calendar year March');
ncwriteatt(outputf,'time','long_name','Years CE');

nccreate(outputf,'lat','Dimensions',{'lat',length(lat(itlat))});
ncwrite(outputf,'lat',lat(itlat));
ncwriteatt(outputf,'lat','units','degrees_north');
ncwriteatt(outputf,'lat','long_name','latitude');

nccreate(outputf,'lon','Dimensions',{'lon',length(lon(itlon))});
ncwrite(outputf,'lon',lon(itlon));
ncwriteatt(outputf,'lon','units','degrees_east');
ncwriteatt(outputf,'lon','long_name','longitude');

nccreate(outputf,'bmus','Dimensions',{'time',length(analyrs0)});
ncwrite(outputf,'bmus',bmus);
ncwriteatt(outputf,'bmus','long_name','Best matching units');
ncwriteatt(outputf,'bmus','units','SOM node number');



for i=1:somRows*somCols

   tmp_ptrn=permute(reshape(ptrns(i,:),length(itlat),length(itlon)),[2 1]);
   tmp_ptrn(tmp_ptrn==NaN)=1e20;
   pnm=['tmp_ptrn_' num2str(i)];
   
   nccreate(outputf,pnm,'Dimensions',{'lon',length(itlon),'lat',length(itlat)},'FillValue',1e20);
   ncwrite(outputf,pnm,tmp_ptrn);
   ncwriteatt(outputf,pnm,'missing_value',1e20);

end

% Add note about what kind of SOM map it is
eval(['!ncatted -O --glb_att_add note="SOM rows = ' num2str(somRows) ', SOM columns = ' num2str(somCols) '" ' outputf]);
 

 

