def cn_line_thickness(plot, val=0., factor=2.): ''' Increases the thickness of contour lines corresponding to a list of values cn_line_thickness(contour, val=0., factor=2.) plot : plot Id of the plot to modify val : scalar or list of values, which contour lines should be modified. factor : scaling factor for line thickness ''' cnLevels = ngl.get_float_array(plot, "cnLevels") cnLineThicknesses = ngl.get_float_array(plot, "cnLineThicknesses") try: (v for v in val) except TypeError: val = [val] for i, thickness in enumerate(cnLineThicknesses[:]): if cnLevels[i] in val: cnLineThicknesses[i] = thickness * factor rlist = {"cnMonoLineThickness": False, "cnLineThicknesses": cnLineThicknesses} _set_values(plot, rlist)
def grid_wind(rs): """ Grid winds based on u and v components @param rs array of dicts @return uwnd, vwnd """ lats = [] lons = [] udata = [] vdata = [] for row in rs: if row['sknt'] is None or row['drct'] is None: continue # mps u,v = mesonet.uv( row['sknt'] / 0.514, row['drct'] ) if v is not None: lats.append( nt.sts[row['station']]['lat'] ) lons.append( nt.sts[row['station']]['lon'] ) vdata.append( v ) udata.append( u ) if len(vdata) < 4: print "No wind data at all for time: %s" % (ts,) return None ugrid = Ngl.natgrid(lons, lats, udata, iemre.XAXIS, iemre.YAXIS) vgrid = Ngl.natgrid(lons, lats, vdata, iemre.XAXIS, iemre.YAXIS) if ugrid is not None: ugt = ugrid.transpose() vgt = vgrid.transpose() return ugt, vgt else: return None, None
def lb_format_labels(plot, fmt, minmax=None): '''Applies a formatting to the lables of a label bar lb_format_labels(plot, fmt, minmax=None) plot : plot id of object that controlls the lable bar fmt : formatting string minmax : values of the maximum and minimum. Required, if cnLabelBarEndStyle is set to IncludeMinMaxLabels. If not provided in this case, a ValueError will be raised. ''' levels = [float(s) for s in ngl.get_string_array(plot, "cnLevels")] labels = [fmt % lev for lev in levels] if ngl.get_string(plot, "cnLabelBarEndStyle") == "IncludeMinMaxLabels": if not minmax: raise ValueError("You need to provide minmax," + " since cnLabelBarEndStyle is set to " + "IncludeMinMaxLabels!") minlabel = [fmt % minmax[0]] minlabel.extend(labels) labels = minlabel labels.append(fmt % minmax[1]) rlist = {"cnExplicitLabelBarLabelsOn": True, "lbLabelStrings": labels} _set_values(plot, rlist)
def _draw_main_title(self, wks, res): """Draw a title string above the panel plot.""" # A panel title is specified using the panel resources. ngl_panel_title_string = getattr(res, 'nglPanelTitleString', None) if ngl_panel_title_string is not None: # If a panel title is requested then it first needs to be parsed # for newlines. This allows a multi-line title to be properly # centered automatically. panel_titles = reversed( [p.strip() for p in ngl_panel_title_string.split('\n')]) # Create resources for displaying the text. txres = Ngl.Resources() txres.txFontHeightF = getattr(res, 'nglPanelTitleFontHeightF', defaults['fontheight']['title']) txres.txFont = getattr(res, 'nglPanelTitleFont', defaults['font']['title']) txres.txJust = 'BottomCenter' # Work out the center coordinate of the title, this is the same # for each line of a multi-line title. title_x = self.panel_center_x + getattr(res, 'nglPanelTitleOffsetXF', 0.) for i, t in enumerate(panel_titles): # For each line of a multi-line title (just one for a single # line title) work out the y coordinate and then draw the text # on the workstation. title_y = self.panel_y0 + 0.04 + \ (i+ (i * 0.5)) * txres.txFontHeightF Ngl.text_ndc(wks, t, title_x, title_y, txres)
def estimate_hilo( ts ): """ Estimate the High and Low Temperature based on gridded data """ # Query Obs highs = [] lows = [] lats = [] lons = [] icursor.execute(""" SELECT x(s.geom) as lon, y(s.geom) as lat, max_tmpf, min_tmpf from summary_%s c, stations s WHERE day = '%s' and s.network in ('AWOS','IA_ASOS', 'MN_ASOS', 'WI_ASOS', 'IL_ASOS', 'MO_ASOS', 'KS_ASOS', 'NE_ASOS', 'SD_ASOS', 'ND_ASOS', 'KY_ASOS', 'MI_ASOS', 'OH_ASOS') and c.iemid = s.iemid and max_tmpf > -90 and min_tmpf < 90""" % (ts.year, ts.strftime("%Y-%m-%d"))) for row in icursor: lats.append( row['lat'] ) lons.append( row['lon'] ) highs.append( row['max_tmpf'] ) lows.append( row['min_tmpf'] ) # Create the analysis highA = Ngl.natgrid(lons, lats, highs, iemre.XAXIS, iemre.YAXIS) lowA = Ngl.natgrid(lons, lats, lows, iemre.XAXIS, iemre.YAXIS) for id in nt.sts.keys(): nt.sts[id]['high'] = highA[nt.sts[id]['gridi'], nt.sts[id]['gridj']] nt.sts[id]['low'] = lowA[nt.sts[id]['gridi'], nt.sts[id]['gridj']]
def _get_plot_dimensions(self, plots, res): """Get the dimensions of the plots to be panelled.""" # Select the index of the plot to get the size from. base_plot = getattr(res, 'nglPanelScalePlotIndex', 0) pwidth = Ngl.get_float(plots[base_plot], 'vpWidthF') pheight = Ngl.get_float(plots[base_plot], 'vpHeightF') return pwidth, pheight
def vpbox(wks): """ Draw a box around the viewport! """ xbox = [0.1,0.9,0.9,0.1,0.1] ybox = [0.8,0.8,0.2,0.2,0.8] res = Ngl.Resources() res.gsLineColor = "NavyBlue" res.gsLineThicknessF = 1.5 Ngl.polyline_ndc(wks,xbox,ybox,res)
def add_panel_label(wks, plot, panLabel="", factor=.05, placement="ul", axfunc=min, rlist=None): ''' Adds a label to a plot similar to the result from the nglPanelFigureString resource. The box around the perimenter of the label is drawn by the text_ndc function and controlled by txPerim* attributes. add_panel_label(wks, plot, panLabel="", factor=(1., 1.), placement="ul", axfunc=min, rlist=None) wks : workstation Id as returned by open_wks() plot : plot Id of the panel to add the label panLabel : String containing the panel label factor : ratio of margin to reference axis length placement : One of "ul", "ur", "ll" or "lr" to specify the corner where the label should be placed axfunct : function which is used to give the reference axis length based on the viewport width and height. This function should accept one list or tupel as argument. rlist : Resouce object that can be used to customize the label and its perimeter box. It can contain any resource that is accepted by text_ndc as a valid resource. ''' vpXF, vpYF, vpWidthF, vpHeightF = [ngl.get_float(plot, name) for name in ["vpXF", "vpYF", "vpWidthF", "vpHeightF"]] margin = factor * axfunc([vpWidthF, vpHeightF]) ul_edge = [vpXF + .5 * vpWidthF, vpYF + .5 * vpHeightF] if placement[0] == "u": ul_edge[1] = vpYF - margin tx_just = "Top" elif placement[0] == "l": ul_edge[1] = vpYF - vpHeightF + margin tx_just = "Bottom" if placement[1] == "l": ul_edge[0] = vpXF + margin tx_just = tx_just + "Left" elif placement[1] == "r": ul_edge[0] = vpXF + vpWidthF - margin tx_just = tx_just + "Right" if len(ul_edge) != 2: raise ValueError("placement is not in ['ul', 'ur', 'll', 'lr']") tx_res = {"txFontHeightF": .02, "txPerimOn": True, "txBackgroundFillColor": 0, "txJust": tx_just} if rlist: tx_res.update(rlist.__dict__) ngl.text_ndc(wks, panLabel, *ul_edge, rlistc=_dict2Resource(tx_res))
def lg_create_legend_nd(wks, labels, x, y, shape, rlist=None): # Set defaults if not rlist: rlist = {} else: rlist = _resource2dict(rlist) ngl._set_legend_res(rlist, rlist) _set_default(rlist, "lgOrientation", "Vertical") _set_default(rlist, "vpWidthF", 0.6) _set_default(rlist, "vpHeightF", 0.6) _set_default(rlist, "lgItemCount", len(labels)) _set_default(rlist, "lgLineColors", [i + 2 for i in range(rlist["lgItemCount"])]) _set_default(rlist, "lgLineLabelFontColors", rlist["lgLineColors"]) if rlist["lgOrientation"].lower() == "vertical": nItems, nLegends = shape lwidth = rlist["vpWidthF"] / nLegends lheight = rlist["vpHeightF"] xpos = [x + i * lwidth for i in range(nLegends)] ypos = [y for i in range(nLegends)] else: nLegends, nItems = shape lwidth = rlist["vpWidthF"] lheight = rlist["vpHeightF"] / nLegends ypos = [y - i * lheight for i in range(nLegends)] xpos = [x for i in range(nLegends)] istart = 0 lg = [] for xi, yi in zip(xpos, ypos): nItem = min(nItems, rlist["lgItemCount"] - istart) if nItem <= 0: continue iend = istart + nItem lres = rlist.copy() if rlist["lgOrientation"].lower() == "vertical": lres["vpWidthF"] = lwidth lres["vpHeightF"] = lheight * nItem / nItems else: lres["vpWidthF"] = lwidth * nItem / nItems lres["vpHeightF"] = lheight for key in ("lgDashIndexes", "lgItemPositions", "lgItemTypes", "lgLabelStrings", "lgLineColors", "lgLineDashSegLens", "lgLineLabelFontColors", "lgLineLabelFontHeights", "lgLineLabelStrings", "lgLineThicknesses", "lgMarkerColors", "lgMarkerIndexes", "lgMarkerSizes", "lgMarkerThicknesses", ): if key in rlist: lres[key] = rlist[key][istart:iend] lres["lgItemCount"] = nItem lg.append(ngl.legend_ndc(wks, nItem, labels[istart:iend], xi, yi, _dict2Resource(lres))) istart = iend return lg
def watermark(wks): txres = Ngl.Resources() txres.txFontHeightF = 0.016 txres.txJust = "CenterLeft" lstring = "Iowa Environmental Mesonet" Ngl.text_ndc(wks, lstring,.11,.186,txres) lstring = "Map Generated %s" % (mx.DateTime.now().strftime("%d %b %Y %-I:%M %p"),) txres.txFontHeightF = 0.010 Ngl.text_ndc(wks, lstring,.11,.17,txres)
def plot(c): r = resource() r.trYReverse = c.reverseY r.trXReverse = c.reverseX r.trXLog = c.XlogAxis r.trYLog = c.YlogAxis # #Line styles r.xyLineColors = lineColors r.xyLineThicknesses = lineThickness #Plot title r.tiMainString = c.PlotTitle #Axis labels (ToDo: add defaults) #X and Y axis labels r.tiXAxisString = c.Xlabel r.tiYAxisString = c.Ylabel if c.switchXY: r.tiXAxisString,r.tiYAxisString = r.tiYAxisString,r.tiXAxisString # Legends, for multicurve plot legends = [] for id in c.listVariables(): if not id == c.Xid: if len(c.label[id]) > 0: legends.append(c.label[id]) else: legends.append(id) #ToDo: Add option to skip legends #Legends are redundant if there's only one curve if len(legends) > 1: r.pmLegendDisplayMode = "Always" r.xyExplicitLegendLabels = legends # #Suppress line drawing and just plot symbol for scatter plot curves r.xyMarkers = plotSymbols r.xyMarkerColors = lineColors r.xyMarkerSizeF = .01 r.xyMarkLineModes = [] for id in c.listVariables(): if not id == c.Xid: if c.scatter[id]: r.xyMarkLineModes.append('Markers') else: r.xyMarkLineModes.append('Lines') # w = Ngl.open_wks('x11','Climate Workbook') if c.switchXY: plot = Ngl.xy(w,c.Y(),c.X(),r) else: plot = Ngl.xy(w,c.X(),c.Y(),r) # #Now draw the plot r.nglDraw = True Ngl.panel(w,[plot],[1,1],r) return plotObj(w,plot) #So that user can delete window or save plot
def save(self,filename = 'plot'): #'eps' workstation doesn't work reliably, but 'ps' is OK weps = Ngl.open_wks('ps',filename,self.WorkstationResources) Ngl.change_workstation(self.plot,weps) Ngl.draw(self.plot) Ngl.change_workstation(self.plot,self.workstation) Ngl.destroy(weps)
def _draw_plots(self, plots, res): """Draw the provided plots.""" for plot in xrange(self.number_plots): # It is OK for a plot to be None, it will just be skipped. This # allows the user to have a lot of control over their panel plot. if plots[plot] is not None: # Set the position of the plot. res_pos = Ngl.Resources() res_pos.vpXF, res_pos.vpYF = self.plot_coordinates[plot] Ngl.set_values(plots[plot], res_pos) # Draw to plot. Ngl.draw(plots[plot])
def __call__(self, *args): """Ngl graphics function with modifications applied.""" # Make a local copy of the resources arguments, preventing them # from being modified in the calling namespace. These copied (and # possibly modified) are used only inside this method. res = list() for i, arg in enumerate(args): if isinstance(arg, Ngl.Resources): res.append((copy(arg), i)) # Form the new argument list containing copies of the resource # variables. We alse need to intercept nglDraw and nglFrame at the top # level, making sure they are turned off while modifications are # applied. After modifications we can check if drawing and frame # advancing was requested and do so then. new_args = list(args) draw_on = frame_on = False for r, i in res: draw_on = getattr(r, 'nglDraw', True) frame_on = getattr(r, 'nglFrame', True) if draw_on: setattr(r, 'nglDraw', False) if frame_on: setattr(r, 'nglFrame', False) new_args[i] = r # Call the modifier pre-plot methods. special_resources = list() for modifier in self.modifiers: # Run the preplot method of each modifier. modifier.preplot(*new_args) special_resources += modifier.resource_names # Go back and remove all special resources from resource variables # before they are passed to the Ngl plotting routine. for r, i in res: for resource_name in special_resources: try: delattr(r, resource_name) except AttributeError: pass # Make the plot. plot = self.f(*new_args) # Call the modifier post-plot methods. wks = args[0] for modifier in self.modifiers: modifier.postplot(wks, plot) # Check if the plot should be drawn and the frame advanced. Do so now # if required. if draw_on: Ngl.draw(plot) if frame_on: Ngl.frame(wks) # Return the modified plot. return plot
def estimate_snow( ts ): """ Estimate the Snow """ # Query Obs snowd = [] snow = [] lats = [] lons = [] icursor.execute(""" SELECT x(s.geom) as lon, y(s.geom) as lat, snow, snowd from summary_%s c, stations s WHERE day = '%s' and s.network in ('IA_COOP', 'MN_COOP', 'WI_COOP', 'IL_COOP', 'MO_COOP', 'KS_COOP', 'NE_COOP', 'SD_COOP', 'ND_COOP', 'KY_COOP', 'MI_COOP', 'OH_COOP') and c.iemid = s.iemid and snowd >= 0""" % (ts.year, ts.strftime("%Y-%m-%d"))) for row in icursor: lats.append( row['lat'] ) lons.append( row['lon'] ) snow.append( row['snow'] ) snowd.append( row['snowd'] ) if len(lats) < 5: # No data! for id in nt.sts.keys(): nt.sts[id]['snow'] = 0 nt.sts[id]['snowd'] = 0 return # Create the analysis snowA = Ngl.natgrid(lons, lats, snow, iemre.XAXIS, iemre.YAXIS) snowdA = Ngl.natgrid(lons, lats, snowd, iemre.XAXIS, iemre.YAXIS) for id in nt.sts.keys(): snowfall = snowA[nt.sts[id]['gridi'], nt.sts[id]['gridj']] snowdepth = snowdA[nt.sts[id]['gridi'], nt.sts[id]['gridj']] if snowfall > 0 and snowfall < 0.1: nt.sts[id]['snow'] = 0.0001 elif snowfall < 0: nt.sts[id]['snow'] = 0 elif numpy.isnan(snowfall): nt.sts[id]['snow'] = 0 else: nt.sts[id]['snow'] = snowfall if snowdepth > 0 and snowdepth < 0.1: nt.sts[id]['snowd'] = 0.0001 elif snowdepth < 0: nt.sts[id]['snowd'] = 0 elif numpy.isnan(snowdepth): nt.sts[id]['snowd'] = 0 else: nt.sts[id]['snowd'] = snowdepth
def natgrid_interp(data_in, lats_in, lons_in, lats_out, lons_out, valid_range=None, wrapping_overlap_interval=10.): IM_i = len(lons_in) JM_i = len(lats_in) IM_o = len(lons_out) JM_o = len(lats_out) lons_in_interval1 = np.zeros(IM_i) lons_in_interval2 = np.zeros(IM_i) lons_out_interval1 = np.zeros(IM_o) lons_out_interval2 = np.zeros(IM_o) for i in range(IM_i): lons_in_interval1[i] = Ngl.normalize_angle(lons_in[i], 0) lons_in_interval2[i] = Ngl.normalize_angle(lons_in[i], 1) for i in range(IM_o): lons_out_interval1[i] = Ngl.normalize_angle(lons_out[i], 0) if valid_range == None: valid_range = [data_in.min(), data_in.max()] x_in_interval1 = np.tile(lons_in_interval1,JM_i) y_in = np.repeat(lats_in, IM_i) z_in = data_in.flatten() if lons_in_interval1.max() - lons_in_interval1.min() > 180. and lons_in_interval2.max() - lons_in_interval2.min() > 180.: wrap = True ## span of lons is greater than 180; assume that it is a global run and therefore needs to be wrapped logical_wrapping = np.logical_and(lons_in_interval2[:] > -wrapping_overlap_interval, lons_in_interval2[:] < 0.) lons_wrapped = lons_in_interval2[logical_wrapping] data_in_wrapped = data_in[:,logical_wrapping] IM_wrapped = len(lons_wrapped) lons_wrapped_vector = np.tile(lons_wrapped,JM_i) lats_wrapped_vector = np.repeat(lats_in, IM_wrapped) data_in_wrapped_vector = data_in_wrapped.flatten() ### and add them together x_in_interval1 = np.concatenate((x_in_interval1, lons_wrapped_vector)) y_in = np.concatenate((y_in, lats_wrapped_vector)) z_in = np.concatenate((z_in, data_in_wrapped_vector)) # logical_wrapping = np.logical_and(lons_in_interval2[:] < wrapping_overlap_interval, lons_in_interval2[:] > 0.) lons_wrapped = lons_in_interval1[logical_wrapping] + 360. data_in_wrapped = data_in[:,logical_wrapping] IM_wrapped = len(lons_wrapped) lons_wrapped_vector = np.tile(lons_wrapped,JM_i) lats_wrapped_vector = np.repeat(lats_in, IM_wrapped) data_in_wrapped_vector = data_in_wrapped.flatten() ### and add them together x_in_interval1 = np.concatenate((x_in_interval1, lons_wrapped_vector)) y_in = np.concatenate((y_in, lats_wrapped_vector)) z_in = np.concatenate((z_in, data_in_wrapped_vector)) # ### reorder output lons # lons_out_interval1_unsorted = lons_out_interval1 # lons_out_interval1 = lons_out_interval1[lons_out_interval1.argsort()] output1 = Ngl.natgrid(x_in_interval1, y_in, z_in, lons_out_interval1, lats_out).transpose() output_masked = np.ma.masked_array(output1, mask=np.logical_or(output1 < min(valid_range), output1 > max(valid_range))) return(output_masked)
def manual_title(wks, cfg): """ Manually place a title """ if cfg.has_key("_title"): txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txJust = "CenterLeft" Ngl.text_ndc(wks, cfg["_title"], .11, .834, txres) del txres if cfg.has_key("_valid"): txres = Ngl.Resources() txres.txFontHeightF = 0.013 txres.txJust = "CenterLeft" Ngl.text_ndc(wks, "Map Valid: "+ cfg["_valid"], .11, .811, txres) del txres
def postplot(self, wks, plot): """Annotate the plot with title strings.""" for position in ('left', 'right', 'center'): for string_spec in self.string_specs[position]: # Create text and annotation resource variables based on the # current string specification. txres = self._text_resources(string_spec, position) anres = self._annotation_resources(string_spec, position) # Create the actual text object. text_object = Ngl.text_ndc(wks, string_spec['string'], 0., 0., txres) # Add the text object to the plot as an annotation. The plot # is a mutable object so doing this attaches the annotation to # the input plot. anno = Ngl.add_annotation(plot, text_object, anres)
def tm_lat_lon_labels(plot, ax="XB", direction=None, fmt="%d"): '''Add degree symbols to the tickmark labels of one axis of a plot. This function has to be called for each axis, that should get degree tickmark labels tm_lat_lon_labels(plot, ax="XB", direction="zonal") plot : plot Id of the plot to modify ax : one of "XB", "XT", "YL", "YR". Specifies the axis to work on. direction : String that starts with either "z" or "m", to indicate the direction of the axis (zonal or meridional). If omitted, a x-axis will be assumed to be zonal. If the string starts with any other character, there will be no hemisperic lables added, i.e N, S, W or E. fmt : format string of the number ''' def do_nothing(x): return x func_code = ngl.get_string(plot, "tm" + ax + "LabelFuncCode") fmt_s = func_code.join([fmt, "S", "o", "N", ""]) if not direction: if ax[0].lower() == "x": direction = "zonal" else: direction = "meridional" if direction[0].lower() == "z": hem_label = ("W", "E") func = abs elif direction[0].lower() == "m": hem_label = ("S", "N") func = abs else: hem_label = ("", "") func = do_nothing tm_values = ngl.get_float_array(plot, "tm" + ax + "Values") mtm_values = ngl.get_float_array(plot, "tm" + ax + "MinorValues") labels = [fmt_s % func(val) + hem_label[0] if val < 0. else fmt_s % func(val) + hem_label[1] for val in tm_values] rlist = {"tm" + ax + "Mode": "Explicit", "tm" + ax + "Values": tm_values, "tm" + ax + "MinorValues": mtm_values, "tm" + ax + "Labels": labels} _set_values(plot, rlist)
def load_soilt(data): soil_obs = [] lats = [] lons = [] valid = 'YESTERDAY' if mx.DateTime.now().hour < 7: valid = '%s' % ((mx.DateTime.now() - mx.DateTime.RelativeDateTime(days=2)).strftime("%Y-%m-%d"), ) rs = isuag.query("""SELECT station, c30 from daily WHERE valid = '%s'""" % (valid,) ).dictresult() for i in range(len(rs)): stid = rs[i]['station'] if not nt.sts.has_key(stid): continue soil_obs.append( rs[i]['c30'] ) lats.append( nt.sts[stid]['lat'] ) lons.append( nt.sts[stid]['lon'] ) if len(lons) == 0: print 'No ISUAG Data for %s' % (valid,) sys.exit() numxout = 40 numyout = 40 xmin = min(lons) - 1. ymin = min(lats) - 1. xmax = max(lons) + 1. ymax = max(lats) + 1. xc = (xmax-xmin)/(numxout-1) yc = (ymax-ymin)/(numyout-1) xo = xmin + xc* numpy.arange(0,numxout) yo = ymin + yc* numpy.arange(0,numyout) analysis = Ngl.natgrid(lons, lats, soil_obs, list(xo), list(yo)) for id in data.keys(): data[id]['soilt'] = sampler(xo,yo,analysis, data[id]['lon'], data[id]['lat'])
def gridcell_areas(lat, lon, mask=None, radius=6372000., lat_edges_in=False, lon_edges_in=False): ### assume uniform longitude spacing lat_edges, lon_edges = get_gridcell_edges(lat, lon) if lon_edges_in: IM = lon.shape[0] - 1 lon_edges = lon[:] res_lon = lon_edges[1] - lon_edges[0] else: IM = lon.shape[0] res_lon = lon[1]-lon[0] # if lat_edges_in: JM = lat.shape[0] - 1 lat_edges = lat[:] else: JM = lat.shape[0] southern_edge = np.fmax(lat_edges[0:JM], np.ones(JM)*-89.99) northern_edge = np.fmin(lat_edges[1:], np.ones(JM)*89.99) # area = Ngl.gc_qarea(southern_edge,np.zeros(JM)-res_lon/2.,\ northern_edge,np.zeros(JM)-res_lon/2.,\ northern_edge,np.zeros(JM)+res_lon/2.,\ southern_edge,np.zeros(JM)+res_lon/2.,\ radius=radius) ### 1-D array in meters sq. area_array = np.array(np.reshape(np.repeat(area,IM), [JM,IM])) if not mask==None: area_array = np.ma.array(area_array, mask=mask) return area_array
def pointfind2(plat, plon, lat, lon, pdif=1): """ return indeces and values of the grid point closest to lat/lon point the same as pointfind but could be faster Usage: pointfind(plat, plon, lat, lon, pdif = 0.5) Input: plat - latitude of the point plon - longitude of the point lat - 2d array of latutudes lon - 2d array of longitudes pdif - we don't need it but leave it to have the same input as pointfind Output: indeces and values of the points that fulfil conditions """ dist_min = 1000000. for i in range(lon.shape[0]): for j in range(lon.shape[1]): dist = Ngl.gc_dist(plat,plon,lat[i,j],lon[i,j]) if dist_min > dist: dist_min = dist i_min = i j_min = j lat_min = lat[i,j] lon_min = lon[i,j] print(i_min,j_min,lat_min,lon_min) gg1 = i_min, j_min return(gg1, lat_min, lon_min)
def cn_sym_min_max(x, res, ncontours=15, outside=True, aboutZero=True): '''Adjust the contour level configuration of a plot resource to give nice contour levels symmetric about zero. The contour levels are computed with NGL.nice_cntr_levels(). cn_sym_min_max(x, res, ncontours=15, outside=True, aboutZero=True) x : data used in the contour plot. res : Resource object that will be updated accordingly. outside : Whether the maxima is outside or inside the contour range. Will be passed to NGL.nice_cntr_levels(). aboutZero : Whether the contour levels will be centered about Zero. Will be passed to NGL.nice_cntr_levels(). ''' min_x = np.min(x) max_x = np.max(x) if min_x == max_x: min_x, max_x = -1., 1. min_out, max_out, step_size = ngl.nice_cntr_levels(min_x, max_x, outside=outside, max_steps=ncontours, aboutZero=aboutZero) newres = {"cnLevelSelectionMode": "ManualLevels", "cnMinLevelValF": min_out, "cnMaxLevelValF": max_out, "cnLevelSpacingF": (max_out - min_out) / step_size} res.__dict__.update(newres)
def get_cyclic_colormap(ncolor=180., saturation=1., value=.75, bg_color=(1., 1., 1.), fg_color=(0., 0., 0.)): ''' Returns a cyclic colormap by conversion from the HSV to RGB color space cmap = get_cyclic_colormap(ncolor=180., saturation=1., value=.75, bg_color=(1., 1., 1.), fg_color=(0., 0., 0.)) cmap : Numpy Nx3 array with RGB values of colormap ncolor : Number of colors to produce. Note that the colormap actually have ncolor + 2 colors (foreground and background color added). saturation : saturation of the colormap in HSV space value : brightness of the colormap. bg_color : background color in RGB fg_color : foreground color in RGB ''' hue = np.linspace(0., 360., ncolor, endpoint=False) cmap = np.zeros((ncolor + 2, 3)) cmap[0, :] = bg_color cmap[1, :] = fg_color for i, h in enumerate(hue): cmap[i + 2, :] = ngl.hsvrgb(h, saturation, value) return cmap
def plot_using_ngl(self, field_2d = None, file_name = None): import Ngl wks_type = "png" wks = Ngl.open_wks(wks_type, "cv") res = Ngl.Resources() res.mpProjection = "Orthographic" pass
def draw_2d(self, varname, v): res = Ngl.Resources() plot_name = "wo_%s" % varname.lower() lgr.info("plot name set to - %s" % plot_name) wks = _get_wks(plot_name) for t in range(3): plot = Ngl.contour(wks, v[t, :, :], res) return plot
def merge(ts): """ Process an hour's worth of stage4 data into the hourly RE """ # Load up the 12z 24h total, this is what we base our deltas on fp = "/mesonet/ARCHIVE/data/%s/stage4/ST4.%s.24h.grib" % ( ts.strftime("%Y/%m/%d"), ts.strftime("%Y%m%d%H") ) grib = Nio.open_file(fp, 'r') # Rough subsample, since the whole enchillata is too much lats = numpy.ravel( grib.variables["g5_lat_0"][200:-100:5,300:900:5] ) lons = numpy.ravel( grib.variables["g5_lon_1"][200:-100:5,300:900:5] ) vals = numpy.ravel( grib.variables["A_PCP_GDS5_SFC_acc24h"][200:-100:5,300:900:5] ) res = Ngl.natgrid(lons, lats, vals, iemre.XAXIS, iemre.YAXIS) stage4 = res.transpose() # Prevent Large numbers, negative numbers stage4 = numpy.where( stage4 < 10000., stage4, 0.) stage4 = numpy.where( stage4 < 0., 0., stage4) # Open up our RE file nc = netCDF4.Dataset("/mesonet/data/iemre/%s_mw_hourly.nc" % (ts.year,),'a') ts0 = ts + mx.DateTime.RelativeDateTime(days=-1) jan1 = mx.DateTime.DateTime(ts.year, 1, 1, 0, 0) offset0 = int(( ts0 - jan1).hours) offset1 = int(( ts - jan1).hours) if offset0 < 0: offset0 = 0 iemre2 = numpy.sum(nc.variables["p01m"][offset0:offset1,:,:], axis=0) iemre2 = numpy.where( iemre2 > 0., iemre2, 0.00024) iemre2 = numpy.where( iemre2 < 10000., iemre2, 0.00024) print "Stage IV 24h [Avg %5.2f Max %5.2f] IEMRE Hourly [Avg %5.2f Max: %5.2f]" % ( numpy.average(stage4), numpy.max(stage4), numpy.average(iemre2), numpy.max(iemre2) ) multiplier = stage4 / iemre2 print "Multiplier MIN: %5.2f AVG: %5.2f MAX: %5.2f" % ( numpy.min(multiplier), numpy.average(multiplier),numpy.max(multiplier)) for offset in range(offset0, offset1): data = nc.variables["p01m"][offset,:,:] # Keep data within reason data = numpy.where( data > 10000., 0., data) adjust = numpy.where( data > 0, data, 0.00001) * multiplier adjust = numpy.where( adjust > 250.0, 0, adjust) nc.variables["p01m"][offset,:,:] = numpy.where( adjust < 0.01, 0, adjust) ts = jan1 + mx.DateTime.RelativeDateTime(hours=offset) print "%s IEMRE %5.2f %5.2f Adjusted %5.2f %5.2f" % (ts.strftime("%Y-%m-%d %H"), numpy.average(data), numpy.max(data), numpy.average(nc.variables["p01m"][offset]), numpy.max(nc.variables["p01m"][offset])) nc.sync() iemre2 = numpy.sum(nc.variables["p01m"][offset0:offset1,:,:], axis=0) print "Stage IV 24h [Avg %5.2f Max %5.2f] IEMRE Hourly [Avg %5.2f Max: %5.2f]" % ( numpy.average(stage4), numpy.max(stage4), numpy.average(iemre2), numpy.max(iemre2) ) nc.close()
def plot_cc(wks,cont,x='lh',y='dse'): """ """ ## if (x == 'lh' and y == 'dse'): vy = np.linspace(240,360,101) press = 101300. vx,es = cclap(vy*1000/1004.,press) vx = 2.5 * 10**3 * vx ccstring = 'C-C, RH=100%' ## Line of constant moist static energy vy2 = 345. - vx lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineLabelString = 'MSE = 345 kJ/kg' lres.gsLineDashSegLenF = 0.09 line = Ngl.add_polyline(wks,cont,vx,vy2,lres) if (x == 'lh' and y == 'mse'): vy = np.linspace(240,360,101) press = 101300. vx,es = 2.5 * 10**3 * cclap(vy*1000/1004.,press) vy = vy + vx ccstring = 'C-C, RH=100%' ## Line of constant moist static energy vy2 = 345. * np.ones(vx.shape[0]) lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineLabelString = 'MSE = 345 kJ/kg' lres.gsLineDashSegLenF = 0.09 line = Ngl.add_polyline(wks,cont,vx,vy2,lres) lres = Ngl.Resources() lres.gsLineDashPattern = 15 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineLabelString = ccstring line = Ngl.add_polyline(wks,cont,vx,vy,lres) return wks,cont
def contour(A,**kwargs): #The following allows an expert user to pass #Ngl options directly to the plotter. #ToDo: Note that #options explicitly specified later will over-ride #what the user specified. This should be fixed, #by checking for things already specified. We should #also allow for using this resource to specify a color #map. if 'resource' in kwargs.keys(): r = kwargs['resource'] else: r = Dummy() # r.cnFillOn = True #Uses color fill # Set axes if they have been specified # as keyword arguments if 'x' in kwargs.keys(): r.sfXArray = kwargs['x'] if 'y' in kwargs.keys(): r.sfYArray = kwargs['y'] # # Now create the plot rw = Dummy() #Set the color map if 'colors' in kwargs.keys(): if (kwargs['colors'] == 'gray') or (kwargs['colors'] == 'grey') : #Set the default greyscale rw.wkColorMap = 'gsdtol' else: rw.wkColorMap = kwargs['colors'] else: #Default rainbow color table rw.wkColorMap = "temp1" w = Ngl.open_wks('x11','Climate Workbook',rw) r.nglDraw = False r.nglFrame = False plot = Ngl.contour(w,A,r) #Now draw the plot r.nglDraw = True Ngl.panel(w,[plot],[1,1],r) return plotObj(w,plot,rw) #So user can delete or save plot
def generate_map_plots(self, file_name, title_on=True, labels_on=True): """ Generate and save map plots. Store the plots in the file indicated by ``file_name`` in the current directory. Map plots are stored in a PDF file, with each map occupying its own page. :arg str file_name: The name for the PDF file containing map plots. :arg bool title_on: Determines, whether main title is plotted. :arg bool labels_on: Determines whether individual map titles are plotted. """ # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title # Open a workstation, display in X11 window # Alternatively wks_type = "ps", wks_type = "pdf" or wks_type = "x11" wks_type = "pdf" wks = Ngl.open_wks(wks_type, file_name, resources) # # Generate map plots # for dataset in self.map_data: # Set title if labels_on: resources.lbTitleString = dataset["title"] # Generate map plot cmap = Ngl.contour_map(wks, dataset["data"], resources) # Clean up del cmap del resources Ngl.end()
# o Using mpShapeMode to allow a free aspect ratio. # o Changing the map projection. # # Output: # This example produces two visualizations: # 1.) Cylindrical Equidistant projection # 2.) Mollweide projection # # Notes: # from __future__ import print_function import Ngl wks_type = "png" wks = Ngl.open_wks(wks_type, "map1") projections = ["CylindricalEquidistant", "Mollweide"] mpres = Ngl.Resources() # Indicate you want to set some # resources. mpres.mpShapeMode = "FreeAspect" # Allow the aspect ratio to be # changed. mpres.vpWidthF = 0.8 # Make the aspect ratio square. mpres.vpHeightF = 0.8 mpres.pmTitleDisplayMode = "Always" # Force the title to appear. for i in range(len(projections)): mpres.mpProjection = projections[i]
# function [lon_f, lat_f, trendyr,figTitle, figPath, colorLab] = Pyn_figure3(exmNum, mdlNum) figData = eng.Pyn_figure4_ERA5(exmNum, nargout=6) figPath = np.array(figData[4]) figPath = str(figPath) # ---Generate some dummy lat/lon data lat = np.squeeze(np.array(figData[1], 'f')) lon = np.squeeze(np.array(figData[0], 'f')) nlat = lat.size nlon = lon.size # ---Start the graphics section 创建画板 wks_type = "x11" wks = Ngl.open_wks(wks_type, figPath) # # One color map per row of plots colormap = np.array(figData[5]) # ---Values to use for contour labelbar varMin = -4 # Data mins varMax = 4 # Data maxs varInt = 1 # Data spacing levels = np.arange(varMin, varMax + 0.01, varInt) # list(np.arange(varMin,varMax,varInt)) nlevs = len(levels) # -- number of levels # -- convert list of floats to list of strings labels = ['{:.2f}'.format(x) for x in levels]
def add_labels_lcm(wks,map,dlat,dlon): PI = 3.14159 RAD_TO_DEG = 180./PI #-- determine whether we are in northern or southern hemisphere if (float(minlat) >= 0. and float(maxlat) > 0.): HEMISPHERE = "NH" else: HEMISPHERE = "SH" #-- pick some "nice" values for the latitude labels. lat_values = np.arange(int(minlat),int(maxlat),10) lat_values = lat_values.astype(float) nlat = len(lat_values) #-- We need to get the slope of the left and right min/max longitude lines. #-- Use NDC coordinates to do this. lat1_ndc = 0. lon1_ndc = 0. lat2_ndc = 0. lon2_ndc = 0. lon1_ndc,lat1_ndc = Ngl.datatondc(map,minlon,lat_values[0]) lon2_ndc,lat2_ndc = Ngl.datatondc(map,minlon,lat_values[nlat-1]) slope_lft = (lat2_ndc-lat1_ndc)/(lon2_ndc-lon1_ndc) lon1_ndc,lat1_ndc = Ngl.datatondc(map,maxlon,lat_values[0]) lon2_ndc,lat2_ndc = Ngl.datatondc(map,maxlon,lat_values[nlat-1]) slope_rgt = (lat2_ndc-lat1_ndc)/(lon2_ndc-lon1_ndc) #-- set some text resources txres = Ngl.Resources() txres.txFontHeightF = 0.01 txres.txPosXF = 0.1 #-- Loop through lat values, and attach labels to the left and right edges of #-- the masked LC plot. The labels will be rotated to fit the line better. dum_lft = [] #-- assign arrays dum_rgt = [] #-- assign arrays lat_label_lft = [] #-- assign arrays lat_label_rgt = [] #-- assign arrays for n in range(0,nlat): #-- left label if(HEMISPHERE == "NH"): rotate_val = -90. direction = "N" else: rotate_val = 90. direction = "S" #-- add extra white space to labels lat_label_lft.append("{}~S~o~N~{} ".format(str(np.abs(lat_values[n])),direction)) lat_label_rgt.append(" {}~S~o~N~{}".format(str(np.abs(lat_values[n])),direction)) txres.txAngleF = RAD_TO_DEG * np.arctan(slope_lft) + rotate_val dum_lft.append(Ngl.add_text(wks,map,lat_label_lft[n],minlon,lat_values[n],txres)) #-- right label if(HEMISPHERE == "NH"): rotate_val = 90 else: rotate_val = -90 txres.txAngleF = RAD_TO_DEG * np.arctan(slope_rgt) + rotate_val dum_rgt.append(Ngl.add_text(wks,map,lat_label_rgt[n],maxlon,lat_values[n],txres)) #---------------------------------------------------------------------- # Now do longitude labels. These are harder because we're not adding # them to a straight line. # Loop through lon values, and attach labels to the bottom edge for # northern hemisphere, or top edge for southern hemisphere. #---------------------------------------------------------------------- del(txres.txPosXF) txres.txPosYF = -5.0 #-- pick some "nice" values for the longitude labels lon_values = np.arange(int(minlon+10),int(maxlon-10),10).astype(float) lon_values = np.where(lon_values > 180, 360-lon_values, lon_values) nlon = lon_values.size dum_bot = [] #-- assign arrays lon_labels = [] #-- assign arrays if(HEMISPHERE == "NH"): lat_val = minlat else: lat_val = maxlat ctrl = "~C~" for n in range(0,nlon): if(lon_values[n] < 0): if(HEMISPHERE == "NH"): lon_labels.append("{}~S~o~N~W{}".format(str(np.abs(lon_values[n])),ctrl)) else: lon_labels.append("{}{}~S~o~N~W".format(ctrl,str(np.abs(lon_values[n])))) elif(lon_values[n] > 0): if(HEMISPHERE == "NH"): lon_labels.append("{}~S~o~N~E{}".format(str(lon_values[n]),ctrl)) else: lon_labels.append("{}{}~S~o~N~E".format(ctrl,str(lon_values[n]))) else: if(HEMISPHERE == "NH"): lon_labels.append("{}0~S~o~N~{}".format(ctrl,ctrl)) else: lon_labels.append("{}0~S~o~N~{}".format(ctrl,ctrl)) #-- For each longitude label, we need to figure out how much to rotate #-- it, so get the approximate slope at that point. if(HEMISPHERE == "NH"): #-- add labels to bottom of LC plot lon1_ndc,lat1_ndc = Ngl.datatondc(map, lon_values[n]-0.5, minlat) lon2_ndc,lat2_ndc = Ngl.datatondc(map, lon_values[n]+0.5, minlat) txres.txJust = "TopCenter" else: #-- add labels to top of LC plot lon1_ndc,lat1_ndc = Ngl.datatondc(map, lon_values[n]+0.5, maxlat) lon2_ndc,lat2_ndc = Ngl.datatondc(map, lon_values[n]-0.5, maxlat) txres.txJust = "BottomCenter" slope_bot = (lat1_ndc-lat2_ndc)/(lon1_ndc-lon2_ndc) txres.txAngleF = RAD_TO_DEG * np.arctan(slope_bot) #-- attach to map dum_bot.append(Ngl.add_text(wks, map, str(lon_labels[n]), \ lon_values[n], lat_val, txres)) return
lat2d[:, i] = lat for i in range(0, len(lat)): lon2d[i, :] = lon dx, dy = mpcalc.lat_lon_grid_deltas(lon2d, lat2d) div1 = mpcalc.divergence(u, v, dx, dy) div = np.array(div1) # open workspace for analysis plot wks_type = "png" wks = ngl.open_wks( wks_type, "GFSanalysis_%s_%s_divergence_%shPa" % (region, init_dt[0:10], lev_hPa)) # define resources for analysis plot res = ngl.Resources() res.nglDraw = False res.nglFrame = False cmap = ngl.read_colormap_file("MPL_RdBu") res.cnLinesOn = False res.cnLineLabelsOn = False res.cnFillOn = True res.cnFillPalette = cmap
# # To use the ScientificPython module to read in the netCDF file, # comment out the above "import" command, and uncomment the # import line below. # # from Scientific.IO.NetCDF import NetCDFFile # # Import Ngl support functions. # import Ngl # # Open three netCDF files and get variables. # data_dir = Ngl.pynglpath("data") cdf_file1 = Nio.open_file(os.path.join(data_dir, "cdf", "941110_P.cdf"), "r") cdf_file2 = Nio.open_file(os.path.join(data_dir, "cdf", "sstdata_netcdf.nc"), "r") cdf_file3 = Nio.open_file(os.path.join(data_dir, "cdf", "Pstorm.cdf"), "r") # # This is the ScientificPython method for opening netCDF files. # # cdf_file1 = NetCDFFile(os.path.join(data_dir,"cdf","941110_P.cdf"),"r") # cdf_file2 = NetCDFFile(os.path.join(data_dir,"cdf","sstdata_netcdf.nc"),"r") # cdf_file3 = NetCDFFile(os.path.join(data_dir,"cdf","Pstorm.cdf"),"r") psl = cdf_file1.variables["Psl"][:] sst = cdf_file2.variables["sst"] pf = cdf_file3.variables["p"]
def plotline(nlines,plotin,yearsin,nsep,title,Datatitle,figtitlein,colormap,xString,yString,unit): wkres = Ngl.Resources() wkres.wkColorMap = colormap wks_type = "eps" wks = Ngl.open_wks(wks_type,figtitlein,wkres) res = Ngl.Resources() plot = [] res.tiXAxisString = xString res.tiYAxisString = yString for iline in range(0,nlines): yearsplot = yearsin[iline] print yearsplot # nyearsin = len(yearsplot) # yearnums = range(0,nyearsin) A = np.array(yearsplot) regress = (np.zeros((5,nsep),np.float)) for ibin in range(0,nsep): if ibin == 0: if (plotdensity): res.tiYAxisString = "frequency" else: res.tiYAxisString = "number of events" else: res.tiYAxisString = "" linreg = plotin[iline][ibin][:] print A.shape print linreg.shape regress[:,ibin] = stats.linregress(A,linreg) if ibin == nsep -1: res.tiMainString = '{:^80}'.format(' >' + '{:2.1g}'.format(tbound1[ibin]) + unit + '; p=' + '{:5.3f}'.format(regress[3,ibin]) + " ") else: res.tiMainString = '{:^80}'.format('{:2.1g}'.format(tbound1[ibin]) + '-' + '{:2.1g}'.format(tbound2[ibin]) + unit + '; p=' + '{:5.3f}'.format(regress[3,ibin])) plot.append(Ngl.xy(wks,yearsplot,plotin[iline][ibin,:],res)) panelres = Ngl.Resources() panelres.nglPanelLabelBar = True panelres.nglPanelYWhiteSpacePercent = 8. panelres.nglPanelXWhiteSpacePercent = 0.0 panelres.nglPanelLabelBar = False # Turn on panel labelbar panelres.nglPanelTop = 1.0 panelres.nglPanelBottom = 0.00 panelres.nglPanelLeft = 0.0 panelres.nglPanelRight = 1.0 panelres.nglPaperOrientation = "Portrait" panelres.nglScale = False panelres.nglMaximize = True #txres = Ngl.Resources() #txres.txFontHeightF = 0.012 #Ngl.text_ndc(wks,'Annual timeseries of global number of events of various scales from' + Datatitle,0.5,0.94,txres) Ngl.panel(wks,plot,[nlines,float(nbounds)],panelres) print 'panelled'
if(not os.path.exists(shp_filename)): print("You do not have the '%s' shapefile." % shp_filename) print("See the comments at the top of this script for more information.") print("No shapefile outlines will be added.") ADD_SHAPE_OUTLINES = False else: ADD_SHAPE_OUTLINES = True #---Read data a = Nio.open_file(wrf_filename + ".nc") hgt = a.variables["HGT"][0,:,:] # Read first time step ( nlat x nlon) #---Send graphics to PNG file wks_type = "png" wks = Ngl.open_wks(wks_type,"wrf2") #---Set some plot options res = Ngl.Resources() # Contour options res.cnFillOn = True # turn on contour fill res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off line labels res.cnFillPalette = "OceanLakeLandSnow" # You may need to change these levels depending on your WRF output file # Try first running this script with these two lines commented out. res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = [0.5,10,50,75,100,150,200,250,300,400,500,600,700,800,900,1000,1100]
for i,dt in enumerate(dates): nc = Dataset(datadir+'scp_narr_%s.nc' % str(dt.year),'r',format='NETCDF4_CLASSIC') idex = date2index(dt,nc['time']) scp = nc.variables["scp"][idex][:][:] cin = nc.variables["sbcin"][idex][:][:] #cin mask term5 = np.fabs(cin) term5[np.fabs(cin)>50]=0. term5[np.fabs(cin)<=50]=1. scp = scp * term5 scp_climo = np.append(scp_climo,[scp],axis=0) nc.close() mean_scp = np.max(scp_climo,axis=0) #print mean_scp.shape #print len(dates) wkres = Ngl.Resources() #-- generate an resources object for workstation wkres.wkWidth = 2500 #-- plot resolution 2500 pixel width wkres.wkHeight = 2000 #-- plot resolution 2500 pixel height wks_type = "png" #-- graphics output type wks = Ngl.open_wks(wks_type,"test",wkres) #-- create 1st plot: vectors on global map res = Ngl.Resources() res.mpFillOn = True res.mpOutlineOn = True res.mpLandFillColor = "transparent" res.mpOceanFillColor = "grey" # No fill res.mpInlandWaterFillColor = "grey" res.mpFillDrawOrder = "PostDraw" res.mpGridAndLimbOn = True #---Contour options res.mpProjection = "LambertConformal"
temp[k] = temp[k] / len(separate_month(times)[i]) minval[k] = int(np.amin(temp[k])) maxval[k] = int(np.amax(temp[k])) i = i + 1 # Mean_T = sp_temp/len(separate_month(times)[i]) # print(Mean_T) inc = 10 L_lats = np.arange(-80, 100, 20) L_levs = [1000, 500, 200, 100, 50, 30, 10] wks_type = "png" wks_name = "Mean_T" wks = Ngl.open_wks(wks_type, wks_name) res = Ngl.Resources() #resources.nglDraw = False # Turn off draw for the individual plots #resources.nglFrame = False #res.tiMainString = "MAM Zonal Mean Temperature from 1979 to 2019 " res.tiMainFontHeightF = 0.024 res.cnLevelSelectionMode = "ManualLevels" #res.cnMinLevelValF = minval #res.cnMaxLevelValF = maxval #res.cnLevelSpacingF = inc res.cnFillOn = True res.cnLineLabelsOn = False
# coding=utf-8 import sys import cv2 import geojson import sms_warr as sms import Ngl def read_features(): return None if __name__ == '__main__': file_name = sys.argv[1] nio = sms.SmsWarr(file_name) temp = nio.get_temperature() print(temp) Ngl.contour()
figPath = np.array(figData[4]) figPath = str(figPath) if figPath=='/no': continue else: # ---Generate some dummy lat/lon data lat = np.squeeze(np.array(figData[1], 'f')) lon = np.squeeze(np.array(figData[0], 'f')) nlat = lat.size nlon = lon.size # ---Start the graphics section 创建画板 wks_type = "eps" wks = Ngl.open_wks(wks_type, figPath) # # One color map per row of plots colormap = np.array(figData[5]) # ---Values to use for contour labelbar varMin = -0.8 # Data mins varMax = 0.8 # Data maxs varInt = 0.2 # Data spacing levels = np.arange(varMin, varMax+0.01, varInt) # list(np.arange(varMin,varMax,varInt)) nlevs = len(levels) # -- number of levels # -- convert list of floats to list of strings labels = ['{:.2f}'.format(x) for x in levels]
def bilinear_interp(data_in, lats_in, lons_in, lats_out, lons_out): IM_i = len(lons_in) JM_i = len(lats_in) IM_o = len(lons_out) JM_o = len(lats_out) # # ## find four points from old grid that surround each point on new grid J_index_below = np.zeros(JM_o, dtype=np.int) J_index_above = np.zeros(JM_o, dtype=np.int) for j in range(JM_o): J_index_below[j] = np.sum(lats_in[:] <= lats_out[j]) - 1 J_index_above[j] = JM_i - max(np.sum(lats_in[:] >= lats_out[j]), 1) # I_index_below = np.zeros(IM_o, dtype=np.int) I_index_above = np.zeros(IM_o, dtype=np.int) for i in range(IM_o): found = False for ii in range(IM_i): if not found: if Ngl.normalize_angle(lons_in[ii], 0) == Ngl.normalize_angle( lons_out[i], 0): I_index_below[i] = ii I_index_above[i] = ii found = True for ii in range(IM_i - 1): if not found: if Ngl.normalize_angle(lons_in[ii], 0) < Ngl.normalize_angle( lons_out[i], 0) and Ngl.normalize_angle( lons_in[ii + 1], 0) > Ngl.normalize_angle( lons_out[i], 0): I_index_below[i] = ii I_index_above[i] = ii + 1 found = True elif Ngl.normalize_angle(lons_in[ii], 1) < Ngl.normalize_angle( lons_out[i], 1) and Ngl.normalize_angle( lons_in[ii + 1], 1) > Ngl.normalize_angle( lons_out[i], 1): I_index_below[i] = ii I_index_above[i] = ii + 1 found = True if not found: if Ngl.normalize_angle(lons_in[IM_i - 1], 1) < Ngl.normalize_angle( lons_out[i], 1) and Ngl.normalize_angle( lons_in[0], 1) > Ngl.normalize_angle(lons_out[i], 1): I_index_below[i] = IM_i - 1 I_index_above[i] = 0 found = True elif Ngl.normalize_angle( lons_in[IM_i - 1], 0) < Ngl.normalize_angle( lons_out[i], 0) and Ngl.normalize_angle( lons_in[0], 0) > Ngl.normalize_angle( lons_out[i], 0): I_index_below[i] = IM_i - 1 I_index_above[i] = 0 found = True if not found: raise RuntimeError # # print(J_index_below) # print(J_index_above) # print(I_index_below) # print(I_index_above) # # if type(data_in) == np.ma.masked_array: masked_in = True data_out = np.ma.masked_all([JM_o, IM_o]) else: masked_in = False data_out = np.zeros([JM_o, IM_o]) # # ### now loop to do the interpolation if masked_in: for i in range(IM_o): for j in range(JM_o): if I_index_below[i] != I_index_above[i] and J_index_below[ j] != J_index_above[j]: weights = np.ma.masked_all([4]) values = np.ma.masked_all([4]) weights[0] = absdeltalon( lons_in[I_index_below[i]], lons_out[i]) * abs(lats_in[J_index_below[j]] - lats_out[j]) weights[1] = absdeltalon( lons_in[I_index_above[i]], lons_out[i]) * abs(lats_in[J_index_below[j]] - lats_out[j]) weights[2] = absdeltalon( lons_in[I_index_below[i]], lons_out[i]) * abs(lats_in[J_index_above[j]] - lats_out[j]) weights[3] = absdeltalon( lons_in[I_index_above[i]], lons_out[i]) * abs(lats_in[J_index_above[j]] - lats_out[j]) values[0] = data_in[J_index_below[j], I_index_below[i]] values[1] = data_in[J_index_below[j], I_index_above[i]] values[2] = data_in[J_index_above[j], I_index_below[i]] values[3] = data_in[J_index_above[j], I_index_above[i]] weights.mask = values.mask data_out[j, i] = np.sum(weights * values) / np.sum(weights) elif I_index_below[i] == I_index_above[ i] and J_index_below[j] != J_index_above[j]: weights = np.ma.masked_all([2]) values = np.ma.masked_all([2]) weights[0] = abs(lats_in[J_index_below[j]] - lats_out[j]) weights[1] = abs(lats_in[J_index_above[j]] - lats_out[j]) values[0] = data_in[J_index_below[j], I_index_below[i]] values[1] = data_in[J_index_above[j], I_index_above[i]] weights.mask = values.mask data_out[j, i] = np.sum(weights * values) / np.sum(weights) elif J_index_below[j] == J_index_above[ j] and I_index_below[i] != I_index_above[i]: weights = np.ma.masked_all([2]) values = np.ma.masked_all([2]) weights[0] = absdeltalon(lons_in[I_index_below[i]], lons_out[i]) weights[1] = absdeltalon(lons_in[I_index_above[i]], lons_out[i]) values[0] = data_in[J_index_below[j], I_index_below[i]] values[1] = data_in[J_index_above[j], I_index_above[i]] weights.mask = values.mask data_out[j, i] = np.sum(weights * values) / np.sum(weights) else: data_out[j, i] = data_in[J_index_below[j], I_index_below[i]] else: for i in range(IM_o): for j in range(JM_o): if I_index_below[i] != I_index_above[i] and J_index_below[ j] != J_index_above[j]: weights = np.zeros([4]) values = np.zeros([4]) weights[0] = absdeltalon( lons_in[I_index_below[i]], lons_out[i]) * abs(lats_in[J_index_below[j]] - lats_out[j]) weights[1] = absdeltalon( lons_in[I_index_above[i]], lons_out[i]) * abs(lats_in[J_index_below[j]] - lats_out[j]) weights[2] = absdeltalon( lons_in[I_index_below[i]], lons_out[i]) * abs(lats_in[J_index_above[j]] - lats_out[j]) weights[3] = absdeltalon( lons_in[I_index_above[i]], lons_out[i]) * abs(lats_in[J_index_above[j]] - lats_out[j]) values[0] = data_in[J_index_below[j], I_index_below[i]] values[1] = data_in[J_index_below[j], I_index_above[i]] values[2] = data_in[J_index_above[j], I_index_below[i]] values[3] = data_in[J_index_above[j], I_index_above[i]] data_out[j, i] = np.sum(weights * values) / np.sum(weights) elif I_index_below[i] == I_index_above[ i] and J_index_below[j] != J_index_above[j]: weights = np.zeros([2]) values = np.zeros([2]) weights[0] = abs(lats_in[J_index_below[j]] - lats_out[j]) weights[1] = abs(lats_in[J_index_above[j]] - lats_out[j]) values[0] = data_in[J_index_below[j], I_index_below[i]] values[1] = data_in[J_index_above[j], I_index_above[i]] data_out[j, i] = np.sum(weights * values) / np.sum(weights) elif J_index_below[j] == J_index_above[ j] and I_index_below[i] != I_index_above[i]: weights = np.zeros([2]) values = np.zeros([2]) weights[0] = absdeltalon(lons_in[I_index_below[i]], lons_out[i]) weights[1] = absdeltalon(lons_in[I_index_above[i]], lons_out[i]) values[0] = data_in[J_index_below[j], I_index_below[i]] values[1] = data_in[J_index_above[j], I_index_above[i]] data_out[j, i] = np.sum(weights * values) / np.sum(weights) else: data_out[j, i] = data_in[J_index_below[j], I_index_below[i]] # # return (data_out)
def natgrid_interp(data_in, lats_in, lons_in, lats_out, lons_out, valid_range=None, wrapping_overlap_interval=10.): IM_i = len(lons_in) JM_i = len(lats_in) IM_o = len(lons_out) JM_o = len(lats_out) lons_in_interval1 = np.zeros(IM_i) lons_in_interval2 = np.zeros(IM_i) lons_out_interval1 = np.zeros(IM_o) lons_out_interval2 = np.zeros(IM_o) for i in range(IM_i): lons_in_interval1[i] = Ngl.normalize_angle(lons_in[i], 0) lons_in_interval2[i] = Ngl.normalize_angle(lons_in[i], 1) for i in range(IM_o): lons_out_interval1[i] = Ngl.normalize_angle(lons_out[i], 0) if valid_range == None: valid_range = [data_in.min(), data_in.max()] x_in_interval1 = np.tile(lons_in_interval1, JM_i) y_in = np.repeat(lats_in, IM_i) z_in = data_in.flatten() if lons_in_interval1.max() - lons_in_interval1.min( ) > 180. and lons_in_interval2.max() - lons_in_interval2.min() > 180.: wrap = True ## span of lons is greater than 180; assume that it is a global run and therefore needs to be wrapped logical_wrapping = np.logical_and( lons_in_interval2[:] > -wrapping_overlap_interval, lons_in_interval2[:] < 0.) lons_wrapped = lons_in_interval2[logical_wrapping] data_in_wrapped = data_in[:, logical_wrapping] IM_wrapped = len(lons_wrapped) lons_wrapped_vector = np.tile(lons_wrapped, JM_i) lats_wrapped_vector = np.repeat(lats_in, IM_wrapped) data_in_wrapped_vector = data_in_wrapped.flatten() ### and add them together x_in_interval1 = np.concatenate((x_in_interval1, lons_wrapped_vector)) y_in = np.concatenate((y_in, lats_wrapped_vector)) z_in = np.concatenate((z_in, data_in_wrapped_vector)) # logical_wrapping = np.logical_and( lons_in_interval2[:] < wrapping_overlap_interval, lons_in_interval2[:] > 0.) lons_wrapped = lons_in_interval1[logical_wrapping] + 360. data_in_wrapped = data_in[:, logical_wrapping] IM_wrapped = len(lons_wrapped) lons_wrapped_vector = np.tile(lons_wrapped, JM_i) lats_wrapped_vector = np.repeat(lats_in, IM_wrapped) data_in_wrapped_vector = data_in_wrapped.flatten() ### and add them together x_in_interval1 = np.concatenate((x_in_interval1, lons_wrapped_vector)) y_in = np.concatenate((y_in, lats_wrapped_vector)) z_in = np.concatenate((z_in, data_in_wrapped_vector)) # ### reorder output lons # lons_out_interval1_unsorted = lons_out_interval1 # lons_out_interval1 = lons_out_interval1[lons_out_interval1.argsort()] output1 = Ngl.natgrid(x_in_interval1, y_in, z_in, lons_out_interval1, lats_out).transpose() output_masked = np.ma.masked_array(output1, mask=np.logical_or( output1 < min(valid_range), output1 > max(valid_range))) return (output_masked)
def conservative_regrid(data_in, lats_in, lons_in, lats_out, lons_out, centers_out=True, weights_in=None, spherical=True, radius=6372000., dilute_w_masked_data=True, return_frac_input_masked=False): # """ do a conservative remapping from one 2-d grid to another. assumes that input coordinate arrays are monotonic increasing (but handles lon jump across meridian) and that lat and lon are second-to last and last dimensions possible to mask the input data either by using a masked array or by setting weights array to zero for masked gridcells option dilute_w_masked_data means that where the input data is masked, a value of zero is averaged into the output grid, so that global integrals equal. setting this false will mean that global integrals do not equal, hoe=wever this could be back-calculated out using the fraction masked if return_frac_input_masked is set to true using the weights_in argument will also lead to non-equal global integrals """ # shape = data_in.shape ndims = len(shape) JM_i = shape[ndims - 2] IM_i = shape[ndims - 1] maxlat = 89.9 if weights_in == None: weights_in = np.ones([JM_i, IM_i]) weights_mask = np.zeros([JM_i, IM_i], dtype=np.bool) else: weights_mask = weights_in[:] == 0. if type(data_in) == np.ma.core.MaskedArray: if ndims == 2: mask_in = np.logical_or(data_in[:].mask, weights_mask) elif ndims == 3: mask_in = np.logical_or(data_in[0, :].mask, weights_mask) elif ndims == 4: mask_in = np.logical_or(data_in[0, 0, :].mask, weights_mask) else: mask_in = np.logical_or(np.zeros([JM_i, IM_i], dtype=np.bool), weights_mask) ## check to see if coordinates input are for gridcell centers or edges. assume that if edges, length of vector will be one longer than length of data # # # # ####### lats_in if len(lats_in) == JM_i: if spherical: lat_edges_in = np.zeros(JM_i + 1) lat_edges_in[0] = max(-maxlat, lats_in[0] - 0.5 * (lats_in[1] - lats_in[0])) lat_edges_in[JM_i] = min( maxlat, lats_in[JM_i - 1] + 0.5 * (lats_in[JM_i - 1] - lats_in[JM_i - 2])) lat_edges_in[1:JM_i] = (lats_in[0:JM_i - 1] + lats_in[1:JM_i]) / 2. else: lat_edges_in = np.zeros(JM_i + 1) lat_edges_in[0] = lats_in[0] - 0.5 * (lats_in[1] - lats_in[0]) lat_edges_in[JM_i] = lats_in[JM_i - 1] + 0.5 * (lats_in[JM_i - 1] - lats_in[JM_i - 2]) lat_edges_in[1:JM_i] = (lats_in[0:JM_i - 1] + lats_in[1:JM_i]) / 2. elif len(lats_in) == JM_i + 1: lat_edges_in = lats_in else: raise RuntimeError # ####### lats_out if centers_out: JM_o = len(lats_out) if spherical: lat_edges_out = np.zeros(JM_o + 1) lat_edges_out[0] = max( -maxlat, lats_out[0] - 0.5 * (lats_out[1] - lats_out[0])) lat_edges_out[JM_o] = min( maxlat, lats_out[JM_o - 1] + 0.5 * (lats_out[JM_o - 1] - lats_out[JM_o - 2])) lat_edges_out[1:JM_o] = (lats_out[0:JM_o - 1] + lats_out[1:JM_o]) / 2. else: lat_edges_out = np.zeros(JM_o + 1) lat_edges_out[0] = lats_out[0] - 0.5 * (lats_out[1] - lats_out[0]) lat_edges_out[JM_o] = lats_out[ JM_o - 1] + 0.5 * (lats_out[JM_o - 1] - lats_out[JM_o - 2]) lat_edges_out[1:JM_o] = (lats_out[0:JM_o - 1] + lats_out[1:JM_o]) / 2. else: JM_o = len(lats_out) - 1 lat_edges_out = lats_out # ####### lons_in if len(lons_in) == IM_i: lon_edges_in = np.zeros(IM_i + 1) lon_edges_in[0] = lons_in[0] - 0.5 * (lons_in[1] - lons_in[0]) lon_edges_in[IM_i] = lons_in[IM_i - 1] + 0.5 * (lons_in[IM_i - 1] - lons_in[IM_i - 2]) lon_edges_in[1:IM_i] = (lons_in[0:IM_i - 1] + lons_in[1:IM_i]) / 2. elif len(lons_in) == IM_i + 1: lon_edges_in = lons_in else: raise RuntimeError # ####### lons_out if centers_out: IM_o = len(lons_out) lon_edges_out = np.zeros(IM_o + 1) lon_edges_out[0] = lons_out[0] - 0.5 * (lons_out[1] - lons_out[0]) lon_edges_out[IM_o] = lons_out[IM_o - 1] + 0.5 * (lons_out[IM_o - 1] - lons_out[IM_o - 2]) lon_edges_out[1:IM_o] = (lons_out[0:IM_o - 1] + lons_out[1:IM_o]) / 2. else: IM_o = len(lons_out) - 1 lon_edges_out = lons_out # # # ### first define ranges to loop over that map overlapping lat and lons lon_looplist = [[]] for i in range(IM_o): if i > 0: lon_looplist.append([]) ### figure out which lon quadrant to normalize the data to. if -90<lon<90 then normalize to option 1, otherwise to zero if (Ngl.normalize_angle(lon_edges_out[i], 1) < 90.) and (Ngl.normalize_angle(lon_edges_out[i], 1) > -90.): lon_sector = 1 else: lon_sector = 0 min_cell_lon_o = Ngl.normalize_angle(lon_edges_out[i], lon_sector) max_cell_lon_o = Ngl.normalize_angle(lon_edges_out[i + 1], lon_sector) for ii in range(IM_i): min_cell_lon_i = Ngl.normalize_angle(lon_edges_in[ii], lon_sector) max_cell_lon_i = Ngl.normalize_angle(lon_edges_in[ii + 1], lon_sector) overlap_interval_lon = min(max_cell_lon_i, max_cell_lon_o) - max( min_cell_lon_i, min_cell_lon_o) if overlap_interval_lon > 0.: lon_looplist[i].append(ii) # # # lat_looplist = [[]] for j in range(JM_o): if j > 0: lat_looplist.append([]) min_cell_lat_o = lat_edges_out[j] max_cell_lat_o = lat_edges_out[j + 1] for jj in range(JM_i): min_cell_lat_i = lat_edges_in[jj] max_cell_lat_i = lat_edges_in[jj + 1] overlap_interval_lat = min(max_cell_lat_i, max_cell_lat_o) - max( min_cell_lat_i, min_cell_lat_o) if overlap_interval_lat > 0.: lat_looplist[j].append(jj) # # # ### now begin looping over output grid total_weights = np.zeros([JM_o, IM_o]) total_weights_inputmasked = np.zeros([JM_o, IM_o]) if ndims == 2: total_value = np.zeros([JM_o, IM_o]) elif ndims == 3: total_value = np.zeros([shape[0], JM_o, IM_o]) elif ndims == 4: total_value = np.zeros([shape[0], shape[1], JM_o, IM_o]) else: raise RuntimeError for i in range(IM_o): ### figure out which lon quadrant to normalize the data to. if -90<lon<90 then normalize to option 1, otherwise to zero if (Ngl.normalize_angle(lon_edges_out[i], 1) < 90.) and (Ngl.normalize_angle(lon_edges_out[i], 1) > -90.): lon_sector = 1 else: lon_sector = 0 min_cell_lon_o = Ngl.normalize_angle(lon_edges_out[i], lon_sector) max_cell_lon_o = Ngl.normalize_angle(lon_edges_out[i + 1], lon_sector) for j in range(JM_o): min_cell_lat_o = lat_edges_out[j] max_cell_lat_o = lat_edges_out[j + 1] for ii in lon_looplist[i]: for jj in lat_looplist[j]: if not (mask_in[jj, ii]) or dilute_w_masked_data: min_cell_lat_i = lat_edges_in[jj] max_cell_lat_i = lat_edges_in[jj + 1] min_cell_lon_i = Ngl.normalize_angle( lon_edges_in[ii], lon_sector) max_cell_lon_i = Ngl.normalize_angle( lon_edges_in[ii + 1], lon_sector) overlap_interval_lat = min( max_cell_lat_i, max_cell_lat_o) - max( min_cell_lat_i, min_cell_lat_o) overlap_interval_lon = min( max_cell_lon_i, max_cell_lon_o) - max( min_cell_lon_i, min_cell_lon_o) if overlap_interval_lat > 0. and overlap_interval_lon > 0.: fractional_overlap_lat = overlap_interval_lat / ( max_cell_lat_i - min_cell_lat_i) fractional_overlap_lon = overlap_interval_lon / ( max_cell_lon_i - min_cell_lon_i) fractional_overlap_total = fractional_overlap_lat * fractional_overlap_lon if spherical: weight = fractional_overlap_total * weights_in[ jj, ii] * Ngl.gc_qarea(min_cell_lat_i, min_cell_lon_i, max_cell_lat_i, min_cell_lon_i, max_cell_lat_i, max_cell_lon_i, min_cell_lat_i, max_cell_lon_i, radius=radius) else: weight = fractional_overlap_total * weights_in[ jj, ii] total_weights[j, i] = total_weights[j, i] + weight if not (mask_in[jj, ii]): total_weights_inputmasked[ j, i] = total_weights_inputmasked[j, i] + weight if ndims == 2: total_value[j, i] = total_value[ j, i] + weight * data_in[jj, ii] elif ndims == 3: total_value[:, j, i] = total_value[:, j, i] + weight * data_in[:, jj, ii] elif ndims == 4: total_value[:, :, j, i] = total_value[:, :, j, i] + weight * data_in[:, :, jj, ii] # if ndims > 2: total_weights_bc, total_value_bc = np.broadcast_arrays( total_weights, total_value) total_weights_inputmasked_bc, total_value_bc = np.broadcast_arrays( total_weights_inputmasked, total_value) else: total_weights_bc = total_weights total_weights_inputmasked_bc = total_weights_inputmasked # if total_weights_inputmasked.min() > 0.: mean_value = total_value[:] / total_weights_bc[:] fraction_maskedinput = total_weights_inputmasked[:] / total_weights[:] else: mean_value = np.ma.masked_array( total_value[:] / total_weights_bc[:], mask=total_weights_inputmasked_bc[:] == 0.) fraction_maskedinput = np.ma.masked_array( total_weights_inputmasked[:] / total_weights[:], mask=total_weights_inputmasked[:] == 0.) # # if not return_frac_input_masked: return mean_value else: return mean_value, fraction_maskedinput
pnew = [800., 750.] lev = 0 f = Nio.open_file("/home/yumeng/realthesis/LowRes/LowRes_200610.01_tracer.nc") # interpolation from sigma coordinate to pressure coordinate # get parameters and variables for interpolation hyam = f.variables["hyam"][:] / p0mb hybm = f.variables["hybm"][:] PS = f.variables["aps"][:, :, :] f = Nio.open_file("/home/yumeng/realthesis/Uniform/AMRDUST.nc") DU_CI = f.variables["CI"][:, :, :, :] * 1e6 DU_AI = f.variables["AI"][:, :, :, :] * 1e6 lon_Uni = f.variables["lon"][:] lat_Uni = f.variables["lat"][:] # start the interpolation NewTracer_CI_Uni = Ngl.vinth2p(DU_CI[:, :, :, :], hyam, hybm, pnew, PS[:, :, :], interp, p0mb1, 1, extrap) NewTracer_AI_Uni = Ngl.vinth2p(DU_AI[:, :, :, :], hyam, hybm, pnew, PS[:, :, :], interp, p0mb1, 1, extrap) NewTracer_AI_Uni = np.ma.masked_where(NewTracer_AI_Uni == 1.e30, NewTracer_AI_Uni) print(np.max(NewTracer_AI_Uni)) # day 10 to 20 # set up colormap rlist = Ngl.Resources() rlist.wkColorMap = "WhiteYellowOrangeRed" for it in range(30): print(it) # use colormap and type information to setup output background wks_type = "pdf" wks = Ngl.open_wks(wks_type, "Uniform" + str(it), rlist)
(diri + fname)) print("You can get the files from the NCL website at:") print("http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/") sys.exit() minval = 250. #-- minimum contour level maxval = 315 #-- maximum contour level inc = 5. #-- contour level spacing #-- open file and read variables f = Nio.open_file(diri + fname, "r") #-- open data file temp = f.variables["tsurf"][0, :, :] #-- first time step lat = f.variables["lat"][:] #-- all latitudes lon = f.variables["lon"][:] #-- all longitudes tempac, lon = Ngl.add_cyclic(temp, lon) #-- open a workstation wks_type = "png" #-- graphics output type wkres = Ngl.Resources() #-- generate an res object #-- for workstation wkres.wkWidth = 2500 #-- plot res 2500 pixel width wkres.wkHeight = 2500 #-- plot resolution 2500 wks = Ngl.open_wks(wks_type, "plot_contour_ngl", wkres) #-- open workstation #-- set resources res = Ngl.Resources() #-- generate an resource object for plot if hasattr(f.variables["tsurf"], "long_name"): res.tiMainString = f.variables["tsurf"].long_name #-- set main title
def plotmap(plotvars1,plotvars2, plotmin1,plotmax1,plotmin2,plotmax2, vartitle1,vartitle2, title, figtitle, minlon,maxlon,minlat,maxlat, FillValue,panellabels = [], labelbarlabels = [], labelbarlabels2 = []): nplots = plotvars1.shape[0] wkres = Ngl.Resources() wkres.wkColorMap = "WhiteBlue" wks_type = "eps" wks = Ngl.open_wks(wks_type,figtitle,wkres) # if lons start negative, shift everything over so there isn't a line down # the middle of the Pacific lons1 = plotvars1.lon.values lons2 = plotvars2.lon.values lats1 = plotvars1.lat.values lats2 = plotvars2.lat.values if lons1[0] < 0: #nlonhalf1 = len(lons1)/2 #lonsnew1 = np.zeros(lons1.shape,np.float) #lonsnew1[0:nlonhalf1] = lons1[nlonhalf1:nlons1] #lonsnew1[nlonhalf1:nlons1] = lons1[0:nlonhalf1] + 360.0 lonsnew1 = shiftlonlons(lons1,len(lons1)) lonsnew2 = shiftlonlons(lons2,len(lons2)) for iplot in range(0,nplots): plotvars1[iplot] = shiftlons(plotvars1[iplot],len(lons1)) plotvars2[iplot] = shiftlons(plotvars2[iplot],len(lons2)) else: lonsnew1 = lons1 lonsnew2 = lons2 # initialize plotting resources res1 = Ngl.Resources() res1 = initcontourplot(res1,minlat,minlon,maxlat,maxlon,lats1,lonsnew1) res1.sfMissingValueV = FillValue res1.lbOrientation = "Vertical" # including some font heights res1.lbLabelFontHeightF = 0.01 res1.lbTitleFontHeightF = 0.01 res1.tiMainFontHeightF = 0.015 res1.lbTitlePosition = 'Bottom' res1.lbBottomMarginF = 0.0 # initialize plotting resources res2 = Ngl.Resources() res2 = initcontourplot(res2,minlat,minlon,maxlat,maxlon,lats2,lonsnew2) res2.sfMissingValueV = FillValue res2.lbOrientation = "Vertical" # including some font heights res2.lbLabelFontHeightF = 0.01 res2.lbTitleFontHeightF = 0.01 res2.tiMainFontHeightF = 0.008 res2.lbTitlePosition = 'Bottom' res2.lbBottomMarginF = 0.0 # turn off grid lines res1.mpGridAndLimbOn = False res2.mpGridAndLimbOn = False # initialize plotting array toplot = [] # fill plotting array for iplot in range(0,nplots): tempplot = plotvars1[iplot].values tempplot[np.where(np.isnan(tempplot))] = FillValue # update plot resources with correct lat/lon res1.cnMinLevelValF = plotmin1[iplot] res1.cnMaxLevelValF = plotmax1[iplot] res1.cnLevelSpacingF = ((plotmax1[iplot]-plotmin1[iplot])/10.0) res1.tiMainString = (vartitle1[iplot]) if panellabels != []: res1.lbTitleString = labelbarlabels[iplot] res1.tiYAxisString = panellabels[iplot] # Y axes label. toplot.append(Ngl.contour_map(wks,tempplot,res1)) tempplot = plotvars2[iplot].values tempplot[np.where(np.isnan(tempplot))] = FillValue res2.cnMinLevelValF = plotmin2[iplot] # contour levels. res2.cnMaxLevelValF = plotmax2[iplot] res2.cnLevelSpacingF = ((plotmax2[iplot]-plotmin2[iplot])/10.0) res2.tiMainString = vartitle2[iplot] if panellabels != []: res2.lbTitleString = labelbarlabels2[iplot] res2.tiYAxisString = " " # so plots are the same # size toplot.append(Ngl.contour_map(wks,tempplot,res2)) textres = Ngl.Resources() textres.txFontHeightF = 0.015 Ngl.text_ndc(wks,title,0.5,0.87,textres) panelres = Ngl.Resources() panelres.nglPanelLabelBar = True panelres.nglPanelYWhiteSpacePercent = 0. panelres.nglPanelXWhiteSpacePercent = 0. panelres.nglPanelLabelBar = False # Turn on panel labelbar if nplots > 5: panelres.nglPanelTop = 0.8 panelres.nglPanelBottom = 0.15 else: panelres.nglPanelTop = 0.95 panelres.nglPanelBottom = 0.01 panelres.nglPanelLeft = 0.01 panelres.nglPanelRight = 0.99 panelres.nglPanelFigureStrings = ( ['a.','b.','c.','d.','e.','f.','g.','h.','i.','j.','k.','l.','m.','n.','o.','p.']) panelres.nglPanelFigureStringsJust = "TopLeft" panelres.nglPanelFigureStringsFontHeightF = 0.008 panelres.nglPanelFigureStringsParallelPosF = -0.55 panelres.nglPanelFigureStringsOrthogonalPosF = -0.7 panelres.nglPanelFigureStringsPerimOn = False # turn off boxes #panelres.amJust = "TopLeft" panelres.nglPaperOrientation = "Auto" plot = Ngl.panel(wks,toplot,[nplots,2],panelres)
#-- open a file and read variables f = Nio.open_file("rectilinear_grid_2D.nc", "r") u = f.variables["u10"] v = f.variables["v10"] ua = f.variables["u10"][0,:,:] va = f.variables["v10"][0,:,:] lat = f.variables["lat"] lon = f.variables["lon"] nlon = len(lon) nlat = len(lat) #-- open a workstation wks = Ngl.open_wks("png",os.path.basename(__file__).split('.')[0]) #-- resource settings stres = Ngl.Resources() stres.nglFrame = False stres.vfXArray = lon[::3] stres.vfYArray = lat[::3] stres.mpFillOn = True stres.mpOceanFillColor = "Transparent" stres.mpLandFillColor = "Gray90" stres.mpInlandWaterFillColor = "Gray90" #-- create the plot plot = Ngl.streamline_map(wks,ua[::3,::3],va[::3,::3],stres)
def contourwithoverlay(wks,resMP,varin, plotoverlay): plottemp = Ngl.contour_map(wks,varin,resMP) Ngl.overlay(plottemp,plotoverlay) return(plottemp)
# # Import Nio for reading netCDF files. # import Nio # # Import Ngl support functions. # import Ngl import os # # Open the netCDF file. # file = Nio.open_file(os.path.join(Ngl.pynglpath("data"),"cdf","pop.nc")) # # Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type,"streamline1") # # Get the u/v and lat/lon variables. # urot = file.variables["urot"] vrot = file.variables["vrot"] lat2d = file.variables["lat2d"] lon2d = file.variables["lon2d"]
for i in range(nlon): c_thick[j, i] = max(float(sum(cldfra[:, j, i]) - 1) * 1.e2, 0.) for k in range(1, nk): if (cldfra[k,j,i] == 1 and cldfra[k-1,j,i] == 0 \ and c_base[j,i] == 0.0): c_base[j, i] = lev[k] #get cloud base #------------------------------------------------- if (k < nk - 1): if (cldfra[k + 1, j, i] == 0 and cldfra[k, j, i] == 1): c_top[j, i] = lev[k] elif (k == nk - 1 and cldfra[k, j, i] == 1): c_top[j, i] = lev[k] #------------------------------------------------------------ #print(str(cldfra[:,190,1])) del cldfra #c_thick = c_top - c_base;# print(c_thick.shape) #print(str(c_thick[190,1]),str(c_top[190,1]),str(c_base[190,1])) newFile.write(bytearray(c_thick)) newFile.write(bytearray(c_top)) newFile.write(bytearray(c_base)) print("\n" + "-" * 80) del a #loop t end_time = cpu_time() end_time = (end_time - start_time) / 60.0 print("\033[92m\"{}\" has done!\nTime elapsed: {:.2f}" \ .format(os.path.basename(__file__), end_time), "mins.\033[0m") Ngl.end() #Nio.end() #exit()
# # Import numpy. # import numpy # # Import NGL support functions. # import Ngl # # Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type,"ngl11p") dirc = Ngl.pynglpath("data") data = Ngl.asciiread(dirc+"/asc/u.cocos",(39,14),"float") pressure = data[:,0] # First column of data is pressure (mb). height = data[:,1] # Second column is height (km). u = data[:,2:14] # Rest of columns are climatological zonal winds # (u: m/s) unew = Ngl.add_cyclic(u) # Add cyclic points to u. #----------- Begin first plot ----------------------------------------- resources = Ngl.Resources() resources.tiMainString = "~F26~Cocos Island" # Main title.
maxval = 315 #-- maximum contour level inc = 5. #-- contour level spacing #-- open file and read variables f = Nio.open_file(diri + fname, "r") #-- open data file temp = f.variables["tsurf"][0, ::-1, :] #-- first time step, reverse latitude u = f.variables["u10"][0, ::-1, :] #-- first time step, reverse latitude v = f.variables["v10"][0, ::-1, :] #-- first time step, reverse latitude lat = f.variables["lat"][::-1] #-- reverse latitudes lon = f.variables["lon"][:] #-- all longitudes nlon = len(lon) #-- number of longitudes nlat = len(lat) #-- number of latitudes #-- open a workstation wkres = Ngl.Resources() #-- generate an resources object for workstation wks_type = "x11" #-- graphics output type wks = Ngl.open_wks(wks_type, "plot_vector_PyNGL", wkres) #-- create 1st plot: vectors on global map res = Ngl.Resources() res.vfXCStartV = float(lon[0]) #-- minimum longitude res.vfXCEndV = float(lon[len(lon[:]) - 1]) #-- maximum longitude res.vfYCStartV = float(lat[0]) #-- minimum latitude res.vfYCEndV = float(lat[len(lat[:]) - 1]) #-- maximum latitude res.tiMainString = "~F25~Wind velocity vectors" #-- title string res.tiMainFontHeightF = 0.024 #-- decrease title font size res.mpLimitMode = "Corners" #-- select a sub-region res.mpLeftCornerLonF = float(lon[0]) #-- left longitude value
lon1_ndc,lat1_ndc = Ngl.datatondc(map, lon_values[n]+0.5, maxlat) lon2_ndc,lat2_ndc = Ngl.datatondc(map, lon_values[n]-0.5, maxlat) txres.txJust = "BottomCenter" slope_bot = (lat1_ndc-lat2_ndc)/(lon1_ndc-lon2_ndc) txres.txAngleF = RAD_TO_DEG * np.arctan(slope_bot) #-- attach to map dum_bot.append(Ngl.add_text(wks, map, str(lon_labels[n]), \ lon_values[n], lat_val, txres)) return #------------------------------------------------------- # MAIN #------------------------------------------------------- wks = Ngl.open_wks("png","plot_mptick_10") #-- open workstation #----------------------------------- #-- first plot: Lambert Conformal #----------------------------------- #-- northern hemisphere minlon = -90. #-- min lon to mask maxlon = 40. #-- max lon to mask minlat = 20. #-- min lat to mask maxlat = 80. #-- max lat to mask mpres = Ngl.Resources() #-- resource object mpres.nglMaximize = True mpres.nglDraw = False #-- turn off plot draw and frame advance. We will mpres.nglFrame = False #-- do it later after adding subtitles.
f=Nio.open_file("/home/smc001/hall4/zet.nc","r") print f temp=f.variables["ZET_vgrid5"] #lat=f.variables["lat"] #lon=f.variables["lon"] lat=xr.open_dataset('/home/smc001/hall4/zet.nc').lat lon=xr.open_dataset('/home/smc001/hall4/zet.nc').lon temp1=temp[0,50,:,:] nlon=len(lon[:,0]) nlat=len(lat[0,:]) wks_type="png" wks = Ngl.open_wks(wks_type, "zet_1km") resources = Ngl.Resources() resources.gsnMaximize = True resources.cnFillOn = True resources.cnLinesOn = False resources.cnLineLabelsOn = False cmap=Ngl.read_colormap_file("radar_1") cmap[0:7,:]=1. resources.cnFillPalette = cmap resources.lbOrientation = "Vertical" resources.mpDataBaseVersion = "MediumRes" resources.gsnAddCyclic = False resources.sfXArray = lon.values resources.sfYArray = lat.values resources.cnLevelSelectionMode = "ExplicitLevels"
# from __future__ import print_function import Ngl import numpy M = 29 N = 25 T = numpy.zeros([N, M]) # # create a mound as a test data set # jspn = numpy.power(range(-M // 2 + 5, M // 2 + 5), 2) ispn = numpy.power(range(-N // 2 - 3, N // 2 - 3), 2) for i in range(len(ispn)): T[i, :] = ispn[i] + jspn T = 100. - 8. * numpy.sqrt(T) # # Open a workstation and draw the contour plot with color fill. # wks_type = "png" wks = Ngl.open_wks(wks_type, "cn02p") res = Ngl.Resources() res.cnFillOn = True Ngl.contour(wks, T, res) Ngl.end()
# Set up arrays for polygons, polymarkers, and polylines. # xx = numpy.array([1., 32., 64.], 'f') ytopline = [0.5, 0.5, 0.5] # Top line ymidline = [0.0, 0.0, 0.0] # Middle line ybotline = [-0.5, -0.5, -0.5] # Bottom line xdots = x[26:37:5] # X and Y coordinates for polymarkers. ydots = y[26:37:5] xsquare = [16.0, 48.0, 48.0, 16.0, 16.0] # X and Y coordinates ysquare = [-0.5, -0.5, 0.5, 0.5, -0.5] # for polygon. # Send output to PNG file wks_type = "png" wks = Ngl.open_wks(wks_type, "xy2") # # Set up common resources for the XY plots. # xyres = Ngl.Resources() xyres.nglDraw = False xyres.nglFrame = False xyres.trXMaxF = 64 # Create first XY plot, but don't draw it yet. xy1 = Ngl.xy(wks, x, y, xyres) # # Set some resources for the primitives to be drawn.
#---Read variable to plot f = Nio.open_file(mpas_file) temp = f.variables["temperature"][0,:,0] #---Read edge and lat/lon information lonCell = f.variables["lonCell"][:] latCell = f.variables["latCell"][:] #---Convert to degrees from radians RAD2DEG = 180.0/(math.atan(1)*4.0) latCell = latCell * RAD2DEG lonCell = lonCell * RAD2DEG #---Start the graphics wks_type = "png" wks = Ngl.open_wks(wks_type,"mpas3") res = Ngl.Resources() # Plot mods desired. res.cnFillOn = True # color plot desired res.cnFillMode = "RasterFill" res.cnFillPalette = "ncl_default" res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off contour labels res.cnLevelSpacingF = 0.5 # 2 was chosen res.lbOrientation = "Horizontal" # vertical by default res.lbBoxLinesOn = False # turn off labelbar boxes res.lbLabelFontHeightF = 0.01 res.mpFillOn = True
diri = "./" #-- data directory fname = "rectilinear_grid_2D.nc" #-- data file name #-- open file and read variables f = Nio.open_file(diri + fname, "r") #-- open data file temp = f.variables["tsurf"][0, :, :] #-- first time step u = f.variables["u10"][0, :, :] #-- first time step v = f.variables["v10"][0, :, :] #-- first time step lat = f.variables["lat"][:] #-- all latitudes lon = f.variables["lon"][:] #-- all longitudes nlon = len(lon) #-- number of longitudes nlat = len(lat) #-- number of latitudes #-- open a workstation wkres = Ngl.Resources() #-- generate an resources object for workstation wkres.wkWidth = 2500 #-- plot resolution 2500 pixel width wkres.wkHeight = 2500 #-- plot resolution 2500 pixel height wks_type = "png" #-- graphics output type wks_name = os.path.basename(__file__).split(".")[0] wks = Ngl.open_wks(wks_type, wks_name, wkres) #-- create 1st plot: vectors on global map res = Ngl.Resources() res.tiMainString = "~F25~Wind velocity vectors" #-- title string res.tiMainFontHeightF = 0.024 #-- decrease title font size res.mpLimitMode = "Corners" #-- select a sub-region res.mpLeftCornerLonF = float(lon[0]) #-- left longitude value res.mpRightCornerLonF = float(lon[nlon - 1]) #-- right longitude value
jr = i + 1 jl = i - 1 while np.isnan(lat[jr]): jr += 1 while np.isnan(lat[jl]): jl -= 1 lat[i] = 0.5 * (lat[jl] + lat[jr]) ''' Plot ''' (lon_m, lat_m, hgt_m) = read_topo_bin() lon_m = np.ravel(lon_m[:, :]) lat_m = np.ravel(lat_m[:, :]) hgt_m = np.ravel(hgt_m[:, :]) print(hgt_m.shape) print(lat_m.shape) res = Ngl.Resources() (wks, res) = wks_setting(res) res.sfXArray = lon_m res.sfYArray = lat_m #res.caXMissingV = undef ;res.caYMissingV = res.caXMissingV res.sfMissingValueV = undef # Contour options res.cnFillOn = True # turn on contour fill res.cnMissingValFillColor = [0.194771, 0.210458, 0.610458] res.cnLinesOn = True # turn off contour lines res.cnLineLabelsOn = False # turn off line labels #res.cnFillMode = "RasterFill" res.lbLabelFontHeightF = 0.015 # default is a bit large #print(np.arange(125,3125,125))