converted usage of Numeric to numpy

git-svn-id: svn://svn.code.sf.net/p/fonttools/code/trunk@537 4cde692c-a291-49d1-8350-778aa11640f8
This commit is contained in:
jvr 2008-03-04 15:25:27 +00:00
parent f5e9825454
commit 1b7d54fedc
11 changed files with 103 additions and 107 deletions

View File

@ -3,7 +3,7 @@
# name of this module (not). # name of this module (not).
# #
import Numeric import numpy
def calcBounds(array): def calcBounds(array):
"""Return the bounding rectangle of a 2D points array as a tuple: """Return the bounding rectangle of a 2D points array as a tuple:
@ -11,8 +11,8 @@ def calcBounds(array):
""" """
if len(array) == 0: if len(array) == 0:
return 0, 0, 0, 0 return 0, 0, 0, 0
xMin, yMin = Numeric.minimum.reduce(array) xMin, yMin = numpy.minimum.reduce(array)
xMax, yMax = Numeric.maximum.reduce(array) xMax, yMax = numpy.maximum.reduce(array)
return xMin, yMin, xMax, yMax return xMin, yMin, xMax, yMax
def updateBounds(bounds, (x, y), min=min, max=max): def updateBounds(bounds, (x, y), min=min, max=max):
@ -33,18 +33,18 @@ def pointsInRect(array, rect):
return [] return []
lefttop = rect[:2] lefttop = rect[:2]
rightbottom = rect[2:] rightbottom = rect[2:]
condition = Numeric.logical_and( condition = numpy.logical_and(
Numeric.greater_equal(array, lefttop), numpy.greater_equal(array, lefttop),
Numeric.less_equal(array, rightbottom)) numpy.less_equal(array, rightbottom))
return Numeric.logical_and.reduce(condition, -1) return numpy.logical_and.reduce(condition, -1)
def vectorLength(vector): def vectorLength(vector):
"""Return the length of the given vector.""" """Return the length of the given vector."""
return Numeric.sqrt(vector[0]**2 + vector[1]**2) return numpy.sqrt(vector[0]**2 + vector[1]**2)
def asInt16(array): def asInt16(array):
"""Round and cast to 16 bit integer.""" """Round and cast to 16 bit integer."""
return Numeric.floor(array + 0.5).astype(Numeric.Int16) return numpy.floor(array + 0.5).astype(numpy.int16)
def normRect((xMin, yMin, xMax, yMax)): def normRect((xMin, yMin, xMax, yMax)):
@ -117,12 +117,12 @@ def _test():
>>> not pointInRect((101, 100), (0, 0, 100, 100)) >>> not pointInRect((101, 100), (0, 0, 100, 100))
True True
>>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100))) >>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
[1, 1, 1, 0] [True, True, True, False]
>>> vectorLength((3, 4)) >>> vectorLength((3, 4))
5.0 5.0
>>> vectorLength((1, 1)) == math.sqrt(2) >>> vectorLength((1, 1)) == math.sqrt(2)
True True
>>> list(asInt16(Numeric.array([0, 0.1, 0.5, 0.9]))) >>> list(asInt16(numpy.array([0, 0.1, 0.5, 0.9])))
[0, 0, 1, 1] [0, 0, 1, 1]
>>> normRect((0, 10, 100, 200)) >>> normRect((0, 10, 100, 200))
(0, 10, 100, 200) (0, 10, 100, 200)

View File

