Skip to content

Commit 718a8a8

Browse files
Merge pull request #68 from inwoo-park/plot
CHG: Python > Matlab - Fix to plotting functions in src/m.
2 parents dd92a3d + 688e545 commit 718a8a8

File tree

7 files changed

+336
-19
lines changed

7 files changed

+336
-19
lines changed

configure.ac

Lines changed: 63 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,20 +29,72 @@ AM_PROG_AR
2929
#Libtool
3030
LT_INIT([win32-dll])
3131

32-
#Run issm_options.m4
32+
# =====================================================================
33+
# Automatic-Differentiation switches
34+
# =====================================================================
35+
AC_ARG_ENABLE([ad],
36+
AS_HELP_STRING([--enable-ad],
37+
[Build ISSM with CoDiPack+MediPack (disables PETSc)]),
38+
[enable_ad=$enableval],
39+
[enable_ad=no])
40+
41+
AC_ARG_WITH([codipack-dir],
42+
AS_HELP_STRING([--with-codipack-dir=DIR], [Prefix of CoDiPack install]),
43+
[CODIPACK_DIR=$withval],
44+
[CODIPACK_DIR=])
45+
46+
AC_ARG_WITH([medipack-dir],
47+
AS_HELP_STRING([--with-medipack-dir=DIR], [Prefix of MediPack install]),
48+
[MEDIPACK_DIR=$withval],
49+
[MEDIPACK_DIR=])
50+
51+
# --- Validation & flag embedding -------------------------------------
52+
if test "x$enable_ad" = "xyes"; then
53+
if test -z "$CODIPACK_DIR" || test -z "$MEDIPACK_DIR"; then
54+
AC_MSG_ERROR([--enable-ad needs BOTH --with-codipack-dir and --with-medipack-dir])
55+
fi
56+
57+
# Tell source files we are in AD mode
58+
AC_DEFINE([ISSM_USE_AD], [1], [Define to 1 if building with automatic differentiation])
59+
60+
# Drop PETSc automatically (picked up by m4/issm_options.m4)
61+
ENABLE_PETSC=no
62+
AM_CONDITIONAL([USE_AD], [true])
63+
else
64+
ENABLE_PETSC=yes
65+
AM_CONDITIONAL([USE_AD], [false])
66+
fi
67+
68+
dnl ---- Embed include-paths, lib-paths & libs globally -----------------
69+
if test "x$enable_ad" = "xyes"; then
70+
AM_CPPFLAGS="$AM_CPPFLAGS -I$CODIPACK_DIR/include -I$MEDIPACK_DIR/include -DCODI_ForcedInlines"
71+
AM_LDFLAGS="$AM_LDFLAGS -L$CODIPACK_DIR/lib -L$MEDIPACK_DIR/lib"
72+
LIBS="$LIBS -lcodi -lmedi"
73+
fi
74+
75+
dnl Export the variables so Automake can substitute them
76+
AC_SUBST([AM_CPPFLAGS])
77+
AC_SUBST([AM_LDFLAGS])
78+
AC_SUBST([LIBS])
79+
80+
# ---------------------------------------------------------------------
81+
# Run ISSM’s usual option-detection macro collection
82+
# ---------------------------------------------------------------------
3383
ISSM_OPTIONS
84+
ISSM_ENABLE_AD
3485

35-
#List all Makefiles
86+
# ---------------------------------------------------------------------
87+
# Output files
88+
# ---------------------------------------------------------------------
3689
AC_CONFIG_FILES([
37-
Makefile
38-
src/Makefile
39-
src/c/Makefile
40-
src/wrappers/Makefile
41-
src/wrappers/python/Makefile
42-
src/wrappers/matlab/Makefile
43-
src/wrappers/javascript/Makefile
44-
src/m/Makefile
90+
Makefile
91+
src/Makefile
92+
src/c/Makefile
93+
src/m/Makefile
94+
src/wrappers/Makefile
95+
src/wrappers/python/Makefile
96+
src/wrappers/matlab/Makefile
97+
src/wrappers/javascript/Makefile
4598
])
4699

