", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
+ try:
+ if len(symbols)==len("".join(symbols)):
+ return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
+ else:
+ return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
+ except:
+ warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
+ SyntaxWarning, stacklevel=2)
+
+
+ # last resort, just use MatchFirst
+ return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
+
+def dictOf( key, value ):
+ """Helper to easily and clearly define a dictionary by specifying the respective patterns
+ for the key and value. Takes care of defining the C{Dict}, C{ZeroOrMore}, and C{Group} tokens
+ in the proper order. The key pattern can include delimiting markers or punctuation,
+ as long as they are suppressed, thereby leaving the significant key text. The value
+ pattern can include named results, so that the C{Dict} results can include named token
+ fields.
+ """
+ return Dict( ZeroOrMore( Group ( key + value ) ) )
+
+def originalTextFor(expr, asString=True):
+ """Helper to return the original, untokenized text for a given expression. Useful to
+ restore the parsed fields of an HTML start tag into the raw tag text itself, or to
+ revert separate tokens with intervening whitespace back to the original matching
+ input text. Simpler to use than the parse action C{keepOriginalText}, and does not
+ require the inspect module to chase up the call stack. By default, returns a
+ string containing the original parsed text.
+
+ If the optional C{asString} argument is passed as False, then the return value is a
+ C{ParseResults} containing any results names that were originally matched, and a
+ single token containing the original matched text from the input string. So if
+ the expression passed to C{originalTextFor} contains expressions with defined
+ results names, you must set C{asString} to False if you want to preserve those
+ results name values."""
+ locMarker = Empty().setParseAction(lambda s,loc,t: loc)
+ endlocMarker = locMarker.copy()
+ endlocMarker.callPreparse = False
+ matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
+ if asString:
+ extractText = lambda s,l,t: s[t._original_start:t._original_end]
+ else:
+ def extractText(s,l,t):
+ del t[:]
+ t.insert(0, s[t._original_start:t._original_end])
+ del t["_original_start"]
+ del t["_original_end"]
+ matchExpr.setParseAction(extractText)
+ return matchExpr
+
+# convenience constants for positional expressions
+empty = Empty().setName("empty")
+lineStart = LineStart().setName("lineStart")
+lineEnd = LineEnd().setName("lineEnd")
+stringStart = StringStart().setName("stringStart")
+stringEnd = StringEnd().setName("stringEnd")
+
+_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
+_printables_less_backslash = "".join([ c for c in printables if c not in r"\]" ])
+_escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
+_escapedOctChar = Combine( Suppress(_bslash) + Word("0","01234567") ).setParseAction(lambda s,l,t:unichr(int(t[0],8)))
+_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1)
+_charRange = Group(_singleChar + Suppress("-") + _singleChar)
+_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
+
+_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
+
+def srange(s):
+ r"""Helper to easily define string ranges for use in Word construction. Borrows
+ syntax from regexp '[]' string range definitions::
+ srange("[0-9]") -> "0123456789"
+ srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
+ srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
+ The input string must be enclosed in []'s, and the returned string is the expanded
+ character set joined into a single string.
+ The values enclosed in the []'s may be::
+ a single character
+ an escaped character with a leading backslash (such as \- or \])
+ an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
+ an escaped octal character with a leading '\0' (\041, which is a '!' character)
+ a range of any of the above, separated by a dash ('a-z', etc.)
+ any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
+ """
+ try:
+ return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])
+ except:
+ return ""
+
+def matchOnlyAtCol(n):
+ """Helper method for defining parse actions that require matching at a specific
+ column in the input text.
+ """
+ def verifyCol(strg,locn,toks):
+ if col(locn,strg) != n:
+ raise ParseException(strg,locn,"matched token not at column %d" % n)
+ return verifyCol
+
+def replaceWith(replStr):
+ """Helper method for common parse actions that simply return a literal value. Especially
+ useful when used with C{transformString()}.
+ """
+ def _replFunc(*args):
+ return [replStr]
+ return _replFunc
+
+def removeQuotes(s,l,t):
+ """Helper parse action for removing quotation marks from parsed quoted strings.
+ To use, add this parse action to quoted string using::
+ quotedString.setParseAction( removeQuotes )
+ """
+ return t[0][1:-1]
+
+def upcaseTokens(s,l,t):
+ """Helper parse action to convert tokens to upper case."""
+ return [ tt.upper() for tt in map(_ustr,t) ]
+
+def downcaseTokens(s,l,t):
+ """Helper parse action to convert tokens to lower case."""
+ return [ tt.lower() for tt in map(_ustr,t) ]
+
+def keepOriginalText(s,startLoc,t):
+ """DEPRECATED - use new helper method C{originalTextFor}.
+ Helper parse action to preserve original parsed text,
+ overriding any nested parse actions."""
+ try:
+ endloc = getTokensEndLoc()
+ except ParseException:
+ raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action")
+ del t[:]
+ t += ParseResults(s[startLoc:endloc])
+ return t
+
+def getTokensEndLoc():
+ """Method to be called from within a parse action to determine the end
+ location of the parsed tokens."""
+ import inspect
+ fstack = inspect.stack()
+ try:
+ # search up the stack (through intervening argument normalizers) for correct calling routine
+ for f in fstack[2:]:
+ if f[3] == "_parseNoCache":
+ endloc = f[0].f_locals["loc"]
+ return endloc
+ else:
+ raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
+ finally:
+ del fstack
+
+def _makeTags(tagStr, xml):
+ """Internal helper to construct opening and closing tag expressions, given a tag name"""
+ if isinstance(tagStr,basestring):
+ resname = tagStr
+ tagStr = Keyword(tagStr, caseless=not xml)
+ else:
+ resname = tagStr.name
+
+ tagAttrName = Word(alphas,alphanums+"_-:")
+ if (xml):
+ tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
+ openTag = Suppress("<") + tagStr("tag") + \
+ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
+ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
+ else:
+ printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
+ tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
+ openTag = Suppress("<") + tagStr + \
+ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
+ Optional( Suppress("=") + tagAttrValue ) ))) + \
+ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
+ closeTag = Combine(_L("") + tagStr + ">")
+
+ openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
+ closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("%s>" % tagStr)
+ openTag.tag = resname
+ closeTag.tag = resname
+ return openTag, closeTag
+
+def makeHTMLTags(tagStr):
+ """Helper to construct opening and closing tag expressions for HTML, given a tag name"""
+ return _makeTags( tagStr, False )
+
+def makeXMLTags(tagStr):
+ """Helper to construct opening and closing tag expressions for XML, given a tag name"""
+ return _makeTags( tagStr, True )
+
+def withAttribute(*args,**attrDict):
+ """Helper to create a validating parse action to be used with start tags created
+ with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag
+ with a required attribute value, to avoid false matches on common tags such as
+ or .
+
+ Call withAttribute with a series of attribute names and values. Specify the list
+ of filter attributes names and values as:
+ - keyword arguments, as in (class="Customer",align="right"), or
+ - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
+ For attribute names with a namespace prefix, you must use the second form. Attribute
+ names are matched insensitive to upper/lower case.
+
+ To verify that the attribute exists, but without specifying a value, pass
+ withAttribute.ANY_VALUE as the value.
+ """
+ if args:
+ attrs = args[:]
+ else:
+ attrs = attrDict.items()
+ attrs = [(k,v) for k,v in attrs]
+ def pa(s,l,tokens):
+ for attrName,attrValue in attrs:
+ if attrName not in tokens:
+ raise ParseException(s,l,"no matching attribute " + attrName)
+ if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
+ raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
+ (attrName, tokens[attrName], attrValue))
+ return pa
+withAttribute.ANY_VALUE = object()
+
+opAssoc = _Constants()
+opAssoc.LEFT = object()
+opAssoc.RIGHT = object()
+
+def operatorPrecedence( baseExpr, opList ):
+ """Helper method for constructing grammars of expressions made up of
+ operators working in a precedence hierarchy. Operators may be unary or
+ binary, left- or right-associative. Parse actions can also be attached
+ to operator expressions.
+
+ Parameters:
+ - baseExpr - expression representing the most basic element for the nested
+ - opList - list of tuples, one for each operator precedence level in the
+ expression grammar; each tuple is of the form
+ (opExpr, numTerms, rightLeftAssoc, parseAction), where:
+ - opExpr is the pyparsing expression for the operator;
+ may also be a string, which will be converted to a Literal;
+ if numTerms is 3, opExpr is a tuple of two expressions, for the
+ two operators separating the 3 terms
+ - numTerms is the number of terms for this operator (must
+ be 1, 2, or 3)
+ - rightLeftAssoc is the indicator whether the operator is
+ right or left associative, using the pyparsing-defined
+ constants opAssoc.RIGHT and opAssoc.LEFT.
+ - parseAction is the parse action to be associated with
+ expressions matching this operator expression (the
+ parse action tuple member may be omitted)
+ """
+ ret = Forward()
+ lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') )
+ for i,operDef in enumerate(opList):
+ opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
+ if arity == 3:
+ if opExpr is None or len(opExpr) != 2:
+ raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
+ opExpr1, opExpr2 = opExpr
+ thisExpr = Forward()#.setName("expr%d" % i)
+ if rightLeftAssoc == opAssoc.LEFT:
+ if arity == 1:
+ matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
+ elif arity == 2:
+ if opExpr is not None:
+ matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
+ else:
+ matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
+ elif arity == 3:
+ matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
+ Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
+ else:
+ raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
+ elif rightLeftAssoc == opAssoc.RIGHT:
+ if arity == 1:
+ # try to avoid LR with this extra test
+ if not isinstance(opExpr, Optional):
+ opExpr = Optional(opExpr)
+ matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
+ elif arity == 2:
+ if opExpr is not None:
+ matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
+ else:
+ matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
+ elif arity == 3:
+ matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
+ Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
+ else:
+ raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
+ else:
+ raise ValueError("operator must indicate right or left associativity")
+ if pa:
+ matchExpr.setParseAction( pa )
+ thisExpr << ( matchExpr | lastExpr )
+ lastExpr = thisExpr
+ ret << lastExpr
+ return ret
+
+dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes")
+sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes")
+quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes")
+unicodeString = Combine(_L('u') + quotedString.copy())
+
+def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
+ """Helper method for defining nested lists enclosed in opening and closing
+ delimiters ("(" and ")" are the default).
+
+ Parameters:
+ - opener - opening character for a nested list (default="("); can also be a pyparsing expression
+ - closer - closing character for a nested list (default=")"); can also be a pyparsing expression
+ - content - expression for items within the nested lists (default=None)
+ - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString)
+
+ If an expression is not provided for the content argument, the nested
+ expression will capture all whitespace-delimited content between delimiters
+ as a list of separate values.
+
+ Use the ignoreExpr argument to define expressions that may contain
+ opening or closing characters that should not be treated as opening
+ or closing characters for nesting, such as quotedString or a comment
+ expression. Specify multiple expressions using an Or or MatchFirst.
+ The default is quotedString, but if no expressions are to be ignored,
+ then pass None for this argument.
+ """
+ if opener == closer:
+ raise ValueError("opening and closing strings cannot be the same")
+ if content is None:
+ if isinstance(opener,basestring) and isinstance(closer,basestring):
+ if len(opener) == 1 and len(closer)==1:
+ if ignoreExpr is not None:
+ content = (Combine(OneOrMore(~ignoreExpr +
+ CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1))
+ ).setParseAction(lambda t:t[0].strip()))
+ else:
+ content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS
+ ).setParseAction(lambda t:t[0].strip()))
+ else:
+ if ignoreExpr is not None:
+ content = (Combine(OneOrMore(~ignoreExpr +
+ ~Literal(opener) + ~Literal(closer) +
+ CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
+ ).setParseAction(lambda t:t[0].strip()))
+ else:
+ content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) +
+ CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
+ ).setParseAction(lambda t:t[0].strip()))
+ else:
+ raise ValueError("opening and closing arguments must be strings if no content expression is given")
+ ret = Forward()
+ if ignoreExpr is not None:
+ ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) )
+ else:
+ ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) )
+ return ret
+
+def indentedBlock(blockStatementExpr, indentStack, indent=True):
+ """Helper method for defining space-delimited indentation blocks, such as
+ those used to define block statements in Python source code.
+
+ Parameters:
+ - blockStatementExpr - expression defining syntax of statement that
+ is repeated within the indented block
+ - indentStack - list created by caller to manage indentation stack
+ (multiple statementWithIndentedBlock expressions within a single grammar
+ should share a common indentStack)
+ - indent - boolean indicating whether block must be indented beyond the
+ the current level; set to False for block of left-most statements
+ (default=True)
+
+ A valid block must contain at least one blockStatement.
+ """
+ def checkPeerIndent(s,l,t):
+ if l >= len(s): return
+ curCol = col(l,s)
+ if curCol != indentStack[-1]:
+ if curCol > indentStack[-1]:
+ raise ParseFatalException(s,l,"illegal nesting")
+ raise ParseException(s,l,"not a peer entry")
+
+ def checkSubIndent(s,l,t):
+ curCol = col(l,s)
+ if curCol > indentStack[-1]:
+ indentStack.append( curCol )
+ else:
+ raise ParseException(s,l,"not a subentry")
+
+ def checkUnindent(s,l,t):
+ if l >= len(s): return
+ curCol = col(l,s)
+ if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
+ raise ParseException(s,l,"not an unindent")
+ indentStack.pop()
+
+ NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
+ INDENT = Empty() + Empty().setParseAction(checkSubIndent)
+ PEER = Empty().setParseAction(checkPeerIndent)
+ UNDENT = Empty().setParseAction(checkUnindent)
+ if indent:
+ smExpr = Group( Optional(NL) +
+ #~ FollowedBy(blockStatementExpr) +
+ INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
+ else:
+ smExpr = Group( Optional(NL) +
+ (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
+ blockStatementExpr.ignore(_bslash + LineEnd())
+ return smExpr
+
+alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
+punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
+
+anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:"))
+commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";").streamline()
+_htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),'><& "'))
+replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None
+
+# it's easy to get these comment structures wrong - they're very common, so may as well make them available
+cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment")
+
+htmlComment = Regex(r"")
+restOfLine = Regex(r".*").leaveWhitespace()
+dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment")
+cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?" + str(tokenlist))
+ print ("tokens = " + str(tokens))
+ print ("tokens.columns = " + str(tokens.columns))
+ print ("tokens.tables = " + str(tokens.tables))
+ print (tokens.asXML("SQL",True))
+ except ParseBaseException as err:
+ print (teststring + "->")
+ print (err.line)
+ print (" "*(err.column-1) + "^")
+ print (err)
+ print()
+
+ selectToken = CaselessLiteral( "select" )
+ fromToken = CaselessLiteral( "from" )
+
+ ident = Word( alphas, alphanums + "_$" )
+ columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
+ columnNameList = Group( delimitedList( columnName ) )#.setName("columns")
+ tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
+ tableNameList = Group( delimitedList( tableName ) )#.setName("tables")
+ simpleSQL = ( selectToken + \
+ ( '*' | columnNameList ).setResultsName( "columns" ) + \
+ fromToken + \
+ tableNameList.setResultsName( "tables" ) )
+
+ test( "SELECT * from XYZZY, ABC" )
+ test( "select * from SYS.XYZZY" )
+ test( "Select A from Sys.dual" )
+ test( "Select AA,BB,CC from Sys.dual" )
+ test( "Select A, B, C from Sys.dual" )
+ test( "Select A, B, C from Sys.dual" )
+ test( "Xelect A, B, C from Sys.dual" )
+ test( "Select A, B, C frox Sys.dual" )
+ test( "Select" )
+ test( "Select ^^^ frox Sys.dual" )
+ test( "Select A, B, C from Sys.dual, Table2 " )
diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py
index e15c640cf765..37ae7cb08ee7 100644
--- a/lib/matplotlib/pyplot.py
+++ b/lib/matplotlib/pyplot.py
@@ -13,6 +13,7 @@
plt.plot(x, y)
"""
+from __future__ import print_function
import sys, warnings
diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py
index 7a507df17ac5..caefd612ad7c 100644
--- a/lib/matplotlib/quiver.py
+++ b/lib/matplotlib/quiver.py
@@ -15,6 +15,7 @@
"""
+from __future__ import print_function
import numpy as np
from numpy import ma
import matplotlib.collections as collections
diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py
index 40e3a2ba5780..ce77fb86d6c6 100644
--- a/lib/matplotlib/rcsetup.py
+++ b/lib/matplotlib/rcsetup.py
@@ -12,6 +12,7 @@
parameter set listed here should also be visited to the
:file:`matplotlibrc.template` in matplotlib's root source directory.
"""
+from __future__ import print_function
import os
import warnings
@@ -92,11 +93,11 @@ def validate_fonttype(s):
try:
fonttype = validate_int(s)
except ValueError:
- if s.lower() in fonttypes.keys():
+ if s.lower() in fonttypes.iterkeys():
return fonttypes[s.lower()]
raise ValueError('Supported Postscript/PDF font types are %s' % fonttypes.keys())
else:
- if fonttype not in fonttypes.values():
+ if fonttype not in fonttypes.itervalues():
raise ValueError('Supported Postscript/PDF font types are %s' % fonttypes.values())
return fonttype
@@ -577,4 +578,4 @@ def __call__(self, s):
rc['datapath'][0] = '/'
for key in rc:
if not rc[key][1](rc[key][0]) == rc[key][0]:
- print "%s: %s != %s"%(key, rc[key][1](rc[key][0]), rc[key][0])
+ print("%s: %s != %s"%(key, rc[key][1](rc[key][0]), rc[key][0]))
diff --git a/lib/matplotlib/scale.py b/lib/matplotlib/scale.py
index 870a3cfb5854..a508825955d7 100644
--- a/lib/matplotlib/scale.py
+++ b/lib/matplotlib/scale.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import textwrap
import numpy as np
from numpy import ma
@@ -312,28 +313,29 @@ class SymmetricalLogScale(ScaleBase):
name = 'symlog'
class SymmetricalLogTransform(Transform):
- input_dims = 1
- output_dims = 1
- is_separable = True
-
- def __init__(self, base, linthresh):
- Transform.__init__(self)
- self.base = base
- self.linthresh = linthresh
- self._log_base = np.log(base)
- self._linadjust = (np.log(linthresh) / self._log_base) / linthresh
-
- def transform(self, a):
- sign = np.sign(a)
- masked = ma.masked_inside(a, -self.linthresh, self.linthresh, copy=False)
- log = sign * self.linthresh * (1 + ma.log(np.abs(masked) / self.linthresh))
- if masked.mask.any():
- return ma.where(masked.mask, a, log)
- else:
- return log
-
- def inverted(self):
- return SymmetricalLogScale.InvertedSymmetricalLogTransform(self.base, self.linthresh)
+ input_dims = 1
+ output_dims = 1
+ is_separable = True
+
+ def __init__(self, base, linthresh):
+ Transform.__init__(self)
+ self.base = base
+ self.linthresh = linthresh
+ self._log_base = np.log(base)
+ self._linadjust = (np.log(linthresh) / self._log_base) / linthresh
+
+ def transform(self, a):
+ sign = np.sign(a)
+ masked = ma.masked_inside(a, -self.linthresh, self.linthresh, copy=False)
+ log = sign * self.linthresh * (1 + ma.log(np.abs(masked) / self.linthresh))
+ if masked.mask.any():
+ return ma.where(masked.mask, a, log)
+ else:
+ return log
+
+ def inverted(self):
+ return SymmetricalLogScale.InvertedSymmetricalLogTransform(
+ self.base, self.linthresh)
class InvertedSymmetricalLogTransform(Transform):
input_dims = 1
@@ -344,9 +346,9 @@ def __init__(self, base, linthresh):
Transform.__init__(self)
self.base = base
self.linthresh = linthresh
- self._log_base = np.log(base)
- self._log_linthresh = np.log(linthresh) / self._log_base
- self._linadjust = linthresh / (np.log(linthresh) / self._log_base)
+ log_base = np.log(base)
+ logb_linthresh = np.log(linthresh) / log_base
+ self._linadjust = 1.0 - logb_linthresh
def transform(self, a):
sign = np.sign(a)
@@ -357,6 +359,10 @@ def transform(self, a):
else:
return exp
+ def inverted(self):
+ return SymmetricalLogScale.SymmetricalLogTransform(
+ self.base, self.linthresh)
+
def __init__(self, axis, **kwargs):
"""
*basex*/*basey*:
@@ -387,7 +393,6 @@ def __init__(self, axis, **kwargs):
assert base > 0.0
assert linthresh > 0.0
-
self.base = base
self.linthresh = linthresh
self.subs = subs
diff --git a/lib/matplotlib/sphinxext/__init__.py b/lib/matplotlib/sphinxext/__init__.py
index 8b137891791f..2caf15b12cc7 100644
--- a/lib/matplotlib/sphinxext/__init__.py
+++ b/lib/matplotlib/sphinxext/__init__.py
@@ -1 +1,2 @@
+from __future__ import print_function
diff --git a/lib/matplotlib/sphinxext/ipython_console_highlighting.py b/lib/matplotlib/sphinxext/ipython_console_highlighting.py
index 217b779dda78..c9bf1c1514ab 100644
--- a/lib/matplotlib/sphinxext/ipython_console_highlighting.py
+++ b/lib/matplotlib/sphinxext/ipython_console_highlighting.py
@@ -4,6 +4,7 @@
'pycon' lexer for the python console. At the very least it will give better
highlighted tracebacks.
"""
+from __future__ import print_function
#-----------------------------------------------------------------------------
# Needed modules
@@ -13,7 +14,7 @@
# Third party
from pygments.lexer import Lexer, do_insertions
-from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer,
+from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer,
PythonTracebackLexer)
from pygments.token import Comment, Generic
@@ -48,7 +49,7 @@ class IPythonConsoleLexer(Lexer):
- It assumes the default IPython prompts, not customized ones.
"""
-
+
name = 'IPython console session'
aliases = ['ipython']
mimetypes = ['text/x-ipython-console']
diff --git a/lib/matplotlib/sphinxext/ipython_directive.py b/lib/matplotlib/sphinxext/ipython_directive.py
new file mode 100644
index 000000000000..0374e50824eb
--- /dev/null
+++ b/lib/matplotlib/sphinxext/ipython_directive.py
@@ -0,0 +1,568 @@
+from __future__ import print_function
+import sys, os, shutil, imp, warnings, cStringIO, re
+
+import IPython
+from IPython.Shell import MatplotlibShell
+
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+from docutils.parsers.rst import directives
+import sphinx
+
+
+sphinx_version = sphinx.__version__.split(".")
+# The split is necessary for sphinx beta versions where the string is
+# '6b1'
+sphinx_version = tuple([int(re.split('[a-z]', x)[0])
+ for x in sphinx_version[:2]])
+
+
+
+COMMENT, INPUT, OUTPUT = range(3)
+rgxin = re.compile('In \[(\d+)\]:\s?(.*)\s*')
+rgxout = re.compile('Out\[(\d+)\]:\s?(.*)\s*')
+fmtin = 'In [%d]:'
+fmtout = 'Out[%d]:'
+
+def block_parser(part):
+ """
+ part is a string of ipython text, comprised of at most one
+ input, one ouput, comments, and blank lines. The block parser
+ parses the text into a list of::
+
+ blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
+ where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
+ data is, depending on the type of token::
+
+ COMMENT : the comment string
+
+ INPUT: the (DECORATOR, INPUT_LINE, REST) where
+ DECORATOR: the input decorator (or None)
+ INPUT_LINE: the input as string (possibly multi-line)
+ REST : any stdout generated by the input line (not OUTPUT)
+
+
+ OUTPUT: the output string, possibly multi-line
+
+ """
+
+ block = []
+ lines = part.split('\n')
+ #print 'PARSE', lines
+ N = len(lines)
+ i = 0
+ decorator = None
+ while 1:
+
+ if i==N:
+ # nothing left to parse -- the last line
+ break
+
+ line = lines[i]
+ i += 1
+ line_stripped = line.strip()
+ if line_stripped.startswith('#'):
+ block.append((COMMENT, line))
+ continue
+
+
+ if line_stripped.startswith('@'):
+ # we're assuming at most one decorator -- may need to
+ # rethink
+ decorator = line_stripped
+ continue
+
+ # does this look like an input line?
+ matchin = rgxin.match(line)
+ if matchin:
+ lineno, inputline = int(matchin.group(1)), matchin.group(2)
+
+ # the ....: continuation string
+ continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
+ Nc = len(continuation)
+ # input lines can continue on for more than one line, if
+ # we have a '\' line continuation char or a function call
+ # echo line 'print'. The input line can only be
+ # terminated by the end of the block or an output line, so
+ # we parse out the rest of the input line if it is
+ # multiline as well as any echo text
+
+ rest = []
+ while i 2:
+ if debug:
+ print('\n'.join(lines))
+ else:
+ #print 'INSERTING %d lines'%len(lines)
+ state_machine.insert_input(
+ lines, state_machine.input_lines.source(0))
+
+ return []
+
+ipython_directive.DEBUG = False
+
+def setup(app):
+ setup.app = app
+ options = {
+ 'suppress': directives.flag,
+ 'doctest': directives.flag,
+ 'verbatim': directives.flag,
+ }
+
+
+ app.add_directive('ipython', ipython_directive, True, (0, 2, 0), **options)
+
+
+def test():
+
+ examples = [
+ r"""
+In [9]: pwd
+Out[9]: '/home/jdhunter/py4science/book'
+
+In [10]: cd bookdata/
+/home/jdhunter/py4science/book/bookdata
+
+In [2]: from pylab import *
+
+In [2]: ion()
+
+In [3]: im = imread('stinkbug.png')
+
+@savefig mystinkbug.png width=4in
+In [4]: imshow(im)
+Out[4]:
+
+""",
+ r"""
+
+In [1]: x = 'hello world'
+
+# string methods can be
+# used to alter the string
+@doctest
+In [2]: x.upper()
+Out[2]: 'HELLO WORLD'
+
+@verbatim
+In [3]: x.st
+x.startswith x.strip
+""",
+ r"""
+
+In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
+ .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
+
+In [131]: print url.split('&')
+--------> print(url.split('&'))
+['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
+
+In [60]: import urllib
+
+""",
+ r"""\
+
+In [133]: import numpy.random
+
+@suppress
+In [134]: numpy.random.seed(2358)
+
+@doctest
+In [135]: np.random.rand(10,2)
+Out[135]:
+array([[ 0.64524308, 0.59943846],
+ [ 0.47102322, 0.8715456 ],
+ [ 0.29370834, 0.74776844],
+ [ 0.99539577, 0.1313423 ],
+ [ 0.16250302, 0.21103583],
+ [ 0.81626524, 0.1312433 ],
+ [ 0.67338089, 0.72302393],
+ [ 0.7566368 , 0.07033696],
+ [ 0.22591016, 0.77731835],
+ [ 0.0072729 , 0.34273127]])
+
+""",
+
+ r"""
+In [106]: print x
+--------> print(x)
+jdh
+
+In [109]: for i in range(10):
+ .....: print i
+ .....:
+ .....:
+0
+1
+2
+3
+4
+5
+6
+7
+8
+9
+
+
+""",
+
+ r"""
+
+In [144]: from pylab import *
+
+In [145]: ion()
+
+# use a semicolon to suppress the output
+@savefig test_hist.png width=4in
+In [151]: hist(np.random.randn(10000), 100);
+
+
+@savefig test_plot.png width=4in
+In [151]: plot(np.random.randn(10000), 'o');
+ """,
+
+ r"""
+# use a semicolon to suppress the output
+In [151]: plt.clf()
+
+@savefig plot_simple.png width=4in
+In [151]: plot([1,2,3])
+
+@savefig hist_simple.png width=4in
+In [151]: hist(np.random.randn(10000), 100);
+
+""",
+ r"""
+# update the current fig
+In [151]: ylabel('number')
+
+In [152]: title('normal distribution')
+
+
+@savefig hist_with_text.png
+In [153]: grid(True)
+
+ """,
+
+
+ r"""
+
+In [239]: 1/2
+@verbatim
+Out[239]: 0
+
+In [240]: 1.0/2.0
+Out[240]: 0.5
+""",
+
+ r"""
+@verbatim
+In [6]: pwd
+Out[6]: '/home/jdhunter/mypy'
+""",
+
+ r"""
+@verbatim
+In [151]: myfile.upper?
+Type: builtin_function_or_method
+Base Class:
+String Form:
+Namespace: Interactive
+Docstring:
+ S.upper() -> string
+ Return a copy of the string S converted to uppercase.
+ """
+ ]
+
+
+
+ ipython_directive.DEBUG = True
+ #options = dict(suppress=True)
+ options = dict()
+ for example in examples:
+ content = example.split('\n')
+ ipython_directive('debug', arguments=None, options=options,
+ content=content, lineno=0,
+ content_offset=None, block_text=None,
+ state=None, state_machine=None,
+ )
+
+
+if __name__=='__main__':
+ test()
diff --git a/lib/matplotlib/sphinxext/mathmpl.py b/lib/matplotlib/sphinxext/mathmpl.py
index ba691b77fb29..0c126a66b02e 100644
--- a/lib/matplotlib/sphinxext/mathmpl.py
+++ b/lib/matplotlib/sphinxext/mathmpl.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import os
import sys
try:
diff --git a/lib/matplotlib/sphinxext/only_directives.py b/lib/matplotlib/sphinxext/only_directives.py
index ffb4d841a535..9d8d0bb0aa01 100644
--- a/lib/matplotlib/sphinxext/only_directives.py
+++ b/lib/matplotlib/sphinxext/only_directives.py
@@ -3,6 +3,7 @@
# either html or latex.
#
+from __future__ import print_function
from docutils.nodes import Body, Element
from docutils.parsers.rst import directives
diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py
index 5d7b2c524b72..94ae17265822 100644
--- a/lib/matplotlib/sphinxext/plot_directive.py
+++ b/lib/matplotlib/sphinxext/plot_directive.py
@@ -106,6 +106,7 @@
be applied before each plot.
"""
+from __future__ import print_function
import sys, os, glob, shutil, imp, warnings, cStringIO, re, textwrap, \
traceback, exceptions
@@ -624,9 +625,8 @@ def run(arguments, content, options, state_machine, state, lineno):
else:
function_name = None
- fd = open(source_file_name, 'r')
- code = fd.read()
- fd.close()
+ with open(source_file_name, 'r') as fd:
+ code = fd.read()
output_base = os.path.basename(source_file_name)
else:
source_file_name = rst_file
@@ -765,12 +765,11 @@ def run(arguments, content, options, state_machine, state, lineno):
# copy script (if necessary)
target_name = os.path.join(dest_dir, output_base + source_ext)
- f = open(target_name, 'w')
- if source_file_name == rst_file:
- code_escaped = unescape_doctest(code)
- else:
- code_escaped = code
- f.write(code_escaped)
- f.close()
+ with open(target_name, 'w') as f:
+ if source_file_name == rst_file:
+ code_escaped = unescape_doctest(code)
+ else:
+ code_escaped = code
+ f.write(code_escaped)
return errors
diff --git a/lib/matplotlib/spines.py b/lib/matplotlib/spines.py
index 0ea9eac7a9e3..c477bf62419f 100644
--- a/lib/matplotlib/spines.py
+++ b/lib/matplotlib/spines.py
@@ -1,4 +1,4 @@
-from __future__ import division
+from __future__ import division, print_function
import matplotlib
rcParams = matplotlib.rcParams
diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py
index 7036995ceff1..d456b7ffcdce 100644
--- a/lib/matplotlib/table.py
+++ b/lib/matplotlib/table.py
@@ -19,7 +19,7 @@
License : matplotlib license
"""
-from __future__ import division
+from __future__ import division, print_function
import warnings
import artist
@@ -184,7 +184,7 @@ def __init__(self, ax, loc=None, bbox=None):
Artist.__init__(self)
if is_string_like(loc) and loc not in self.codes:
- warnings.warn('Unrecognized location %s. Falling back on bottom; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys())))
+ warnings.warn('Unrecognized location %s. Falling back on bottom; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.iterkeys())))
loc = 'bottom'
if is_string_like(loc): loc = self.codes.get(loc, 1)
self.set_figure(ax.figure)
@@ -243,7 +243,7 @@ def _get_grid_bbox(self, renderer):
Only include those in the range (0,0) to (maxRow, maxCol)"""
boxes = [self._cells[pos].get_window_extent(renderer)
- for pos in self._cells.keys()
+ for pos in self._cells.iterkeys()
if pos[0] >= 0 and pos[1] >= 0]
bbox = Bbox.union(boxes)
@@ -254,13 +254,14 @@ def contains(self,mouseevent):
Returns T/F, {}
"""
- if callable(self._contains): return self._contains(self,mouseevent)
+ if callable(self._contains):
+ return self._contains(self,mouseevent)
# TODO: Return index of the cell containing the cursor so that the user
# doesn't have to bind to each one individually.
if self._cachedRenderer is not None:
boxes = [self._cells[pos].get_window_extent(self._cachedRenderer)
- for pos in self._cells.keys()
+ for pos in self._cells.iterkeys()
if pos[0] >= 0 and pos[1] >= 0]
bbox = bbox_all(boxes)
return bbox.contains(mouseevent.x,mouseevent.y),{}
diff --git a/lib/matplotlib/testing/__init__.py b/lib/matplotlib/testing/__init__.py
index e69de29bb2d1..350b53fa98e7 100644
--- a/lib/matplotlib/testing/__init__.py
+++ b/lib/matplotlib/testing/__init__.py
@@ -0,0 +1 @@
+from __future__ import print_function
diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py
index 76ae263d013d..349d4ea3c179 100644
--- a/lib/matplotlib/testing/compare.py
+++ b/lib/matplotlib/testing/compare.py
@@ -1,10 +1,15 @@
#=======================================================================
+
""" A set of utilities for comparing results.
"""
#=======================================================================
+from __future__ import division
+
import matplotlib
from matplotlib.testing.noseclasses import ImageComparisonFailure
+from matplotlib.testing import image_util
+from matplotlib import _png
import math
import operator
import os
@@ -12,6 +17,7 @@
import shutil
import subprocess
import sys
+from functools import reduce
#=======================================================================
@@ -32,7 +38,7 @@ def compare_float( expected, actual, relTol = None, absTol = None ):
exMsg = "You haven't specified a 'relTol' relative tolerance "
exMsg += "or a 'absTol' absolute tolerance function argument. "
exMsg += "You must specify one."
- raise ValueError, exMsg
+ raise ValueError(exMsg)
msg = ""
@@ -96,7 +102,7 @@ def convert(*args):
msg += "Standard output:\n%s\n" % stdout
if stderr:
msg += "Standard error:\n%s\n" % stderr
- raise IOError, msg
+ raise IOError(msg)
return convert
if matplotlib.checkdep_ghostscript() is not None:
@@ -128,10 +134,10 @@ def convert(filename):
'''
base, extension = filename.rsplit('.', 1)
if extension not in converter:
- raise ImageComparisonFailure, "Don't know how to convert %s files to png" % extension
+ raise ImageComparisonFailure("Don't know how to convert %s files to png" % extension)
newname = base + '_' + extension + '.png'
if not os.path.exists(filename):
- raise IOError, "'%s' does not exist" % filename
+ raise IOError("'%s' does not exist" % filename)
# Only convert the file if the destination doesn't already exist or
# is out of date.
if (not os.path.exists(newname) or
@@ -146,7 +152,7 @@ def verify(filename):
Verify the file through some sort of verification tool.
"""
if not os.path.exists(filename):
- raise IOError, "'%s' does not exist" % filename
+ raise IOError("'%s' does not exist" % filename)
base, extension = filename.rsplit('.', 1)
verifier = verifiers.get(extension, None)
if verifier is not None:
@@ -160,7 +166,7 @@ def verify(filename):
msg += "Standard output:\n%s\n" % stdout
if stderr:
msg += "Standard error:\n%s\n" % stderr
- raise IOError, msg
+ raise IOError(msg)
# Turning this off, because it seems to cause multiprocessing issues
if matplotlib.checkdep_xmllint() and False:
@@ -171,9 +177,9 @@ def crop_to_same(actual_path, actual_image, expected_path, expected_image):
# clip the images to the same size -- this is useful only when
# comparing eps to pdf
if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf':
- aw, ah = actual_image.size
- ew, eh = expected_image.size
- actual_image = actual_image.crop((aw/2-ew/2, ah/2-eh/2, aw/2+ew/2, ah/2+eh/2))
+ aw, ah = actual_image.shape
+ ew, eh = expected_image.shape
+ actual_image = actual_image[int(aw/2-ew/2):int(aw/2+ew/2),int(ah/2-eh/2):int(ah/2+eh/2)]
return actual_image, expected_image
def compare_images( expected, actual, tol, in_decorator=False ):
@@ -195,18 +201,6 @@ def compare_images( expected, actual, tol, in_decorator=False ):
True. (default=False)
'''
- try:
- from PIL import Image, ImageOps, ImageFilter
- except ImportError, e:
- msg = "Image Comparison requires the Python Imaging Library to " \
- "be installed. To run tests without using PIL, then use " \
- "the '--without-tag=PIL' command-line option.\n" \
- "Importing PIL failed with the following error:\n%s" % e
- if in_decorator:
- raise NotImplementedError, e
- else:
- return msg
-
verify(actual)
# Convert the image to png
@@ -216,19 +210,27 @@ def compare_images( expected, actual, tol, in_decorator=False ):
expected = convert(expected)
# open the image files and remove the alpha channel (if it exists)
- expectedImage = Image.open( expected ).convert("RGB")
- actualImage = Image.open( actual ).convert("RGB")
+ expectedImage = _png.read_png_uint8( expected )
+ actualImage = _png.read_png_uint8( actual )
actualImage, expectedImage = crop_to_same(actual, actualImage, expected, expectedImage)
# normalize the images
- expectedImage = ImageOps.autocontrast( expectedImage, 2 )
- actualImage = ImageOps.autocontrast( actualImage, 2 )
+ expectedImage = image_util.autocontrast( expectedImage, 2 )
+ actualImage = image_util.autocontrast( actualImage, 2 )
# compare the resulting image histogram functions
- h1 = expectedImage.histogram()
- h2 = actualImage.histogram()
- rms = math.sqrt( reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2)) / len(h1) )
+ rms = 0
+ bins = np.arange(257)
+ for i in xrange(0, 3):
+ h1p = expectedImage[:,:,i]
+ h2p = actualImage[:,:,i]
+
+ h1h = np.histogram(h1p, bins=bins)[0]
+ h2h = np.histogram(h2p, bins=bins)[0]
+
+ rms += np.sum(np.power((h1h-h2h), 2))
+ rms = np.sqrt(rms / (256 * 3))
diff_image = os.path.join(os.path.dirname(actual),
'failed-diff-'+os.path.basename(actual))
@@ -266,17 +268,28 @@ def compare_images( expected, actual, tol, in_decorator=False ):
return msg
def save_diff_image( expected, actual, output ):
- from PIL import Image
- expectedImage = Image.open( expected ).convert("RGB")
- actualImage = Image.open( actual ).convert("RGB")
+ expectedImage = _png.read_png( expected )
+ actualImage = _png.read_png( actual )
actualImage, expectedImage = crop_to_same(actual, actualImage, expected, expectedImage)
expectedImage = np.array(expectedImage).astype(np.float)
actualImage = np.array(actualImage).astype(np.float)
assert expectedImage.ndim==actualImage.ndim
assert expectedImage.shape==actualImage.shape
absDiffImage = abs(expectedImage-actualImage)
+
# expand differences in luminance domain
- absDiffImage *= 10
- save_image_np = np.clip(absDiffImage,0,255).astype(np.uint8)
- save_image = Image.fromarray(save_image_np)
- save_image.save(output)
+ absDiffImage *= 255 * 10
+ save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8)
+ height, width, depth = save_image_np.shape
+
+ # The PDF renderer doesn't produce an alpha channel, but the
+ # matplotlib PNG writer requires one, so expand the array
+ if depth == 3:
+ with_alpha = np.empty((height, width, 4), dtype=np.uint8)
+ with_alpha[:,:,0:3] = save_image_np
+ save_image_np = with_alpha
+
+ # Hard-code the alpha channel to fully solid
+ save_image_np[:,:,3] = 255
+
+ _png.write_png(save_image_np.tostring(), width, height, output)
diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py
index 54fc958c79a6..c21e6f2210cb 100644
--- a/lib/matplotlib/testing/decorators.py
+++ b/lib/matplotlib/testing/decorators.py
@@ -1,6 +1,7 @@
+from __future__ import print_function
from matplotlib.testing.noseclasses import KnownFailureTest, \
KnownFailureDidNotFailTest, ImageComparisonFailure
-import os, sys, shutil, new
+import os, sys, shutil
import nose
import matplotlib
import matplotlib.tests
@@ -33,7 +34,7 @@ def failer(*args, **kwargs):
try:
# Always run the test (to generate images).
result = f(*args, **kwargs)
- except Exception, err:
+ except Exception as err:
if fail_condition:
if known_exception_class is not None:
if not isinstance(err,known_exception_class):
@@ -49,7 +50,7 @@ def failer(*args, **kwargs):
return nose.tools.make_decorator(f)(failer)
return known_fail_decorator
-class CleanupTest:
+class CleanupTest(object):
@classmethod
def setup_class(cls):
cls.original_units_registry = matplotlib.units.registry.copy()
@@ -71,7 +72,7 @@ def cleanup(func):
name = func.__name__
func = staticmethod(func)
func.__get__(1).__name__ = '_private'
- new_class = new.classobj(
+ new_class = type(
name,
(CleanupTest,),
{'_func': func})
@@ -163,8 +164,8 @@ def compare_images_decorator(func):
# of output file. The only way to achieve this with nose
# appears to be to create a test class with "setup_class" and
# "teardown_class" methods. Creating a class instance doesn't
- # work, so we use new.classobj to actually create a class and
- # fill it with the appropriate methods.
+ # work, so we use type() to actually create a class and fill
+ # it with the appropriate methods.
name = func.__name__
# For nose 1.0, we need to rename the test function to
# something without the word "test", or it will be run as
@@ -172,7 +173,7 @@ def compare_images_decorator(func):
# generator.
func = staticmethod(func)
func.__get__(1).__name__ = '_private'
- new_class = new.classobj(
+ new_class = type(
name,
(ImageComparisonTest,),
{'_func': func,
diff --git a/lib/matplotlib/testing/image_util.py b/lib/matplotlib/testing/image_util.py
new file mode 100644
index 000000000000..aebdf92b1d8c
--- /dev/null
+++ b/lib/matplotlib/testing/image_util.py
@@ -0,0 +1,99 @@
+# This module contains some functionality from the Python Imaging
+# Library, that has been ported to use Numpy arrays rather than PIL
+# Image objects.
+
+
+# The Python Imaging Library is
+
+# Copyright (c) 1997-2009 by Secret Labs AB
+# Copyright (c) 1995-2009 by Fredrik Lundh
+
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+
+# Permission to use, copy, modify, and distribute this software and its
+# associated documentation for any purpose and without fee is hereby
+# granted, provided that the above copyright notice appears in all
+# copies, and that both that copyright notice and this permission notice
+# appear in supporting documentation, and that the name of Secret Labs
+# AB or the author not be used in advertising or publicity pertaining to
+# distribution of the software without specific, written prior
+# permission.
+
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
+# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+# FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
+# ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+from __future__ import print_function
+import numpy as np
+
+# TODO: Vectorize this
+def autocontrast(image, cutoff=0):
+ """
+ Maximize image contrast, based on histogram. This completely
+ ignores the alpha channel.
+ """
+ assert image.dtype == np.uint8
+
+ output_image = np.empty((image.shape[0], image.shape[1], 3), np.uint8)
+
+ for i in xrange(0, 3):
+ plane = image[:,:,i]
+ output_plane = output_image[:,:,i]
+ h = np.histogram(plane, bins=256)[0]
+ if cutoff:
+ # cut off pixels from both ends of the histogram
+ # get number of pixels
+ n = 0
+ for ix in xrange(256):
+ n = n + h[ix]
+ # remove cutoff% pixels from the low end
+ cut = n * cutoff / 100
+ for lo in range(256):
+ if cut > h[lo]:
+ cut = cut - h[lo]
+ h[lo] = 0
+ else:
+ h[lo] = h[lo] - cut
+ cut = 0
+ if cut <= 0:
+ break
+ # remove cutoff% samples from the hi end
+ cut = n * cutoff / 100
+ for hi in xrange(255, -1, -1):
+ if cut > h[hi]:
+ cut = cut - h[hi]
+ h[hi] = 0
+ else:
+ h[hi] = h[hi] - cut
+ cut = 0
+ if cut <= 0:
+ break
+
+ # find lowest/highest samples after preprocessing
+ for lo in xrange(256):
+ if h[lo]:
+ break
+ for hi in xrange(255, -1, -1):
+ if h[hi]:
+ break
+
+ if hi <= lo:
+ output_plane[:,:] = plane
+ else:
+ scale = 255.0 / (hi - lo)
+ offset = -lo * scale
+ lut = np.arange(256, dtype=np.float)
+ lut *= scale
+ lut += offset
+ lut = lut.clip(0, 255)
+ lut = lut.astype(np.uint8)
+
+ output_plane[:,:] = lut[plane]
+
+ return output_image
diff --git a/lib/matplotlib/testing/jpl_units/Duration.py b/lib/matplotlib/testing/jpl_units/Duration.py
index cde977931382..dc2a44bd08f7 100644
--- a/lib/matplotlib/testing/jpl_units/Duration.py
+++ b/lib/matplotlib/testing/jpl_units/Duration.py
@@ -4,11 +4,13 @@
#
#===========================================================================
+
"""Duration module."""
#===========================================================================
# Place all imports after here.
#
+from __future__ import print_function
#
# Place all imports before here.
#===========================================================================
@@ -18,11 +20,11 @@ class Duration:
"""Class Duration in development.
"""
allowed = [ "ET", "UTC" ]
-
+
#-----------------------------------------------------------------------
def __init__( self, frame, seconds ):
"""Create a new Duration object.
-
+
= ERROR CONDITIONS
- If the input frame is not in the allowed list, an error is thrown.
@@ -47,12 +49,12 @@ def frame( self ):
def __abs__( self ):
"""Return the absolute value of the duration."""
return Duration( self._frame, abs( self._seconds ) )
-
+
#-----------------------------------------------------------------------
def __neg__( self ):
"""Return the negative value of this Duration."""
return Duration( self._frame, -self._seconds )
-
+
#-----------------------------------------------------------------------
def seconds( self ):
"""Return the number of seconds in the Duration."""
@@ -69,7 +71,7 @@ def __nonzero__( self ):
- Returns -1 if self < rhs, 0 if self == rhs, +1 if self > rhs.
"""
return self._seconds != 0
-
+
#-----------------------------------------------------------------------
def __cmp__( self, rhs ):
"""Compare two Durations.
@@ -85,7 +87,7 @@ def __cmp__( self, rhs ):
"""
self.checkSameFrame( rhs, "compare" )
return cmp( self._seconds, rhs._seconds )
-
+
#-----------------------------------------------------------------------
def __add__( self, rhs ):
"""Add two Durations.
@@ -104,10 +106,10 @@ def __add__( self, rhs ):
if isinstance( rhs, U.Epoch ):
return rhs + self
-
+
self.checkSameFrame( rhs, "add" )
return Duration( self._frame, self._seconds + rhs._seconds )
-
+
#-----------------------------------------------------------------------
def __sub__( self, rhs ):
"""Subtract two Durations.
@@ -123,7 +125,7 @@ def __sub__( self, rhs ):
"""
self.checkSameFrame( rhs, "sub" )
return Duration( self._frame, self._seconds - rhs._seconds )
-
+
#-----------------------------------------------------------------------
def __mul__( self, rhs ):
"""Scale a UnitDbl by a value.
@@ -135,7 +137,7 @@ def __mul__( self, rhs ):
- Returns the scaled Duration.
"""
return Duration( self._frame, self._seconds * float( rhs ) )
-
+
#-----------------------------------------------------------------------
def __rmul__( self, lhs ):
"""Scale a Duration by a value.
@@ -147,7 +149,7 @@ def __rmul__( self, lhs ):
- Returns the scaled Duration.
"""
return Duration( self._frame, self._seconds * float( lhs ) )
-
+
#-----------------------------------------------------------------------
def __div__( self, rhs ):
"""Divide a Duration by a value.
@@ -159,7 +161,7 @@ def __div__( self, rhs ):
- Returns the scaled Duration.
"""
return Duration( self._frame, self._seconds / float( rhs ) )
-
+
#-----------------------------------------------------------------------
def __rdiv__( self, rhs ):
"""Divide a Duration by a value.
@@ -171,17 +173,17 @@ def __rdiv__( self, rhs ):
- Returns the scaled Duration.
"""
return Duration( self._frame, float( rhs ) / self._seconds )
-
+
#-----------------------------------------------------------------------
def __str__( self ):
"""Print the Duration."""
return "%g %s" % ( self._seconds, self._frame )
-
+
#-----------------------------------------------------------------------
def __repr__( self ):
"""Print the Duration."""
return "Duration( '%s', %g )" % ( self._frame, self._seconds )
-
+
#-----------------------------------------------------------------------
def checkSameFrame( self, rhs, func ):
"""Check to see if frames are the same.
@@ -199,5 +201,5 @@ def checkSameFrame( self, rhs, func ):
"LHS: %s\n" \
"RHS: %s" % ( func, self._frame, rhs._frame )
raise ValueError( msg )
-
+
#===========================================================================
diff --git a/lib/matplotlib/testing/jpl_units/Epoch.py b/lib/matplotlib/testing/jpl_units/Epoch.py
index 93821c3e48ed..591a1709217a 100644
--- a/lib/matplotlib/testing/jpl_units/Epoch.py
+++ b/lib/matplotlib/testing/jpl_units/Epoch.py
@@ -4,11 +4,13 @@
#
#===========================================================================
+
"""Epoch module."""
#===========================================================================
# Place all imports after here.
#
+from __future__ import print_function
import math
import datetime as DT
from matplotlib.dates import date2num
@@ -40,8 +42,8 @@ def __init__( self, frame, sec=None, jd=None, daynum=None, dt=None ):
or using a matplotlib day number
# Epoch( 'ET', daynum=730119.5 )
-
-
+
+
= ERROR CONDITIONS
- If the input units are not in the allowed list, an error is thrown.
@@ -64,7 +66,7 @@ def __init__( self, frame, sec=None, jd=None, daynum=None, dt=None ):
"Sec = %s\nJD = %s\ndnum= %s\ndt = %s" \
% ( str( sec ), str( jd ), str( daynum ), str( dt ) )
raise ValueError( msg )
-
+
if frame not in self.allowed:
msg = "Input frame '%s' is not one of the supported frames of %s" \
% ( frame, str( self.allowed.keys() ) )
@@ -80,7 +82,7 @@ def __init__( self, frame, sec=None, jd=None, daynum=None, dt=None ):
jd = float( daynum ) + 1721425.5
self._jd = math.floor( jd )
self._seconds = ( jd - self._jd ) * 86400.0
-
+
else:
self._seconds = float( sec )
self._jd = float( jd )
@@ -110,13 +112,13 @@ def julianDate( self, frame ):
t = self.convert( frame )
return t._jd + t._seconds / 86400.0
-
+
#-----------------------------------------------------------------------
def secondsPast( self, frame, jd ):
t = self
if frame != self._frame:
t = self.convert( frame )
-
+
delta = t._jd - jd
return t._seconds + delta * 86400
@@ -138,7 +140,7 @@ def __cmp__( self, rhs ):
return cmp( t._jd, rhs._jd )
return cmp( t._seconds, rhs._seconds )
-
+
#-----------------------------------------------------------------------
def __add__( self, rhs ):
"""Add a duration to an Epoch.
@@ -156,7 +158,7 @@ def __add__( self, rhs ):
sec = t._seconds + rhs.seconds()
return Epoch( t._frame, sec, t._jd )
-
+
#-----------------------------------------------------------------------
def __sub__( self, rhs ):
"""Subtract two Epoch's or a Duration from an Epoch.
@@ -178,7 +180,7 @@ def __sub__( self, rhs ):
# Handle Epoch - Duration
if isinstance( rhs, U.Duration ):
return self + -rhs
-
+
t = self
if self._frame != rhs._frame:
t = self.convert( rhs._frame )
@@ -187,17 +189,17 @@ def __sub__( self, rhs ):
sec = t._seconds - rhs._seconds
return U.Duration( rhs._frame, days*86400 + sec )
-
+
#-----------------------------------------------------------------------
def __str__( self ):
"""Print the Epoch."""
return "%22.15e %s" % ( self.julianDate( self._frame ), self._frame )
-
+
#-----------------------------------------------------------------------
def __repr__( self ):
"""Print the Epoch."""
return str( self )
-
+
#-----------------------------------------------------------------------
def range( start, stop, step ):
"""Generate a range of Epoch objects.
@@ -205,12 +207,12 @@ def range( start, stop, step ):
Similar to the Python range() method. Returns the range [
start, stop ) at the requested step. Each element will be a
Epoch object.
-
+
= INPUT VARIABLES
- - start The starting value of the range.
- - stop The stop value of the range.
- - step Step to use.
-
+ - start The starting value of the range.
+ - stop The stop value of the range.
+ - step Step to use.
+
= RETURN VALUE
- Returns a list contianing the requested Epoch values.
"""
diff --git a/lib/matplotlib/testing/jpl_units/EpochConverter.py b/lib/matplotlib/testing/jpl_units/EpochConverter.py
index e46764ec53ab..ae0d8b600c64 100644
--- a/lib/matplotlib/testing/jpl_units/EpochConverter.py
+++ b/lib/matplotlib/testing/jpl_units/EpochConverter.py
@@ -4,11 +4,13 @@
#
#===========================================================================
+
"""EpochConverter module containing class EpochConverter."""
#===========================================================================
# Place all imports after here.
#
+from __future__ import print_function
import matplotlib.units as units
import matplotlib.dates as date_ticker
from matplotlib.cbook import iterable
diff --git a/lib/matplotlib/testing/jpl_units/StrConverter.py b/lib/matplotlib/testing/jpl_units/StrConverter.py
index d291cee8130f..74a16987f6f7 100644
--- a/lib/matplotlib/testing/jpl_units/StrConverter.py
+++ b/lib/matplotlib/testing/jpl_units/StrConverter.py
@@ -4,11 +4,13 @@
#
#===========================================================================
+
"""StrConverter module containing class StrConverter."""
#===========================================================================
# Place all imports after here.
#
+from __future__ import print_function
import matplotlib.units as units
from matplotlib.cbook import iterable
@@ -81,7 +83,7 @@ def convert( value, unit, axis ):
labels = [ l.get_text() for l in labels if l.get_text() ]
if ( not labels ):
- ticks = []
+ ticks = []
labels = []
diff --git a/lib/matplotlib/testing/jpl_units/UnitDbl.py b/lib/matplotlib/testing/jpl_units/UnitDbl.py
index b99355626df2..d94512946665 100644
--- a/lib/matplotlib/testing/jpl_units/UnitDbl.py
+++ b/lib/matplotlib/testing/jpl_units/UnitDbl.py
@@ -4,12 +4,13 @@
#
#===========================================================================
+
"""UnitDbl module."""
#===========================================================================
# Place all imports after here.
#
-
+from __future__ import print_function
#
# Place all imports before here.
#===========================================================================
diff --git a/lib/matplotlib/testing/jpl_units/UnitDblConverter.py b/lib/matplotlib/testing/jpl_units/UnitDblConverter.py
index 8d88f464cd7d..c76a5039a8d8 100644
--- a/lib/matplotlib/testing/jpl_units/UnitDblConverter.py
+++ b/lib/matplotlib/testing/jpl_units/UnitDblConverter.py
@@ -4,11 +4,13 @@
#
#===========================================================================
+
"""UnitDblConverter module containing class UnitDblConverter."""
#===========================================================================
# Place all imports after here.
#
+from __future__ import print_function
import numpy as np
import matplotlib.units as units
import matplotlib.ticker as ticker
diff --git a/lib/matplotlib/testing/jpl_units/UnitDblFormatter.py b/lib/matplotlib/testing/jpl_units/UnitDblFormatter.py
index b43d74b1d0cd..986a09fce4df 100644
--- a/lib/matplotlib/testing/jpl_units/UnitDblFormatter.py
+++ b/lib/matplotlib/testing/jpl_units/UnitDblFormatter.py
@@ -4,11 +4,13 @@
#
#===========================================================================
+
"""UnitDblFormatter module containing class UnitDblFormatter."""
#===========================================================================
# Place all imports after here.
#
+from __future__ import print_function
import matplotlib.ticker as ticker
#
# Place all imports before here.
diff --git a/lib/matplotlib/testing/jpl_units/__init__.py b/lib/matplotlib/testing/jpl_units/__init__.py
index 8d414e087cc8..71439a7ea56a 100644
--- a/lib/matplotlib/testing/jpl_units/__init__.py
+++ b/lib/matplotlib/testing/jpl_units/__init__.py
@@ -1,10 +1,11 @@
#=======================================================================
+
"""
This is a sample set of units for use with testing unit conversion
of matplotlib routines. These are used because they use very strict
enforcement of unitized data which will test the entire spectrum of how
unitized data might be used (it is not always meaningful to convert to
-a float without specific units given).
+a float without specific units given).
UnitDbl is essentially a unitized floating point number. It has a
minimal set of supported units (enough for testing purposes). All
@@ -30,6 +31,7 @@
"""
#=======================================================================
+from __future__ import print_function
from Duration import Duration
from Epoch import Epoch
from UnitDbl import UnitDbl
diff --git a/lib/matplotlib/testing/noseclasses.py b/lib/matplotlib/testing/noseclasses.py
index 255e04bc518c..0f649ab5f00d 100644
--- a/lib/matplotlib/testing/noseclasses.py
+++ b/lib/matplotlib/testing/noseclasses.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import os
from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin
diff --git a/lib/matplotlib/tests/__init__.py b/lib/matplotlib/tests/__init__.py
index 58fe6d10f81b..f2b102b7734c 100644
--- a/lib/matplotlib/tests/__init__.py
+++ b/lib/matplotlib/tests/__init__.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
from matplotlib import rcParams, rcdefaults, use
_multiprocess_can_split_ = True
diff --git a/lib/matplotlib/tests/baseline_images/test_image/imshow.pdf b/lib/matplotlib/tests/baseline_images/test_image/imshow.pdf
index b10c1f3cff8c..e37200aa6a70 100644
Binary files a/lib/matplotlib/tests/baseline_images/test_image/imshow.pdf and b/lib/matplotlib/tests/baseline_images/test_image/imshow.pdf differ
diff --git a/lib/matplotlib/tests/baseline_images/test_image/imshow.png b/lib/matplotlib/tests/baseline_images/test_image/imshow.png
index 18b7602bbd8a..6cce06fd5d0f 100644
Binary files a/lib/matplotlib/tests/baseline_images/test_image/imshow.png and b/lib/matplotlib/tests/baseline_images/test_image/imshow.png differ
diff --git a/lib/matplotlib/tests/baseline_images/test_image/imshow.svg b/lib/matplotlib/tests/baseline_images/test_image/imshow.svg
index db0d8798d594..c1456c0c3809 100644
--- a/lib/matplotlib/tests/baseline_images/test_image/imshow.svg
+++ b/lib/matplotlib/tests/baseline_images/test_image/imshow.svg
@@ -1,395 +1,64 @@
-
+
-
diff --git a/lib/matplotlib/tests/baseline_images/test_png/pngsuite.png b/lib/matplotlib/tests/baseline_images/test_png/pngsuite.png
index 5c3dced973c7..4ed2d26db561 100644
Binary files a/lib/matplotlib/tests/baseline_images/test_png/pngsuite.png and b/lib/matplotlib/tests/baseline_images/test_png/pngsuite.png differ
diff --git a/lib/matplotlib/tests/baseline_images/test_tightlayout/tight_layout5.svg b/lib/matplotlib/tests/baseline_images/test_tightlayout/tight_layout5.svg
index bd31e9d63232..57560eed43e0 100644
--- a/lib/matplotlib/tests/baseline_images/test_tightlayout/tight_layout5.svg
+++ b/lib/matplotlib/tests/baseline_images/test_tightlayout/tight_layout5.svg
@@ -28,46 +28,9 @@ L91.3897 12.96
z
" style="fill:#ffffff;"/>
-
-
-
-
-
-
+
@@ -75,46 +38,46 @@ FgAksQAgiQUASSwASGIBQBILAJJYAJDEAoAkFgCk/wA701etNCsnUQAAAABJRU5ErkJggg==
+L0 -4" id="m3b2efec686"/>
-
+
+L0 4" id="m40327e05a4"/>
-
+
+M31.7812 66.4062
+Q24.1719 66.4062 20.3281 58.9062
+Q16.5 51.4219 16.5 36.375
+Q16.5 21.3906 20.3281 13.8906
+Q24.1719 6.39062 31.7812 6.39062
+Q39.4531 6.39062 43.2812 13.8906
+Q47.125 21.3906 47.125 36.375
+Q47.125 51.4219 43.2812 58.9062
+Q39.4531 66.4062 31.7812 66.4062
+M31.7812 74.2188
+Q44.0469 74.2188 50.5156 64.5156
+Q56.9844 54.8281 56.9844 36.375
+Q56.9844 17.9688 50.5156 8.26562
+Q44.0469 -1.42188 31.7812 -1.42188
+Q19.5312 -1.42188 13.0625 8.26562
+Q6.59375 17.9688 6.59375 36.375
+Q6.59375 54.8281 13.0625 64.5156
+Q19.5312 74.2188 31.7812 74.2188" id="BitstreamVeraSans-Roman-30"/>
-
+
@@ -124,50 +87,50 @@ Q19.5312 -74.2188 31.7812 -74.2188" id="BitstreamVeraSans-Roman-30"/>
+L0 -4" id="m3b2efec686"/>
-
+
+L0 4" id="m40327e05a4"/>
-
+
+L7.32812 8.29688
+Q12.9375 14.1094 22.625 23.8906
+Q32.3281 33.6875 34.8125 36.5312
+Q39.5469 41.8438 41.4219 45.5312
+Q43.3125 49.2188 43.3125 52.7812
+Q43.3125 58.5938 39.2344 62.25
+Q35.1562 65.9219 28.6094 65.9219
+Q23.9688 65.9219 18.8125 64.3125
+Q13.6719 62.7031 7.8125 59.4219
+L7.8125 69.3906
+Q13.7656 71.7812 18.9375 73
+Q24.125 74.2188 28.4219 74.2188
+Q39.75 74.2188 46.4844 68.5469
+Q53.2188 62.8906 53.2188 53.4219
+Q53.2188 48.9219 51.5312 44.8906
+Q49.8594 40.875 45.4062 35.4062
+Q44.1875 33.9844 37.6406 27.2188
+Q31.1094 20.4531 19.1875 8.29688" id="BitstreamVeraSans-Roman-32"/>
-
+
@@ -177,46 +140,46 @@ Q31.1094 -20.4531 19.1875 -8.29688" id="BitstreamVeraSans-Roman-32"/>
+L0 -4" id="m3b2efec686"/>
-
+
+L0 4" id="m40327e05a4"/>
-
+
-
+
@@ -226,55 +189,55 @@ z
+L0 -4" id="m3b2efec686"/>
-
+
+L0 4" id="m40327e05a4"/>
-
+
+M33.0156 40.375
+Q26.375 40.375 22.4844 35.8281
+Q18.6094 31.2969 18.6094 23.3906
+Q18.6094 15.5312 22.4844 10.9531
+Q26.375 6.39062 33.0156 6.39062
+Q39.6562 6.39062 43.5312 10.9531
+Q47.4062 15.5312 47.4062 23.3906
+Q47.4062 31.2969 43.5312 35.8281
+Q39.6562 40.375 33.0156 40.375
+M52.5938 71.2969
+L52.5938 62.3125
+Q48.875 64.0625 45.0938 64.9844
+Q41.3125 65.9219 37.5938 65.9219
+Q27.8281 65.9219 22.6719 59.3281
+Q17.5312 52.7344 16.7969 39.4062
+Q19.6719 43.6562 24.0156 45.9219
+Q28.375 48.1875 33.5938 48.1875
+Q44.5781 48.1875 50.9531 41.5156
+Q57.3281 34.8594 57.3281 23.3906
+Q57.3281 12.1562 50.6875 5.35938
+Q44.0469 -1.42188 33.0156 -1.42188
+Q20.3594 -1.42188 13.6719 8.26562
+Q6.98438 17.9688 6.98438 36.375
+Q6.98438 53.6562 15.1875 63.9375
+Q23.3906 74.2188 37.2031 74.2188
+Q40.9219 74.2188 44.7031 73.4844
+Q48.4844 72.75 52.5938 71.2969" id="BitstreamVeraSans-Roman-36"/>
-
+
@@ -284,63 +247,63 @@ Q48.4844 -72.75 52.5938 -71.2969" id="BitstreamVeraSans-Roman-36"/>
+L0 -4" id="m3b2efec686"/>
-
+
+L0 4" id="m40327e05a4"/>
-
+
+M31.7812 34.625
+Q24.75 34.625 20.7188 30.8594
+Q16.7031 27.0938 16.7031 20.5156
+Q16.7031 13.9219 20.7188 10.1562
+Q24.75 6.39062 31.7812 6.39062
+Q38.8125 6.39062 42.8594 10.1719
+Q46.9219 13.9688 46.9219 20.5156
+Q46.9219 27.0938 42.8906 30.8594
+Q38.875 34.625 31.7812 34.625
+M21.9219 38.8125
+Q15.5781 40.375 12.0312 44.7188
+Q8.5 49.0781 8.5 55.3281
+Q8.5 64.0625 14.7188 69.1406
+Q20.9531 74.2188 31.7812 74.2188
+Q42.6719 74.2188 48.875 69.1406
+Q55.0781 64.0625 55.0781 55.3281
+Q55.0781 49.0781 51.5312 44.7188
+Q48 40.375 41.7031 38.8125
+Q48.8281 37.1562 52.7969 32.3125
+Q56.7812 27.4844 56.7812 20.5156
+Q56.7812 9.90625 50.3125 4.23438
+Q43.8438 -1.42188 31.7812 -1.42188
+Q19.7344 -1.42188 13.25 4.23438
+Q6.78125 9.90625 6.78125 20.5156
+Q6.78125 27.4844 10.7812 32.3125
+Q14.7969 37.1562 21.9219 38.8125
+M18.3125 54.3906
+Q18.3125 48.7344 21.8438 45.5625
+Q25.3906 42.3906 31.7812 42.3906
+Q38.1406 42.3906 41.7188 45.5625
+Q45.3125 48.7344 45.3125 54.3906
+Q45.3125 60.0625 41.7188 63.2344
+Q38.1406 66.4062 31.7812 66.4062
+Q25.3906 66.4062 21.8438 63.2344
+Q18.3125 60.0625 18.3125 54.3906" id="BitstreamVeraSans-Roman-38"/>
-
+
@@ -352,25 +315,25 @@ Q18.3125 -60.0625 18.3125 -54.3906" id="BitstreamVeraSans-Roman-38"/>
+L4 0" id="mb2dea9eb6c"/>
-
+
+L-4 0" id="m845dcb4779"/>
-
+
-
+
@@ -380,25 +343,25 @@ L-4 0" id="m40a72f9137"/>
+L4 0" id="mb2dea9eb6c"/>
-
+
+L-4 0" id="m845dcb4779"/>
-
+
-
+
@@ -408,25 +371,25 @@ L-4 0" id="m40a72f9137"/>
+L4 0" id="mb2dea9eb6c"/>
-
+
+L-4 0" id="m845dcb4779"/>
-
+
-
+
@@ -436,25 +399,25 @@ L-4 0" id="m40a72f9137"/>
+L4 0" id="mb2dea9eb6c"/>
-
+
+L-4 0" id="m845dcb4779"/>
-
+
-
+
@@ -464,25 +427,25 @@ L-4 0" id="m40a72f9137"/>
+L4 0" id="mb2dea9eb6c"/>
-
+
+L-4 0" id="m845dcb4779"/>
-
+
-
+
@@ -510,4 +473,9 @@ L91.3897 12.96" style="fill:none;stroke:#000000;"/>
+
+
+
+
+
diff --git a/lib/matplotlib/tests/test_agg.py b/lib/matplotlib/tests/test_agg.py
index 4d971e117e15..7caf5c5fc622 100644
--- a/lib/matplotlib/tests/test_agg.py
+++ b/lib/matplotlib/tests/test_agg.py
@@ -1,9 +1,11 @@
+from __future__ import print_function
+
import os
def report_memory(i):
pid = os.getpid()
a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
- print i, ' ', a2[1],
+ print(i, ' ', a2[1], end=' ')
return int(a2[1].split()[0])
# This test is disabled -- it uses old API. -ADS 2009-09-07
diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py
index b028d6144dcf..11a6bd9a0691 100644
--- a/lib/matplotlib/tests/test_axes.py
+++ b/lib/matplotlib/tests/test_axes.py
@@ -319,7 +319,7 @@ def test_polar_theta_position():
ax.plot(theta, r)
ax.set_theta_zero_location("NW")
ax.set_theta_direction('clockwise')
-
+
@image_comparison(baseline_images=['axvspan_epoch'])
def test_axvspan_epoch():
from datetime import datetime
@@ -389,8 +389,8 @@ def test_imshow():
#Create a NxN image
N=100
(x,y) = np.indices((N,N))
- x -= N/2
- y -= N/2
+ x -= N//2
+ y -= N//2
r = np.sqrt(x**2+y**2-x*y)
#Create a contour plot at N/4 and extract both the clip path and transform
@@ -406,8 +406,8 @@ def test_imshow_clip():
#Create a NxN image
N=100
(x,y) = np.indices((N,N))
- x -= N/2
- y -= N/2
+ x -= N//2
+ y -= N//2
r = np.sqrt(x**2+y**2-x*y)
#Create a contour plot at N/4 and extract both the clip path and transform
@@ -508,7 +508,7 @@ def test_symlog2():
ax.set_xscale('symlog', linthreshx=0.01)
ax.grid(True)
ax.set_ylim(-0.1, 0.1)
-
+
@image_comparison(baseline_images=['pcolormesh'], tol=0.02)
def test_pcolormesh():
n = 12
@@ -542,7 +542,7 @@ def test_pcolormesh():
ax.set_title('gouraud')
ax.set_xticks([])
ax.set_yticks([])
-
+
@image_comparison(baseline_images=['canonical'])
def test_canonical():
@@ -625,7 +625,7 @@ def test_markevery_line():
ax.plot(x, y, '-+', markevery=(5, 20), label='mark every 5 starting at 10')
ax.legend()
-
+
if __name__=='__main__':
import nose
nose.runmodule(argv=['-s','--with-doctest'], exit=False)
diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py
index ba0a3ae76ec8..40016e8ea30e 100644
--- a/lib/matplotlib/tests/test_backend_svg.py
+++ b/lib/matplotlib/tests/test_backend_svg.py
@@ -1,6 +1,8 @@
+from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
-import cStringIO as StringIO
+import sys
+from io import BytesIO
import xml.parsers.expat
from matplotlib.testing.decorators import knownfailureif, cleanup
@@ -19,8 +21,8 @@ def test_visibility():
for artist in b:
artist.set_visible(False)
- fd = StringIO.StringIO()
- fig.savefig(fd, format='svg')
+ fd = BytesIO()
+ fig.savefig(fd,format='svg')
fd.seek(0)
buf = fd.read()
diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py
index 26338c1094c4..a77ccc87ab3e 100644
--- a/lib/matplotlib/tests/test_basic.py
+++ b/lib/matplotlib/tests/test_basic.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
from nose.tools import assert_equal
from matplotlib.testing.decorators import knownfailureif
import sys
@@ -20,12 +21,17 @@ def test_override_builtins():
'sum'
])
+ if sys.version_info[0] >= 3:
+ builtins = sys.modules['builtins']
+ else:
+ builtins = sys.modules['__builtin__']
+
overridden = False
for key in globals().keys():
- if key in dir(sys.modules["__builtin__"]):
- if (globals()[key] != getattr(sys.modules["__builtin__"], key) and
+ if key in dir(builtins):
+ if (globals()[key] != getattr(builtins, key) and
key not in ok_to_override):
- print "'%s' was overridden in globals()." % key
+ print("'%s' was overridden in globals()." % key)
overridden = True
assert not overridden
diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py
index a49e5c7a41e1..734fdbc4ee7f 100644
--- a/lib/matplotlib/tests/test_cbook.py
+++ b/lib/matplotlib/tests/test_cbook.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import numpy as np
from numpy.testing.utils import assert_array_equal
import matplotlib.cbook as cbook
diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py
index f1ca8295c13a..24d9a98331ea 100644
--- a/lib/matplotlib/tests/test_dates.py
+++ b/lib/matplotlib/tests/test_dates.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import datetime
import numpy as np
from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup
diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py
index 2c9db8a23e17..87aa2cb81146 100644
--- a/lib/matplotlib/tests/test_image.py
+++ b/lib/matplotlib/tests/test_image.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import numpy as np
from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup
@@ -6,7 +7,7 @@
from nose.tools import assert_raises
from numpy.testing import assert_array_equal
-import cStringIO
+import io
import os
@image_comparison(baseline_images=['image_interps'])
@@ -70,7 +71,7 @@ def test_image_python_io():
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
- buffer = cStringIO.StringIO()
+ buffer = io.BytesIO()
fig.savefig(buffer)
buffer.seek(0)
plt.imread(buffer)
@@ -96,10 +97,10 @@ def test_imsave():
random.seed(1)
data = random.rand(256, 128)
- buff_dpi1 = cStringIO.StringIO()
+ buff_dpi1 = io.BytesIO()
plt.imsave(buff_dpi1, data, dpi=1)
- buff_dpi100 = cStringIO.StringIO()
+ buff_dpi100 = io.BytesIO()
plt.imsave(buff_dpi100, data, dpi=100)
buff_dpi1.seek(0)
@@ -135,6 +136,8 @@ def test_imshow():
ax.imshow(arr, interpolation="bilinear", extent=(1,2,1,2))
ax.set_xlim(0,3)
ax.set_ylim(0,3)
+ ax.set_xticks([])
+ ax.set_yticks([])
if __name__=='__main__':
import nose
diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py
index 63689cd27157..ed370e26d3ea 100644
--- a/lib/matplotlib/tests/test_mathtext.py
+++ b/lib/matplotlib/tests/test_mathtext.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import numpy as np
import matplotlib
from matplotlib.testing.decorators import image_comparison, knownfailureif
@@ -200,7 +201,7 @@ def test_mathtext_exceptions():
parser.parse(math)
except ValueError as e:
exc = str(e).split('\n')
- print e
+ print(e)
assert exc[3].startswith(msg)
else:
assert False, "Expected '%s', but didn't get it" % msg
diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py
index c985d4cb3b97..8e292a229f75 100644
--- a/lib/matplotlib/tests/test_mlab.py
+++ b/lib/matplotlib/tests/test_mlab.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import numpy as np
import matplotlib.mlab as mlab
import tempfile
@@ -13,10 +14,12 @@ def test_colinear_pca():
def test_recarray_csv_roundtrip():
expected = np.recarray((99,),
[('x',np.float),('y',np.float),('t',np.float)])
+ # initialising all values: uninitialised memory sometimes produces floats
+ # that do not round-trip to string and back.
expected['x'][:] = np.linspace(-1e9, -1, 99)
expected['y'][:] = np.linspace(1, 1e9, 99)
expected['t'][:] = np.linspace(0, 0.01, 99)
- fd = tempfile.TemporaryFile(suffix='csv')
+ fd = tempfile.TemporaryFile(suffix='csv', mode="w+")
mlab.rec2csv(expected,fd)
fd.seek(0)
actual = mlab.csv2rec(fd)
diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py
index 4a02446a0196..84b6c14aba75 100644
--- a/lib/matplotlib/tests/test_simplification.py
+++ b/lib/matplotlib/tests/test_simplification.py
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
import numpy as np
import matplotlib
from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup
@@ -8,7 +10,7 @@
from matplotlib import patches, path, transforms
from nose.tools import raises
-import cStringIO
+import io
nan = np.nan
Path = path.Path
@@ -69,8 +71,6 @@ def test_noise():
path = transform.transform_path(path)
simplified = list(path.iter_segments(simplify=(800, 600)))
- print len(simplified)
-
assert len(simplified) == 3884
@cleanup
@@ -89,8 +89,6 @@ def test_sine_plus_noise():
path = transform.transform_path(path)
simplified = list(path.iter_segments(simplify=(800, 600)))
- print len(simplified)
-
assert len(simplified) == 876
@image_comparison(baseline_images=['simplify_curve'])
@@ -130,14 +128,12 @@ def test_fft_peaks():
path = transform.transform_path(path)
simplified = list(path.iter_segments(simplify=(800, 600)))
- print len(simplified)
-
assert len(simplified) == 20
@cleanup
def test_start_with_moveto():
# Should be entirely clipped away to a single MOVETO
- data = """
+ data = b"""
ZwAAAAku+v9UAQAA+Tj6/z8CAADpQ/r/KAMAANlO+v8QBAAAyVn6//UEAAC6ZPr/2gUAAKpv+v+8
BgAAm3r6/50HAACLhfr/ewgAAHyQ+v9ZCQAAbZv6/zQKAABepvr/DgsAAE+x+v/lCwAAQLz6/7wM
AAAxx/r/kA0AACPS+v9jDgAAFN36/zQPAAAF6Pr/AxAAAPfy+v/QEAAA6f36/5wRAADbCPv/ZhIA
@@ -159,7 +155,15 @@ def test_start_with_moveto():
AABHqP//ej8AAD6z//+FPwAANb7//48/AAAsyf//lz8AACPU//+ePwAAGt///6M/AAAR6v//pj8A
AAj1//+nPwAA/////w=="""
- verts = np.fromstring(data.decode('base64'), dtype='> sys.stderr, """\
+ print("""\
WARNING: found a TeX cache dir in the deprecated location "%s".
- Moving it to the new default location "%s"."""%(oldcache, texcache)
+ Moving it to the new default location "%s"."""%(oldcache, texcache), file=sys.stderr)
shutil.move(oldcache, texcache)
if not os.path.exists(texcache):
os.mkdir(texcache)
@@ -148,11 +151,11 @@ def __init__(self):
setattr(self, font_family_attr,
self.font_info[font.lower()])
if DEBUG:
- print 'family: %s, font: %s, info: %s'%(font_family,
- font, self.font_info[font.lower()])
+ print('family: %s, font: %s, info: %s'%(font_family,
+ font, self.font_info[font.lower()]))
break
else:
- if DEBUG: print '$s font is not compatible with usetex'
+ if DEBUG: print('$s font is not compatible with usetex')
else:
mpl.verbose.report('No LaTeX-compatible font found for the %s font family in rcParams. Using default.' % ff, 'helpful')
setattr(self, font_family_attr, self.font_info[font_family])
@@ -186,16 +189,16 @@ def get_font_config(self):
changed = [par for par in self._rc_cache_keys if rcParams[par] != \
self._rc_cache[par]]
if changed:
- if DEBUG: print 'DEBUG following keys changed:', changed
+ if DEBUG: print('DEBUG following keys changed:', changed)
for k in changed:
if DEBUG:
- print 'DEBUG %-20s: %-10s -> %-10s' % \
- (k, self._rc_cache[k], rcParams[k])
+ print('DEBUG %-20s: %-10s -> %-10s' % \
+ (k, self._rc_cache[k], rcParams[k]))
# deepcopy may not be necessary, but feels more future-proof
self._rc_cache[k] = copy.deepcopy(rcParams[k])
- if DEBUG: print 'DEBUG RE-INIT\nold fontconfig:', self._fontconfig
+ if DEBUG: print('DEBUG RE-INIT\nold fontconfig:', self._fontconfig)
self.__init__()
- if DEBUG: print 'DEBUG fontconfig:', self._fontconfig
+ if DEBUG: print('DEBUG fontconfig:', self._fontconfig)
return self._fontconfig
def get_font_preamble(self):
@@ -228,7 +231,6 @@ def make_tex(self, tex, fontsize):
"""
basefile = self.get_basefile(tex, fontsize)
texfile = '%s.tex'%basefile
- fh = file(texfile, 'w')
custom_preamble = self.get_custom_preamble()
fontcmd = {'sans-serif' : r'{\sffamily %s}',
'monospace' : r'{\ttfamily %s}'}.get(self.font_family,
@@ -236,7 +238,7 @@ def make_tex(self, tex, fontsize):
tex = fontcmd % tex
if rcParams['text.latex.unicode']:
- unicode_preamble = """\usepackage{ucs}
+ unicode_preamble = r"""\usepackage{ucs}
\usepackage[utf8x]{inputenc}"""
else:
unicode_preamble = ''
@@ -252,18 +254,17 @@ def make_tex(self, tex, fontsize):
\end{document}
""" % (self._font_preamble, unicode_preamble, custom_preamble,
fontsize, fontsize*1.25, tex)
- if rcParams['text.latex.unicode']:
- fh.write(s.encode('utf8'))
- else:
- try:
- fh.write(s)
- except UnicodeEncodeError, err:
- mpl.verbose.report("You are using unicode and latex, but have "
- "not enabled the matplotlib 'text.latex.unicode' "
- "rcParam.", 'helpful')
- raise
-
- fh.close()
+ with open(texfile, 'wb') as fh:
+ if rcParams['text.latex.unicode']:
+ fh.write(s.encode('utf8'))
+ else:
+ try:
+ fh.write(s.encode('ascii'))
+ except UnicodeEncodeError as err:
+ mpl.verbose.report("You are using unicode and latex, but have "
+ "not enabled the matplotlib 'text.latex.unicode' "
+ "rcParam.", 'helpful')
+ raise
return texfile
@@ -280,7 +281,6 @@ def make_tex_preview(self, tex, fontsize):
"""
basefile = self.get_basefile(tex, fontsize)
texfile = '%s.tex'%basefile
- fh = file(texfile, 'w')
custom_preamble = self.get_custom_preamble()
fontcmd = {'sans-serif' : r'{\sffamily %s}',
'monospace' : r'{\ttfamily %s}'}.get(self.font_family,
@@ -288,7 +288,7 @@ def make_tex_preview(self, tex, fontsize):
tex = fontcmd % tex
if rcParams['text.latex.unicode']:
- unicode_preamble = """\usepackage{ucs}
+ unicode_preamble = r"""\usepackage{ucs}
\usepackage[utf8x]{inputenc}"""
else:
unicode_preamble = ''
@@ -317,18 +317,17 @@ def make_tex_preview(self, tex, fontsize):
\end{document}
""" % (self._font_preamble, unicode_preamble, custom_preamble,
fontsize, fontsize*1.25, tex)
- if rcParams['text.latex.unicode']:
- fh.write(s.encode('utf8'))
- else:
- try:
- fh.write(s)
- except UnicodeEncodeError, err:
- mpl.verbose.report("You are using unicode and latex, but have "
- "not enabled the matplotlib 'text.latex.unicode' "
- "rcParam.", 'helpful')
- raise
-
- fh.close()
+ with open(texfile, 'wb') as fh:
+ if rcParams['text.latex.unicode']:
+ fh.write(s.encode('utf8'))
+ else:
+ try:
+ fh.write(s.encode('ascii'))
+ except UnicodeEncodeError as err:
+ mpl.verbose.report("You are using unicode and latex, but have "
+ "not enabled the matplotlib 'text.latex.unicode' "
+ "rcParam.", 'helpful')
+ raise
return texfile
@@ -356,9 +355,8 @@ def make_dvi(self, tex, fontsize):
mpl.verbose.report(command, 'debug')
exit_status = os.system(command)
try:
- fh = file(outfile)
- report = fh.read()
- fh.close()
+ with open(outfile) as fh:
+ report = fh.read()
except IOError:
report = 'No latex error report available.'
try:
@@ -402,9 +400,8 @@ def make_dvi_preview(self, tex, fontsize):
mpl.verbose.report(command, 'debug')
exit_status = os.system(command)
try:
- fh = file(outfile)
- report = fh.read()
- fh.close()
+ with open(outfile) as fh:
+ report = fh.read()
except IOError:
report = 'No latex error report available.'
@@ -416,7 +413,8 @@ def make_dvi_preview(self, tex, fontsize):
# find the box extent information in the latex output
# file and store them in ".baseline" file
m = TexManager._re_vbox.search(report)
- open(basefile+'.baseline',"w").write(" ".join(m.groups()))
+ with open(basefile+'.baseline',"w") as fh:
+ fh.write(" ".join(m.groups()))
for fname in glob.glob(basefile+'*'):
if fname.endswith('dvi'): pass
@@ -448,9 +446,8 @@ def make_png(self, tex, fontsize, dpi):
mpl.verbose.report(command, 'debug')
exit_status = os.system(command)
try:
- fh = file(outfile)
- report = fh.read()
- fh.close()
+ with open(outfile) as fh:
+ report = fh.read()
except IOError:
report = 'No dvipng error report available.'
if exit_status:
@@ -481,13 +478,13 @@ def make_ps(self, tex, fontsize):
os.path.split(dvifile)[-1], outfile))
mpl.verbose.report(command, 'debug')
exit_status = os.system(command)
- fh = file(outfile)
- if exit_status:
- raise RuntimeError('dvipng was not able to \
-process the flowing file:\n%s\nHere is the full report generated by dvipng: \
-\n\n'% dvifile + fh.read())
- else: mpl.verbose.report(fh.read(), 'debug')
- fh.close()
+ with open(outfile) as fh:
+ if exit_status:
+ raise RuntimeError('dvipng was not able to \
+ process the flowing file:\n%s\nHere is the full report generated by dvipng: \
+ \n\n'% dvifile + fh.read())
+ else:
+ mpl.verbose.report(fh.read(), 'debug')
os.remove(outfile)
return psfile
@@ -498,10 +495,10 @@ def get_ps_bbox(self, tex, fontsize):
rendering of the tex string
"""
psfile = self.make_ps(tex, fontsize)
- ps = file(psfile)
- for line in ps:
- if line.startswith('%%BoundingBox:'):
- return [int(val) for val in line.split()[1:]]
+ with open(psfile) as ps:
+ for line in ps:
+ if line.startswith('%%BoundingBox:'):
+ return [int(val) for val in line.split()[1:]]
raise RuntimeError('Could not parse %s'%psfile)
def get_grey(self, tex, fontsize=None, dpi=None):
@@ -597,7 +594,8 @@ def get_text_width_height_descent(self, tex, fontsize, renderer=None):
if DEBUG or not os.path.exists(baselinefile):
dvifile = self.make_dvi_preview(tex, fontsize)
- l = open(baselinefile).read().split()
+ with open(baselinefile) as fh:
+ l = fh.read().split()
height, depth, width = [float(l1)*dpi_fraction for l1 in l]
return width, height+depth, depth
@@ -605,7 +603,9 @@ def get_text_width_height_descent(self, tex, fontsize, renderer=None):
# use dviread. It sometimes returns a wrong descent.
dvifile = self.make_dvi(tex, fontsize)
dvi = dviread.Dvi(dvifile, 72*dpi_fraction)
- page = iter(dvi).next()
- dvi.close()
+ try:
+ page = next(iter(dvi))
+ finally:
+ dvi.close()
# A total height (including the descent) needs to be returned.
return page.width, page.height+page.descent, page.descent
diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py
index 73df0304b764..62c609eb3ffb 100644
--- a/lib/matplotlib/text.py
+++ b/lib/matplotlib/text.py
@@ -1,7 +1,7 @@
"""
Classes for including text in a figure.
"""
-from __future__ import division
+from __future__ import division, print_function
import math
import numpy as np
@@ -22,8 +22,6 @@
from matplotlib.artist import allow_rasterization
-import matplotlib.nxutils as nxutils
-
from matplotlib.path import Path
import matplotlib.font_manager as font_manager
from matplotlib.ft2font import FT2Font
@@ -212,11 +210,8 @@ def contains(self,mouseevent):
r = l+w
t = b+h
- xyverts = (l,b), (l, t), (r, t), (r, b)
x, y = mouseevent.x, mouseevent.y
- inside = nxutils.pnpoly(x, y, xyverts)
-
- return inside,{}
+ return x >= l and x <= r and y >= t and y <= b
def _get_xy_display(self):
'get the (possibly unit converted) transformed x, y in display coords'
@@ -1007,7 +1002,7 @@ def set_font_properties(self, fp):
self.set_fontproperties(fp)
docstring.interpd.update(Text = artist.kwdoc(Text))
-docstring.dedent_interpd(Text.__init__.im_func)
+docstring.dedent_interpd(Text.__init__)
class TextWithDash(Text):
@@ -1798,7 +1793,7 @@ def __init__(self, s, xy,
self.arrow = None
- if arrowprops and arrowprops.has_key("arrowstyle"):
+ if arrowprops and "arrowstyle" in arrowprops:
self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5))
self.arrow_patch = FancyArrowPatch((0, 0), (1,1),
@@ -1917,11 +1912,11 @@ def _update_position_xytext(self, renderer, xy_pixel):
# pick the x,y corner of the text bbox closest to point
# annotated
- dsu = [(abs(val-x0), val) for val in l, r, xc]
+ dsu = [(abs(val-x0), val) for val in (l, r, xc)]
dsu.sort()
_, x = dsu[0]
- dsu = [(abs(val-y0), val) for val in b, t, yc]
+ dsu = [(abs(val-y0), val) for val in (b, t, yc)]
dsu.sort()
_, y = dsu[0]
diff --git a/lib/matplotlib/textpath.py b/lib/matplotlib/textpath.py
index d27dff6a2b9a..68eb3fdcc289 100644
--- a/lib/matplotlib/textpath.py
+++ b/lib/matplotlib/textpath.py
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
+from __future__ import print_function
+
import urllib
from matplotlib.path import Path
import matplotlib.font_manager as font_manager
@@ -297,8 +299,10 @@ def get_glyphs_tex(self, prop, s, glyph_map=None,
else:
dvifile = texmanager.make_dvi(s, self.FONT_SCALE)
dvi = dviread.Dvi(dvifile, self.DPI)
- page = iter(dvi).next()
- dvi.close()
+ try:
+ page = next(iter(dvi))
+ finally:
+ dvi.close()
if glyph_map is None:
diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py
index c180e5dbe38d..db0fc8537024 100644
--- a/lib/matplotlib/ticker.py
+++ b/lib/matplotlib/ticker.py
@@ -123,8 +123,7 @@
more information and examples of using date locators and formatters.
"""
-
-from __future__ import division
+from __future__ import division, print_function
import decimal
import locale
import math
@@ -370,7 +369,7 @@ def set_useLocale(self, val):
self._useLocale = val
useLocale = property(fget=get_useLocale, fset=set_useLocale)
-
+
def fix_minus(self, s):
'use a unicode minus rather than hyphen'
if rcParams['text.usetex'] or not rcParams['axes.unicode_minus']: return s
@@ -545,7 +544,7 @@ def _formatSciNotation(self, s):
else:
s = ('%se%s%s' %(significand, sign, exponent)).rstrip('e')
return s
- except IndexError, msg:
+ except IndexError:
return s
@@ -1396,7 +1395,7 @@ def __call__(self):
#
# "simple" mode is when the range falls entirely within (-t,
# t) -- it should just display (vmin, 0, vmax)
-
+
has_a = has_b = has_c = False
if vmin < -t:
has_a = True
@@ -1446,11 +1445,11 @@ def get_log_range(lo, hi):
if has_b:
total_ticks += 1
stride = max(np.floor(float(total_ticks) / (self.numticks - 1)), 1)
-
+
decades = []
if has_a:
decades.extend(-1 * (b ** (np.arange(a_range[0], a_range[1], stride)[::-1])))
-
+
if has_b:
decades.append(0.0)
@@ -1469,7 +1468,7 @@ def get_log_range(lo, hi):
ticklocs.extend(subs * decade)
else:
ticklocs = decades
-
+
return self.raise_if_exceeds(np.array(ticklocs))
def view_limits(self, vmin, vmax):
diff --git a/lib/matplotlib/tight_bbox.py b/lib/matplotlib/tight_bbox.py
index 53d0606a4092..4b09b4a314a4 100644
--- a/lib/matplotlib/tight_bbox.py
+++ b/lib/matplotlib/tight_bbox.py
@@ -2,6 +2,7 @@
This module is to support *bbox_inches* option in savefig command.
"""
+from __future__ import print_function
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
@@ -109,7 +110,7 @@ def adjust_bbox_pdf(fig, bbox_inches):
def process_figure_for_rasterizing(figure,
bbox_inches_restore, mode):
-
+
"""
This need to be called when figure dpi changes during the drawing
(e.g., rasterizing). It recovers the bbox and re-adjust it with
diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py
index d76214f3eafc..5a7f9149d421 100644
--- a/lib/matplotlib/transforms.py
+++ b/lib/matplotlib/transforms.py
@@ -29,9 +29,11 @@
themselves.
"""
+from __future__ import print_function
import numpy as np
from numpy import ma
-from matplotlib._path import affine_transform
+from matplotlib._path import (affine_transform, count_bboxes_overlapping_bbox,
+ update_path_extents)
from numpy.linalg import inv
from weakref import WeakKeyDictionary
@@ -43,7 +45,6 @@
import cbook
from path import Path
-from _path import count_bboxes_overlapping_bbox, update_path_extents
DEBUG = False
if DEBUG:
@@ -121,7 +122,7 @@ def invalidate(self):
# Stop at subtrees that have already been invalidated
if root._invalid != value or root.pass_through:
root._invalid = self.INVALID
- stack.extend(root._parents.keys())
+ stack.extend(root._parents.iterkeys())
def set_children(self, *children):
"""
@@ -177,7 +178,7 @@ def recurse(root):
props['style'] = 'bold'
props['shape'] = 'box'
props['label'] = '"%s"' % label
- props = ' '.join(['%s=%s' % (key, val) for key, val in props.items()])
+ props = ' '.join(['%s=%s' % (key, val) for key, val in props.iteritems()])
fobj.write('%s [%s];\n' %
(hash(root), props))
@@ -185,7 +186,7 @@ def recurse(root):
if hasattr(root, '_children'):
for child in root._children:
name = '?'
- for key, val in root.__dict__.items():
+ for key, val in root.__dict__.iteritems():
if val is child:
name = key
break
@@ -1191,7 +1192,7 @@ def transform_angles(self, angles, pts, radians=False, pushoff=1e-5):
close to *pts*, to find the angle in the transformed system.
"""
# Must be 2D
- if self.input_dims <> 2 or self.output_dims <> 2:
+ if self.input_dims != 2 or self.output_dims != 2:
raise NotImplementedError('Only defined in 2D')
# pts must be array with 2 columns for x,y
@@ -2330,4 +2331,3 @@ def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'):
elif not units == 'inches':
raise ValueError('units must be dots, points, or inches')
return trans + ScaledTranslation(x, y, fig.dpi_scale_trans)
-
diff --git a/lib/matplotlib/tri/__init__.py b/lib/matplotlib/tri/__init__.py
index 1d216f65b595..f7fd7ca8d0f5 100644
--- a/lib/matplotlib/tri/__init__.py
+++ b/lib/matplotlib/tri/__init__.py
@@ -2,6 +2,7 @@
Unstructured triangular grid functions.
"""
+from __future__ import print_function
from triangulation import *
from tricontour import *
from tripcolor import *
diff --git a/lib/matplotlib/tri/_tri.cpp b/lib/matplotlib/tri/_tri.cpp
index 2c92d2c9dfdd..7d8358d1ac5e 100644
--- a/lib/matplotlib/tri/_tri.cpp
+++ b/lib/matplotlib/tri/_tri.cpp
@@ -980,19 +980,22 @@ XY TriContourGenerator::interp(int point1,
-
-#if defined(_MSC_VER)
-DL_EXPORT(void)
-#elif defined(__cplusplus)
-extern "C" void
+#if PY_MAJOR_VERSION >= 3
+PyMODINIT_FUNC
+PyInit__tri(void)
#else
-void
+PyMODINIT_FUNC
+init_tri(void)
#endif
-init_tri()
{
+ import_array();
+
static TriModule* triModule = NULL;
triModule = new TriModule();
- import_array();
+
+ #if PY_MAJOR_VERSION >= 3
+ return triModule->module().ptr();
+ #endif
}
TriModule::TriModule()
diff --git a/lib/matplotlib/tri/triangulation.py b/lib/matplotlib/tri/triangulation.py
index 9ba82ea2acb4..e99cd05235bc 100644
--- a/lib/matplotlib/tri/triangulation.py
+++ b/lib/matplotlib/tri/triangulation.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import matplotlib.delaunay as delaunay
import matplotlib._tri as _tri
import numpy as np
diff --git a/lib/matplotlib/tri/tricontour.py b/lib/matplotlib/tri/tricontour.py
index 2549c45704f8..a0403e725d41 100644
--- a/lib/matplotlib/tri/tricontour.py
+++ b/lib/matplotlib/tri/tricontour.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
from matplotlib.contour import ContourSet
from matplotlib.tri.triangulation import Triangulation
import matplotlib._tri as _tri
diff --git a/lib/matplotlib/tri/tripcolor.py b/lib/matplotlib/tri/tripcolor.py
index 2748cd0a4fc5..b3a6fdd50917 100644
--- a/lib/matplotlib/tri/tripcolor.py
+++ b/lib/matplotlib/tri/tripcolor.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
from matplotlib.collections import PolyCollection
from matplotlib.colors import Normalize
from matplotlib.tri.triangulation import Triangulation
diff --git a/lib/matplotlib/tri/triplot.py b/lib/matplotlib/tri/triplot.py
index cdd5cb3427df..3a852aa96074 100644
--- a/lib/matplotlib/tri/triplot.py
+++ b/lib/matplotlib/tri/triplot.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
from matplotlib.cbook import ls_mapper
from matplotlib.patches import PathPatch
from matplotlib.path import Path
diff --git a/lib/matplotlib/type1font.py b/lib/matplotlib/type1font.py
index 6fad8461c78b..521717ce6f20 100644
--- a/lib/matplotlib/type1font.py
+++ b/lib/matplotlib/type1font.py
@@ -22,8 +22,9 @@
v1.1, 1993. ISBN 0-201-57044-0.
"""
+from __future__ import print_function
import matplotlib.cbook as cbook
-import cStringIO
+import io
import itertools
import numpy as np
import re
@@ -52,13 +53,10 @@ def __init__(self, input):
if isinstance(input, tuple) and len(input) == 3:
self.parts = input
else:
- file = open(input, 'rb')
- try:
+ with open(input, 'rb') as file:
data = self._read(file)
- finally:
- file.close()
self.parts = self._split(data)
-
+
self._parse()
def _read(self, file):
@@ -72,9 +70,8 @@ def _read(self, file):
data = ''
while len(rawdata) > 0:
if not rawdata.startswith(chr(128)):
- raise RuntimeError, \
- 'Broken pfb file (expected byte 128, got %d)' % \
- ord(rawdata[0])
+ raise RuntimeError('Broken pfb file (expected byte 128, got %d)' % \
+ ord(rawdata[0]))
type = ord(rawdata[1])
if type in (1,2):
length, = struct.unpack('= 3:
+ import multiprocessing
+ from distutils import util
+ def refactor(x):
+ from lib2to3.refactor import RefactoringTool, get_fixers_from_package
+ class DistutilsRefactoringTool(RefactoringTool):
+ def ignore(self, msg, *args, **kw):
+ pass
+ log_error = log_message = log_debug = ignore
+ fixer_names = get_fixers_from_package('lib2to3.fixes')
+ r = DistutilsRefactoringTool(fixer_names, options=None)
+ r.refactor([x], write=True)
+
+ original_build_py = build_py
+ class build_py(original_build_py):
+ def run_2to3(self, files):
+ # We need to skip certain files that have already been
+ # converted to Python 3.x
+ filtered = [x for x in files if 'py3' not in x]
+ if sys.platform.startswith('win'):
+ # doing this in parallel on windows may crash your computer
+ [refactor(f) for f in filtered]
+ else:
+ p = multiprocessing.Pool()
+ p.map(refactor, filtered)
+
print_raw("pymods %s" % py_modules)
print_raw("packages %s" % packages)
distrib = setup(name="matplotlib",
@@ -270,5 +299,6 @@ def add_dateutil():
ext_modules = ext_modules,
package_dir = {'': 'lib'},
package_data = package_data,
+ cmdclass = {'build_py': build_py},
**additional_params
)
diff --git a/setupext.py b/setupext.py
index 9e032cab7d12..e063fab1ed60 100644
--- a/setupext.py
+++ b/setupext.py
@@ -107,7 +107,6 @@
BUILT_WINDOWING = False
BUILT_CONTOUR = False
BUILT_DELAUNAY = False
-BUILT_NXUTILS = False
BUILT_CONTOUR = False
BUILT_GDK = False
BUILT_PATH = False
@@ -138,6 +137,9 @@
('PY_ARRAY_UNIQUE_SYMBOL', 'MPL_ARRAY_API'),
('PYCXX_ISO_CPP_LIB', '1')]
+if sys.version_info[0] >= 3:
+ defines.append(('PYCXX_PYTHON_2TO3', '1'))
+
setup_cfg = os.environ.get('MPLSETUPCFG', 'setup.cfg')
# Based on the contents of setup.cfg, determine the build options
if os.path.exists(setup_cfg):
@@ -182,6 +184,12 @@
basedirlist = basedir[sys.platform]
print("basedirlist is: %s" % basedirlist)
+def make_extension(*args, **kwargs):
+ ext = Extension(*args, **kwargs)
+ for dir in basedirlist:
+ ext.include_dirs.append(os.path.join(dir, 'include'))
+ return ext
+
if options['display_status']:
def print_line(char='='):
print(char * 76)
@@ -335,7 +343,7 @@ def find_include_file(include_dirs, filename):
return False
def check_for_freetype():
- module = Extension('test', [])
+ module = make_extension('test', [])
add_base_flags(module)
if not get_pkgconfig(module, 'freetype2'):
basedirs = module.include_dirs[:] # copy the list to avoid inf loop!
@@ -351,7 +359,7 @@ def check_for_freetype():
return True
def check_for_libpng():
- module = Extension("test", [])
+ module = make_extension("test", [])
get_pkgconfig(module, 'libpng')
add_base_flags(module)
@@ -555,7 +563,7 @@ def check_for_numpy():
'numpy 1.1 or later is required; you have %s' %
numpy.__version__)
return False
- module = Extension('test', [])
+ module = make_extension('test', [])
add_numpy_flags(module)
add_base_flags(module)
@@ -635,7 +643,7 @@ def check_for_gtk():
gotit = True
if gotit:
- module = Extension('test', [])
+ module = make_extension('test', [])
add_pygtk_flags(module)
if not find_include_file(module.include_dirs, os.path.join("gtk", "gtk.h")):
explanation = (
@@ -740,7 +748,10 @@ def check_for_tk():
gotit = False
explanation = None
try:
- import Tkinter
+ if sys.version_info[0] < 3:
+ import Tkinter
+ else:
+ import tkinter as Tkinter
except ImportError:
explanation = 'TKAgg requires Tkinter'
except RuntimeError:
@@ -752,18 +763,18 @@ def check_for_tk():
gotit = True
if gotit:
- module = Extension('test', [])
+ module = make_extension('test', [])
try:
explanation = add_tk_flags(module)
- except RuntimeError:
- # This deals with the change in exception handling syntax in
- # python 3. If we only need to support >= 2.6, we can just use the
- # commented out lines below.
- exc_type,exc,tb = sys.exc_info()
- explanation = str(exc)
- gotit = False
-# except RuntimeError, e:
-# explanation = str(e)
+ # except RuntimeError:
+ # # This deals with the change in exception handling syntax in
+ # # python 3. If we only need to support >= 2.6, we can just use the
+ # # commented out lines below.
+ # exc_type,exc,tb = sys.exc_info()
+ # explanation = str(exc)
+ # gotit = False
+ except RuntimeError as e:
+ explanation = str(e)
else:
if not find_include_file(module.include_dirs, "tk.h"):
message = 'Tkinter present, but header files are not found. ' + \
@@ -810,7 +821,10 @@ def query_tcltk():
return TCL_TK_CACHE
# By this point, we already know that Tkinter imports correctly
- import Tkinter
+ if sys.version_info[0] < 3:
+ import Tkinter
+ else:
+ import tkinter as Tkinter
tcl_lib_dir = ''
tk_lib_dir = ''
# First try to open a Tk window (requires a running X server)
@@ -845,7 +859,14 @@ def query_tcltk():
return TCL_TK_CACHE
def parse_tcl_config(tcl_lib_dir, tk_lib_dir):
- import Tkinter
+ try:
+ if sys.version_info[0] < 3:
+ import Tkinter
+ else:
+ import tkinter as Tkinter
+ except ImportError:
+ return None
+
tcl_poss = [tcl_lib_dir,
os.path.normpath(os.path.join(tcl_lib_dir, '..')),
"/usr/lib/tcl"+str(Tkinter.TclVersion),
@@ -869,7 +890,7 @@ def get_var(file, varname):
executable="/bin/sh",
stdout=subprocess.PIPE)
result = p.communicate()[0]
- return result
+ return result.decode('ascii')
tcl_lib_dir = get_var(tcl_config, 'TCL_LIB_SPEC').split()[0][2:].strip()
tcl_inc_dir = get_var(tcl_config, 'TCL_INCLUDE_SPEC')[2:].strip()
@@ -935,7 +956,7 @@ def add_tk_flags(module):
message = None
if sys.platform == 'win32':
major, minor1, minor2, s, tmp = sys.version_info
- if major == 2 and minor1 in [6, 7]:
+ if (2, 6) <= (major, minor1) <= (3, 2):
module.include_dirs.extend(['win32_static/include/tcl85'])
module.libraries.extend(['tk85', 'tcl85'])
elif major == 2 and minor1 in [3, 4, 5]:
@@ -1048,7 +1069,7 @@ def build_windowing(ext_modules, packages):
windows better, .e.g. maintaining focus on win32"""
global BUILT_WINDOWING
if BUILT_WINDOWING: return # only build it if you you haven't already
- module = Extension('matplotlib._windowing',
+ module = make_extension('matplotlib._windowing',
['src/_windowing.cpp'],
)
add_windowing_flags(module)
@@ -1062,7 +1083,7 @@ def build_ft2font(ext_modules, packages):
deps.extend(glob.glob('CXX/*.cxx'))
deps.extend(glob.glob('CXX/*.c'))
- module = Extension('matplotlib.ft2font', deps,
+ module = make_extension('matplotlib.ft2font', deps,
define_macros=defines)
add_ft2font_flags(module)
ext_modules.append(module)
@@ -1076,7 +1097,7 @@ def build_ttconv(ext_modules, packages):
'ttconv/pprdrv_tt2.cpp',
'ttconv/ttutil.cpp']
- module = Extension('matplotlib.ttconv', deps,
+ module = make_extension('matplotlib.ttconv', deps,
define_macros=defines)
add_base_flags(module)
ext_modules.append(module)
@@ -1089,7 +1110,7 @@ def build_gtkagg(ext_modules, packages):
deps.extend(glob.glob('CXX/*.cxx'))
deps.extend(glob.glob('CXX/*.c'))
- module = Extension('matplotlib.backends._gtkagg',
+ module = make_extension('matplotlib.backends._gtkagg',
deps,
define_macros=defines
)
@@ -1112,7 +1133,7 @@ def build_tkagg(ext_modules, packages):
deps.extend(glob.glob('CXX/*.cxx'))
deps.extend(glob.glob('CXX/*.c'))
- module = Extension('matplotlib.backends._tkagg',
+ module = make_extension('matplotlib.backends._tkagg',
deps,
define_macros=defines
)
@@ -1135,7 +1156,7 @@ def build_macosx(ext_modules, packages):
'CXX/IndirectPythonInterface.cxx',
'src/agg_py_transforms.cpp',
'src/path_cleanup.cpp']
- module = Extension('matplotlib.backends._macosx',
+ module = make_extension('matplotlib.backends._macosx',
deps,
extra_link_args = ['-framework','Cocoa'],
define_macros=defines
@@ -1153,7 +1174,7 @@ def build_png(ext_modules, packages):
deps.extend(glob.glob('CXX/*.cxx'))
deps.extend(glob.glob('CXX/*.c'))
- module = Extension(
+ module = make_extension(
'matplotlib._png',
deps,
include_dirs=numpy_inc_dirs,
@@ -1185,7 +1206,7 @@ def build_agg(ext_modules, packages):
deps.extend(glob.glob('CXX/*.c'))
temp_copy('src/_backend_agg.cpp', 'src/backend_agg.cpp')
deps.append('src/backend_agg.cpp')
- module = Extension(
+ module = make_extension(
'matplotlib.backends._backend_agg',
deps,
include_dirs=numpy_inc_dirs,
@@ -1219,7 +1240,7 @@ def build_path(ext_modules, packages):
deps.extend(['src/agg_py_transforms.cpp',
'src/path_cleanup.cpp',
'src/path.cpp'])
- module = Extension(
+ module = make_extension(
'matplotlib._path',
deps,
include_dirs=numpy_inc_dirs,
@@ -1248,7 +1269,7 @@ def build_image(ext_modules, packages):
deps.extend(glob.glob('CXX/*.cxx'))
deps.extend(glob.glob('CXX/*.c'))
- module = Extension(
+ module = make_extension(
'matplotlib._image',
deps,
include_dirs=numpy_inc_dirs,
@@ -1271,7 +1292,7 @@ def build_delaunay(ext_modules, packages):
sourcefiles=["_delaunay.cpp", "VoronoiDiagramGenerator.cpp",
"delaunay_utils.cpp", "natneighbors.cpp"]
sourcefiles = [os.path.join('lib/matplotlib/delaunay',s) for s in sourcefiles]
- delaunay = Extension('matplotlib._delaunay',sourcefiles,
+ delaunay = make_extension('matplotlib._delaunay',sourcefiles,
include_dirs=numpy_inc_dirs,
define_macros=defines
)
@@ -1286,7 +1307,7 @@ def build_contour(ext_modules, packages):
global BUILT_CONTOUR
if BUILT_CONTOUR: return # only build it if you you haven't already
- module = Extension(
+ module = make_extension(
'matplotlib._cntr',
[ 'src/cntr.c'],
include_dirs=numpy_inc_dirs,
@@ -1299,28 +1320,12 @@ def build_contour(ext_modules, packages):
BUILT_CONTOUR = True
-def build_nxutils(ext_modules, packages):
- global BUILT_NXUTILS
- if BUILT_NXUTILS: return # only build it if you you haven't already
- module = Extension(
- 'matplotlib.nxutils',
- [ 'src/nxutils.c'],
- include_dirs=numpy_inc_dirs,
- define_macros=defines
- )
- add_numpy_flags(module)
- add_base_flags(module)
- ext_modules.append(module)
-
- BUILT_NXUTILS = True
-
-
def build_gdk(ext_modules, packages):
global BUILT_GDK
if BUILT_GDK: return # only build it if you you haven't already
temp_copy('src/_backend_gdk.c', 'src/backend_gdk.c')
- module = Extension(
+ module = make_extension(
'matplotlib.backends._backend_gdk',
['src/backend_gdk.c'],
libraries = [],
@@ -1344,7 +1349,7 @@ def build_tri(ext_modules, packages):
deps.extend(glob.glob('CXX/*.cxx'))
deps.extend(glob.glob('CXX/*.c'))
- module = Extension('matplotlib._tri', deps,
+ module = make_extension('matplotlib._tri', deps,
define_macros=defines)
add_numpy_flags(module)
add_base_flags(module)
diff --git a/src/_backend_agg.cpp b/src/_backend_agg.cpp
index f7a986fc2f95..fffd5c748484 100644
--- a/src/_backend_agg.cpp
+++ b/src/_backend_agg.cpp
@@ -102,7 +102,11 @@ Py::Object
BufferRegion::to_string(const Py::Tuple &args)
{
// owned=true to prevent memory leak
+ #if PY3K
+ return Py::Bytes(PyBytes_FromStringAndSize((const char*)data, height*stride), true);
+ #else
return Py::String(PyString_FromStringAndSize((const char*)data, height*stride), true);
+ #endif
}
@@ -152,12 +156,20 @@ BufferRegion::to_string_argb(const Py::Tuple &args)
unsigned char tmp;
size_t i, j;
- PyObject* str = PyString_FromStringAndSize(
- (const char*)data, height * stride);
+ #if PY3K
+ PyObject* str = PyBytes_FromStringAndSize((const char*)data, height * stride);
+ if (PyBytes_AsStringAndSize(str, (char**)&begin, &length))
+ {
+ throw Py::TypeError("Could not create memory for blit");
+ }
+ #else
+ PyObject* str = PyString_FromStringAndSize((const char*)data, height * stride);
if (PyString_AsStringAndSize(str, (char**)&begin, &length))
{
throw Py::TypeError("Could not create memory for blit");
}
+ #endif
+
pix = begin;
end = begin + (height * stride);
@@ -200,7 +212,7 @@ void
GCAgg::_set_antialiased(const Py::Object& gc)
{
_VERBOSE("GCAgg::antialiased");
- isaa = Py::Int(gc.getAttr("_antialiased"));
+ isaa = Py::Boolean(gc.getAttr("_antialiased"));
}
@@ -910,7 +922,8 @@ RendererAgg::draw_text_image(const Py::Tuple& args)
}
else
{
- FT2Image *image = static_cast(image_obj.ptr());
+ FT2Image* image = static_cast(
+ Py::getPythonExtensionBase(image_obj.ptr()));
if (!image->get_buffer())
{
throw Py::ValueError(
@@ -1521,7 +1534,7 @@ RendererAgg::_draw_path_collection_generic
if (check_snap)
{
- gc.isaa = bool(Py::Int(antialiaseds[i % Naa]));
+ gc.isaa = Py::Boolean(antialiaseds[i % Naa]);
transformed_path_t tpath(path, trans);
nan_removed_t nan_removed(tpath, true, has_curves);
@@ -1540,7 +1553,7 @@ RendererAgg::_draw_path_collection_generic
}
else
{
- gc.isaa = bool(Py::Int(antialiaseds[i % Naa]));
+ gc.isaa = Py::Boolean(antialiaseds[i % Naa]);
transformed_path_t tpath(path, trans);
nan_removed_t nan_removed(tpath, true, has_curves);
@@ -1993,6 +2006,12 @@ RendererAgg::write_rgba(const Py::Tuple& args)
FILE *fp = NULL;
bool close_file = false;
Py::Object py_fileobj = Py::Object(args[0]);
+
+ #if PY3K
+ int fd = PyObject_AsFileDescriptor(py_fileobj.ptr());
+ PyErr_Clear();
+ #endif
+
if (py_fileobj.isString())
{
std::string fileName = Py::String(py_fileobj);
@@ -2008,6 +2027,15 @@ RendererAgg::write_rgba(const Py::Tuple& args)
}
close_file = true;
}
+ #if PY3K
+ else if (fd != -1)
+ {
+ if (write(fd, pixBuffer, NUMBYTES) != (ssize_t)NUMBYTES)
+ {
+ throw Py::RuntimeError("Error writing to file");
+ }
+ }
+ #else
else if (PyFile_CheckExact(py_fileobj.ptr()))
{
fp = PyFile_AsFile(py_fileobj.ptr());
@@ -2016,6 +2044,7 @@ RendererAgg::write_rgba(const Py::Tuple& args)
throw Py::RuntimeError("Error writing to file");
}
}
+ #endif
else
{
PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(),
@@ -2071,7 +2100,11 @@ RendererAgg::tostring_rgb(const Py::Tuple& args)
}
//todo: how to do this with native CXX
+ #if PY3K
+ PyObject* o = Py_BuildValue("y#", buf_tmp, row_len * height);
+ #else
PyObject* o = Py_BuildValue("s#", buf_tmp, row_len * height);
+ #endif
delete [] buf_tmp;
return Py::asObject(o);
@@ -2107,7 +2140,12 @@ RendererAgg::tostring_argb(const Py::Tuple& args)
}
//todo: how to do this with native CXX
+
+ #if PY3K
+ PyObject* o = Py_BuildValue("y#", buf_tmp, row_len * height);
+ #else
PyObject* o = Py_BuildValue("s#", buf_tmp, row_len * height);
+ #endif
delete [] buf_tmp;
return Py::asObject(o);
}
@@ -2146,9 +2184,11 @@ RendererAgg::tostring_bgra(const Py::Tuple& args)
}
//todo: how to do this with native CXX
- PyObject* o = Py_BuildValue("s#",
- buf_tmp,
- row_len * height);
+ #if PY3K
+ PyObject* o = Py_BuildValue("y#", buf_tmp, row_len * height);
+ #else
+ PyObject* o = Py_BuildValue("s#", buf_tmp, row_len * height);
+ #endif
delete [] buf_tmp;
return Py::asObject(o);
}
@@ -2161,12 +2201,14 @@ RendererAgg::buffer_rgba(const Py::Tuple& args)
_VERBOSE("RendererAgg::buffer_rgba");
- args.verify_length(2);
- int startw = Py::Int(args[0]);
- int starth = Py::Int(args[1]);
+ args.verify_length(0);
+
+ #if PY3K
+ return Py::asObject(PyMemoryView_FromObject(this));
+ #else
int row_len = width * 4;
- int start = row_len * starth + startw * 4;
- return Py::asObject(PyBuffer_FromMemory(pixBuffer + start, row_len*height - start));
+ return Py::asObject(PyBuffer_FromMemory(pixBuffer, row_len*height));
+ #endif
}
@@ -2280,6 +2322,14 @@ RendererAgg::points_to_pixels(const Py::Object& points)
return p * dpi / 72.0;
}
+#if PY3K
+int
+RendererAgg::buffer_get( Py_buffer* buf, int flags )
+{
+ return PyBuffer_FillInfo(buf, this, pixBuffer, width * height * 4, 1,
+ PyBUF_SIMPLE);
+}
+#endif
RendererAgg::~RendererAgg()
{
@@ -2310,8 +2360,8 @@ Py::Object _backend_agg_module::new_renderer(const Py::Tuple &args,
debug = 0;
}
- unsigned int width = (unsigned int)Py::Int(args[0]);
- unsigned int height = (unsigned int)Py::Int(args[1]);
+ unsigned int width = (int)Py::Int(args[0]);
+ unsigned int height = (int)Py::Int(args[1]);
double dpi = Py::Float(args[2]);
if (width > 1 << 15 || height > 1 << 15)
@@ -2401,11 +2451,18 @@ void RendererAgg::init_type()
"restore_region(region)");
add_varargs_method("restore_region2", &RendererAgg::restore_region2,
"restore_region(region, x1, y1, x2, y2, x3, y3)");
+
+ #if PY3K
+ behaviors().supportBufferType();
+ #endif
}
-extern "C"
- DL_EXPORT(void)
- init_backend_agg(void)
+PyMODINIT_FUNC
+#if PY3K
+PyInit__backend_agg(void)
+#else
+init_backend_agg(void)
+#endif
{
//static _backend_agg_module* _backend_agg = new _backend_agg_module;
@@ -2415,4 +2472,8 @@ extern "C"
static _backend_agg_module* _backend_agg = NULL;
_backend_agg = new _backend_agg_module;
+
+ #if PY3K
+ return _backend_agg->module().ptr();
+ #endif
}
diff --git a/src/_backend_agg.h b/src/_backend_agg.h
index 633f3e7c8bc9..187d1435332c 100644
--- a/src/_backend_agg.h
+++ b/src/_backend_agg.h
@@ -195,6 +195,10 @@ class RendererAgg: public Py::PythonExtension
Py::Object restore_region(const Py::Tuple & args);
Py::Object restore_region2(const Py::Tuple & args);
+ #if PY3K
+ virtual int buffer_get( Py_buffer *, int flags );
+ #endif
+
virtual ~RendererAgg();
static const size_t PIXELS_PER_INCH;
diff --git a/src/_backend_gdk.c b/src/_backend_gdk.c
index 4c50aa2a4082..152554c2187a 100644
--- a/src/_backend_gdk.c
+++ b/src/_backend_gdk.c
@@ -52,7 +52,7 @@ static PyMethodDef _backend_gdk_functions[] = {
{ NULL, NULL, 0 }
};
-DL_EXPORT(void)
+PyMODINIT_FUNC
init_backend_gdk(void)
{
PyObject *mod;
diff --git a/src/_gtkagg.cpp b/src/_gtkagg.cpp
index 5a0b4613fe10..60c704a3d53a 100644
--- a/src/_gtkagg.cpp
+++ b/src/_gtkagg.cpp
@@ -131,9 +131,7 @@ class _gtkagg_module : public Py::ExtensionModule<_gtkagg_module>
}
};
-
-extern "C"
-DL_EXPORT(void)
+PyMODINIT_FUNC
init_gtkagg(void)
{
init_pygobject();
diff --git a/src/_image.cpp b/src/_image.cpp
index 6bb202a8b320..4a9ddabf0870 100644
--- a/src/_image.cpp
+++ b/src/_image.cpp
@@ -200,8 +200,13 @@ Image::as_rgba_str(const Py::Tuple& args, const Py::Dict& kwargs)
std::pair bufpair = _get_output_buffer();
+ #if PY3K
+ Py::Object ret = Py::asObject(Py_BuildValue("lly#", rowsOut, colsOut,
+ bufpair.first, colsOut * rowsOut * 4));
+ #else
Py::Object ret = Py::asObject(Py_BuildValue("lls#", rowsOut, colsOut,
bufpair.first, colsOut * rowsOut * 4));
+ #endif
if (bufpair.second) delete [] bufpair.first;
return ret;
@@ -221,9 +226,14 @@ Image::color_conv(const Py::Tuple& args)
args.verify_length(1);
int format = Py::Int(args[0]);
-
+ PyObject* py_buffer = NULL;
int row_len = colsOut * 4;
- PyObject* py_buffer = PyBuffer_New(row_len * rowsOut);
+#if PY3K
+ unsigned char* buf = (unsigned char *)malloc(row_len * rowsOut);
+ if (buf == NULL)
+ throw Py::MemoryError("Image::color_conv could not allocate memory");
+#else
+ py_buffer = PyBuffer_New(row_len * rowsOut);
if (py_buffer == NULL)
throw Py::MemoryError("Image::color_conv could not allocate memory");
@@ -231,7 +241,11 @@ Image::color_conv(const Py::Tuple& args)
Py_ssize_t buffer_len;
int ret = PyObject_AsWriteBuffer(py_buffer, &buf, &buffer_len);
if (ret != 0)
+ {
+ Py_XDECREF(py_buffer);
throw Py::MemoryError("Image::color_conv could not allocate memory");
+ }
+#endif
agg::rendering_buffer rtmp;
rtmp.attach(reinterpret_cast(buf), colsOut, rowsOut,
@@ -246,9 +260,17 @@ Image::color_conv(const Py::Tuple& args)
agg::color_conv(&rtmp, rbufOut, agg::color_conv_rgba32_to_argb32());
break;
default:
+ Py_XDECREF(py_buffer);
throw Py::ValueError("Image::color_conv unknown format");
}
+#if PY3K
+ py_buffer = PyByteArray_FromStringAndSize((char *)buf, row_len * rowsOut);
+ if (py_buffer == NULL) {
+ free(buf);
+ }
+#endif
+
PyObject* o = Py_BuildValue("llN", rowsOut, colsOut, py_buffer);
return Py::asObject(o);
}
@@ -1530,10 +1552,10 @@ _image_module::pcolor(const Py::Tuple& args)
Py::Object xp = args[0];
Py::Object yp = args[1];
Py::Object dp = args[2];
- unsigned int rows = Py::Int(args[3]);
- unsigned int cols = Py::Int(args[4]);
+ unsigned int rows = (unsigned long)Py::Int(args[3]);
+ unsigned int cols = (unsigned long)Py::Int(args[4]);
Py::Tuple bounds = args[5];
- unsigned int interpolation = Py::Int(args[6]);
+ unsigned int interpolation = (unsigned long)Py::Int(args[6]);
if (rows >= 32768 || cols >= 32768)
{
@@ -1927,17 +1949,13 @@ _image_module::pcolor2(const Py::Tuple& args)
return Py::asObject(imo);
}
-
-
-#if defined(_MSC_VER)
-DL_EXPORT(void)
-#elif defined(__cplusplus)
-extern "C" void
+#if PY3K
+PyMODINIT_FUNC
+PyInit__image(void)
#else
-void
-#endif
-
+PyMODINIT_FUNC
init_image(void)
+#endif
{
_VERBOSE("init_image");
@@ -1966,6 +1984,10 @@ init_image(void)
d["ASPECT_FREE"] = Py::Int(Image::ASPECT_FREE);
d["ASPECT_PRESERVE"] = Py::Int(Image::ASPECT_PRESERVE);
+
+#if PY3K
+ return _image->module().ptr();
+#endif
}
diff --git a/src/_macosx.m b/src/_macosx.m
index 40edd27b0648..44d62e8eca4f 100644
--- a/src/_macosx.m
+++ b/src/_macosx.m
@@ -506,7 +506,7 @@ static int _get_snap(GraphicsContext* self, enum e_snap_mode* mode)
static PyObject*
GraphicsContext_repr(GraphicsContext* self)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return PyUnicode_FromFormat("GraphicsContext object %p wrapping the Quartz 2D graphics context %p", (void*)self, (void*)(self->cr));
#else
return PyString_FromFormat("GraphicsContext object %p wrapping the Quartz 2D graphics context %p", (void*)self, (void*)(self->cr));
@@ -2252,7 +2252,7 @@ static CGRect _find_enclosing_rect(CGPoint points[3])
#else
ATSFontRef font = 0;
#endif
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
PyObject* ascii = NULL;
#endif
@@ -2435,41 +2435,7 @@ static CGRect _find_enclosing_rect(CGPoint points[3])
for (i = 0; i < n; i++)
{
PyObject* item = PyList_GET_ITEM(family, i);
-#if PY_MAJOR_VERSION >= 3
- ascii = PyUnicode_AsASCIIString(item);
- if(!ascii) return 0;
- temp = PyBytes_AS_STRING(ascii);
-#else
- if(!PyString_Check(item)) return 0;
- temp = PyString_AS_STRING(item);
-#endif
- for (j = 0; j < NMAP; j++)
- { if (!strcmp(map[j].name, temp))
- { temp = psnames[map[j].index][k];
- break;
- }
- }
- /* If the font name is not found in mapping, we assume */
- /* that the user specified the Postscript name directly */
-
- /* Check if this font can be found on the system */
- string = CFStringCreateWithCString(kCFAllocatorDefault,
- temp,
- kCFStringEncodingMacRoman);
-#ifdef COMPILING_FOR_10_5
- font = CTFontCreateWithName(string, size, NULL);
-#else
- font = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault);
-#endif
-
- CFRelease(string);
-
- if(font)
- {
- name = temp;
- break;
- }
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
Py_DECREF(ascii);
ascii = NULL;
#endif
@@ -2488,7 +2454,7 @@ static CGRect _find_enclosing_rect(CGPoint points[3])
#ifndef COMPILING_FOR_10_5
CGContextSelectFont(cr, name, size, kCGEncodingMacRoman);
#endif
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
Py_XDECREF(ascii);
#endif
return font;
@@ -2989,7 +2955,7 @@ static void _data_provider_release(void* info, const void* data, size_t size)
CGDataProviderRef provider;
double rect[4] = {0.0, 0.0, self->size.width, self->size.height};
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
if (!PyBytes_Check(image))
{
PyErr_SetString(PyExc_RuntimeError, "image is not a byte array");
@@ -3017,7 +2983,7 @@ static void _data_provider_release(void* info, const void* data, size_t size)
}
Py_INCREF(image);
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
n = PyByteArray_GET_SIZE(image);
data = PyByteArray_AS_STRING(image);
#else
@@ -3296,7 +3262,7 @@ static void _data_provider_release(void* info, const void* data, size_t size)
static PyObject*
FigureCanvas_repr(FigureCanvas* self)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return PyUnicode_FromFormat("FigureCanvas object %p wrapping NSView %p",
(void*)self, (void*)(self->view));
#else
@@ -3765,7 +3731,7 @@ static void _data_provider_release(void* info, const void* data, size_t size)
static PyObject*
FigureManager_repr(FigureManager* self)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return PyUnicode_FromFormat("FigureManager object %p wrapping NSWindow %p",
(void*) self, (void*)(self->window));
#else
@@ -4175,7 +4141,7 @@ -(void)save_figure:(id)sender
static PyObject*
NavigationToolbar_repr(NavigationToolbar* self)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return PyUnicode_FromFormat("NavigationToolbar object %p", (void*)self);
#else
return PyString_FromFormat("NavigationToolbar object %p", (void*)self);
@@ -4286,7 +4252,7 @@ -(void)save_figure:(id)sender
{
if(states[i]==1)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
PyList_SET_ITEM(list, j, PyLong_FromLong(i));
#else
PyList_SET_ITEM(list, j, PyInt_FromLong(i));
@@ -4706,7 +4672,7 @@ -(void)save_figure:(id)sender
static PyObject*
NavigationToolbar2_repr(NavigationToolbar2* self)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return PyUnicode_FromFormat("NavigationToolbar2 object %p", (void*)self);
#else
return PyString_FromFormat("NavigationToolbar2 object %p", (void*)self);
@@ -5643,7 +5609,7 @@ - (int)index
static PyObject*
Timer_repr(Timer* self)
{
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return PyUnicode_FromFormat("Timer object %p wrapping CFRunLoopTimerRef %p",
(void*) self, (void*)(self->timer));
#else
@@ -5824,7 +5790,7 @@ static void timer_callback(CFRunLoopTimerRef timer, void* info)
{NULL, NULL, 0, NULL}/* sentinel */
};
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
@@ -5854,13 +5820,13 @@ void init_macosx(void)
|| PyType_Ready(&NavigationToolbarType) < 0
|| PyType_Ready(&NavigationToolbar2Type) < 0
|| PyType_Ready(&TimerType) < 0)
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
return NULL;
#else
return;
#endif
-#if PY_MAJOR_VERSION >= 3
+#if PY3K
module = PyModule_Create(&moduledef);
if (module==NULL) return NULL;
#else
diff --git a/src/_path.cpp b/src/_path.cpp
index 82557dda88c6..2729b3b1042a 100644
--- a/src/_path.cpp
+++ b/src/_path.cpp
@@ -393,7 +393,7 @@ _path_module::update_path_extents(const Py::Tuple& args)
"Must pass Bbox object as arg 3 of update_path_extents");
}
Py::Object minpos_obj = args[3];
- bool ignore = bool(Py::Int(args[4]));
+ bool ignore = Py::Boolean(args[4]);
double xm, ym;
PyArrayObject* input_minpos = NULL;
@@ -613,7 +613,7 @@ _path_module::point_in_path_collection(const Py::Tuple& args)
Py::SeqBase transforms_obj = args[5];
Py::SeqBase offsets_obj = args[6];
agg::trans_affine offset_trans = py_to_agg_transformation_matrix(args[7].ptr());
- bool filled = Py::Int(args[8]);
+ bool filled = Py::Boolean(args[8]);
PyArrayObject* offsets = (PyArrayObject*)PyArray_FromObject(
offsets_obj.ptr(), PyArray_DOUBLE, 0, 2);
@@ -942,7 +942,7 @@ _path_module::clip_path_to_rect(const Py::Tuple &args)
PathIterator path(args[0]);
Py::Object bbox_obj = args[1];
- bool inside = Py::Int(args[2]);
+ bool inside = Py::Boolean(args[2]);
double x0, y0, x1, y1;
if (!py_convert_bbox(bbox_obj.ptr(), x0, y0, x1, y1))
@@ -1499,7 +1499,7 @@ _path_module::convert_to_svg(const Py::Tuple& args)
Py::Object clip_obj = args[2];
bool do_clip;
- agg::rect_base clip_rect;
+ agg::rect_base clip_rect(0, 0, 0, 0);
if (clip_obj.isNone() || !clip_obj.isTrue())
{
do_clip = false;
@@ -1596,18 +1596,29 @@ _path_module::convert_to_svg(const Py::Tuple& args)
--wait;
}
+ #if PY3K
+ PyObject* result = PyUnicode_FromStringAndSize(buffer, p - buffer);
+ #else
PyObject* result = PyString_FromStringAndSize(buffer, p - buffer);
+ #endif
free(buffer);
return Py::Object(result, true);
}
-extern "C"
- DL_EXPORT(void)
- init_path(void)
+PyMODINIT_FUNC
+#if PY3K
+PyInit__path(void)
+#else
+init_path(void)
+#endif
{
static _path_module* _path = NULL;
_path = new _path_module;
import_array();
+
+ #if PY3K
+ return _path->module().ptr();
+ #endif
}
diff --git a/src/_png.cpp b/src/_png.cpp
index 151c8da78b9d..224eb30bc8b0 100644
--- a/src/_png.cpp
+++ b/src/_png.cpp
@@ -42,8 +42,12 @@ class _png_module : public Py::ExtensionModule<_png_module>
{
add_varargs_method("write_png", &_png_module::write_png,
"write_png(buffer, width, height, fileobj, dpi=None)");
- add_varargs_method("read_png", &_png_module::read_png,
+ add_varargs_method("read_png", &_png_module::read_png_float,
"read_png(fileobj)");
+ add_varargs_method("read_png_float", &_png_module::read_png_float,
+ "read_png_float(fileobj)");
+ add_varargs_method("read_png_uint8", &_png_module::read_png_uint8,
+ "read_png_uint8(fileobj)");
initialize("Module to write PNG files");
}
@@ -51,7 +55,9 @@ class _png_module : public Py::ExtensionModule<_png_module>
private:
Py::Object write_png(const Py::Tuple& args);
- Py::Object read_png(const Py::Tuple& args);
+ Py::Object read_png_uint8(const Py::Tuple& args);
+ Py::Object read_png_float(const Py::Tuple& args);
+ PyObject* _read_png(const Py::Object& py_fileobj, const bool float_result);
};
static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length)
@@ -61,8 +67,13 @@ static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t lengt
PyObject* result = NULL;
if (write_method)
{
+ #if PY3K
+ result = PyObject_CallFunction(write_method, (char *)"y#", data,
+ length);
+ #else
result = PyObject_CallFunction(write_method, (char *)"s#", data,
length);
+ #endif
}
Py_XDECREF(write_method);
Py_XDECREF(result);
@@ -114,6 +125,10 @@ Py::Object _png_module::write_png(const Py::Tuple& args)
}
Py::Object py_fileobj = Py::Object(args[3]);
+#if PY3K
+ int fd = PyObject_AsFileDescriptor(py_fileobj.ptr());
+ PyErr_Clear();
+#endif
if (py_fileobj.isString())
{
std::string fileName = Py::String(py_fileobj);
@@ -125,10 +140,17 @@ Py::Object _png_module::write_png(const Py::Tuple& args)
}
close_file = true;
}
+#if PY3K
+ else if (fd != -1)
+ {
+ fp = fdopen(fd, "w");
+ }
+#else
else if (PyFile_CheckExact(py_fileobj.ptr()))
{
fp = PyFile_AsFile(py_fileobj.ptr());
}
+#endif
else
{
PyObject* write_method = PyObject_GetAttrString(
@@ -211,24 +233,30 @@ Py::Object _png_module::write_png(const Py::Tuple& args)
}
catch (...)
{
+ if (png_ptr && info_ptr)
+ {
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ }
+ delete [] row_pointers;
if (fp && close_file)
{
fclose(fp);
}
- delete [] row_pointers;
/* Changed calls to png_destroy_write_struct to follow
http://www.libpng.org/pub/png/libpng-manual.txt.
This ensures the info_ptr memory is released.
*/
- if (png_ptr && info_ptr)
- {
- png_destroy_write_struct(&png_ptr, &info_ptr);
- }
throw;
}
png_destroy_write_struct(&png_ptr, &info_ptr);
delete [] row_pointers;
+#if PY3K
+ if (fp)
+ {
+ fflush(fp);
+ }
+#endif
if (fp && close_file)
{
fclose(fp);
@@ -251,7 +279,11 @@ static void _read_png_data(PyObject* py_file_obj, png_bytep data, png_size_t len
{
result = PyObject_CallFunction(read_method, (char *)"i", length);
}
+#if PY3K
+ if (PyBytes_AsStringAndSize(result, &buffer, &bufflen) == 0)
+#else
if (PyString_AsStringAndSize(result, &buffer, &bufflen) == 0)
+#endif
{
if (bufflen == (Py_ssize_t)length)
{
@@ -268,16 +300,18 @@ static void read_png_data(png_structp png_ptr, png_bytep data, png_size_t length
_read_png_data(py_file_obj, data, length);
}
-Py::Object
-_png_module::read_png(const Py::Tuple& args)
+PyObject*
+_png_module::_read_png(const Py::Object& py_fileobj, const bool float_result)
{
-
- args.verify_length(1);
png_byte header[8]; // 8 is the maximum size that can be checked
FILE* fp = NULL;
bool close_file = false;
- Py::Object py_fileobj = Py::Object(args[0]);
+#if PY3K
+ int fd = PyObject_AsFileDescriptor(py_fileobj.ptr());
+ PyErr_Clear();
+#endif
+
if (py_fileobj.isString())
{
std::string fileName = Py::String(py_fileobj);
@@ -289,10 +323,16 @@ _png_module::read_png(const Py::Tuple& args)
}
close_file = true;
}
+#if PY3K
+ else if (fd != -1) {
+ fp = fdopen(fd, "r");
+ }
+#else
else if (PyFile_CheckExact(py_fileobj.ptr()))
{
fp = PyFile_AsFile(py_fileobj.ptr());
}
+#endif
else
{
PyObject* read_method = PyObject_GetAttrString(py_fileobj.ptr(), "read");
@@ -429,35 +469,70 @@ _png_module::read_png(const Py::Tuple& args)
int num_dims = (png_get_color_type(png_ptr, info_ptr)
& PNG_COLOR_MASK_COLOR) ? 3 : 2;
- double max_value = (1 << ((bit_depth < 8) ? 8 : bit_depth)) - 1;
- PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNew(
- num_dims, dimensions, PyArray_FLOAT);
+ PyArrayObject *A = NULL;
+ if (float_result) {
+ double max_value = (1 << ((bit_depth < 8) ? 8 : bit_depth)) - 1;
- if (A == NULL)
- {
- throw Py::MemoryError("Could not allocate image array");
- }
+ A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_FLOAT);
- for (png_uint_32 y = 0; y < height; y++)
- {
- png_byte* row = row_pointers[y];
- for (png_uint_32 x = 0; x < width; x++)
+ if (A == NULL)
+ {
+ throw Py::MemoryError("Could not allocate image array");
+ }
+
+ for (png_uint_32 y = 0; y < height; y++)
{
- size_t offset = y * A->strides[0] + x * A->strides[1];
- if (bit_depth == 16)
+ png_byte* row = row_pointers[y];
+ for (png_uint_32 x = 0; x < width; x++)
{
- png_uint_16* ptr = &reinterpret_cast(row)[x * dimensions[2]];
- for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
+ size_t offset = y * A->strides[0] + x * A->strides[1];
+ if (bit_depth == 16)
+ {
+ png_uint_16* ptr = &reinterpret_cast(row)[x * dimensions[2]];
+ for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
+ {
+ *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
+ }
+ }
+ else
{
- *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
+ png_byte* ptr = &(row[x * dimensions[2]]);
+ for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
+ {
+ *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
+ }
}
}
- else
+ }
+ } else {
+ A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_UBYTE);
+
+ if (A == NULL)
+ {
+ throw Py::MemoryError("Could not allocate image array");
+ }
+
+ for (png_uint_32 y = 0; y < height; y++)
+ {
+ png_byte* row = row_pointers[y];
+ for (png_uint_32 x = 0; x < width; x++)
{
- png_byte* ptr = &(row[x * dimensions[2]]);
- for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
+ size_t offset = y * A->strides[0] + x * A->strides[1];
+ if (bit_depth == 16)
+ {
+ png_uint_16* ptr = &reinterpret_cast(row)[x * dimensions[2]];
+ for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
+ {
+ *(png_byte*)(A->data + offset + p*A->strides[2]) = ptr[p] >> 8;
+ }
+ }
+ else
{
- *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
+ png_byte* ptr = &(row[x * dimensions[2]]);
+ for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
+ {
+ *(png_byte*)(A->data + offset + p*A->strides[2]) = ptr[p];
+ }
}
}
}
@@ -482,18 +557,39 @@ _png_module::read_png(const Py::Tuple& args)
if (PyErr_Occurred()) {
Py_DECREF((PyObject *)A);
- throw Py::Exception();
+ return NULL;
} else {
- return Py::asObject((PyObject*)A);
+ return (PyObject *)A;
}
}
-extern "C"
- DL_EXPORT(void)
- init_png(void)
+Py::Object
+_png_module::read_png_float(const Py::Tuple& args)
+{
+ args.verify_length(1);
+ return Py::asObject(_read_png(args[0], true));
+}
+
+Py::Object
+_png_module::read_png_uint8(const Py::Tuple& args)
+{
+ args.verify_length(1);
+ return Py::asObject(_read_png(args[0], false));
+}
+
+PyMODINIT_FUNC
+#if PY3K
+PyInit__png(void)
+#else
+init_png(void)
+#endif
{
import_array();
static _png_module* _png = NULL;
_png = new _png_module;
+
+#if PY3K
+ return _png->module().ptr();
+#endif
}
diff --git a/src/_tkagg.cpp b/src/_tkagg.cpp
index 854b40bdd20f..92247f616cca 100644
--- a/src/_tkagg.cpp
+++ b/src/_tkagg.cpp
@@ -40,8 +40,6 @@ extern "C"
# define SIZE_T_FORMAT "%zu"
#endif
-
-
typedef struct
{
PyObject_HEAD
@@ -267,10 +265,34 @@ static PyMethodDef functions[] =
{NULL, NULL} /* sentinel */
};
-extern "C"
- DL_EXPORT(void) init_tkagg(void)
+#if PY3K
+static PyModuleDef _tkagg_module = {
+ PyModuleDef_HEAD_INIT,
+ "_tkagg",
+ "",
+ -1,
+ functions,
+ NULL, NULL, NULL, NULL
+};
+
+PyMODINIT_FUNC
+PyInit__tkagg(void)
+{
+ PyObject* m;
+
+ m = PyModule_Create(&_tkagg_module);
+
+ import_array();
+
+ return m;
+}
+#else
+PyMODINIT_FUNC
+init_tkagg(void)
{
import_array();
Py_InitModule("_tkagg", functions);
}
+#endif
+
diff --git a/src/_ttconv.cpp b/src/_ttconv.cpp
index b203a138a442..eb4aa07701aa 100644
--- a/src/_ttconv.cpp
+++ b/src/_ttconv.cpp
@@ -6,6 +6,8 @@
Python wrapper for TrueType conversion library in ../ttconv.
*/
+#include "mplutils.h"
+
#include
#include "ttconv/pprdrv.h"
#include
@@ -46,7 +48,11 @@ class PythonFileWriter : public TTStreamWriter
PyObject* result = NULL;
if (_write_method)
{
+ #if PY3K
+ result = PyObject_CallFunction(_write_method, (char *)"y", a);
+ #else
result = PyObject_CallFunction(_write_method, (char *)"s", a);
+ #endif
if (! result)
{
throw PythonExceptionOccurred();
@@ -86,7 +92,11 @@ int pyiterable_to_vector_int(PyObject* object, void* address)
PyObject* item;
while ((item = PyIter_Next(iterator)))
{
+ #if PY3K
+ long value = PyLong_AsLong(item);
+ #else
long value = PyInt_AsLong(item);
+ #endif
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
{
@@ -169,7 +179,11 @@ class PythonDictionaryCallback : public TTDictionaryCallback
virtual void add_pair(const char* a, const char* b)
{
+ #if PY3K
+ PyObject* value = PyBytes_FromString(b);
+ #else
PyObject* value = PyString_FromString(b);
+ #endif
if (value)
{
if (PyDict_SetItemString(_dict, a, value))
@@ -237,7 +251,7 @@ py_get_pdf_charprocs(PyObject* self, PyObject* args, PyObject* kwds)
static PyMethodDef ttconv_methods[] =
{
{
- "convert_ttf_to_ps", (PyCFunction)convert_ttf_to_ps, METH_KEYWORDS,
+ "convert_ttf_to_ps", (PyCFunction)convert_ttf_to_ps, METH_VARARGS | METH_KEYWORDS,
"convert_ttf_to_ps(filename, output, fonttype, glyph_ids)\n"
"\n"
"Converts the Truetype font into a Type 3 or Type 42 Postscript font, "
@@ -255,7 +269,7 @@ static PyMethodDef ttconv_methods[] =
"composite glyphs, then the component glyphs will also be included."
},
{
- "get_pdf_charprocs", (PyCFunction)py_get_pdf_charprocs, METH_KEYWORDS,
+ "get_pdf_charprocs", (PyCFunction)py_get_pdf_charprocs, METH_VARARGS | METH_KEYWORDS,
"get_pdf_charprocs(filename, glyph_ids)\n"
"\n"
"Given a Truetype font file, returns a dictionary containing the PDF Type 3\n"
@@ -271,17 +285,36 @@ static PyMethodDef ttconv_methods[] =
{0, 0, 0, 0} /* Sentinel */
};
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
+static const char* module_docstring =
+ "Module to handle converting and subsetting TrueType "
+ "fonts to Postscript Type 3, Postscript Type 42 and "
+ "Pdf Type 3 fonts.";
+
+#if PY3K
+static PyModuleDef ttconv_module = {
+ PyModuleDef_HEAD_INIT,
+ "ttconv",
+ module_docstring,
+ -1,
+ ttconv_methods,
+ NULL, NULL, NULL, NULL
+};
+
PyMODINIT_FUNC
-initttconv(void)
+PyInit_ttconv(void)
{
PyObject* m;
- m = Py_InitModule3("ttconv", ttconv_methods,
- "Module to handle converting and subsetting TrueType "
- "fonts to Postscript Type 3, Postscript Type 42 and "
- "Pdf Type 3 fonts.");
+ m = PyModule_Create(&ttconv_module);
+
+ return m;
}
+#else
+PyMODINIT_FUNC
+initttconv(void)
+{
+ PyObject* m;
+ m = Py_InitModule3("ttconv", ttconv_methods, module_docstring);
+}
+#endif
diff --git a/src/_windowing.cpp b/src/_windowing.cpp
index 949944c0539a..7a20baa0a39a 100644
--- a/src/_windowing.cpp
+++ b/src/_windowing.cpp
@@ -1,5 +1,3 @@
-/* -*- mode: c++; c-basic-offset: 4 -*- */
-
#include "Python.h"
#include
@@ -11,14 +9,14 @@ _GetForegroundWindow(PyObject *module, PyObject *args)
{
return NULL;
}
- return PyInt_FromLong((long) handle);
+ return PyLong_FromSize_t((size_t)handle);
}
static PyObject *
_SetForegroundWindow(PyObject *module, PyObject *args)
{
HWND handle;
- if (!PyArg_ParseTuple(args, "l:SetForegroundWindow", &handle))
+ if (!PyArg_ParseTuple(args, "n:SetForegroundWindow", &handle))
{
return NULL;
}
@@ -38,7 +36,29 @@ static PyMethodDef _windowing_methods[] =
{NULL, NULL}
};
-extern "C" DL_EXPORT(void) init_windowing()
+#if PY_MAJOR_VERSION >= 3
+
+static struct PyModuleDef moduledef = {
+ PyModuleDef_HEAD_INIT,
+ "_windowing",
+ "",
+ -1,
+ _windowing_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+PyMODINIT_FUNC PyInit__windowing(void)
+{
+ PyObject *module = PyModule_Create(&moduledef);
+ return module;
+}
+
+#else
+PyMODINIT_FUNC init_windowing()
{
Py_InitModule("_windowing", _windowing_methods);
}
+#endif
diff --git a/src/cntr.c b/src/cntr.c
index 2a00bdf4458a..4448714b6a59 100644
--- a/src/cntr.c
+++ b/src/cntr.c
@@ -22,6 +22,12 @@
#include
#include "numpy/arrayobject.h"
+#if PY_MAJOR_VERSION >= 3
+#define PY3K 1
+#else
+#define PY3K 0
+#endif
+
/* Note that all arrays in these routines are Fortran-style,
in the sense that the "i" index varies fastest; the dimensions
of the corresponding C array are z[jmax][imax] in the notation
@@ -1745,7 +1751,11 @@ static void
Cntr_dealloc(Cntr* self)
{
Cntr_clear(self);
- self->ob_type->tp_free((PyObject*)self);
+ #if PY3K
+ Py_TYPE(self)->tp_free((PyObject*)self);
+ #else
+ self->ob_type->tp_free((PyObject*)self);
+ #endif
}
static PyObject *
@@ -1915,8 +1925,12 @@ static PyMethodDef Cntr_methods[] = {
};
static PyTypeObject CntrType = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
+ #if PY3K
+ PyVarObject_HEAD_INIT(NULL, 0)
+ #else
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ #endif
"cntr.Cntr", /*tp_name*/
sizeof(Cntr), /*tp_basicsize*/
0, /*tp_itemsize*/
@@ -1960,24 +1974,54 @@ static PyMethodDef module_methods[] = {
{NULL} /* Sentinel */
};
+#if PY3K
+static PyModuleDef cntr_module = {
+ PyModuleDef_HEAD_INIT,
+ "_cntr",
+ "Contouring engine as an extension type (numpy).",
+ -1,
+ module_methods,
+ NULL, NULL, NULL, NULL
+};
+
+#define ERROR_RETURN return NULL
+
+PyMODINIT_FUNC
+PyInit__cntr(void)
+#else
+#define ERROR_RETURN return
+
PyMODINIT_FUNC
init_cntr(void)
+#endif
{
PyObject* m;
- if (PyType_Ready(&CntrType) < 0)
- return;
+ if (PyType_Ready(&CntrType) < 0) {
+ ERROR_RETURN;
+ }
+
+ #if PY3K
+ m = PyModule_Create(&cntr_module);
+ #else
+ m = Py_InitModule3("_cntr", module_methods,
+ "Contouring engine as an extension type (numpy).");
+ #endif
- m = Py_InitModule3("_cntr", module_methods,
- "Contouring engine as an extension type (numpy).");
+ if (m == NULL) {
+ ERROR_RETURN;
+ }
- if (m == NULL)
- return;
PyModule_AddIntConstant(m, "_slitkind", (long)kind_slit_up );
/* We can add all the point_kinds values later if we need them. */
import_array();
+
Py_INCREF(&CntrType);
PyModule_AddObject(m, "Cntr", (PyObject *)&CntrType);
+
+ #if PY3K
+ return m;
+ #endif
}
diff --git a/src/ft2font.cpp b/src/ft2font.cpp
index 0547c9ff4b3c..025d263708d3 100644
--- a/src/ft2font.cpp
+++ b/src/ft2font.cpp
@@ -50,33 +50,35 @@
FT_Library _ft2Library;
-// FT2Image::FT2Image() :
-// _isDirty(true),
-// _buffer(NULL),
-// _width(0), _height(0),
-// _rgbCopy(NULL),
-// _rgbaCopy(NULL) {
-// _VERBOSE("FT2Image::FT2Image");
-// }
-
-FT2Image::FT2Image(unsigned long width, unsigned long height) :
+FT2Image::FT2Image(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds) :
+ Py::PythonClass< FT2Image >::PythonClass(self, args, kwds),
_isDirty(true),
_buffer(NULL),
- _width(0), _height(0),
- _rgbCopy(NULL),
- _rgbaCopy(NULL)
+ _width(0), _height(0)
{
_VERBOSE("FT2Image::FT2Image");
+
+ args.verify_length(2);
+ int width = Py::Int(args[0]);
+ int height = Py::Int(args[1]);
+
resize(width, height);
}
-FT2Image::~FT2Image()
-{
- _VERBOSE("FT2Image::~FT2Image");
+FT2Image::~FT2Image() {
delete [] _buffer;
_buffer = NULL;
- delete _rgbCopy;
- delete _rgbaCopy;
+}
+
+Py::PythonClassObject FT2Image::factory(int width, int height)
+{
+ Py::Callable class_type(type());
+ Py::Tuple args(2);
+ args[0] = Py::Int(width);
+ args[1] = Py::Int(height);
+ Py::PythonClassObject o = Py::PythonClassObject(
+ class_type.apply(args, Py::Dict()));
+ return o;
}
void
@@ -134,7 +136,9 @@ FT2Image::draw_bitmap(FT_Bitmap* bitmap,
unsigned char* dst = _buffer + (i * image_width + x1);
unsigned char* src = bitmap->buffer + (((i - y_offset) * bitmap->pitch) + x_start);
for (FT_Int j = x1; j < x2; ++j, ++dst, ++src)
+ {
*dst |= *src;
+ }
}
_isDirty = true;
@@ -182,6 +186,7 @@ FT2Image::py_write_bitmap(const Py::Tuple & args)
return Py::Object();
}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_write_bitmap)
void
FT2Image::draw_rect(unsigned long x0, unsigned long y0,
@@ -232,6 +237,7 @@ FT2Image::py_draw_rect(const Py::Tuple & args)
return Py::Object();
}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_draw_rect)
void
FT2Image::draw_rect_filled(unsigned long x0, unsigned long y0,
@@ -275,6 +281,7 @@ FT2Image::py_draw_rect_filled(const Py::Tuple & args)
return Py::Object();
}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_draw_rect_filled)
char FT2Image::as_str__doc__[] =
"width, height, s = image_as_str()\n"
@@ -289,10 +296,13 @@ FT2Image::py_as_str(const Py::Tuple & args)
args.verify_length(0);
return Py::asObject
- (PyString_FromStringAndSize((const char *)_buffer,
- _width*_height)
- );
+#if PY3K
+ (PyBytes_FromStringAndSize((const char *)_buffer, _width*_height));
+#else
+ (PyString_FromStringAndSize((const char *)_buffer, _width*_height));
+#endif
}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_as_str)
char FT2Image::as_array__doc__[] =
"x = image.as_array()\n"
@@ -315,98 +325,7 @@ FT2Image::py_as_array(const Py::Tuple & args)
return Py::asObject((PyObject*)A);
}
-
-void
-FT2Image::makeRgbCopy()
-{
- if (!_isDirty)
- {
- return;
- }
-
- if (!_rgbCopy)
- {
- _rgbCopy = new FT2Image(_width * 3, _height);
- }
- else
- {
- _rgbCopy->resize(_width * 3, _height);
- }
- unsigned char *src = _buffer;
- unsigned char *src_end = src + (_width * _height);
- unsigned char *dst = _rgbCopy->_buffer;
-
- unsigned char tmp;
- while (src != src_end)
- {
- tmp = 255 - *src++;
- *dst++ = tmp;
- *dst++ = tmp;
- *dst++ = tmp;
- }
-}
-
-char FT2Image::as_rgb_str__doc__[] =
- "width, height, s = image_as_rgb_str()\n"
- "\n"
- "Return the image buffer as a 24-bit RGB string.\n"
- "\n"
- ;
-Py::Object
-FT2Image::py_as_rgb_str(const Py::Tuple & args)
-{
- _VERBOSE("FT2Image::as_str_rgb");
- args.verify_length(0);
-
- makeRgbCopy();
-
- return _rgbCopy->py_as_str(args);
-}
-
-void FT2Image::makeRgbaCopy()
-{
- if (!_isDirty)
- {
- return;
- }
-
- if (!_rgbaCopy)
- {
- _rgbaCopy = new FT2Image(_width * 4, _height);
- }
- else
- {
- _rgbaCopy->resize(_width * 4, _height);
- }
- unsigned char *src = _buffer;
- unsigned char *src_end = src + (_width * _height);
- unsigned char *dst = _rgbaCopy->_buffer;
-
- while (src != src_end)
- {
- // We know the array has already been zero'ed out in
- // the resize method, so we just skip over the r, g and b.
- dst += 3;
- *dst++ = *src++;
- }
-}
-
-char FT2Image::as_rgba_str__doc__[] =
- "width, height, s = image_as_rgb_str()\n"
- "\n"
- "Return the image buffer as a 32-bit RGBA string.\n"
- "\n"
- ;
-Py::Object
-FT2Image::py_as_rgba_str(const Py::Tuple & args)
-{
- _VERBOSE("FT2Image::as_str_rgba");
- args.verify_length(0);
-
- makeRgbaCopy();
-
- return _rgbaCopy->py_as_str(args);
-}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_as_array)
Py::Object
FT2Image::py_get_width(const Py::Tuple & args)
@@ -416,6 +335,7 @@ FT2Image::py_get_width(const Py::Tuple & args)
return Py::Int((long)get_width());
}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_get_width)
Py::Object
FT2Image::py_get_height(const Py::Tuple & args)
@@ -425,27 +345,30 @@ FT2Image::py_get_height(const Py::Tuple & args)
return Py::Int((long)get_height());
}
+PYCXX_VARARGS_METHOD_DECL(FT2Image, py_get_height)
-Glyph::Glyph(const FT_Face& face, const FT_Glyph& glyph, size_t ind) :
- glyphInd(ind)
+Py::PythonClassObject Glyph::factory(
+ const FT_Face& face, const FT_Glyph& glyph, size_t ind)
{
- _VERBOSE("Glyph::Glyph");
+ Py::Callable class_type(type());
+ Py::PythonClassObject obj = Py::PythonClassObject(
+ class_type.apply(Py::Tuple(), Py::Dict()));
+ Glyph* o = obj.getCxxObject();
+ o->glyphInd = ind;
FT_BBox bbox;
FT_Glyph_Get_CBox(glyph, ft_glyph_bbox_subpixels, &bbox);
- setattr("width", Py::Int(face->glyph->metrics.width / HORIZ_HINTING));
- setattr("height", Py::Int(face->glyph->metrics.height));
- setattr("horiBearingX", Py::Int(face->glyph->metrics.horiBearingX / HORIZ_HINTING));
- setattr("horiBearingY", Py::Int(face->glyph->metrics.horiBearingY));
- setattr("horiAdvance", Py::Int(face->glyph->metrics.horiAdvance));
- setattr("linearHoriAdvance", Py::Int(face->glyph->linearHoriAdvance / HORIZ_HINTING));
- setattr("vertBearingX", Py::Int(face->glyph->metrics.vertBearingX));
+ o->setattro("width", Py::Int(face->glyph->metrics.width / HORIZ_HINTING));
+ o->setattro("height", Py::Int(face->glyph->metrics.height));
+ o->setattro("horiBearingX", Py::Int(face->glyph->metrics.horiBearingX / HORIZ_HINTING));
+ o->setattro("horiBearingY", Py::Int(face->glyph->metrics.horiBearingY));
+ o->setattro("horiAdvance", Py::Int(face->glyph->metrics.horiAdvance));
+ o->setattro("linearHoriAdvance", Py::Int(face->glyph->linearHoriAdvance / HORIZ_HINTING));
+ o->setattro("vertBearingX", Py::Int(face->glyph->metrics.vertBearingX));
- setattr("vertBearingY", Py::Int(face->glyph->metrics.vertBearingY));
- setattr("vertAdvance", Py::Int(face->glyph->metrics.vertAdvance));
- //setattr("bitmap_left", Py::Int( face->glyph->bitmap_left) );
- //setattr("bitmap_top", Py::Int( face->glyph->bitmap_top) );
+ o->setattro("vertBearingY", Py::Int(face->glyph->metrics.vertBearingY));
+ o->setattro("vertAdvance", Py::Int(face->glyph->metrics.vertAdvance));
Py::Tuple abbox(4);
@@ -453,7 +376,9 @@ Glyph::Glyph(const FT_Face& face, const FT_Glyph& glyph, size_t ind) :
abbox[1] = Py::Int(bbox.yMin);
abbox[2] = Py::Int(bbox.xMax);
abbox[3] = Py::Int(bbox.yMax);
- setattr("bbox", abbox);
+ o->setattro("bbox", abbox);
+
+ return obj;
}
Glyph::~Glyph()
@@ -462,7 +387,7 @@ Glyph::~Glyph()
}
int
-Glyph::setattr(const char *name, const Py::Object &value)
+Glyph::setattro(const Py::String &name, const Py::Object &value)
{
_VERBOSE("Glyph::setattr");
__dict__[name] = value;
@@ -470,11 +395,11 @@ Glyph::setattr(const char *name, const Py::Object &value)
}
Py::Object
-Glyph::getattr(const char *name)
+Glyph::getattro(const Py::String &name)
{
_VERBOSE("Glyph::getattr");
if (__dict__.hasKey(name)) return __dict__[name];
- else return getattr_default(name);
+ else return genericGetAttro(name);
}
inline double conv(int v)
@@ -483,7 +408,11 @@ inline double conv(int v)
}
-//see http://freetype.sourceforge.net/freetype2/docs/glyphs/glyphs-6.html
+char FT2Font::get_path__doc__[] =
+ "get_path()\n"
+ "\n"
+ "Get the path data from the currently loaded glyph as a tuple of vertices, codes.\n"
+ ;
Py::Object
FT2Font::get_path()
{
@@ -817,12 +746,17 @@ FT2Font::get_path()
return result;
}
+PYCXX_NOARGS_METHOD_DECL(FT2Font, get_path)
-
-FT2Font::FT2Font(std::string facefile) :
- image(NULL)
+FT2Font::FT2Font(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds) :
+ Py::PythonClass::PythonClass(self, args, kwds),
+ image()
{
+ args.verify_length(1);
+ std::string facefile = Py::String(args[0]);
+
_VERBOSE(Printf("FT2Font::FT2Font %s", facefile.c_str()).str());
+
clear(Py::Tuple(0));
int error = FT_New_Face(_ft2Library, facefile.c_str(), 0, &face);
@@ -831,28 +765,24 @@ FT2Font::FT2Font(std::string facefile) :
{
std::ostringstream s;
s << "Could not load facefile " << facefile << "; Unknown_File_Format" << std::endl;
- ob_refcnt--;
throw Py::RuntimeError(s.str());
}
else if (error == FT_Err_Cannot_Open_Resource)
{
std::ostringstream s;
s << "Could not open facefile " << facefile << "; Cannot_Open_Resource" << std::endl;
- ob_refcnt--;
throw Py::RuntimeError(s.str());
}
else if (error == FT_Err_Invalid_File_Format)
{
std::ostringstream s;
s << "Could not open facefile " << facefile << "; Invalid_File_Format" << std::endl;
- ob_refcnt--;
throw Py::RuntimeError(s.str());
}
else if (error)
{
std::ostringstream s;
s << "Could not open facefile " << facefile << "; freetype error code " << error << std::endl;
- ob_refcnt--;
throw Py::RuntimeError(s.str());
}
@@ -869,7 +799,6 @@ FT2Font::FT2Font(std::string facefile) :
{
std::ostringstream s;
s << "Could not set the fontsize for facefile " << facefile << std::endl;
- ob_refcnt--;
throw Py::RuntimeError(s.str());
}
@@ -895,40 +824,40 @@ FT2Font::FT2Font(std::string facefile) :
style_name = "UNAVAILABLE";
}
- setattr("postscript_name", Py::String(ps_name));
- setattr("num_faces", Py::Int(face->num_faces));
- setattr("family_name", Py::String(family_name));
- setattr("style_name", Py::String(style_name));
- setattr("face_flags", Py::Int(face->face_flags));
- setattr("style_flags", Py::Int(face->style_flags));
- setattr("num_glyphs", Py::Int(face->num_glyphs));
- setattr("num_fixed_sizes", Py::Int(face->num_fixed_sizes));
- setattr("num_charmaps", Py::Int(face->num_charmaps));
+ setattro("postscript_name", Py::String(ps_name));
+ setattro("num_faces", Py::Int(face->num_faces));
+ setattro("family_name", Py::String(family_name));
+ setattro("style_name", Py::String(style_name));
+ setattro("face_flags", Py::Int(face->face_flags));
+ setattro("style_flags", Py::Int(face->style_flags));
+ setattro("num_glyphs", Py::Int(face->num_glyphs));
+ setattro("num_fixed_sizes", Py::Int(face->num_fixed_sizes));
+ setattro("num_charmaps", Py::Int(face->num_charmaps));
int scalable = FT_IS_SCALABLE(face);
- setattr("scalable", Py::Int(scalable));
+ setattro("scalable", Py::Int(scalable));
if (scalable)
{
- setattr("units_per_EM", Py::Int(face->units_per_EM));
+ setattro("units_per_EM", Py::Int(face->units_per_EM));
Py::Tuple bbox(4);
bbox[0] = Py::Int(face->bbox.xMin);
bbox[1] = Py::Int(face->bbox.yMin);
bbox[2] = Py::Int(face->bbox.xMax);
bbox[3] = Py::Int(face->bbox.yMax);
- setattr("bbox", bbox);
- setattr("ascender", Py::Int(face->ascender));
- setattr("descender", Py::Int(face->descender));
- setattr("height", Py::Int(face->height));
- setattr("max_advance_width", Py::Int(face->max_advance_width));
- setattr("max_advance_height", Py::Int(face->max_advance_height));
- setattr("underline_position", Py::Int(face->underline_position));
- setattr("underline_thickness", Py::Int(face->underline_thickness));
+ setattro("bbox", bbox);
+ setattro("ascender", Py::Int(face->ascender));
+ setattro("descender", Py::Int(face->descender));
+ setattro("height", Py::Int(face->height));
+ setattro("max_advance_width", Py::Int(face->max_advance_width));
+ setattro("max_advance_height", Py::Int(face->max_advance_height));
+ setattro("underline_position", Py::Int(face->underline_position));
+ setattro("underline_thickness", Py::Int(face->underline_thickness));
}
- setattr("fname", Py::String(facefile));
+ setattro("fname", Py::String(facefile));
_VERBOSE("FT2Font::FT2Font done");
}
@@ -937,7 +866,6 @@ FT2Font::~FT2Font()
{
_VERBOSE("FT2Font::~FT2Font");
- Py_XDECREF(image);
FT_Done_Face(face);
for (size_t i = 0; i < glyphs.size(); i++)
@@ -947,7 +875,7 @@ FT2Font::~FT2Font()
}
int
-FT2Font::setattr(const char *name, const Py::Object &value)
+FT2Font::setattro(const Py::String &name, const Py::Object &value)
{
_VERBOSE("FT2Font::setattr");
__dict__[name] = value;
@@ -955,11 +883,11 @@ FT2Font::setattr(const char *name, const Py::Object &value)
}
Py::Object
-FT2Font::getattr(const char *name)
+FT2Font::getattro(const Py::String &name)
{
_VERBOSE("FT2Font::getattr");
if (__dict__.hasKey(name)) return __dict__[name];
- else return getattr_default(name);
+ else return genericGetAttro(name);
}
char FT2Font::clear__doc__[] =
@@ -974,9 +902,6 @@ FT2Font::clear(const Py::Tuple & args)
_VERBOSE("FT2Font::clear");
args.verify_length(0);
- Py_XDECREF(image);
- image = NULL;
-
angle = 0.0;
pen.x = 0;
@@ -991,9 +916,7 @@ FT2Font::clear(const Py::Tuple & args)
return Py::Object();
}
-
-
-
+PYCXX_VARARGS_METHOD_DECL(FT2Font, clear)
char FT2Font::set_size__doc__[] =
"set_size(ptsize, dpi)\n"
@@ -1027,7 +950,7 @@ FT2Font::set_size(const Py::Tuple & args)
}
return Py::Object();
}
-
+PYCXX_VARARGS_METHOD_DECL(FT2Font, set_size)
char FT2Font::set_charmap__doc__[] =
"set_charmap(i)\n"
@@ -1053,6 +976,7 @@ FT2Font::set_charmap(const Py::Tuple & args)
}
return Py::Object();
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, set_charmap)
char FT2Font::select_charmap__doc__[] =
"select_charmap(i)\n"
@@ -1074,6 +998,7 @@ FT2Font::select_charmap(const Py::Tuple & args)
}
return Py::Object();
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, select_charmap)
FT_BBox
FT2Font::compute_string_bbox()
@@ -1114,7 +1039,6 @@ FT2Font::compute_string_bbox()
return bbox;
}
-
char FT2Font::get_kerning__doc__[] =
"dx = get_kerning(left, right, mode)\n"
"\n"
@@ -1150,7 +1074,7 @@ FT2Font::get_kerning(const Py::Tuple & args)
}
}
-
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_kerning)
char FT2Font::set_text__doc__[] =
@@ -1272,6 +1196,7 @@ FT2Font::set_text(const Py::Tuple & args, const Py::Dict & kwargs)
_VERBOSE("FT2Font::set_text done");
return xys;
}
+PYCXX_KEYWORDS_METHOD_DECL(FT2Font, set_text)
char FT2Font::get_num_glyphs__doc__[] =
"get_num_glyphs()\n"
@@ -1286,6 +1211,7 @@ FT2Font::get_num_glyphs(const Py::Tuple & args)
return Py::Int((long)glyphs.size());
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_num_glyphs)
char FT2Font::load_char__doc__[] =
"load_char(charcode, flags=LOAD_FORCE_AUTOHINT)\n"
@@ -1333,10 +1259,9 @@ FT2Font::load_char(const Py::Tuple & args, const Py::Dict & kwargs)
size_t num = glyphs.size(); //the index into the glyphs list
glyphs.push_back(thisGlyph);
- Glyph* gm = new Glyph(face, thisGlyph, num);
- return Py::asObject(gm);
+ return Glyph::factory(face, thisGlyph, num);
}
-
+PYCXX_KEYWORDS_METHOD_DECL(FT2Font, load_char)
char FT2Font::load_glyph__doc__[] =
"load_glyph(glyphindex, flags=LOAD_FORCE_AUTOHINT)\n"
@@ -1384,10 +1309,9 @@ FT2Font::load_glyph(const Py::Tuple & args, const Py::Dict & kwargs)
size_t num = glyphs.size(); //the index into the glyphs list
glyphs.push_back(thisGlyph);
- Glyph* gm = new Glyph(face, thisGlyph, num);
- return Py::asObject(gm);
+ return Glyph::factory(face, thisGlyph, num);
}
-
+PYCXX_KEYWORDS_METHOD_DECL(FT2Font, load_glyph)
char FT2Font::get_width_height__doc__[] =
"w, h = get_width_height()\n"
@@ -1409,6 +1333,7 @@ FT2Font::get_width_height(const Py::Tuple & args)
ret[1] = Py::Int(bbox.yMax - bbox.yMin);
return ret;
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_width_height)
char FT2Font::get_descent__doc__[] =
"d = get_descent()\n"
@@ -1426,6 +1351,7 @@ FT2Font::get_descent(const Py::Tuple & args)
FT_BBox bbox = compute_string_bbox();
return Py::Int(- bbox.yMin);;
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_descent)
char FT2Font::draw_glyphs_to_bitmap__doc__[] =
"draw_glyphs_to_bitmap()\n"
@@ -1444,9 +1370,8 @@ FT2Font::draw_glyphs_to_bitmap(const Py::Tuple & args)
size_t width = (string_bbox.xMax - string_bbox.xMin) / 64 + 2;
size_t height = (string_bbox.yMax - string_bbox.yMin) / 64 + 2;
- Py_XDECREF(image);
- image = NULL;
- image = new FT2Image(width, height);
+ image = FT2Image::factory(width, height);
+ FT2Image* image_cxx = Py::PythonClassObject(image).getCxxObject();
for (size_t n = 0; n < glyphs.size(); n++)
{
@@ -1470,12 +1395,12 @@ FT2Font::draw_glyphs_to_bitmap(const Py::Tuple & args)
FT_Int x = (FT_Int)(bitmap->left - (string_bbox.xMin / 64.));
FT_Int y = (FT_Int)((string_bbox.yMax / 64.) - bitmap->top + 1);
- image->draw_bitmap(&bitmap->bitmap, x, y);
+ image_cxx->draw_bitmap(&bitmap->bitmap, x, y);
}
return Py::Object();
}
-
+PYCXX_VARARGS_METHOD_DECL(FT2Font, draw_glyphs_to_bitmap)
char FT2Font::get_xys__doc__[] =
"get_xys()\n"
@@ -1525,6 +1450,7 @@ FT2Font::get_xys(const Py::Tuple & args)
return xys;
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_xys)
char FT2Font::draw_glyph_to_bitmap__doc__[] =
"draw_glyph_to_bitmap(bitmap, x, y, glyph)\n"
@@ -1544,11 +1470,7 @@ FT2Font::draw_glyph_to_bitmap(const Py::Tuple & args)
_VERBOSE("FT2Font::draw_glyph_to_bitmap");
args.verify_length(4);
- if (!FT2Image::check(args[0].ptr()))
- {
- throw Py::TypeError("Usage: draw_glyph_to_bitmap(bitmap, x,y,glyph)");
- }
- FT2Image* im = static_cast(args[0].ptr());
+ FT2Image* im = Py::PythonClassObject(args[0]).getCxxObject();
double xd = Py::Float(args[1]);
double yd = Py::Float(args[2]);
@@ -1558,13 +1480,9 @@ FT2Font::draw_glyph_to_bitmap(const Py::Tuple & args)
sub_offset.x = 0; // int((xd - (double)x) * 64.0);
sub_offset.y = 0; // int((yd - (double)y) * 64.0);
- if (!Glyph::check(args[3].ptr()))
- {
- throw Py::TypeError("Usage: draw_glyph_to_bitmap(bitmap, x,y,glyph)");
- }
- Glyph* glyph = static_cast(args[3].ptr());
+ Glyph* glyph = Py::PythonClassObject(args[3]).getCxxObject();
- if ((size_t)glyph->glyphInd >= glyphs.size())
+ if (glyph->glyphInd >= glyphs.size())
{
throw Py::ValueError("glyph num is out of range");
}
@@ -1584,6 +1502,7 @@ FT2Font::draw_glyph_to_bitmap(const Py::Tuple & args)
im->draw_bitmap(&bitmap->bitmap, x + bitmap->left, y);
return Py::Object();
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, draw_glyph_to_bitmap)
char FT2Font::get_glyph_name__doc__[] =
"get_glyph_name(index)\n"
@@ -1602,12 +1521,13 @@ FT2Font::get_glyph_name(const Py::Tuple & args)
}
char buffer[128];
- if (FT_Get_Glyph_Name(face, (FT_UInt) Py::Int(args[0]), buffer, 128))
+ if (FT_Get_Glyph_Name(face, (FT_UInt) (unsigned long)Py::Int(args[0]), buffer, 128))
{
throw Py::RuntimeError("Could not get glyph names.");
}
return Py::String(buffer);
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_glyph_name)
char FT2Font::get_charmap__doc__[] =
"get_charmap()\n"
@@ -1633,7 +1553,7 @@ FT2Font::get_charmap(const Py::Tuple & args)
}
return charmap;
}
-
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_charmap)
// ID Platform Encoding
// 0 Unicode Reserved (set to 0)
@@ -1722,10 +1642,12 @@ FT2Font::get_sfnt(const Py::Tuple & args)
key[2] = Py::Int(sfnt.language_id);
key[3] = Py::Int(sfnt.name_id);
names[key] = Py::String((char *) sfnt.string,
- (int) sfnt.string_len);
+ (int) sfnt.string_len,
+ "latin-1");
}
return names;
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_sfnt)
char FT2Font::get_name_index__doc__[] =
"get_name_index(name)\n"
@@ -1743,6 +1665,7 @@ FT2Font::get_name_index(const Py::Tuple & args)
return Py::Long((long)
FT_Get_Name_Index(face, (FT_String *) glyphname.c_str()));
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_name_index)
char FT2Font::get_ps_font_info__doc__[] =
"get_ps_font_info()\n"
@@ -1775,6 +1698,7 @@ FT2Font::get_ps_font_info(const Py::Tuple & args)
info[8] = Py::Int(fontinfo.underline_thickness);
return info;
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_ps_font_info)
char FT2Font::get_sfnt_table__doc__[] =
"get_sfnt_table(name)\n"
@@ -1870,9 +1794,15 @@ FT2Font::get_sfnt_table(const Py::Tuple & args)
}
case 2:
{
+ #if PY3K
+ char os_2_dict[] = "{s:h, s:h, s:h, s:h, s:h, s:h, s:h, s:h,"
+ "s:h, s:h, s:h, s:h, s:h, s:h, s:h, s:h, s:y#, s:(llll),"
+ "s:y#, s:h, s:h, s:h}";
+ #else
char os_2_dict[] = "{s:h, s:h, s:h, s:h, s:h, s:h, s:h, s:h,"
"s:h, s:h, s:h, s:h, s:h, s:h, s:h, s:h, s:s#, s:(llll),"
"s:s#, s:h, s:h, s:h}";
+ #endif
TT_OS2 *t = (TT_OS2 *)table;
return Py::asObject(Py_BuildValue(os_2_dict,
"version", (unsigned)t->version,
@@ -1983,10 +1913,14 @@ FT2Font::get_sfnt_table(const Py::Tuple & args)
pclt["typeFamily"] = Py::Int((short) t->TypeFamily);
pclt["capHeight"] = Py::Int((short) t->CapHeight);
pclt["symbolSet"] = Py::Int((short) t->SymbolSet);
+ #if PY3K
+ pclt["typeFace"] = Py::String((char *) t->TypeFace, 16, "latin-1");
+ pclt["characterComplement"] = Py::Bytes((char *) t->CharacterComplement, 8);
+ #else
pclt["typeFace"] = Py::String((char *) t->TypeFace, 16);
- pclt["characterComplement"] = Py::String((char *)
- t->CharacterComplement, 8);
- pclt["filename"] = Py::String((char *) t->FileName, 6);
+ pclt["characterComplement"] = Py::String((char *) t->CharacterComplement, 8);
+ #endif
+ // pclt["filename"] = Py::String((char *) t->FileName, 6);
pclt["strokeWeight"] = Py::Int((int) t->StrokeWeight);
pclt["widthType"] = Py::Int((int) t->WidthType);
pclt["serifStyle"] = Py::Int((int) t->SerifStyle);
@@ -1996,6 +1930,7 @@ FT2Font::get_sfnt_table(const Py::Tuple & args)
return Py::Object();
}
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_sfnt_table)
char FT2Font::get_image__doc__ [] =
"get_image()\n"
@@ -2005,13 +1940,13 @@ Py::Object
FT2Font::get_image(const Py::Tuple &args)
{
args.verify_length(0);
- if (image)
+ if (!image.isNone())
{
- Py_XINCREF(image);
- return Py::asObject(image);
+ return image;
}
throw Py::RuntimeError("You must call .set_text() before .get_image()");
}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, get_image)
char FT2Font::attach_file__doc__ [] =
"attach_file(filename)\n"
@@ -2036,53 +1971,31 @@ FT2Font::attach_file(const Py::Tuple &args)
}
return Py::Object();
}
-
-Py::Object
-ft2font_module::new_ft2image(const Py::Tuple &args)
-{
- args.verify_length(2);
-
- int width = Py::Int(args[0]);
- int height = Py::Int(args[1]);
-
- return Py::asObject(new FT2Image(width, height));
-}
-
-Py::Object
-ft2font_module::new_ft2font(const Py::Tuple &args)
-{
- _VERBOSE("ft2font_module::new_ft2font ");
- args.verify_length(1);
-
- std::string facefile = Py::String(args[0]);
- return Py::asObject(new FT2Font(facefile));
-}
+PYCXX_VARARGS_METHOD_DECL(FT2Font, attach_file)
void
-FT2Image::init_type()
+FT2Image::init_type(void)
{
_VERBOSE("FT2Image::init_type");
behaviors().name("FT2Image");
behaviors().doc("FT2Image");
- add_varargs_method("write_bitmap", &FT2Image::py_write_bitmap,
- FT2Image::write_bitmap__doc__);
- add_varargs_method("draw_rect", &FT2Image::py_draw_rect,
- FT2Image::draw_rect__doc__);
- add_varargs_method("draw_rect_filled", &FT2Image::py_draw_rect_filled,
- FT2Image::draw_rect_filled__doc__);
- add_varargs_method("as_array", &FT2Image::py_as_array,
- FT2Image::as_array__doc__);
- add_varargs_method("as_str", &FT2Image::py_as_str,
- FT2Image::as_str__doc__);
- add_varargs_method("as_rgb_str", &FT2Image::py_as_rgb_str,
- FT2Image::as_rgb_str__doc__);
- add_varargs_method("as_rgba_str", &FT2Image::py_as_rgba_str,
- FT2Image::as_rgba_str__doc__);
- add_varargs_method("get_width", &FT2Image::py_get_width,
- "Returns the width of the image");
- add_varargs_method("get_height", &FT2Image::py_get_height,
- "Returns the height of the image");
+ PYCXX_ADD_VARARGS_METHOD(write_bitmap, py_write_bitmap,
+ FT2Image::write_bitmap__doc__);
+ PYCXX_ADD_VARARGS_METHOD(draw_rect, py_draw_rect,
+ FT2Image::draw_rect__doc__);
+ PYCXX_ADD_VARARGS_METHOD(draw_rect_filled, py_draw_rect_filled,
+ FT2Image::draw_rect_filled__doc__);
+ PYCXX_ADD_VARARGS_METHOD(as_array, py_as_array,
+ FT2Image::as_array__doc__);
+ PYCXX_ADD_VARARGS_METHOD(as_str, py_as_str,
+ FT2Image::as_str__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_width, py_get_width,
+ "Returns the width of the image");
+ PYCXX_ADD_VARARGS_METHOD(get_height, py_get_height,
+ "Returns the height of the image");
+
+ behaviors().readyType();
}
void
@@ -2091,8 +2004,9 @@ Glyph::init_type()
_VERBOSE("Glyph::init_type");
behaviors().name("Glyph");
behaviors().doc("Glyph");
- behaviors().supportGetattr();
- behaviors().supportSetattr();
+ behaviors().supportGetattro();
+ behaviors().supportSetattro();
+ behaviors().readyType();
}
void
@@ -2101,58 +2015,59 @@ FT2Font::init_type()
_VERBOSE("FT2Font::init_type");
behaviors().name("FT2Font");
behaviors().doc("FT2Font");
-
- add_varargs_method("clear", &FT2Font::clear,
- FT2Font::clear__doc__);
- add_varargs_method("draw_glyph_to_bitmap", &FT2Font::draw_glyph_to_bitmap,
- FT2Font::draw_glyph_to_bitmap__doc__);
- add_varargs_method("draw_glyphs_to_bitmap", &FT2Font::draw_glyphs_to_bitmap,
- FT2Font::draw_glyphs_to_bitmap__doc__);
- add_varargs_method("get_xys", &FT2Font::get_xys,
- FT2Font::get_xys__doc__);
-
- add_varargs_method("get_num_glyphs", &FT2Font::get_num_glyphs,
- FT2Font::get_num_glyphs__doc__);
- add_keyword_method("load_char", &FT2Font::load_char,
- FT2Font::load_char__doc__);
- add_keyword_method("load_glyph", &FT2Font::load_glyph,
- FT2Font::load_glyph__doc__);
- add_keyword_method("set_text", &FT2Font::set_text,
- FT2Font::set_text__doc__);
- add_varargs_method("set_size", &FT2Font::set_size,
- FT2Font::set_size__doc__);
- add_varargs_method("set_charmap", &FT2Font::set_charmap,
- FT2Font::set_charmap__doc__);
- add_varargs_method("select_charmap", &FT2Font::select_charmap,
- FT2Font::select_charmap__doc__);
-
- add_varargs_method("get_width_height", &FT2Font::get_width_height,
- FT2Font::get_width_height__doc__);
- add_varargs_method("get_descent", &FT2Font::get_descent,
- FT2Font::get_descent__doc__);
- add_varargs_method("get_glyph_name", &FT2Font::get_glyph_name,
- FT2Font::get_glyph_name__doc__);
- add_varargs_method("get_charmap", &FT2Font::get_charmap,
- FT2Font::get_charmap__doc__);
- add_varargs_method("get_kerning", &FT2Font::get_kerning,
- FT2Font::get_kerning__doc__);
- add_varargs_method("get_sfnt", &FT2Font::get_sfnt,
- FT2Font::get_sfnt__doc__);
- add_varargs_method("get_name_index", &FT2Font::get_name_index,
- FT2Font::get_name_index__doc__);
- add_varargs_method("get_ps_font_info", &FT2Font::get_ps_font_info,
- FT2Font::get_ps_font_info__doc__);
- add_varargs_method("get_sfnt_table", &FT2Font::get_sfnt_table,
- FT2Font::get_sfnt_table__doc__);
- add_varargs_method("get_image", &FT2Font::get_image,
- FT2Font::get_image__doc__);
- add_varargs_method("attach_file", &FT2Font::attach_file,
- FT2Font::attach_file__doc__);
- add_noargs_method("get_path", &FT2Font::get_path,
- "");
-
- behaviors().supportGetattr();
- behaviors().supportSetattr();
+ behaviors().supportGetattro();
+ behaviors().supportSetattro();
+
+ PYCXX_ADD_VARARGS_METHOD(clear, clear,
+ FT2Font::clear__doc__);
+ PYCXX_ADD_VARARGS_METHOD(draw_glyph_to_bitmap, draw_glyph_to_bitmap,
+ FT2Font::draw_glyph_to_bitmap__doc__);
+ PYCXX_ADD_VARARGS_METHOD(draw_glyphs_to_bitmap, draw_glyphs_to_bitmap,
+ FT2Font::draw_glyphs_to_bitmap__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_xys, get_xys,
+ FT2Font::get_xys__doc__);
+
+ PYCXX_ADD_VARARGS_METHOD(get_num_glyphs, get_num_glyphs,
+ FT2Font::get_num_glyphs__doc__);
+ PYCXX_ADD_KEYWORDS_METHOD(load_char, load_char,
+ FT2Font::load_char__doc__);
+ PYCXX_ADD_KEYWORDS_METHOD(load_glyph, load_glyph,
+ FT2Font::load_glyph__doc__);
+ PYCXX_ADD_KEYWORDS_METHOD(set_text, set_text,
+ FT2Font::set_text__doc__);
+ PYCXX_ADD_VARARGS_METHOD(set_size, set_size,
+ FT2Font::set_size__doc__);
+ PYCXX_ADD_VARARGS_METHOD(set_charmap, set_charmap,
+ FT2Font::set_charmap__doc__);
+ PYCXX_ADD_VARARGS_METHOD(select_charmap, select_charmap,
+ FT2Font::select_charmap__doc__);
+
+ PYCXX_ADD_VARARGS_METHOD(get_width_height, get_width_height,
+ FT2Font::get_width_height__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_descent, get_descent,
+ FT2Font::get_descent__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_glyph_name, get_glyph_name,
+ FT2Font::get_glyph_name__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_charmap, get_charmap,
+ FT2Font::get_charmap__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_kerning, get_kerning,
+ FT2Font::get_kerning__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_sfnt, get_sfnt,
+ FT2Font::get_sfnt__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_name_index, get_name_index,
+ FT2Font::get_name_index__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_ps_font_info, get_ps_font_info,
+ FT2Font::get_ps_font_info__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_sfnt_table, get_sfnt_table,
+ FT2Font::get_sfnt_table__doc__);
+ PYCXX_ADD_VARARGS_METHOD(get_image, get_image,
+ FT2Font::get_image__doc__);
+ PYCXX_ADD_VARARGS_METHOD(attach_file, attach_file,
+ FT2Font::attach_file__doc__);
+ PYCXX_ADD_NOARGS_METHOD(get_path, get_path,
+ FT2Font::get_path__doc__);
+
+ behaviors().readyType();
}
//todo add module docs strings
@@ -2208,18 +2123,35 @@ char ft2font_new__doc__[] =
" postscript_name PostScript name of the font\n"
;
-#if defined(_MSC_VER)
-DL_EXPORT(void)
-#elif defined(__cplusplus)
-extern "C" void
+ft2font_module::ft2font_module()
+ : Py::ExtensionModule("ft2font")
+{
+ FT2Image::init_type();
+ Glyph::init_type();
+ FT2Font::init_type();
+
+ initialize("The ft2font module");
+
+ Py::Dict d(moduleDictionary());
+ Py::Object ft2font_type(FT2Font::type());
+ d["FT2Font"] = ft2font_type;
+ Py::Object ft2image_type(FT2Image::type());
+ d["FT2Image"] = ft2image_type;
+}
+
+ft2font_module::~ft2font_module()
+{
+ FT_Done_FreeType(_ft2Library);
+}
+
+PyMODINIT_FUNC
+#if PY3K
+PyInit_ft2font(void)
#else
-void
-#endif
initft2font(void)
+#endif
{
static ft2font_module* ft2font = new ft2font_module;
- import_array();
-
Py::Dict d = ft2font->moduleDictionary();
d["SCALABLE"] = Py::Int(FT_FACE_FLAG_SCALABLE);
d["FIXED_SIZES"] = Py::Int(FT_FACE_FLAG_FIXED_SIZES);
@@ -2269,10 +2201,10 @@ initft2font(void)
{
throw Py::RuntimeError("Could not find initialize the freetype2 library");
}
-}
-ft2font_module::~ft2font_module()
-{
+ import_array();
- FT_Done_FreeType(_ft2Library);
+ #if PY3K
+ return ft2font->module().ptr();
+ #endif
}
diff --git a/src/ft2font.h b/src/ft2font.h
index cf5d966e83af..509eda7d9b95 100644
--- a/src/ft2font.h
+++ b/src/ft2font.h
@@ -21,14 +21,13 @@ extern "C"
#include FT_TRUETYPE_TABLES_H
}
-
// the freetype string rendered into a width, height buffer
-class FT2Image : public Py::PythonExtension
+class FT2Image : public Py::PythonClass
{
public:
- // FT2Image();
- FT2Image(unsigned long width, unsigned long height);
- ~FT2Image();
+ FT2Image(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds);
+ virtual ~FT2Image();
+ static Py::PythonClassObject factory(int width, int height);
static void init_type();
@@ -62,11 +61,6 @@ class FT2Image : public Py::PythonExtension
Py::Object py_as_array(const Py::Tuple & args);
static char as_str__doc__ [];
Py::Object py_as_str(const Py::Tuple & args);
- static char as_rgb_str__doc__ [];
- Py::Object py_as_rgb_str(const Py::Tuple & args);
- static char as_rgba_str__doc__ [];
- Py::Object py_as_rgba_str(const Py::Tuple & args);
-
Py::Object py_get_width(const Py::Tuple & args);
Py::Object py_get_height(const Py::Tuple & args);
@@ -75,8 +69,6 @@ class FT2Image : public Py::PythonExtension
unsigned char *_buffer;
unsigned long _width;
unsigned long _height;
- FT2Image* _rgbCopy;
- FT2Image* _rgbaCopy;
void makeRgbCopy();
void makeRgbaCopy();
@@ -84,26 +76,27 @@ class FT2Image : public Py::PythonExtension
void resize(long width, long height);
};
-
-class Glyph : public Py::PythonExtension
+class Glyph : public Py::PythonClass
{
public:
- Glyph(const FT_Face&, const FT_Glyph&, size_t);
- ~Glyph();
- int setattr(const char *_name, const Py::Object &value);
- Py::Object getattr(const char *_name);
+ Glyph(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds) :
+ Py::PythonClass::PythonClass(self, args, kwds) { }
+ virtual ~Glyph();
+ static Py::PythonClassObject factory(const FT_Face&, const FT_Glyph&, size_t);
+ int setattro(const Py::String &name, const Py::Object &value);
+ Py::Object getattro(const Py::String &name);
static void init_type(void);
size_t glyphInd;
private:
Py::Dict __dict__;
};
-class FT2Font : public Py::PythonExtension
+class FT2Font : public Py::PythonClass
{
public:
- FT2Font(std::string);
- ~FT2Font();
+ FT2Font(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds);
+ virtual ~FT2Font();
static void init_type(void);
Py::Object clear(const Py::Tuple & args);
Py::Object set_size(const Py::Tuple & args);
@@ -116,7 +109,6 @@ class FT2Font : public Py::PythonExtension
Py::Object load_glyph(const Py::Tuple & args, const Py::Dict & kws);
Py::Object get_width_height(const Py::Tuple & args);
Py::Object get_descent(const Py::Tuple & args);
- Py::Object draw_rect_filled(const Py::Tuple & args);
Py::Object get_xys(const Py::Tuple & args);
Py::Object draw_glyphs_to_bitmap(const Py::Tuple & args);
Py::Object draw_glyph_to_bitmap(const Py::Tuple & args);
@@ -128,10 +120,10 @@ class FT2Font : public Py::PythonExtension
Py::Object get_sfnt_table(const Py::Tuple & args);
Py::Object get_image(const Py::Tuple & args);
Py::Object attach_file(const Py::Tuple & args);
- int setattr(const char *_name, const Py::Object &value);
- Py::Object getattr(const char *_name);
+ int setattro(const Py::String &name, const Py::Object &value);
+ Py::Object getattro(const Py::String &name);
Py::Object get_path();
- FT2Image* image;
+ Py::Object image;
private:
Py::Dict __dict__;
@@ -145,7 +137,6 @@ class FT2Font : public Py::PythonExtension
double ptsize;
double dpi;
-
FT_BBox compute_string_bbox();
void set_scalable_attributes();
@@ -180,27 +171,8 @@ class ft2font_module : public Py::ExtensionModule
{
public:
- ft2font_module()
- : Py::ExtensionModule("ft2font")
- {
- FT2Image::init_type();
- Glyph::init_type();
- FT2Font::init_type();
-
- add_varargs_method("FT2Font", &ft2font_module::new_ft2font,
- "FT2Font");
- add_varargs_method("FT2Image", &ft2font_module::new_ft2image,
- "FT2Image");
- initialize("The ft2font module");
- }
-
- ~ft2font_module();
- //static FT_Library ft2Library;
-
-private:
-
- Py::Object new_ft2font(const Py::Tuple &args);
- Py::Object new_ft2image(const Py::Tuple &args);
+ ft2font_module();
+ virtual ~ft2font_module();
};
#endif
diff --git a/src/mplutils.h b/src/mplutils.h
index e0305f142f50..4616d1260191 100644
--- a/src/mplutils.h
+++ b/src/mplutils.h
@@ -15,10 +15,18 @@
#ifndef _MPLUTILS_H
#define _MPLUTILS_H
+#include
+
#include
#include
#include
+#if PY_MAJOR_VERSION >= 3
+#define PY3K 1
+#else
+#define PY3K 0
+#endif
+
void _VERBOSE(const std::string&);
diff --git a/src/nxutils.c b/src/nxutils.c
index e7d69793c2e5..e918ab5b9be7 100644
--- a/src/nxutils.c
+++ b/src/nxutils.c
@@ -238,7 +238,7 @@ static PyMethodDef module_methods[] = {
};
PyMODINIT_FUNC
- initnxutils(void)
+initnxutils(void)
{
PyObject* m;
diff --git a/test/_buildbot_install.py b/test/_buildbot_install.py
index 609ab186d368..54f59ce1edac 100644
--- a/test/_buildbot_install.py
+++ b/test/_buildbot_install.py
@@ -1,5 +1,6 @@
"""This script will install matplotlib to a virtual environment to
faciltate testing."""
+from __future__ import print_function
import shutil, os, sys
from subprocess import Popen, PIPE, STDOUT
from optparse import OptionParser
diff --git a/test/_buildbot_test.py b/test/_buildbot_test.py
index 31122f5215a1..f9ec21595269 100644
--- a/test/_buildbot_test.py
+++ b/test/_buildbot_test.py
@@ -1,4 +1,5 @@
"""This script will test matplotlib in a virtual environment"""
+from __future__ import print_function
import os, glob
from _buildbot_util import check_call
diff --git a/test/_buildbot_test_postmortem.py b/test/_buildbot_test_postmortem.py
index 39d6c9b4cf7e..927cecd796fc 100644
--- a/test/_buildbot_test_postmortem.py
+++ b/test/_buildbot_test_postmortem.py
@@ -4,6 +4,7 @@
This is meant to be run from the mplroot directory."""
+from __future__ import print_function
import os, shutil
roots = ['test_matplotlib','test_plots']
@@ -91,8 +92,8 @@ def path_split_all(fname):
continue
if not os.path.exists(expected_fname):
continue
- print fname
- print absdiff_fname
+ print(fname)
+ print(absdiff_fname)
teststr = os.path.splitext(fname)[0]
this_targetdir = os.path.join(target_dir,teststr)
diff --git a/test/_buildbot_util.py b/test/_buildbot_util.py
index 66ebede1a501..0638dc90132d 100644
--- a/test/_buildbot_util.py
+++ b/test/_buildbot_util.py
@@ -1,5 +1,6 @@
"""Module to help _buildbot_*.py scripts."""
+from __future__ import print_function
import shutil, os, sys
from subprocess import Popen, PIPE, STDOUT
diff --git a/unit/agg_memleak.py b/unit/agg_memleak.py
index c0ee78d43f58..7dd1008fb477 100644
--- a/unit/agg_memleak.py
+++ b/unit/agg_memleak.py
@@ -2,6 +2,7 @@
And another broken test...
"""
+from __future__ import print_function
import sys, time, os
from matplotlib.ft2font import FT2Font
from numpy.random import rand
@@ -11,7 +12,7 @@
def report_memory(i):
pid = os.getpid()
a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
- print i, ' ', a2[1],
+ print(i, ' ', a2[1], end='')
return int(a2[1].split()[0])
fname = '/usr/local/share/matplotlib/Vera.ttf'
@@ -52,7 +53,7 @@ def report_memory(i):
if i==1: start = val
end = val
-print 'Average memory consumed per loop: %1.4f\n' % ((end-start)/float(N))
+print('Average memory consumed per loop: %1.4f\n' % ((end-start)/float(N)))
# w/o text and w/o write_png: Average memory consumed per loop: 0.02
# w/o text and w/ write_png : Average memory consumed per loop: 0.3400
diff --git a/unit/compare_backend_driver_results.py b/unit/compare_backend_driver_results.py
index 28aed8dcd9f5..4b705d001f82 100644
--- a/unit/compare_backend_driver_results.py
+++ b/unit/compare_backend_driver_results.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import sys
def parse_results(filename):
@@ -33,9 +34,9 @@ def compare_results(results_a, results_b):
sections = results_a.keys()
sections.sort()
for section in results_a.keys():
- print "backend %s" % section
- print " %-40s %6s %6s %6s %6s" % ("test", "a", "b", "delta", "% diff")
- print " " + '-' * 69
+ print("backend %s" % section)
+ print(" %-40s %6s %6s %6s %6s" % ("test", "a", "b", "delta", "% diff"))
+ print(" " + '-' * 69)
deltas = []
section_a = results_a[section]
section_b = results_b[section]
@@ -54,13 +55,13 @@ def compare_results(results_a, results_b):
for diff, delta, time_a, time_b, test in deltas:
if diff is None:
if time_a is None:
- print " %-40s ??? % 6.3f ??? ???" % (test, time_b)
+ print(" %-40s ??? % 6.3f ??? ???" % (test, time_b))
else:
- print " %-40s % 6.3f ??? ??? ???" % (test, time_a)
+ print(" %-40s % 6.3f ??? ??? ???" % (test, time_a))
else:
- print " %-40s % 6.3f % 6.3f % 6.3f %6d%%" % (test, time_a, time_b, delta, diff * 100)
+ print(" %-40s % 6.3f % 6.3f % 6.3f %6d%%" % (test, time_a, time_b, delta, diff * 100))
+
-
if __name__ == '__main__':
results_a_filename = sys.argv[-2]
results_b_filename = sys.argv[-1]
diff --git a/unit/ellipse_large.py b/unit/ellipse_large.py
index 6836a693049e..3a407db5ab8d 100644
--- a/unit/ellipse_large.py
+++ b/unit/ellipse_large.py
@@ -4,6 +4,7 @@
# bound ellipses, it demonstrates how significant this error
# is to our plots.
+from __future__ import print_function
import math
from pylab import *
from matplotlib.patches import Ellipse, Arc
diff --git a/unit/inside_poly_memleak.py b/unit/inside_poly_memleak.py
old mode 100644
new mode 100755
index c51e952c45db..915283ccb89b
--- a/unit/inside_poly_memleak.py
+++ b/unit/inside_poly_memleak.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python
+
"""
Another broken test...
"""
+from __future__ import print_function
import os, sys, time
import matplotlib.nxutils as nxutils
from numpy.random import rand
@@ -10,7 +12,7 @@
def report_memory(i):
pid = os.getpid()
a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
- print i, ' ', a2[1],
+ print(i, ' ', a2[1], end='')
return int(a2[1].split()[1])
diff --git a/unit/inside_poly_profile.py b/unit/inside_poly_profile.py
index 9af65544bb4a..a75b462fa7b5 100644
--- a/unit/inside_poly_profile.py
+++ b/unit/inside_poly_profile.py
@@ -2,6 +2,7 @@
Broken.
"""
+from __future__ import print_function
import os, sys, time
import matplotlib.nxutils as nxutils
@@ -24,7 +25,7 @@
points = rand(numpoints,2)
mask = nxutils.points_inside_poly(points, verts)
tnew = time.time() - t0
- print numverts, numpoints, told, tnew, told/tnew
+ print(numverts, numpoints, told, tnew, told/tnew)
diff --git a/unit/legend_unit.py b/unit/legend_unit.py
index c2b573d4f111..48b8ff06e19c 100644
--- a/unit/legend_unit.py
+++ b/unit/legend_unit.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
from pylab import figure, show, nx
Ntests = 3
diff --git a/unit/longs_test.py b/unit/longs_test.py
index af0865653080..1697f7b61343 100644
--- a/unit/longs_test.py
+++ b/unit/longs_test.py
@@ -1,6 +1,8 @@
#!/usr/bin/env python
# try plotting very large numbers
+from __future__ import print_function
+
from pylab import *
x = arange(1000) + 2**32
diff --git a/unit/memleak_gui.py b/unit/memleak_gui.py
old mode 100644
new mode 100755
index 712e3e96ec56..77570c86a5c2
--- a/unit/memleak_gui.py
+++ b/unit/memleak_gui.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+
'''
This illustrates a leak that occurs with any interactive backend.
Run with :
@@ -13,6 +14,7 @@
You may need to edit cbook.report_memory to support your platform
'''
+from __future__ import print_function
import os, sys, time
import gc
from optparse import OptionParser
@@ -48,8 +50,8 @@
import pylab
import matplotlib.cbook as cbook
-print '# columns are: iteration, OS memory (k), number of python objects'
-print '#'
+print('# columns are: iteration, OS memory (k), number of python objects')
+print('#')
for i in range(indEnd+1):
fig = pylab.figure()
@@ -68,40 +70,40 @@
gc.collect()
end = val
-print '# columns above are: iteration, OS memory (k), number of python objects'
-print '#'
-print '# uncollectable list:', gc.garbage
-print '#'
+print('# columns above are: iteration, OS memory (k), number of python objects')
+print('#')
+print('# uncollectable list:', gc.garbage)
+print('#')
if i > indStart:
- print '# Backend %(backend)s, toolbar %(toolbar)s' % matplotlib.rcParams
+ print('# Backend %(backend)s, toolbar %(toolbar)s' % matplotlib.rcParams)
backend = options.backend.lower()
if backend.startswith("gtk"):
import gtk
import gobject
- print "# pygtk version: %s, gtk version: %s, pygobject version: %s, glib version: %s" % \
- (gtk.pygtk_version, gtk.gtk_version,
- gobject.pygobject_version, gobject.glib_version)
+ print("# pygtk version: %s, gtk version: %s, pygobject version: %s, glib version: %s" % \
+ (gtk.pygtk_version, gtk.gtk_version,
+ gobject.pygobject_version, gobject.glib_version))
elif backend.startswith("qt4"):
import PyQt4.pyqtconfig
- print "# PyQt4 version: %s, Qt version %x" % \
+ print("# PyQt4 version: %s, Qt version %x" % \
(PyQt4.pyqtconfig.Configuration().pyqt_version_str,
- PyQt4.pyqtconfig.Configuration().qt_version)
+ PyQt4.pyqtconfig.Configuration().qt_version))
elif backend.startswith("qt"):
import pyqtconfig
- print "# pyqt version: %s, qt version: %x" % \
+ print("# pyqt version: %s, qt version: %x" % \
(pyqtconfig.Configuration().pyqt_version_str,
- pyqtconfig.Configuration().qt_version)
+ pyqtconfig.Configuration().qt_version))
elif backend.startswith("wx"):
import wx
- print "# wxPython version: %s" % wx.__version__
+ print("# wxPython version: %s" % wx.__version__)
elif backend.startswith("tk"):
import Tkinter
- print "# Tkinter version: %s, Tk version: %s, Tcl version: %s" % (Tkinter.__version__, Tkinter.TkVersion, Tkinter.TclVersion)
+ print("# Tkinter version: %s, Tk version: %s, Tcl version: %s" % (Tkinter.__version__, Tkinter.TkVersion, Tkinter.TclVersion))
- print '# Averaging over loops %d to %d' % (indStart, indEnd)
- print '# Memory went from %dk to %dk' % (start, end)
- print '# Average memory consumed per loop: %1.4fk bytes\n' % ((end-start)/float(indEnd-indStart))
+ print('# Averaging over loops %d to %d' % (indStart, indEnd))
+ print('# Memory went from %dk to %dk' % (start, end))
+ print('# Average memory consumed per loop: %1.4fk bytes\n' % ((end-start)/float(indEnd-indStart)))
if options.cycles:
cbook.print_cycles(gc.garbage)
diff --git a/unit/memleak_hawaii3.py b/unit/memleak_hawaii3.py
old mode 100644
new mode 100755
index 320156f3905d..6aab771e46dd
--- a/unit/memleak_hawaii3.py
+++ b/unit/memleak_hawaii3.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python
+from __future__ import print_function
+
import os, sys, time, gc
import matplotlib
matplotlib.use('PDF')
@@ -43,9 +45,9 @@
gc.collect()
val = report_memory(i)
- print i, val
+ print(i, val)
if i==indStart: start = val # wait a few cycles for memory usage to stabilize
end = val
-print 'Average memory consumed per loop: %1.4fk bytes\n' % ((end-start)/float(indEnd-indStart))
+print('Average memory consumed per loop: %1.4fk bytes\n' % ((end-start)/float(indEnd-indStart)))
diff --git a/unit/memleak_nongui.py b/unit/memleak_nongui.py
index a2308ef44762..e3ac8321d00b 100644
--- a/unit/memleak_nongui.py
+++ b/unit/memleak_nongui.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import os,matplotlib
matplotlib.use('Agg')
from matplotlib.figure import Figure
@@ -7,7 +8,7 @@ def plot():
fig = Figure()
i = 0
while True:
- print i,report_memory(i)
+ print(i, report_memory(i))
fig.clf()
ax = fig.add_axes([0.1,0.1,0.7,0.7])
ax.plot([1,2,3])
diff --git a/unit/mlab_unit.py b/unit/mlab_unit.py
index 9e91fc260476..8ba82dad5c6f 100644
--- a/unit/mlab_unit.py
+++ b/unit/mlab_unit.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import datetime, StringIO, unittest
import matplotlib.mlab as mlab
import numpy
@@ -40,9 +41,9 @@ def test_csv2rec_roundtrip(self):
mlab.rec2csv( ra, fh )
fh.seek(0)
if 0:
- print 'CSV contents:','-'*40
- print fh.read()
- print '-'*40
+ print('CSV contents:','-'*40)
+ print(fh.read())
+ print('-'*40)
fh.seek(0)
ra2 = mlab.csv2rec(fh)
fh.close()
@@ -50,9 +51,9 @@ def test_csv2rec_roundtrip(self):
#print 'ra2', ra2
for name in ra.dtype.names:
if 0:
- print name, repr(ra[name]), repr(ra2[name])
+ print(name, repr(ra[name]), repr(ra2[name]))
dt = ra.dtype[name]
- print 'repr(dt.type)',repr(dt.type)
+ print('repr(dt.type)',repr(dt.type))
self.failUnless( numpy.all(ra[name] == ra2[name]) ) # should not fail with numpy 1.0.5
def test_csv2rec_masks(self):
diff --git a/unit/test_wxagg.py b/unit/test_wxagg.py
index 8b3ff1bb0aa5..e48ef522667e 100755
--- a/unit/test_wxagg.py
+++ b/unit/test_wxagg.py
@@ -29,6 +29,8 @@
# the sale, use or other dealings in this Software without prior written
# authorization from Illinois Institute of Technology.
+from __future__ import print_function
+
import wx
import time
@@ -112,10 +114,10 @@ def main():
agg = canvas.get_renderer()
if 0:
- print 'll.x =', BBOX.ll().x().get()
- print 'll.y =', BBOX.ll().y().get()
- print 'ur.x =', BBOX.ur().x().get()
- print 'ur.y =', BBOX.ur().y().get()
+ print('ll.x =', BBOX.ll().x().get())
+ print('ll.y =', BBOX.ll().y().get())
+ print('ur.x =', BBOX.ur().x().get())
+ print('ur.y =', BBOX.ur().y().get())
# test the pure python implementation
if TEST_PY:
@@ -144,30 +146,30 @@ def main():
# time the pure python implementation
if TIME_PY:
t = time_loop(_py_convert_agg_to_wx_image, (agg,None))
- print 'Python agg2img: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('Python agg2img: %.4f seconds (%.1f HZ)' % (t, 1/t))
t = time_loop(_py_convert_agg_to_wx_bitmap, (agg,None))
- print 'Python agg2bmp: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('Python agg2bmp: %.4f seconds (%.1f HZ)' % (t, 1/t))
t = time_loop(_py_convert_agg_to_wx_image, (agg,BBOX))
- print 'Python agg2img w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('Python agg2img w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t))
t = time_loop(_py_convert_agg_to_wx_bitmap, (agg,BBOX))
- print 'Python agg2bmp w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('Python agg2bmp w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t))
# time the C++ implementation
if TIME_EXT:
t = time_loop(wxagg.convert_agg_to_wx_image, (agg,None))
- print '_wxagg agg2img: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('_wxagg agg2img: %.4f seconds (%.1f HZ)' % (t, 1/t))
t = time_loop(wxagg.convert_agg_to_wx_bitmap, (agg,None))
- print '_wxagg agg2bmp: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('_wxagg agg2bmp: %.4f seconds (%.1f HZ)' % (t, 1/t))
t = time_loop(wxagg.convert_agg_to_wx_image, (agg,BBOX))
- print '_wxagg agg2img w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('_wxagg agg2img w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t))
t = time_loop(wxagg.convert_agg_to_wx_bitmap, (agg,BBOX))
- print '_wxagg agg2bmp w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t)
+ print('_wxagg agg2bmp w/bbox: %.4f seconds (%.1f HZ)' % (t, 1/t))
if __name__ == '__main__':
diff --git a/unit/threading_test.py b/unit/threading_test.py
old mode 100644
new mode 100755
index 10d5458dea6e..6e1c9967ce42
--- a/unit/threading_test.py
+++ b/unit/threading_test.py
@@ -1,10 +1,12 @@
#! /usr/bin/python
+
"""
-Test by Karen Tracey for threading problem reported in
+Test by Karen Tracey for threading problem reported in
http://www.mail-archive.com/matplotlib-devel@lists.sourceforge.net/msg04819.html
and solved by JDH in git commit 175e3ec5bed9144.
"""
+from __future__ import print_function
import os
import threading
import traceback
@@ -39,17 +41,17 @@ def png_thread(tn):
png_f.close()
if excp:
- print 'png_thread %d failed on iteration %d:' % (tn, i)
- print traceback.format_exc(excp)
+ print('png_thread %d failed on iteration %d:' % (tn, i))
+ print(traceback.format_exc(excp))
exception_raised = True
- else:
- print 'png_thread %d completed iteration %d.' % (tn, i)
+ else:
+ print('png_thread %d completed iteration %d.' % (tn, i))
os.unlink(png_fname)
def main(tc):
threads = []
- for i in range(tc):
+ for i in range(tc):
threads.append(threading.Thread(target=png_thread, args=(i+1,)))
for t in threads:
@@ -63,7 +65,7 @@ def main(tc):
else:
msg = 'Failed! Exception raised before %d threads completed %d iterations.'
- print msg % (tc, max_iterations)
+ print(msg % (tc, max_iterations))
if __name__== "__main__":
main(thread_count)
|