@ -14,7 +14,7 @@ __all__ = [
] ]
from fontTools.misc.arrayTools import calcBounds from fontTools.misc.arrayTools import calcBounds
import Numeric import numpy
epsilon = 1e-12 epsilon = 1e-12
@ -50,7 +50,7 @@ def calcCubicBounds(pt1, pt2, pt3, pt4):
>>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100)) >>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))
(0.0, 0.0, 100.0, 100.0) (0.0, 0.0, 100.0, 100.0)
>>> calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)) >>> calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0))
(35.566243270259356, 0.0, 64.433756729740679, 75.0) (35.5662432703, 0.0, 64.4337567297, 75.0)
""" """
a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4) a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
# calc first derivative # calc first derivative
@ -84,7 +84,7 @@ def splitLine(pt1, pt2, where, isHorizontal):
((0, 0), (0.0, 0.0)) ((0, 0), (0.0, 0.0))
((0.0, 0.0), (100, 100)) ((0.0, 0.0), (100, 100))
""" """
pt1, pt2 = Numeric.array((pt1, pt2)) pt1, pt2 = numpy.array((pt1, pt2))
a = (pt2 - pt1) a = (pt2 - pt1)
b = pt1 b = pt1
ax = a[isHorizontal] ax = a[isHorizontal]
@ -308,7 +308,7 @@ def solveCubic(a, b, c, d,
# #
def calcQuadraticParameters(pt1, pt2, pt3): def calcQuadraticParameters(pt1, pt2, pt3):
pt1, pt2, pt3 = Numeric.array((pt1, pt2, pt3)) pt1, pt2, pt3 = numpy.array((pt1, pt2, pt3))
c = pt1 c = pt1
b = (pt2 - c) * 2.0 b = (pt2 - c) * 2.0
a = pt3 - c - b a = pt3 - c - b
@ -316,7 +316,7 @@ def calcQuadraticParameters(pt1, pt2, pt3):
def calcCubicParameters(pt1, pt2, pt3, pt4): def calcCubicParameters(pt1, pt2, pt3, pt4):
pt1, pt2, pt3, pt4 = Numeric.array((pt1, pt2, pt3, pt4)) pt1, pt2, pt3, pt4 = numpy.array((pt1, pt2, pt3, pt4))
d = pt1 d = pt1
c = (pt2 - d) * 3.0 c = (pt2 - d) * 3.0
b = (pt3 - pt2) * 3.0 - c b = (pt3 - pt2) * 3.0 - c
@ -341,7 +341,7 @@ def calcCubicPoints(a, b, c, d):
def _segmentrepr(obj): def _segmentrepr(obj):
""" """
>>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], Numeric.array([0.1, 2.2])]]]) >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], numpy.array([0.1, 2.2])]]])
'(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))' '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))'
""" """
try: try:

View File

@ -77,7 +77,7 @@ class NFNT:
return header + self.bits + locTable + owTable return header + self.bits + locTable + owTable
def unpackGlyphs(self): def unpackGlyphs(self):
import Numeric import numpy
nGlyphs = len(self.locTable) - 1 nGlyphs = len(self.locTable) - 1
self.glyphs = [None] * nGlyphs self.glyphs = [None] * nGlyphs
@ -85,7 +85,7 @@ class NFNT:
imageWidth = self.rowWords * 16 imageWidth = self.rowWords * 16
imageHeight = self.fRectHeight imageHeight = self.fRectHeight
bits = self.bits bits = self.bits
bitImage = Numeric.zeros((imageWidth, imageHeight), Numeric.Int8) bitImage = numpy.zeros((imageWidth, imageHeight), numpy.int8)
for y in range(imageHeight): for y in range(imageHeight):
for xByte in range(rowBytes): for xByte in range(rowBytes):
@ -108,7 +108,7 @@ class NFNT:
self.glyphs[i] = glyph = Glyph(width, offset, bitImage[imageL:imageR]) self.glyphs[i] = glyph = Glyph(width, offset, bitImage[imageL:imageR])
def packGlyphs(self): def packGlyphs(self):
import Numeric import numpy
imageWidth = 0 imageWidth = 0
kernMax = 0 kernMax = 0
imageHeight = None imageHeight = None
@ -130,7 +130,7 @@ class NFNT:
imageWidth = 16 * ((imageWidth - 1) / 16 + 1) imageWidth = 16 * ((imageWidth - 1) / 16 + 1)
rowBytes = imageWidth / 8 rowBytes = imageWidth / 8
rowWords = rowBytes / 2 rowWords = rowBytes / 2
bitImage = Numeric.zeros((imageWidth, imageHeight), Numeric.Int8) bitImage = numpy.zeros((imageWidth, imageHeight), numpy.int8)
locTable = [] locTable = []
widthTable = [] widthTable = []
offsetTable = [] offsetTable = []
@ -261,7 +261,6 @@ class NFNT:
class Glyph: class Glyph:
def __init__(self, width, offset, pixels=None, pixelDepth=1): def __init__(self, width, offset, pixels=None, pixelDepth=1):
import Numeric
self.width = width self.width = width
self.offset = offset self.offset = offset
self.pixelDepth = pixelDepth self.pixelDepth = pixelDepth

View File