47-
#End of configure.ac
48100
AC_OUTPUT

m4/issm_options.m4

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2616,3 +2616,50 @@ AC_DEFUN([ISSM_OPTIONS],[
26162616
AC_SUBST([CXXFLAGS])
26172617
AC_SUBST([OSLIBS])
26182618
])
2619+
2620+
dnl =====================================================================
2621+
dnl ISSM_ENABLE_AD – Automatic-Differentiation (CoDiPack + MediPack)
2622+
dnl =====================================================================
2623+
AC_DEFUN([ISSM_ENABLE_AD], [
2624+
# --- command-line switches ------------------------------------------
2625+
AC_ARG_ENABLE([ad],
2626+
AS_HELP_STRING([--enable-ad],
2627+
[Build ISSM with CoDiPack+MediPack automatic differentiation (disables PETSc)]),
2628+
[enable_ad=$enableval],
2629+
[enable_ad=no])
2630+
2631+
AC_ARG_WITH([codipack-dir],
2632+
AS_HELP_STRING([--with-codipack-dir=DIR],
2633+
[Prefix of CoDiPack install]),
2634+
[CODIPACK_ROOT=$withval], [CODIPACK_ROOT=])
2635+
2636+
AC_ARG_WITH([medipack-dir],
2637+
AS_HELP_STRING([--with-medipack-dir=DIR],
2638+
[Prefix of MediPack install]),
2639+
[MEDIPACK_ROOT=$withval], [MEDIPACK_ROOT=])
2640+
2641+
# --- validation & flag injection ------------------------------------
2642+
if test "x$enable_ad" = "xyes"; then
2643+
if test -z "$CODIPACK_ROOT" || test -z "$MEDIPACK_ROOT"; then
2644+
AC_MSG_ERROR([--enable-ad needs BOTH --with-codipack-dir and --with-medipack-dir])
2645+
fi
2646+
2647+
AC_DEFINE([ISSM_USE_AD], [1],
2648+
[Define to 1 if building with automatic differentiation])
2649+
2650+
ENABLE_PETSC=no
2651+
AM_CONDITIONAL([USE_AD], [true])
2652+
2653+
AM_CPPFLAGS="$AM_CPPFLAGS -I$CODIPACK_ROOT/include -I$MEDIPACK_ROOT/include -DCODI_ForcedInlines"
2654+
AM_LDFLAGS="$AM_LDFLAGS -L$CODIPACK_ROOT/lib -L$MEDIPACK_ROOT/lib"
2655+
LIBS="$LIBS -lcodi -lmedi"
2656+
else
2657+
ENABLE_PETSC=yes
2658+
AM_CONDITIONAL([USE_AD], [false])
2659+
fi
2660+
2661+
dnl Export augmented vars once
2662+
AC_SUBST([AM_CPPFLAGS])
2663+
AC_SUBST([AM_LDFLAGS])
2664+
AC_SUBST([LIBS])
2665+
])

