├── 2018.04.30 ├── simulation.py └── simulation.xlsm ├── LICENSE ├── README.md ├── Tutor 2 ├── gridsection.py ├── tutor2.py └── tutor2.xlsm ├── Tutor 3 ├── dynamicsection.py ├── gridsection.py ├── propertysection.py └── tutor3.xlsm ├── material ├── pythonExcel.png ├── tutor1.2019-02-14.gif └── tutor2.gif ├── tutor1.py └── tutor1.xlsm /2018.04.30/simulation.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import h5py 5 | import numpy as np 6 | import pandas as pd 7 | import matplotlib.pyplot as plt 8 | import xlwings as xw 9 | 10 | from mpl_toolkits.mplot3d import Axes3D 11 | from matplotlib import cm 12 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 13 | import datetime 14 | import subprocess 15 | 16 | realPath = os.path.dirname(os.path.realpath(__file__)) 17 | hdf5File = realPath+'\\simModel\\simModel.hdf5' 18 | filename = realPath+'\\simModel\\model.dxx' 19 | sht = xw.Book.caller().sheets[0] 20 | gridVaryOpt={ } 21 | defaultDim = 200 22 | kwMap = {'dx':'DX','dy':'DY','dz':'DZ','por':'POROSITY','permx':'KX','permy':'PERMY', 23 | 'permz':'PERMZ'} 24 | class CWell: 25 | wellCount = 0 26 | 27 | def __init__(self, name, hI,hJ): 28 | self.name = name 29 | self.head_I = hI 30 | self.head_J = hJ 31 | CWell.wellCount += 1 32 | self.id = CWell.wellCount 33 | 34 | 35 | def getKeyWordBeginRow(iRow,strKW): 36 | index = 'A' 37 | while (sht.range(index+str(iRow)).value != strKW): 38 | iRow = iRow+1 39 | 40 | return iRow 41 | 42 | def getKeyWordEndRow(irow): 43 | irow = irow+1 44 | index = 'B' 45 | while (sht.range(index+str(irow)).value != None): 46 | irow = irow+1 47 | 48 | return irow-1 49 | 50 | def draw2YCurve(ax,title,xlabel,leftMaps,rightMaps): 51 | lineColor = ['b+-','ro-','gs-','h--'] 52 | lmaxV = 0 53 | lminV = 10000 54 | rmaxV = 0 55 | rminV = 10000 56 | 57 | for lMap in leftMaps: 58 | x = lMap['x'] 59 | y = lMap['y'] 60 | i = lMap['id'] 61 | ax.plot(x,y,lineColor[i],lw=2,label=lMap['ylabel']) 62 | 63 | maxNum = max(y) 64 | minNum = min(y) 65 | if(maxNum>lmaxV): 66 | lmaxV = maxNum 67 | if(minNumrmaxV): 81 | rmaxV = maxNum 82 | if(minNum0): 91 | ax2.legend(loc='upper right') 92 | ax2.set_ylim(rminV,rmaxV) 93 | 94 | def drawCurve(ax,xlabel,curvelegend,x,yArray): 95 | 96 | lineColor = ['b+-','ro-','gs-','h--'] 97 | 98 | for i,y in enumerate(yArray): 99 | ax.plot(x, y, lineColor[i], lw=2, zorder=30) 100 | 101 | ax.grid() 102 | ax.set_xlabel(xlabel, fontweight='bold', fontsize=15) 103 | ax.set_xticklabels([]) 104 | ax.set_yticklabels([]) 105 | 106 | ax.legend(ax.lines, curvelegend, fancybox=True, shadow=True, prop={'size': 15}) 107 | 108 | def readGeneralInfo(): 109 | nx = sht.range('B3').options(numbers=int).value 110 | ny = sht.range('C3').options(numbers=int).value 111 | nz = sht.range('D3').options(numbers=int).value 112 | 113 | gridVaryOpt['xopt'] = sht.range('B4').value 114 | gridVaryOpt['yopt'] = sht.range('C4').value 115 | gridVaryOpt['zopt'] = sht.range('D4').value 116 | 117 | gridVaryOpt['por'] = sht.range('F3').value 118 | gridVaryOpt['kx'] = sht.range('G3').value 119 | gridVaryOpt['ky'] = sht.range('H3').value 120 | gridVaryOpt['kz'] = sht.range('I3').value 121 | 122 | return nx,ny,nz 123 | 124 | nx,ny,nz = readGeneralInfo() 125 | 126 | def createHDF5(nx,ny,nz): 127 | 128 | ni = nx 129 | nj = ny 130 | nk = nz 131 | 132 | fModel = h5py.File(hdf5File, "w") 133 | 134 | staticEntry = fModel.create_group(u"StaticGroup") 135 | staticEntry.attrs[u'nx'] = nx 136 | staticEntry.attrs[u'ny'] = ny 137 | staticEntry.attrs[u'nz'] = nz 138 | 139 | fModel.create_group(u"DynamicGroup") 140 | fModel.create_group(u"PvtGroup") 141 | fModel.create_group(u"InitGroup") 142 | fModel.create_dataset(u'StaticGroup/dx', (nk,nj,ni), dtype='f') 143 | fModel.create_dataset(u'StaticGroup/dy', (nk,nj,ni), dtype='f') 144 | fModel.create_dataset(u'StaticGroup/dz', (nk,nj,ni), dtype='f') 145 | fModel.create_dataset(u'StaticGroup/por', (nk,nj,ni), dtype='f') 146 | fModel.create_dataset(u'StaticGroup/permx', (nk,nj,ni), dtype='f') 147 | fModel.create_dataset(u'StaticGroup/permy', (nk,nj,ni), dtype='f') 148 | fModel.create_dataset(u'StaticGroup/permz', (nk,nj,ni), dtype='f') 149 | fModel.create_dataset(u'StaticGroup/tops', (nj,ni), dtype='f') 150 | 151 | fModel.close() 152 | 153 | def init(): 154 | 155 | sht.range((9,3),(9,defaultDim+3-1)).color = (255,255,255) 156 | sht.range((10,3),(10,defaultDim+3-1)).color = (255,255,255) 157 | sht.range((11,3),(11,defaultDim+3-1)).color = (255,255,255) 158 | sht.range((17,3),(17,defaultDim+3-1)).color = (255,255,255) 159 | sht.range((18,3),(18,defaultDim+3-1)).color = (255,255,255) 160 | sht.range((19,3),(19,defaultDim+3-1)).color = (255,255,255) 161 | sht.range((20,3),(20,defaultDim+3-1)).color = (255,255,255) 162 | 163 | 164 | def defineGrid(): 165 | init() 166 | 167 | createHDF5(nx,ny,nz) 168 | 169 | #prepare gui 170 | if gridVaryOpt['xopt'] == 'CON': 171 | sht.range('A9').value = 'DX' 172 | sht.range('B9').value = 'CON' 173 | sht.range('C9').color = (102,255,102) 174 | elif gridVaryOpt['xopt'] == 'XVAR': 175 | sht.range('A9').value = 'DX' 176 | sht.range('B9').value = 'XVAR' 177 | sht.range((9,3),(9,nx+3-1)).color = (102,255,102) 178 | 179 | if gridVaryOpt['yopt'] == 'CON': 180 | sht.range('A10').value = 'DY' 181 | sht.range('B10').value = 'CON' 182 | sht.range('C10').color = (102,255,102) 183 | elif gridVaryOpt['yopt'] == 'YVAR': 184 | sht.range('A10').value = 'DY' 185 | sht.range('B10').value = 'YVAR' 186 | sht.range((10,3),(10,ny+3-1)).color = (102,255,102) 187 | 188 | if gridVaryOpt['zopt'] == 'CON': 189 | sht.range('A11').value = 'DZ' 190 | sht.range('B11').value = 'CON' 191 | sht.range('C11').color = (102,255,102) 192 | elif gridVaryOpt['zopt'] == 'ZVAR': 193 | sht.range('A11').value = 'DZ' 194 | sht.range('B11').value = 'ZVAR' 195 | sht.range((11,3),(11,nz+3-1)).color = (102,255,102) 196 | 197 | if gridVaryOpt['por'] == 'CON': 198 | sht.range('A17').value = 'POR' 199 | sht.range('B17').value = 'CON' 200 | sht.range('C17').color = (102,255,102) 201 | elif gridVaryOpt['por'] == 'ZVAR': 202 | sht.range('A17').value = 'POR' 203 | sht.range('B17').value = 'ZVAR' 204 | sht.range((17,3),(17,nz+3-1)).color = (102,255,102) 205 | 206 | if gridVaryOpt['kx'] == 'CON': 207 | sht.range('A18').value = 'PERMX' 208 | sht.range('B18').value = 'CON' 209 | sht.range('C18').color = (102,255,102) 210 | elif gridVaryOpt['kx'] == 'ZVAR': 211 | sht.range('A18').value = 'PERMX' 212 | sht.range('B18').value = 'ZVAR' 213 | sht.range((18,3),(18,nz+3-1)).color = (102,255,102) 214 | 215 | if gridVaryOpt['ky'] == 'CON': 216 | sht.range('A19').value = 'PERMY' 217 | sht.range('B19').value = 'CON' 218 | sht.range('C19').color = (102,255,102) 219 | elif gridVaryOpt['ky'] == 'ZVAR': 220 | sht.range('A19').value = 'PERMY' 221 | sht.range('B19').value = 'ZVAR' 222 | sht.range((19,3),(19,nz+3-1)).color = (102,255,102) 223 | 224 | if gridVaryOpt['kz'] == 'CON': 225 | sht.range('A20').value = 'PERMZ' 226 | sht.range('B20').value = 'CON' 227 | sht.range('C20').color = (102,255,102) 228 | elif gridVaryOpt['kz'] == 'ZVAR': 229 | sht.range('A20').value = 'PERMZ' 230 | sht.range('B20').value = 'ZVAR' 231 | sht.range((20,3),(20,nz+3-1)).color = (102,255,102) 232 | 233 | def readGrid(): 234 | 235 | fModel = h5py.File(hdf5File, "a") 236 | dset_dx = fModel['StaticGroup/dx'] 237 | dset_dy = fModel['StaticGroup/dy'] 238 | dset_dz = fModel['StaticGroup/dz'] 239 | dset_por = fModel['StaticGroup/por'] 240 | dset_kx = fModel['StaticGroup/permx'] 241 | dset_ky = fModel['StaticGroup/permy'] 242 | dset_kz = fModel['StaticGroup/permz'] 243 | dset_tops = fModel['StaticGroup/tops'] 244 | 245 | iDxRow = getKeyWordBeginRow(1,'DX') 246 | iDyRow = getKeyWordBeginRow(1,'DY') 247 | iDzRow = getKeyWordBeginRow(1,'DZ') 248 | if gridVaryOpt['xopt'] == 'XVAR' : 249 | dxVar = sht.range((iDxRow,3),(iDxRow,nx+3-1)).options(np.array).value 250 | idArray = np.arange(nx) 251 | for id in idArray: 252 | dset_dx[:,:,id] = dxVar[id] 253 | elif gridVaryOpt['xopt'] == 'CON' : 254 | dset_dx[:,:,:] = sht.range((iDxRow,3)).options(numbers=float).value 255 | 256 | if gridVaryOpt['yopt'] == 'YVAR' : 257 | dyVar = sht.range((iDyRow,3),(iDyRow,ny+3-1)).options(np.array).value 258 | idArray = np.arange(ny) 259 | for id in idArray: 260 | dset_dy[:,id,:] = dyVar[id] 261 | elif gridVaryOpt['yopt'] == 'CON' : 262 | dset_dy[:,:,:] = sht.range((iDyRow,3)).options(numbers=float).value 263 | 264 | if gridVaryOpt['zopt'] == 'ZVAR' : 265 | dzVar = sht.range((iDzRow,3),(iDzRow,nz+3-1)).options(np.array).value 266 | idArray = np.arange(nz) 267 | for id in idArray: 268 | dset_dz[id,:,:] = dzVar[id] 269 | elif gridVaryOpt['zopt'] == 'CON' : 270 | dset_dz[:,:,:] = sht.range((iDzRow,3)).options(numbers=float).value 271 | 272 | itopRow = getKeyWordBeginRow(1,'TOPS') 273 | dset_tops[:,:] = sht.range((itopRow,3)).options(numbers=float).value 274 | 275 | iporRow = getKeyWordBeginRow(1,'POR') 276 | ikxRow = getKeyWordBeginRow(1,'PERMX') 277 | ikyRow = getKeyWordBeginRow(1,'PERMY') 278 | ikzRow = getKeyWordBeginRow(1,'PERMZ') 279 | if gridVaryOpt['por'] == 'ZVAR' : 280 | porVar = sht.range((iporRow,3),(iporRow,nz+3-1)).options(np.array).value 281 | idArray = np.arange(nz) 282 | for id in idArray: 283 | dset_por[id,:,:] = porVar[id] 284 | elif gridVaryOpt['por'] == 'CON' : 285 | dset_por[:,:,:] = sht.range((iporRow,3)).options(numbers=float).value 286 | 287 | if gridVaryOpt['kx'] == 'ZVAR' : 288 | kxVar = sht.range((ikxRow,3),(ikxRow,nz+3-1)).options(np.array).value 289 | idArray = np.arange(nz) 290 | for id in idArray: 291 | dset_kx[id,:,:] = kxVar[id] 292 | elif gridVaryOpt['kx'] == 'CON' : 293 | dset_kx[:,:,:] = sht.range((ikxRow,3)).options(numbers=float).value 294 | 295 | if gridVaryOpt['ky'] == 'ZVAR' : 296 | kyVar = sht.range((ikyRow,3),(ikyRow,nz+3-1)).options(np.array).value 297 | idArray = np.arange(nz) 298 | for id in idArray: 299 | dset_ky[id,:,:] = kyVar[id] 300 | elif gridVaryOpt['ky'] == 'CON' : 301 | dset_ky[:,:,:] = sht.range((ikyRow,3)).options(numbers=float).value 302 | 303 | if gridVaryOpt['kz'] == 'ZVAR' : 304 | kzVar = sht.range((ikzRow,3),(ikzRow,nz+3-1)).options(np.array).value 305 | idArray = np.arange(nz) 306 | for id in idArray: 307 | dset_kz[id,:,:] = kzVar[id] 308 | elif gridVaryOpt['kz'] == 'CON' : 309 | dset_kz[:,:,:] = sht.range((ikzRow,3)).options(numbers=float).value 310 | 311 | fModel.flush() 312 | fModel.close() 313 | 314 | def drawPvtCurve(): 315 | fig = plt.figure('PVT') 316 | 317 | iRowPvtSec= getKeyWordBeginRow(1,'PVT') 318 | 319 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'OIL-PVT') 320 | iRowEnd = getKeyWordEndRow(iRowBegin) 321 | 322 | df_PVTo = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 323 | 324 | o_x = df_PVTo['P'] 325 | o_y0 = df_PVTo['MUO'] 326 | o_y1 = df_PVTo['BO'] 327 | o_y2 = df_PVTo['RSO'] 328 | 329 | ax = fig.add_subplot(2,1,1) 330 | 331 | lMap1 = {'x':o_x,'y':o_y0,'id':0,'ylabel':'MUO'} 332 | lMap2 = {'x':o_x,'y':o_y1,'id':1,'ylabel':'BO'} 333 | rMap = {'x':o_x,'y':o_y2,'id':2,'ylabel':'RSO'} 334 | leftMaps = [lMap1,lMap2] 335 | rightMaps = [rMap] 336 | 337 | draw2YCurve(ax,'Oil PVT','P',leftMaps,rightMaps) 338 | 339 | # pvtg 340 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'GAS-PVT') 341 | iRowEnd = getKeyWordEndRow(iRowBegin) 342 | df_PVTg = sht.range((iRowBegin,2),(iRowEnd,4)).options(pd.DataFrame,index=False).value 343 | 344 | g_x = df_PVTg['P'] 345 | g_y0 = df_PVTg['MUG'] 346 | g_y1 = df_PVTg['BG'] 347 | 348 | ax = fig.add_subplot(2,1,2) 349 | 350 | lMap1 = {'x':g_x,'y':g_y0,'id':0,'ylabel':'MUG'} 351 | lMap2 = {'x':g_x,'y':g_y1,'id':1,'ylabel':'BG'} 352 | leftMaps = [lMap1,lMap2] 353 | rightMaps = [] 354 | 355 | draw2YCurve(ax,'Gas PVT','P',leftMaps,rightMaps) 356 | 357 | plt.show() 358 | 359 | def readPvt(f): 360 | iRowPvtSec= getKeyWordBeginRow(1,'PVT') 361 | 362 | iRowPbo = getKeyWordBeginRow(iRowPvtSec,'PBO') 363 | fPbo = sht.range((iRowPbo,2),(iRowPbo,2)).value 364 | iRowMuo_s = getKeyWordBeginRow(iRowPvtSec,'Viso_SLOPE') 365 | fMuo_s = sht.range((iRowMuo_s,2),(iRowMuo_s,2)).value 366 | iRowBo_s = getKeyWordBeginRow(iRowPvtSec,'Bo_SLOPE') 367 | fBo_s = sht.range((iRowBo_s,2),(iRowBo_s,2)).value 368 | 369 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'OIL-PVT') 370 | iRowEnd = getKeyWordEndRow(iRowBegin) 371 | 372 | df_PVTo = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame).value 373 | 374 | # df to hdf5 375 | df_to_nparray = df_PVTo.to_records(index=True) 376 | 377 | #pvto_nparray = np.asarray(df_to_nparray) 378 | # create dataset 379 | f['PvtGroup/PVTO'] = df_to_nparray 380 | 381 | # pb 382 | f['PvtGroup'].attrs[u'PB'] = fPbo 383 | f['PvtGroup'].attrs[u'MUO_SLOPE'] = fMuo_s 384 | f['PvtGroup'].attrs[u'BO_SLOPE'] = fBo_s 385 | # pvtw 386 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'WATER-PVT') 387 | iRowEnd = getKeyWordEndRow(iRowBegin) 388 | df_PVTw = sht.range((iRowBegin,2),(iRowEnd,4)).options(pd.DataFrame).value 389 | df_to_nparray = df_PVTw.to_records(index=True) 390 | f['PvtGroup/PVTW'] = df_to_nparray 391 | 392 | # pvtg 393 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'GAS-PVT') 394 | iRowEnd = getKeyWordEndRow(iRowBegin) 395 | df_PVTg = sht.range((iRowBegin,2),(iRowEnd,4)).options(pd.DataFrame).value 396 | df_to_nparray = df_PVTg.to_records(index=True) 397 | f['PvtGroup/PVTG'] = df_to_nparray 398 | 399 | # density 400 | iDenRow = getKeyWordBeginRow(iRowPvtSec,u'DENSITY') 401 | df_density = sht.range((iDenRow,2),(iDenRow+1,4)).options(pd.DataFrame).value 402 | df_to_nparray = df_density.to_records(index=True) 403 | f['PvtGroup/DENSITY'] = df_to_nparray 404 | 405 | # rock 406 | iRockRow = getKeyWordBeginRow(iRowPvtSec,u'CROCK') 407 | fRock = sht.range((iRockRow,3),(iRockRow,3)).value 408 | f['PvtGroup'].attrs[u'ROCK'] = fRock 409 | 410 | def drawRelPermCurve(): 411 | fig = plt.figure('Rel. Perm') 412 | #ax = fig.add_subplot(111) 413 | 414 | iRowPvtSec= getKeyWordBeginRow(1,'PVT') 415 | # water-oil 416 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'WATER-OIL') 417 | iRowEnd = getKeyWordEndRow(iRowBegin) 418 | 419 | df_SWOF = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 420 | 421 | wo_x = df_SWOF['SAT'] 422 | wo_y0 = df_SWOF['KRW'] 423 | wo_y1 = df_SWOF['KROW'] 424 | 425 | wo_yArray = [wo_y0,wo_y1] 426 | ax = fig.add_subplot(2,1,1) 427 | 428 | drawCurve(ax,'SAT',['KRW','KROW'],wo_x,wo_yArray) 429 | 430 | # GAS-LIQUID 431 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'GAS-LIQUID') 432 | iRowEnd = getKeyWordEndRow(iRowBegin) 433 | 434 | df_SGLF = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 435 | 436 | x = df_SGLF['SLIQ'] 437 | y0 = df_SGLF['KRG'] 438 | y1 = df_SGLF['KROG'] 439 | 440 | yArray = [y0,y1] 441 | ax = fig.add_subplot(2,1,2) 442 | 443 | drawCurve(ax,'SLIQ',['KRG','KROG'],x,yArray) 444 | 445 | plt.show() 446 | 447 | 448 | def readRelativePerm(f): 449 | iRowPvtSec= getKeyWordBeginRow(1,'PVT') 450 | # water-oil 451 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'WATER-OIL') 452 | iRowEnd = getKeyWordEndRow(iRowBegin) 453 | 454 | df_SWOF = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 455 | #sht.range('G29:J39').options(pd.DataFrame).value = df_PVTo 456 | # df to hdf5 457 | df_to_nparray = df_SWOF.to_records(index=True) 458 | # create dataset 459 | f['PvtGroup/SWOF'] = df_to_nparray 460 | 461 | # GAS-LIQUID 462 | iRowBegin = getKeyWordBeginRow(iRowPvtSec,'GAS-LIQUID') 463 | iRowEnd = getKeyWordEndRow(iRowBegin) 464 | 465 | df_SGLF = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 466 | #sht.range('G29:J39').options(pd.DataFrame).value = df_PVTo 467 | # df to hdf5 468 | df_to_nparray = df_SGLF.to_records(index=True) 469 | # create dataset 470 | f['PvtGroup/SGLF'] = df_to_nparray 471 | 472 | def readPropSection(): 473 | f = h5py.File(hdf5File,'a') 474 | readPvt(f) 475 | readRelativePerm(f) 476 | 477 | f.close() 478 | 479 | def readInitSection(): 480 | f = h5py.File(hdf5File,'a') 481 | iRowInitSec= getKeyWordBeginRow(1,'INITIAL SECTION') 482 | iRowEquil = getKeyWordBeginRow(iRowInitSec,'EQUIL') 483 | fRefP = sht.range((iRowEquil+1,2),(iRowEquil+1,2)).value 484 | fRefDepth = sht.range((iRowEquil+1,3),(iRowEquil+1,3)).value 485 | fOWC = sht.range((iRowEquil+1,4),(iRowEquil+1,4)).value 486 | fOGC = sht.range((iRowEquil+1,5),(iRowEquil+1,5)).value 487 | 488 | f[u'InitGroup'].attrs[u'RefPress'] = fRefP 489 | f[u'InitGroup'].attrs[u'RefDepth'] = fRefDepth 490 | f[u'InitGroup'].attrs[u'OWC'] = fOWC 491 | f[u'InitGroup'].attrs[u'OGC'] = fOGC 492 | 493 | f.close() 494 | 495 | def drawWells(): 496 | fig = plt.figure('WELL PRODUCTION') 497 | 498 | iRow = getKeyWordBeginRow(1,'SCHEDULE SECTION') 499 | index = 'A' 500 | wells = {} 501 | while (sht.range(index+str(iRow)).value!='END'): 502 | iRow = iRow+1 503 | kw = sht.range(index+str(iRow)).value 504 | if(kw==u'General Info'): 505 | iwellDefRow = getKeyWordBeginRow(iRow,u'Well Name') 506 | wellName = sht.range('B'+str(iwellDefRow)).value 507 | head_I = sht.range('D'+str(iwellDefRow)).options(numbers=int).value 508 | head_J = sht.range('F'+str(iwellDefRow)).options(numbers=int).value 509 | well = CWell(wellName,head_I,head_J) 510 | wells[wellName] = well 511 | 512 | elif(kw == u'Production'): 513 | wName = sht.range('A'+str(iRow+1)).value 514 | iEndProdRow = getKeyWordEndRow(iRow) 515 | df_prod = sht.range((iRow,2),(iEndProdRow,7)).options(pd.DataFrame,index=False).value 516 | iRow = iEndProdRow 517 | 518 | well = wells.get(wName) 519 | well.df_prod = df_prod 520 | 521 | wellNUm = len(wells) 522 | subRow = int(wellNUm/2) 523 | if(wellNUm%2>0): 524 | subRow += 1 525 | wellId = 1 526 | for well in wells.values(): 527 | wellName = well.name 528 | df_prod = well.df_prod 529 | df_prod['Date'] = df_prod['Date'].astype('int64') 530 | df_prod['Date'] = pd.to_datetime(df_prod['Date'],format="%Y%m") 531 | x = df_prod['Date'] 532 | 533 | y1 = df_prod[u'Monthly Oil Production'] 534 | y2 = df_prod[u'Monthly Water Production'] 535 | 536 | ax = fig.add_subplot(subRow,2,wellId) 537 | 538 | lMap1 = {'x':x,'y':y1,'id':0,'ylabel':'OPR'} 539 | lMap2 = {'x':x,'y':y2,'id':1,'ylabel':'WPR'} 540 | leftMaps = [lMap1,lMap2] 541 | rightMaps = [] 542 | 543 | draw2YCurve(ax,wellName,'Date',leftMaps,rightMaps) 544 | 545 | wellId += 1 546 | 547 | plt.show() 548 | 549 | 550 | def readScheduleSection(): 551 | iRow = getKeyWordBeginRow(1,'SCHEDULE SECTION') 552 | index = 'A' 553 | wells = {} 554 | while (sht.range(index+str(iRow)).value!='END'): 555 | iRow = iRow+1 556 | kw = sht.range(index+str(iRow)).value 557 | if(kw==u'General Info'): 558 | iwellDefRow = getKeyWordBeginRow(iRow,u'Well Name') 559 | wellName = sht.range('B'+str(iwellDefRow)).value 560 | head_I = sht.range('D'+str(iwellDefRow)).options(numbers=int).value 561 | head_J = sht.range('F'+str(iwellDefRow)).options(numbers=int).value 562 | well = CWell(wellName,head_I,head_J) 563 | wells[wellName] = well 564 | 565 | elif(kw == u'Well Completion'): 566 | comp = [] 567 | wName = sht.range('B'+str(iRow)).value 568 | well = wells.get(wName) 569 | iRow = iRow + 3 570 | iEndComp = getKeyWordEndRow(iRow) 571 | for i_layer in range(iRow,iEndComp+1): 572 | nLayer = sht.range('D'+str(i_layer)).options(numbers=int).value 573 | comp.append(nLayer) 574 | 575 | iRow = iEndComp 576 | well.comp = comp 577 | 578 | elif(kw == u'Production'): 579 | wName = sht.range('A'+str(iRow+1)).value 580 | iEndProdRow = getKeyWordEndRow(iRow) 581 | prod_date = sht.range((iRow+1,2),(iEndProdRow,2)).options(numbers=str).value 582 | df_prod = sht.range((iRow,3),(iEndProdRow,7)).options(pd.DataFrame,index=False).value 583 | iRow = iEndProdRow 584 | 585 | 586 | well = wells.get(wName) 587 | well.df_prod = df_prod 588 | 589 | 590 | np_prodDate = np.array(prod_date) 591 | asciiList = [n.encode("ascii", "ignore") for n in np_prodDate] 592 | well.prod_date = asciiList 593 | 594 | fModel = h5py.File(hdf5File,'a') 595 | dt = h5py.special_dtype(vlen=str) 596 | 597 | for well in wells.values(): 598 | groupName = "DynamicGroup/Field/"+well.name 599 | wellentry = fModel.create_group(groupName) 600 | wellentry.attrs[u'name'] = well.name 601 | wellentry.attrs[u'id'] = well.id 602 | wellentry.attrs[u'headI'] = well.head_I 603 | wellentry.attrs[u'headJ'] = well.head_J 604 | wellentry.attrs[u'comp'] = well.comp 605 | #wellentry.attrs[u'prodDate'] = well.prod_date 606 | df_to_nparray = well.df_prod.to_records(index=True) 607 | #wellentry.create_dataset(u'prod', data=df_to_nparray) 608 | fModel[groupName+'/'+'prodData'] = df_to_nparray 609 | wellentry.create_dataset('date', (len(well.prod_date),), data=well.prod_date,dtype=dt) 610 | 611 | fModel.close() 612 | 613 | def outputIOSection(f): 614 | f.write('TITLE1 GENERATED FROM EXCEL\nTITLE2 CASE 1\n') 615 | f.write('##################### I/O SECTION #######################\n') 616 | f.write('IO_CONTROL\nSUMMARY\nPRINTGRID 13*0\n') 617 | 618 | def outputDimSection(f,fModel): 619 | f.write('############# DYNAMIC DIMENSIONING SECTION ##############\n') 620 | f.write('DIMENSION\n') 621 | datasetNames = [n for n in fModel.keys()] 622 | nx = 0 623 | ny = 0 624 | nz = 0 625 | for n in datasetNames: 626 | if(n=='StaticGroup'): 627 | staticG = fModel[n] 628 | modelShape = [] 629 | #staticG.items() 630 | for item in staticG.attrs.keys(): 631 | modelShape.append(staticG.attrs[item]) 632 | elif(n=='DynamicGroup'): 633 | dynamicG = fModel[n] 634 | fieldG = dynamicG['Field'] 635 | 636 | dateArray = [] 637 | for wellG in fieldG.keys(): 638 | well = fieldG[wellG] 639 | wellDate = well[u'date'] 640 | dateArray.append(wellDate) 641 | 642 | date_tuple = tuple(dateArray) 643 | mergedDate = np.concatenate(date_tuple) 644 | uniqueDate = np.unique(mergedDate, return_index=True)[0] 645 | 646 | 647 | 648 | nx = modelShape[0] 649 | ny = modelShape[1] 650 | nz = modelShape[2] 651 | f.write('NX {} NY {} NZ {}\n'.format(nx,ny,nz)) 652 | 653 | f.write('NCMAX 3 NWMAX 2\nBLACKOIL\n') 654 | 655 | startDate = uniqueDate[0] 656 | intDate = int(float(startDate)) 657 | #formatedDate = datetime.datetime.strptime(str(intDate), '%Y%m').strftime('%Y %m %d') 658 | 659 | firstDate = datetime.datetime.strptime(str(intDate), '%Y%m') 660 | #delta = datetime.timedelta(days=1) 661 | prevDate = firstDate #-delta 662 | f.write('FIRSTDAY {}\n'.format(prevDate.strftime('%Y %m %d'))) 663 | 664 | def dumpGridSection(f,fModel): 665 | f.write('################### GRID SECTION #######################') 666 | f.write('\nGRID\nCARTESIAN\n') 667 | datasetNames = [n for n in fModel.keys()] 668 | for n in datasetNames: 669 | if(n=='StaticGroup'): 670 | staticG = fModel[n] 671 | modelShape = [] 672 | #staticG.items() 673 | for item in staticG.attrs.keys(): 674 | modelShape.append(staticG.attrs[item]) 675 | 676 | # keys() is used for iter 677 | for item in staticG.keys(): 678 | x = staticG[item].value 679 | 680 | 681 | if(item!='tops'): 682 | f.write('{} XYZALL\n'.format(kwMap[item])) 683 | for indexes, value in np.ndenumerate(x): 684 | z,y,x = indexes 685 | if(x==modelShape[0]-1): 686 | f.write('{:.3f}\n'.format(value)) 687 | else: 688 | f.write('{:.3f} '.format(value)) 689 | else: 690 | f.write('TOPS CON {}'.format(x[0][0])) 691 | 692 | f.write('\n\n') 693 | 694 | elif(n=='PvtGroup'): 695 | pvtG = fModel[n] 696 | fCRock = pvtG.attrs[u'ROCK'] 697 | f.write('CROCK CON {}\n'.format(fCRock)) 698 | 699 | 700 | def dumpPvtSection(f,fModel): 701 | f.write('##################### PVT SECTION #######################\n') 702 | f.write('PVT\n#\n') 703 | f.write('COMPONENTS H2O HOIL SGAS\n') 704 | f.write('# ---- ---- ----\n') 705 | f.write('MW 18.015 210.0 22.9674\n') 706 | f.write('COMPRESS 2.88E-6 1.3687E-5 0\n') 707 | f.write('CTEXP 0 3.8E-5 0.00038\n') 708 | f.write('DENSITY 64.79 49.111 0.0605438\n') 709 | f.write('GRAVITY 1.0383 0.7411 0.7928\n') 710 | f.write('PHASE_ID WATER OIL GAS\n') 711 | 712 | datasetNames = [n for n in fModel.keys()] 713 | for n in datasetNames: 714 | if(n=='PvtGroup'): 715 | pvtG = fModel[n] 716 | fPb = pvtG.attrs[u'PB'] 717 | fBo_s= pvtG.attrs[u'BO_SLOPE'] 718 | 719 | pvto = pvtG[u'PVTO'] 720 | a = pvto[...] 721 | df_pvto = pd.DataFrame(a) 722 | pvtg = pvtG[u'PVTG'] 723 | a = pvtg[...] 724 | df_pvtg = pd.DataFrame(a) 725 | df_merged = pd.merge(df_pvto,df_pvtg,how='outer',on='P') 726 | df_merged = df_merged.sort_values(by = 'P',ascending = True) 727 | df_merged = df_merged.interpolate(method='linear') 728 | 729 | cols = df_merged.columns.tolist() 730 | cols.insert(1,cols.pop(cols.index('RSO'))) 731 | cols.insert(2,cols.pop(cols.index('BO'))) 732 | cols.insert(3,cols.pop(cols.index('BG'))) 733 | cols.insert(4,cols.pop(cols.index('MUO'))) 734 | cols.insert(5,cols.pop(cols.index('MUG'))) 735 | 736 | df_merged = df_merged[cols] 737 | df_merged = df_merged.rename(columns={df_merged.columns[0]:'PTAB' 738 | ,df_merged.columns[2]:'BO' 739 | ,df_merged.columns[3]:'BG' 740 | ,df_merged.columns[4]:'VIS_OIL' 741 | ,df_merged.columns[5]:'VIS_GAS'}) 742 | 743 | df_merged.to_csv(f,sep=' ',float_format='%.3f',index=False) 744 | 745 | f.write('\n#\nPB {}\n'.format(fPb)) 746 | pvtw = pvtG[u'PVTW'] 747 | a = pvtw[...] 748 | df_pvtw = pd.DataFrame(a) 749 | mx_pvtw = df_pvtw.as_matrix(columns=None) 750 | mx_pvto = df_merged.as_matrix(columns=None) 751 | pvtoRows= df_pvto.iloc[:,0].size 752 | fPusat = mx_pvto[pvtoRows-1,0] 753 | # 754 | maxPress = fPusat+200 755 | pvtG.attrs[u'MAXPRESS'] = maxPress 756 | # 757 | BoPb = 0 758 | if(df_pvto[df_pvto[u'P']==fPb].empty): 759 | #df_prodByDate = df_pvto[df_pvto[u'P'].isin([fPb])] 760 | df_pvto.loc[df_pvto.shape[0]+1] = {'P':fPb,'MUO':np.nan,'BO':np.nan,'RSO':np.nan} 761 | df_pvto = df_pvto.interpolate(method='linear') 762 | BoPb = df_pvto[df_pvto[u'P']==fPb]['BO'] 763 | mx_BoPb = BoPb.as_matrix(columns=None) 764 | fBoPb = mx_BoPb[0] 765 | else: 766 | df_pb = df_pvto[df_pvto[u'P'].isin([fPb])] 767 | BoPb = df_pb['BO'] 768 | 769 | mx_BoPb = BoPb.as_matrix(columns=None) 770 | 771 | fBoPb = mx_BoPb[0] 772 | 773 | fBusat = (1 + fBo_s * (fPusat - fPb))* fBoPb 774 | 775 | fBW = mx_pvtw[0,2] 776 | fRefPw = mx_pvtw[0,0] 777 | fVisW = mx_pvtw[0,1] 778 | f.write('BWI {}\nREFERPW {}\nVIS_WAT {}\n'.format(fBW,fRefPw,fVisW)) 779 | f.write('CVISW {}\nCVISO {}\n'.format(0.0,0.0)) 780 | f.write('PUSAT {}\nBUSAT {:.3f}\n'.format(fPusat,fBusat)) 781 | 782 | 783 | f.write('#WATER-OIL RELATIVE PERMEABILITY TABLE\n') 784 | f.write('RELPERM TABLE 1\n') 785 | f.write('STONE2\n') 786 | f.write('WATER-OIL\n') 787 | f.write('# SW KRW KROW PCWO (PSIA)\n') 788 | 789 | swof = pvtG[u'SWOF'] 790 | a = swof[...] 791 | df_swof = pd.DataFrame(a) 792 | df_swof.drop(u'index',axis=1,inplace=True) 793 | df_swof.to_csv(f,sep=' ',float_format='%.5f',index=False,header=False) 794 | 795 | f.write('#\n#GAS-OIL RELATIVE PERMEABILITY TABLE\n#\n') 796 | f.write('GAS-LIQUID\n') 797 | f.write('#SLIQ KRG KROG PCOG (PSIA)\n') 798 | sglf = pvtG[u'SGLF'] 799 | a = sglf[...] 800 | df_sglf = pd.DataFrame(a) 801 | df_sglf.drop(u'index',axis=1,inplace=True) 802 | df_sglf.to_csv(f,sep=' ',float_format='%.5f',index=False,header=False) 803 | 804 | def dumpInitSection(f,fModel): 805 | f.write('############### EQUILLIBRATION SECTION #################\n') 806 | f.write('EQUIL MODEL 1\n') 807 | datasetNames = [n for n in fModel.keys()] 808 | for n in datasetNames: 809 | if(n=='InitGroup'): 810 | initG = fModel[n] 811 | fRefPress = initG.attrs[u'RefPress'] 812 | fRefDepth = initG.attrs[u'RefDepth'] 813 | fwoc = initG.attrs[u'OWC'] 814 | fgoc = initG.attrs[u'OGC'] 815 | 816 | f.write('PRESI CON {}\n'.format(fRefPress)) 817 | f.write('TRESI CON {}\n'.format(100.0)) 818 | f.write('PCGRAVITY\n') 819 | f.write('DEPTH {} DWOC {} DGOC {} PCWOR 0. PCGOC 0.\n'.format(fRefDepth,fwoc,fgoc)) 820 | 821 | def dumpSolutionSection(f,fModel): 822 | f.write('############### SOLUTION SECTION #######################\n') 823 | f.write('SOLUTION\n') 824 | 825 | datasetNames = [n for n in fModel.keys()] 826 | for n in datasetNames: 827 | if(n=='PvtGroup'): 828 | pvtG = fModel[n] 829 | maxpress = pvtG.attrs[u'MAXPRESS'] 830 | f.write('MAXPRES {}\n'.format(maxpress)) 831 | 832 | f.write('RELTOL 0.0005\n') 833 | 834 | def dumpSchduleSection(f,fModel): 835 | f.write('############### RECURRENT SECTION #######################\n') 836 | f.write('RUN\n') 837 | 838 | datasetNames = [n for n in fModel.keys()] 839 | for n in datasetNames: 840 | if(n=='DynamicGroup'): 841 | dynamicG = fModel[n] 842 | fieldG = dynamicG['Field'] 843 | 844 | wellProd_dfs = [] 845 | dateArray = [] 846 | for wellG in fieldG.keys(): 847 | well = fieldG[wellG] 848 | wellDate = well[u'date'] 849 | 850 | prod = well[u'prodData'] 851 | a = prod[...] 852 | df_prod = pd.DataFrame(a) 853 | df_prod[u'wellName'] = well.attrs[u'name'] 854 | df_prod[u'wellId'] = well.attrs[u'id'] 855 | df_prod[u'Date'] = wellDate 856 | 857 | df_prod[u'wopr'] = df_prod[u'Monthly Oil Production']/df_prod[u'Production Days'] 858 | 859 | wellProd_dfs.append(df_prod) 860 | dateArray.append(wellDate) 861 | 862 | df_mergedProd = pd.concat(wellProd_dfs) 863 | mergedDate = df_mergedProd[u'Date'] 864 | uniqueDate = np.unique(mergedDate,return_index=True)[0] 865 | # 866 | #date_tuple = tuple(dateArray) 867 | #mergedDate = np.concatenate(date_tuple) 868 | #uniqueDate = np.unique(mergedDate, return_index=True)[0] 869 | date = uniqueDate[0] 870 | 871 | f.write('WELSPECS\n') 872 | 873 | for wellG in fieldG.keys(): 874 | well = fieldG[wellG] 875 | wellName = well.attrs[u'name'] 876 | wellId = well.attrs[u'id'] 877 | headI = well.attrs[u'headI'] 878 | headJ = well.attrs[u'headJ'] 879 | f.write('WELL {} \'{}\' PRODUCER VERTICAL {} {}\n'.format(wellId,wellName,headI,headJ)) 880 | 881 | f.write('COMPLETION\n') 882 | for wellG in fieldG.keys(): 883 | well = fieldG[wellG] 884 | wellName = well.attrs[u'name'] 885 | wellId = well.attrs[u'id'] 886 | comps = well.attrs[u'comp'] 887 | f.write('WELL {} \'{}\' RW 0.25\n'.format(wellId,wellName)) 888 | for comp in comps: 889 | f.write(' WPIV_KXYH {} -1.0 4*0\n'.format(comp)) 890 | 891 | f.write('\nOPERATION\n') 892 | df_prodByDate = df_mergedProd[df_mergedProd[u'Date'].isin([date])] 893 | for index,prodItem in df_prodByDate.iterrows(): 894 | wellName = prodItem[u'wellName'] 895 | wellId = prodItem[u'wellId'] 896 | wopr = prodItem[u'wopr'] 897 | f.write(' WELL {} \'{}\' BHP 14.7 MAXOIL {:.3f}\n'.format(wellId,wellName,wopr)) 898 | 899 | for i, date in enumerate(uniqueDate): 900 | if i==0: 901 | continue 902 | 903 | intDate = int(float(date)) 904 | formatedDate = datetime.datetime.strptime(str(intDate), '%Y%m').strftime('%Y %m %d') 905 | f.write('DATE {}'.format(formatedDate)) 906 | f.write('\nOPERATION\n') 907 | df_prodByDate = df_mergedProd[df_mergedProd[u'Date'].isin([date])] 908 | for index,prodItem in df_prodByDate.iterrows(): 909 | wellName = prodItem[u'wellName'] 910 | wellId = prodItem[u'wellId'] 911 | wopr = prodItem[u'wopr'] 912 | f.write(' WELL {} \'{}\' BHP 14.7 MAXOIL {:.3f}\n'.format(wellId,wellName,wopr)) 913 | 914 | def dumpModel2XXSim(): 915 | f = open(filename,'w') 916 | 917 | fModel = h5py.File(hdf5File,'r+') 918 | 919 | outputIOSection(f) 920 | outputDimSection(f,fModel) 921 | dumpGridSection(f,fModel) 922 | dumpPvtSection(f,fModel) 923 | dumpInitSection(f,fModel) 924 | dumpSolutionSection(f,fModel) 925 | dumpSchduleSection(f,fModel) 926 | 927 | f.write('\nSTOP') 928 | f.flush() 929 | f.close() 930 | fModel.close() 931 | 932 | 933 | def runXXSim(): 934 | defineGrid() 935 | readGrid() 936 | 937 | readPropSection() 938 | 939 | readInitSection() 940 | 941 | readScheduleSection() 942 | 943 | dumpModel2XXSim() 944 | 945 | -------------------------------------------------------------------------------- /2018.04.30/simulation.xlsm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/2018.04.30/simulation.xlsm -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExcelPySim 2 | A reservoir simulation processing software based on the combination of Excel and Python. ![main banner](material/pythonExcel.png?raw=True "main banner") 3 | 4 | ## What 5 | It's a reservoir simulation processing software based on Microsoft Excel, but is developed with Python language. That's, Microsoft Excel is the main work platform or main frame for reservoir simulation work, but the software is developed with Python, not the embedded VBA. 6 | ## Why 7 | Reservoir or geological engineers are born data analyst!And Python is the popular language for data analysis, machine learning and AI, refer to [How popular is Python](https://www.quora.com/How-popular-is-python "Python is popular"). At the same time, Microsoft Excel is the software we use frequently when we work. Why not write a reservoir simulation processing software based on Excel+Python, which will enable us to learn new python skill while working in a familiar Excel environment? 8 | ## How 9 | ### *How to integrate Python into Excel?* 10 | Thanks [XlWings](https://github.com/ZoomerAnalytics/xlwings "XlWings"), it provides the solution for us because it makes it easy to call Python from Excel and vice versa. Please install [XlWings](https://github.com/ZoomerAnalytics/xlwings "XlWings") and read its documents at first before you try ExcelPySim. 11 | ### *How it work?* 12 | A xlsm file is open to input data which is read by and converted into a deck file for XXSim reservoir simulation software. After finishing input, a button in the xlsm file could be clicked to call the XXSim simulator to run. Please visit [XXSim Github](https://github.com/ReservoirSimulator/XXSim "xxsim") or [XXSim Website](https://www.peclouds.com "xxsim website") for more. 13 | ## Getting Started 14 | It is started with a simple black oil case. 15 | ### Tutorial 1 16 | ![tutor 1](material/tutor1.2019-02-14.gif?raw=True "tutor1 dynamic") 17 | There are two files, 'tutor1.xlsm' and 'tutor1.py' which process the grid section of black oil case. By tutorial 1, it is shown that the combination of [XlWings](https://github.com/ZoomerAnalytics/xlwings "XlWings") and Excel can provide a solution to a Excel-based reservoir simulation pre-processing tool. The use of xlwings is simple, just call your Python functions in your VBA macros. As follow is the python code to read and write Excel, 18 | ```python 19 | # read value from excel 20 | nx = sheet.range('B3').options(numbers=int).value 21 | # write value to excel 22 | sheet.range('A10').value = 'Grid Size: DX' 23 | ``` 24 | 25 | ### Tutorial 2 26 | ![tutor 2](material/tutor2.gif?raw=True "tutor2 dynamic") 27 | Reservoir engineers need to process production data frequently, so the reading and plotting of well production data is put forward to the tutorial 2. The production data format in tutor2.xlsm is just an example, so when you use it, it is need to adjust the Excel format and edit the code according to the actual situation. Two important libs for data analysis, numpy and pandas, have been imported in Tutorial 2 to process chunks of production data, which is much more convenient and effective than VBA. Just one line code to read production data: 28 | ```python 29 | df_prod = sheet.range((iRow,2),(iEndRow,7)).options(pd.DataFrame,index=False).value 30 | ``` 31 | Please visit [pandas tutorial](https://pandas.pydata.org/pandas-docs/stable/getting_started/tutorials.html "Pandas") to learn more. 32 | ### Tutorial 3 33 | In this tutorial, PVT and SCAL data are readed and shown in graph. Also [Pandas](https://pandas.pydata.org "Pandas") is used to read and store table data. 34 | ## Joining us? 35 | Reservoir simulation technology is important one of reservoir engineering methods and reservoir simulation tool should be one of tools at hand of a reservoir engineer. I hope it is helpful by the open source method to those that want to learn or use reservoir simulation technology and even python or machine learning. Anyone is welcome to participate. 36 | ### About me 37 | **Wang Tao, Co-Founder of XXSim reservoir simulation software** 38 | *Reservoir simulation engineer, C++ coder* 39 | Found more about Wang Tao check out these links: 40 | [LinkedIn](https://www.linkedin.com/in/tao-wang-xxsim/ "Linkedin") | [AAPG Blog](https://www.aapg.org/publications/blogs/learn/article/Articleid/42130/interview-with-tao-wang-pecloud "aapg") | [Twitter](https://twitter.com/wangtao74 "Twitter") | [Website](https://www.peclouds.com "peclouds") 41 | -------------------------------------------------------------------------------- /Tutor 2/gridsection.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import matplotlib.pyplot as plt 5 | import xlwings as xw 6 | 7 | 8 | gridVaryOpt={ } 9 | defaultDim = 200 10 | kwMap = {'dx':'DX','dy':'DY','dz':'DZ','por':'POROSITY','permx':'KX','permy':'PERMY', 11 | 'permz':'PERMZ'} 12 | 13 | 14 | def readGeneralInfo(sht): 15 | 16 | nx = sht.range('B3').options(numbers=int).value 17 | ny = sht.range('C3').options(numbers=int).value 18 | nz = sht.range('D3').options(numbers=int).value 19 | 20 | gridVaryOpt['xopt'] = sht.range('B4').value 21 | gridVaryOpt['yopt'] = sht.range('C4').value 22 | gridVaryOpt['zopt'] = sht.range('D4').value 23 | 24 | gridVaryOpt['por'] = sht.range('F3').value 25 | gridVaryOpt['kx'] = sht.range('G3').value 26 | gridVaryOpt['ky'] = sht.range('H3').value 27 | gridVaryOpt['kz'] = sht.range('I3').value 28 | 29 | return (nx,ny,nz) 30 | 31 | 32 | def reset(sht): 33 | 34 | whiteColor = (255,255,255) 35 | sht.range((9,3),(9,defaultDim+3-1)).color = whiteColor 36 | sht.range((10,3),(10,defaultDim+3-1)).color = whiteColor 37 | sht.range((11,3),(11,defaultDim+3-1)).color = whiteColor 38 | sht.range((17,3),(17,defaultDim+3-1)).color = whiteColor 39 | sht.range((18,3),(18,defaultDim+3-1)).color = whiteColor 40 | sht.range((19,3),(19,defaultDim+3-1)).color = whiteColor 41 | sht.range((20,3),(20,defaultDim+3-1)).color = whiteColor 42 | 43 | sht.range((9,3),(9,defaultDim+3-1)).value = "" 44 | sht.range((10,3),(10,defaultDim+3-1)).value = "" 45 | sht.range((11,3),(11,defaultDim+3-1)).value = "" 46 | sht.range((17,3),(17,defaultDim+3-1)).value = "" 47 | sht.range((18,3),(18,defaultDim+3-1)).value = "" 48 | sht.range((19,3),(19,defaultDim+3-1)).value = "" 49 | sht.range((20,3),(20,defaultDim+3-1)).value = "" 50 | 51 | def DxInterface(sht,gridDimn,backColor): 52 | if gridVaryOpt['xopt'] == 'CON': 53 | sht.range('A9').value = 'Grid Size: DX' 54 | sht.range('B9').value = 'Constant' 55 | sht.range('C9').color = backColor 56 | elif gridVaryOpt['xopt'] == 'XVAR': 57 | sht.range('A9').value = 'Grid Size: DX' 58 | sht.range('B9').value = 'Variable by X direction' 59 | sht.range((9,3),(9,gridDimn[0]+3-1)).color = backColor 60 | 61 | def DyInterface(sht,gridDimn,backColor): 62 | if gridVaryOpt['yopt'] == 'CON': 63 | sht.range('A10').value = 'Grid Size: DY' 64 | sht.range('B10').value = 'Constant' 65 | sht.range('C10').color = backColor 66 | elif gridVaryOpt['yopt'] == 'YVAR': 67 | sht.range('A10').value = 'Grid Size: DY' 68 | sht.range('B10').value = 'Variable by Y direction' 69 | sht.range((10,3),(10,gridDimn[1]+3-1)).color = backColor 70 | 71 | def DzInterface(sht,gridDimn,backColor): 72 | if gridVaryOpt['zopt'] == 'CON': 73 | sht.range('A11').value = 'Grid Size: DZ' 74 | sht.range('B11').value = 'Constant' 75 | sht.range('C11').color = backColor 76 | elif gridVaryOpt['zopt'] == 'ZVAR': 77 | sht.range('A11').value = 'Grid Size: DZ' 78 | sht.range('B11').value = 'Variable by Z direction' 79 | sht.range((11,3),(11,gridDimn[2]+3-1)).color = backColor 80 | 81 | def PoroInterface(sht,gridDimn,backColor): 82 | if gridVaryOpt['por'] == 'CON': 83 | sht.range('A17').value = 'Porosity' 84 | sht.range('B17').value = 'Constant' 85 | sht.range('C17').color = backColor 86 | elif gridVaryOpt['por'] == 'ZVAR': 87 | sht.range('A17').value = 'Porosity' 88 | sht.range('B17').value = 'Variable by Z direction' 89 | sht.range((17,3),(17,gridDimn[2]+3-1)).color = backColor 90 | 91 | def PermxInterface(sht,gridDimn,backColor): 92 | if gridVaryOpt['kx'] == 'CON': 93 | sht.range('A18').value = 'PERMX' 94 | sht.range('B18').value = 'Constant' 95 | sht.range('C18').color = backColor 96 | elif gridVaryOpt['kx'] == 'ZVAR': 97 | sht.range('A18').value = 'PERMX' 98 | sht.range('B18').value = 'Variable by Z direction' 99 | sht.range((18,3),(18,gridDimn[2]+3-1)).color = backColor 100 | 101 | def PermyInterface(sht,gridDimn,backColor): 102 | if gridVaryOpt['ky'] == 'CON': 103 | sht.range('A19').value = 'PERMY' 104 | sht.range('B19').value = 'Constant' 105 | sht.range('C19').color = backColor 106 | elif gridVaryOpt['ky'] == 'ZVAR': 107 | sht.range('A19').value = 'PERMY' 108 | sht.range('B19').value = 'Variable by Z direction' 109 | sht.range((19,3),(19,gridDimn[2]+3-1)).color = backColor 110 | 111 | def PermzInterface(sht,gridDimn,backColor): 112 | if gridVaryOpt['kz'] == 'CON': 113 | sht.range('A20').value = 'PERMZ' 114 | sht.range('B20').value = 'Constant' 115 | sht.range('C20').color = backColor 116 | elif gridVaryOpt['kz'] == 'ZVAR': 117 | sht.range('A20').value = 'PERMZ' 118 | sht.range('B20').value = 'Variable by Z direction' 119 | sht.range((20,3),(20,gridDimn[2]+3-1)).color = backColor 120 | 121 | def GridStep0(): 122 | 123 | greenColor = (102,255,102) 124 | 125 | sht = xw.Book.caller().sheets[1] 126 | 127 | reset(sht) 128 | 129 | gridDimension = readGeneralInfo(sht) 130 | 131 | DxInterface(sht,gridDimension,greenColor) 132 | 133 | DyInterface(sht,gridDimension,greenColor) 134 | 135 | DzInterface(sht,gridDimension,greenColor) 136 | 137 | PoroInterface(sht,gridDimension,greenColor) 138 | 139 | PermxInterface(sht,gridDimension,greenColor) 140 | 141 | PermyInterface(sht,gridDimension,greenColor) 142 | 143 | PermzInterface(sht,gridDimension,greenColor) 144 | -------------------------------------------------------------------------------- /Tutor 2/tutor2.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import numpy as np 5 | import pandas as pd 6 | import matplotlib.pyplot as plt 7 | from mpl_toolkits.mplot3d import Axes3D 8 | from matplotlib import cm 9 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 10 | 11 | import xlwings as xw 12 | 13 | import datetime 14 | 15 | class CWell: 16 | wellCount = 0 17 | 18 | def __init__(self, name, hI,hJ): 19 | self.name = name 20 | self.head_I = hI 21 | self.head_J = hJ 22 | CWell.wellCount += 1 23 | self.id = CWell.wellCount 24 | 25 | 26 | def getKeyWordBeginRow(sht,iRow,strKW): 27 | index = 'A' 28 | while (sht.range(index+str(iRow)).value != strKW): 29 | iRow = iRow+1 30 | 31 | return iRow 32 | 33 | def getKeyWordEndRow(sht,irow): 34 | irow = irow+1 35 | index = 'B' 36 | while (sht.range(index+str(irow)).value != None): 37 | irow = irow+1 38 | 39 | return irow-1 40 | 41 | def draw2YCurve(ax,title,xlabel,leftMaps,rightMaps): 42 | lineColor = ['b+-','ro-','gs-','h--'] 43 | lmaxV = 0 44 | lminV = 10000 45 | rmaxV = 0 46 | rminV = 10000 47 | 48 | for lMap in leftMaps: 49 | x = lMap['x'] 50 | y = lMap['y'] 51 | i = lMap['id'] 52 | ax.plot(x,y,lineColor[i],lw=2,label=lMap['ylabel']) 53 | 54 | maxNum = max(y) 55 | minNum = min(y) 56 | if(maxNum>lmaxV): 57 | lmaxV = maxNum 58 | if(minNumrmaxV): 72 | rmaxV = maxNum 73 | if(minNum0): 82 | ax2.legend(loc='upper right') 83 | ax2.set_ylim(rminV,rmaxV) 84 | 85 | def drawWells(wells): 86 | fig = plt.figure('WELL PRODUCTION') 87 | 88 | wellNUm = len(wells) 89 | subRow = int(wellNUm/2) 90 | if(wellNUm%2>0): 91 | subRow += 1 92 | wellId = 1 93 | for well in wells.values(): 94 | wellName = well.name 95 | df_prod = well.df_prod 96 | df_prod['Date'] = df_prod['Date'].astype('int64') 97 | df_prod['Date'] = pd.to_datetime(df_prod['Date'],format="%Y%m") 98 | x = df_prod['Date'] 99 | 100 | y1 = df_prod[u'Monthly Oil Production'] 101 | y2 = df_prod[u'Monthly Water Production'] 102 | 103 | ax = fig.add_subplot(subRow,2,wellId) 104 | 105 | lMap1 = {'x':x,'y':y1,'id':0,'ylabel':'Monthly Oil Production Rate'} 106 | lMap2 = {'x':x,'y':y2,'id':1,'ylabel':'Monthly Water Production Rate'} 107 | leftMaps = [lMap1,lMap2] 108 | rightMaps = [] 109 | 110 | draw2YCurve(ax,wellName,'Date',leftMaps,rightMaps) 111 | 112 | wellId += 1 113 | 114 | plt.show() 115 | 116 | def readDynamicSection(sht): 117 | iRow = 1 118 | index = 'A' 119 | wells = {} 120 | while (sht.range(index+str(iRow)).value!='END'): 121 | iRow = iRow+1 122 | kw = sht.range(index+str(iRow)).value 123 | if(kw==u'Well Name'): 124 | wellName = sht.range('B'+str(iRow)).value 125 | iwellDefRow = getKeyWordBeginRow(sht,iRow,u'well type') 126 | head_I = sht.range('D'+str(iwellDefRow)).options(numbers=int).value 127 | head_J = sht.range('F'+str(iwellDefRow)).options(numbers=int).value 128 | well = CWell(wellName,head_I,head_J) 129 | wells[wellName] = well 130 | 131 | elif(kw == u'Well Completion'): 132 | comp = [] 133 | wName = sht.range('B'+str(iRow)).value 134 | well = wells.get(wName) 135 | iRow = iRow + 3 136 | iEndComp = getKeyWordEndRow(sht,iRow) 137 | for i_layer in range(iRow,iEndComp+1): 138 | nLayer = sht.range('D'+str(i_layer)).options(numbers=int).value 139 | comp.append(nLayer) 140 | 141 | iRow = iEndComp 142 | well.comp = comp 143 | 144 | elif(kw == u'Production'): 145 | wName = sht.range('A'+str(iRow+1)).value 146 | iEndProdRow = getKeyWordEndRow(sht,iRow) 147 | prod_date = sht.range((iRow+1,2),(iEndProdRow,2)).options(numbers=str).value 148 | df_prod = sht.range((iRow,2),(iEndProdRow,7)).options(pd.DataFrame,index=False).value 149 | iRow = iEndProdRow 150 | 151 | 152 | well = wells.get(wName) 153 | well.df_prod = df_prod 154 | 155 | 156 | np_prodDate = np.array(prod_date) 157 | asciiList = [n.encode("ascii", "ignore") for n in np_prodDate] 158 | well.prod_date = asciiList 159 | 160 | drawWells(wells) 161 | 162 | def DynamicStep0(): 163 | 164 | sht = xw.Book.caller().sheets[0] 165 | 166 | readDynamicSection(sht) 167 | 168 | ''' 169 | if __name__ == '__main__': 170 | # Expects the Excel file next to this source file, adjust accordingly. 171 | xw.Book('tutor2.xlsm').set_mock_caller() 172 | DynamicStep0() 173 | ''' -------------------------------------------------------------------------------- /Tutor 2/tutor2.xlsm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/Tutor 2/tutor2.xlsm -------------------------------------------------------------------------------- /Tutor 3/dynamicsection.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import numpy as np 5 | import pandas as pd 6 | import matplotlib.pyplot as plt 7 | from mpl_toolkits.mplot3d import Axes3D 8 | from matplotlib import cm 9 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 10 | 11 | import xlwings as xw 12 | 13 | import datetime 14 | 15 | class CWell: 16 | wellCount = 0 17 | 18 | def __init__(self, name, hI,hJ): 19 | self.name = name 20 | self.head_I = hI 21 | self.head_J = hJ 22 | CWell.wellCount += 1 23 | self.id = CWell.wellCount 24 | 25 | 26 | def getKeyWordBeginRow(sht,iRow,strKW): 27 | index = 'A' 28 | while (sht.range(index+str(iRow)).value != strKW): 29 | iRow = iRow+1 30 | 31 | return iRow 32 | 33 | def getKeyWordEndRow(sht,irow): 34 | irow = irow+1 35 | index = 'B' 36 | while (sht.range(index+str(irow)).value != None): 37 | irow = irow+1 38 | 39 | return irow-1 40 | 41 | def draw2YCurve(ax,title,xlabel,leftMaps,rightMaps): 42 | lineColor = ['b+-','ro-','gs-','h--'] 43 | lmaxV = 0 44 | lminV = 10000 45 | rmaxV = 0 46 | rminV = 10000 47 | 48 | for lMap in leftMaps: 49 | x = lMap['x'] 50 | y = lMap['y'] 51 | i = lMap['id'] 52 | ax.plot(x,y,lineColor[i],lw=2,label=lMap['ylabel']) 53 | 54 | maxNum = max(y) 55 | minNum = min(y) 56 | if(maxNum>lmaxV): 57 | lmaxV = maxNum 58 | if(minNumrmaxV): 72 | rmaxV = maxNum 73 | if(minNum0): 82 | ax2.legend(loc='upper right') 83 | ax2.set_ylim(rminV,rmaxV) 84 | 85 | def drawWells(wells): 86 | fig = plt.figure('WELL PRODUCTION') 87 | 88 | wellNUm = len(wells) 89 | subRow = int(wellNUm/2) 90 | if(wellNUm%2>0): 91 | subRow += 1 92 | wellId = 1 93 | for well in wells.values(): 94 | wellName = well.name 95 | df_prod = well.df_prod 96 | df_prod['Date'] = df_prod['Date'].astype('int64') 97 | df_prod['Date'] = pd.to_datetime(df_prod['Date'],format="%Y%m") 98 | x = df_prod['Date'] 99 | 100 | y1 = df_prod[u'Monthly Oil Production'] 101 | y2 = df_prod[u'Monthly Water Production'] 102 | 103 | ax = fig.add_subplot(subRow,2,wellId) 104 | 105 | lMap1 = {'x':x,'y':y1,'id':0,'ylabel':'Monthly Oil Production Rate'} 106 | lMap2 = {'x':x,'y':y2,'id':1,'ylabel':'Monthly Water Production Rate'} 107 | leftMaps = [lMap1,lMap2] 108 | rightMaps = [] 109 | 110 | draw2YCurve(ax,wellName,'Date',leftMaps,rightMaps) 111 | 112 | wellId += 1 113 | 114 | plt.show() 115 | 116 | def readDynamicSection(sht): 117 | iRow = 1 118 | index = 'A' 119 | wells = {} 120 | while (sht.range(index+str(iRow)).value!='END'): 121 | iRow = iRow+1 122 | kw = sht.range(index+str(iRow)).value 123 | if(kw==u'Well Name'): 124 | wellName = sht.range('B'+str(iRow)).value 125 | iwellDefRow = getKeyWordBeginRow(sht,iRow,u'well type') 126 | head_I = sht.range('D'+str(iwellDefRow)).options(numbers=int).value 127 | head_J = sht.range('F'+str(iwellDefRow)).options(numbers=int).value 128 | well = CWell(wellName,head_I,head_J) 129 | wells[wellName] = well 130 | 131 | elif(kw == u'Well Completion'): 132 | comp = [] 133 | wName = sht.range('B'+str(iRow)).value 134 | well = wells.get(wName) 135 | iRow = iRow + 3 136 | iEndComp = getKeyWordEndRow(sht,iRow) 137 | for i_layer in range(iRow,iEndComp+1): 138 | nLayer = sht.range('D'+str(i_layer)).options(numbers=int).value 139 | comp.append(nLayer) 140 | 141 | iRow = iEndComp 142 | well.comp = comp 143 | 144 | elif(kw == u'Production'): 145 | wName = sht.range('A'+str(iRow+1)).value 146 | iEndProdRow = getKeyWordEndRow(sht,iRow) 147 | prod_date = sht.range((iRow+1,2),(iEndProdRow,2)).options(numbers=str).value 148 | df_prod = sht.range((iRow,2),(iEndProdRow,7)).options(pd.DataFrame,index=False).value 149 | iRow = iEndProdRow 150 | 151 | 152 | well = wells.get(wName) 153 | well.df_prod = df_prod 154 | 155 | 156 | np_prodDate = np.array(prod_date) 157 | asciiList = [n.encode("ascii", "ignore") for n in np_prodDate] 158 | well.prod_date = asciiList 159 | 160 | drawWells(wells) 161 | 162 | def DynamicStep0(): 163 | 164 | sht = xw.Book.caller().sheets[1] 165 | 166 | readDynamicSection(sht) 167 | 168 | ''' 169 | if __name__ == '__main__': 170 | # Expects the Excel file next to this source file, adjust accordingly. 171 | xw.Book('tutor2.xlsm').set_mock_caller() 172 | DynamicStep0() 173 | ''' -------------------------------------------------------------------------------- /Tutor 3/gridsection.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import matplotlib.pyplot as plt 5 | import xlwings as xw 6 | 7 | 8 | gridVaryOpt={ } 9 | defaultDim = 200 10 | kwMap = {'dx':'DX','dy':'DY','dz':'DZ','por':'POROSITY','permx':'KX','permy':'PERMY', 11 | 'permz':'PERMZ'} 12 | 13 | 14 | def readGeneralInfo(sht): 15 | 16 | nx = sht.range('B3').options(numbers=int).value 17 | ny = sht.range('C3').options(numbers=int).value 18 | nz = sht.range('D3').options(numbers=int).value 19 | 20 | gridVaryOpt['xopt'] = sht.range('B4').value 21 | gridVaryOpt['yopt'] = sht.range('C4').value 22 | gridVaryOpt['zopt'] = sht.range('D4').value 23 | 24 | gridVaryOpt['por'] = sht.range('F3').value 25 | gridVaryOpt['kx'] = sht.range('G3').value 26 | gridVaryOpt['ky'] = sht.range('H3').value 27 | gridVaryOpt['kz'] = sht.range('I3').value 28 | 29 | return (nx,ny,nz) 30 | 31 | 32 | def reset(sht): 33 | 34 | whiteColor = (255,255,255) 35 | sht.range((9,3),(9,defaultDim+3-1)).color = whiteColor 36 | sht.range((10,3),(10,defaultDim+3-1)).color = whiteColor 37 | sht.range((11,3),(11,defaultDim+3-1)).color = whiteColor 38 | sht.range((17,3),(17,defaultDim+3-1)).color = whiteColor 39 | sht.range((18,3),(18,defaultDim+3-1)).color = whiteColor 40 | sht.range((19,3),(19,defaultDim+3-1)).color = whiteColor 41 | sht.range((20,3),(20,defaultDim+3-1)).color = whiteColor 42 | 43 | sht.range((9,3),(9,defaultDim+3-1)).value = "" 44 | sht.range((10,3),(10,defaultDim+3-1)).value = "" 45 | sht.range((11,3),(11,defaultDim+3-1)).value = "" 46 | sht.range((17,3),(17,defaultDim+3-1)).value = "" 47 | sht.range((18,3),(18,defaultDim+3-1)).value = "" 48 | sht.range((19,3),(19,defaultDim+3-1)).value = "" 49 | sht.range((20,3),(20,defaultDim+3-1)).value = "" 50 | 51 | def DxInterface(sht,gridDimn,backColor): 52 | if gridVaryOpt['xopt'] == 'CON': 53 | sht.range('A9').value = 'Grid Size: DX' 54 | sht.range('B9').value = 'Constant' 55 | sht.range('C9').color = backColor 56 | elif gridVaryOpt['xopt'] == 'XVAR': 57 | sht.range('A9').value = 'Grid Size: DX' 58 | sht.range('B9').value = 'Variable by X direction' 59 | sht.range((9,3),(9,gridDimn[0]+3-1)).color = backColor 60 | 61 | def DyInterface(sht,gridDimn,backColor): 62 | if gridVaryOpt['yopt'] == 'CON': 63 | sht.range('A10').value = 'Grid Size: DY' 64 | sht.range('B10').value = 'Constant' 65 | sht.range('C10').color = backColor 66 | elif gridVaryOpt['yopt'] == 'YVAR': 67 | sht.range('A10').value = 'Grid Size: DY' 68 | sht.range('B10').value = 'Variable by Y direction' 69 | sht.range((10,3),(10,gridDimn[1]+3-1)).color = backColor 70 | 71 | def DzInterface(sht,gridDimn,backColor): 72 | if gridVaryOpt['zopt'] == 'CON': 73 | sht.range('A11').value = 'Grid Size: DZ' 74 | sht.range('B11').value = 'Constant' 75 | sht.range('C11').color = backColor 76 | elif gridVaryOpt['zopt'] == 'ZVAR': 77 | sht.range('A11').value = 'Grid Size: DZ' 78 | sht.range('B11').value = 'Variable by Z direction' 79 | sht.range((11,3),(11,gridDimn[2]+3-1)).color = backColor 80 | 81 | def PoroInterface(sht,gridDimn,backColor): 82 | if gridVaryOpt['por'] == 'CON': 83 | sht.range('A17').value = 'Porosity' 84 | sht.range('B17').value = 'Constant' 85 | sht.range('C17').color = backColor 86 | elif gridVaryOpt['por'] == 'ZVAR': 87 | sht.range('A17').value = 'Porosity' 88 | sht.range('B17').value = 'Variable by Z direction' 89 | sht.range((17,3),(17,gridDimn[2]+3-1)).color = backColor 90 | 91 | def PermxInterface(sht,gridDimn,backColor): 92 | if gridVaryOpt['kx'] == 'CON': 93 | sht.range('A18').value = 'PERMX' 94 | sht.range('B18').value = 'Constant' 95 | sht.range('C18').color = backColor 96 | elif gridVaryOpt['kx'] == 'ZVAR': 97 | sht.range('A18').value = 'PERMX' 98 | sht.range('B18').value = 'Variable by Z direction' 99 | sht.range((18,3),(18,gridDimn[2]+3-1)).color = backColor 100 | 101 | def PermyInterface(sht,gridDimn,backColor): 102 | if gridVaryOpt['ky'] == 'CON': 103 | sht.range('A19').value = 'PERMY' 104 | sht.range('B19').value = 'Constant' 105 | sht.range('C19').color = backColor 106 | elif gridVaryOpt['ky'] == 'ZVAR': 107 | sht.range('A19').value = 'PERMY' 108 | sht.range('B19').value = 'Variable by Z direction' 109 | sht.range((19,3),(19,gridDimn[2]+3-1)).color = backColor 110 | 111 | def PermzInterface(sht,gridDimn,backColor): 112 | if gridVaryOpt['kz'] == 'CON': 113 | sht.range('A20').value = 'PERMZ' 114 | sht.range('B20').value = 'Constant' 115 | sht.range('C20').color = backColor 116 | elif gridVaryOpt['kz'] == 'ZVAR': 117 | sht.range('A20').value = 'PERMZ' 118 | sht.range('B20').value = 'Variable by Z direction' 119 | sht.range((20,3),(20,gridDimn[2]+3-1)).color = backColor 120 | 121 | def GridStep0(): 122 | 123 | greenColor = (102,255,102) 124 | 125 | sht = xw.Book.caller().sheets[1] 126 | 127 | reset(sht) 128 | 129 | gridDimension = readGeneralInfo(sht) 130 | 131 | DxInterface(sht,gridDimension,greenColor) 132 | 133 | DyInterface(sht,gridDimension,greenColor) 134 | 135 | DzInterface(sht,gridDimension,greenColor) 136 | 137 | PoroInterface(sht,gridDimension,greenColor) 138 | 139 | PermxInterface(sht,gridDimension,greenColor) 140 | 141 | PermyInterface(sht,gridDimension,greenColor) 142 | 143 | PermzInterface(sht,gridDimension,greenColor) 144 | -------------------------------------------------------------------------------- /Tutor 3/propertysection.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import numpy as np 5 | import pandas as pd 6 | import matplotlib.pyplot as plt 7 | from mpl_toolkits.mplot3d import Axes3D 8 | from matplotlib import cm 9 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 10 | 11 | import xlwings as xw 12 | 13 | def getKeyWordBeginRow(sht,iRow,strKW): 14 | index = 'A' 15 | while (sht.range(index+str(iRow)).value != strKW): 16 | iRow = iRow+1 17 | 18 | return iRow 19 | 20 | def getKeyWordEndRow(sht,irow): 21 | irow = irow+1 22 | index = 'B' 23 | while (sht.range(index+str(irow)).value != None): 24 | irow = irow+1 25 | 26 | return irow-1 27 | 28 | def draw2YCurve(ax,title,xlabel,leftMaps,rightMaps): 29 | lineColor = ['b+-','ro-','gs-','h--'] 30 | lmaxV = 0 31 | lminV = 10000 32 | rmaxV = 0 33 | rminV = 10000 34 | 35 | for lMap in leftMaps: 36 | x = lMap['x'] 37 | y = lMap['y'] 38 | i = lMap['id'] 39 | ax.plot(x,y,lineColor[i],lw=2,label=lMap['ylabel']) 40 | 41 | maxNum = max(y) 42 | minNum = min(y) 43 | if(maxNum>lmaxV): 44 | lmaxV = maxNum 45 | if(minNumrmaxV): 59 | rmaxV = maxNum 60 | if(minNum0): 69 | ax2.legend(loc='upper right') 70 | ax2.set_ylim(rminV,rmaxV) 71 | 72 | def drawCurve(ax,xlabel,curvelegend,x,yArray): 73 | 74 | lineColor = ['b+-','ro-','gs-','h--'] 75 | 76 | for i,y in enumerate(yArray): 77 | ax.plot(x, y, lineColor[i], lw=2, zorder=30) 78 | 79 | ax.grid() 80 | ax.set_xlabel(xlabel, fontweight='bold', fontsize=15) 81 | ax.set_xticklabels([]) 82 | ax.set_yticklabels([]) 83 | 84 | ax.legend(ax.lines, curvelegend, fancybox=True, shadow=True, prop={'size': 15}) 85 | 86 | def drawPvtCurve(pvt): 87 | fig = plt.figure('PVT') 88 | 89 | # draw pvt_oil 90 | df_PVTo = pvt[0] 91 | o_x = df_PVTo['P'] 92 | o_y0 = df_PVTo['MUO'] 93 | o_y1 = df_PVTo['BO'] 94 | o_y2 = df_PVTo['RSO'] 95 | 96 | ax = fig.add_subplot(2,1,1) 97 | 98 | lMap1 = {'x':o_x,'y':o_y0,'id':0,'ylabel':'MUO'} 99 | lMap2 = {'x':o_x,'y':o_y1,'id':1,'ylabel':'BO'} 100 | rMap = {'x':o_x,'y':o_y2,'id':2,'ylabel':'RSO'} 101 | leftMaps = [lMap1,lMap2] 102 | rightMaps = [rMap] 103 | 104 | draw2YCurve(ax,'Oil PVT','P',leftMaps,rightMaps) 105 | 106 | # draw pvt_gas 107 | df_PVTg = pvt[2] 108 | g_x = df_PVTg['P'] 109 | g_y0 = df_PVTg['MUG'] 110 | g_y1 = df_PVTg['BG'] 111 | 112 | ax = fig.add_subplot(2,1,2) 113 | 114 | lMap1 = {'x':g_x,'y':g_y0,'id':0,'ylabel':'MUG'} 115 | lMap2 = {'x':g_x,'y':g_y1,'id':1,'ylabel':'BG'} 116 | leftMaps = [lMap1,lMap2] 117 | rightMaps = [] 118 | 119 | draw2YCurve(ax,'Gas PVT','P',leftMaps,rightMaps) 120 | 121 | plt.show() 122 | 123 | def readPvt(sht): 124 | iRowPvtSec= getKeyWordBeginRow(sht,1,'PVT') 125 | 126 | iRowPbo = getKeyWordBeginRow(sht,iRowPvtSec,'PBO') 127 | fPbo = sht.range((iRowPbo,2),(iRowPbo,2)).value 128 | iRowMuo_s = getKeyWordBeginRow(sht,iRowPvtSec,'Viso_SLOPE') 129 | fMuo_s = sht.range((iRowMuo_s,2),(iRowMuo_s,2)).value 130 | iRowBo_s = getKeyWordBeginRow(sht,iRowPvtSec,'Bo_SLOPE') 131 | fBo_s = sht.range((iRowBo_s,2),(iRowBo_s,2)).value 132 | 133 | iRowBegin = getKeyWordBeginRow(sht,iRowPvtSec,'OIL-PVT') 134 | iRowEnd = getKeyWordEndRow(sht,iRowBegin) 135 | 136 | df_PVTo = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 137 | 138 | 139 | # pvtw 140 | iRowBegin = getKeyWordBeginRow(sht,iRowPvtSec,'WATER-PVT') 141 | iRowEnd = getKeyWordEndRow(sht,iRowBegin) 142 | df_PVTw = sht.range((iRowBegin,2),(iRowEnd,4)).options(pd.DataFrame,index=False).value 143 | df_to_nparray = df_PVTw.to_records(index=True) 144 | 145 | # pvtg 146 | iRowBegin = getKeyWordBeginRow(sht,iRowPvtSec,'GAS-PVT') 147 | iRowEnd = getKeyWordEndRow(sht,iRowBegin) 148 | df_PVTg = sht.range((iRowBegin,2),(iRowEnd,4)).options(pd.DataFrame,index=False).value 149 | 150 | # density 151 | iDenRow = getKeyWordBeginRow(sht,iRowPvtSec,u'DENSITY') 152 | df_density = sht.range((iDenRow,2),(iDenRow+1,4)).options(pd.DataFrame).value 153 | 154 | # rock 155 | iRockRow = getKeyWordBeginRow(sht,iRowPvtSec,u'CROCK') 156 | fRock = sht.range((iRockRow,3),(iRockRow,3)).value 157 | 158 | return (df_PVTo,df_PVTw,df_PVTg) 159 | 160 | def drawRelPermCurve(relPerm): 161 | fig = plt.figure('Rel. Perm') 162 | 163 | # OIL-WATER 164 | df_SWOF = relPerm[0] 165 | 166 | wo_x = df_SWOF['SAT'] 167 | wo_y0 = df_SWOF['KRW'] 168 | wo_y1 = df_SWOF['KROW'] 169 | 170 | wo_yArray = [wo_y0,wo_y1] 171 | ax = fig.add_subplot(2,1,1) 172 | 173 | drawCurve(ax,'SAT',['KRW','KROW'],wo_x,wo_yArray) 174 | 175 | # GAS-LIQUID 176 | df_SGLF = relPerm[1] 177 | 178 | x = df_SGLF['SLIQ'] 179 | y0 = df_SGLF['KRG'] 180 | y1 = df_SGLF['KROG'] 181 | 182 | yArray = [y0,y1] 183 | ax = fig.add_subplot(2,1,2) 184 | 185 | drawCurve(ax,'SLIQ',['KRG','KROG'],x,yArray) 186 | 187 | plt.show() 188 | 189 | 190 | def readRelativePerm(sht): 191 | iRowPvtSec= getKeyWordBeginRow(sht,1,'PVT') 192 | # water-oil 193 | iRowBegin = getKeyWordBeginRow(sht,iRowPvtSec,'WATER-OIL') 194 | iRowEnd = getKeyWordEndRow(sht,iRowBegin) 195 | 196 | df_SWOF = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 197 | 198 | # GAS-LIQUID 199 | iRowBegin = getKeyWordBeginRow(sht,iRowPvtSec,'GAS-LIQUID') 200 | iRowEnd = getKeyWordEndRow(sht,iRowBegin) 201 | 202 | df_SGLF = sht.range((iRowBegin,2),(iRowEnd,5)).options(pd.DataFrame,index=False).value 203 | 204 | return (df_SWOF,df_SGLF) 205 | 206 | def Pvt(): 207 | sht = xw.Book.caller().sheets[0] 208 | pvt = readPvt(sht) 209 | drawPvtCurve(pvt) 210 | 211 | 212 | def RelPerm(): 213 | sht = xw.Book.caller().sheets[0] 214 | relPerm = readRelativePerm(sht) 215 | drawRelPermCurve(relPerm) 216 | 217 | ''' 218 | def readPropSection(sht): 219 | pvt = readPvt(sht) 220 | drawPvtCurve(pvt) 221 | 222 | relPerm = readRelativePerm(sht) 223 | drawRelPermCurve(relPerm) 224 | 225 | if __name__ == '__main__': 226 | # Expects the Excel file next to this source file, adjust accordingly. 227 | xw.Book('tutor3.xlsm').set_mock_caller() 228 | 229 | sht = xw.Book.caller().sheets[0] 230 | 231 | readPropSection(sht) 232 | ''' -------------------------------------------------------------------------------- /Tutor 3/tutor3.xlsm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/Tutor 3/tutor3.xlsm -------------------------------------------------------------------------------- /material/pythonExcel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/material/pythonExcel.png -------------------------------------------------------------------------------- /material/tutor1.2019-02-14.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/material/tutor1.2019-02-14.gif -------------------------------------------------------------------------------- /material/tutor2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/material/tutor2.gif -------------------------------------------------------------------------------- /tutor1.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import sys 3 | import os 4 | import matplotlib.pyplot as plt 5 | import xlwings as xw 6 | 7 | 8 | sht = xw.Book.caller().sheets[0] 9 | gridVaryOpt={ } 10 | defaultDim = 200 11 | kwMap = {'dx':'DX','dy':'DY','dz':'DZ','por':'POROSITY','permx':'KX','permy':'PERMY', 12 | 'permz':'PERMZ'} 13 | 14 | 15 | def readGeneralInfo(): 16 | nx = sht.range('B3').options(numbers=int).value 17 | ny = sht.range('C3').options(numbers=int).value 18 | nz = sht.range('D3').options(numbers=int).value 19 | 20 | gridVaryOpt['xopt'] = sht.range('B4').value 21 | gridVaryOpt['yopt'] = sht.range('C4').value 22 | gridVaryOpt['zopt'] = sht.range('D4').value 23 | 24 | gridVaryOpt['por'] = sht.range('F3').value 25 | gridVaryOpt['kx'] = sht.range('G3').value 26 | gridVaryOpt['ky'] = sht.range('H3').value 27 | gridVaryOpt['kz'] = sht.range('I3').value 28 | 29 | return (nx,ny,nz) 30 | 31 | 32 | def reset(): 33 | 34 | whiteColor = (255,255,255) 35 | sht.range((9,3),(9,defaultDim+3-1)).color = whiteColor 36 | sht.range((10,3),(10,defaultDim+3-1)).color = whiteColor 37 | sht.range((11,3),(11,defaultDim+3-1)).color = whiteColor 38 | sht.range((17,3),(17,defaultDim+3-1)).color = whiteColor 39 | sht.range((18,3),(18,defaultDim+3-1)).color = whiteColor 40 | sht.range((19,3),(19,defaultDim+3-1)).color = whiteColor 41 | sht.range((20,3),(20,defaultDim+3-1)).color = whiteColor 42 | 43 | sht.range((9,3),(9,defaultDim+3-1)).value = "" 44 | sht.range((10,3),(10,defaultDim+3-1)).value = "" 45 | sht.range((11,3),(11,defaultDim+3-1)).value = "" 46 | sht.range((17,3),(17,defaultDim+3-1)).value = "" 47 | sht.range((18,3),(18,defaultDim+3-1)).value = "" 48 | sht.range((19,3),(19,defaultDim+3-1)).value = "" 49 | sht.range((20,3),(20,defaultDim+3-1)).value = "" 50 | 51 | def DxInterface(gridDimn,backColor): 52 | if gridVaryOpt['xopt'] == 'CON': 53 | sht.range('A9').value = 'Grid Size: DX' 54 | sht.range('B9').value = 'Constant' 55 | sht.range('C9').color = backColor 56 | elif gridVaryOpt['xopt'] == 'XVAR': 57 | sht.range('A9').value = 'Grid Size: DX' 58 | sht.range('B9').value = 'Variable by X direction' 59 | sht.range((9,3),(9,gridDimn[0]+3-1)).color = backColor 60 | 61 | def DyInterface(gridDimn,backColor): 62 | if gridVaryOpt['yopt'] == 'CON': 63 | sht.range('A10').value = 'Grid Size: DY' 64 | sht.range('B10').value = 'Constant' 65 | sht.range('C10').color = backColor 66 | elif gridVaryOpt['yopt'] == 'YVAR': 67 | sht.range('A10').value = 'Grid Size: DY' 68 | sht.range('B10').value = 'Variable by Y direction' 69 | sht.range((10,3),(10,gridDimn[1]+3-1)).color = backColor 70 | 71 | def DzInterface(gridDimn,backColor): 72 | if gridVaryOpt['zopt'] == 'CON': 73 | sht.range('A11').value = 'Grid Size: DZ' 74 | sht.range('B11').value = 'Constant' 75 | sht.range('C11').color = backColor 76 | elif gridVaryOpt['zopt'] == 'ZVAR': 77 | sht.range('A11').value = 'Grid Size: DZ' 78 | sht.range('B11').value = 'Variable by Z direction' 79 | sht.range((11,3),(11,gridDimn[2]+3-1)).color = backColor 80 | 81 | def PoroInterface(gridDimn,backColor): 82 | if gridVaryOpt['por'] == 'CON': 83 | sht.range('A17').value = 'Porosity' 84 | sht.range('B17').value = 'Constant' 85 | sht.range('C17').color = backColor 86 | elif gridVaryOpt['por'] == 'ZVAR': 87 | sht.range('A17').value = 'Porosity' 88 | sht.range('B17').value = 'Variable by Z direction' 89 | sht.range((17,3),(17,gridDimn[2]+3-1)).color = backColor 90 | 91 | def PermxInterface(gridDimn,backColor): 92 | if gridVaryOpt['kx'] == 'CON': 93 | sht.range('A18').value = 'PERMX' 94 | sht.range('B18').value = 'Constant' 95 | sht.range('C18').color = backColor 96 | elif gridVaryOpt['kx'] == 'ZVAR': 97 | sht.range('A18').value = 'PERMX' 98 | sht.range('B18').value = 'Variable by Z direction' 99 | sht.range((18,3),(18,gridDimn[2]+3-1)).color = backColor 100 | 101 | def PermyInterface(gridDimn,backColor): 102 | if gridVaryOpt['ky'] == 'CON': 103 | sht.range('A19').value = 'PERMY' 104 | sht.range('B19').value = 'Constant' 105 | sht.range('C19').color = backColor 106 | elif gridVaryOpt['ky'] == 'ZVAR': 107 | sht.range('A19').value = 'PERMY' 108 | sht.range('B19').value = 'Variable by Z direction' 109 | sht.range((19,3),(19,gridDimn[2]+3-1)).color = backColor 110 | 111 | def PermzInterface(gridDimn,backColor): 112 | if gridVaryOpt['kz'] == 'CON': 113 | sht.range('A20').value = 'PERMZ' 114 | sht.range('B20').value = 'Constant' 115 | sht.range('C20').color = backColor 116 | elif gridVaryOpt['kz'] == 'ZVAR': 117 | sht.range('A20').value = 'PERMZ' 118 | sht.range('B20').value = 'Variable by Z direction' 119 | sht.range((20,3),(20,gridDimn[2]+3-1)).color = backColor 120 | 121 | def GridStep0(): 122 | 123 | greenColor = (102,255,102) 124 | 125 | reset() 126 | 127 | gridDimension = readGeneralInfo() 128 | 129 | DxInterface(gridDimension,greenColor) 130 | 131 | DyInterface(gridDimension,greenColor) 132 | 133 | DzInterface(gridDimension,greenColor) 134 | 135 | PoroInterface(gridDimension,greenColor) 136 | 137 | PermxInterface(gridDimension,greenColor) 138 | 139 | PermyInterface(gridDimension,greenColor) 140 | 141 | PermzInterface(gridDimension,greenColor) -------------------------------------------------------------------------------- /tutor1.xlsm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReservoirSimulator/ExcelPySim/107d2fd1089c81e099dce9f6f7e69500de46c1c1/tutor1.xlsm --------------------------------------------------------------------------------