@ -14,7 +14,7 @@ a table's length chages you need to rewrite the whole file anyway.
import sys import sys
import struct, sstruct import struct, sstruct
import Numeric import numpy
import os import os
@ -143,7 +143,7 @@ class SFNTWriter:
def calcMasterChecksum(self, directory): def calcMasterChecksum(self, directory):
# calculate checkSumAdjustment # calculate checkSumAdjustment
tags = self.tables.keys() tags = self.tables.keys()
checksums = Numeric.zeros(len(tags)+1) checksums = numpy.zeros(len(tags)+1)
for i in range(len(tags)): for i in range(len(tags)):
checksums[i] = self.tables[tags[i]].checkSum checksums[i] = self.tables[tags[i]].checkSum
@ -151,10 +151,10 @@ class SFNTWriter:
assert directory_end == len(directory) assert directory_end == len(directory)
checksums[-1] = calcChecksum(directory) checksums[-1] = calcChecksum(directory)
checksum = Numeric.add.reduce(checksums) checksum = numpy.add.reduce(checksums)
# BiboAfba! # BiboAfba!
checksumadjustment = Numeric.array(0xb1b0afbaL - 0x100000000L, checksumadjustment = numpy.array(0xb1b0afbaL - 0x100000000L,
Numeric.Int32) - checksum numpy.int32) - checksum
# write the checksum to the file # write the checksum to the file
self.file.seek(self.tables['head'].offset + 8) self.file.seek(self.tables['head'].offset + 8)
self.file.write(struct.pack(">l", checksumadjustment)) self.file.write(struct.pack(">l", checksumadjustment))
@ -215,10 +215,10 @@ def calcChecksum(data, start=0):
remainder = len(data) % 4 remainder = len(data) % 4
if remainder: if remainder:
data = data + '\0' * (4-remainder) data = data + '\0' * (4-remainder)
a = Numeric.fromstring(struct.pack(">l", start) + data, Numeric.Int32) a = numpy.fromstring(struct.pack(">l", start) + data, numpy.int32)
if sys.byteorder <> "big": if sys.byteorder <> "big":
a = a.byteswapped() a = a.byteswap()
return Numeric.add.reduce(a) return numpy.add.reduce(a)
def maxPowerOfTwo(x): def maxPowerOfTwo(x):

View File

@ -2,7 +2,7 @@ import sys
import DefaultTable import DefaultTable
import sstruct import sstruct
import array import array
import Numeric import numpy
from types import StringType from types import StringType
from fontTools.misc.textTools import safeEval, readHex from fontTools.misc.textTools import safeEval, readHex
from fontTools import ttLib from fontTools import ttLib
@ -59,18 +59,18 @@ class table_G_P_K_G_(DefaultTable.DefaultTable):
for i in range(1, self.numGMAPs +1): for i in range(1, self.numGMAPs +1):
pos += len(self.GMAPs[i-1]) pos += len(self.GMAPs[i-1])
GMAPoffsets[i] = pos GMAPoffsets[i] = pos
gmapArray = Numeric.array(GMAPoffsets, Numeric.UInt32) gmapArray = numpy.array(GMAPoffsets, numpy.uint32)
if sys.byteorder <> "big": if sys.byteorder <> "big":
gmapArray = gmapArray.byteswapped() gmapArray = gmapArray.byteswap()
dataList.append(gmapArray.tostring()) dataList.append(gmapArray.tostring())
glyphletOffsets[0] = pos glyphletOffsets[0] = pos
for i in range(1, self.numGlyplets +1): for i in range(1, self.numGlyplets +1):
pos += len(self.glyphlets[i-1]) pos += len(self.glyphlets[i-1])
glyphletOffsets[i] = pos glyphletOffsets[i] = pos
glyphletArray = Numeric.array(glyphletOffsets, Numeric.UInt32) glyphletArray = numpy.array(glyphletOffsets, numpy.uint32)
if sys.byteorder <> "big": if sys.byteorder <> "big":
glyphletArray = glyphletArray.byteswapped() glyphletArray = glyphletArray.byteswap()
dataList.append(glyphletArray.tostring()) dataList.append(glyphletArray.tostring())
dataList += self.GMAPs dataList += self.GMAPs
dataList += self.glyphlets dataList += self.glyphlets

View File

@ -2,7 +2,7 @@ import sys
import DefaultTable import DefaultTable
import struct import struct
import array import array
import Numeric import numpy
import operator import operator
from fontTools import ttLib from fontTools import ttLib
from fontTools.misc.textTools import safeEval, readHex from fontTools.misc.textTools import safeEval, readHex
@ -194,7 +194,7 @@ class cmap_format_0(CmapSubtable):
assert charCodes == range(256) assert charCodes == range(256)
valueList = map(ttFont.getGlyphID, valueList) valueList = map(ttFont.getGlyphID, valueList)
glyphIdArray = Numeric.array(valueList, Numeric.Int8) glyphIdArray = numpy.array(valueList, numpy.int8)
data = struct.pack(">HHH", 0, 262, self.language) + glyphIdArray.tostring() data = struct.pack(">HHH", 0, 262, self.language) + glyphIdArray.tostring()
assert len(data) == 262 assert len(data) == 262
return data return data
@ -796,13 +796,13 @@ class cmap_format_4(CmapSubtable):
entrySelector = maxExponent entrySelector = maxExponent
rangeShift = 2 * segCount - searchRange rangeShift = 2 * segCount - searchRange
charCodeArray = Numeric.array( endCode + [0] + startCode, Numeric.UInt16) charCodeArray = numpy.array( endCode + [0] + startCode, numpy.uint16)
idDeltaeArray = Numeric.array(idDelta, Numeric.Int16) idDeltaeArray = numpy.array(idDelta, numpy.int16)
restArray = Numeric.array(idRangeOffset + glyphIndexArray, Numeric.UInt16) restArray = numpy.array(idRangeOffset + glyphIndexArray, numpy.uint16)
if sys.byteorder <> "big": if sys.byteorder <> "big":
charCodeArray = charCodeArray.byteswapped() charCodeArray = charCodeArray.byteswap()
idDeltaeArray = idDeltaeArray.byteswapped() idDeltaeArray = idDeltaeArray.byteswap()
restArray = restArray.byteswapped() restArray = restArray.byteswap()
data = charCodeArray.tostring() + idDeltaeArray.tostring() + restArray.tostring() data = charCodeArray.tostring() + idDeltaeArray.tostring() + restArray.tostring()
length = struct.calcsize(cmap_format_4_format) + len(data) length = struct.calcsize(cmap_format_4_format) + len(data)
@ -870,9 +870,9 @@ class cmap_format_6(CmapSubtable):
firstCode = codes[0] firstCode = codes[0]
valueList = map(operator.getitem, [cmap]*lenCodes, codes) valueList = map(operator.getitem, [cmap]*lenCodes, codes)
valueList = map(ttFont.getGlyphID, valueList) valueList = map(ttFont.getGlyphID, valueList)
glyphIndexArray = Numeric.array(valueList, Numeric.UInt16) glyphIndexArray = numpy.array(valueList, numpy.uint16)
if sys.byteorder <> "big": if sys.byteorder <> "big":
glyphIndexArray = glyphIndexArray.byteswapped() glyphIndexArray = glyphIndexArray.byteswap()
data = glyphIndexArray.tostring() data = glyphIndexArray.tostring()
else: else:
data = "" data = ""

View File

@ -21,7 +21,7 @@ from fontTools import ttLib
from fontTools.misc.textTools import safeEval, readHex from fontTools.misc.textTools import safeEval, readHex
import ttProgram import ttProgram
import array import array
import Numeric import numpy
from types import StringType, TupleType from types import StringType, TupleType
@ -285,15 +285,15 @@ class Glyph:
continue # ignore anything but "pt" continue # ignore anything but "pt"
coordinates.append([safeEval(attrs["x"]), safeEval(attrs["y"])]) coordinates.append([safeEval(attrs["x"]), safeEval(attrs["y"])])
flags.append(not not safeEval(attrs["on"])) flags.append(not not safeEval(attrs["on"]))
coordinates = Numeric.array(coordinates, Numeric.Int16) coordinates = numpy.array(coordinates, numpy.int16)
flags = Numeric.array(flags, Numeric.Int8) flags = numpy.array(flags, numpy.int8)
if not hasattr(self, "coordinates"): if not hasattr(self, "coordinates"):
self.coordinates = coordinates self.coordinates = coordinates
self.flags = flags self.flags = flags
self.endPtsOfContours = [len(coordinates)-1] self.endPtsOfContours = [len(coordinates)-1]
else: else:
self.coordinates = Numeric.concatenate((self.coordinates, coordinates)) self.coordinates = numpy.concatenate((self.coordinates, coordinates))
self.flags = Numeric.concatenate((self.flags, flags)) self.flags = numpy.concatenate((self.flags, flags))
self.endPtsOfContours.append(len(self.coordinates)-1) self.endPtsOfContours.append(len(self.coordinates)-1)
elif name == "component": elif name == "component":
if self.numberOfContours > 0: if self.numberOfContours > 0:
@ -368,7 +368,7 @@ class Glyph:
self.decompileCoordinatesRaw(nCoordinates, data) self.decompileCoordinatesRaw(nCoordinates, data)
# fill in repetitions and apply signs # fill in repetitions and apply signs
coordinates = Numeric.zeros((nCoordinates, 2), Numeric.Int16) coordinates = numpy.zeros((nCoordinates, 2), numpy.int16)
xIndex = 0 xIndex = 0
yIndex = 0 yIndex = 0
for i in range(nCoordinates): for i in range(nCoordinates):
@ -401,16 +401,13 @@ class Glyph:
assert xIndex == len(xCoordinates) assert xIndex == len(xCoordinates)
assert yIndex == len(yCoordinates) assert yIndex == len(yCoordinates)
# convert relative to absolute coordinates # convert relative to absolute coordinates
self.coordinates = Numeric.add.accumulate(coordinates) self.coordinates = numpy.add.accumulate(coordinates)
# discard all flags but for "flagOnCurve" # discard all flags but for "flagOnCurve"
if hasattr(Numeric, "__version__"): self.flags = numpy.bitwise_and(flags, flagOnCurve).astype(numpy.int8)
self.flags = Numeric.bitwise_and(flags, flagOnCurve).astype(Numeric.Int8)
else:
self.flags = Numeric.boolean_and(flags, flagOnCurve).astype(Numeric.Int8)
def decompileCoordinatesRaw(self, nCoordinates, data): def decompileCoordinatesRaw(self, nCoordinates, data):
# unpack flags and prepare unpacking of coordinates # unpack flags and prepare unpacking of coordinates
flags = Numeric.array([0] * nCoordinates, Numeric.Int8) flags = numpy.array([0] * nCoordinates, numpy.int8)
# Warning: deep Python trickery going on. We use the struct module to unpack # Warning: deep Python trickery going on. We use the struct module to unpack
# the coordinates. We build a format string based on the flags, so we can # the coordinates. We build a format string based on the flags, so we can
# unpack the coordinates in one struct.unpack() call. # unpack the coordinates in one struct.unpack() call.
@ -479,7 +476,7 @@ class Glyph:
# make a copy # make a copy
coordinates = self.coordinates.astype(self.coordinates.typecode()) coordinates = self.coordinates.astype(self.coordinates.typecode())
# absolute to relative coordinates # absolute to relative coordinates
coordinates[1:] = Numeric.subtract(coordinates[1:], coordinates[:-1]) coordinates[1:] = numpy.subtract(coordinates[1:], coordinates[:-1])
flags = self.flags flags = self.flags
compressedflags = [] compressedflags = []
xPoints = [] xPoints = []
@ -542,8 +539,8 @@ class Glyph:
def recalcBounds(self, glyfTable): def recalcBounds(self, glyfTable):
coordinates, endPts, flags = self.getCoordinates(glyfTable) coordinates, endPts, flags = self.getCoordinates(glyfTable)
if len(coordinates) > 0: if len(coordinates) > 0:
self.xMin, self.yMin = Numeric.minimum.reduce(coordinates) self.xMin, self.yMin = numpy.minimum.reduce(coordinates)
self.xMax, self.yMax = Numeric.maximum.reduce(coordinates) self.xMax, self.yMax = numpy.maximum.reduce(coordinates)
else: else:
self.xMin, self.yMin, self.xMax, self.yMax = (0, 0, 0, 0) self.xMin, self.yMin, self.xMax, self.yMax = (0, 0, 0, 0)
@ -586,26 +583,26 @@ class Glyph:
if scale_component_offset: if scale_component_offset:
# the Apple way: first move, then scale (ie. scale the component offset) # the Apple way: first move, then scale (ie. scale the component offset)
coordinates = coordinates + move coordinates = coordinates + move
coordinates = Numeric.dot(coordinates, compo.transform) coordinates = numpy.dot(coordinates, compo.transform)
else: else:
# the MS way: first scale, then move # the MS way: first scale, then move
coordinates = Numeric.dot(coordinates, compo.transform) coordinates = numpy.dot(coordinates, compo.transform)
coordinates = coordinates + move coordinates = coordinates + move
# due to the transformation the coords. are now floats; # due to the transformation the coords. are now floats;
# round them off nicely, and cast to short # round them off nicely, and cast to short
coordinates = Numeric.floor(coordinates + 0.5).astype(Numeric.Int16) coordinates = numpy.floor(coordinates + 0.5).astype(numpy.int16)
if allCoords is None or len(allCoords) == 0: if allCoords is None or len(allCoords) == 0:
allCoords = coordinates allCoords = coordinates
allEndPts = endPts allEndPts = endPts
allFlags = flags allFlags = flags
else: else:
allEndPts = allEndPts + (Numeric.array(endPts) + len(allCoords)).tolist() allEndPts = allEndPts + (numpy.array(endPts) + len(allCoords)).tolist()
if len(coordinates) > 0: if len(coordinates) > 0:
allCoords = Numeric.concatenate((allCoords, coordinates)) allCoords = numpy.concatenate((allCoords, coordinates))
allFlags = Numeric.concatenate((allFlags, flags)) allFlags = numpy.concatenate((allFlags, flags))
return allCoords, allEndPts, allFlags return allCoords, allEndPts, allFlags
else: else:
return Numeric.array([], Numeric.Int16), [], Numeric.array([], Numeric.Int8) return numpy.array([], numpy.int16), [], numpy.array([], numpy.int8)
def __cmp__(self, other): def __cmp__(self, other):
if self.numberOfContours <= 0: if self.numberOfContours <= 0:
@ -613,8 +610,8 @@ class Glyph:
else: else:
if cmp(len(self.coordinates), len(other.coordinates)): if cmp(len(self.coordinates), len(other.coordinates)):
return 1 return 1
ctest = Numeric.alltrue(Numeric.alltrue(Numeric.equal(self.coordinates, other.coordinates))) ctest = numpy.alltrue(numpy.alltrue(numpy.equal(self.coordinates, other.coordinates)))
ftest = Numeric.alltrue(Numeric.equal(self.flags, other.flags)) ftest = numpy.alltrue(numpy.equal(self.flags, other.flags))
if not ctest or not ftest: if not ctest or not ftest:
return 1 return 1
return ( return (
@ -667,18 +664,18 @@ class GlyphComponent:
if self.flags & WE_HAVE_A_SCALE: if self.flags & WE_HAVE_A_SCALE:
scale, = struct.unpack(">h", data[:2]) scale, = struct.unpack(">h", data[:2])
self.transform = Numeric.array( self.transform = numpy.array(
[[scale, 0], [0, scale]]) / float(0x4000) # fixed 2.14 [[scale, 0], [0, scale]]) / float(0x4000) # fixed 2.14
data = data[2:] data = data[2:]
elif self.flags & WE_HAVE_AN_X_AND_Y_SCALE: elif self.flags & WE_HAVE_AN_X_AND_Y_SCALE:
xscale, yscale = struct.unpack(">hh", data[:4]) xscale, yscale = struct.unpack(">hh", data[:4])
self.transform = Numeric.array( self.transform = numpy.array(
[[xscale, 0], [0, yscale]]) / float(0x4000) # fixed 2.14 [[xscale, 0], [0, yscale]]) / float(0x4000) # fixed 2.14
data = data[4:] data = data[4:]
elif self.flags & WE_HAVE_A_TWO_BY_TWO: elif self.flags & WE_HAVE_A_TWO_BY_TWO:
(xscale, scale01, (xscale, scale01,
scale10, yscale) = struct.unpack(">hhhh", data[:8]) scale10, yscale) = struct.unpack(">hhhh", data[:8])
self.transform = Numeric.array( self.transform = numpy.array(
[[xscale, scale01], [scale10, yscale]]) / float(0x4000) # fixed 2.14 [[xscale, scale01], [scale10, yscale]]) / float(0x4000) # fixed 2.14
data = data[8:] data = data[8:]
more = self.flags & MORE_COMPONENTS more = self.flags & MORE_COMPONENTS
@ -716,7 +713,7 @@ class GlyphComponent:
if hasattr(self, "transform"): if hasattr(self, "transform"):
# XXX needs more testing # XXX needs more testing
transform = Numeric.floor(self.transform * 0x4000 + 0.5) transform = numpy.floor(self.transform * 0x4000 + 0.5)
if transform[0][1] or transform[1][0]: if transform[0][1] or transform[1][0]:
flags = flags | WE_HAVE_A_TWO_BY_TWO flags = flags | WE_HAVE_A_TWO_BY_TWO
data = data + struct.pack(">hhhh", data = data + struct.pack(">hhhh",
@ -772,19 +769,19 @@ class GlyphComponent:
scale01 = safeEval(attrs["scale01"]) scale01 = safeEval(attrs["scale01"])
scale10 = safeEval(attrs["scale10"]) scale10 = safeEval(attrs["scale10"])
scaley = safeEval(attrs["scaley"]) scaley = safeEval(attrs["scaley"])
self.transform = Numeric.array([[scalex, scale01], [scale10, scaley]]) self.transform = numpy.array([[scalex, scale01], [scale10, scaley]])
elif attrs.has_key("scalex"): elif attrs.has_key("scalex"):
scalex = safeEval(attrs["scalex"]) scalex = safeEval(attrs["scalex"])
scaley = safeEval(attrs["scaley"]) scaley = safeEval(attrs["scaley"])
self.transform = Numeric.array([[scalex, 0], [0, scaley]]) self.transform = numpy.array([[scalex, 0], [0, scaley]])
elif attrs.has_key("scale"): elif attrs.has_key("scale"):
scale = safeEval(attrs["scale"]) scale = safeEval(attrs["scale"])
self.transform = Numeric.array([[scale, 0], [0, scale]]) self.transform = numpy.array([[scale, 0], [0, scale]])
self.flags = safeEval(attrs["flags"]) self.flags = safeEval(attrs["flags"])
def __cmp__(self, other): def __cmp__(self, other):
if hasattr(self, "transform"): if hasattr(self, "transform"):
if Numeric.alltrue(Numeric.equal(self.transform, other.transform)): if numpy.alltrue(numpy.equal(self.transform, other.transform)):
selfdict = self.__dict__.copy() selfdict = self.__dict__.copy()
otherdict = other.__dict__.copy() otherdict = other.__dict__.copy()
del selfdict["transform"] del selfdict["transform"]

View File

@ -1,6 +1,6 @@
import sys import sys
import DefaultTable import DefaultTable
import Numeric import numpy
from fontTools import ttLib from fontTools import ttLib
from fontTools.misc.textTools import safeEval from fontTools.misc.textTools import safeEval
@ -14,10 +14,10 @@ class table__h_m_t_x(DefaultTable.DefaultTable):
def decompile(self, data, ttFont): def decompile(self, data, ttFont):
numberOfMetrics = int(getattr(ttFont[self.headerTag], self.numberOfMetricsName)) numberOfMetrics = int(getattr(ttFont[self.headerTag], self.numberOfMetricsName))
metrics = Numeric.fromstring(data[:4 * numberOfMetrics], metrics = numpy.fromstring(data[:4 * numberOfMetrics],
Numeric.Int16) numpy.int16)
if sys.byteorder <> "big": if sys.byteorder <> "big":
metrics = metrics.byteswapped() metrics = metrics.byteswap()
metrics.shape = (numberOfMetrics, 2) metrics.shape = (numberOfMetrics, 2)
data = data[4 * numberOfMetrics:] data = data[4 * numberOfMetrics:]
numberOfSideBearings = ttFont['maxp'].numGlyphs - numberOfMetrics numberOfSideBearings = ttFont['maxp'].numGlyphs - numberOfMetrics
@ -25,17 +25,17 @@ class table__h_m_t_x(DefaultTable.DefaultTable):
if numberOfSideBearings: if numberOfSideBearings:
assert numberOfSideBearings > 0, "bad hmtx/vmtx table" assert numberOfSideBearings > 0, "bad hmtx/vmtx table"
lastAdvance = metrics[-1][0] lastAdvance = metrics[-1][0]
advances = Numeric.array([lastAdvance] * numberOfSideBearings, advances = numpy.array([lastAdvance] * numberOfSideBearings,
Numeric.Int16) numpy.int16)
sideBearings = Numeric.fromstring(data[:2 * numberOfSideBearings], sideBearings = numpy.fromstring(data[:2 * numberOfSideBearings],
Numeric.Int16) numpy.int16)
if sys.byteorder <> "big": if sys.byteorder <> "big":
sideBearings = sideBearings.byteswapped() sideBearings = sideBearings.byteswap()
data = data[2 * numberOfSideBearings:] data = data[2 * numberOfSideBearings:]
additionalMetrics = Numeric.array([advances, sideBearings], additionalMetrics = numpy.array([advances, sideBearings],
Numeric.Int16) numpy.int16)
metrics = Numeric.concatenate((metrics, metrics = numpy.concatenate((metrics,
Numeric.transpose(additionalMetrics))) numpy.transpose(additionalMetrics)))
if data: if data:
sys.stderr.write("too much data for hmtx/vmtx table\n") sys.stderr.write("too much data for hmtx/vmtx table\n")
metrics = metrics.tolist() metrics = metrics.tolist()
@ -61,14 +61,14 @@ class table__h_m_t_x(DefaultTable.DefaultTable):
metrics = metrics[:lastIndex] metrics = metrics[:lastIndex]
setattr(ttFont[self.headerTag], self.numberOfMetricsName, len(metrics)) setattr(ttFont[self.headerTag], self.numberOfMetricsName, len(metrics))
metrics = Numeric.array(metrics, Numeric.Int16) metrics = numpy.array(metrics, numpy.int16)
if sys.byteorder <> "big": if sys.byteorder <> "big":
metrics = metrics.byteswapped() metrics = metrics.byteswap()
data = metrics.tostring() data = metrics.tostring()
additionalMetrics = Numeric.array(additionalMetrics, Numeric.Int16) additionalMetrics = numpy.array(additionalMetrics, numpy.int16)
if sys.byteorder <> "big": if sys.byteorder <> "big":
additionalMetrics = additionalMetrics.byteswapped() additionalMetrics = additionalMetrics.byteswap()
data = data + additionalMetrics.tostring() data = data + additionalMetrics.tostring()
return data return data

View File

@ -1,7 +1,7 @@
import sys import sys
import DefaultTable import DefaultTable
import array import array
import Numeric import numpy
from fontTools import ttLib from fontTools import ttLib
import struct import struct
@ -19,7 +19,7 @@ class table__l_o_c_a(DefaultTable.DefaultTable):
locations.fromstring(data) locations.fromstring(data)
if sys.byteorder <> "big": if sys.byteorder <> "big":
locations.byteswap() locations.byteswap()
locations = Numeric.array(locations, Numeric.Int32) locations = numpy.array(locations, numpy.int32)
if not longFormat: if not longFormat:
locations = locations * 2 locations = locations * 2
if len(locations) < (ttFont['maxp'].numGlyphs + 1): if len(locations) < (ttFont['maxp'].numGlyphs + 1):
@ -30,16 +30,16 @@ class table__l_o_c_a(DefaultTable.DefaultTable):
locations = self.locations locations = self.locations
if max(locations) < 0x20000: if max(locations) < 0x20000:
locations = locations / 2 locations = locations / 2
locations = locations.astype(Numeric.Int16) locations = locations.astype(numpy.int16)
ttFont['head'].indexToLocFormat = 0 ttFont['head'].indexToLocFormat = 0
else: else:
ttFont['head'].indexToLocFormat = 1 ttFont['head'].indexToLocFormat = 1
if sys.byteorder <> "big": if sys.byteorder <> "big":
locations = locations.byteswapped() locations = locations.byteswap()
return locations.tostring() return locations.tostring()
def set(self, locations): def set(self, locations):
self.locations = Numeric.array(locations, Numeric.Int32) self.locations = numpy.array(locations, numpy.int32)
def toXML(self, writer, ttFont): def toXML(self, writer, ttFont):
writer.comment("The 'loca' table will be calculated by the compiler") writer.comment("The 'loca' table will be calculated by the compiler")
@ -52,5 +52,5 @@ class table__l_o_c_a(DefaultTable.DefaultTable):
return len(self.locations) return len(self.locations)
def __cmp__(self, other): def __cmp__(self, other):
return cmp(len(self), len(other)) or not Numeric.alltrue(Numeric.equal(self.locations, other.locations)) return cmp(len(self), len(other)) or not numpy.alltrue(numpy.equal(self.locations, other.locations))

View File

@ -7,7 +7,7 @@ import PyBrowser
import W, Lists import W, Lists
import os import os
import ATM import ATM
import Numeric import numpy
import Qd import Qd
from rf.views.wGlyphList import GlyphList from rf.views.wGlyphList import GlyphList
@ -169,14 +169,14 @@ class Glyph:
self.flags = [] self.flags = []
startpt = 0 startpt = 0
for endpt in endPts: for endpt in endPts:
self.contours.append(Numeric.array(coordinates[startpt:endpt+1])) self.contours.append(numpy.array(coordinates[startpt:endpt+1]))
self.flags.append(flags[startpt:endpt+1]) self.flags.append(flags[startpt:endpt+1])
startpt = endpt + 1 startpt = endpt + 1
def getcontours(self, scale, move): def getcontours(self, scale, move):
contours = [] contours = []
for i in range(len(self.contours)): for i in range(len(self.contours)):
contours.append(((self.contours[i] * Numeric.array(scale) + move), self.flags[i])) contours.append(((self.contours[i] * numpy.array(scale) + move), self.flags[i]))
return contours return contours

View File

@ -11,10 +11,10 @@ except ImportError:
pass pass
try: try:
import Numeric import numpy
except ImportError: except ImportError:
print "*** Warning: FontTools needs Numerical Python (NumPy), see:" print "*** Warning: FontTools needs the numpy library, see:"
print " http://sourceforge.net/projects/numpy/" print " http://numpy.scipy.org/"
try: try:
import xml.parsers.expat import xml.parsers.expat