src/m/plot/applyoptions.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,12 @@ def applyoptions(md, data, options, fig, axgrid, gridindex):
139139
# }}}
140140
# {{{ box
141141
if options.exist('box'):
142-
eval(options.getfieldvalue('box'))
142+
isbox=options.getfieldvalue('box')
143+
if (isbox == 'off') | (isbox == 0) | (isbox == False):
144+
ax.axis('off')
145+
elif (isbox == 'on') | (isbox == 1) | (isbox == True):
146+
ax.axis('on')
147+
#eval(options.getfieldvalue('box'))
143148
# }}}
144149
# {{{ xlim, ylim, zlim
145150
if options.exist('xlim'):
@@ -179,7 +184,11 @@ def applyoptions(md, data, options, fig, axgrid, gridindex):
179184
norm = options.getfieldvalue('colornorm')
180185
else:
181186
caxis = options.getfieldvalue('caxis')
182-
norm = mpl.colors.Normalize(vmin=caxis[0],vmax=caxis[1])
187+
if options.exist('log'):
188+
#NOTE: Use LogNorn rather than processing log dataset in "processdata".
189+
norm=mpl.colors.LogNorm(vmin=caxis[0],vmax=caxis[1],clip=False)
190+
else:
191+
norm = mpl.colors.Normalize(vmin=caxis[0],vmax=caxis[1])
183192
if options.exist('colormap'):
184193
cmap = getcolormap(options)
185194
cbar_extend = 0
@@ -216,13 +225,21 @@ def applyoptions(md, data, options, fig, axgrid, gridindex):
216225
# }}}
217226
# {{{ colorbar
218227
if options.getfieldvalue('colorbar', 1) == 1:
219-
cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
228+
formatter = mpl.ticker.ScalarFormatter(useMathText=1)
229+
if options.exist('log'):
230+
formatter = mpl.ticker.LogFormatterSciNotation(base=options.getfieldvalue('log'))
231+
232+
cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend,
233+
format=formatter)
220234
if options.exist('alpha'):
221235
cb.set_alpha(options.getfieldvalue('alpha'))
222236
if options.exist('colorbarnumticks'):
223237
cb.locator = MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks', 5))
224238
else:
225-
cb.locator = MaxNLocator(nbins=5) # default 5 ticks
239+
if options.exist('log'):
240+
cb.locator = mpl.ticker.LogLocator(options.getfieldvalue('log'))
241+
else:
242+
cb.locator = MaxNLocator(nbins=5) # default 5 ticks
226243
if options.exist('colorbartickspacing'):
227244
locs = np.arange(lims[0], lims[1] + 1, options.getfieldvalue('colorbartickspacing'))
228245
cb.set_ticks(locs)

