RoutingPreProc.py 7.13 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#
#
#
import numpy as np
import os, sys
import pickle
from mpi4py import MPI
import gc
#
import matplotlib as mpl
mpl.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
14
import time
15 16 17 18
#
# Gert the information from the configuration file.
#
import configparser
19
config=configparser.ConfigParser({'SaveWeights':'true', "DiagLon":"0.0, 0.0", "DiagLat":"0.0, 0.0", "numop" : 100})
20 21 22
config.read("run.def")
saveweights=config.get("OverAll", "SaveWeights")
nbasmax=int(config.getfloat("OverAll", "nbasmax"))
23
numop=int(config.getfloat("OverAll", "numop"))
24 25 26 27
OutGraphFile=config.get("OverAll","GraphFile")
lonint=np.array(config.get("OverAll", "DiagLon").split(","),dtype=float)
latint=np.array(config.get("OverAll", "DiagLat").split(","),dtype=float)
#
28 29
EarthRadius=config.getfloat("OverAll", "EarthRadius")
#
30 31 32 33 34 35
import ModelGrid as MG
import Partition as PA
import RPPtools as RPP
import HydroGrid as HG
import diagplots as DP
import Interface as IF
36
from Truncate import trunc as TR
37
from spherical_geometry import vector
38 39 40 41 42 43 44 45 46 47 48 49 50 51
#
# Logging in MPI : https://groups.google.com/forum/#!topic/mpi4py/SaNzc8bdj6U
#
import getargs
log_master, log_world = getargs.getLogger()
INFO, DEBUG, ERROR = log_master.info, log_master.debug, log_world.error
INFO_ALL, DEBUG_ALL = log_world.info, log_world.debug
#
# Read full grid and partition the domain.
#
gg = MG.GlobalGrid()
#
comm = MPI.COMM_WORLD
szhalo=1
52
nbcore=comm.Get_size()
53 54
rank=comm.Get_rank()
#
55 56 57 58 59 60 61 62
# Verify directories
#
wdir="Weights"
if rank == 0 :
    if not os.path.exists(wdir) :
        os.mkdir(wdir)
comm.Barrier()
#
63 64
# Region of grid to be treated
#
65
part = PA.partition(gg.ni, gg.nj, gg.land, comm, nbcore, szhalo, rank)
66 67 68 69 70 71 72 73 74 75
#
# Weight file to be created
#
wfile=os.path.basename(config.get("OverAll", "ModelGridFile").replace(".","_"))+"_i"+str(part.istart).zfill(4)+"di"+str(part.ni).zfill(4)+"j"+str(part.jstart).zfill(4)+"dj"+str(part.nj).zfill(4)
#
#
modelgrid=MG.ModelGrid(part.ihstart+gg.igstart,part.nih,part.jhstart+gg.jgstart,part.njh)
INFO("Longitude interval on proc "+str(rank)+" = "+str(modelgrid.box_land[0][0])+" : "+str(modelgrid.box_land[0][1]))
INFO("Latitude interval on proc "+str(rank)+" = "+str(modelgrid.box_land[1][0])+" : "+str(modelgrid.box_land[1][1]))

76
print("modelgrid.box_land",modelgrid.box_land)
77 78 79 80 81 82 83 84 85 86
hydrogrid=HG.HydroGrid(modelgrid.box_land)

icell = 0
sub_index = []
sub_area = []
sub_lon = []
sub_lat = []
#
# Only compute the weights if the file does not exist.
#
87

88 89
if not os.path.exists(wdir+"/"+wfile) :
    INFO("Computing weights")
90
    for cell, center, radius, area in zip(modelgrid.polylist, modelgrid.centers, modelgrid.radius, modelgrid.area) :
91 92
        llinside=vector.vector_to_lonlat(cell.polygons[0].inside[0],cell.polygons[0].inside[1],cell.polygons[0].inside[2])
        area_in=np.zeros((hydrogrid.jjm,hydrogrid.iim), dtype=float)
93 94 95 96 97 98

        selected = hydrogrid.select(center, radius)
        INFO(str(icell)+" Number of HydroCells selected : "+str(len(selected))+ " out of "+str(len(hydrogrid.index)))
        for isel in selected :
            hydrocell = hydrogrid.polylist[isel]
            index = hydrogrid.index[isel]
99 100
            if cell.intersects_poly(hydrocell):
                inter = cell.intersection(hydrocell)
101 102 103 104 105 106 107
                # Another strange behaviour of SphericalHarmonics. There should be an overlap but the intersection polygone is empty.
                if len(inter.polygons) > 0 :
                    inside = inter.polygons[0]._inside
                    if hydrocell.contains_point(inside) and cell.contains_point(inside):
                        area_in[index[0],index[1]] = inter.area()*(EarthRadius**2)
                    else:
                        area_in[index[0],index[1]] = (4*np.pi-inter.area())*(EarthRadius**2)
Anthony's avatar
Anthony committed
108
        
109
        ##############
Anthony's avatar
Anthony committed
110
        # Output of Overlap areas for each grid point
