You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <js...@us...> - 2007-11-05 19:47:41
|
Revision: 4111 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4111&view=rev Author: jswhit Date: 2007-11-05 11:47:27 -0800 (Mon, 05 Nov 2007) Log Message: ----------- support for orthographic Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 17:30:08 UTC (rev 4110) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 19:47:27 UTC (rev 4111) @@ -661,7 +661,7 @@ # set defaults for area_thresh. self.resolution = resolution - if area_thresh is None: + if area_thresh is None and resolution is not None: if resolution == 'c': area_thresh = 10000. elif resolution == 'l': @@ -681,13 +681,11 @@ self.coastsegs, self.coastpolygontypes = self._readboundarydata('gshhs') # reformat for use in matplotlib.patches.Polygon. self.coastpolygons = [] - for xy in self.coastsegs: - x, y = zip(*xy) - self.coastpolygons.append((x,y)) - # split coastline segments that jump across entire plot. + # also, split coastline segments that jump across entire plot. coastsegs = [] for seg in self.coastsegs: x, y = zip(*seg) + self.coastpolygons.append((x,y)) x = npy.array(x,npy.float64); y = npy.array(y,npy.float64) xd = (x[1:]-x[0:-1])**2 yd = (y[1:]-y[0:-1])**2 @@ -749,13 +747,29 @@ # see if map projection region polygon contains a pole. NPole = PointShape(self(0.,90.)) SPole = PointShape(self(0.,-90.)) - hasNP = self._boundarypolyxy.contains(NPole) - hasSP = self._boundarypolyxy.contains(SPole) + boundarypolyxy = self._boundarypolyxy + hasNP = boundarypolyxy.contains(NPole) + hasSP = boundarypolyxy.contains(SPole) containsPole = hasNP or hasSP # make sure geostationary projection has containsPole=False # even if only a limited area is requested (since entire # disk will be used to subset boundary geometries). if self.projection == 'geos': containsPole = False + # make sure orthographic projection has containsPole=True + # we will compute the intersections in stereographic + # coordinates, then transform to orthographic. + if self.projection == 'ortho': + containsPole = True + lon_0=self.projparams['lon_0'] + lat_0=self.projparams['lat_0'] + # FIXME: won't work for points exactly on equator?? + if npy.abs(lat_0) < 1.e-4: lat_0 = 1.e04 + maptran = pyproj.Proj(proj='stere',lon_0=lon_0,lat_0=lat_0) + # boundary polygon for orthographic projection + # in stereographic coorindates. + b = npy.asarray(self._boundarypolyll.boundary) + blons = b[:,0]; blats = b[:,1] + boundarypolyxy = PolygonShape(zip(*maptran(blons,blats))) # iterate over boundary geometries. for line in bdatmetafile: linesplit = line.split() @@ -828,7 +842,13 @@ b = npy.asarray(poly.boundary) else: b = npy.asarray(poly.coords) - bx, by = self(b[:,0], b[:,1]) + blons = b[:,0]; blats = b[:,1] + # special case for ortho, compute polygon + # coordinates in stereographic coords. + if self.projection == 'ortho': + bx, by = maptran(blons, blats) + else: + bx, by = self(blons, blats) mask = npy.logical_and(bx<1.e20,by<1.e20) # if less than two points are valid in # map proj coords, skip this geometry. @@ -841,9 +861,9 @@ bx = npy.compress(mask, bx) by = npy.compress(mask, by) poly = LineShape(zip(bx,by)) - if self._boundarypolyxy.intersects(poly): + if boundarypolyxy.intersects(poly): try: - poly = self._boundarypolyxy.intersection(poly) + poly = boundarypolyxy.intersection(poly) except: continue if hasattr(poly,'geoms'): @@ -855,6 +875,19 @@ b = npy.asarray(psub.boundary) else: b = npy.asarray(psub.coords) + # if projection == 'ortho', + # transform polygon from stereographic + # to orthographic coordinates. + if self.projection == 'ortho': + # if coastline polygon covers more than 99% + # of map region, it's probably bogus, so + # skip it. + if name == 'gshhs' and \ + psub.area/boundarypolyxy.area > 0.99: continue + bx = b[:,0]; by = b[:,1] + blons, blats = maptran(bx, by, inverse=True) + bx, by = self(blons, blats) + b[:,0] = bx; b[:,1] = by polygons.append(zip(b[:,0],b[:,1])) polygon_types.append(type) return polygons, polygon_types This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2007-11-05 17:30:28
|
Revision: 4110 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4110&view=rev Author: mdboom Date: 2007-11-05 09:30:08 -0800 (Mon, 05 Nov 2007) Log Message: ----------- Make STIX fonts work. Modified Paths: -------------- trunk/matplotlib/examples/mathtext_examples.py trunk/matplotlib/lib/matplotlib/_mathtext_data.py trunk/matplotlib/lib/matplotlib/config/mplconfig.py trunk/matplotlib/lib/matplotlib/config/rcsetup.py trunk/matplotlib/lib/matplotlib/mathtext.py trunk/matplotlib/lib/matplotlib/rcsetup.py trunk/matplotlib/matplotlibrc.template Modified: trunk/matplotlib/examples/mathtext_examples.py =================================================================== --- trunk/matplotlib/examples/mathtext_examples.py 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/examples/mathtext_examples.py 2007-11-05 17:30:08 UTC (rev 4110) @@ -48,7 +48,8 @@ r'$\mathcal{H} = \int d \tau \left(\epsilon E^2 + \mu H^2\right)$', r'$\widehat{abc}\widetilde{def}$', r'$\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega$', - r'$\alpha \beta \gamma \delta \epsilon \zeta \eta \theta \iota \lambda \mu \nu \xi \pi \kappa \rho \sigma \tau \upsilon \phi \chi \psi$' + r'$\alpha \beta \gamma \delta \epsilon \zeta \eta \theta \iota \lambda \mu \nu \xi \pi \kappa \rho \sigma \tau \upsilon \phi \chi \psi$', + ur'Generic symbol: $\u23ce \mathrm{\ue0f2}$' ] from pylab import * Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007-11-05 17:30:08 UTC (rev 4110) @@ -1755,7 +1755,10 @@ uni2type1 = dict([(v,k) for k,v in type12uni.items()]) -tex2uni = {'doteq': 8784, +tex2uni = { +'widehat': 0x0302, +'widetilde': 0x0303, +'doteq': 8784, 'partial': 8706, 'gg': 8811, 'asymp': 8781, Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2007-11-05 17:30:08 UTC (rev 4110) @@ -166,7 +166,7 @@ it = T.Trait('serif:oblique' , mplT.FontconfigPatternHandler()) bf = T.Trait('serif:bold' , mplT.FontconfigPatternHandler()) sf = T.Trait('sans' , mplT.FontconfigPatternHandler()) - use_cm = T.true + fontset = T.Trait('cm', 'cm', 'stix', 'custom') fallback_to_cm = T.true class axes(TConfig): @@ -344,7 +344,7 @@ 'mathtext.it' : (self.tconfig.mathtext, 'it'), 'mathtext.bf' : (self.tconfig.mathtext, 'bf'), 'mathtext.sf' : (self.tconfig.mathtext, 'sf'), - 'mathtext.use_cm' : (self.tconfig.mathtext, 'use_cm'), + 'mathtext.fontset' : (self.tconfig.mathtext, 'fontset'), 'mathtext.fallback_to_cm' : (self.tconfig.mathtext, 'fallback_to_cm'), 'image.aspect' : (self.tconfig.image, 'aspect'), Modified: trunk/matplotlib/lib/matplotlib/config/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2007-11-05 17:30:08 UTC (rev 4110) @@ -203,6 +203,8 @@ parse_fontconfig_pattern(s) return s +validate_fontset = ValidateInStrings('fontset', ['cm', 'stix', 'custom']) + validate_verbose = ValidateInStrings('verbose',[ 'silent', 'helpful', 'debug', 'debug-annoying', ]) @@ -365,7 +367,7 @@ 'mathtext.it' : ['serif:italic', validate_font_properties], 'mathtext.bf' : ['serif:bold', validate_font_properties], 'mathtext.sf' : ['sans\-serif', validate_font_properties], - 'mathtext.use_cm' : [True, validate_bool], + 'mathtext.fontset' : ['cm', validate_fontset], 'mathtext.fallback_to_cm' : [True, validate_bool], 'image.aspect' : ['equal', validate_aspect], # equal, auto, a number Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007-11-05 17:30:08 UTC (rev 4110) @@ -528,7 +528,7 @@ A generic base class for all font setups that use Truetype fonts (through ft2font) """ - basepath = os.path.join( get_data_path(), 'fonts', 'ttf' ) + basepath = os.path.join( get_data_path(), 'fonts' ) class CachedFont: def __init__(self, font): @@ -665,7 +665,7 @@ TruetypeFonts.__init__(self, *args, **kwargs) if not len(self.fontmap): for key, val in self._fontmap.iteritems(): - fullpath = os.path.join(self.basepath, val + ".ttf") + fullpath = os.path.join(self.basepath, 'ttf', val + ".ttf") self.fontmap[key] = fullpath self.fontmap[val] = fullpath @@ -750,7 +750,8 @@ """ fontmap = {} - + use_cmex = True + def __init__(self, *args, **kwargs): # This must come first so the backend's owner is set correctly if rcParams['mathtext.fallback_to_cm']: @@ -772,18 +773,20 @@ def _get_glyph(self, fontname, sym, fontsize): found_symbol = False - uniindex = latex_to_cmex.get(sym) - if uniindex is not None: - fontname = 'ex' - found_symbol = True - else: + if self.use_cmex: + uniindex = latex_to_cmex.get(sym) + if uniindex is not None: + fontname = 'ex' + found_symbol = True + + if not found_symbol: try: uniindex = get_unicode_index(sym) found_symbol = True except ValueError: uniindex = ord('?') warn("No TeX to unicode mapping for '%s'" % - sym.encode('ascii', 'replace'), + sym.encode('ascii', 'backslashreplace'), MathTextWarning) # Only characters in the "Letter" class should be italicized in 'it' @@ -804,7 +807,7 @@ except KeyError: warn("Font '%s' does not have a glyph for '%s'" % (cached_font.font.postscript_name, - sym.encode('ascii', 'replace')), + sym.encode('ascii', 'backslashreplace')), MathTextWarning) found_symbol = False @@ -815,6 +818,7 @@ return self.cm_fallback._get_glyph(fontname, sym, fontsize) else: warn("Substituting with a dummy symbol.", MathTextWarning) + fontname = 'rm' new_fontname = fontname cached_font = self._get_font(fontname) uniindex = 0xA4 # currency character, for lack of anything better @@ -829,6 +833,71 @@ return self.cm_fallback.get_sized_alternatives_for_symbol( fontname, sym) return [(fontname, sym)] + +class StixFonts(UnicodeFonts): + _fontmap = { 'rm' : ('STIXGeneral', 'otf'), + 'tt' : ('VeraMono', 'ttf'), + 'it' : ('STIXGeneralItalic', 'otf'), + 'bf' : ('STIXGeneralBol', 'otf'), + 'sf' : ('Vera', 'ttf'), + 'nonunirm' : ('STIXNonUni', 'otf'), + 'nonuniit' : ('STIXNonUniIta', 'otf'), + 'nonunibf' : ('STIXNonUniBol', 'otf'), + + 0 : ('STIXGeneral', 'otf'), + 1 : ('STIXSiz1Sym', 'otf'), + 2 : ('STIXSiz2Sym', 'otf'), + 3 : ('STIXSiz3Sym', 'otf'), + 4 : ('STIXSiz4Sym', 'otf'), + 5 : ('STIXSiz5Sym', 'otf') + } + fontmap = {} + use_cmex = False + cm_fallback = False + + def __init__(self, *args, **kwargs): + TruetypeFonts.__init__(self, *args, **kwargs) + if not len(self.fontmap): + for key, (name, ext) in self._fontmap.iteritems(): + fullpath = os.path.join(self.basepath, ext, name + "." + ext) + self.fontmap[key] = fullpath + self.fontmap[name] = fullpath + + def _get_glyph(self, fontname, sym, fontsize): + # Handle calligraphic letters + if fontname == 'cal': + if len(sym) != 1 or ord(sym) < ord('A') or ord(sym) > ord('Z'): + raise ValueError(r"Sym '%s' is not available in \mathcal font" % sym) + fontname = 'nonuniit' + sym = unichr(ord(sym) + 0xe22d - ord('A')) + + # Handle private use area glyphs + if (fontname in ('it', 'rm', 'bf') and + len(sym) == 1 and ord(sym) >= 0xe000 and ord(sym) <= 0xf8ff): + fontname = 'nonuni' + fontname + + return UnicodeFonts._get_glyph(self, fontname, sym, fontsize) + + _size_alternatives = {} + def get_sized_alternatives_for_symbol(self, fontname, sym): + alternatives = self._size_alternatives.get(sym) + if alternatives: + return alternatives + + alternatives = [] + try: + uniindex = get_unicode_index(sym) + except ValueError: + return [(fontname, sym)] + + for i in range(6): + cached_font = self._get_font(i) + glyphindex = cached_font.charmap.get(uniindex) + if glyphindex is not None: + alternatives.append((i, unichr(uniindex))) + + self._size_alternatives[sym] = alternatives + return alternatives class StandardPsFonts(Fonts): """ @@ -1091,7 +1160,7 @@ Node.__init__(self) self.c = c self.font_output = state.font_output - assert isinstance(state.font, str) + assert isinstance(state.font, (str, unicode, int)) self.font = state.font self.fontsize = state.fontsize self.dpi = state.dpi @@ -1876,7 +1945,7 @@ ) | Error(r"Expected \hspace{n}")) ).setParseAction(self.customspace).setName('customspace') - symbol =(Regex(r"([a-zA-Z0-9 +\-*/<>=:,.;!'@()])|(\\[%${}\[\]])") + symbol =(Regex(ur"([a-zA-Z0-9 +\-*/<>=:,.;!'@()\u0080-\uffff])|(\\[%${}\[\]])") | Combine( bslash + oneOf(tex2uni.keys()) @@ -2508,10 +2577,15 @@ font_output = StandardPsFonts(prop) else: backend = self._backend_mapping[self._output]() - if rcParams['mathtext.use_cm']: + fontset = rcParams['mathtext.fontset'] + if fontset == 'cm': font_output = BakomaFonts(prop, backend) + elif fontset == 'stix': + font_output = StixFonts(prop, backend) + elif fontset == 'custom': + font_output = UnicodeFonts(prop, backend) else: - font_output = UnicodeFonts(prop, backend) + raise ValueError("mathtext.fontset must be either 'cm', 'stix', or 'custom'") fontsize = prop.get_size_in_points() Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/rcsetup.py 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2007-11-05 17:30:08 UTC (rev 4110) @@ -202,7 +202,9 @@ def validate_font_properties(s): parse_fontconfig_pattern(s) return s - + +validate_fontset = ValidateInStrings('fontset', ['cm', 'stix', 'custom']) + validate_verbose = ValidateInStrings('verbose',[ 'silent', 'helpful', 'debug', 'debug-annoying', ]) @@ -365,7 +367,7 @@ 'mathtext.it' : ['serif:italic', validate_font_properties], 'mathtext.bf' : ['serif:bold', validate_font_properties], 'mathtext.sf' : ['sans\-serif', validate_font_properties], - 'mathtext.use_cm' : [True, validate_bool], + 'mathtext.fontset' : [True, validate_fontset], 'mathtext.fallback_to_cm' : [True, validate_bool], 'image.aspect' : ['equal', validate_aspect], # equal, auto, a number Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2007-11-05 16:50:11 UTC (rev 4109) +++ trunk/matplotlib/matplotlibrc.template 2007-11-05 17:30:08 UTC (rev 4110) @@ -160,20 +160,18 @@ # processing. # The following settings allow you to select the fonts in math mode. -# They map from a TeX font name to a set of arguments for the FontProperties constructor. -# (See FontProperties for more details). -# These settings are only used if mathtext.use_cm is False, otherwise, the -# Bakoma TeX Computer Modern fonts are used. +# They map from a TeX font name to a fontconfig font pattern. +# These settings are only used if mathtext.fontset is 'custom'. #mathtext.cal : cursive #mathtext.rm : serif #mathtext.tt : monospace #mathtext.it : serif:italic #mathtext.bf : serif:bold #mathtext.sf : sans -#mathtext.use_cm : True +#mathtext.fontset : cm # Should be 'cm' (Computer Modern), 'stix' or 'custom' #mathtext.fallback_to_cm : True # When True, use symbols from the Computer Modern # fonts when a symbol can not be found in one of - # the user-specified math fonts. + # the custom math fonts. ### AXES # default face and edge color, default tick sizes, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-05 16:50:25
|
Revision: 4109 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4109&view=rev Author: jswhit Date: 2007-11-05 08:50:11 -0800 (Mon, 05 Nov 2007) Log Message: ----------- fix for coastline segments that jump across plot. Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 16:11:12 UTC (rev 4108) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 16:50:11 UTC (rev 4109) @@ -682,9 +682,27 @@ # reformat for use in matplotlib.patches.Polygon. self.coastpolygons = [] for xy in self.coastsegs: - x = [x1 for x1,x2 in xy] - y = [x2 for x1,x2 in xy] + x, y = zip(*xy) self.coastpolygons.append((x,y)) + # split coastline segments that jump across entire plot. + coastsegs = [] + for seg in self.coastsegs: + x, y = zip(*seg) + x = npy.array(x,npy.float64); y = npy.array(y,npy.float64) + xd = (x[1:]-x[0:-1])**2 + yd = (y[1:]-y[0:-1])**2 + dist = npy.sqrt(xd+yd) + split = dist > 5000000. + if npy.sum(split) and self.projection not in ['merc','cyl','mill']: + ind = (npy.compress(split,squeeze(split*npy.indices(xd.shape)))+1).tolist() + iprev = 0 + ind.append(len(xd)) + for i in ind: + coastsegs.append(zip(x[iprev:i],y[iprev:i])) + iprev = i + else: + coastsegs.append(seg) + self.coastsegs = coastsegs def __call__(self,x,y,inverse=False): """ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-05 16:11:30
|
Revision: 4108 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4108&view=rev Author: jswhit Date: 2007-11-05 08:11:12 -0800 (Mon, 05 Nov 2007) Log Message: ----------- fixes for non-fulldisk geos and ortho, cleanups in _getmapboundary Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 15:45:00 UTC (rev 4107) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 16:11:12 UTC (rev 4108) @@ -734,6 +734,10 @@ hasNP = self._boundarypolyxy.contains(NPole) hasSP = self._boundarypolyxy.contains(SPole) containsPole = hasNP or hasSP + # make sure geostationary projection has containsPole=False + # even if only a limited area is requested (since entire + # disk will be used to subset boundary geometries). + if self.projection == 'geos': containsPole = False # iterate over boundary geometries. for line in bdatmetafile: linesplit = line.split() @@ -843,47 +847,55 @@ """ nx = 100 ny = 100 - if self.projection == 'ortho' and self._fulldisk: + maptran = self + if self.projection in ['ortho','geos']: # circular region. thetas = linspace(0.,2.*npy.pi,2*nx*ny)[:-1] - radius = self.rmajor - x = radius*npy.cos(thetas) + 0.5*self.xmax - y = radius*npy.sin(thetas) + 0.5*self.ymax + if self.projection == 'ortho': + rminor = self.rmajor + rmajor = self.rmajor + else: + rminor = self._height + rmajor = self._width + x = rmajor*npy.cos(thetas) + rmajor + y = rminor*npy.sin(thetas) + rminor boundaryxy = PolygonShape(zip(x,y)) - elif self.projection == 'geos' and self._fulldisk: - # elliptical region - thetas = linspace(0.,2.*npy.pi,2*nx*ny)[:-1] - rminor = self._height - rmajor = self._width - x = rmajor*npy.cos(thetas) + 0.5*self.xmax - y = rminor*npy.sin(thetas) + 0.5*self.ymax - boundaryxy = PolygonShape(zip(x,y)) + # compute proj instance for full disk, if necessary. + if not self._fulldisk: + projparms = self.projparams + del projparms['x_0'] + del projparms['y_0'] + if self.projection == 'ortho': + llcrnrx = -self.rmajor + llcrnry = -self.rmajor + urcrnrx = -llcrnrx + urcrnry = -llcrnry + else: + llcrnrx = -self._width + llcrnry = -self._height + urcrnrx = -llcrnrx + urcrnry = -llcrnry + projparms['x_0']=-llcrnrx + projparms['y_0']=-llcrnry + maptran = pyproj.Proj(projparms) elif self.projection in ['moll','robin','sinu']: # quasi-elliptical region. - x = []; y = [] + lon_0 = self.projparams['lon_0'] # left side lats1 = linspace(-89.9,89.9,ny).tolist() - lons1 = len(lats1)*[self.projparams['lon_0']-179.9] - x,y = self(lons1,lats1) + lons1 = len(lats1)*[lon_0-179.9] # top. - lons2 = linspace(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179,nx).tolist() + lons2 = linspace(lon_0-179.9,lon_0+179.9,nx).tolist() lats2 = len(lons2)*[89.9] - xx,yy = self(lons2,lats2) - x = x+xx; y = y+yy # right side lats3 = linspace(89.9,-89.9,ny).tolist() - lons3 = len(lats3)*[self.projparams['lon_0']+179.9] - xx,yy = self(lons3,lats3) - x = x+xx; y = y+yy + lons3 = len(lats3)*[lon_0+179.9] # bottom. - lons4 = linspace(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180).tolist() + lons4 = linspace(lon_0+179.9,lon_0-179.9,nx).tolist() lats4 = len(lons4)*[-89.9] - xx,yy = self(lons4,lats4) - x = x+xx; y = y+yy - x = npy.array(x,npy.float64) - y = npy.array(y,npy.float64) - lons = lons1+lons2+lons3+lons4 - lats = lats1+lats2+lats3+lats4 + lons = npy.array(lons1+lons2+lons3+lons4,npy.float64) + lats = npy.array(lats1+lats2+lats3+lats4,npy.float64) + x, y = maptran(lons,lats) boundaryxy = PolygonShape(zip(x,y)) else: # all other projections are rectangular. # left side (x = xmin, ymin <= y <= ymax) @@ -911,7 +923,7 @@ lats = [self.llcrnrlat, self.urcrnrlat, self.urcrnrlat, self.llcrnrlat] else: if self.projection not in ['moll','robin','sinu']: - lons, lats = self(x,y,inverse=True) + lons, lats = maptran(x,y,inverse=True) # fix lons so there are no jumps. n = 1 lonprev = lons[0] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2007-11-05 15:45:03
|
Revision: 4107 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4107&view=rev Author: mdboom Date: 2007-11-05 07:45:00 -0800 (Mon, 05 Nov 2007) Log Message: ----------- First pass at getting STIX fonts to work. Support .otf fonts in font_manager.py Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/_mathtext_data.py trunk/matplotlib/lib/matplotlib/font_manager.py trunk/matplotlib/lib/matplotlib/mathtext.py Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py =================================================================== --- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007-11-05 02:36:20 UTC (rev 4106) +++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2007-11-05 15:45:00 UTC (rev 4107) @@ -1885,7 +1885,7 @@ 'measeq': 8798, 'upharpoonleft': 8639, 'lq': 8216, -'Upsilon': 978, +'Upsilon': 933, 'subsetneq': 8842, 'greater': 62, 'supsetneq': 8843, @@ -2238,7 +2238,7 @@ 'combiningbreve' : 774, 'combiningoverline' : 772, 'combininggraveaccent' : 768, -'combiningacuteaccent' : 714, +'combiningacuteaccent' : 769, 'combiningdiaeresis' : 776, 'combiningtilde' : 771, 'combiningrightarrowabove' : 8407, Modified: trunk/matplotlib/lib/matplotlib/font_manager.py =================================================================== --- trunk/matplotlib/lib/matplotlib/font_manager.py 2007-11-05 02:36:20 UTC (rev 4106) +++ trunk/matplotlib/lib/matplotlib/font_manager.py 2007-11-05 15:45:00 UTC (rev 4107) @@ -36,7 +36,7 @@ import os, sys, glob, shutil from sets import Set import matplotlib -from matplotlib import afm +from matplotlib import afm from matplotlib import ft2font from matplotlib import rcParams, get_home, get_configdir from matplotlib.cbook import is_string_like @@ -95,6 +95,10 @@ path = os.path.join(home, '.fonts') X11FontDirectories.append(path) +def get_fontext_synonyms(fontext): + return {'ttf': ('ttf', 'otf'), + 'afm': ('afm',)}[fontext] + def win32FontDirectory(): """Return the user-specified font directory for Win32.""" @@ -121,6 +125,8 @@ if directory is None: directory = win32FontDirectory() + fontext = get_fontext_synonyms(fontext) + key, items = None, {} for fontdir in MSFontDirectories: try: @@ -129,7 +135,10 @@ continue if not local: - return glob.glob(os.path.join(directory, '*.'+fontext)) + files = [] + for ext in fontext: + files.extend(glob.glob(os.path.join(directory, '*.'+ext))) + return files try: for j in range(_winreg.QueryInfoKey(local)[1]): try: @@ -137,7 +146,7 @@ if not os.path.dirname(direc): direc = os.path.join(directory, direc) direc = os.path.abspath(direc).lower() - if direc[-4:] == '.'+fontext: + if os.path.splitext(direc)[1][1:] in fontext: items[direc] = 1 except EnvironmentError: continue @@ -168,13 +177,16 @@ if directory is None: directory = OSXFontDirectory() + fontext = get_fontext_synonyms(fontext) + files = [] for path in directory: if fontext is None: files.extend(glob.glob(os.path.join(path,'*'))) else: - files.extend(glob.glob(os.path.join(path, '*.'+fontext))) - files.extend(glob.glob(os.path.join(path, '*.'+fontext.upper()))) + for ext in fontext: + files.extend(glob.glob(os.path.join(path, '*.'+ext))) + files.extend(glob.glob(os.path.join(path, '*.'+ext.upper()))) return files @@ -201,12 +213,14 @@ except ImportError: return {} + fontext = get_fontext_synonyms(fontext) + fontfiles = {} status, output = commands.getstatusoutput("fc-list file") if status == 0: for line in output.split('\n'): fname = line.split(':')[0] - if (os.path.splitext(fname)[1] == "." + fontext and + if (os.path.splitext(fname)[1][1:] in fontext and os.path.exists(fname)): fontfiles[fname] = 1 @@ -221,7 +235,8 @@ AFM fonts as an option. """ fontfiles = {} - + fontexts = get_fontext_synonyms(fontext) + if fontpaths is None: if sys.platform == 'win32': fontdir = win32FontDirectory() @@ -230,7 +245,7 @@ # now get all installed fonts directly... for f in win32InstalledFonts(fontdir): base, ext = os.path.splitext(f) - if len(ext)>1 and ext[1:].lower()==fontext: + if len(ext)>1 and ext[1:].lower() in fontexts: fontfiles[f] = 1 else: fontpaths = x11FontDirectory() @@ -246,8 +261,10 @@ fontpaths = [fontpaths] for path in fontpaths: - files = glob.glob(os.path.join(path, '*.'+fontext)) - files.extend(glob.glob(os.path.join(path, '*.'+fontext.upper()))) + files = [] + for ext in fontexts: + files.extend(glob.glob(os.path.join(path, '*.'+ext))) + files.extend(glob.glob(os.path.join(path, '*.'+ext.upper()))) for fname in files: fontfiles[os.path.abspath(fname)] = 1 @@ -1047,16 +1064,17 @@ def fc_match(pattern, fontext): import commands + fontexts = get_fontext_synonyms(fontext) ext = "." + fontext status, output = commands.getstatusoutput('fc-match -sv "%s"' % pattern) if status == 0: for match in _fc_match_regex.finditer(output): file = match.group(1) - if os.path.splitext(file)[1] == ext: + if os.path.splitext(file)[1][1:] in fontexts: return file return None - _fc_match_regex = re.compile(r'\sfile:\s+"(.*)"') + _fc_match_regex = re.compile(r'\sfile:\s+"([^"]*)"') _fc_match_cache = {} def findfont(prop, fontext='ttf'): Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2007-11-05 02:36:20 UTC (rev 4106) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2007-11-05 15:45:00 UTC (rev 4107) @@ -814,6 +814,7 @@ MathTextWarning) return self.cm_fallback._get_glyph(fontname, sym, fontsize) else: + warn("Substituting with a dummy symbol.", MathTextWarning) new_fontname = fontname cached_font = self._get_font(fontname) uniindex = 0xA4 # currency character, for lack of anything better This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2007-11-05 02:36:22
|
Revision: 4106 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4106&view=rev Author: efiring Date: 2007-11-04 18:36:20 -0800 (Sun, 04 Nov 2007) Log Message: ----------- Added easy access to minor tick properties (Pierre G-M) Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/axis.py Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2007-11-05 01:36:15 UTC (rev 4105) +++ trunk/matplotlib/lib/matplotlib/axes.py 2007-11-05 02:36:20 UTC (rev 4106) @@ -1173,8 +1173,8 @@ # Otherwise, it will compute the bounds of it's current data # and the data in xydata xys = npy.asarray(xys) - + self.dataLim.update_numerix_xy(xys, -1) @@ -1631,25 +1631,33 @@ self.xaxis.set_minor_formatter(mticker.NullFormatter()) self.transData.get_funcx().set_type( mtrans.IDENTITY ) - def get_xticks(self): + def get_xticks(self, minor=False): 'Return the x ticks as a list of locations' - return self.xaxis.get_ticklocs() + return self.xaxis.get_ticklocs(minor=minor) - def set_xticks(self, ticks): + def set_xticks(self, ticks, minor=False): """ Set the x ticks with list of ticks ACCEPTS: sequence of floats """ - return self.xaxis.set_ticks(ticks) + return self.xaxis.set_ticks(ticks, minor=minor) - def get_xticklabels(self): + def get_xmajorticklabels(self): 'Get the xtick labels as a list of Text instances' - return cbook.silent_list('Text xticklabel', self.xaxis.get_ticklabels()) + return cbook.silent_list('Text xticklabel', self.xaxis.get_majorticklabels()) - def set_xticklabels(self, labels, fontdict=None, **kwargs): + def get_xminorticklabels(self): + 'Get the xtick labels as a list of Text instances' + return cbook.silent_list('Text xticklabel', self.xaxis.get_minorticklabels()) + + def get_xticklabels(self, minor=False): + 'Get the xtick labels as a list of Text instances' + return cbook.silent_list('Text xticklabel', self.xaxis.get_ticklabels(minor=minor)) + + def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs): """ - SET_XTICKLABELS(labels, fontdict=None, **kwargs) + set_xticklabels(labels, fontdict=None, minor=False, **kwargs) Set the xtick labels with list of strings labels Return a list of axis text instances. @@ -1659,7 +1667,7 @@ ACCEPTS: sequence of strings """ - return self.xaxis.set_ticklabels(labels, fontdict, **kwargs) + return self.xaxis.set_ticklabels(labels, fontdict, minor=minor, **kwargs) set_xticklabels.__doc__ = cbook.dedent(set_xticklabels.__doc__) % martist.kwdocd def invert_yaxis(self): @@ -1795,25 +1803,33 @@ self.yaxis.set_minor_formatter(mticker.NullFormatter()) self.transData.get_funcy().set_type( mtrans.IDENTITY ) - def get_yticks(self): + def get_yticks(self, minor=False): 'Return the y ticks as a list of locations' - return self.yaxis.get_ticklocs() + return self.yaxis.get_ticklocs(minor=minor) - def set_yticks(self, ticks): + def set_yticks(self, ticks, minor=False): """ Set the y ticks with list of ticks ACCEPTS: sequence of floats """ - return self.yaxis.set_ticks(ticks) + return self.yaxis.set_ticks(ticks, minor=minor) - def get_yticklabels(self): - 'Get the ytick labels as a list of Text instances' - return cbook.silent_list('Text yticklabel', self.yaxis.get_ticklabels()) + def get_ymajorticklabels(self): + 'Get the xtick labels as a list of Text instances' + return cbook.silent_list('Text yticklabel', self.yaxis.get_majorticklabels()) - def set_yticklabels(self, labels, fontdict=None, **kwargs): + def get_yminorticklabels(self): + 'Get the xtick labels as a list of Text instances' + return cbook.silent_list('Text yticklabel', self.yaxis.get_minorticklabels()) + + def get_yticklabels(self, minor=False): + 'Get the xtick labels as a list of Text instances' + return cbook.silent_list('Text yticklabel', self.yaxis.get_ticklabels(minor=minor)) + + def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs): """ - SET_YTICKLABELS(labels, fontdict=None, **kwargs) + set_yticklabels(labels, fontdict=None, minor=False, **kwargs) Set the ytick labels with list of strings labels. Return a list of Text instances. @@ -1823,7 +1839,7 @@ ACCEPTS: sequence of strings """ - return self.yaxis.set_ticklabels(labels, fontdict, **kwargs) + return self.yaxis.set_ticklabels(labels, fontdict, minor=minor, **kwargs) set_yticklabels.__doc__ = cbook.dedent(set_yticklabels.__doc__) % martist.kwdocd def toggle_log_lineary(self): @@ -3702,7 +3718,7 @@ if xerr is not None: if iterable(xerr) and len(xerr)==2: - # using list comps rather than arrays to preserve units + # using list comps rather than arrays to preserve units left = [thisx-thiserr for (thisx, thiserr) in cbook.safezip(x,xerr[0])] right = [thisx+thiserr for (thisx, thiserr) in cbook.safezip(x,xerr[1])] else: Modified: trunk/matplotlib/lib/matplotlib/axis.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axis.py 2007-11-05 01:36:15 UTC (rev 4105) +++ trunk/matplotlib/lib/matplotlib/axis.py 2007-11-05 02:36:20 UTC (rev 4106) @@ -520,8 +520,8 @@ def get_children(self): children = [self.label] majorticks = self.get_major_ticks() - minorticks = self.get_minor_ticks() - + minorticks = self.get_minor_ticks() + children.extend(majorticks) children.extend(minorticks) return children @@ -661,24 +661,62 @@ 'Return the depth of the axis used by the picker' return self.pickradius - def get_ticklabels(self): - 'Return a list of Text instances for ticklabels' + def get_majorticklabels(self): + 'Return a list of Text instances for the major ticklabels' ticks = self.get_major_ticks() labels1 = [tick.label1 for tick in ticks if tick.label1On] labels2 = [tick.label2 for tick in ticks if tick.label2On] - return silent_list('Text ticklabel', labels1+labels2) + return silent_list('Text major ticklabel', labels1+labels2) - def get_ticklines(self): - 'Return the ticklines lines as a list of Line2D instance' + def get_minorticklabels(self): + 'Return a list of Text instances for the minor ticklabels' + ticks = self.get_minor_ticks() + labels1 = [tick.label1 for tick in ticks if tick.label1On] + labels2 = [tick.label2 for tick in ticks if tick.label2On] + return silent_list('Text minor ticklabel', labels1+labels2) + + def get_ticklabels(self, minor=False): + 'Return a list of Text instances for ticklabels' + if minor: + return self.get_minorticklabels() + return self.get_majorticklabels() + + def get_majorticklines(self): + 'Return the major tick lines as a list of Line2D instances' lines = [] - ticks = self.get_major_ticks() + ticks = self.get_major_ticks() for tick in ticks: lines.append(tick.tick1line) lines.append(tick.tick2line) return silent_list('Line2D ticklines', lines) - def get_ticklocs(self): + def get_minorticklines(self): + 'Return the minor tick lines as a list of Line2D instances' + lines = [] + ticks = self.get_minor_ticks() + for tick in ticks: + lines.append(tick.tick1line) + lines.append(tick.tick2line) + return silent_list('Line2D ticklines', lines) + + def get_ticklines(self, minor=False): + 'Return the tick lines as a list of Line2D instances' + if minor: + return self.get_minorticklines() + return self.get_majorticklines() + + def get_majorticklocs(self): + "Get the major tick locations in data coordinates as a numpy array" + return self.major.locator() + + def get_minorticklocs(self): + "Get the minor tick locations in data coordinates as a numpy array" + return self.minor.locator() + + def get_ticklocs(self, minor=False): "Get the tick locations in data coordinates as a numpy array" + if minor: + return self.minor.locator() return self.major.locator() def _get_tick(self, major): @@ -718,15 +756,12 @@ def get_major_ticks(self): 'get the tick instances; grow as necessary' - numticks = len(self.major.locator()) - if len(self.majorTicks)<numticks: # update the new tick label properties from the old protoTick = self.majorTicks[0] for i in range(numticks-len(self.majorTicks)): tick = self._get_tick(major=True) - #tick = protoTick if self._gridOnMajor: tick.gridOn = True self._copy_tick_props(protoTick, tick) self.majorTicks.append(tick) @@ -915,24 +950,28 @@ def set_ticklabels(self, ticklabels, *args, **kwargs): """ Set the text values of the tick labels. Return a list of Text - instances. + instances. Use kwarg minor=True to select minor ticks. ACCEPTS: sequence of strings """ #ticklabels = [str(l) for l in ticklabels] + minor = kwargs.pop('minor', False) + if minor: + self.set_minor_formatter(FixedFormatter(ticklabels)) + ticks = self.get_minor_ticks() + else: + self.set_major_formatter( FixedFormatter(ticklabels) ) + ticks = self.get_major_ticks() - self.set_major_formatter( FixedFormatter(ticklabels) ) - - ret = [] - for i, tick in enumerate(self.get_major_ticks()): + for i, tick in enumerate(ticks): if i<len(ticklabels): tick.label1.set_text(ticklabels[i]) ret.append(tick.label1) tick.label1.update(kwargs) return ret - def set_ticks(self, ticks): + def set_ticks(self, ticks, minor=False): """ Set the locations of the tick marks from sequence ticks @@ -940,9 +979,13 @@ """ ### XXX if the user changes units, the information will be lost here ticks = self.convert_units(ticks) - self.set_major_locator( FixedLocator(ticks) ) self.get_view_interval().update(ticks,0) - return self.get_major_ticks() + if minor: + self.set_minor_locator(FixedLocator(ticks)) + return self.get_minor_ticks() + else: + self.set_major_locator( FixedLocator(ticks) ) + return self.get_major_ticks() def _update_label_position(self, bboxes, bboxes2): """ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-05 01:36:18
|
Revision: 4105 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4105&view=rev Author: jswhit Date: 2007-11-04 17:36:15 -0800 (Sun, 04 Nov 2007) Log Message: ----------- fixed mollweide Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 22:14:41 UTC (rev 4104) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-05 01:36:15 UTC (rev 4105) @@ -862,26 +862,28 @@ # quasi-elliptical region. x = []; y = [] # left side - lats = linspace(-89.9,89.9,ny).tolist() - lons = len(lats)*[self.projparams['lon_0']-179.9] - x,y = self(lons,lats) + lats1 = linspace(-89.9,89.9,ny).tolist() + lons1 = len(lats1)*[self.projparams['lon_0']-179.9] + x,y = self(lons1,lats1) # top. - lons = linspace(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179,nx).tolist() - lats = len(lons)*[89.9] - xx,yy = self(lons,lats) + lons2 = linspace(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179,nx).tolist() + lats2 = len(lons2)*[89.9] + xx,yy = self(lons2,lats2) x = x+xx; y = y+yy # right side - lats = linspace(89.9,-89.9,ny).tolist() - lons = len(lats)*[self.projparams['lon_0']+179.9] - xx,yy = self(lons,lats) + lats3 = linspace(89.9,-89.9,ny).tolist() + lons3 = len(lats3)*[self.projparams['lon_0']+179.9] + xx,yy = self(lons3,lats3) x = x+xx; y = y+yy # bottom. - lons = linspace(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180).tolist() - lats = len(lons)*[-89.9] - xx,yy = self(lons,lats) + lons4 = linspace(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180).tolist() + lats4 = len(lons4)*[-89.9] + xx,yy = self(lons4,lats4) x = x+xx; y = y+yy x = npy.array(x,npy.float64) y = npy.array(y,npy.float64) + lons = lons1+lons2+lons3+lons4 + lats = lats1+lats2+lats3+lats4 boundaryxy = PolygonShape(zip(x,y)) else: # all other projections are rectangular. # left side (x = xmin, ymin <= y <= ymax) @@ -908,21 +910,21 @@ lons = [self.llcrnrlon, self.llcrnrlon, self.urcrnrlon, self.urcrnrlon] lats = [self.llcrnrlat, self.urcrnrlat, self.urcrnrlat, self.llcrnrlat] else: - lons, lats = self(x,y,inverse=True) - # fix lons so there are no jumps. - n = 1 - lonprev = lons[0] - for lon,lat in zip(lons[1:],lats[1:]): - if npy.abs(lon-lonprev) > 90.: - if lonprev < 0: - lon = lon - 360. - else: - lon = lon + 360 - lons[n] = lon - lonprev = lon - n = n + 1 + if self.projection not in ['moll','robin','sinu']: + lons, lats = self(x,y,inverse=True) + # fix lons so there are no jumps. + n = 1 + lonprev = lons[0] + for lon,lat in zip(lons[1:],lats[1:]): + if npy.abs(lon-lonprev) > 90.: + if lonprev < 0: + lon = lon - 360. + else: + lon = lon + 360 + lons[n] = lon + lonprev = lon + n = n + 1 boundaryll = PolygonShape(zip(lons,lats)) - #print 'map projection region',boundaryll.geom_type,boundaryll.is_valid return PolygonShape(zip(lons,lats)), boundaryxy This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-04 22:14:43
|
Revision: 4104 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4104&view=rev Author: jswhit Date: 2007-11-04 14:14:41 -0800 (Sun, 04 Nov 2007) Log Message: ----------- fix Antarctica for moll,robin and sinu (moll still broken) Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 15:57:19 UTC (rev 4103) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 22:14:41 UTC (rev 4104) @@ -758,7 +758,7 @@ # regions and high-resolution boundary geometries). if not containsPole: # close Antarctica for cylindrical projections. - if name == 'gshhs' and self.projection in ['cyl','merc','mill']: + if name == 'gshhs' and self.projection in ['cyl','merc','mill','moll','robin','sinu']: b = npy.asarray(poly.boundary) lons = b[:,0] lats = b[:,1] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-04 15:57:22
|
Revision: 4103 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4103&view=rev Author: jswhit Date: 2007-11-04 07:57:19 -0800 (Sun, 04 Nov 2007) Log Message: ----------- remove debug code Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 06:09:22 UTC (rev 4102) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 15:57:19 UTC (rev 4103) @@ -777,10 +777,6 @@ lons.append(lonend) lats.append(-90.) poly = PolygonShape(zip(lons,lats)) - #b = npy.asarray(poly.boundary) - #import pylab - #pylab.fill(b[:,0],b[:,1],'b') - #pylab.show() else: continue if poly.intersects(self._boundarypolyll): @@ -797,8 +793,6 @@ b = npy.asarray(psub.coords) blons = b[:,0]; blats = b[:,1] bx, by = self(blons, blats) - #if (bx > 1.20).any() or (by > 1.e20).any(): - # continue polygons.append(zip(bx,by)) polygon_types.append(type) except: @@ -814,6 +808,8 @@ b = npy.asarray(poly.coords) bx, by = self(b[:,0], b[:,1]) mask = npy.logical_and(bx<1.e20,by<1.e20) + # if less than two points are valid in + # map proj coords, skip this geometry. if sum(mask) <= 1: continue if name == 'gshhs': poly = PolygonShape(zip(bx,by)) @@ -823,23 +819,6 @@ bx = npy.compress(mask, bx) by = npy.compress(mask, by) poly = LineShape(zip(bx,by)) - if 0: - import pylab - print poly - pp = self._boundarypolyxy.intersection(poly) - print name, pp - a = npy.asarray(self._boundarypolyxy.boundary) - pylab.plot(a[:,0],a[:,1],'b') - pylab.plot(bx,by,'r') - if hasattr(pp,'geoms'): - px = pp.geoms - else: - px = [pp] - for p in px: - c = npy.asarray(p.boundary) - pylab.fill(c[:,0],c[:,1],'g') - pylab.show() - raise SystemExit(0) if self._boundarypolyxy.intersects(poly): try: poly = self._boundarypolyxy.intersection(poly) @@ -858,7 +837,6 @@ polygon_types.append(type) return polygons, polygon_types - def _getmapboundary(self): """ define map boundary polygon (in lat/lon coordinates) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2007-11-04 06:09:24
|
Revision: 4102 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4102&view=rev Author: efiring Date: 2007-11-03 23:09:22 -0700 (Sat, 03 Nov 2007) Log Message: ----------- Basic numpification, reformatting, some refactoring Modified Paths: -------------- trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 01:02:08 UTC (rev 4101) +++ trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 06:09:22 UTC (rev 4102) @@ -10,94 +10,28 @@ from matplotlib.lines import Line2D import pyproj, sys, os, math, dbflib from proj import Proj -import matplotlib.numerix as NX -from matplotlib.numerix import ma +from matplotlib.numerix import npyma as ma import numpy as npy from numpy import linspace from matplotlib.numerix.mlab import squeeze -from matplotlib.cbook import popd, is_scalar +from matplotlib.cbook import is_scalar, dedent + from shapelib import ShapeFile +import time + + # basemap data files now installed in lib/matplotlib/toolkits/basemap/data basemap_datadir = os.sep.join([os.path.dirname(__file__), 'data']) __version__ = '0.9.7' -# test to see numerix set to use numpy (if not, raise an error) -if NX.which[0] != 'numpy': - raise ImportError("numerix must be set to numpy") -class Basemap(object): - """ - Set up a basemap with one of 19 supported map projections - (cylindrical equidistant, mercator, polyconic, oblique mercator, - transverse mercator, miller cylindrical, lambert conformal conic, - azimuthal equidistant, equidistant conic, lambert azimuthal equal area, - albers equal area conic, gnomonic, orthographic, sinusoidal, mollweide, - geostationary, robinson, cassini-soldner or stereographic). - Doesn't actually draw anything, but sets up the map projection class and - creates the coastline, lake river and political boundary data - structures in native map projection coordinates. - Uses a pyrex interface to C-code from proj.4 (http://proj.maptools.org). - - Useful instance variables: - - projection - map projection ('cyl','merc','mill','lcc','eqdc','aea', - 'laea', 'nplaea', 'splaea', 'tmerc', 'omerc', 'cass', 'gnom', 'poly', - 'sinu', 'moll', 'ortho', 'robin', 'aeqd', 'npaeqd', 'spaeqd', 'stere', - 'geos', 'npstere' or 'spstere') - (projections prefixed with 'np' or 'sp' are special case polar-centric - versions of the parent projection) - aspect - map aspect ratio (size of y dimension / size of x dimension). - llcrnrlon - longitude of lower left hand corner of the desired map domain. - llcrnrlon - latitude of lower left hand corner of the desired map domain. - urcrnrlon - longitude of upper right hand corner of the desired map domain. - urcrnrlon - latitude of upper right hand corner of the desired map domain. - llcrnrx,llcrnry,urcrnrx,urcrnry - corners of map domain in projection coordinates. - rmajor,rminor - equatorial and polar radii of ellipsoid used (in meters). - resolution - resolution of boundary dataset being used ('c' for crude, - 'l' for low, etc.). If None, no boundary dataset is associated with the - Basemap instance. - srs - a string representing the 'spatial reference system' for the map - projection as defined by PROJ.4. - - Example Usage: - ->>> from matplotlib.toolkits.basemap import Basemap ->>> from pylab import load, meshgrid, title, arange, show ->>> # read in topo data (on a regular lat/lon grid) ->>> etopo = load('etopo20data.gz') ->>> lons = load('etopo20lons.gz') ->>> lats = load('etopo20lats.gz') ->>> # create Basemap instance for Robinson projection. ->>> m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1])) ->>> # compute native map projection coordinates for lat/lon grid. ->>> x, y = m(*meshgrid(lons,lats)) ->>> # make filled contour plot. ->>> cs = m.contourf(x,y,etopo,30,cmap=cm.jet) ->>> m.drawcoastlines() # draw coastlines ->>> m.drawmapboundary() # draw a line around the map region ->>> m.drawparallels(arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels ->>> m.drawmeridians(arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians ->>> title('Robinson Projection') # add a title ->>> show() - - [this example (simpletest.py) plus many others can be found in the - examples directory of source distribution. The "OO" version of this - example (which does not use pylab) is called "simpletest_oo.py".] - - Contact: Jeff Whitaker <jef...@no...> - """ - - def __init__(self,llcrnrlon=None,llcrnrlat=None, - urcrnrlon=None,urcrnrlat=None,\ - width=None,height=None,\ - projection='cyl',resolution='c',area_thresh=None,rsphere=6370997.0,\ - lat_ts=None,lat_1=None,lat_2=None,lat_0=None,lon_0=None,\ - lon_1=None,lon_2=None,suppress_ticks=True,\ - satellite_height=None,boundinglat=None,anchor='C',ax=None): - """ +# The __init__ docstring is pulled out here because it is so long; +# Having it in the usual place makes it hard to get from the +# __init__ argument list to the code that uses the arguments. +_Basemap_init_doc = """ create a Basemap instance. arguments: @@ -133,12 +67,12 @@ lon_0 - center of desired map domain (in degrees). lat_0 - center of desired map domain (in degrees). - For 'sinu', 'moll', 'npstere', 'spstere', 'nplaea', 'splaea', 'nplaea', - 'splaea', 'npaeqd', 'spaeqd' or 'robin', the values of - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat,width and height are ignored (because - either they are computed internally, or entire globe is always plotted). For the - cylindrical projections ('cyl','merc' and 'mill'), the default is to use - llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=180 and urcrnrlat=90). For all other + For 'sinu', 'moll', 'npstere', 'spstere', 'nplaea', 'splaea', 'nplaea', + 'splaea', 'npaeqd', 'spaeqd' or 'robin', the values of + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat,width and height are ignored (because + either they are computed internally, or entire globe is always plotted). For the + cylindrical projections ('cyl','merc' and 'mill'), the default is to use + llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=180 and urcrnrlat=90). For all other projections except 'ortho' and 'geos', either the lat/lon values of the corners or width and height must be specified by the user. For 'ortho' and 'geos', the lat/lon values of the corners may be specified, @@ -191,7 +125,7 @@ The following parameters are map projection parameters which all default to None. Not all parameters are used by all projections, some are ignored. - lat_ts - latitude of natural origin (used for mercator, and + lat_ts - latitude of natural origin (used for mercator, and optionally for stereographic projection). lat_1 - first standard parallel for lambert conformal, albers equal area projection and equidistant conic projections. Latitude of one @@ -201,13 +135,13 @@ lat_2 - second standard parallel for lambert conformal, albers equal area projection and equidistant conic projections. Latitude of one of the two points on the projection centerline for oblique mercator. - If lat_2 is not given, it is set to lat_1 for + If lat_2 is not given, it is set to lat_1 for lambert conformal, albers equal area and equidistant conic. lon_1 - longitude of one of the two points on the projection centerline for oblique mercator. lon_2 - longitude of one of the two points on the projection centerline for oblique mercator. - lat_0 - central latitude (y-axis origin) - used by all projections, + lat_0 - central latitude (y-axis origin) - used by all projections, lon_0 - central meridian (x-axis origin) - used by all projections, boundinglat - bounding latitude for pole-centered projections (npstere,spstere, nplaea,splaea,npaeqd,spaeqd). These projections are square regions centered @@ -215,10 +149,147 @@ latitude circle boundinglat is tangent to the edge of the map at lon_0. satellite_height - height of satellite (in m) above equator - only relevant for geostationary projections ('geos'). - + """ +_unsupported_projection = """ + unsupported projection, use 'cyl' - cylindrical equidistant, 'merc' - + mercator, 'lcc' - lambert conformal conic, 'stere' - stereographic, + 'npstere' - stereographic, special case centered on north pole. + 'spstere' - stereographic, special case centered on south pole, + 'aea' - albers equal area conic, 'tmerc' - transverse mercator, + 'aeqd' - azimuthal equidistant, 'mill' - miller cylindrical, + 'npaeqd' - azimuthal equidistant, special case centered on north pole, + 'spaeqd' - azimuthal equidistant, special case centered on south pole, + 'eqdc' - equidistant conic, 'laea' - lambert azimuthal equal area, + 'nplaea' - lambert azimuthal, special case centered on north pole, + 'splaea' - lambert azimuthal, special case centered on south pole, + 'cass' - cassini-soldner (transverse cylindrical equidistant), + 'poly' - polyconic, 'omerc' - oblique mercator, 'ortho' - orthographic, + 'geos' - geostationary, 'sinu' - sinusoidal, 'moll' - mollweide, + 'robin' - robinson, or 'gnom' - gnomonic. You tried '%s' + """ + +# This allows substitution of longer names into error messages. +projnames = {'cyl' : 'Cylindrical Equidistant', + 'merc' : 'Mercator', + 'tmerc' : 'Transverse Mercator', + 'omerc' : 'Oblique Mercator', + 'mill' : 'Miller Cylindrical', + 'llc' : 'Lambert Conformal', + 'laea' : 'Lambert Azimuthal Equal Area', + 'nplaea' : 'North-Polar Lambert Azimuthal', + 'splaea' : 'South-Polar Lambert Azimuthal', + 'eqdc' : 'Equidistant Conic', + 'eaqd' : 'Azimuthal Equidistant', + 'npaeqd' : 'North-Polar Azimuthal Equidistant', + 'spaeqd' : 'South-Polar Azimuthal Equidistant', + 'aea' : 'Albers Equal Area', + 'stere' : 'Stereographic', + 'npstere' : 'Nouth-Polar Stereographic', + 'spstere' : 'South-Polar Stereographic', + 'cass' : 'Cassini-Soldner', + 'poly' : 'Polyconic', + 'ortho' : 'Orthographic', + 'geos' : 'Geostationary', + 'sinu' : 'Sinusoidal', + 'moll' : 'Mollweide', + 'robin' : 'Robinson', + 'gnom' : 'Gnomonic', + } + +def _validated_ll(param, name, minval, maxval): + param = float(param) + if param > maxval or param < minval: + raise ValueError('%s must be between %f and %f degrees' % + (name, minval, maxval)) + return param + +def _insert_validated(d, param, name, minval, maxval): + if param is not None: + d[name] = _validated_ll(param, name, minval, maxval) + + +class Basemap(object): + """ + Set up a basemap with one of 19 supported map projections + (cylindrical equidistant, mercator, polyconic, oblique mercator, + transverse mercator, miller cylindrical, lambert conformal conic, + azimuthal equidistant, equidistant conic, lambert azimuthal equal area, + albers equal area conic, gnomonic, orthographic, sinusoidal, mollweide, + geostationary, robinson, cassini-soldner or stereographic). + Doesn't actually draw anything, but sets up the map projection class and + creates the coastline, lake river and political boundary data + structures in native map projection coordinates. + Uses a pyrex interface to C-code from proj.4 (http://proj.maptools.org). + + Useful instance variables: + + projection - map projection ('cyl','merc','mill','lcc','eqdc','aea', + 'laea', 'nplaea', 'splaea', 'tmerc', 'omerc', 'cass', 'gnom', 'poly', + 'sinu', 'moll', 'ortho', 'robin', 'aeqd', 'npaeqd', 'spaeqd', 'stere', + 'geos', 'npstere' or 'spstere') + (projections prefixed with 'np' or 'sp' are special case polar-centric + versions of the parent projection) + aspect - map aspect ratio (size of y dimension / size of x dimension). + llcrnrlon - longitude of lower left hand corner of the desired map domain. + llcrnrlon - latitude of lower left hand corner of the desired map domain. + urcrnrlon - longitude of upper right hand corner of the desired map domain. + urcrnrlon - latitude of upper right hand corner of the desired map domain. + llcrnrx,llcrnry,urcrnrx,urcrnry - corners of map domain in projection coordinates. + rmajor,rminor - equatorial and polar radii of ellipsoid used (in meters). + resolution - resolution of boundary dataset being used ('c' for crude, + 'l' for low, etc.). If None, no boundary dataset is associated with the + Basemap instance. + srs - a string representing the 'spatial reference system' for the map + projection as defined by PROJ.4. + + Example Usage: + + >>> from matplotlib.toolkits.basemap import Basemap + >>> from pylab import load, meshgrid, title, arange, show + >>> # read in topo data (on a regular lat/lon grid) + >>> etopo = load('etopo20data.gz') + >>> lons = load('etopo20lons.gz') + >>> lats = load('etopo20lats.gz') + >>> # create Basemap instance for Robinson projection. + >>> m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1])) + >>> # compute native map projection coordinates for lat/lon grid. + >>> x, y = m(*meshgrid(lons,lats)) + >>> # make filled contour plot. + >>> cs = m.contourf(x,y,etopo,30,cmap=cm.jet) + >>> m.drawcoastlines() # draw coastlines + >>> m.drawmapboundary() # draw a line around the map region + >>> m.drawparallels(arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels + >>> m.drawmeridians(arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians + >>> title('Robinson Projection') # add a title + >>> show() + + [this example (simpletest.py) plus many others can be found in the + examples directory of source distribution. The "OO" version of this + example (which does not use pylab) is called "simpletest_oo.py".] + + Contact: Jeff Whitaker <jef...@no...> + """ + + + def __init__(self, llcrnrlon=None, llcrnrlat=None, + urcrnrlon=None, urcrnrlat=None, + width=None, height=None, + projection='cyl', resolution='c', + area_thresh=None, rsphere=6370997.0, + lat_ts=None, + lat_1=None, lat_2=None, + lat_0=None, lon_0=None, + lon_1=None, lon_2=None, + suppress_ticks=True, + satellite_height=None, + boundinglat=None, + anchor='C', + ax=None): + # docstring is added after definition + #print "starting: ", time.clock() # where to put plot in figure (default is 'C' or center) self.anchor = anchor # map projection. @@ -228,241 +299,103 @@ projparams = {} projparams['proj'] = projection try: - if rsphere[0] > rsphere[1]: - projparams['a'] = rsphere[0] - projparams['b'] = rsphere[1] - else: - projparams['a'] = rsphere[1] - projparams['b'] = rsphere[0] - except: + projparams['a'] = max(rsphere) + projparams['b'] = min(rsphere) + except TypeError: projparams['a'] = rsphere projparams['b'] = rsphere # set units to meters. projparams['units']='m' # check for sane values of lon_0, lat_0, lat_ts, lat_1, lat_2 - if lat_0 is not None: - if lat_0 > 90. or lat_0 < -90.: - raise ValueError, 'lat_0 must be between -90 and +90 degrees' - else: - projparams['lat_0'] = lat_0 - if lon_0 is not None: - if lon_0 < -720. or lon_0 > 720.: - raise ValueError, 'lon_0 must be between -720 and +720 degrees' - else: - projparams['lon_0'] = lon_0 - if lon_1 is not None: - if lon_1 < -720. or lon_1 > 720.: - raise ValueError, 'lon_1 must be between -720 and +720 degrees' - else: - projparams['lon_1'] = lon_1 - if lon_2 is not None: - if lon_2 < -720. or lon_2 > 720.: - raise ValueError, 'lon_2 must be between -720 and +720 degrees' - else: - projparams['lon_2'] = lon_2 - if lat_1 is not None: - if lat_1 > 90. or lat_1 < -90.: - raise ValueError, 'lat_1 must be between -90 and +90 degrees' - else: - projparams['lat_1'] = lat_1 - if lat_2 is not None: - if lat_2 > 90. or lat_2 < -90.: - raise ValueError, 'lat_2 must be between -90 and +90 degrees' - else: - projparams['lat_2'] = lat_2 - if lat_ts is not None: - if lat_ts > 90. or lat_ts < -90.: - raise ValueError, 'lat_ts must be between -90 and +90 degrees' - else: - projparams['lat_ts'] = lat_ts + _insert_validated(projparams, lat_0, 'lat_0', -90, 90) + _insert_validated(projparams, lat_1, 'lat_1', -90, 90) + _insert_validated(projparams, lat_2, 'lat_2', -90, 90) + _insert_validated(projparams, lat_ts, 'lat_ts', -90, 90) + _insert_validated(projparams, lon_0, 'lon_0', -360, 720) + _insert_validated(projparams, lon_1, 'lon_1', -360, 720) + _insert_validated(projparams, lon_2, 'lon_2', -360, 720) if satellite_height is not None: projparams['h'] = satellite_height - if None not in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: - # make sure lat/lon limits are converted to floats. - self.llcrnrlon = float(llcrnrlon) - self.llcrnrlat = float(llcrnrlat) - self.urcrnrlon = float(urcrnrlon) - self.urcrnrlat = float(urcrnrlat) - # check values of urcrnrlon,urcrnrlat and llcrnrlon,llcrnrlat - if self.urcrnrlat > 90.0 or self.llcrnrlat > 90.0: - raise ValueError, 'urcrnrlat and llcrnrlat must be less than 90' - if self.urcrnrlat < -90.0 or self.llcrnrlat < -90.0: - raise ValueError, 'urcrnrlat and llcrnrlat must be greater than -90' - if self.urcrnrlon > 720. or self.llcrnrlon > 720.: - raise ValueError, 'urcrnrlon and llcrnrlon must be less than 720' - if self.urcrnrlon < -360. or self.llcrnrlon < -360.: - raise ValueError, 'urcrnrlon and llcrnrlon must be greater than -360' - # for each of the supported projections, compute lat/lon of domain corners + using_corners = (None not in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]) + if using_corners: + self.llcrnrlon = _validated_ll(llcrnrlon, 'llcrnrlon', -360, 720) + self.urcrnrlon = _validated_ll(urcrnrlon, 'urcrnrlon', -360, 720) + self.llcrnrlat = _validated_ll(llcrnrlat, 'llcrnrlat', -90, 90) + self.urcrnrlat = _validated_ll(urcrnrlat, 'urcrnrlat', -90, 90) + # for each of the supported projections, compute lat/lon of domain corners # and set values in projparams dict as needed. - if projection == 'lcc': + if projection in ['lcc', 'eqdc', 'aea']: # if lat_0 is given, but not lat_1, # set lat_1=lat_0 if lat_1 is None and lat_0 is not None: lat_1 = lat_0 projparams['lat_1'] = lat_1 if lat_1 is None or lon_0 is None: - raise ValueError, 'must specify lat_1 or lat_0 and lon_0 for Lambert Conformal basemap (lat_2 is optional)' + raise ValueError('must specify lat_1 or lat_0 and lon_0 for %(projection)s basemap (lat_2 is optional)' % projnames) if lat_2 is None: projparams['lat_2'] = lat_1 - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: if width is None or height is None: raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat - - elif projection == 'eqdc': - # if lat_0 is given, but not lat_1, - # set lat_1=lat_0 - if lat_1 is None and lat_0 is not None: - lat_1 = lat_0 - projparams['lat_1'] = lat_1 - if lat_1 is None or lon_0 is None: - raise ValueError, 'must specify lat_1 or lat_0 and lon_0 for Equidistant Conic basemap (lat_2 is optional)' - if lat_2 is None: - projparams['lat_2'] = lat_1 - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: - if width is None or height is None: - raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat - elif projection == 'aea': - # if lat_0 is given, but not lat_1, - # set lat_1=lat_0 - if lat_1 is None and lat_0 is not None: - lat_1 = lat_0 - projparams['lat_1'] = lat_1 - if lat_1 is None or lon_0 is None: - raise ValueError, 'must specify lat_1 or lat_0 and lon_0 for Albers Equal Area basemap (lat_2 is optional)' - if lat_2 is None: - projparams['lat_2'] = lat_1 - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: - if width is None or height is None: - raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + if lon_0 is None or lat_0 is None: + raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) + self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat + self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + + # skipping over the following for now; it can be beautified and + # consolidated later elif projection == 'stere': if lat_0 is None or lon_0 is None: raise ValueError, 'must specify lat_0 and lon_0 for Stereographic basemap (lat_ts is optional)' - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: if width is None or height is None: raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat - elif projection == 'spstere': + if lon_0 is None or lat_0 is None: + raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) + self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat + self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + elif projection in ['spstere', 'npstere', + 'splaea', 'nplaea', + 'spaeqd', 'npaeqd']: if boundinglat is None or lon_0 is None: - raise ValueError, 'must specify boundinglat and lon_0 for South-Polar Stereographic basemap' - projparams['lat_ts'] = -90. - projparams['lat_0'] = -90. - projparams['proj'] = 'stere' - self.llcrnrlon = lon_0+45. - self.urcrnrlon = lon_0-135. + raise ValueError('must specify boundinglat and lon_0 for %(projection) basemap' % projnames) + if projection[0] == 's': + sgn = -1 + else: + sgn = 1 + rootproj = projection[2:] + projparams['proj'] = rootproj + if rootproj == 'stere': + projparams['lat_ts'] = sgn * 90. + projparams['lat_0'] = sgn * 90. + self.llcrnrlon = lon_0 - sgn*45. + self.urcrnrlon = lon_0 + sgn*135. proj = pyproj.Proj(projparams) x,y = proj(lon_0,boundinglat) lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True) self.urcrnrlat = self.llcrnrlat if width is not None or height is not None: print 'warning: width and height keywords ignored for %s projection' % self.projection - elif projection == 'npstere': - if boundinglat is None or lon_0 is None: - raise ValueError, 'must specify boundinglat and lon_0 for North-Polar Stereographic basemap' - projparams['lat_ts'] = 90. - projparams['lat_0'] = 90. - projparams['proj'] = 'stere' - self.llcrnrlon = lon_0-45. - self.urcrnrlon = lon_0+135. - proj = pyproj.Proj(projparams) - x,y = proj(lon_0,boundinglat) - lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True) - self.urcrnrlat = self.llcrnrlat - if width is not None or height is not None: - print 'warning: width and height keywords ignored for %s projection' % self.projection - elif projection == 'splaea': - if boundinglat is None or lon_0 is None: - raise ValueError, 'must specify boundinglat and lon_0 for South-Polar Lambert Azimuthal basemap' - projparams['lat_0'] = -90. - projparams['proj'] = 'laea' - self.llcrnrlon = lon_0+45. - self.urcrnrlon = lon_0-135. - proj = pyproj.Proj(projparams) - x,y = proj(lon_0,boundinglat) - lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True) - self.urcrnrlat = self.llcrnrlat - if width is not None or height is not None: - print 'warning: width and height keywords ignored for %s projection' % self.projection - elif projection == 'nplaea': - if boundinglat is None or lon_0 is None: - raise ValueError, 'must specify boundinglat and lon_0 for North-Polar Lambert Azimuthal basemap' - projparams['lat_0'] = 90. - projparams['proj'] = 'laea' - self.llcrnrlon = lon_0-45. - self.urcrnrlon = lon_0+135. - proj = pyproj.Proj(projparams) - x,y = proj(lon_0,boundinglat) - lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True) - self.urcrnrlat = self.llcrnrlat - if width is not None or height is not None: - print 'warning: width and height keywords ignored for %s projection' % self.projection - elif projection == 'spaeqd': - if boundinglat is None or lon_0 is None: - raise ValueError, 'must specify boundinglat and lon_0 for South-Polar Azimuthal Equidistant basemap' - projparams['lat_0'] = -90. - projparams['proj'] = 'aeqd' - self.llcrnrlon = lon_0+45. - self.urcrnrlon = lon_0-135. - proj = pyproj.Proj(projparams) - x,y = proj(lon_0,boundinglat) - lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True) - self.urcrnrlat = self.llcrnrlat - if width is not None or height is not None: - print 'warning: width and height keywords ignored for %s projection' % self.projection - elif projection == 'npaeqd': - if boundinglat is None or lon_0 is None: - raise ValueError, 'must specify boundinglat and lon_0 for North-Polar Azimuthal Equidistant basemap' - projparams['lat_0'] = 90. - projparams['proj'] = 'aeqd' - self.llcrnrlon = lon_0-45. - self.urcrnrlon = lon_0+135. - proj = pyproj.Proj(projparams) - x,y = proj(lon_0,boundinglat) - lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True) - self.urcrnrlat = self.llcrnrlat - if width is not None or height is not None: - print 'warning: width and height keywords ignored for %s projection' % self.projection elif projection == 'laea': if lat_0 is None or lon_0 is None: raise ValueError, 'must specify lat_0 and lon_0 for Lambert Azimuthal basemap' - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: if width is None or height is None: raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + if lon_0 is None or lat_0 is None: + raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) + self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat + self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat elif projection == 'merc': if lat_ts is None: raise ValueError, 'must specify lat_ts for Mercator basemap' # clip plot region to be within -89.99S to 89.99N # (mercator is singular at poles) - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: llcrnrlon = -180. llcrnrlat = -90. urcrnrlon = 180 @@ -478,16 +411,15 @@ elif projection in ['tmerc','gnom','cass','poly'] : if lat_0 is None or lon_0 is None: raise ValueError, 'must specify lat_0 and lon_0 for Transverse Mercator, Gnomonic, Cassini-Soldnerr Polyconic basemap' - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: if width is None or height is None: raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat - + if lon_0 is None or lat_0 is None: + raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) + self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat + self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + elif projection == 'ortho': if projparams['a'] != projparams['b']: raise ValueError, 'orthographic projection only works for perfect spheres - not ellipsoids' @@ -495,7 +427,7 @@ raise ValueError, 'must specify lat_0 and lon_0 for Orthographic basemap' if width is not None or height is not None: print 'warning: width and height keywords ignored for %s projection' % self.projection - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: llcrnrlon = -180. llcrnrlat = -90. urcrnrlon = 180 @@ -510,7 +442,7 @@ raise ValueError, 'must specify lon_0 and satellite_height for Geostationary basemap' if width is not None or height is not None: print 'warning: width and height keywords ignored for %s projection' % self.projection - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: llcrnrlon = -180. llcrnrlat = -90. urcrnrlon = 180 @@ -538,29 +470,27 @@ projparams['lon_1'] = lon_1 projparams['lat_2'] = lat_2 projparams['lon_2'] = lon_2 - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: if width is None or height is None: raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + if lon_0 is None or lat_0 is None: + raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) + self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat + self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat elif projection == 'aeqd': if lat_0 is None or lon_0 is None: raise ValueError, 'must specify lat_0 and lon_0 for Azimuthal Equidistant basemap' - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: if width is None or height is None: raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters' - else: - if lon_0 is None or lat_0 is None: - raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' - llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) - self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat - self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat + if lon_0 is None or lat_0 is None: + raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region' + llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams) + self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat + self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat elif projection == 'mill': - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: llcrnrlon = -180. llcrnrlat = -90. urcrnrlon = 180 @@ -570,7 +500,7 @@ if width is not None or height is not None: print 'warning: width and height keywords ignored for %s projection' % self.projection elif projection == 'cyl': - if None in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat]: + if not using_corners: llcrnrlon = -180. llcrnrlat = -90. urcrnrlon = 180 @@ -580,26 +510,12 @@ if width is not None or height is not None: print 'warning: width and height keywords ignored for %s projection' % self.projection else: - raise ValueError, """ - unsupported projection, use 'cyl' - cylindrical equidistant, 'merc' - - mercator, 'lcc' - lambert conformal conic, 'stere' - stereographic, - 'npstere' - stereographic, special case centered on north pole. - 'spstere' - stereographic, special case centered on south pole, - 'aea' - albers equal area conic, 'tmerc' - transverse mercator, - 'aeqd' - azimuthal equidistant, 'mill' - miller cylindrical, - 'npaeqd' - azimuthal equidistant, special case centered on north pole, - 'spaeqd' - azimuthal equidistant, special case centered on south pole, - 'eqdc' - equidistant conic, 'laea' - lambert azimuthal equal area, - 'nplaea' - lambert azimuthal, special case centered on north pole, - 'splaea' - lambert azimuthal, special case centered on south pole, - 'cass' - cassini-soldner (transverse cylindrical equidistant), - 'poly' - polyconic, 'omerc' - oblique mercator, 'ortho' - orthographic, - 'geos' - geostationary, 'sinu' - sinusoidal, 'moll' - mollweide, - 'robin' - robinson, or 'gnom' - gnomonic. You tried '%s'""" % projection + raise ValueError(_unsupported_projection % projection) + # initialize proj4 proj = Proj(projparams,self.llcrnrlon,self.llcrnrlat,self.urcrnrlon,self.urcrnrlat) - + # make sure axis ticks are suppressed. self.noticks = suppress_ticks @@ -665,6 +581,8 @@ # if no boundary data needed, we are done. if self.resolution is None: return + + ################## starting boundary processing ################### if area_thresh is None: if resolution == 'c': area_thresh = 10000. @@ -681,8 +599,10 @@ msg = """ Unable to open boundary dataset file. Only the 'crude', 'low' and 'intermediate' resolution datasets are installed by default. If you -are requesting a 'high' resolution dataset, you need to download +are requesting a 'high' resolution dataset, you need to download and install those files manually (see the basemap README for details).""" + + #print "reading data file:", time.clock() try: bdatfile = open(os.path.join(basemap_datadir,'gshhs_'+resolution+'.txt')) except: @@ -705,6 +625,7 @@ coastlats.append(lat) coastsegtype.append(typ) coastsegind.append(len(coastlons)) + #print "read coasts", time.clock() # read in country boundary data. cntrylons = []; cntrylats = []; cntrysegind = [] @@ -770,7 +691,7 @@ # so valid longitudes can range from -360 to 720. # This means a lot of redundant processing is done when # creating the class instance, but it a lot easier to figure - # out what to do when the projection domain straddles the + # out what to do when the projection domain straddles the # Greenwich meridian. coastlons2 = [lon+360. for lon in coastlons] cntrylons2 = [lon+360. for lon in cntrylons] @@ -780,35 +701,50 @@ cntrylons3 = [lon-360. for lon in cntrylons] statelons3 = [lon-360. for lon in statelons] riverlons3 = [lon-360. for lon in riverlons] - + #print "starting to make coast polygons", time.clock() # transform coastline polygons to native map coordinates. - xc,yc = proj(NX.array(coastlons),NX.array(coastlats)) + xc,yc = proj(npy.array(coastlons),npy.array(coastlats)) xc = xc.tolist(); yc = yc.tolist() - xc2,yc2 = proj(NX.array(coastlons2),NX.array(coastlats)) - xc3,yc3 = proj(NX.array(coastlons3),NX.array(coastlats)) + xc2,yc2 = proj(npy.array(coastlons2),npy.array(coastlats)) + xc3,yc3 = proj(npy.array(coastlons3),npy.array(coastlats)) xc2 = xc2.tolist(); yc2 = yc2.tolist() xc3 = xc3.tolist(); yc3 = yc3.tolist() # set up segments in form needed for LineCollection, # ignoring 'inf' values that are off the map. - segments = [zip(xc[i0:i1],yc[i0:i1]) for i0,i1 in zip(coastsegind[:-1],coastsegind[1:])] - segmentsll = [zip(coastlons[i0:i1],coastlats[i0:i1]) for i0,i1 in zip(coastsegind[:-1],coastsegind[1:])] + segments = [zip(xc[i0:i1],yc[i0:i1]) for i0,i1 in + zip(coastsegind[:-1],coastsegind[1:])] + segmentsll = [zip(coastlons[i0:i1],coastlats[i0:i1]) for i0,i1 in + zip(coastsegind[:-1],coastsegind[1:])] segtypes = [i for i in coastsegtype[:-1]] - segments2 = [zip(xc2[i0:i1],yc2[i0:i1]) for i0,i1 in zip(coastsegind[:-1],coastsegind[1:]) if max(xc2[i0:i1]) < 1.e20 and max(yc2[i0:i1]) < 1.e20] - segmentsll2 = [zip(coastlons2[i0:i1],coastlats[i0:i1]) for i0,i1 in zip(coastsegind[:-1],coastsegind[1:]) if max(xc2[i0:i1]) < 1.e20 and max(yc2[i0:i1]) < 1.e20] - segtypes2 = [i for i0,i1,i in zip(coastsegind[:-1],coastsegind[1:],coastsegtype[:-1]) if max(xc2[i0:i1]) < 1.e20 and max(yc2[i0:i1]) < 1.e20] + segments2 = [zip(xc2[i0:i1],yc2[i0:i1]) for i0,i1 in + zip(coastsegind[:-1],coastsegind[1:]) + if max(xc2[i0:i1]) < 1.e20 + and max(yc2[i0:i1]) < 1.e20] + segmentsll2 = [zip(coastlons2[i0:i1],coastlats[i0:i1]) for i0,i1 in + zip(coastsegind[:-1],coastsegind[1:]) + if max(xc2[i0:i1]) < 1.e20 + and max(yc2[i0:i1]) < 1.e20] + segtypes2 = [i for i0,i1,i in zip(coastsegind[:-1],coastsegind[1:],coastsegtype[:-1]) + if max(xc2[i0:i1]) < 1.e20 and max(yc2[i0:i1]) < 1.e20] + segments3 = [zip(xc3[i0:i1],yc3[i0:i1]) for i0,i1 in zip(coastsegind[:-1],coastsegind[1:]) if max(xc3[i0:i1]) < 1.e20 and max(yc3[i0:i1]) < 1.e20] segmentsll3 = [zip(coastlons3[i0:i1],coastlats[i0:i1]) for i0,i1 in zip(coastsegind[:-1],coastsegind[1:]) if max(xc3[i0:i1]) < 1.e20 and max(yc3[i0:i1]) < 1.e20] segtypes3 = [i for i0,i1,i in zip(coastsegind[:-1],coastsegind[1:],coastsegtype[:-1]) if max(xc3[i0:i1]) < 1.e20 and max(yc3[i0:i1]) < 1.e20] - self.coastsegs = segments+segments2+segments3 - self.coastsegsll = segmentsll+segmentsll2+segmentsll3 - self.coastsegtypes = segtypes+segtypes2+segtypes3 + self.coastsegs = segments +segments2+segments3 + self.coastsegsll = segmentsll +segmentsll2+segmentsll3 + self.coastsegtypes = segtypes +segtypes2+segtypes3 + #print len(coastsegind) + #print len(segments), len(segments2), len(segments3) + #print len(self.coastsegs), len(self.coastsegsll), len(self.coastsegtypes) + #print "made segments", time.clock() + # same as above for country segments. - xc,yc = proj(NX.array(cntrylons),NX.array(cntrylats)) + xc,yc = proj(npy.array(cntrylons),npy.array(cntrylats)) xc = xc.tolist(); yc = yc.tolist() - xc2,yc2 = proj(NX.array(cntrylons2),NX.array(cntrylats)) - xc3,yc3 = proj(NX.array(cntrylons3),NX.array(cntrylats)) + xc2,yc2 = proj(npy.array(cntrylons2),npy.array(cntrylats)) + xc3,yc3 = proj(npy.array(cntrylons3),npy.array(cntrylats)) xc2 = xc2.tolist(); yc2 = yc2.tolist() xc3 = xc3.tolist(); yc3 = yc3.tolist() segments = [zip(xc[i0:i1],yc[i0:i1]) for i0,i1 in zip(cntrysegind[:-1],cntrysegind[1:])] @@ -817,10 +753,10 @@ self.cntrysegs = segments+segments2+segments3 # same as above for state segments. - xc,yc = proj(NX.array(statelons),NX.array(statelats)) + xc,yc = proj(npy.array(statelons),npy.array(statelats)) xc = xc.tolist(); yc = yc.tolist() - xc2,yc2 = proj(NX.array(statelons2),NX.array(statelats)) - xc3,yc3 = proj(NX.array(statelons3),NX.array(statelats)) + xc2,yc2 = proj(npy.array(statelons2),npy.array(statelats)) + xc3,yc3 = proj(npy.array(statelons3),npy.array(statelats)) xc2 = xc2.tolist(); yc2 = yc2.tolist() xc3 = xc3.tolist(); yc3 = yc3.tolist() segments = [zip(xc[i0:i1],yc[i0:i1]) for i0,i1 in zip(statesegind[:-1],statesegind[1:])] @@ -829,10 +765,10 @@ self.statesegs = segments+segments2+segments3 # same as above for river segments. - xc,yc = proj(NX.array(riverlons),NX.array(riverlats)) + xc,yc = proj(npy.array(riverlons),npy.array(riverlats)) xc = xc.tolist(); yc = yc.tolist() - xc2,yc2 = proj(NX.array(riverlons2),NX.array(riverlats)) - xc3,yc3 = proj(NX.array(riverlons3),NX.array(riverlats)) + xc2,yc2 = proj(npy.array(riverlons2),npy.array(riverlats)) + xc3,yc3 = proj(npy.array(riverlons3),npy.array(riverlats)) xc2 = xc2.tolist(); yc2 = yc2.tolist() xc3 = xc3.tolist(); yc3 = yc3.tolist() segments = [zip(xc[i0:i1],yc[i0:i1]) for i0,i1 in zip(riversegind[:-1],riversegind[1:])] @@ -840,6 +776,7 @@ segments3 = [zip(xc3[i0:i1],yc3[i0:i1]) for i0,i1 in zip(riversegind[:-1],riversegind[1:]) if max(xc3[i0:i1]) < 1.e20 and max(yc3[i0:i1]) < 1.e20] self.riversegs = segments+segments2+segments3 + #print "Making final set of polygons", time.clock() # store coast polygons for filling. self.coastpolygons = [] coastpolygonsll = [] @@ -939,6 +876,7 @@ self.coastpolygons = polygons coastpolygonsll = polygonsll self.coastpolygontypes = polygontypes + #print "made coastpolygons", time.clock() states = []; rivers = []; countries = [] for seg in self.cntrysegs: if self._insidemap_seg(seg): @@ -953,12 +891,13 @@ self.riversegs = rivers self.cntryegs = countries + #print "starting projection limb checks", time.clock() # split up segments that go outside projection limb coastsegs = [] coastsegtypes = [] for seg,segtype in zip(self.coastsegs,self.coastsegtypes): - xx = NX.array([x for x,y in seg],NX.Float32) - yy = NX.array([y for x,y in seg],NX.Float32) + xx = npy.array([x for x,y in seg],npy.float32) + yy = npy.array([y for x,y in seg],npy.float32) i1,i2 = self._splitseg(xx,yy) if i1 and i2: for i,j in zip(i1,i2): @@ -970,10 +909,11 @@ coastsegs.append(segtype) self.coastsegs = coastsegs self.coastsegtypes = coastsegtypes + #print "finished p l checks", time.clock() states = [] for seg in self.statesegs: - xx = NX.array([x for x,y in seg],NX.Float32) - yy = NX.array([y for x,y in seg],NX.Float32) + xx = npy.array([x for x,y in seg],npy.float32) + yy = npy.array([y for x,y in seg],npy.float32) i1,i2 = self._splitseg(xx,yy) if i1 and i2: for i,j in zip(i1,i2): @@ -984,8 +924,8 @@ self.statesegs = states countries = [] for seg in self.cntrysegs: - xx = NX.array([x for x,y in seg],NX.Float32) - yy = NX.array([y for x,y in seg],NX.Float32) + xx = npy.array([x for x,y in seg],npy.float32) + yy = npy.array([y for x,y in seg],npy.float32) i1,i2 = self._splitseg(xx,yy) if i1 and i2: for i,j in zip(i1,i2): @@ -996,8 +936,8 @@ self.cntrysegs = countries rivers = [] for seg in self.riversegs: - xx = NX.array([x for x,y in seg],NX.Float32) - yy = NX.array([y for x,y in seg],NX.Float32) + xx = npy.array([x for x,y in seg],npy.float32) + yy = npy.array([y for x,y in seg],npy.float32) i1,i2 = self._splitseg(xx,yy) if i1 and i2: for i,j in zip(i1,i2): @@ -1007,18 +947,19 @@ rivers.append(seg) self.riversegs = rivers + "Starting remaining coast processing", time.clock() # split coastline segments that jump across entire plot. coastsegs = [] coastsegtypes = [] for seg,segtype in zip(self.coastsegs,self.coastsegtypes): - xx = NX.array([x for x,y in seg],NX.Float32) - yy = NX.array([y for x,y in seg],NX.Float32) + xx = npy.array([x for x,y in seg],npy.float32) + yy = npy.array([y for x,y in seg],npy.float32) xd = (xx[1:]-xx[0:-1])**2 yd = (yy[1:]-yy[0:-1])**2 - dist = NX.sqrt(xd+yd) + dist = npy.sqrt(xd+yd) split = dist > 5000000. - if NX.sum(split) and self.projection not in ['merc','cyl','mill']: - ind = (NX.compress(split,squeeze(split*NX.indices(xd.shape)))+1).tolist() + if npy.sum(split) and self.projection not in ['merc','cyl','mill']: + ind = (npy.compress(split,squeeze(split*npy.indices(xd.shape)))+1).tolist() iprev = 0 ind.append(len(xd)) for i in ind: @@ -1055,11 +996,11 @@ y = poly[1] lons = polyll[0] lats = polyll[1] - mask = NX.logical_or(NX.greater(x,1.e20),NX.greater(y,1.e20)) + mask = npy.logical_or(npy.greater(x,1.e20),npy.greater(y,1.e20)) # replace values in polygons that are over the horizon. xsave = False ysave = False - if NX.sum(mask): + if npy.sum(mask): i1,i2 = self._splitseg(x,y,mask=mask) # loop over segments of polygon that are outside projection limb. for i,j in zip(i1,i2): @@ -1147,12 +1088,12 @@ lons.reverse() lats.reverse() xx,yy = self(lons,lats) - xx = NX.array(xx); yy = NX.array(yy) - xdist = NX.fabs(xx[1:]-xx[0:-1]) + xx = npy.array(xx); yy = npy.array(yy) + xdist = npy.fabs(xx[1:]-xx[0:-1]) if max(xdist) > 1000000: - nmin = NX.argmax(xdist)+1 - xnew = NX.zeros(len(xx),NX.Float64) - ynew = NX.zeros(len(xx),NX.Float64) + nmin = npy.argmax(xdist)+1 + xnew = npy.zeros(len(xx),npy.float64) + ynew = npy.zeros(len(xx),npy.float64) lonsnew = len(xx)*[0] latsnew = len(xx)*[0] xnew[0:len(xx)-nmin] = xx[nmin:] @@ -1169,12 +1110,12 @@ x.reverse() y.reverse() # close polygon (add lines along left and right edges down to S pole) - for phi in NX.arange(-89.999,lats[0],0.1): + for phi in npy.arange(-89.999,lats[0],0.1): xx,yy = self(lon_0-179.99,phi) xn.append(xx); yn.append(yy) xn = xn+x yn = yn+y - for phi in NX.arange(lats[-1],-89.999,-0.1): + for phi in npy.arange(lats[-1],-89.999,-0.1): xx,yy = self(lon_0+179.99,phi) xn.append(xx); yn.append(yy) # move points outside map to edge of map @@ -1190,11 +1131,17 @@ xn.append(x); yn.append(y) coastpolygons.append((xn,yn)) self.coastpolygons = coastpolygons + #print "finished init", time.clock() + __init__.__doc__ = _Basemap_init_doc + #### End of the world's longest __init__ + + + def _splitseg(self,xx,yy,mask=None): """split segment up around missing values (outside projection limb)""" if mask is None: - mask = (NX.logical_or(NX.greater_equal(xx,1.e20),NX.greater_equal(yy,1.e20))).tolist() + mask = (npy.logical_or(npy.greater_equal(xx,1.e20),npy.greater_equal(yy,1.e20))).tolist() i1=[]; i2=[] mprev = 1 for i,m in enumerate(mask): @@ -1239,37 +1186,38 @@ def __call__(self,x,y,inverse=False): """ - Calling a Basemap class instance with the arguments lon, lat will - convert lon/lat (in degrees) to x/y native map projection - coordinates (in meters). If optional keyword 'inverse' is - True (default is False), the inverse transformation from x/y - to lon/lat is performed. + Calling a Basemap class instance with the arguments lon, lat will + convert lon/lat (in degrees) to x/y native map projection + coordinates (in meters). If optional keyword 'inverse' is + True (default is False), the inverse transformation from x/y + to lon/lat is performed. - For cylindrical equidistant projection ('cyl'), this - does nothing (i.e. x,y == lon,lat). + For cylindrical equidistant projection ('cyl'), this + does nothing (i.e. x,y == lon,lat). - For non-cylindrical projections, the inverse transformation - always returns longitudes between -180 and 180 degrees. For - cylindrical projections (self.projection == 'cyl','mill' or 'merc') - the inverse transformation will return longitudes between - self.llcrnrlon and self.llcrnrlat. + For non-cylindrical projections, the inverse transformation + always returns longitudes between -180 and 180 degrees. For + cylindrical projections (self.projection == 'cyl','mill' or 'merc') + the inverse transformation will return longitudes between + self.llcrnrlon and self.llcrnrlat. - input arguments lon, lat can be either scalar floats or N arrays. + input arguments lon, lat can be either scalar floats or N arrays. """ return self.projtran(x,y,inverse=inverse) def makegrid(self,nx,ny,returnxy=False): """ - return arrays of shape (ny,nx) containing lon,lat coordinates of - an equally spaced native projection grid. - if returnxy = True, the x,y values of the grid are returned also. + return arrays of shape (ny,nx) containing lon,lat coordinates of + an equally spaced native projection grid. + if returnxy = True, the x,y values of the grid are returned also. """ return self.projtran.makegrid(nx,ny,returnxy=returnxy) def drawmapboundary(self,color='k',linewidth=1.0,ax=None): """ - draw boundary around map projection region. If ax=None (default), - default axis instance is used, otherwise specified axis instance is used. + draw boundary around map projection region. If ax=None (default), + default axis instance is used, otherwise specified axis + instance is used. """ # get current axes instance (if none specified). if ax is None and self.ax is None: @@ -1301,21 +1249,21 @@ ellps.set_clip_on(False) elif self.projection in ['moll','robin','sinu']: # elliptical region. # left side - lats = NX.arange(-89.9,89.9+dtheta,dtheta).tolist() + lats = npy.arange(-89.9,89.9+dtheta,dtheta).tolist() lons = len(lats)*[self.projparams['lon_0']-179.9] x,y = self(lons,lats) # top. - lons = NX.arange(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179+dtheta,dtheta).tolist() + lons = npy.arange(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179+dtheta,dtheta).tolist() lats = len(lons)*[89.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy # right side - lats = NX.arange(89.9,-89.9-dtheta,-dtheta).tolist() + lats = npy.arange(89.9,-89.9-dtheta,-dtheta).tolist() lons = len(lats)*[self.projparams['lon_0']+179.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy # bottom. - lons = NX.arange(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180-dtheta,-dtheta).tolist() + lons = npy.arange(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180-dtheta,-dtheta).tolist() lats = len(lons)*[-89.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy @@ -1334,18 +1282,18 @@ def fillcontinents(self,color='0.8',ax=None,zorder=None): """ - Fill continents. + Fill continents. - color - color to fill continents (default gray). - ax - axes instance (overrides default axes instance). - zorder - sets the zorder for the continent polygons (if not specified, - uses default zorder for a Polygon patch). Set to zero if you want to paint - over the filled continents). + color - color to fill continents (default gray). + ax - axes instance (overrides default axes instance). + zorder - sets the zorder for the continent polygons (if not specified, + uses default zorder for a Polygon patch). Set to zero if you want to paint + over the filled continents). - After filling continents, lakes are re-filled with axis background color. + After filling continents, lakes are re-filled with axis background color. """ if self.resolution is None: - raise AttributeError, 'there are no boundary datasets associated with this Basemap instance' + raise AttributeError, 'there are no boundary datasets associated with this Basemap instance' # get current axes instance (if none specified). if ax is None and self.ax is None: try: @@ -1359,18 +1307,18 @@ axisbgc = ax.get_axis_bgcolor() np = 0 for x,y in self.coastpolygons: - xa = NX.array(x,NX.Flo... [truncated message content] |
From: <js...@us...> - 2007-11-04 01:02:10
|
Revision: 4101 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4101&view=rev Author: jswhit Date: 2007-11-03 18:02:08 -0700 (Sat, 03 Nov 2007) Log Message: ----------- remove use of ravel Modified Paths: -------------- trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-03 12:31:59 UTC (rev 4100) +++ trunk/toolkits/basemap/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-04 01:02:08 UTC (rev 4101) @@ -653,8 +653,8 @@ self.latmax = 90. else: lons, lats = self.makegrid(101,101) - self.latmin = min(NX.ravel(lats)) - self.latmax = max(NX.ravel(lats)) + self.latmin = lats.min() + self.latmax = lats.max() # if ax == None, pylab.gca may be used. self.ax = ax @@ -2844,10 +2844,10 @@ # check that xout,yout are # within region defined by xin,yin. if checkbounds: - if min(NX.ravel(xout)) < min(xin) or \ - max(NX.ravel(xout)) > max(xin) or \ - min(NX.ravel(yout)) < min(yin) or \ - max(NX.ravel(yout)) > max(yin): + if xout.min() < xin.min() or \ + xout.max() > xin.max() or \ + yout.min() < yin.min() or \ + yout.max() > yin.max(): raise ValueError, 'yout or xout outside range of yin or xin' # compute grid coordinates of output grid. delx = xin[1:]-xin[0:-1] @@ -2858,7 +2858,7 @@ ycoords = (len(yin)-1)*(yout-yin[0])/(yin[-1]-yin[0]) else: # irregular (but still rectilinear) input grid. - xoutflat = NX.ravel(xout); youtflat = NX.ravel(yout) + xoutflat = xout.flatten(); youtflat = yout.flatten() ix = (NX.searchsorted(xin,xoutflat)-1).tolist() iy = (NX.searchsorted(yin,youtflat)-1).tolist() xoutflat = xoutflat.tolist(); xin = xin.tolist() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-11-03 12:32:03
|
Revision: 4100 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4100&view=rev Author: jdh2358 Date: 2007-11-03 05:31:59 -0700 (Sat, 03 Nov 2007) Log Message: ----------- added readme and exercise template Added Paths: ----------- trunk/py4science/workbook/README trunk/py4science/workbook/template.tex Added: trunk/py4science/workbook/README =================================================================== --- trunk/py4science/workbook/README (rev 0) +++ trunk/py4science/workbook/README 2007-11-03 12:31:59 UTC (rev 4100) @@ -0,0 +1,22 @@ +This is the workbook for the py4science course. It is made up of a +bunch of different units, each of which lives in a separate *.tex +file. To make a new unit, copy template.tex to yourfile.tex and fill +it in. We use the latex listing package for including python source +code. + +For every unit, create an example in ../examples/your_example.py, a +skeleton in ../examples/your_example_skel.py, and a symlink from +../examples/your_example_skel.py -> examples_skel/your_example.py +(../examples is in the top level of the py4science repository). If +there are any figures, you should create a PNG and EPS version of each +and add them to the fig subdirectory of the workbook directory. You +will need to svn add your tex file, example, skeleton, skeleton +symlink, and figures. + +You can build the workbook in skeleton form with + + > make skeletons # create workbook_skeletons.pdf + +and in solved form with + + > make solved # creates workbook_solved.pdf Added: trunk/py4science/workbook/template.tex =================================================================== --- trunk/py4science/workbook/template.tex (rev 0) +++ trunk/py4science/workbook/template.tex 2007-11-03 12:31:59 UTC (rev 4100) @@ -0,0 +1,37 @@ +\section{Your Example} +\label{sec:your_example} + +This is your introduction. Refer to python packages like +\texttt{numpy} and \texttt{matplotlib}, as well as functions like +\texttt{n.arange}, with ``texttt''. + +Refer to figures like Figure~\ref{fig:your_figure}. Your example code +should be included like. + +\lstinputlisting[label=code:your_example,caption={IGNORED}]{examples/your_example.py} + +and your figures should be saved in the \textff{fig} subdirectory with +a PNG and EPS version. You should include it like + +\begin{figure} +\begin{centering}\includegraphics[width=4in]{fig/your_example}\par\end{centering} + +\caption{\label{fig:your_example}Your figure caption here} +\end{figure} + +If you want to include python code inline, including ipython sessions use the following environment. I sometimes decorate ipython sessions with comments. + +\begin{listing} +# use namespaces! +In [1]: import numpy as n + +In [2]: x = n.random.rand(10) + +In [3]: x**2 +Out[3]: +array([ 0.08694464, 0.99225328, 0.05017794, 0.44827437, 0.25938905, + 0.10617795, 0.27397649, 0.33391573, 0.27975237, 0.06808894]) + +In [4]: + +\end{listing} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-03 12:22:45
|
Revision: 4099 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4099&view=rev Author: jswhit Date: 2007-11-03 05:22:43 -0700 (Sat, 03 Nov 2007) Log Message: ----------- only read in state, country and river geometries when draw method invoked. Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-02 23:21:06 UTC (rev 4098) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-03 12:22:43 UTC (rev 4099) @@ -661,9 +661,6 @@ # set defaults for area_thresh. self.resolution = resolution - # if no boundary data needed, we are done. - if self.resolution is None: - return if area_thresh is None: if resolution == 'c': area_thresh = 10000. @@ -680,18 +677,14 @@ self._boundarypolyll, self._boundarypolyxy = self._getmapboundary() # read in coastline polygons, only keeping those that # intersect map boundary polygon. - self.coastsegs, self.coastpolygontypes = self._readboundarydata('gshhs') - # same for countries, states, rivers. - self.cntrysegs, types = self._readboundarydata('countries') - self.statesegs, types = self._readboundarydata('states') - self.riversegs, types = self._readboundarydata('rivers') - # for coastlines, reformat for use in - # matplotlib.patches.Polygon. - self.coastpolygons = [] - for xy in self.coastsegs: - x = [x1 for x1,x2 in xy] - y = [x2 for x1,x2 in xy] - self.coastpolygons.append((x,y)) + if self.resolution is not None: + self.coastsegs, self.coastpolygontypes = self._readboundarydata('gshhs') + # reformat for use in matplotlib.patches.Polygon. + self.coastpolygons = [] + for xy in self.coastsegs: + x = [x1 for x1,x2 in xy] + y = [x2 for x1,x2 in xy] + self.coastpolygons.append((x,y)) def __call__(self,x,y,inverse=False): """ @@ -791,22 +784,25 @@ else: continue if poly.intersects(self._boundarypolyll): - poly = poly.intersection(self._boundarypolyll) - if hasattr(poly,'geoms'): - geoms = poly.geoms - else: - geoms = [poly] - for psub in geoms: - if name == 'gshhs': - b = npy.asarray(psub.boundary) + try: + poly = poly.intersection(self._boundarypolyll) + if hasattr(poly,'geoms'): + geoms = poly.geoms else: - b = npy.asarray(psub.coords) - blons = b[:,0]; blats = b[:,1] - bx, by = self(blons, blats) - #if (bx > 1.20).any() or (by > 1.e20).any(): - # continue - polygons.append(zip(bx,by)) - polygon_types.append(type) + geoms = [poly] + for psub in geoms: + if name == 'gshhs': + b = npy.asarray(psub.boundary) + else: + b = npy.asarray(psub.coords) + blons = b[:,0]; blats = b[:,1] + bx, by = self(blons, blats) + #if (bx > 1.20).any() or (by > 1.e20).any(): + # continue + polygons.append(zip(bx,by)) + polygon_types.append(type) + except: + pass # if map boundary polygon is not valid in lat/lon # coordinates, compute intersection between map # projection region and boundary geometries in map @@ -860,7 +856,6 @@ b = npy.asarray(psub.coords) polygons.append(zip(b[:,0],b[:,1])) polygon_types.append(type) - print name,len(polygons) return polygons, polygon_types @@ -1119,6 +1114,10 @@ """ if self.resolution is None: raise AttributeError, 'there are no boundary datasets associated with this Basemap instance' + # read in country line segments, only keeping those that + # intersect map boundary polygon. + if not hasattr(self,'cntrysegs'): + self.cntrysegs, types = self._readboundarydata('countries') # get current axes instance (if none specified). if ax is None and self.ax is None: try: @@ -1150,6 +1149,10 @@ """ if self.resolution is None: raise AttributeError, 'there are no boundary datasets associated with this Basemap instance' + # read in state line segments, only keeping those that + # intersect map boundary polygon. + if not hasattr(self,'statesegs'): + self.statesegs, types = self._readboundarydata('states') # get current axes instance (if none specified). if ax is None and self.ax is None: try: @@ -1181,6 +1184,10 @@ """ if self.resolution is None: raise AttributeError, 'there are no boundary datasets associated with this Basemap instance' + # read in river line segments, only keeping those that + # intersect map boundary polygon. + if not hasattr(self,'riversegs'): + self.riversegs, types = self._readboundarydata('rivers') # get current axes instance (if none specified). if ax is None and self.ax is None: try: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-02 23:21:25
|
Revision: 4098 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4098&view=rev Author: jswhit Date: 2007-11-02 16:21:06 -0700 (Fri, 02 Nov 2007) Log Message: ----------- fixed for map projection regions that are not polygons in lat/lon coords Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-02 18:45:38 UTC (rev 4097) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-02 23:21:06 UTC (rev 4098) @@ -10,7 +10,6 @@ from matplotlib.lines import Line2D import pyproj, sys, os, math, dbflib from proj import Proj -import matplotlib.numerix as NX from matplotlib.numerix import ma import numpy as npy from numpy import linspace @@ -18,17 +17,15 @@ from matplotlib.cbook import popd, is_scalar from shapelib import ShapeFile from shapely.geometry import Polygon as PolygonShape -from shapely import wkb +from shapely.geometry import LineString as LineShape +from shapely.geometry import Point as PointShape +from shapely import wkb, wkt # basemap data files now installed in lib/matplotlib/toolkits/basemap/data basemap_datadir = os.sep.join([os.path.dirname(__file__), 'data']) __version__ = '0.9.7' -# test to see numerix set to use numpy (if not, raise an error) -if NX.which[0] != 'numpy': - raise ImportError("numerix must be set to numpy") - class Basemap(object): """ @@ -655,8 +652,8 @@ self.latmax = 90. else: lons, lats = self.makegrid(101,101) - self.latmin = min(NX.ravel(lats)) - self.latmax = max(NX.ravel(lats)) + self.latmin = lats.min() + self.latmax = lats.max() # if ax == None, pylab.gca may be used. self.ax = ax @@ -680,7 +677,7 @@ raise ValueError, "boundary resolution must be one of 'c','l','i' or 'h'" self.area_thresh = area_thresh # define map boundary polygon (in lat/lon coordinates) - self._boundarypoly = self._getmapboundary() + self._boundarypolyll, self._boundarypolyxy = self._getmapboundary() # read in coastline polygons, only keeping those that # intersect map boundary polygon. self.coastsegs, self.coastpolygontypes = self._readboundarydata('gshhs') @@ -738,6 +735,13 @@ raise IOError, msg polygons = [] polygon_types = [] + # see if map projection region polygon contains a pole. + NPole = PointShape(self(0.,90.)) + SPole = PointShape(self(0.,-90.)) + hasNP = self._boundarypolyxy.contains(NPole) + hasSP = self._boundarypolyxy.contains(SPole) + containsPole = hasNP or hasSP + # iterate over boundary geometries. for line in bdatmetafile: linesplit = line.split() area = float(linesplit[1]) @@ -746,57 +750,117 @@ north = float(linesplit[3]) if area < 0.: area = 1.e30 useit = self.latmax>=south and self.latmin<=north and area>self.area_thresh - # skip Antartica for now. - #if south < -68: useit = False if useit: offsetbytes = int(linesplit[4]) bytecount = int(linesplit[5]) bdatfile.seek(offsetbytes,0) polystring = bdatfile.read(bytecount) poly = wkb.loads(polystring) - # close Antartica for cylindrical projections. - if name == 'gshhs' and self.projection in ['cyl','merc','mill']: - b = npy.asarray(poly.boundary) - lons = b[:,0] - lats = b[:,1] - if south < -68: - if math.fabs(lons[0]+0.) < 1.e-5: - lons1 = lons[:-2][::-1] - lats1 = lats[:-2][::-1] - lons2 = lons1 + 360. - lons3 = lons2 + 360. - lons = lons1.tolist()+lons2.tolist()+lons3.tolist() - lats = lats1.tolist()+lats1.tolist()+lats1.tolist() - lonstart,latstart = lons[0], lats[0] - lonend,latend = lons[-1], lats[-1] - lons.insert(0,lonstart) - lats.insert(0,-90.) - lons.append(lonend) - lats.append(-90.) - poly = PolygonShape(zip(lons,lats)) - #b = npy.asarray(poly.boundary) - #import pylab - #pylab.fill(b[:,0],b[:,1],'b') - #pylab.show() + # if map boundary polygon is a valid one in lat/lon + # coordinates (i.e. it does not contain either pole), + # the intersections of the boundary geometries + # and the map projection region can be computed before + # transforming the boundary geometry to map projection + # coordinates (this saves time, especially for small map + # regions and high-resolution boundary geometries). + if not containsPole: + # close Antarctica for cylindrical projections. + if name == 'gshhs' and self.projection in ['cyl','merc','mill']: + b = npy.asarray(poly.boundary) + lons = b[:,0] + lats = b[:,1] + if south < -68: + if math.fabs(lons[0]+0.) < 1.e-5: + lons1 = lons[:-2][::-1] + lats1 = lats[:-2][::-1] + lons2 = lons1 + 360. + lons3 = lons2 + 360. + lons = lons1.tolist()+lons2.tolist()+lons3.tolist() + lats = lats1.tolist()+lats1.tolist()+lats1.tolist() + lonstart,latstart = lons[0], lats[0] + lonend,latend = lons[-1], lats[-1] + lons.insert(0,lonstart) + lats.insert(0,-90.) + lons.append(lonend) + lats.append(-90.) + poly = PolygonShape(zip(lons,lats)) + #b = npy.asarray(poly.boundary) + #import pylab + #pylab.fill(b[:,0],b[:,1],'b') + #pylab.show() + else: + continue + if poly.intersects(self._boundarypolyll): + poly = poly.intersection(self._boundarypolyll) + if hasattr(poly,'geoms'): + geoms = poly.geoms else: - continue - if poly.intersects(self._boundarypoly): - poly = poly.intersection(self._boundarypoly) - if hasattr(poly,'geoms'): - geoms = poly.geoms + geoms = [poly] + for psub in geoms: + if name == 'gshhs': + b = npy.asarray(psub.boundary) + else: + b = npy.asarray(psub.coords) + blons = b[:,0]; blats = b[:,1] + bx, by = self(blons, blats) + #if (bx > 1.20).any() or (by > 1.e20).any(): + # continue + polygons.append(zip(bx,by)) + polygon_types.append(type) + # if map boundary polygon is not valid in lat/lon + # coordinates, compute intersection between map + # projection region and boundary geometries in map + # projection coordinates. + else: + if name == 'gshhs': + b = npy.asarray(poly.boundary) else: - geoms = [poly] - for psub in geoms: - if name == 'gshhs': - b = npy.asarray(psub.boundary) + b = npy.asarray(poly.coords) + bx, by = self(b[:,0], b[:,1]) + mask = npy.logical_and(bx<1.e20,by<1.e20) + if sum(mask) <= 1: continue + if name == 'gshhs': + poly = PolygonShape(zip(bx,by)) + else: + # remove parts of geometry that are undefined + # in this map projection. + bx = npy.compress(mask, bx) + by = npy.compress(mask, by) + poly = LineShape(zip(bx,by)) + if 0: + import pylab + print poly + pp = self._boundarypolyxy.intersection(poly) + print name, pp + a = npy.asarray(self._boundarypolyxy.boundary) + pylab.plot(a[:,0],a[:,1],'b') + pylab.plot(bx,by,'r') + if hasattr(pp,'geoms'): + px = pp.geoms else: - b = npy.asarray(psub.coords) - blons = b[:,0]; blats = b[:,1] - bx, by = self(blons, blats) - #if (bx > 1.20).any() or (by > 1.e20).any(): - # continue - polygons.append(zip(bx,by)) - polygon_types.append(type) + px = [pp] + for p in px: + c = npy.asarray(p.boundary) + pylab.fill(c[:,0],c[:,1],'g') + pylab.show() + raise SystemExit(0) + if self._boundarypolyxy.intersects(poly): + try: + poly = self._boundarypolyxy.intersection(poly) + except: + continue + if hasattr(poly,'geoms'): + geoms = poly.geoms + else: + geoms = [poly] + for psub in geoms: + if name == 'gshhs': + b = npy.asarray(psub.boundary) + else: + b = npy.asarray(psub.coords) + polygons.append(zip(b[:,0],b[:,1])) + polygon_types.append(type) + print name,len(polygons) return polygons, polygon_types @@ -804,77 +868,89 @@ """ define map boundary polygon (in lat/lon coordinates) """ - dtheta = 0.1 - dx = (self.xmax-self.xmin)/100. - dy = (self.ymax-self.ymin)/100. + nx = 100 + ny = 100 if self.projection == 'ortho' and self._fulldisk: # circular region. - thetas = npy.arange(0.,2.*npy.pi,dtheta) + thetas = linspace(0.,2.*npy.pi,2*nx*ny)[:-1] radius = self.rmajor x = radius*npy.cos(thetas) + 0.5*self.xmax y = radius*npy.sin(thetas) + 0.5*self.ymax + boundaryxy = PolygonShape(zip(x,y)) elif self.projection == 'geos' and self._fulldisk: # elliptical region - thetas = npy.arange(0.,2.*npy.pi+0.5*dtheta,dtheta) + thetas = linspace(0.,2.*npy.pi,2*nx*ny)[:-1] rminor = self._height rmajor = self._width x = rmajor*npy.cos(thetas) + 0.5*self.xmax y = rminor*npy.sin(thetas) + 0.5*self.ymax + boundaryxy = PolygonShape(zip(x,y)) elif self.projection in ['moll','robin','sinu']: # quasi-elliptical region. x = []; y = [] # left side - lats = NX.arange(-89.9,89.9+dtheta,dtheta).tolist() + lats = linspace(-89.9,89.9,ny).tolist() lons = len(lats)*[self.projparams['lon_0']-179.9] x,y = self(lons,lats) # top. - lons = NX.arange(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179+dtheta,dtheta).tolist() + lons = linspace(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179,nx).tolist() lats = len(lons)*[89.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy # right side - lats = NX.arange(89.9,-89.9-dtheta,-dtheta).tolist() + lats = linspace(89.9,-89.9,ny).tolist() lons = len(lats)*[self.projparams['lon_0']+179.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy # bottom. - lons = NX.arange(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180-dtheta,-dtheta).tolist() + lons = linspace(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180).tolist() lats = len(lons)*[-89.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy x = npy.array(x,npy.float64) y = npy.array(y,npy.float64) + boundaryxy = PolygonShape(zip(x,y)) else: # all other projections are rectangular. # left side (x = xmin, ymin <= y <= ymax) - yy = npy.arange(self.ymin, self.ymax+0.5*dy, dy) + yy = linspace(self.ymin, self.ymax, ny)[:-1] x = len(yy)*[self.xmin]; y = yy.tolist() # top (y = ymax, xmin <= x <= xmax) - xx = npy.arange(self.xmin, self.xmax+0.5*dx, dx) + xx = npy.linspace(self.xmin, self.xmax, nx)[:-1] x = x + xx.tolist() y = y + len(xx)*[self.ymax] # right side (x = xmax, ymin <= y <= ymax) - yy = npy.arange(self.ymax, self.ymin-0.5*dy, -dy) + yy = linspace(self.ymax, self.ymin, ny)[:-1] x = x + len(yy)*[self.xmax]; y = y + yy.tolist() # bottom (y = ymin, xmin <= x <= xmax) - xx = npy.arange(self.xmax, self.xmin-0.5*dx, -dx) + xx = linspace(self.xmax, self.xmin, nx)[:-1] x = x + xx.tolist() y = y + len(xx)*[self.ymin] x = npy.array(x,npy.float64) y = npy.array(y,npy.float64) - lons, lats = self(x,y,inverse=True) - # fix lons so there are no jumps. - n = 1 - lonprev = lons[0] - for lon,lat in zip(lons[1:],lats[1:]): - if npy.abs(lon-lonprev) > 90.: - if lonprev < 0: - lon = lon - 360. - else: - lon = lon + 360 - lons[n] = lon - lonprev = lon - n = n + 1 - return PolygonShape(zip(lons,lats)) + boundaryxy = PolygonShape([(self.xmin,self.ymin),\ + (self.xmin,self.ymax),\ + (self.xmax,self.ymax),\ + (self.xmax,self.ymin)]) + if self.projection in ['mill','merc','cyl']: + lons = [self.llcrnrlon, self.llcrnrlon, self.urcrnrlon, self.urcrnrlon] + lats = [self.llcrnrlat, self.urcrnrlat, self.urcrnrlat, self.llcrnrlat] + else: + lons, lats = self(x,y,inverse=True) + # fix lons so there are no jumps. + n = 1 + lonprev = lons[0] + for lon,lat in zip(lons[1:],lats[1:]): + if npy.abs(lon-lonprev) > 90.: + if lonprev < 0: + lon = lon - 360. + else: + lon = lon + 360 + lons[n] = lon + lonprev = lon + n = n + 1 + boundaryll = PolygonShape(zip(lons,lats)) + #print 'map projection region',boundaryll.geom_type,boundaryll.is_valid + return PolygonShape(zip(lons,lats)), boundaryxy def drawmapboundary(self,color='k',linewidth=1.0,ax=None): @@ -912,21 +988,21 @@ ellps.set_clip_on(False) elif self.projection in ['moll','robin','sinu']: # elliptical region. # left side - lats = NX.arange(-89.9,89.9+dtheta,dtheta).tolist() + lats = npy.arange(-89.9,89.9+dtheta,dtheta).tolist() lons = len(lats)*[self.projparams['lon_0']-179.9] x,y = self(lons,lats) # top. - lons = NX.arange(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179+dtheta,dtheta).tolist() + lons = npy.arange(self.projparams['lon_0']-179.9,self.projparams['lon_0']+179+dtheta,dtheta).tolist() lats = len(lons)*[89.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy # right side - lats = NX.arange(89.9,-89.9-dtheta,-dtheta).tolist() + lats = npy.arange(89.9,-89.9-dtheta,-dtheta).tolist() lons = len(lats)*[self.projparams['lon_0']+179.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy # bottom. - lons = NX.arange(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180-dtheta,-dtheta).tolist() + lons = npy.arange(self.projparams['lon_0']+179.9,self.projparams['lon_0']-180-dtheta,-dtheta).tolist() lats = len(lons)*[-89.9] xx,yy = self(lons,lats) x = x+xx; y = y+yy @@ -970,18 +1046,18 @@ axisbgc = ax.get_axis_bgcolor() np = 0 for x,y in self.coastpolygons: - xa = NX.array(x,NX.Float32) - ya = NX.array(y,NX.Float32) + xa = npy.array(x,npy.float32) + ya = npy.array(y,npy.float32) # check to see if all four corners of domain in polygon (if so, # don't draw since it will just fill in the whole map). delx = 10; dely = 10 if self.projection in ['cyl']: delx = 0.1 dely = 0.1 - test1 = NX.fabs(xa-self.urcrnrx) < delx - test2 = NX.fabs(xa-self.llcrnrx) < delx - test3 = NX.fabs(ya-self.urcrnry) < dely - test4 = NX.fabs(ya-self.llcrnry) < dely + test1 = npy.fabs(xa-self.urcrnrx) < delx + test2 = npy.fabs(xa-self.llcrnrx) < delx + test3 = npy.fabs(ya-self.urcrnry) < dely + test4 = npy.fabs(ya-self.llcrnry) < dely hasp1 = sum(test1*test3) hasp2 = sum(test2*test3) hasp4 = sum(test2*test4) @@ -1277,9 +1353,9 @@ xoffset = (self.urcrnrx-self.llcrnrx)/100. if self.projection in ['merc','cyl','mill','moll','robin','sinu']: - lons = NX.arange(self.llcrnrlon,self.urcrnrlon+0.01,0.01) + lons = npy.arange(self.llcrnrlon,self.urcrnrlon+0.01,0.01) else: - lons = NX.arange(0,360.01,0.01) + lons = npy.arange(0,360.01,0.01) # make sure latmax degree parallel is drawn if projection not merc or cyl or miller try: circlesl = circles.tolist() @@ -1293,24 +1369,24 @@ xdelta = 0.01*(self.xmax-self.xmin) ydelta = 0.01*(self.ymax-self.ymin) for circ in circlesl: - lats = circ*NX.ones(len(lons),NX.Float32) + lats = circ*npy.ones(len(lons),npy.float32) x,y = self(lons,lats) # remove points outside domain. - testx = NX.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta) - x = NX.compress(testx, x) - y = NX.compress(testx, y) - testy = NX.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta) - x = NX.compress(testy, x) - y = NX.compress(testy, y) + testx = npy.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta) + x = npy.compress(testx, x) + y = npy.compress(testx, y) + testy = npy.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta) + x = npy.compress(testy, x) + y = npy.compress(testy, y) if len(x) > 1 and len(y) > 1: # split into separate line segments if necessary. # (not necessary for mercator or cylindrical or miller). xd = (x[1:]-x[0:-1])**2 yd = (y[1:]-y[0:-1])**2 - dist = NX.sqrt(xd+yd) + dist = npy.sqrt(xd+yd) split = dist > 500000. - if NX.sum(split) and self.projection not in ['merc','cyl','mill','moll','robin','sinu']: - ind = (NX.compress(split,squeeze(split*NX.indices(xd.shape)))+1).tolist() + if npy.sum(split) and self.projection not in ['merc','cyl','mill','moll','robin','sinu']: + ind = (npy.compress(split,squeeze(split*npy.indices(xd.shape)))+1).tolist() xl = [] yl = [] iprev = 0 @@ -1355,10 +1431,10 @@ if self.projection == 'moll' and yy[0] < 1.e-4: yy[0] = 1.e-4 if side == 'l': - lons,lats = self(self.llcrnrx*NX.ones(yy.shape,NX.Float32),yy,inverse=True) + lons,lats = self(self.llcrnrx*npy.ones(yy.shape,npy.float32),yy,inverse=True) lons = lons.tolist(); lats = lats.tolist() else: - lons,lats = self(self.urcrnrx*NX.ones(yy.shape,NX.Float32),yy,inverse=True) + lons,lats = self(self.urcrnrx*npy.ones(yy.shape,npy.float32),yy,inverse=True) lons = lons.tolist(); lats = lats.tolist() if max(lons) > 1.e20 or max(lats) > 1.e20: raise ValueError,'inverse transformation undefined - please adjust the map projection region' @@ -1368,10 +1444,10 @@ nmax = int((self.xmax-self.xmin)/dx+1) xx = linspace(self.llcrnrx,self.urcrnrx,nmax) if side == 'b': - lons,lats = self(xx,self.llcrnry*NX.ones(xx.shape,NX.Float32),inverse=True) + lons,lats = self(xx,self.llcrnry*npy.ones(xx.shape,npy.float32),inverse=True) lons = lons.tolist(); lats = lats.tolist() else: - lons,lats = self(xx,self.urcrnry*NX.ones(xx.shape,NX.Float32),inverse=True) + lons,lats = self(xx,self.urcrnry*npy.ones(xx.shape,npy.float32),inverse=True) lons = lons.tolist(); lats = lats.tolist() if max(lons) > 1.e20 or max(lats) > 1.e20: raise ValueError,'inverse transformation undefined - please adjust the map projection region' @@ -1394,7 +1470,7 @@ latlabstr = u'-%s\N{DEGREE SIGN}'%fmt else: latlabstr = u'%s\N{DEGREE SIGN}S'%fmt - latlab = latlabstr%NX.fabs(lat) + latlab = latlabstr%npy.fabs(lat) elif lat>0: if rcParams['text.usetex']: if labelstyle=='+/-': @@ -1493,30 +1569,30 @@ xoffset = (self.urcrnrx-self.llcrnrx)/100. if self.projection not in ['merc','cyl','mill','moll','robin','sinu']: - lats = NX.arange(-latmax,latmax+0.01,0.01) + lats = npy.arange(-latmax,latmax+0.01,0.01) else: - lats = NX.arange(-90,90.01,0.01) + lats = npy.arange(-90,90.01,0.01) xdelta = 0.01*(self.xmax-self.xmin) ydelta = 0.01*(self.ymax-self.ymin) for merid in meridians: - lons = merid*NX.ones(len(lats),NX.Float32) + lons = merid*npy.ones(len(lats),npy.float32) x,y = self(lons,lats) # remove points outside domain. - testx = NX.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta) - x = NX.compress(testx, x) - y = NX.compress(testx, y) - testy = NX.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta) - x = NX.compress(testy, x) - y = NX.compress(testy, y) + testx = npy.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta) + x = npy.compress(testx, x) + y = npy.compress(testx, y) + testy = npy.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta) + x = npy.compress(testy, x) + y = npy.compress(testy, y) if len(x) > 1 and len(y) > 1: # split into separate line segments if necessary. # (not necessary for mercator or cylindrical or miller). xd = (x[1:]-x[0:-1])**2 yd = (y[1:]-y[0:-1])**2 - dist = NX.sqrt(xd+yd) + dist = npy.sqrt(xd+yd) split = dist > 500000. - if NX.sum(split) and self.projection not in ['merc','cyl','mill','moll','robin','sinu']: - ind = (NX.compress(split,squeeze(split*NX.indices(xd.shape)))+1).tolist() + if npy.sum(split) and self.projection not in ['merc','cyl','mill','moll','robin','sinu']: + ind = (npy.compress(split,squeeze(split*npy.indices(xd.shape)))+1).tolist() xl = [] yl = [] iprev = 0 @@ -1564,10 +1640,10 @@ nmax = int((self.ymax-self.ymin)/dy+1) yy = linspace(self.llcrnry,self.urcrnry,nmax) if side == 'l': - lons,lats = self(self.llcrnrx*NX.ones(yy.shape,NX.Float32),yy,inverse=True) + lons,lats = self(self.llcrnrx*npy.ones(yy.shape,npy.float32),yy,inverse=True) lons = lons.tolist(); lats = lats.tolist() else: - lons,lats = self(self.urcrnrx*NX.ones(yy.shape,NX.Float32),yy,inverse=True) + lons,lats = self(self.urcrnrx*npy.ones(yy.shape,npy.float32),yy,inverse=True) lons = lons.tolist(); lats = lats.tolist() if max(lons) > 1.e20 or max(lats) > 1.e20: raise ValueError,'inverse transformation undefined - please adjust the map projection region' @@ -1577,10 +1653,10 @@ nmax = int((self.xmax-self.xmin)/dx+1) xx = linspace(self.llcrnrx,self.urcrnrx,nmax) if side == 'b': - lons,lats = self(xx,self.llcrnry*NX.ones(xx.shape,NX.Float32),inverse=True) + lons,lats = self(xx,self.llcrnry*npy.ones(xx.shape,npy.float32),inverse=True) lons = lons.tolist(); lats = lats.tolist() else: - lons,lats = self(xx,self.urcrnry*NX.ones(xx.shape,NX.Float32),inverse=True) + lons,lats = self(xx,self.urcrnry*npy.ones(xx.shape,npy.float32),inverse=True) lons = lons.tolist(); lats = lats.tolist() if max(lons) > 1.e20 or max(lats) > 1.e20: raise ValueError,'inverse transformation undefined - please adjust the map projection region' @@ -1605,7 +1681,7 @@ lonlabstr = u'-%s\N{DEGREE SIGN}'%fmt else: lonlabstr = u'%s\N{DEGREE SIGN}W'%fmt - lonlab = lonlabstr%NX.fabs(lon-360) + lonlab = lonlabstr%npy.fabs(lon-360) elif lon<180 and lon != 0: if rcParams['text.usetex']: if labelstyle=='+/-': @@ -1721,8 +1797,8 @@ raise ValueError, 'lons and lats must be increasing!' # check that lons in -180,180 for non-cylindrical projections. if self.projection not in ['cyl','merc','mill']: - lonsa = NX.array(lons) - count = NX.sum(lonsa < -180.00001) + NX.sum(lonsa > 180.00001) + lonsa = npy.array(lons) + count = npy.sum(lonsa < -180.00001) + npy.sum(lonsa > 180.00001) if count > 1: raise ValueError,'grid must be shifted so that lons are monotonically increasing and fit in range -180,+180 (see shiftgrid function)' # allow for wraparound point to be outside. @@ -1775,8 +1851,8 @@ raise ValueError, 'lons and lats must be increasing!' # check that lons in -180,180 for non-cylindrical projections. if self.projection not in ['cyl','merc','mill']: - lonsa = NX.array(lons) - count = NX.sum(lonsa < -180.00001) + NX.sum(lonsa > 180.00001) + lonsa = npy.array(lons) + count = npy.sum(lonsa < -180.00001) + npy.sum(lonsa > 180.00001) if count > 1: raise ValueError,'grid must be shifted so that lons are monotonically increasing and fit in range -180,+180 (see shiftgrid function)' # allow for wraparound point to be outside. @@ -2044,8 +2120,8 @@ ax = popd(kwargs,'ax') # make x,y masked arrays # (masked where data is outside of projection limb) - x = ma.masked_values(NX.where(x > 1.e20,1.e20,x), 1.e20) - y = ma.masked_values(NX.where(y > 1.e20,1.e20,y), 1.e20) + x = ma.masked_values(npy.where(x > 1.e20,1.e20,x), 1.e20) + y = ma.masked_values(npy.where(y > 1.e20,1.e20,y), 1.e20) # allow callers to override the hold state by passing hold=True|False b = ax.ishold() h = popd(kwargs, 'hold', None) @@ -2147,10 +2223,10 @@ function to adjust the data to be consistent with the map projection region (see examples/contour_demo.py).""" # mask for points outside projection limb. - xymask = NX.logical_or(NX.greater(x,1.e20),NX.greater(y,1.e20)) + xymask = npy.logical_or(npy.greater(x,1.e20),npy.greater(y,1.e20)) data = ma.asarray(data) # combine with data mask. - mask = NX.logical_or(ma.getmaskarray(data),xymask) + mask = npy.logical_or(ma.getmaskarray(data),xymask) data = ma.masked_array(data,mask=mask) # allow callers to override the hold state by passing hold=True|False b = ax.ishold() @@ -2215,10 +2291,10 @@ function to adjust the data to be consistent with the map projection region (see examples/contour_demo.py).""" # mask for points outside projection limb. - xymask = NX.logical_or(NX.greater(x,1.e20),NX.greater(y,1.e20)) + xymask = npy.logical_or(npy.greater(x,1.e20),npy.greater(y,1.e20)) data = ma.asarray(data) # combine with data mask. - mask = NX.logical_or(ma.getmaskarray(data),xymask) + mask = npy.logical_or(ma.getmaskarray(data),xymask) data = ma.masked_array(data,mask=mask) # allow callers to override the hold state by passing hold=True|False b = ax.ishold() @@ -2339,9 +2415,9 @@ lsmaskf = open(os.path.join(basemap_datadir,'5minmask.bin'),'rb') nlons = 4320; nlats = nlons/2 delta = 360./float(nlons) - lsmask_lons = NX.arange(-180+0.5*delta,180.,delta) - lsmask_lats = NX.arange(-90.+0.5*delta,90.,delta) - lsmask = NX.reshape(NX.fromstring(lsmaskf.read(),NX.UInt8),(nlats,nlons)) + lsmask_lons = npy.arange(-180+0.5*delta,180.,delta) + lsmask_lats = npy.arange(-90.+0.5*delta,90.,delta) + lsmask = npy.reshape(npy.fromstring(lsmaskf.read(),npy.uint8),(nlats,nlons)) lsmaskf.close() # instance variable lsmask is set on first invocation, # it contains the land-sea mask interpolated to the native @@ -2367,17 +2443,17 @@ self.lsmask = mask # optionally, set lakes to ocean color. if lakes: - mask = NX.where(self.lsmask==2,0,self.lsmask) + mask = npy.where(self.lsmask==2,0,self.lsmask) else: mask = self.lsmask ny, nx = mask.shape - rgba = NX.ones((ny,nx,4),NX.UInt8) - rgba_land = NX.array(rgba_land,NX.UInt8) - rgba_ocean = NX.array(rgba_ocean,NX.UInt8) + rgba = npy.ones((ny,nx,4),npy.uint8) + rgba_land = npy.array(rgba_land,npy.uint8) + rgba_ocean = npy.array(rgba_ocean,npy.uint8) for k in range(4): - rgba[:,:,k] = NX.where(mask,rgba_land[k],rgba_ocean[k]) + rgba[:,:,k] = npy.where(mask,rgba_land[k],rgba_ocean[k]) # make points outside projection limb transparent. - rgba[:,:,3] = NX.where(mask==255,0,rgba[:,:,3]) + rgba[:,:,3] = npy.where(mask==255,0,rgba[:,:,3]) # plot mask as rgba image. im = self.imshow(rgba,interpolation='nearest',ax=ax,**kwargs) @@ -2455,10 +2531,10 @@ # check that xout,yout are # within region defined by xin,yin. if checkbounds: - if min(NX.ravel(xout)) < min(xin) or \ - max(NX.ravel(xout)) > max(xin) or \ - min(NX.ravel(yout)) < min(yin) or \ - max(NX.ravel(yout)) > max(yin): + if xout.min() < xin.min() or \ + xout.max() > xin.max() or \ + yout.min() < yin.min() or \ + yout.max() > yin.max(): raise ValueError, 'yout or xout outside range of yin or xin' # compute grid coordinates of output grid. delx = xin[1:]-xin[0:-1] @@ -2469,9 +2545,9 @@ ycoords = (len(yin)-1)*(yout-yin[0])/(yin[-1]-yin[0]) else: # irregular (but still rectilinear) input grid. - xoutflat = NX.ravel(xout); youtflat = NX.ravel(yout) - ix = (NX.searchsorted(xin,xoutflat)-1).tolist() - iy = (NX.searchsorted(yin,youtflat)-1).tolist() + xoutflat = xout.flatten(); youtflat = yout.flatten() + ix = (npy.searchsorted(xin,xoutflat)-1).tolist() + iy = (npy.searchsorted(yin,youtflat)-1).tolist() xoutflat = xoutflat.tolist(); xin = xin.tolist() youtflat = youtflat.tolist(); yin = yin.tolist() xcoords = []; ycoords = [] @@ -2489,33 +2565,33 @@ ycoords.append(len(yin)) # outside range on upper end else: ycoords.append(float(j)+(youtflat[m]-yin[j])/(yin[j+1]-yin[j])) - xcoords = NX.reshape(xcoords,xout.shape) - ycoords = NX.reshape(ycoords,yout.shape) + xcoords = npy.reshape(xcoords,xout.shape) + ycoords = npy.reshape(ycoords,yout.shape) # data outside range xin,yin will be clipped to # values on boundary. if masked: - xmask = NX.logical_or(NX.less(xcoords,0),NX.greater(xcoords,len(xin)-1)) - ymask = NX.logical_or(NX.less(ycoords,0),NX.greater(ycoords,len(yin)-1)) - xymask = NX.logical_or(xmask,ymask) - xcoords = NX.clip(xcoords,0,len(xin)-1) - ycoords = NX.clip(ycoords,0,len(yin)-1) + xmask = npy.logical_or(npy.less(xcoords,0),npy.greater(xcoords,len(xin)-1)) + ymask = npy.logical_or(npy.less(ycoords,0),npy.greater(ycoords,len(yin)-1)) + xymask = npy.logical_or(xmask,ymask) + xcoords = npy.clip(xcoords,0,len(xin)-1) + ycoords = npy.clip(ycoords,0,len(yin)-1) # interpolate to output grid using bilinear interpolation. if order == 1: - xi = xcoords.astype(NX.Int32) - yi = ycoords.astype(NX.Int32) + xi = xcoords.astype(npy.int32) + yi = ycoords.astype(npy.int32) xip1 = xi+1 yip1 = yi+1 - xip1 = NX.clip(xip1,0,len(xin)-1) - yip1 = NX.clip(yip1,0,len(yin)-1) - delx = xcoords-xi.astype(NX.Float32) - dely = ycoords-yi.astype(NX.Float32) + xip1 = npy.clip(xip1,0,len(xin)-1) + yip1 = npy.clip(yip1,0,len(yin)-1) + delx = xcoords-xi.astype(npy.float32) + dely = ycoords-yi.astype(npy.float32) dataout = (1.-delx)*(1.-dely)*datain[yi,xi] + \ delx*dely*datain[yip1,xip1] + \ (1.-delx)*dely*datain[yip1,xi] + \ delx*(1.-dely)*datain[yi,xip1] elif order == 0: - xcoordsi = NX.around(xcoords).astype(NX.Int32) - ycoordsi = NX.around(ycoords).astype(NX.Int32) + xcoordsi = npy.around(xcoords).astype(npy.int32) + ycoordsi = npy.around(ycoords).astype(npy.int32) dataout = datain[ycoordsi,xcoordsi] else: raise ValueError,'order keyword must be 0 or 1' @@ -2524,7 +2600,7 @@ newmask = ma.mask_or(ma.getmask(dataout), xymask) dataout = ma.masked_array(dataout,mask=newmask) elif masked and is_scalar(masked): - dataout = NX.where(xymask,masked,dataout) + dataout = npy.where(xymask,masked,dataout) return dataout def shiftgrid(lon0,datain,lonsin,start=True): @@ -2542,13 +2618,13 @@ returns dataout,lonsout (data and longitudes on shifted grid). """ - if NX.fabs(lonsin[-1]-lonsin[0]-360.) > 1.e-4: + if npy.fabs(lonsin[-1]-lonsin[0]-360.) > 1.e-4: raise ValueError, 'cyclic point not included' if lon0 < lonsin[0] or lon0 > lonsin[-1]: raise ValueError, 'lon0 outside of range of lonsin' - i0 = NX.argmin(NX.fabs(lonsin-lon0)) - dataout = NX.zeros(datain.shape,datain.dtype) - lonsout = NX.zeros(lonsin.shape,lonsin.dtype) + i0 = npy.argmin(npy.fabs(lonsin-lon0)) + dataout = npy.zeros(datain.shape,datain.dtype) + lonsout = npy.zeros(lonsin.shape,lonsin.dtype) if start: lonsout[0:len(lonsin)-i0] = lonsin[i0:] else: @@ -2572,13 +2648,13 @@ if hasattr(arrin,'mask'): arrout = ma.zeros((nlats,nlons+1),arrin.dtype) else: - arrout = NX.zeros((nlats,nlons+1),arrin.dtype) + arrout = npy.zeros((nlats,nlons+1),arrin.dtype) arrout[:,0:nlons] = arrin[:,:] arrout[:,nlons] = arrin[:,0] if hasattr(lonsin,'mask'): lonsout = ma.zeros(nlons+1,lonsin.dtype) else: - lonsout = NX.zeros(nlons+1,lonsin.dtype) + lonsout = npy.zeros(nlons+1,lonsin.dtype) lonsout[0:nlons] = lonsin[:] lonsout[nlons] = lonsin[-1] + lonsin[1]-lonsin[0] return arrout,lonsout This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-11-02 18:45:40
|
Revision: 4097 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4097&view=rev Author: jdh2358 Date: 2007-11-02 11:45:38 -0700 (Fri, 02 Nov 2007) Log Message: ----------- fix unit changes for errorbar_limits code Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/cbook.py Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2007-11-02 16:37:37 UTC (rev 4096) +++ trunk/matplotlib/lib/matplotlib/axes.py 2007-11-02 18:45:38 UTC (rev 4097) @@ -3505,7 +3505,7 @@ texts = [] slices = [] autotexts = [] - for frac, label, expl in zip(x,labels, explode): + for frac, label, expl in cbook.safezip(x,labels, explode): x, y = center theta2 = theta1 + frac thetam = 2*math.pi*0.5*(theta1+theta2) @@ -3645,11 +3645,11 @@ if xerr is not None: if not iterable(xerr): - xerr = [xerr] + xerr = [xerr]*len(x) if yerr is not None: if not iterable(yerr): - yerr = [yerr] + yerr = [yerr]*len(y) l0 = None @@ -3679,6 +3679,18 @@ if not iterable(xuplims): xuplims = npy.array([xuplims]*len(x), bool) else: xuplims = npy.asarray(xuplims, bool) + def xywhere(xs, ys, mask): + """ + return xs[mask], ys[mask] where mask is True but xs and + ys are not arrays + """ + assert len(xs)==len(ys) + assert len(xs)==len(mask) + xs = [thisx for thisx, b in zip(xs, mask) if b] + ys = [thisy for thisy, b in zip(ys, mask) if b] + return xs, ys + + if capsize > 0: plot_kw = { 'ms':2*capsize, @@ -3691,53 +3703,66 @@ if xerr is not None: if iterable(xerr) and len(xerr)==2: # using list comps rather than arrays to preserve units - left = [thisx-thiserr for (thisx, thiserr) in zip(x,xerr[0])] - right = [thisx+thiserr for (thisx, thiserr) in zip(x,xerr[1])] + left = [thisx-thiserr for (thisx, thiserr) in cbook.safezip(x,xerr[0])] + right = [thisx+thiserr for (thisx, thiserr) in cbook.safezip(x,xerr[1])] else: # using list comps rather than arrays to preserve units - left = [thisx-thiserr for (thisx, thiserr) in zip(x,xerr)] - right = [thisx+thiserr for (thisx, thiserr) in zip(x,xerr)] + left = [thisx-thiserr for (thisx, thiserr) in cbook.safezip(x,xerr)] + right = [thisx+thiserr for (thisx, thiserr) in cbook.safezip(x,xerr)] barcols.append( self.hlines(y, left, right, **lines_kw ) ) if capsize > 0: if xlolims.any(): - caplines.extend( self.plot(left[xlolims], y[xlolims], ls='None', marker=mlines.CARETLEFT, **plot_kw) ) + # can't use numpy logical indexing since left and + # y are lists + leftlo, ylo = xywhere(left, y, xlolims) + + caplines.extend( self.plot(leftlo, ylo, ls='None', marker=mlines.CARETLEFT, **plot_kw) ) xlolims = ~xlolims - caplines.extend( self.plot(left[xlolims], y[xlolims], 'k|', **plot_kw) ) + leftlo, ylo = xywhere(left, y, xlolims) + caplines.extend( self.plot(leftlo, ylo, 'k|', **plot_kw) ) else: caplines.extend( self.plot(left, y, 'k|', **plot_kw) ) if xuplims.any(): - caplines.extend( self.plot(right[xuplims], y[xuplims], ls='None', marker=mlines.CARETRIGHT, **plot_kw) ) + + rightup, yup = xywhere(right, y, xuplims) + caplines.extend( self.plot(rightup, yup, ls='None', marker=mlines.CARETRIGHT, **plot_kw) ) xuplims = ~xuplims - caplines.extend( self.plot(right[xuplims], y[xuplims], 'k|', **plot_kw) ) + rightup, yup = xywhere(right, y, xuplims) + caplines.extend( self.plot(rightup, yup, 'k|', **plot_kw) ) else: caplines.extend( self.plot(right, y, 'k|', **plot_kw) ) if yerr is not None: if iterable(yerr) and len(yerr)==2: # using list comps rather than arrays to preserve units - lower = [thisy-thiserr for (thisy, thiserr) in zip(y,yerr[0])] - upper = [thisy+thiserr for (thisy, thiserr) in zip(y,yerr[1])] + lower = [thisy-thiserr for (thisy, thiserr) in cbook.safezip(y,yerr[0])] + upper = [thisy+thiserr for (thisy, thiserr) in cbook.safezip(y,yerr[1])] else: # using list comps rather than arrays to preserve units - lower = [thisy-thiserr for (thisy, thiserr) in zip(y,yerr)] - upper = [thisy+thiserr for (thisy, thiserr) in zip(y,yerr)] + lower = [thisy-thiserr for (thisy, thiserr) in cbook.safezip(y,yerr)] + upper = [thisy+thiserr for (thisy, thiserr) in cbook.safezip(y,yerr)] barcols.append( self.vlines(x, lower, upper, **lines_kw) ) if capsize > 0: if lolims.any(): - caplines.extend( self.plot(x[lolims], lower[lolims], ls='None', marker=mlines.CARETDOWN, **plot_kw) ) + xlo, lowerlo = xywhere(x, lower, lolims) + caplines.extend( self.plot(xlo, lowerlo, ls='None', marker=mlines.CARETDOWN, **plot_kw) ) lolims = ~lolims - caplines.extend( self.plot(x[lolims], lower[lolims], 'k_', **plot_kw) ) + xlo, lowerlo = xywhere(x, lower, lolims) + caplines.extend( self.plot(xlo, lowerlo, 'k_', **plot_kw) ) else: caplines.extend( self.plot(x, lower, 'k_', **plot_kw) ) if uplims.any(): - caplines.extend( self.plot(x[uplims], upper[uplims], ls='None', marker=mlines.CARETUP, **plot_kw) ) + xup, upperup = xywhere(x, upper, uplims) + + caplines.extend( self.plot(xup, upperup, ls='None', marker=mlines.CARETUP, **plot_kw) ) uplims = ~uplims - caplines.extend( self.plot(x[uplims], upper[uplims], 'k_', **plot_kw) ) + xup, upperup = xywhere(x, upper, uplims) + caplines.extend( self.plot(xup, upperup, 'k_', **plot_kw) ) else: caplines.extend( self.plot(x, upper, 'k_', **plot_kw) ) Modified: trunk/matplotlib/lib/matplotlib/cbook.py =================================================================== --- trunk/matplotlib/lib/matplotlib/cbook.py 2007-11-02 16:37:37 UTC (rev 4096) +++ trunk/matplotlib/lib/matplotlib/cbook.py 2007-11-02 18:45:38 UTC (rev 4097) @@ -844,6 +844,15 @@ return mem + +def safezip(x, y): + 'make sure x and y are equal len before zipping' + Nx = len(x) + Ny = len(y) + if Nx!=Ny: + raise RuntimeError('x and y must be equal length; found len(x)=%d and len(y)=%d'% + (Nx, Ny)) + return zip(x, y) class MemoryMonitor: def __init__(self, nmax=20000): self._nmax = nmax This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2007-11-02 16:37:38
|
Revision: 4096 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4096&view=rev Author: dsdale Date: 2007-11-02 09:37:37 -0700 (Fri, 02 Nov 2007) Log Message: ----------- commit patch 1599876, fixes to qt4agg backend and qt4 blitting demo. Thanks to Phil Thompson. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/animation_blit_qt4.py trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2007-11-02 13:13:40 UTC (rev 4095) +++ trunk/matplotlib/CHANGELOG 2007-11-02 16:37:37 UTC (rev 4096) @@ -1,3 +1,6 @@ +2007-11-02 Commited Phil Thompson's patch 1599876, fixes to Qt4Agg + backend and qt4 blitting demo - DSD + 2007-10-31 Made log color scale easier to use with contourf; automatic level generation now works. - EF Modified: trunk/matplotlib/examples/animation_blit_qt4.py =================================================================== --- trunk/matplotlib/examples/animation_blit_qt4.py 2007-11-02 13:13:40 UTC (rev 4095) +++ trunk/matplotlib/examples/animation_blit_qt4.py 2007-11-02 16:37:37 UTC (rev 4096) @@ -15,10 +15,14 @@ class BlitQT(QtCore.QObject): def __init__(self): - QtCore.QObject.__init__(self, None) - self.ax = p.subplot(111) self.canvas = self.ax.figure.canvas + + # By making this a child of the canvas we make sure that it is + # destroyed first and avoids a possible exception when the user clicks + # on the window's close box. + QtCore.QObject.__init__(self, self.canvas) + self.cnt = 0 # create the initial line @@ -26,9 +30,14 @@ self.line, = p.plot(self.x, npy.sin(self.x), animated=True, lw=2) self.background = None + self.old_size = 0, 0 def timerEvent(self, evt): - if self.background is None: + # See if the size has changed since last time round. + current_size = self.ax.bbox.width(), self.ax.bbox.height() + + if self.old_size != current_size: + self.old_size = current_size self.background = self.canvas.copy_from_bbox(self.ax.bbox) # restore the clean slate background Modified: trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py 2007-11-02 13:13:40 UTC (rev 4095) +++ trunk/matplotlib/lib/matplotlib/backends/backend_qt4agg.py 2007-11-02 16:37:37 UTC (rev 4096) @@ -6,8 +6,6 @@ import os, sys import matplotlib -from matplotlib import verbose -from matplotlib.cbook import enumerate from matplotlib.figure import Figure from backend_agg import FigureCanvasAgg @@ -61,7 +59,7 @@ self.drawRect = False self.rect = [] self.replot = True - self.pixmap = QtGui.QPixmap() + self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) def resizeEvent( self, e ): FigureCanvasQT.resizeEvent( self, e ) @@ -86,26 +84,25 @@ # only replot data when needed if type(self.replot) is bool: # might be a bbox for blitting - if ( self.replot ): - #stringBuffer = str( self.buffer_rgba(0,0) ) - FigureCanvasAgg.draw( self ) + if self.replot: + FigureCanvasAgg.draw(self) - # matplotlib is in rgba byte order. - # qImage wants to put the bytes into argb format and - # is in a 4 byte unsigned int. little endian system is LSB first - # and expects the bytes in reverse order (bgra). - if ( QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian ): - stringBuffer = self.renderer._renderer.tostring_bgra() - else: - stringBuffer = self.renderer._renderer.tostring_argb() - qImage = QtGui.QImage( stringBuffer, self.renderer.width, - self.renderer.height, - QtGui.QImage.Format_ARGB32) - self.pixmap = self.pixmap.fromImage( qImage ) - p.drawPixmap( QtCore.QPoint( 0, 0 ), self.pixmap ) + # matplotlib is in rgba byte order. QImage wants to put the bytes + # into argb format and is in a 4 byte unsigned int. Little endian + # system is LSB first and expects the bytes in reverse order + # (bgra). + if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian: + stringBuffer = self.renderer._renderer.tostring_bgra() + else: + stringBuffer = self.renderer._renderer.tostring_argb() + qImage = QtGui.QImage(stringBuffer, self.renderer.width, + self.renderer.height, + QtGui.QImage.Format_ARGB32) + p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage)) + # draw the zoom rectangle to the QPainter - if ( self.drawRect ): + if self.drawRect: p.setPen( QtGui.QPen( QtCore.Qt.black, 1, QtCore.Qt.DotLine ) ) p.drawRect( self.rect[0], self.rect[1], self.rect[2], self.rect[3] ) @@ -117,8 +114,8 @@ reg = self.copy_from_bbox(bbox) stringBuffer = reg.to_string() qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32) - self.pixmap = self.pixmap.fromImage( qImage ) - p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), self.pixmap) + pixmap = QtGui.QPixmap.fromImage(qImage) + p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap) p.end() self.replot = False This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2007-11-02 13:13:42
|
Revision: 4095 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4095&view=rev Author: jdh2358 Date: 2007-11-02 06:13:40 -0700 (Fri, 02 Nov 2007) Log Message: ----------- added Manuel's contour linestyle patch Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/contour.py trunk/matplotlib/lib/matplotlib/mlab.py Modified: trunk/matplotlib/lib/matplotlib/contour.py =================================================================== --- trunk/matplotlib/lib/matplotlib/contour.py 2007-11-02 12:55:51 UTC (rev 4094) +++ trunk/matplotlib/lib/matplotlib/contour.py 2007-11-02 13:13:40 UTC (rev 4095) @@ -390,7 +390,8 @@ self.levels = kwargs.get('levels', None) self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) - + self.linestyles = kwargs.get('linestyles', 'solid') + self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) @@ -457,11 +458,13 @@ else: tlinewidths = self._process_linewidths() self.tlinewidths = tlinewidths + tlinestyles = self._process_linestyles() C = _cntr.Cntr(x, y, z.filled(), _mask) - for level, width in zip(self.levels, tlinewidths): + for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles): nlist = C.trace(level, points = 0) col = collections.LineCollection(nlist, - linewidths = width) + linewidths = width, + linestyle = lstyle) if level < 0.0 and self.monochrome: ls = mpl.rcParams['contour.negative_linestyle'] @@ -696,6 +699,18 @@ linewidths = [linewidths] * Nlev tlinewidths = [(w,) for w in linewidths] return tlinewidths + + def _process_linestyles(self): + linestyles = self.linestyles + Nlev = len(self.levels) + if linestyles is None: + tlinestyles = ['solid'] * Nlev + else: + if cbook.is_string_like(linestyles): + tlinestyles = [linestyles] * Nlev + elif cbook.iterable(linestyles) and len(linestyles) < Nlev: + tlinestyles = list(linestyles) * int(npy.ceil(Nlev/len(linestyles))) + return tlinestyles def get_alpha(self): '''For compatibility with artists, return self.alpha''' Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2007-11-02 12:55:51 UTC (rev 4094) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2007-11-02 13:13:40 UTC (rev 4095) @@ -811,7 +811,7 @@ """ - x = npy.ravel(x) + x = npy.array(x).ravel() # we need a copy x.sort() Nx = len(x) @@ -1449,7 +1449,7 @@ files is automatic, if the filename ends in .gz """ fh = cbook.to_filehandle(fname, 'w') - writer = csv.writer(fh, delimiter=delimiter) + writer = csv.writer(fh, delimiter=delimiter, quoting=csv.QUOTE_NONNUMERIC) header = r.dtype.names writer.writerow(header) for row in r: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2007-11-02 12:57:38
|
Revision: 4094 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4094&view=rev Author: dsdale Date: 2007-11-02 05:55:51 -0700 (Fri, 02 Nov 2007) Log Message: ----------- improved ghostscript version checking Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/config/checkdep.py trunk/matplotlib/lib/matplotlib/config/cutils.py trunk/matplotlib/lib/matplotlib/text.py Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2007-11-01 16:57:26 UTC (rev 4093) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2007-11-02 12:55:51 UTC (rev 4094) @@ -234,12 +234,11 @@ def checkdep_ghostscript(): try: if sys.platform == 'win32': - command = 'gswin32c -v' + command = 'gswin32c --version' else: - command = 'gs -v' + command = 'gs --version' stdin, stdout = os.popen4(command) - line = stdout.readlines()[0] - v = line.split()[-2] + v = stdout.read()[:-1] vtest = '.'.join(v.split('.')[:2]) # deal with version numbers like '7.07.1' float(vtest) return vtest Modified: trunk/matplotlib/lib/matplotlib/config/checkdep.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/checkdep.py 2007-11-01 16:57:26 UTC (rev 4093) +++ trunk/matplotlib/lib/matplotlib/config/checkdep.py 2007-11-02 12:55:51 UTC (rev 4094) @@ -4,28 +4,27 @@ import warnings import distutils.version as version +tex_req = '3.1415' +gs_req = '7.07' +gs_sugg = '8.60' +dvipng_req = '1.5' +pdftops_req = '3.0' + def dvipng(): try: stdin, stdout = os.popen4('dvipng -version') - line = stdout.readlines()[1] - v = line.split()[-1] - float(v) - return v + return stdout.readlines()[1].split()[-1] except (IndexError, ValueError): return None def ghostscript(): try: if sys.platform == 'win32': - command = 'gswin32c -v' + command = 'gswin32c --version' else: - command = 'gs -v' + command = 'gs --version' stdin, stdout = os.popen4(command) - line = stdout.readlines()[0] - v = line.split()[-2] - vtest = '.'.join(v.split('.')[:2]) # deal with version numbers like '7.07.1' - float(vtest) - return vtest + return stdout.read()[:-1] except (IndexError, ValueError): return None @@ -35,9 +34,7 @@ line = stdout.readlines()[0] pattern = '3\.1\d+' match = re.search(pattern, line) - v = match.group(0) - float(v) - return v + return match.group(0) except (IndexError, ValueError): return None @@ -46,9 +43,7 @@ stdin, stdout = os.popen4('pdftops -v') for line in stdout.readlines(): if 'version' in line: - v = line.split()[-1] - float(v) - return v + return line.split()[-1] except (IndexError, ValueError): return None @@ -66,8 +61,6 @@ return False flag = True - gs_req = '7.07' - gs_sugg = '7.07' gs_v = ghostscript() if compare_versions(gs_v, gs_sugg): pass elif compare_versions(gs_v, gs_req): @@ -81,14 +74,13 @@ 'system.') % gs_req) if s == 'xpdf': - pdftops_req = '3.0' pdftops_v = pdftops() if compare_versions(pdftops_v, pdftops_req): pass else: flag = False warnings.warn(('matplotlibrc ps.usedistiller can not be set to ' - 'xpdf unless xpdf-%s or later is installed on your ' - 'system.') % pdftops_req) + 'xpdf unless pdftops-%s or later is installed on ' + 'your system.') % pdftops_req) if flag: return s @@ -99,10 +91,6 @@ if not s: return False - tex_req = '3.1415' - gs_req = '7.07' - gs_sugg = '7.07' - dvipng_req = '1.5' flag = True tex_v = tex() Modified: trunk/matplotlib/lib/matplotlib/config/cutils.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/cutils.py 2007-11-01 16:57:26 UTC (rev 4093) +++ trunk/matplotlib/lib/matplotlib/config/cutils.py 2007-11-02 12:55:51 UTC (rev 4094) @@ -55,8 +55,6 @@ else: raise RuntimeError('please define environment variable $HOME') - - get_home = verbose.wrap('$HOME=%s', _get_home, always=False) def _get_configdir(): @@ -89,9 +87,9 @@ os.mkdir(p) return p + get_configdir = verbose.wrap('CONFIGDIR=%s', _get_configdir, always=False) - def _get_data_path(): 'get the path to matplotlib data' Modified: trunk/matplotlib/lib/matplotlib/text.py =================================================================== --- trunk/matplotlib/lib/matplotlib/text.py 2007-11-01 16:57:26 UTC (rev 4093) +++ trunk/matplotlib/lib/matplotlib/text.py 2007-11-02 12:55:51 UTC (rev 4094) @@ -654,7 +654,7 @@ self._text = '%s' % (s,) def is_math_text(self, s): - if rcParams['text.usetex']: return 'TeX' + if rcParams['text.usetex']: return 'TeX' # Did we find an even number of non-escaped dollar signs? # If so, treat is as math text. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2007-11-01 16:57:34
|
Revision: 4093 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4093&view=rev Author: dsdale Date: 2007-11-01 09:57:26 -0700 (Thu, 01 Nov 2007) Log Message: ----------- remove STIXFonts zip file Removed Paths: ------------- trunk/matplotlib/lib/matplotlib/mpl-data/fonts/otf/STIXBeta.zip Deleted: trunk/matplotlib/lib/matplotlib/mpl-data/fonts/otf/STIXBeta.zip =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2007-11-01 16:56:36
|
Revision: 4092 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4092&view=rev Author: dsdale Date: 2007-11-01 09:56:33 -0700 (Thu, 01 Nov 2007) Log Message: ----------- rm configtest.py from repository Removed Paths: ------------- trunk/matplotlib/lib/matplotlib/config/configtest.py Deleted: trunk/matplotlib/lib/matplotlib/config/configtest.py =================================================================== --- trunk/matplotlib/lib/matplotlib/config/configtest.py 2007-11-01 16:24:53 UTC (rev 4091) +++ trunk/matplotlib/lib/matplotlib/config/configtest.py 2007-11-01 16:56:33 UTC (rev 4092) @@ -1,8 +0,0 @@ -from api import rcParams, mplConfig - -print 'loaded your old rcParams["backend"]:', rcParams['backend'] -print 'changing rcParams["backend"] to cairo' -rcParams["backend"] = 'cairo' -print 'mplConfig.backend.use is now :', mplConfig.backend.use -print 'changing rcParams["backend"] to BogusBackend:' -rcParams["backend"] = 'BogusBackend' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-01 16:25:00
|
Revision: 4091 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4091&view=rev Author: jswhit Date: 2007-11-01 09:24:53 -0700 (Thu, 01 Nov 2007) Log Message: ----------- cleanup Modified Paths: -------------- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py Modified: trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py =================================================================== --- trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-01 15:17:24 UTC (rev 4090) +++ trunk/toolkits/basemap-testing/lib/matplotlib/toolkits/basemap/basemap.py 2007-11-01 16:24:53 UTC (rev 4091) @@ -747,14 +747,14 @@ if area < 0.: area = 1.e30 useit = self.latmax>=south and self.latmin<=north and area>self.area_thresh # skip Antartica for now. + #if south < -68: useit = False if useit: offsetbytes = int(linesplit[4]) bytecount = int(linesplit[5]) bdatfile.seek(offsetbytes,0) polystring = bdatfile.read(bytecount) poly = wkb.loads(polystring) - # close Antarctica for cylindrical projections - + # close Antartica for cylindrical projections. if name == 'gshhs' and self.projection in ['cyl','merc','mill']: b = npy.asarray(poly.boundary) lons = b[:,0] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-01 15:17:32
|
Revision: 4090 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4090&view=rev Author: jswhit Date: 2007-11-01 08:17:24 -0700 (Thu, 01 Nov 2007) Log Message: ----------- hires boundary example Added Paths: ----------- trunk/toolkits/basemap/examples/hires.py Added: trunk/toolkits/basemap/examples/hires.py =================================================================== --- trunk/toolkits/basemap/examples/hires.py (rev 0) +++ trunk/toolkits/basemap/examples/hires.py 2007-11-01 15:17:24 UTC (rev 4090) @@ -0,0 +1,26 @@ +from matplotlib.toolkits.basemap import Basemap +from pylab import * +import time + +# create new figure +fig=figure() +# create Basemap instance. Use 'high' resolution coastlines. +t1 = time.clock() +m = Basemap(llcrnrlon=-11.,llcrnrlat=49.,urcrnrlon=5.,urcrnrlat=59., + resolution='h',projection='tmerc',lon_0=-8.,lat_0=0.) +print 'time to create instance with high-res boundaries = ',time.clock()-t1 +# draw coastlines and fill continents. +m.drawcoastlines() +m.fillcontinents() +# draw political boundaries. +m.drawcountries(linewidth=1) +# draw major rivers. +m.drawrivers(color='b') +# draw parallels +circles = arange(48,65,2).tolist() +m.drawparallels(circles,labels=[1,1,0,0]) +# draw meridians +meridians = arange(-12,13,2) +m.drawmeridians(meridians,labels=[0,0,1,1]) +title("High-Res British Isles",y=1.075) +show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <js...@us...> - 2007-11-01 14:46:55
|
Revision: 4089 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4089&view=rev Author: jswhit Date: 2007-11-01 07:46:46 -0700 (Thu, 01 Nov 2007) Log Message: ----------- test for high-res boundaries Added Paths: ----------- trunk/toolkits/basemap-testing/examples/hires.py Added: trunk/toolkits/basemap-testing/examples/hires.py =================================================================== --- trunk/toolkits/basemap-testing/examples/hires.py (rev 0) +++ trunk/toolkits/basemap-testing/examples/hires.py 2007-11-01 14:46:46 UTC (rev 4089) @@ -0,0 +1,26 @@ +from matplotlib.toolkits.basemap import Basemap +from pylab import * +import time + +# create new figure +fig=figure() +# create Basemap instance. Use 'high' resolution coastlines. +t1 = time.clock() +m = Basemap(llcrnrlon=-11.,llcrnrlat=49.,urcrnrlon=5.,urcrnrlat=59., + resolution='h',projection='tmerc',lon_0=-8.,lat_0=0.) +print 'time to create instance with high-res boundaries = ',time.clock()-t1 +# draw coastlines and fill continents. +m.drawcoastlines() +m.fillcontinents() +# draw political boundaries. +m.drawcountries(linewidth=1) +# draw major rivers. +m.drawrivers(color='b') +# draw parallels +circles = arange(48,65,2).tolist() +m.drawparallels(circles,labels=[1,1,0,0]) +# draw meridians +meridians = arange(-12,13,2) +m.drawmeridians(meridians,labels=[0,0,1,1]) +title("High-Res British Isles",y=1.075) +show() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2007-11-01 14:32:54
|
Revision: 4088 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4088&view=rev Author: dsdale Date: 2007-11-01 07:32:52 -0700 (Thu, 01 Nov 2007) Log Message: ----------- dont enable usetex in arrow_demo.py Modified Paths: -------------- trunk/matplotlib/examples/arrow_demo.py Modified: trunk/matplotlib/examples/arrow_demo.py =================================================================== --- trunk/matplotlib/examples/arrow_demo.py 2007-11-01 14:17:28 UTC (rev 4087) +++ trunk/matplotlib/examples/arrow_demo.py 2007-11-01 14:32:52 UTC (rev 4088) @@ -11,7 +11,6 @@ """ from pylab import * -rc('text', usetex=True) rates_to_bases={'r1':'AT', 'r2':'TA', 'r3':'GA','r4':'AG','r5':'CA','r6':'AC', \ 'r7':'GT', 'r8':'TG', 'r9':'CT','r10':'TC','r11':'GC','r12':'CG'} numbered_bases_to_rates = dict([(v,k) for k, v in rates_to_bases.items()]) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2007-11-01 14:17:29
|
Revision: 4087 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=4087&view=rev Author: dsdale Date: 2007-11-01 07:17:28 -0700 (Thu, 01 Nov 2007) Log Message: ----------- install fonts/otf to mpl-data Modified Paths: -------------- trunk/matplotlib/setup.py Modified: trunk/matplotlib/setup.py =================================================================== --- trunk/matplotlib/setup.py 2007-11-01 14:02:29 UTC (rev 4086) +++ trunk/matplotlib/setup.py 2007-11-01 14:17:28 UTC (rev 4087) @@ -126,6 +126,7 @@ 'mpl-data/fonts/pdfcorefonts/*.afm', 'mpl-data/fonts/pdfcorefonts/*.txt', 'mpl-data/fonts/ttf/*.ttf', + 'mpl-data/fonts/otf/*.otf', 'mpl-data/images/*.xpm', 'mpl-data/images/*.svg', 'mpl-data/images/*.png', This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |