
import matplotlib, copy
matplotlib.use('Agg')
from pylab import *

def saveMapPNG(regArray, fileprefix, figTitle='', minVal=0, maxVal=0, grid='rect'):
    figure(figsize=(3, 2))
    if grid == 'hex':
        theArray = convertHexToRect(regArray)
    else:
        theArray = regArray
    Z = array(theArray)
    if maxVal > 0:
        C = pcolor(Z, vmin=minVal, vmax=maxVal, edgecolors='None')
    else:
        C = pcolor(Z, vmin=minVal, edgecolors='None')
    if grid == 'hex':
        xlim(1, 2 * len(regArray[0]))
        ylim(0, 2 * len(regArray))
        xticks([0, 2 * len(regArray[0]) - 1], ('',''))
        yticks([0, 2 * len(regArray) - 1], ('',''))
    else:
        xticks([1, len(regArray[0]) - 1], ('',''))
        yticks([0, len(regArray) - 1], ('',''))
    
    C.set_linewidth(0)
    if len(figTitle) > 0:
        title(figTitle, fontsize=9)
    D = colorbar(orientation="vertical", drawedges=False)
    savefig(fileprefix + '.png', dpi=250)
    show()

def coordTranslate(xorig, yorig, dx, dy, xmax, ymax):
    newx = (xorig + dx) % xmax
    newy = (yorig + dy) % ymax
    
    return newx, newy
    
def convertHexToRect(theArray):
    newArray = []
    numRows = len(theArray)
    numCols = len(theArray[0])
    newCols = (numCols + 1) * 2
    for row in range(numRows):
        newrow1 = [0.] * newCols
        newrow2 = [0.] * newCols
        if row % 2 == 0:
            spacer = 0
        else:
            spacer = 1
        
        for aCol in range(0, 2 * numCols, 2):
            oCol = aCol/2
            newrow1[spacer + aCol]     = theArray[row][oCol]
            newrow1[spacer + aCol + 1] = theArray[row][oCol]
            newrow2[spacer + aCol]     = theArray[row][oCol]
            newrow2[spacer + aCol + 1] = theArray[row][oCol]
        newArray.append(newrow1)
        newArray.append(newrow2)
    
    return newArray

    