src/m/plot/plot_landsat.py

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
#!/usr/bin/env python3
2+
import socket
3+
import copy
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
from cmaptools import getcolormap
7+
from processmesh import processmesh
8+
from processdata import processdata
9+
from InterpFromMeshToGrid import InterpFromMeshToGrid
10+
from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
11+
from applyoptions import applyoptions
12+
13+
def plot_landsat(md,data,options,fig,axgrid,gridindex):
14+
"""
15+
Explain
16+
-------
17+
This funtion loads Landsat Image Mosaic Antarctica (LIMA) for background image.
18+
19+
Usage
20+
-----
21+
plot_landsat(md,data,options,plotlines,plotcols,i)
22+
"""
23+
24+
#process mesh and data
25+
x2d, y2d, z2d, elements2d, is2d, isplanet=processmesh(md,[],options)
26+
data, datatype=processdata(md,data,options)
27+
28+
ismask = options.exist('mask')
29+
if ismask:
30+
mask = options.getfieldvalue('mask')
31+
options2 = copy.deepcopy(options)
32+
options2.removefield('caxis',False)
33+
options2.removefield('log',False)
34+
mask, datatype=processdata(md,mask,options2)
35+
data[~mask] = np.nan
36+
37+
#check is2d
38+
if not is2d:
39+
raise Exception('buildgridded error message: gridded not supported for 3d meshes, project on a layer')
40+
41+
#Get options
42+
hostname = socket.gethostname().lower().replace('-','')
43+
transparency = options.getfieldvalue('transparency',.2)
44+
highres = options.getfieldvalue('highres',0)
45+
isunit = options.getfieldvalue('unit',1)
46+
47+
#Get xlim, and ylim
48+
xlim=options.getfieldvalue('xlim',np.array([min(x2d),max(x2d)]))/isunit
49+
ylim=options.getfieldvalue('ylim',np.array([min(y2d),max(y2d)]))/isunit
50+
51+
pwr = md.radaroverlay.pwr
52+
xm = md.radaroverlay.x
53+
ym = md.radaroverlay.y
54+
if md.mesh.epsg == 3031 & np.size(pwr)==0 | np.size(xm)==0 | np.size(ym) == 0:
55+
#Antarctica region
56+
if highres:
57+
print(' LIMA with geotiff') # {{{
58+
59+
# find merged mosaic landsat image
60+
limapath = {'simba00':'/drive/project_inwoo/issm/Data/LIMA/AntarcticaLandsat.tif'};
61+
limapath = limapath[hostname]
62+
print(' LIMA path is %s'%(limapath))
63+
64+
# read image
65+
#im = imread(limapath);
66+
67+
## Region of LIMA data set
68+
#info = gdalinfo(limapath); # get geotiff info
69+
#xm = info.xmin + info.dx*np.arange(info.nx)
70+
#ym = info.ymax - info.dy*np.arange(info.ny)
71+
72+
## find region of model at LIMA
73+
#offset = 1e+4;
74+
#posx = np.where((xm > xlim[0]-offset)&(xm < xlim[1]+offset))[0]
75+
#posy = np.where((ym > ylim[0]-offset)&(ym < ylim[1]+offset))[0]
76+
# }}}
77+
else:
78+
print(' LIMA with reduced tiff') # {{{
79+
#Find merged mosaic landsat image
80+
limapath = {'inwoob85md3h':'/drive/project_inwoo/issm/Data/LIMA/tiff_90pct/00000-20080319-092059124.tif',
81+
'simba00':'/home/inwoo/data/LIMA/tiff_90pct/00000-20080319-092059124.tif'}
82+
if not hostname in limapath.keys():
83+
raise Exception('Error: Landsat image at Antarctic region is downloaded at https://lima.usgs.gov/fullcontinent.php. Download geotiff image using "wget -c https://lima.usgs.gov/tiff_90pct.zip -O tiff_90pct.zip"');
84+
85+
limapath = limapath[hostname]
86+
print(' LIMA path is %s'%(limapath))
87+
88+
# read image
89+
#im = imread(limapath)
90+
91+
## Region of LIMA data set
92+
#info = gdalinfo(limapath) # get geotiff info
93+
#xm = info.xmin + info.dx*np.arange(info.nx)
94+
#ym = info.ymax - info.dy*np.arange(info.ny)
95+
96+
## find region of model at LIMA
97+
#offset = 1e+4
98+
#posx = np.where((xm > xlim[0]-offset)&(xm < xlim[1]+offset))[0]
99+
#posy = np.where((ym > ylim[0]-offset)&(ym < ylim[1]+offset))[0]
100+
# }}}
101+
102+
# Update region of radaroverlay
103+
md.radaroverlay.x = xm[posx]
104+
md.radaroverlay.y = ym[posy]
105+
md.radaroverlay.pwr = im[posy, posx,:]
106+
elif md.mesh.epsg == 3431 & np.size(pwr)==0 | np.size(xm)==0 | np.size(ym) == 0:
107+
#Greenland region
108+
raise Exception('Greenland region is not yet available.')
109+
110+
#Check dataset.
111+
if (np.size(pwr)>0) & (np.size(xm)>0) & (np.size(ym)>0):
112+
#Existing radaroverlay
113+
if np.ndim(pwr) != 3:
114+
raise Exception('Error: Check np.ndim(md.radaroverlay.pwr) should be equal to 3.')
115+
116+
#Check image size
117+
#shape of image should be (ny, nx, band)
118+
nx = len(xm)
119+
ny = len(ym)
120+
if (np.shape(pwr)[0]==nx) & (np.shape(pwr)[1]==ny):
121+
pwr = np.transpose(pwr,[1,0,2])
122+
123+
#Close-up to specific xlim
124+
posx = np.where((xlim[0]<=xm)&(xm<=xlim[1]))[0]
125+
posy = np.where((ylim[0]<=ym)&(ym<=ylim[1]))[0]
126+
xm = xm[posx]
127+
ym = ym[posy]
128+
pwr = pwr[posy[0]:posy[-1]+1,posx[0]:posx[-1]+1,:]
129+
else:
130+
raise Exception('Error: data array in md.radaroverlay is not implemented yet.')
131+
132+
#Prepare grid
133+
if np.ndim(xm) == 1:
134+
data_grid=InterpFromMeshToGrid(elements2d+1,x2d/isunit,y2d/isunit,data,xm,ym,np.nan)
135+
else:
136+
data_grid=InterpFromMeshToMesh2d(elements2d+1,x2d,y2d,data,np.ravel(xm),np.ravel(ym),'default',np.nan)
137+
data_grid=np.reshape(data_grid,np.shape(xm))
138+
139+
data_nan=np.isnan(data_grid)
140+
if options.exist('caxis'):
141+
caxis_opt=options.getfieldvalue('caxis')
142+
data_grid[np.where(data_grid<caxis_opt[0])]=caxis_opt[0]
143+
data_grid[np.where(data_grid>caxis_opt[1])]=caxis_opt[1]
144+
data_min=caxis_opt[0];
145+
data_max=caxis_opt[1];
146+
else:
147+
data_min=np.nanmin(data_grid)
148+
data_max=np.nanmax(data_grid)
149+
150+
options.addfielddefault('colormap',plt.cm.viridis)
151+
cmap = getcolormap(copy.deepcopy(options))
152+
#TODO: Matlab version
153+
#image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(colorm)/(data_max-data_min))),colorm);
154+
#NOTE: Python version for ind2rgb
155+
image_rgb = cmap((data_grid-data_min)/(data_max-data_min))
156+
157+
alpha=np.ones(np.shape(data_grid))
158+
alpha[np.where(~data_nan)]=transparency
159+
alpha=np.repeat(alpha[:,:,np.newaxis],axis=2,repeats=3)
160+
161+
final=alpha*(pwr/255)+(1-alpha)*image_rgb[:,:,:3]
162+
163+
#Select plot area
164+
ax = axgrid[gridindex]
165+
166+
xmin = min(xm)/isunit
167+
xmax = max(xm)/isunit
168+
ymin = min(ym)/isunit
169+
ymax = max(ym)/isunit
170+
#Draw RGB image
171+
h=ax.imshow(final, extent=[xmin, xmax, ymin, ymax], origin='lower')
172+
173+
#last step: mesh gridded?
174+
if options.exist('edgecolor'):
175+
ax.triplot(x,y,triangles=elements,
176+
color=options.getfieldvalue('edgecolor'),
177+
linewdith=options.getfieldvalue('linewidth',1),
178+
)
179+
180+
#Apply options
181+
if ~np.isnan(data_min):
182+
options.changefieldvalue('caxis',[data_min, data_max]) # force caxis so that the colorbar is ready
183+
options.addfielddefault('axis','xy equal off') # default axis
184+
applyoptions(md,data,options,fig,axgrid,gridindex)

src/m/plot/plot_manager.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from processdata import processdata
1818
from processmesh import processmesh
1919
from plot_gridded import plot_gridded
20+
from plot_landsat import plot_landsat
2021

2122

2223
def plot_manager(md, options, fig, axgrid, gridindex):
@@ -82,6 +83,11 @@ def plot_manager(md, options, fig, axgrid, gridindex):
8283
else:
8384
print(("WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data))
8485
# }}}
86+
# {{{ Landsat plot
87+
if options.getfieldvalue('landsat',0):
88+
plot_landsat(md,data,options,fig,axgrid,gridindex)
89+
return
90+
# }}}
8591
# {{{ Gridded plot TODO
8692
if options.exist('gridded'):
8793
plot_gridded(md,data,options,fig,axgrid,gridindex)

0 commit comments

Comments
 (0)