importnumpyasnpfromPseudoNetCDF.camxfiles.MemmapsimportuamivimportnetCDF4fromlibtiffimportTIFFtiff=TIFF.open('d4_twn1x1.tiff',mode='r')image=tiff.read_image()towns=[int(i)foriinset(image.flatten())]towns.sort()T=['T'+str(i)foriintowns]nrow3,ncol3=image.shapezz=np.zeros(shape=(nrow3,ncol3),dtype=int)forjinrange(nrow3):zz[j,:]=np.array(image[nrow3-j-1,:],dtype=int)image=zznc=netCDF4.Dataset('20160101.ncT','r+')V=[list(filter(lambdax:nc.variables[x].ndim==j,[iforiinnc.variables]))forjin[1,2,3,4]]nt,nlay,nrow,ncol=nc.variables[V[3][0]].shapedca=np.zeros(shape=(9,nrow,ncol))forjinrange(0,nrow3,3):jj=j//3foriinrange(0,ncol3,3):ii=i//3iv=0forj1inrange(3):fori1inrange(3):dca[iv,jj,ii]=image[j+j1,i+i1]iv+=1forsinT:zz=nc.createVariable(s,"f4",('TSTEP','LAY','ROW','COL'))v=snc.variables[v].units="fraction "nc.variables[v].long_name='fraction of TOWN in code: '+s[1:]nc.variables[v].var_desc="AR fractional area per grid cell "zz=np.zeros(shape=(nrow,ncol))forvinT:nc.variables[v][0,0,:,:]=zzforsintowns:v='T'+str(s)forivinrange(9):idx=np.where(dca[iv,:,:]==s)zz=np.zeros(shape=(nrow,ncol))zz[idx]=1./9.nc.variables[v][0,0,:,:]+=zznc.NVARS=len(T)+1nc.close()