Changeset 1782 in lmdz_wrf


Ignore:
Timestamp:
Feb 26, 2018, 6:33:54 PM (7 years ago)
Author:
lfita
Message:

New version for matrix reconstruction taking as reference vector values

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/ORforcing_reconstruct.py

    r1750 r1782  
    1515
    1616parser = OptionParser()
     17parser.add_option("-F", "--filename", dest="fn", help="name of files (overwrites -f option)", \
     18  metavar="VALUE")
    1719parser.add_option("-f", "--fileHEader", dest="fh", help="header of files",           \
    1820  metavar="VALUE")
     21parser.add_option("-i", "--indices", dest="indn", help="name of the variable indices", \
     22  metavar="VALUE")
    1923parser.add_option("-L", "--latitude", dest="latn", help="name of the variable latitiude", \
    2024  metavar="VALUE")
    2125parser.add_option("-l", "--longitude", dest="lonn", help="name of the variable longitiude", \
    2226  metavar="VALUE")
     27parser.add_option("-t", "--TransposeVariables", dest="tvars", help="whether variables should be trasposed", \
     28  metavar="VALUE")
    2329parser.add_option("-v", "--Variables", dest="varns", help="',' separated list of variables", \
    2430  metavar="VALUE")
     
    3036####### ###### ##### #### ### ## #
    3137
    32 filen = opts.fh + opts.year + '.nc'
     38if opts.fn is None:
     39    filen = opts.fh + opts.year + '.nc'
     40else:
     41    filen = opts.fn
    3342
    3443# Variable whcih provides the indices of a 1D vector from the dimy, dimx space
    35 indvar = 'land'
     44indvar = opts.indn
    3645
    3746# 2D longitude, latitude matrices
     
    4150# Range to retrieve
    4251Xmin=-90.25
    43 #Xmin='all'
     52Xmin='all'
    4453Xmax=-33.25
    4554Ymin=-67.25
     
    91100latv = olat[:]
    92101
    93 vecdimn = oind.dimensions[0]
    94102if len(olon.dimensions) == 2:
     103    dimx = lonv.shape[1]
     104    dimy = lonv.shape[0]
     105    veclon = lonv.reshape(dimx*dimy)
     106    veclat = latv.reshape(dimx*dimy)
    95107    Xdimn = olon.dimensions[1]
    96108    Ydimn = olon.dimensions[0]
    97     dimx = lonv.shape[1]
    98     dimy = lonv.shape[0]
    99 elif len(olon.dimensions) == 1:
    100     Xdimn = olon.dimensions[0]
    101     Ydimn = olat.dimensions[0]
    102     dimx = lonv.shape[0]
    103     dimy = latv.shape[0]
    104     lonv, latv = np.meshgrid(lonv, latv)
    105 
    106 # Fortran indices, first 1
    107 indv = indv - 1
    108 
    109 veclon = np.zeros((len(indv)), dtype=np.float)
    110 veclat = np.zeros((len(indv)), dtype=np.float)
    111 
    112 # Construct veclon, veclat
    113 for iid in range(len(indv)):
    114     iy = int((indv[iid]-1)/dimx)
    115     ix = int(indv[iid] - iy*dimx - 1)
    116     veclon[iid] = lonv[iy,ix]
    117     veclat[iid] = latv[iy,ix]
     109else:
     110    veclon = lonv.copy()
     111    veclat = latv.copy()
     112    Xdimn = 'x'
     113    Ydimn = 'y'
     114
     115vecdimn = oind.dimensions[0]
    118116
    119117if not gen.searchInlist(availProj, matProj):
     
    157155    dimy = int((Ymax - Ymin+resY)/resY)
    158156
    159 matindt, matXt, matYt = Sci.module_scientific.reconstruct_matrix(vectorxpos=veclon,  \
    160   vectorypos=veclat, dvec=veclon.shape[0], xmin=Xmin, xmax=Xmax, ymin=Ymin,ymax=Ymax,\
    161   dmatx=dimx, dmaty=dimy, matproj=matProj, maxdiff=maxdiff)
     157print 'Xmin:', Xmin, 'Xmax:', Xmax, 'Ymin:', Ymin, 'Ymax:', Ymax, 'maxdiff:', maxdiff
     158
     159matindt, matXt, matYt, matdifft = Sci.module_scientific.reconstruct_matrix(          \
     160  vectorxpos=veclon, vectorypos=veclat, dvec=veclon.shape[0], xmin=Xmin, xmax=Xmax,  \
     161  ymin=Ymin,ymax=Ymax, dmatx=dimx, dmaty=dimy, matproj=matProj, maxdiff=maxdiff)
    162162
    163163matind = matindt.transpose()
     164Nfound = np.sum(matind != -1)
     165Nstations = veclon.shape[0]
     166print '  Nfound:', Nfound, ' number of stations:', Nstations
     167
     168if Nfound*1. / Nstations < 0.8:
     169    print gen.errormsg
     170    print '  '+main + ': only ', '{:.2f}'.format(Nfound*100./Nstations),\
     171      '% of points ' + 'have been found !!'
     172    print '    this is not enough. Something must went wrong!'
     173    print '    Longitudes Latitudes _______'
     174    for i in range(veclon.shape[0]):
     175        print '    ', veclon[i], veclat[i]
     176    dx2 = dimx/2
     177    dy2 = dimy/2
     178    print '    dx2, dy2 -/+ 5 fraction of destiny longitudes _______'
     179    for j in range(-5,5):
     180        print matXt[dx2-5:dx2+5,dy2+j]
     181    print '    dx2, dy2 -/+ 5 fraction of destiny latitudes _______'
     182    for j in range(-5,5):
     183        print matYt[dx2-5:dx2+5,dy2+j]
     184    print '    dx2, dy2 -/+ 5 fraction of indices equivalency _______'
     185    for j in range(-5,5):
     186        print matindt[dx2-5:dx2+5,dy2+j]
     187    print '     min distance lon(dy2,dx2)=', matXt[dx2,dy2], ':',                    \
     188      np.min(veclon - matXt[dx2,dy2])
     189    print '     min distance lat(dy2,dx2)=', matYt[dx2,dy2], ':',                    \
     190      np.min(veclat - matYt[dx2,dy2])
     191    print '     longitude borders:', Xmin, Xmax, 'dX:', resX
     192    print '     latitude borders:', Ymin, Ymax, 'dY:', resY
     193    #quit(-1)
     194
    164195# Fortran like, First 1
    165196matind = np.where(matind != -1, matind - 1, matind)
     
    189220ncvar.set_attribute(newvar, 'coordinates', 'lon lat')
    190221
     222# Variable differences
     223newvar = onewnc.createVariable('vec1D_matdiff', 'i', ('y', 'x'), fill_value=-1)
     224newvar[:] = matdifft.transpose()
     225ncvar.basicvardef(newvar,'vec1D_matdiff', 'matrix differences respect 1D ', 'degrees')
     226ncvar.set_attribute(newvar, 'coordinates', 'lon lat')
     227
    191228# Looking for equivalencies in the 1D vector
    192229matlonlat = matind.copy()
     
    207244    if not onewnc.variables.has_key(vn):
    208245        ovar = onc.variables[vn]
    209         indn = ovar.dimensions
     246        if gen.Str_Bool(opts.tvars):
     247            indn0 = ovar.dimensions
     248            indn = list(indn0)[::-1]
     249        else:
     250            indn = ovar.dimensions
    210251        vardims = []
    211252        shapevar = []
     
    252293            quit(-1)
    253294
    254         print '  reconstructing:', vn, '...'
     295        print '  reconstructing:', vn, ' shape:', newvar.shape, '...'
    255296        # Filling variable. It would be faster if we can avoid this loop... I'm feeling lazy!
    256297        if not gen.searchInlist(vardims,'x') and not gen.searchInlist(vardims,'y'):
    257             newvar[:] = ovar[:]
     298            if gen.Str_Bool(opts.tvars):
     299                newvar[:] = ovar[:].transpose()
     300            else:
     301                newvar[:] = ovar[:]
    258302        else:
    259             ovart = ovar[:].transpose()
     303            if gen.Str_Bool(opts.tvars):
     304                ovart = ovar[:]
     305            else:
     306                ovart = ovar[:].transpose()
     307            print '  Lluis shapes ovart:', ovart.shape, 'newvar:', newvar.shape
    260308            if newvar.dtype == type(float(2.)) or newvar.dtype == type(np.float(2.)) \
    261309              or newvar.dtype == type(np.float32(2)) or                              \
     
    280328# Global attributes
    281329for atn in onc.ncattrs():
    282     atv = ovar.getncattr(atn)
     330    atv = onc.getncattr(atn)
    283331    ncvar.set_attribute(onewnc, atn, atv)
    284332onewnc.sync()
     
    287335
    288336# Reconstructing times
    289 otime = onewnc.variables['time']
    290 ncvar.set_attribute(otime, 'units', 'seconds since ' + opts.year + '-01-01 00:00:00')
     337#otime = onewnc.variables['time']
     338#ncvar.set_attribute(otime, 'units', 'seconds since ' + opts.year + '-01-01 00:00:00')
    291339
    292340onewnc.sync()
  • trunk/tools/module_scientific.f90

    r1747 r1782  
    127127
    128128  SUBROUTINE reconstruct_matrix(vectorXpos, vectorYpos, dvec, Xmin, Xmax, Ymin, Ymax, dmatx, dmaty,   &
    129     matProj, maxdiff, matind, matX, matY)
     129    matProj, maxdiff, matind, matX, matY, matdiff)
    130130! Subroutine to reconstruct a 2D matrix from a pair of syncronized vectors with the positions on x
    131131!   and y coordinates
     
    138138    CHARACTER(len=50), INTENT(in)                        :: matPRoj
    139139    INTEGER, DIMENSION(dmatx, dmaty), INTENT(out)        :: matind
    140     REAL(r_k), DIMENSION(dmatx, dmaty), INTENT(out)      :: matX, matY
     140    REAL(r_k), DIMENSION(dmatx, dmaty), INTENT(out)      :: matX, matY, matdiff
    141141
    142142! Local
    143     INTEGER                                              :: i,j, idiff, jdiff
     143    INTEGER                                              :: i,j,iv, idiff, jdiff
    144144    REAL(r_k)                                            :: ddx, ddy, Xpos, Ypos, mindiff
    145     REAL(r_k), DIMENSION(dvec)                           :: diff
    146     INTEGER, DIMENSION(1)                                :: mindiffloc
     145    REAL(r_k), DIMENSION(dmatx,dmaty)                    :: diff
     146    REAL(r_k)                                            :: nXpos, xXpos, nYpos, xYpos
     147    INTEGER, DIMENSION(2)                                :: mindiffloc
    147148    CHARACTER(LEN=50)                                    :: RSa, RSb
    148149
     
    157158! matind: matrix with the correspondant indiced from the vector of positions
    158159! matX, matY: matrix with the coordinates of the elements of the matrix
     160! matdiff: matrix with the differences at each grid point
    159161
    160162    fname = 'reconstruct_matrix'
    161163
    162     matind = zeroRK
     164    matind = -oneRK
     165    matdiff = -oneRK
     166
     167    nXpos = MINVAL(vectorXpos)
     168    xXpos = MAXVAL(vectorXpos)
     169    nYpos = MINVAL(vectorYpos)
     170    xYpos = MAXVAL(vectorYpos)
     171    PRINT *, 'Limits of the positions to localize in a matrix: longitudes:', nXpos,  &
     172     ' ,',xXpos, ' latitudes:', nYpos, ' ,', xYpos
    163173
    164174    Projection: SELECT CASE(TRIM(matProj))
     
    176186          matX(i,j) = Xpos
    177187          matY(i,j) = Ypos
    178 
    179           diff = SQRT((Xpos - vectorXpos)**2 + (Ypos - vectorYpos)**2)
    180           mindiffloc = MINLOC(diff)
    181           mindiff = MINVAL(diff)
    182           IF (mindiff > maxdiff) THEN
    183             !Assuming no values
    184             matind(i,j) = -1
    185             !WRITE(RSa, '(f20.10)')mindiff
    186             !WRITE(RSb, '(f20.10)')maxdiff
    187             !msg = 'Difference: ' // TRIM(RSa) // ' overpasses the maximum authorized distance: ' //   &
    188             !  TRIM(RSb)
    189             !CALL ErrMsg(msg, fname, -1)
    190           ELSE
    191             matind(i,j) = mindiffloc(1)
    192           END IF
    193 
    194188        END DO
    195189      END DO
     
    200194      CALL ErrMsg(msg, fname, -1)
    201195    END SELECT Projection
     196
     197    ! Let's do it properly...
     198    DO iv=1,dvec
     199      diff = SQRT((matX - vectorXpos(iv))**2 + (matY - vectorYpos(iv))**2)
     200      mindiffloc = MINLOC(diff)
     201      mindiff = MINVAL(diff)
     202      IF (mindiff > maxdiff) THEN
     203        PRINT *,'  vectorXpos:', vectorXpos(iv), 'vectorYpos:', vectorYpos(iv)
     204        !PRINT *,'  Xpos:', Xpos, 'Ypos:', Ypos
     205        WRITE(RSa, '(f20.10)')mindiff
     206        WRITE(RSb, '(f20.10)')maxdiff
     207        msg = 'Difference: ' // TRIM(RSa) // ' overpasses the maximum authorized distance: ' //   &
     208          TRIM(RSb)
     209        CALL ErrMsg(msg, fname, -1)
     210      ELSE
     211        i = mindiffloc(1)
     212        j = mindiffloc(2)
     213        matind(i,j) = iv
     214        matdiff(i,j) = mindiff
     215      END IF
     216    END DO
     217
     218    RETURN
    202219
    203220  END SUBROUTINE reconstruct_matrix
Note: See TracChangeset for help on using the changeset viewer.