111
        #
Anthony's avatar
Anthony committed
112 113
        #ncfile="Area_"+str("%.2f"%llinside[0])+"_"+str("%.2f"%llinside[1])+"_"+str(rank+1)+"of"+str(nbcore)+".nc"
        #RPP.dumpfield(area_in, hydrogrid.lon, hydrogrid.lat, ncfile, "Intersect area")
114
        #
Anthony's avatar
Anthony committed
115

116 117
        INFO(str(icell)+" Sum of overlap "+str(np.sum(area_in)/area)+
             " Nb of Hydro grid overlaping : "+str(np.count_nonzero(area_in)))
118 119 120 121
        sub_index.append(np.where(area_in > 0.0))
        sub_area.append(np.extract(area_in > 0.0, area_in))
        sub_lon.append(np.extract(area_in > 0.0, hydrogrid.lon))
        sub_lat.append(np.extract(area_in > 0.0, hydrogrid.lat))
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        icell = icell + 1
    #
    # Save the weights to a dedicated file for future use
    #
    if ( saveweights.lower() == 'true' ) :
        with open(wdir+"/"+wfile, 'wb') as fp:
            pickle.dump(sub_index, fp)
            pickle.dump(sub_area, fp)
            pickle.dump(sub_lon, fp)
            pickle.dump(sub_lat, fp)
        fp.close()
else :
    #
    # Extract the weights from the file if it exists
    #
    INFO("Reading weights")
    with open (wdir+"/"+wfile, 'rb') as fp:
        sub_index = pickle.load(fp)
        sub_area = pickle.load(fp)
        sub_lon = pickle.load(fp)
        sub_lat = pickle.load(fp)
    fp.close()
#
#
#
nbpt = len(sub_index)
sub_pts = np.array(list(len(sub_index[i][0]) for i in range(len(sub_index))))
149
nbvmax = part.domainmax(max(sub_pts))
150 151 152 153 154 155
print("nbpt : ", nbpt)
print("nbvmax : ", nbvmax)
print("nbasmax : ", nbasmax)
#
# Extract hydo data from file
#
156
INFO("hydrodata")
157 158
hydrodata = HG.HydroData(hydrogrid.ncfile, hydrogrid.box, sub_index)

159
INFO("initiatmgrid")
160
IF.initatmgrid(rank, nbcore, nbpt, modelgrid)
161

162
INFO("hoverlap")
163
hoverlap = IF.HydroOverlap(nbpt, nbvmax, sub_pts, sub_index, sub_area, sub_lon, sub_lat, part, modelgrid, hydrodata)
164 165 166 167 168 169 170 171 172 173 174

#
# Do some memory management and synchronize procs.
#
comm.Barrier()
del sub_index
del sub_area
del sub_lon
del sub_lat
gc.collect()

175
if rank ==0 :
176 177
    if lonint[0] != lonint[1] and latint[0] != latint[1] :
        DP.MAPPLOT("MapHydroGrid", lonint, latint, hoverlap, hoverlap.hierarchy_bx, modelgrid.polyll, title="Distance to ocean")
178

179
hsuper = IF.HydroSuper(nbvmax, hydrodata, hoverlap, nbasmax)
180 181 182
#
# Plot the hydrological supermesh
#
183
if rank == 0 :
184 185
    if lonint[0] != lonint[1] and latint[0] != latint[1] :
        DP.SUPERMESHPLOT("MapSuperGrid_Beforelinkup", lonint, latint, hoverlap, hsuper, modelgrid.polyll)
186 187 188

print("=================== LINKUP ====================")
hsuper.linkup(hydrodata)
189
if rank ==0 :
190 191
    if lonint[0] != lonint[1] and latint[0] != latint[1] :
        DP.SUPERMESHPLOT("MapSuperGrid_Afterlinkup", lonint, latint, hoverlap, hsuper, modelgrid.polyll)
192 193 194
#
# Do some memory management and synchronize procs.
#
195
 
196 197 198 199 200
comm.Barrier()
del hoverlap
gc.collect()

print("=================== Compute fetch ====================")
201
t = time.time()
POLCHER Jan's avatar
POLCHER Jan committed
202
hsuper.fetch(part)
203 204 205 206 207
comm.Barrier()
t1 = time.time()
print("Time for fetch: {:0.2f} s.".format(t1-t)) 
comm.Barrier()

208
hsuper.dumpnetcdf(OutGraphFile.replace(".nc","_HydroSuper.nc"), gg, modelgrid, part)
209

210
print("Rank : {0} - Basin_count Before Truncate : ".format(part.rank), hsuper.basin_count)
211
hs = TR(hsuper, part, comm, modelgrid, numop = numop)
212 213 214 215
print("Rank : {0} - Basin_count After Truncate : ".format(part.rank), hsuper.basin_count)

hgraph = IF.HydroGraph(nbasmax, hsuper, part, modelgrid)
hgraph.dumpnetcdf(OutGraphFile, gg, modelgrid, part)
216 217

IF.closeinterface(comm)